-
Notifications
You must be signed in to change notification settings - Fork 23
/
node.ts
49 lines (37 loc) · 1.26 KB
/
node.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
import { PPAble } from "./pretty_printing";
import { StructEqualityComparable } from "./struct_equality";
import { assert } from "./utils";
export type Position = { offset: number; line: number; column: number };
export type Range = { start: Position; end: Position };
let nNodes = 0;
/**
* Generic tree node with pretty-printer, optional source tripple information
* and structural equality comparison. Useful for building ASTs.
*/
export abstract class Node implements StructEqualityComparable, PPAble {
readonly id: number;
readonly src?: Range;
constructor(src?: Range) {
this.id = nNodes++;
this.src = src;
}
abstract pp(): string;
abstract getFields(): any[];
getChildren(): Node[] {
return this.getFields().filter((field) => field instanceof Node);
}
walk(cb: (node: Node) => void): void {
cb(this);
for (const child of this.getChildren()) {
child.walk(cb);
}
}
get requiredSrc(): Range {
assert(this.src !== undefined, `Missing source information for node ${this.pp()}`);
return this.src;
}
getSourceFragment(src: string): string {
const rng = this.requiredSrc;
return src.slice(rng.start.offset, rng.end.offset);
}
}