-
Notifications
You must be signed in to change notification settings - Fork 0
/
traverser.spec.ts
87 lines (82 loc) · 2.54 KB
/
traverser.spec.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { expect, test } from 'vitest'
import { NodeTypes, RootNode } from './ast'
import { traverser } from './traverser'
import type { Visitor } from './traverser'
// 遍历树
test('traverser', () => {
const ast: RootNode = {
type: NodeTypes.Program,
body: [
{
type: NodeTypes.CallExpression,
name: 'add',
params: [
{
type: NodeTypes.NumberLiteral,
value: '2',
},
{
type: NodeTypes.CallExpression,
name: 'subtract',
params: [
{
type: NodeTypes.NumberLiteral,
value: '4',
},
{
type: NodeTypes.NumberLiteral,
value: '2',
},
],
},
],
},
],
}
const callCounts: Array<string | NodeTypes>[] = []
const visitor: Visitor = {
Program: {
enter(node, parent) {
callCounts.push(['program-enter', node.type, ''])
},
exit(node, parent) {
callCounts.push(['program-exit', node.type, ''])
},
},
CallExpression: {
enter(node, parent) {
callCounts.push(['callExpression-enter', node.type, parent!.type])
},
exit(node, parent) {
callCounts.push(['callExpression-exit', node.type, parent!.type])
},
},
NumberLiteral: {
enter(node, parent) {
callCounts.push(['numberLiteral-enter', node.type, parent!.type])
},
exit(node, parent) {
callCounts.push(['numberLiteral-exit', node.type, parent!.type])
},
},
}
traverser(ast, visitor)
expect(callCounts).toEqual([
['program-enter', NodeTypes.Program, ''],
['callExpression-enter', NodeTypes.CallExpression, NodeTypes.Program],
['numberLiteral-enter', NodeTypes.NumberLiteral, NodeTypes.CallExpression],
['numberLiteral-exit', NodeTypes.NumberLiteral, NodeTypes.CallExpression],
[
'callExpression-enter',
NodeTypes.CallExpression,
NodeTypes.CallExpression,
],
['numberLiteral-enter', NodeTypes.NumberLiteral, NodeTypes.CallExpression],
['numberLiteral-exit', NodeTypes.NumberLiteral, NodeTypes.CallExpression],
['numberLiteral-enter', NodeTypes.NumberLiteral, NodeTypes.CallExpression],
['numberLiteral-exit', NodeTypes.NumberLiteral, NodeTypes.CallExpression],
['callExpression-exit', NodeTypes.CallExpression, NodeTypes.CallExpression],
['callExpression-exit', NodeTypes.CallExpression, NodeTypes.Program],
['program-exit', NodeTypes.Program, ''],
])
})