/
ast-converter.ts
69 lines (61 loc) · 1.78 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
import { SourceFile } from 'typescript';
import { convertError, Converter, ASTMaps } from './convert';
import { convertComments } from './convert-comments';
import { convertTokens } from './node-utils';
import { Extra } from './parser-options';
import { TSESTree } from './ts-estree';
import { simpleTraverse } from './simple-traverse';
export function astConverter(
ast: SourceFile,
extra: Extra,
shouldPreserveNodeMaps: boolean,
): { estree: TSESTree.Program; astMaps: ASTMaps } {
/**
* The TypeScript compiler produced fundamental parse errors when parsing the
* source.
*/
// internal typescript api...
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const parseDiagnostics = (ast as any).parseDiagnostics;
if (parseDiagnostics.length) {
throw convertError(parseDiagnostics[0]);
}
/**
* Recursively convert the TypeScript AST into an ESTree-compatible AST
*/
const instance = new Converter(ast, {
errorOnUnknownASTType: extra.errorOnUnknownASTType || false,
useJSXTextNode: extra.useJSXTextNode || false,
shouldPreserveNodeMaps,
});
const estree = instance.convertProgram();
/**
* Optionally remove range and loc if specified
*/
if (!extra.range || !extra.loc) {
simpleTraverse(estree, {
enter: node => {
if (!extra.range) {
delete node.range;
}
if (!extra.loc) {
delete node.loc;
}
},
});
}
/**
* Optionally convert and include all tokens in the AST
*/
if (extra.tokens) {
estree.tokens = convertTokens(ast);
}
/**
* Optionally convert and include all comments in the AST
*/
if (extra.comment) {
estree.comments = convertComments(ast, extra.code);
}
const astMaps = instance.getASTMaps();
return { estree, astMaps };
}