-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathparser.ts
48 lines (44 loc) · 1.39 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
import lex, { SourceTokenList } from 'coffee-lex';
import { patchCoffeeScript } from './ext/coffee-script';
import mapProgram from './mappers/mapProgram';
import { Node, Program } from './nodes';
import parseCS1AsCS2 from './parseCS1AsCS2';
import parseCS2 from './parseCS2';
import fixLocations from './util/fixLocations';
import ParseContext from './util/ParseContext';
export type Options = {
useCS2: boolean;
};
export const DEFAULT_OPTIONS: Options = {
useCS2: false,
};
export function parse(
source: string,
options: Options = DEFAULT_OPTIONS
): Program {
patchCoffeeScript();
const parse = options.useCS2 ? parseCS2 : parseCS1AsCS2;
const sourceLex = (s: string): SourceTokenList =>
lex(s, { useCS2: options.useCS2 });
const context = ParseContext.fromSource(source, sourceLex, parse);
fixLocations(context, context.ast);
const program = mapProgram(context);
traverse(program, (node, parent) => {
node.parentNode = parent;
});
return program;
}
export function traverse(
node: Node,
callback: (node: Node, parent: Node | null) => boolean | void
): void {
function traverseRec(currentNode: Node, currentParent: Node | null): void {
const shouldDescend = callback(currentNode, currentParent);
if (shouldDescend !== false) {
for (const child of currentNode.getChildren()) {
traverseRec(child, currentNode);
}
}
}
traverseRec(node, null);
}