-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprint-ast.ts
More file actions
40 lines (34 loc) · 1000 Bytes
/
print-ast.ts
File metadata and controls
40 lines (34 loc) · 1000 Bytes
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
// 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("")}`
}