/
parser.ts
619 lines (573 loc) · 15.9 KB
/
parser.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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import { Lexer } from './lexer.js'
import { SourceTokenType, prettyToken, tokenType } from './token-type.js'
export interface SourceToken {
type: Exclude<SourceTokenType, FlowScalar['type']>
indent: number
source: string
}
export interface ErrorToken {
type: 'error'
source: string
message: string
}
export interface Directive {
type: 'directive'
source: string
}
export interface Document {
type: 'document'
offset: number
start: SourceToken[]
value?: Token
end?: SourceToken[]
}
export interface FlowScalar {
type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar'
offset: number
indent: number
source: string
end?: SourceToken[]
}
export interface BlockScalar {
type: 'block-scalar'
offset: number
indent: number
props: Token[]
source?: string
}
export interface BlockMap {
type: 'block-map'
offset: number
indent: number
items: Array<
| { start: SourceToken[]; key?: never; sep?: never; value?: never }
| {
start: SourceToken[]
key: Token | null
sep: SourceToken[]
value?: Token
}
>
}
export interface BlockSequence {
type: 'block-seq'
offset: number
indent: number
items: Array<{ start: SourceToken[]; value?: Token }>
}
export interface FlowCollection {
type: 'flow-collection'
offset: number
indent: number
start: SourceToken
items: Array<Token>
end: SourceToken[]
}
export type Token =
| SourceToken
| ErrorToken
| Directive
| Document
| FlowScalar
| BlockScalar
| BlockMap
| BlockSequence
| FlowCollection
function includesToken(list: SourceToken[], type: SourceToken['type']) {
for (let i = 0; i < list.length; ++i) if (list[i].type === type) return true
return false
}
/** A YAML concrete syntax tree parser */
export class Parser {
push: (token: Token) => void
onNewLine?: (offset: number) => void
lexer = new Lexer(ts => this.token(ts))
/** If true, space and sequence indicators count as indentation */
atNewLine = true
/** If true, next token is a scalar value */
atScalar = false
/** Current indentation level */
indent = 0
offset = 0
/** On the same line with a block map key */
onKeyLine = false
/** Top indicates the node that's currently being built */
stack: Token[] = []
/** The source of the current token, set in parse() */
source = ''
/** The type of the current token, set in parse() */
type = '' as SourceTokenType
/**
* @param push - Called separately with each parsed token
* @param onNewLine - If defined, called separately with the start position of each new line
* @public
*/
constructor(
push: (token: Token) => void,
onNewLine?: (offset: number) => void
) {
this.push = push
this.onNewLine = onNewLine
}
/**
* Parse `source` as a YAML stream, calling `push` with each
* directive, document and other structure as it is completely parsed.
* If `incomplete`, a part of the last line may be left as a buffer for the next call.
*
* Errors are not thrown, but pushed out as `{ type: 'error', message }` tokens.
* @public
*/
parse(source: string, incomplete = false) {
if (this.onNewLine && this.offset === 0) this.onNewLine(0)
this.lexer.lex(source, incomplete)
if (!incomplete) while (this.stack.length > 0) this.pop()
}
/** Advance the parser by the `source` of one lexical token. */
token(source: string) {
this.source = source
if (process.env.LOG_TOKENS) console.log('|', prettyToken(source))
if (this.atScalar) {
this.atScalar = false
this.step()
this.offset += source.length
return
}
const type = tokenType(source)
if (!type) {
const message = `Not a YAML token: ${source}`
this.pop({ type: 'error', source, message })
this.offset += source.length
} else if (type === 'scalar') {
this.atNewLine = false
this.atScalar = true
this.type = 'scalar'
} else {
this.type = type
this.step()
switch (type) {
case 'newline':
this.atNewLine = true
this.indent = 0
if (this.onNewLine) this.onNewLine(this.offset + source.length)
break
case 'space':
case 'seq-item-ind':
if (this.atNewLine) this.indent += source.length
break
case 'doc-mode':
return
default:
this.atNewLine = false
}
this.offset += source.length
}
}
get sourceToken() {
return {
type: this.type,
indent: this.indent,
source: this.source
} as SourceToken
}
step() {
const top = this.peek()
if (!top) return this.stream()
switch (top.type) {
case 'document':
return this.document(top)
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
return this.scalar(top)
case 'block-scalar':
return this.blockScalar(top)
case 'block-map':
return this.blockMap(top)
case 'block-seq':
return this.blockSequence(top)
case 'flow-collection':
return this.flowCollection(top)
}
this.pop() // error
}
peek() {
return this.stack[this.stack.length - 1]
}
pop(error?: Token) {
const token = error || this.stack.pop()
if (!token) {
const message = 'Tried to pop an empty stack'
this.push({ type: 'error', source: '', message })
} else if (this.stack.length === 0) {
this.push(token)
} else {
const top = this.peek()
switch (top.type) {
case 'document':
top.value = token
break
case 'block-scalar':
top.props.push(token) // error
break
case 'block-map': {
const it = top.items[top.items.length - 1]
if (it.value) top.items.push({ start: [], key: token, sep: [] })
else if (it.sep) it.value = token
else {
Object.assign(it, { key: token, sep: [] })
this.onKeyLine = true
}
break
}
case 'block-seq': {
const it = top.items[top.items.length - 1]
if (it.value) top.items.push({ start: [], value: token })
else it.value = token
break
}
case 'flow-collection':
top.items.push(token)
break
default:
this.pop()
this.pop(token)
}
}
}
stream() {
switch (this.type) {
case 'directive-line':
this.push({ type: 'directive', source: this.source })
return
case 'doc-end':
case 'space':
case 'comment':
case 'newline':
this.push(this.sourceToken)
return
case 'doc-mode':
case 'doc-start': {
const doc: Document = {
type: 'document',
offset: this.offset,
start: []
}
if (this.type === 'doc-start') doc.start.push(this.sourceToken)
this.stack.push(doc)
return
}
}
const message = `Unexpected ${this.type} token in YAML stream`
this.push({ type: 'error', message, source: this.source })
}
document(doc: Document) {
if (doc.value) return this.lineEnd(doc)
switch (this.type) {
case 'doc-start': {
const hasContent =
includesToken(doc.start, 'doc-start') ||
includesToken(doc.start, 'anchor') ||
includesToken(doc.start, 'tag')
if (hasContent) {
this.pop()
this.step()
} else doc.start.push(this.sourceToken)
return
}
case 'anchor':
case 'tag':
case 'space':
case 'comment':
case 'newline':
doc.start.push(this.sourceToken)
return
case 'doc-end':
doc.start.push(this.sourceToken)
this.pop()
return
}
const bv = this.startBlockValue()
if (bv) this.stack.push(bv)
else {
const message = `Unexpected ${this.type} token in YAML document`
this.push({ type: 'error', message, source: this.source })
}
}
scalar(scalar: FlowScalar) {
if (this.type === 'map-value-ind') {
let sep: SourceToken[]
if (scalar.end) {
sep = scalar.end
sep.push(this.sourceToken)
delete scalar.end
} else sep = [this.sourceToken]
const map: BlockMap = {
type: 'block-map',
offset: scalar.offset,
indent: scalar.indent,
items: [{ start: [], key: scalar, sep }]
}
this.onKeyLine = true
this.stack[this.stack.length - 1] = map
} else this.lineEnd(scalar)
}
blockScalar(scalar: BlockScalar) {
switch (this.type) {
case 'space':
case 'comment':
case 'newline':
scalar.props.push(this.sourceToken)
return
case 'scalar':
scalar.source = this.source
// block-scalar source includes trailing newline
this.atNewLine = true
this.indent = 0
if (this.onNewLine) {
let nl = this.source.indexOf('\n') + 1
while (nl !== 0) {
this.onNewLine(this.offset + nl)
nl = this.source.indexOf('\n', nl) + 1
}
}
this.pop()
break
default:
this.pop()
this.step()
}
}
blockMap(map: BlockMap) {
const it = map.items[map.items.length - 1]
// it.sep is true-ish if pair already has key or : separator
switch (this.type) {
case 'newline':
this.onKeyLine = false
// fallthrough
case 'space':
case 'comment':
if (it.value) map.items.push({ start: [this.sourceToken] })
else if (it.sep) it.sep.push(this.sourceToken)
else it.start.push(this.sourceToken)
return
}
if (this.indent >= map.indent) {
const atNextItem = !this.onKeyLine && this.indent === map.indent
switch (this.type) {
case 'anchor':
case 'tag':
if (atNextItem || it.value)
map.items.push({ start: [this.sourceToken] })
else if (it.sep) it.sep.push(this.sourceToken)
else it.start.push(this.sourceToken)
return
case 'explicit-key-ind':
if (!it.sep) it.start.push(this.sourceToken)
else if (atNextItem || it.value)
map.items.push({ start: [this.sourceToken] })
else
this.stack.push({
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
})
this.onKeyLine = true
return
case 'map-value-ind':
if (!it.sep) Object.assign(it, { key: null, sep: [this.sourceToken] })
else if (
it.value ||
(atNextItem && !includesToken(it.start, 'explicit-key-ind'))
)
map.items.push({ start: [], key: null, sep: [this.sourceToken] })
else if (includesToken(it.sep, 'map-value-ind'))
this.stack.push({
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start: [], key: null, sep: [this.sourceToken] }]
})
else it.sep.push(this.sourceToken)
this.onKeyLine = true
return
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar': {
const fs = this.flowScalar(this.type)
if (atNextItem || it.value) {
map.items.push({ start: [], key: fs, sep: [] })
this.onKeyLine = true
} else if (it.sep) {
this.stack.push(fs)
} else {
Object.assign(it, { key: fs, sep: [] })
this.onKeyLine = true
}
return
}
default: {
const bv = this.startBlockValue()
if (bv) return this.stack.push(bv)
}
}
}
this.pop()
this.step()
}
blockSequence(seq: BlockSequence) {
const it = seq.items[seq.items.length - 1]
switch (this.type) {
case 'space':
case 'comment':
case 'newline':
if (it.value) seq.items.push({ start: [this.sourceToken] })
else it.start.push(this.sourceToken)
return
case 'anchor':
case 'tag':
if (it.value || this.indent <= seq.indent) break
it.start.push(this.sourceToken)
return
case 'seq-item-ind':
if (this.indent !== seq.indent) break
if (it.value || includesToken(it.start, 'seq-item-ind'))
seq.items.push({ start: [this.sourceToken] })
else it.start.push(this.sourceToken)
return
}
if (this.indent > seq.indent) {
const bv = this.startBlockValue()
if (bv) return this.stack.push(bv)
}
this.pop()
this.step()
}
flowCollection(fc: FlowCollection) {
if (fc.end.length === 0) {
switch (this.type) {
case 'space':
case 'comment':
case 'newline':
case 'comma':
case 'explicit-key-ind':
case 'map-value-ind':
case 'anchor':
case 'tag':
fc.items.push(this.sourceToken)
return
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
fc.items.push(this.flowScalar(this.type))
return
case 'flow-map-end':
case 'flow-seq-end':
fc.end.push(this.sourceToken)
return
}
const bv = this.startBlockValue()
if (bv) return this.stack.push(bv)
this.pop()
this.step()
} else if (this.type === 'map-value-ind') {
const sep = fc.end.splice(1, fc.end.length)
sep.push(this.sourceToken)
const map: BlockMap = {
type: 'block-map',
offset: fc.offset,
indent: fc.indent,
items: [{ start: [], key: fc, sep }]
}
this.onKeyLine = true
this.stack[this.stack.length - 1] = map
} else {
this.lineEnd(fc)
}
}
flowScalar(
type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar'
) {
if (this.onNewLine) {
let nl = this.source.indexOf('\n') + 1
while (nl !== 0) {
this.onNewLine(this.offset + nl)
nl = this.source.indexOf('\n', nl) + 1
}
}
return {
type,
offset: this.offset,
indent: this.indent,
source: this.source
} as FlowScalar
}
startBlockValue() {
switch (this.type) {
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
return this.flowScalar(this.type)
case 'block-scalar-header':
return {
type: 'block-scalar',
offset: this.offset,
indent: this.indent,
props: [this.sourceToken]
} as BlockScalar
case 'flow-map-start':
case 'flow-seq-start':
return {
type: 'flow-collection',
offset: this.offset,
indent: this.indent,
start: this.sourceToken,
items: [],
end: []
} as FlowCollection
case 'seq-item-ind':
return {
type: 'block-seq',
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
} as BlockSequence
case 'explicit-key-ind':
this.onKeyLine = true
return {
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
} as BlockMap
case 'map-value-ind':
this.onKeyLine = true
return {
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start: [], key: null, sep: [this.sourceToken] }]
} as BlockMap
}
return null
}
lineEnd(token: Document | FlowCollection | FlowScalar) {
switch (this.type) {
case 'space':
case 'comment':
case 'newline':
if (token.end) token.end.push(this.sourceToken)
else token.end = [this.sourceToken]
if (this.type === 'newline') this.pop()
return
default:
this.pop()
this.step()
return
}
}
}