forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.ts
301 lines (270 loc) · 9.64 KB
/
parser.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import debug from 'debug';
import type * as ts from 'typescript';
import { astConverter } from './ast-converter';
import { convertError } from './convert';
import { createDefaultProgram } from './create-program/createDefaultProgram';
import { createIsolatedProgram } from './create-program/createIsolatedProgram';
import { createProjectProgram } from './create-program/createProjectProgram';
import {
createNoProgram,
createSourceFile,
} from './create-program/createSourceFile';
import { getWatchProgramsForProjects } from './create-program/getWatchProgramsForProjects';
import type { ASTAndProgram, CanonicalPath } from './create-program/shared';
import {
createProgramFromConfigFile,
useProvidedPrograms,
} from './create-program/useProvidedPrograms';
import { createParserServices } from './createParserServices';
import type {
ParserServices,
ParserServicesNodeMaps,
TSESTreeOptions,
} from './parser-options';
import type { ParseSettings } from './parseSettings';
import { createParseSettings } from './parseSettings/createParseSettings';
import { getFirstSemanticOrSyntacticError } from './semantic-or-syntactic-errors';
import type { TSESTree } from './ts-estree';
import { useProgramFromProjectService } from './useProgramFromProjectService';
const log = debug('typescript-eslint:typescript-estree:parser');
/**
* Cache existing programs for the single run use-case.
*
* clearProgramCache() is only intended to be used in testing to ensure the parser is clean between tests.
*/
const existingPrograms = new Map<CanonicalPath, ts.Program>();
function clearProgramCache(): void {
existingPrograms.clear();
}
/**
* @param parseSettings Internal settings for parsing the file
* @param hasFullTypeInformation True if the program should be attempted to be calculated from provided tsconfig files
* @returns Returns a source file and program corresponding to the linted code
*/
function getProgramAndAST(
parseSettings: ParseSettings,
hasFullTypeInformation: boolean,
): ASTAndProgram {
if (parseSettings.programs) {
const fromProvidedPrograms = useProvidedPrograms(
parseSettings.programs,
parseSettings,
);
if (fromProvidedPrograms) {
return fromProvidedPrograms;
}
}
// no need to waste time creating a program as the caller didn't want parser services
// so we can save time and just create a lonesome source file
if (!hasFullTypeInformation) {
return createNoProgram(parseSettings);
}
if (parseSettings.EXPERIMENTAL_projectService) {
const fromProjectService = useProgramFromProjectService(
parseSettings.EXPERIMENTAL_projectService,
parseSettings,
);
if (fromProjectService) {
return fromProjectService;
}
}
const fromProjectProgram = createProjectProgram(
parseSettings,
getWatchProgramsForProjects(parseSettings),
);
if (fromProjectProgram) {
return fromProjectProgram;
}
// eslint-disable-next-line deprecation/deprecation -- will be cleaned up with the next major
if (parseSettings.DEPRECATED__createDefaultProgram) {
// eslint-disable-next-line deprecation/deprecation -- will be cleaned up with the next major
const fromDefaultProgram = createDefaultProgram(parseSettings);
if (fromDefaultProgram) {
return fromDefaultProgram;
}
}
return createIsolatedProgram(parseSettings);
}
interface EmptyObject {}
type AST<T extends TSESTreeOptions> = TSESTree.Program &
(T['tokens'] extends true ? { tokens: TSESTree.Token[] } : EmptyObject) &
(T['comment'] extends true ? { comments: TSESTree.Comment[] } : EmptyObject);
interface ParseAndGenerateServicesResult<T extends TSESTreeOptions> {
ast: AST<T>;
services: ParserServices;
}
interface ParseWithNodeMapsResult<T extends TSESTreeOptions>
extends ParserServicesNodeMaps {
ast: AST<T>;
}
function parse<T extends TSESTreeOptions = TSESTreeOptions>(
code: string,
options?: T,
): AST<T> {
const { ast } = parseWithNodeMapsInternal(code, options, false);
return ast;
}
function parseWithNodeMapsInternal<T extends TSESTreeOptions = TSESTreeOptions>(
code: string | ts.SourceFile,
options: T | undefined,
shouldPreserveNodeMaps: boolean,
): ParseWithNodeMapsResult<T> {
/**
* Reset the parse configuration
*/
const parseSettings = createParseSettings(code, options);
/**
* Ensure users do not attempt to use parse() when they need parseAndGenerateServices()
*/
if (options?.errorOnTypeScriptSyntacticAndSemanticIssues) {
throw new Error(
`"errorOnTypeScriptSyntacticAndSemanticIssues" is only supported for parseAndGenerateServices()`,
);
}
/**
* Create a ts.SourceFile directly, no ts.Program is needed for a simple parse
*/
const ast = createSourceFile(parseSettings);
/**
* Convert the TypeScript AST to an ESTree-compatible one
*/
const { estree, astMaps } = astConverter(
ast,
parseSettings,
shouldPreserveNodeMaps,
);
return {
ast: estree as AST<T>,
esTreeNodeToTSNodeMap: astMaps.esTreeNodeToTSNodeMap,
tsNodeToESTreeNodeMap: astMaps.tsNodeToESTreeNodeMap,
};
}
function parseWithNodeMaps<T extends TSESTreeOptions = TSESTreeOptions>(
code: string,
options?: T,
): ParseWithNodeMapsResult<T> {
return parseWithNodeMapsInternal(code, options, true);
}
let parseAndGenerateServicesCalls: { [fileName: string]: number } = {};
// Privately exported utility intended for use in typescript-eslint unit tests only
function clearParseAndGenerateServicesCalls(): void {
parseAndGenerateServicesCalls = {};
}
function parseAndGenerateServices<T extends TSESTreeOptions = TSESTreeOptions>(
code: string | ts.SourceFile,
options: T,
): ParseAndGenerateServicesResult<T> {
/**
* Reset the parse configuration
*/
const parseSettings = createParseSettings(code, options);
/**
* If this is a single run in which the user has not provided any existing programs but there
* are programs which need to be created from the provided "project" option,
* create an Iterable which will lazily create the programs as needed by the iteration logic
*/
if (
parseSettings.singleRun &&
!parseSettings.programs &&
parseSettings.projects?.length > 0
) {
parseSettings.programs = {
*[Symbol.iterator](): Iterator<ts.Program> {
for (const configFile of parseSettings.projects) {
const existingProgram = existingPrograms.get(configFile);
if (existingProgram) {
yield existingProgram;
} else {
log(
'Detected single-run/CLI usage, creating Program once ahead of time for project: %s',
configFile,
);
const newProgram = createProgramFromConfigFile(configFile);
existingPrograms.set(configFile, newProgram);
yield newProgram;
}
}
},
};
}
/**
* Generate a full ts.Program or offer provided instances in order to be able to provide parser services, such as type-checking
*/
const hasFullTypeInformation =
parseSettings.programs != null || parseSettings.projects?.length > 0;
if (options !== undefined) {
if (
typeof options.errorOnTypeScriptSyntacticAndSemanticIssues ===
'boolean' &&
options.errorOnTypeScriptSyntacticAndSemanticIssues
) {
parseSettings.errorOnTypeScriptSyntacticAndSemanticIssues = true;
}
if (
parseSettings.errorOnTypeScriptSyntacticAndSemanticIssues &&
!hasFullTypeInformation
) {
throw new Error(
'Cannot calculate TypeScript semantic issues without a valid project.',
);
}
}
/**
* If we are in singleRun mode but the parseAndGenerateServices() function has been called more than once for the current file,
* it must mean that we are in the middle of an ESLint automated fix cycle (in which parsing can be performed up to an additional
* 10 times in order to apply all possible fixes for the file).
*
* In this scenario we cannot rely upon the singleRun AOT compiled programs because the SourceFiles will not contain the source
* with the latest fixes applied. Therefore we fallback to creating the quickest possible isolated program from the updated source.
*/
if (parseSettings.singleRun && options.filePath) {
parseAndGenerateServicesCalls[options.filePath] =
(parseAndGenerateServicesCalls[options.filePath] || 0) + 1;
}
const { ast, program } =
parseSettings.singleRun &&
options.filePath &&
parseAndGenerateServicesCalls[options.filePath] > 1
? createIsolatedProgram(parseSettings)
: getProgramAndAST(parseSettings, hasFullTypeInformation)!;
/**
* Convert the TypeScript AST to an ESTree-compatible one, and optionally preserve
* mappings between converted and original AST nodes
*/
const shouldPreserveNodeMaps =
typeof parseSettings.preserveNodeMaps === 'boolean'
? parseSettings.preserveNodeMaps
: true;
const { estree, astMaps } = astConverter(
ast,
parseSettings,
shouldPreserveNodeMaps,
);
/**
* Even if TypeScript parsed the source code ok, and we had no problems converting the AST,
* there may be other syntactic or semantic issues in the code that we can optionally report on.
*/
if (program && parseSettings.errorOnTypeScriptSyntacticAndSemanticIssues) {
const error = getFirstSemanticOrSyntacticError(program, ast);
if (error) {
throw convertError(error);
}
}
/**
* Return the converted AST and additional parser services
*/
return {
ast: estree as AST<T>,
services: createParserServices(astMaps, program),
};
}
export {
AST,
parse,
parseAndGenerateServices,
parseWithNodeMaps,
ParseAndGenerateServicesResult,
ParseWithNodeMapsResult,
clearProgramCache,
clearParseAndGenerateServicesCalls,
};