-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathast-converter.ts
256 lines (229 loc) · 7.5 KB
/
ast-converter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import ts from "typescript";
import { ParserOptions } from "@typescript-eslint/parser";
import { SourceCode, AST, Scope } from "eslint";
import { Extra } from "@typescript-eslint/typescript-estree/dist/parser-options";
import { analyzeScope } from "@typescript-eslint/parser/dist/analyze-scope";
import { simpleTraverse } from "@typescript-eslint/parser/dist/simple-traverse";
import { visitorKeys } from "@typescript-eslint/parser/dist/visitor-keys";
import { ParseAndGenerateServicesResult, TSESTreeOptions } from "@typescript-eslint/typescript-estree";
import convert from "@typescript-eslint/typescript-estree/dist/ast-converter";
function validateBoolean(value: boolean | undefined, fallback: boolean = false): boolean {
if (typeof value !== "boolean") {
return fallback;
}
return value;
}
function createExtra(code: string) {
const base: Extra = {
tokens: null,
range: false,
loc: false,
comment: false,
comments: [],
strict: false,
jsx: false,
useJSXTextNode: false,
log: () => { },
projects: [],
errorOnUnknownASTType: false,
errorOnTypeScriptSyntacticAndSemanticIssues: false,
code: "",
tsconfigRootDir: process.cwd(),
extraFileExtensions: [],
preserveNodeMaps: undefined,
};
return {
...base,
code,
tokens: [],
loc: true,
comment: true,
comments: [],
};
}
function applyParserOptionsToExtra(extra: Extra, options: TSESTreeOptions) {
/**
* Track range information in the AST
*/
extra.range = typeof options.range === "boolean" && options.range;
extra.loc = typeof options.loc === "boolean" && options.loc;
/**
* Track tokens in the AST
*/
if (typeof options.tokens === "boolean" && options.tokens) {
extra.tokens = [];
}
/**
* Track comments in the AST
*/
if (typeof options.comment === "boolean" && options.comment) {
extra.comment = true;
extra.comments = [];
}
/**
* Enable JSX - note the applicable file extension is still required
*/
if (typeof options.jsx === "boolean" && options.jsx) {
extra.jsx = true;
}
/**
* The JSX AST changed the node type for string literals
* inside a JSX Element from `Literal` to `JSXText`.
*
* When value is `true`, these nodes will be parsed as type `JSXText`.
* When value is `false`, these nodes will be parsed as type `Literal`.
*/
if (typeof options.useJSXTextNode === "boolean" && options.useJSXTextNode) {
extra.useJSXTextNode = true;
}
/**
* Allow the user to cause the parser to error if it encounters an unknown AST Node Type
* (used in testing)
*/
if (
typeof options.errorOnUnknownASTType === "boolean" &&
options.errorOnUnknownASTType
) {
extra.errorOnUnknownASTType = true;
}
/**
* Allow the user to override the function used for logging
*/
if (typeof options.loggerFn === "function") {
extra.log = options.loggerFn;
} else if (options.loggerFn === false) {
extra.log = Function.prototype;
}
if (typeof options.project === "string") {
extra.projects = [options.project];
} else if (
Array.isArray(options.project) &&
options.project.every(projectPath => typeof projectPath === "string")
) {
extra.projects = options.project;
}
if (typeof options.tsconfigRootDir === "string") {
extra.tsconfigRootDir = options.tsconfigRootDir;
}
if (
Array.isArray(options.extraFileExtensions) &&
options.extraFileExtensions.every(ext => typeof ext === "string")
) {
extra.extraFileExtensions = options.extraFileExtensions;
}
/**
* Allow the user to enable or disable the preservation of the AST node maps
* during the conversion process.
*
* NOTE: For backwards compatibility we also preserve node maps in the case where `project` is set,
* and `preserveNodeMaps` is not explicitly set to anything.
*/
extra.preserveNodeMaps =
typeof options.preserveNodeMaps === "boolean" && options.preserveNodeMaps;
if (options.preserveNodeMaps === undefined && extra.projects.length > 0) {
extra.preserveNodeMaps = true;
}
return extra;
}
export type AstConverterCreateOptions = {
getProgram?: () => ts.Program;
};
export class AstConverter {
private readonly getProgram?: () => ts.Program;
public constructor({ getProgram }: AstConverterCreateOptions = { }) {
this.getProgram = getProgram;
}
/**
*
* see also https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/typescript-estree/src/parser.ts#L346
*
*/
public parseAndGenerateServices(src: ts.SourceFile, options: TSESTreeOptions) {
const code = src.getFullText();
let extra: Extra = createExtra(code);
extra.code = code;
/**
* Apply the given parser options
*/
if (typeof options !== "undefined") {
extra = applyParserOptionsToExtra(extra, options);
if (typeof options.errorOnTypeScriptSyntacticAndSemanticIssues === "boolean" && options.errorOnTypeScriptSyntacticAndSemanticIssues) {
extra.errorOnTypeScriptSyntacticAndSemanticIssues = true;
}
}
const { estree, astMaps } = convert(src, extra, true);
/**
* Return the converted AST and additional parser services
*/
const ret: ParseAndGenerateServicesResult<any> = {
ast: estree,
services: {
program: this.getProgram && this.getProgram(),
esTreeNodeToTSNodeMap: astMaps ? astMaps.esTreeNodeToTSNodeMap : undefined,
tsNodeToESTreeNodeMap: astMaps ? astMaps.tsNodeToESTreeNodeMap : undefined,
},
};
return ret;
}
/**
* See also https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/parser/src/parser.ts
*/
public parseForESLint(src: ts.SourceFile, options?: ParserOptions | null) {
try {
if (!options || typeof options !== "object") {
options = {};
}
if (options.sourceType !== "module" && options.sourceType !== "script") {
options.sourceType = "script";
}
if (typeof options.ecmaFeatures !== "object") {
options.ecmaFeatures = {};
}
const parserOptions: TSESTreeOptions = {};
Object.assign(parserOptions, options, {
useJSXTextNode: validateBoolean(options.useJSXTextNode, true),
jsx: validateBoolean(options.ecmaFeatures.jsx),
});
if (typeof options.filePath === "string") {
const tsx = options.filePath.endsWith(".tsx");
if (tsx || options.filePath.endsWith(".ts")) {
parserOptions.jsx = tsx;
}
}
const { ast, services } = this.parseAndGenerateServices(src, parserOptions);
simpleTraverse(ast, {
enter(node) {
switch (node.type) {
// Function#body cannot be null in ESTree spec.
case "FunctionExpression":
if (!node.body) {
node.type = `TSEmptyBody${node.type}` as any;
}
break;
// no default
}
},
});
const scopeManager = analyzeScope(ast, parserOptions);
return {
ast: ast as AST.Program,
scopeManager: scopeManager as Scope.ScopeManager,
services,
visitorKeys: visitorKeys as SourceCode.VisitorKeys,
};
} catch (error) {
throw new Error();
}
}
public convertToESLintSourceCode(src: ts.SourceFile, options?: ParserOptions | null) {
const code = src.getFullText();
const { ast, scopeManager, services, visitorKeys } = this.parseForESLint(src, options);
return new SourceCode({
text: code,
ast,
scopeManager,
parserServices: services,
visitorKeys,
});
}
}