-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathvisit.ts
More file actions
320 lines (293 loc) · 10.7 KB
/
visit.ts
File metadata and controls
320 lines (293 loc) · 10.7 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { Document, type DocValue } from './doc/Document.ts'
import { Alias } from './nodes/Alias.ts'
import { isNode } from './nodes/identity.ts'
import type { Node } from './nodes/Node.ts'
import { Pair } from './nodes/Pair.ts'
import { Scalar } from './nodes/Scalar.ts'
import { YAMLMap } from './nodes/YAMLMap.ts'
import { YAMLSeq } from './nodes/YAMLSeq.ts'
const BREAK = Symbol('break visit')
const SKIP = Symbol('skip children')
const REMOVE = Symbol('remove node')
export type visitorFn<T> = (
key: number | 'key' | 'value' | null,
node: T,
path: readonly (Document | Node | Pair)[]
) => void | symbol | number | Node | Pair
export type visitor =
| visitorFn<Node | Pair | null>
| {
Alias?: visitorFn<Alias>
Collection?: visitorFn<YAMLMap | YAMLSeq>
Map?: visitorFn<YAMLMap>
Node?: visitorFn<Alias | Scalar | YAMLMap | YAMLSeq>
Pair?: visitorFn<Pair>
Scalar?: visitorFn<Scalar>
Seq?: visitorFn<YAMLSeq>
Value?: visitorFn<Scalar | YAMLMap | YAMLSeq>
}
export type asyncVisitorFn<T> = (
key: number | 'key' | 'value' | null,
node: T,
path: readonly (Document | Node | Pair)[]
) =>
| void
| symbol
| number
| Node
| Pair
| Promise<void | symbol | number | Node | Pair>
export type asyncVisitor =
| asyncVisitorFn<Node | Pair | null>
| {
Alias?: asyncVisitorFn<Alias>
Collection?: asyncVisitorFn<YAMLMap | YAMLSeq>
Map?: asyncVisitorFn<YAMLMap>
Node?: asyncVisitorFn<Alias | Scalar | YAMLMap | YAMLSeq>
Pair?: asyncVisitorFn<Pair>
Scalar?: asyncVisitorFn<Scalar>
Seq?: asyncVisitorFn<YAMLSeq>
Value?: asyncVisitorFn<Scalar | YAMLMap | YAMLSeq>
}
/**
* Apply a visitor to an AST node or document.
*
* Walks through the tree (depth-first) starting from `node`, calling a
* `visitor` function with three arguments:
* - `key`: For sequence values and map `Pair`, the node's index in the
* collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
* `null` for the root node.
* - `node`: The current node.
* - `path`: The ancestry of the current node.
*
* The return value of the visitor may be used to control the traversal:
* - `undefined` (default): Do nothing and continue
* - `visit.SKIP`: Do not visit the children of this node, continue with next
* sibling
* - `visit.BREAK`: Terminate traversal completely
* - `visit.REMOVE`: Remove the current node, then continue with the next one
* - `Node`: Replace the current node, then continue by visiting it
* - `number`: While iterating the items of a sequence or map, set the index
* of the next step. This is useful especially if the index of the current
* node has changed.
*
* If `visitor` is a single function, it will be called with all values
* encountered in the tree, including e.g. `null` values. Alternatively,
* separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
* `Alias` and `Scalar` node. To define the same visitor function for more than
* one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
* and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
* specific defined one will be used for each node.
*/
export const visit: {
(node: Node | Document | null, visitor: visitor): void
/** Terminate visit traversal completely */
BREAK: symbol
/** Do not visit the children of the current node */
SKIP: symbol
/** Remove the current node */
REMOVE: symbol
} = function visit(node, visitor) {
const visitor_ = initVisitor(visitor)
if (node instanceof Document) {
const cd = visit_(null, node.value, visitor_, [node])
if (cd === REMOVE) node.value = new Scalar(null)
} else visit_(null, node, visitor_, [])
}
visit.BREAK = BREAK
visit.SKIP = SKIP
visit.REMOVE = REMOVE
function visit_(
key: number | 'key' | 'value' | null,
node: Node | Pair | null,
visitor: visitor,
path: readonly (Document | Node | Pair)[]
): number | symbol | void {
const ctrl = callVisitor(key, node, visitor, path)
if (isNode(ctrl) || ctrl instanceof Pair) {
replaceNode(key, path, ctrl)
return visit_(key, ctrl, visitor, path)
}
if (typeof ctrl !== 'symbol') {
if (node instanceof YAMLMap || node instanceof YAMLSeq) {
path = [...path, node]
for (let i = 0; i < node.items.length; ++i) {
const ci = visit_(i, node.items[i], visitor, path)
if (typeof ci === 'number') i = ci - 1
else if (ci === BREAK) return BREAK
else if (ci === REMOVE) {
node.items.splice(i, 1)
i -= 1
}
}
} else if (node instanceof Pair) {
path = [...path, node]
const ck = visit_('key', node.key, visitor, path)
if (ck === BREAK) return BREAK
else if (ck === REMOVE) node.key = new Scalar(null)
const cv = visit_('value', node.value, visitor, path)
if (cv === BREAK) return BREAK
else if (cv === REMOVE) node.value = null
}
}
return ctrl
}
/**
* Apply an async visitor to an AST node or document.
*
* Walks through the tree (depth-first) starting from `node`, calling a
* `visitor` function with three arguments:
* - `key`: For sequence values and map `Pair`, the node's index in the
* collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
* `null` for the root node.
* - `node`: The current node.
* - `path`: The ancestry of the current node.
*
* The return value of the visitor may be used to control the traversal:
* - `Promise`: Must resolve to one of the following values
* - `undefined` (default): Do nothing and continue
* - `visitAsync.SKIP`: Do not visit the children of this node,
* continue with next sibling
* - `visitAsync.BREAK`: Terminate traversal completely
* - `visitAsync.REMOVE`: Remove the current node,
* then continue with the next one
* - `Node`: Replace the current node, then continue by visiting it
* - `number`: While iterating the items of a sequence or map, set the index
* of the next step. This is useful especially if the index of the current
* node has changed.
*
* If `visitor` is a single function, it will be called with all values
* encountered in the tree, including e.g. `null` values. Alternatively,
* separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
* `Alias` and `Scalar` node. To define the same visitor function for more than
* one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
* and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
* specific defined one will be used for each node.
*/
export const visitAsync: {
(node: Node | Document | null, visitor: asyncVisitor): Promise<void>
/** Terminate visit traversal completely */
BREAK: symbol
/** Do not visit the children of the current node */
SKIP: symbol
/** Remove the current node */
REMOVE: symbol
} = async function visitAsync(node, visitor) {
const visitor_ = initVisitor(visitor)
if (node instanceof Document) {
const cd = await visitAsync_(null, node.value, visitor_, [node])
if (cd === REMOVE) node.value = new Scalar(null)
} else await visitAsync_(null, node, visitor_, [])
}
visitAsync.BREAK = BREAK
visitAsync.SKIP = SKIP
visitAsync.REMOVE = REMOVE
async function visitAsync_(
key: number | 'key' | 'value' | null,
node: Node | Pair | null,
visitor: asyncVisitor,
path: readonly (Document | Node | Pair)[]
): Promise<number | symbol | void> {
const ctrl = await callVisitor(key, node, visitor, path)
if (isNode(ctrl) || ctrl instanceof Pair) {
replaceNode(key, path, ctrl)
return visitAsync_(key, ctrl, visitor, path)
}
if (typeof ctrl !== 'symbol') {
if (node instanceof YAMLMap || node instanceof YAMLSeq) {
path = [...path, node]
for (let i = 0; i < node.items.length; ++i) {
const ci = await visitAsync_(i, node.items[i], visitor, path)
if (typeof ci === 'number') i = ci - 1
else if (ci === BREAK) return BREAK
else if (ci === REMOVE) {
node.items.splice(i, 1)
i -= 1
}
}
} else if (node instanceof Pair) {
path = [...path, node]
const ck = await visitAsync_('key', node.key, visitor, path)
if (ck === BREAK) return BREAK
else if (ck === REMOVE) node.key = new Scalar(null)
const cv = await visitAsync_('value', node.value, visitor, path)
if (cv === BREAK) return BREAK
else if (cv === REMOVE) node.value = null
}
}
return ctrl
}
function initVisitor<V extends visitor | asyncVisitor>(visitor: V) {
if (
typeof visitor === 'object' &&
(visitor.Collection || visitor.Node || visitor.Value)
) {
return Object.assign(
{
Alias: visitor.Node,
Map: visitor.Node,
Scalar: visitor.Node,
Seq: visitor.Node
},
visitor.Value && {
Map: visitor.Value,
Scalar: visitor.Value,
Seq: visitor.Value
},
visitor.Collection && {
Map: visitor.Collection,
Seq: visitor.Collection
},
visitor
)
}
return visitor
}
function callVisitor(
key: number | 'key' | 'value' | null,
node: Node | Pair | null,
visitor: visitor,
path: readonly (Document | Node | Pair)[]
): ReturnType<visitorFn<unknown>>
function callVisitor(
key: number | 'key' | 'value' | null,
node: Node | Pair | null,
visitor: asyncVisitor,
path: readonly (Document | Node | Pair)[]
): ReturnType<asyncVisitorFn<unknown>>
function callVisitor(
key: number | 'key' | 'value' | null,
node: Node | Pair | null,
visitor: visitor | asyncVisitor,
path: readonly (Document | Node | Pair)[]
): ReturnType<visitorFn<unknown>> | ReturnType<asyncVisitorFn<unknown>> {
if (typeof visitor === 'function') return visitor(key, node, path)
if (node instanceof YAMLMap) return visitor.Map?.(key, node, path)
if (node instanceof YAMLSeq) return visitor.Seq?.(key, node, path)
if (node instanceof Pair) return visitor.Pair?.(key, node, path)
if (node instanceof Scalar) return visitor.Scalar?.(key, node, path)
if (node instanceof Alias) return visitor.Alias?.(key, node, path)
return undefined
}
function replaceNode(
key: number | 'key' | 'value' | null,
path: readonly (Document | Node | Pair)[],
node: Node | Pair
): number | symbol | void {
const parent = path[path.length - 1]
if (parent instanceof YAMLMap || parent instanceof YAMLSeq) {
parent.items[key as number] = node
} else if (parent instanceof Pair) {
if (isNode(node)) {
if (key === 'key') parent.key = node
else parent.value = node
} else {
throw new Error(`Cannot replace pair ${key} with non-node value`)
}
} else if (parent instanceof Document) {
parent.value = node as DocValue
} else {
const pt = parent instanceof Alias ? 'alias' : 'scalar'
throw new Error(`Cannot replace node with ${pt} parent`)
}
}