-
Notifications
You must be signed in to change notification settings - Fork 2
/
print-ast.ts
41 lines (35 loc) · 924 Bytes
/
print-ast.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
// Prints the AST of an expression.
function indent(text: string) {
return text.replace(/\n/g, "\n ")
}
function printArray(value: readonly unknown[]) {
return " " + indent(printAST(value))
}
function printASTKey([key, value]: [string, unknown]) {
if (value === void 0) {
return ""
}
return (
"\n " +
key +
":" +
(Array.isArray(value)
? printArray(value)
: typeof value == "object" && value
? "\n " + indent(indent(printAST(value)))
: " " + JSON.stringify(value))
)
}
export function printAST(node: unknown): string {
if (typeof node != "object" || node == null) {
return JSON.stringify(node)
}
return `${
"type" in node
? String(node.type)[0]?.toUpperCase() + String(node.type).slice(1)
: node.constructor.name
}${Object.entries<unknown>(node as {})
.filter(([key]) => key != "type")
.map(printASTKey)
.join("")}`
}