forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ast-converter.ts
73 lines (64 loc) · 2.14 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
import type { SourceFile } from 'typescript';
import type { ASTMaps } from './convert';
import { Converter, convertError } from './convert';
import { convertComments } from './convert-comments';
import { convertTokens } from './node-utils';
import type { ParseSettings } from './parseSettings';
import { simpleTraverse } from './simple-traverse';
import type { TSESTree } from './ts-estree';
export function astConverter(
ast: SourceFile,
parseSettings: ParseSettings,
shouldPreserveNodeMaps: boolean,
): { estree: TSESTree.Program; astMaps: ASTMaps } {
/**
* The TypeScript compiler produced fundamental parse errors when parsing the
* source.
*/
const { parseDiagnostics } = ast;
if (parseDiagnostics.length) {
throw convertError(parseDiagnostics[0]);
}
/**
* Recursively convert the TypeScript AST into an ESTree-compatible AST
*/
const instance = new Converter(ast, {
errorOnInvalidAST: parseSettings.errorOnInvalidAST || false,
errorOnUnknownASTType: parseSettings.errorOnUnknownASTType || false,
shouldPreserveNodeMaps,
});
const estree = instance.convertProgram();
/**
* Optionally remove range and loc if specified
*/
if (!parseSettings.range || !parseSettings.loc) {
simpleTraverse(estree, {
enter: node => {
if (!parseSettings.range) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- TS 4.0 made this an error because the types aren't optional
// @ts-expect-error
delete node.range;
}
if (!parseSettings.loc) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- TS 4.0 made this an error because the types aren't optional
// @ts-expect-error
delete node.loc;
}
},
});
}
/**
* Optionally convert and include all tokens in the AST
*/
if (parseSettings.tokens) {
estree.tokens = convertTokens(ast);
}
/**
* Optionally convert and include all comments in the AST
*/
if (parseSettings.comment) {
estree.comments = convertComments(ast, parseSettings.codeFullText);
}
const astMaps = instance.getASTMaps();
return { estree, astMaps };
}