-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtarget-ts.ts
More file actions
4000 lines (3898 loc) · 186 KB
/
Copy pathtarget-ts.ts
File metadata and controls
4000 lines (3898 loc) · 186 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
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The TypeScript Target for emit-portable. Renders the language-agnostic ParserIR into a
// self-contained TS parser: a char-class/string/comment lexer, a backtracking recursive-
// descent core, a Pratt expression engine (prefix + binary precedence + mixfix call/member/
// index LEDs), and a CST→JSON printer over stdin. It is the reference rendering — its CST
// is checked byte-for-byte against the interpreter (createParser), so a divergence in the
// portable logic surfaces here before Go/Rust are compiled.
import { type ParserIR, type RdRule, type PrattRule, type Step, type Bracket, type CharRange, type LexTok, type TplCfg, type NewlineCfg, type FirstSig, type LexFirstBytes, type LexIdPlan } from './emit-portable.ts';
import { portableIR, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, lidOf, kidOf, lidFlagTable, kidFlagTable, rangesHaveNonAscii, isFirstGuardable, groupByPreserveOrder } from './emit-portable.ts';
import type { Target } from './emit.ts';
import type { CstGrammar } from './types.ts';
import type {
ShapeSpec, ShapeIR, FieldBind, FieldDecl, NodeShape, ChoiceShape, ChoiceArm,
RuleShape, TokenLeafPolicy, ShapeIRRule, CustomShape, KeepShape,
} from './shape-schema.ts';
import { validateShapeOrThrow } from './shape-validate.ts';
export type { ShapeSpec, ShapeIR } from './shape-schema.ts';
const J = (v: unknown) => JSON.stringify(v);
const rangeCond = (v: string, rs: CharRange[]) =>
'(' + rs.map(([lo, hi]) => (lo === hi ? `${v} === ${lo}` : `${v} >= ${lo} && ${v} <= ${hi}`)).join(' || ') + ')';
/** Bail predicate: byte in bail set, or (bailNonAscii && ≥128). */
function bailCondTS(v: string, bail: number[], bailNonAscii: boolean): string {
const parts = bail.map((c) => `${v} === ${c}`);
if (bailNonAscii) parts.push(`${v} >= 128`);
return parts.length ? parts.join(' || ') : 'false';
}
/** 256-entry Uint8Array FIRST/CONT table from ASCII-only ranges (codes >127 omitted). */
function emitAsciiBoolTableTS(name: string, rs: CharRange[]): string {
const ranges = rs
.filter(([lo]) => lo <= 127)
.map(([lo, hi]) => `[${Math.max(0, lo)},${Math.min(127, hi)}]`);
return `const ${name} = /*#__PURE__*/ (() => { const a = new Uint8Array(256); for (const [lo, hi] of [${ranges.join(', ')}]) for (let i = lo; i <= hi; i++) a[i] = 1; return a; })();`;
}
// Boolean expr testing whether the buffered token t starts branch i (FIRST set membership).
const firstCond = (f: FirstSig, t: string, ids: LexIdPlan) => f
? `(${f.lits.map((l) => `${t}.lid === ${lidOf(ids, l)}`).join(' || ') || 'false'} || ${f.toks.map((k) => `${t}.kid === ${kidOf(ids, k)}`).join(' || ') || 'false'})`
: 'false';
/** Non-null FirstSig small enough to pre-filter before a backtracking attempt. */
const isGuardable = (f: FirstSig, nAlts?: number): f is NonNullable<FirstSig> =>
isFirstGuardable(f, nAlts);
/** Emit kid/lid lookup tables into generated lexer source. */
function renderIdTablesTS(ids: LexIdPlan): string {
const pf = buildLidPrefilter(ids);
const bitsLit = [...pf.firstByLenBits].join(', ');
return `const KIND_STR: string[] = ${J(ids.kids)};
const _LIDS: string[] = ${J(ids.lids)};
const _KID_MAP = new Map<string, number>(KIND_STR.map((k, i) => [k, i]));
const _LID_MAP = new Map<string, number>(_LIDS.map((t, i) => [t, i]));
const _LID_MAX_LEN = ${pf.maxByteLen};
const _LID_FIRST_BITS = new Uint8Array([${bitsLit}]);
function kid_of(kind: string): number { return _KID_MAP.get(kind) ?? 0; }
function lid_of(text: string): number {
const n = text.length;
if (n === 0 || n > _LID_MAX_LEN) return 0;
const b0 = text.charCodeAt(0);
// Ident/@-keyword shape: O(1) length×first-byte miss ⇒ lid 0. Punct first bytes skip the probe.
if ((b0 >= 65 && b0 <= 90) || (b0 >= 97 && b0 <= 122) || b0 === 95 || b0 === 36 || b0 === 64) {
if ((_LID_FIRST_BITS[n * 32 + (b0 >> 3)]! & (1 << (b0 & 7))) === 0) return 0;
}
return _LID_MAP.get(text) ?? 0;
}
function tok_kind(t: Tok): string { return KIND_STR[t.kid]!; }
function tok_text(src: string, t: Tok): string { return src.slice(t.off, t.end); }
function mk_tok(off: number, end: number, nl: boolean, kid: number, lid: number): Tok { return { off, end, nl, kid, lid }; }
`;
}
import type { TokenPattern } from './types.ts';
// Compile a token-pattern AST to backtracking-free matcher functions `_mN(p): number`
// (returns the new position, or -1 on no match). Greedy `repeat`, ordered `alt`,
// zero-width `lookahead`/`anchor` — the regex-free token-matcher tier.
function ccCond(p: Extract<TokenPattern, { type: 'charClass' }>): string {
const parts = p.items.map((it) =>
it.type === 'char' ? `cc === ${it.value.charCodeAt(0)}` : `cc >= ${it.from.charCodeAt(0)} && cc <= ${it.to.charCodeAt(0)}`);
const inSet = '(' + parts.join(' || ') + ')';
return p.negate ? `!${inSet}` : inSet;
}
function compilePat(p: TokenPattern, defs: string[]): string {
const name = `_m${defs.length}`;
defs.push(''); // reserve the slot (keeps numbering stable across recursion)
let body: string;
if (typeof p === 'string') {
body = `=> _s.startsWith(${J(p)}, p) ? p + ${p.length} : -1`;
} else switch (p.type) {
case 'anyChar': body = `=> p < _s.length ? p + 1 : -1`; break;
case 'charClass': body = `=> { if (p >= _s.length) return -1; const cc = _s.charCodeAt(p); return ${ccCond(p)} ? p + 1 : -1; }`; break;
case 'seq': { const ms = p.items.map((x) => compilePat(x, defs)); body = `=> { ${ms.map((m) => `p = ${m}(p); if (p < 0) return -1;`).join(' ')} return p; }`; break; }
case 'alt': { const ms = p.items.map((x) => compilePat(x, defs)); body = `=> { ${ms.map((m) => `{ const r = ${m}(p); if (r >= 0) return r; }`).join(' ')} return -1; }`; break; }
case 'repeat': { const m = compilePat(p.body, defs); const mx = p.max !== undefined ? `if (c >= ${p.max}) break;` : ''; body = `=> { let q = p, c = 0; for (;;) { const r = ${m}(q); if (r < 0 || r === q) break; q = r; c++; ${mx} } return c >= ${p.min} ? q : -1; }`; break; }
case 'lookahead': { const m = compilePat(p.body, defs); body = `=> { const r = ${m}(p); return ${p.negate ? 'r < 0' : 'r >= 0'} ? p : -1; }`; break; }
case 'anchor': body = p.kind === 'start' ? `=> p === 0 ? p : -1` : `=> p === _s.length ? p : -1`; break;
default: throw new Error(`portable TS lexer: pattern '${(p as { type: string }).type}' unsupported`);
}
defs[Number(name.slice(2))] = `const ${name} = (p: number): number ${body};`;
return name;
}
function scanTok(t: LexTok, defs: string[], stateful: boolean, ids: LexIdPlan, rxTok: string | undefined, tplTok: string | undefined, identLike: Set<string>): string {
const name = (t as { name: string }).name;
if (tplTok !== undefined && name === tplTok) return ''; // template token is scanned by the state machine
// `emit(...)` threads the lexer state in stateful mode; a plain push otherwise. A skipped
// token (comment) still records a newline it spans, so `sameLine` sees it.
const kid = kidOf(ids, name);
const push = (endExpr: string) => (t.skip
? `if (/[\\n\\r\\u2028\\u2029]/.test(src.slice(pos, ${endExpr}))) pendingNl = true; `
: `${stateful ? 'emit' : 'push'}(pos, ${endExpr}, ${kid}, lid_of(src.slice(pos, ${endExpr}))); `);
const gate = rxTok !== undefined && name === rxTok ? '!prevIsValue() && ' : '';
// Identifier(-prefixed) token: fold a trailing non-ASCII ID_Continue run into the match
// (caf|é → café), mirroring the interpreter's uniIdentContReY extension (gen-lexer.ts).
const ext = (v: string) => (identLike.has(name) ? `${v} = lx_ext(src, ${v}); ` : '');
if (t.kind === 'run') return ` if (${gate}${rangeCond('c', t.first)}) {
let e = pos + 1;
while (e < n) { const cc = src.charCodeAt(e); if (!${rangeCond('cc', t.cont)}) break; e++; }
${ext('e')}${push('e')}pos = e; continue;
}`;
if (t.kind === 'runBail') {
// Cont with non-ASCII: refuse tight loop (byte-index unsafe for multi-unit chars in other
// targets; keep three-target isomorphism — fall back to pattern cascade).
if (rangesHaveNonAscii(t.cont)) {
const m = compilePat(t.pattern, defs);
return ` if (${gate}true) { let e = ${m}(pos); if (e > pos) { ${ext('e')}${push('e')}pos = e; continue; } }`;
}
const tag = t.name.replace(/[^A-Za-z0-9_]/g, '_');
const fTab = `_rbF_${tag}`, cTab = `_rbC_${tag}`;
defs.push(emitAsciiBoolTableTS(fTab, t.first));
defs.push(emitAsciiBoolTableTS(cTab, t.cont));
const m = compilePat(t.pattern, defs);
const bailAt = (v: string) => bailCondTS(v, t.bail, t.bailNonAscii);
// Entry fallback covers cont-bail chars AND complex-head entry chars (headBail).
const entryBail = bailCondTS('c', [...new Set([...t.bail, ...t.headBail])].sort((a, b) => a - b), t.bailNonAscii || t.headBailNonAscii);
return ` if (${gate}${fTab}[c]) {
let e = pos + 1;
while (e < n && ${cTab}[src.charCodeAt(e)]) e++;
if (e >= n || !(${bailAt('src.charCodeAt(e)')})) { ${ext('e')}${push('e')}pos = e; continue; }
{ let e2 = ${m}(pos); if (e2 > pos) { ${ext('e2')}${push('e2')}pos = e2; continue; } }
} else if (${entryBail}) {
let e = ${m}(pos); if (e > pos) { ${ext('e')}${push('e')}pos = e; continue; }
}`;
}
if (t.kind === 'string') return ` if (${gate}c === ${t.delim.charCodeAt(0)}) {
let e = pos + 1, closed = false;
while (e < n) { const ch = src.charCodeAt(e); if (ch === 92) { e += 2; continue; } if (ch === ${t.delim.charCodeAt(0)}) { e++; closed = true; break; } e++; }
if (closed) { ${push('e')}pos = e; continue; }
}`;
if (t.kind === 'line') return ` if (${gate}src.startsWith(${J(t.prefix)}, pos)) {
let e = pos + ${t.prefix.length};
while (e < n && src.charCodeAt(e) !== 10) e++;
${push('e')}pos = e; continue;
}`;
if (t.kind === 'block') return ` if (${gate}src.startsWith(${J(t.open)}, pos)) {
let e = pos + ${t.open.length};
while (e < n && !src.startsWith(${J(t.close)}, e)) e++;
if (e < n) { e += ${t.close.length}; ${push('e')}pos = e; continue; }
}`;
const m = compilePat(t.pattern, defs);
return ` if (${gate}true) { const e = ${m}(pos); if (e > pos) { ${push('e')}pos = e; continue; } }`;
}
function buildLexCandidates(
ir: ParserIR, defs: string[], stateful: boolean, ids: LexIdPlan, rxTok: string | undefined, tplTok: string | undefined,
punctLine: (p: string) => string,
): { codes: string[]; firsts: (LexFirstBytes | null)[] } {
const identLike = new Set(ir.identLike);
const codes: string[] = [];
const firsts: (LexFirstBytes | null)[] = [];
for (const t of ir.tokens) {
const code = scanTok(t, defs, stateful, ids, rxTok, tplTok, identLike);
if (!code) continue;
codes.push(code);
firsts.push(lexTokFirstBytes(t));
}
for (const p of ir.puncts) {
codes.push(punctLine(p));
firsts.push(punctFirstBytes(p));
}
return { codes, firsts };
}
/** Shared first-byte dispatch for all lexFrom variants in this target. */
function renderLexByteDispatchTS(codes: string[], firsts: (LexFirstBytes | null)[], indent: string): string {
const { arms, fallbackIndices } = buildLexDispatchPlan(firsts);
const fallback = fallbackIndices.map((i) => codes[i]).join('\n');
let switchArms = '';
for (const arm of arms) {
switchArms += arm.bytes.map((b) => `${indent} case ${b}:`).join('\n') + '\n';
switchArms += arm.indices.map((i) => codes[i]).join('\n') + '\n';
switchArms += `${indent} break;\n`;
}
return `${indent}if (c >= 128) {
${fallback}
${indent}} else {
${indent} switch (c) {
${switchArms}${indent} }
${indent}}`;
}
function newlineParts(nl: NewlineCfg, pushFn: string, ids: LexIdPlan): { state: string; stateFrom: string; boundary: string; ws: string; hooks: string } {
const commentSkip = nl.comment
? ` if (src.startsWith(${J(nl.comment)}, p)) { let e = p; while (e < n && src.charCodeAt(e) !== 10) e++; pos = e; continue; }\n`
: '';
return {
state: ` let lineStart = true, emittedContent = false, flowDepth = 0;
const _flowOpen = new Set([${nl.flowOpen.map(J).join(', ')}]);
const _flowClose = new Set([${nl.flowClose.map(J).join(', ')}]);
const _kidNl = ${kidOf(ids, nl.token)};
`,
stateFrom: ` const _flowOpen = new Set([${nl.flowOpen.map(J).join(', ')}]);
const _flowClose = new Set([${nl.flowClose.map(J).join(', ')}]);
const _kidNl = ${kidOf(ids, nl.token)};
`,
boundary: ` if (flowDepth === 0 && lineStart) {
let p = pos;
while (p < n && src.charCodeAt(p) === 32) p++;
if (p >= n) { pos = p; lineStart = false; continue; }
const ch = src.charCodeAt(p);
if (ch === 10 || ch === 13) { // LF/CR only — the interpreter's newline mode rejects LS/PS (gen-lexer.ts blank-line check)
pos = p + 1; if (ch === 13 && pos < n && src.charCodeAt(pos) === 10) pos++;
continue;
}
if (ch === 9) {
let b = p;
while (b < n && (src.charCodeAt(b) === 32 || src.charCodeAt(b) === 9)) b++;
if (b >= n) { pos = b; continue; }
const bc = src.charCodeAt(b);
if (bc === 10 || bc === 13) {
pos = b + 1; if (bc === 13 && pos < n && src.charCodeAt(pos) === 10) pos++;
continue;
}
}
${commentSkip} pos = p;
if (emittedContent) ${pushFn}(pos, pos, ${kidOf(ids, nl.token)}, 0);
lineStart = false;
continue;
}
`,
ws: ` if (c === 32 || c === 9 || c === 11 || c === 12 || c === 160 || c === 5760 || (c >= 8192 && c <= 8202) || c === 8239 || c === 8287 || c === 12288 || c === 65279) { pos++; continue; }
if (c === 10 || c === 13) { // LF/CR only — LS/PS fall through to the unexpected-character throw, matching the interpreter
pos++; if (c === 13 && pos < n && src.charCodeAt(pos) === 10) pos++;
if (flowDepth === 0) lineStart = true;
continue;
}
`,
hooks: ` if (kid !== _kidNl) emittedContent = true;
if (kid === 0 && _flowOpen.has(_LIDS[lid]!)) flowDepth++;
else if (kid === 0 && _flowClose.has(_LIDS[lid]!)) flowDepth = Math.max(0, flowDepth - 1);
`,
};
}
/** Emit a dense 0/1 number[] bit table (indexed by lid or kid). */
function tsFlagTable(name: string, flags: boolean[]): string {
return `const ${name}: number[] = [${flags.map((b) => (b ? 1 : 0)).join(', ')}];`;
}
function lexer(ir: ParserIR): string {
const ids = buildLexIdPlan(ir);
const defs: string[] = [];
const rx = ir.regexCtx;
const tpl = ir.tpl;
const nl = ir.newlineCfg;
const rxOnly = !!(rx && !tpl && !nl);
const tplOnly = !!(tpl && !rx && !nl);
const rxTpl = !!(rx && tpl && !nl);
const rxOrTpl = !!(rx || tpl) && !rxOnly && !tplOnly && !rxTpl;
const stateful = !!(rx || tpl);
const newlineOnly = !!(nl && !rx && !tpl);
const pushFn = stateful ? 'emit' : 'push';
const punctLine = (p: string) =>
` if (src.startsWith(${J(p)}, pos)) { ${pushFn}(pos, pos + ${p.length}, 0, ${lidOf(ids, p)}); pos += ${p.length}; continue; }`;
const { codes: lexCodes, firsts: lexFirsts } = buildLexCandidates(ir, defs, stateful, ids, rx?.regexToken, tpl?.token, punctLine);
const cascade = renderLexByteDispatchTS(lexCodes, lexFirsts, ' ');
const rxBitTables = rx ? `${tsFlagTable('_divT', lidFlagTable(ids, rx.divisionTexts))}
${tsFlagTable('_divK', kidFlagTable(ids, rx.divisionTypes))}
${tsFlagTable('_rxT', lidFlagTable(ids, rx.regexTexts))}
${tsFlagTable('_phK', lidFlagTable(ids, rx.parenHeadKw))}
${tsFlagTable('_mem', lidFlagTable(ids, rx.memberAccess))}
${tsFlagTable('_pav', lidFlagTable(ids, rx.postfixAfterValue))}
const KID_IDENT = ${kidOf(ids, rx.identToken)};
const LID_LPAREN = ${lidOf(ids, '(')};
const LID_RPAREN = ${lidOf(ids, ')')};
` : '';
const tplLidConsts = tpl ? `const LID_BRACE_OPEN = ${lidOf(ids, tpl.braceOpen)};
const LID_INTERP_CLOSE = ${lidOf(ids, tpl.interpClose)};
` : '';
const rxModuleConsts = `${rxBitTables}${tplLidConsts}`;
// Per-feature pieces of the shared `emit`, so a grammar can have regex, templates, or both.
const rxState = rx ? ` let prevLid = 0, prevKid = 0, bpLid = 0, hasPrev = false, hasPrev2 = false;
const parenHead: boolean[] = [];
let lastClose = false, lastBang = false;
function prevIsValue(): boolean {
if (!hasPrev) return false;
if (_pav[prevLid]) return lastBang;
const isExprKw = prevKid === KID_IDENT && !!_rxT[prevLid];
const isParenHead = prevLid === LID_RPAREN && lastClose;
return !isExprKw && !isParenHead && (!!_divK[prevKid] || !!_divT[prevLid]);
}
` : '';
const tplState = tpl ? ` const templateStack: number[] = [];
function scanTplSpan(p: number): { interp: boolean; end: number } {
while (p < n) {
if (src.startsWith(${J(tpl.interpOpen)}, p)) return { interp: true, end: p + ${tpl.interpOpen.length} };
if (src.charCodeAt(p) === 92) { p += 2; continue; }
if (src.startsWith(${J(tpl.open)}, p)) return { interp: false, end: p + ${tpl.open.length} };
p++;
}
throw new Error('Unterminated template literal at offset ' + p);
}
` : '';
const emitHooks = [
rx ? ` if (lid === LID_LPAREN) { const isMember = hasPrev2 && !!_mem[bpLid]; parenHead.push(!isMember && prevKid === KID_IDENT && !!_phK[prevLid]); }
else if (lid === LID_RPAREN) { lastClose = parenHead.pop() ?? false; }
if (_pav[lid]) lastBang = prevIsValue();` : '',
tpl ? ` if (templateStack.length > 0) { if (lid === LID_BRACE_OPEN) templateStack[templateStack.length - 1]++; else if (lid === LID_INTERP_CLOSE) templateStack[templateStack.length - 1]--; }` : '',
nl ? newlineParts(nl, 'emit', ids).hooks : '',
].filter(Boolean).join('\n');
const emitTail = rx ? `\n bpLid = prevLid; hasPrev2 = hasPrev; prevKid = kid; prevLid = lid; hasPrev = true;` : '';
const emitFn = stateful ? ` function emit(off: number, end: number, kid: number, lid: number): void {
${emitHooks}
toks.push(mk_tok(off, end, pendingNl, kid, lid)); pendingNl = false;${emitTail}
}
` : '';
const rxStateFrom = rx ? ` function prevIsValue(): boolean {
if (!hasPrev) return false;
if (_pav[prevLid]) return lastBang;
const isExprKw = prevKid === KID_IDENT && !!_rxT[prevLid];
const isParenHead = prevLid === LID_RPAREN && lastClose;
return !isExprKw && !isParenHead && (!!_divK[prevKid] || !!_divT[prevLid]);
}
` : '';
const tplStateFrom = tpl ? ` function scanTplSpan(p: number): { interp: boolean; end: number } {
while (p < n) {
if (src.startsWith(${J(tpl.interpOpen)}, p)) return { interp: true, end: p + ${tpl.interpOpen.length} };
if (src.charCodeAt(p) === 92) { p += 2; continue; }
if (src.startsWith(${J(tpl.open)}, p)) return { interp: false, end: p + ${tpl.open.length} };
p++;
}
throw new Error('Unterminated template literal at offset ' + p);
}
` : '';
const emitRxOnly = rx ? ` function emit(off: number, end: number, kid: number, lid: number): void {
if (lid === LID_LPAREN) { const isMember = hasPrev2 && !!_mem[bpLid]; parenHead.push(!isMember && prevKid === KID_IDENT && !!_phK[prevLid]); }
else if (lid === LID_RPAREN) { lastClose = parenHead.pop() ?? false; }
if (_pav[lid]) lastBang = prevIsValue();
toks.push(mk_tok(off, end, pendingNl, kid, lid)); pendingNl = false;
bpLid = prevLid; hasPrev2 = hasPrev; prevKid = kid; prevLid = lid; hasPrev = true;
}
` : '';
const emitTplOnly = tpl ? ` function emit(off: number, end: number, kid: number, lid: number): void {
if (templateStack.length > 0) { if (lid === LID_BRACE_OPEN) templateStack[templateStack.length - 1]++; else if (lid === LID_INTERP_CLOSE) templateStack[templateStack.length - 1]--; }
toks.push(mk_tok(off, end, pendingNl, kid, lid)); pendingNl = false;
}
` : '';
const emitRxTpl = (rx && tpl) ? ` function emit(off: number, end: number, kid: number, lid: number): void {
if (lid === LID_LPAREN) { const isMember = hasPrev2 && !!_mem[bpLid]; parenHead.push(!isMember && prevKid === KID_IDENT && !!_phK[prevLid]); }
else if (lid === LID_RPAREN) { lastClose = parenHead.pop() ?? false; }
if (_pav[lid]) lastBang = prevIsValue();
if (templateStack.length > 0) { if (lid === LID_BRACE_OPEN) templateStack[templateStack.length - 1]++; else if (lid === LID_INTERP_CLOSE) templateStack[templateStack.length - 1]--; }
toks.push(mk_tok(off, end, pendingNl, kid, lid)); pendingNl = false;
bpLid = prevLid; hasPrev2 = hasPrev; prevKid = kid; prevLid = lid; hasPrev = true;
}
` : '';
// Template dispatch runs at the top of the loop, before token/punct scanning.
const tplDispatch = tpl ? ` if (templateStack.length > 0 && src.startsWith(${J(tpl.interpClose)}, pos) && templateStack[templateStack.length - 1] === 0) {
templateStack.pop();
const sp = scanTplSpan(pos + ${tpl.interpClose.length});
if (sp.interp) { const _tx = src.slice(pos, sp.end); emit(pos, sp.end, ${kidOf(ids, '$templateMiddle')}, lid_of(_tx)); templateStack.push(0); }
else { const _tx = src.slice(pos, sp.end); emit(pos, sp.end, ${kidOf(ids, '$templateTail')}, lid_of(_tx)); }
pos = sp.end; continue;
}
if (src.startsWith(${J(tpl.open)}, pos)) {
const sp = scanTplSpan(pos + ${tpl.open.length});
if (sp.interp) { const _tx = src.slice(pos, sp.end); emit(pos, sp.end, ${kidOf(ids, '$templateHead')}, lid_of(_tx)); templateStack.push(0); }
else { const _tx = src.slice(pos, sp.end); emit(pos, sp.end, ${kidOf(ids, tpl.token)}, lid_of(_tx)); }
pos = sp.end; continue;
}
` : '';
const identNameTs = ir.identToken;
const identKidTs = identNameTs ? kidOf(ids, identNameTs) : 0;
const lxExtConst = ir.identLike.length
? `const LX_UNI_CONT = /[$\\u200c\\u200d\\p{ID_Continue}]+/uy;
function lx_ext(src: string, e: number): number {
if (e >= src.length || src.charCodeAt(e) < 0x80) return e;
LX_UNI_CONT.lastIndex = e;
const m = LX_UNI_CONT.exec(src);
return m ? e + m[0].length : e;
}
`
: '';
const lxUniIdentConst = (identNameTs
? 'const LX_UNI_IDENT = /[$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]*/uy;\n'
: '') + lxExtConst;
const uniIdentPushTs = stateful ? 'emit' : 'push';
const uniIdentFallbackTs = identNameTs
? ` LX_UNI_IDENT.lastIndex = pos;
const _um = LX_UNI_IDENT.exec(src);
if (_um) { ${uniIdentPushTs}(pos, pos + _um[0].length, ${identKidTs}, lid_of(_um[0])); pos += _um[0].length; continue; }
`
: '';
const nlState = nl ? newlineParts(nl, stateful ? 'emit' : 'push', ids).state : '';
const nlStateFrom = nl ? newlineParts(nl, 'push', ids).stateFrom : '';
const nlBoundary = nl ? newlineParts(nl, stateful ? 'emit' : 'push', ids).boundary : '';
const nlWs = nl ? newlineParts(nl, stateful ? 'emit' : 'push', ids).ws : ` if (c === 10 || c === 13 || c === 8232 || c === 8233) { pendingNl = true; pos++; continue; }
if (c === 32 || c === 9 || c === 11 || c === 12 || c === 160 || c === 5760 || (c >= 8192 && c <= 8202) || c === 8239 || c === 8287 || c === 12288 || c === 65279) { pos++; continue; }
`;
const pushHooks = nl && !stateful ? newlineParts(nl, 'push', ids).hooks : '';
const pushFnDef = stateful ? '' : nl
? ` const push = (off: number, end: number, kid: number, lid: number) => {
${pushHooks} toks.push(mk_tok(off, end, pendingNl, kid, lid)); pendingNl = false;
};
`
: ' const push = (off: number, end: number, kid: number, lid: number) => { toks.push(mk_tok(off, end, pendingNl, kid, lid)); pendingNl = false; };\n';
const loopBody = `${nlBoundary} const c = src.charCodeAt(pos);
// JS line terminators LF/CR/LS/PS set newline-before, matching the interpreter (gen-lexer.ts).
${nlWs}${tplDispatch}${cascade}
${uniIdentFallbackTs} throw new Error('Unexpected character at offset ' + pos + ': \\'' + src[pos] + '\\'');`;
if (rxOnly) {
return `${renderIdTablesTS(ids)}${lxUniIdentConst}${rxModuleConsts}${defs.length ? 'let _s = "";\n' + defs.join('\n') + '\n' : ''}function lexFrom(src: string, pos: number, pendingNl: boolean, prevLid: number, prevKid: number, hasPrev: boolean, bpLid: number, hasPrev2: boolean, parenHead: boolean[], lastClose: boolean, lastBang: boolean, toks: Tok[], limit?: number): { pos: number; pendingNl: boolean; prevLid: number; prevKid: number; hasPrev: boolean; bpLid: number; hasPrev2: boolean; parenHead: boolean[]; lastClose: boolean; lastBang: boolean } {
const n = src.length;
const base = toks.length;
${defs.length ? ' _s = src;\n' : ''}${rxStateFrom}${emitRxOnly} while (pos < n && (limit === undefined || toks.length - base < limit)) {
${loopBody}
}
return { pos, pendingNl, prevLid, prevKid, hasPrev, bpLid, hasPrev2, parenHead, lastClose, lastBang };
}
function lex(src: string): Tok[] {
const toks: Tok[] = [];
lexFrom(src, 0, false, 0, 0, false, 0, false, [], false, false, toks);
return toks;
}`;
}
if (tplOnly) {
return `${renderIdTablesTS(ids)}${lxUniIdentConst}${rxModuleConsts}${defs.length ? 'let _s = "";\n' + defs.join('\n') + '\n' : ''}function lexFrom(src: string, pos: number, pendingNl: boolean, templateStack: number[], toks: Tok[], limit?: number): { pos: number; pendingNl: boolean; templateStack: number[] } {
const n = src.length;
const base = toks.length;
${defs.length ? ' _s = src;\n' : ''}${tplStateFrom}${emitTplOnly} while (pos < n && (limit === undefined || toks.length - base < limit)) {
${loopBody}
}
return { pos, pendingNl, templateStack };
}
function lex(src: string): Tok[] {
const toks: Tok[] = [];
lexFrom(src, 0, false, [], toks);
return toks;
}`;
}
if (rxTpl) {
return `${renderIdTablesTS(ids)}${lxUniIdentConst}${rxModuleConsts}${defs.length ? 'let _s = "";\n' + defs.join('\n') + '\n' : ''}function lexFrom(src: string, pos: number, pendingNl: boolean, prevLid: number, prevKid: number, hasPrev: boolean, bpLid: number, hasPrev2: boolean, parenHead: boolean[], lastClose: boolean, lastBang: boolean, templateStack: number[], toks: Tok[], limit?: number): { pos: number; pendingNl: boolean; prevLid: number; prevKid: number; hasPrev: boolean; bpLid: number; hasPrev2: boolean; parenHead: boolean[]; lastClose: boolean; lastBang: boolean; templateStack: number[] } {
const n = src.length;
const base = toks.length;
${defs.length ? ' _s = src;\n' : ''}${rxStateFrom}${tplStateFrom}${emitRxTpl} while (pos < n && (limit === undefined || toks.length - base < limit)) {
${loopBody}
}
return { pos, pendingNl, prevLid, prevKid, hasPrev, bpLid, hasPrev2, parenHead, lastClose, lastBang, templateStack };
}
function lex(src: string): Tok[] {
const toks: Tok[] = [];
lexFrom(src, 0, false, 0, 0, false, 0, false, [], false, false, [], toks);
return toks;
}`;
}
if (rxOrTpl) {
return `${renderIdTablesTS(ids)}${lxUniIdentConst}${rxModuleConsts}${defs.length ? 'let _s = "";\n' + defs.join('\n') + '\n' : ''}function lex(src: string): Tok[] {
const toks: Tok[] = [];
const n = src.length;
let pos = 0;
let pendingNl = false;
${defs.length ? ' _s = src;\n' : ''}${rxState}${tplState}${nlState}${emitFn} while (pos < n) {
${loopBody}
}
return toks;
}`;
}
if (newlineOnly) {
return `${renderIdTablesTS(ids)}${lxUniIdentConst}${defs.length ? 'let _s = "";\n' + defs.join('\n') + '\n' : ''}function lexFrom(src: string, pos: number, pendingNl: boolean, lineStart: boolean, emittedContent: boolean, flowDepth: number, toks: Tok[], limit?: number): { pos: number; pendingNl: boolean; lineStart: boolean; emittedContent: boolean; flowDepth: number } {
const n = src.length;
const base = toks.length;
${defs.length ? ' _s = src;\n' : ''}${nlStateFrom}${pushFnDef} while (pos < n && (limit === undefined || toks.length - base < limit)) {
${loopBody}
}
return { pos, pendingNl, lineStart, emittedContent, flowDepth };
}
function lex(src: string): Tok[] {
const toks: Tok[] = [];
lexFrom(src, 0, false, true, false, 0, toks);
return toks;
}`;
}
return `${renderIdTablesTS(ids)}${lxUniIdentConst}${defs.length ? 'let _s = "";\n' + defs.join('\n') + '\n' : ''}function lexFrom(src: string, pos: number, pendingNl: boolean, toks: Tok[], limit?: number): { pos: number; pendingNl: boolean } {
const n = src.length;
const base = toks.length;
${defs.length ? ' _s = src;\n' : ''}${pushFnDef} while (pos < n && (limit === undefined || toks.length - base < limit)) {
${loopBody}
}
return { pos, pendingNl };
}
function lex(src: string): Tok[] {
const toks: Tok[] = [];
lexFrom(src, 0, false, toks);
return toks;
}`;
}
// A Step as a boolean expression (appends to the in-scope `kids`).
// When `w` is true, emit the builder-mode helpers (`matchLitW` …) that also maintain
// a parallel `spans` array — span bookkeeping never reads consumer handles.
function stepCond(s: Step, ids: LexIdPlan, w = false): string {
const S = w ? 'W' : '';
const ks = w ? 'kids, spans' : 'kids';
const sc = (x: Step) => stepCond(x, ids, w);
switch (s.t) {
case 'lit': return `matchLit${S}(${lidOf(ids, s.value)}, ${J(s.ttype)}, ${ks})`;
case 'tok': return `matchTok${S}(${kidOf(ids, s.name)}, ${J(s.name)}, ${ks})`;
case 'rule': return `callRule${S}(parse${s.name}${S}, ${ks})`;
case 'ruleBp': return `callRule${S}(() => ${s.name}_bp${S}(${s.bp}), ${ks})`;
case 'star': return `star${S}(() => ${sc(s.step)}, ${ks})`;
case 'opt': return `opt${S}(() => ${s.steps.map(sc).join(' && ')}, ${ks})`;
case 'sep': return `sepBy${S}(() => ${sc(s.elem)}, ${lidOf(ids, s.delim)}, ${ks})`;
case 'altlit': return `altLit${S}([${s.opts.map((o) => `[${lidOf(ids, o.value)}, ${J(o.ttype)}]`).join(', ')}], ${ks})`;
case 'alt': {
if (s.predictive) return `(() => { ${predAltBody(s.branches, ids, s.firsts, w)} })()`;
const firsts = s.firsts ?? [];
const nAlts = s.branches.length;
const needPeek = s.branches.some((_, i) => isGuardable(firsts[i] ?? null, nAlts));
const peekInit = needPeek ? `const _ft = peek(); ` : '';
const tries = s.branches.map((br, i) => {
const body = w
? `{ const sp = pos; const bk = kids.length; const bs = spans.length; if (${br.length ? br.map(sc).join(' && ') : 'true'}) return true; pos = sp; kids.length = bk; spans.length = bs; }`
: `{ const sp = pos; const bk = kids.length; if (${br.length ? br.map(sc).join(' && ') : 'true'}) return true; pos = sp; kids.length = bk; }`;
const f = firsts[i] ?? null;
if (!isGuardable(f, nAlts)) return body;
return `if (_ft !== null && ${firstCond(f, '_ft', ids)}) ${body}`;
}).join(' ');
return `(() => { ${peekInit}${tries} return false; })()`;
}
case 'not': return w
? `(() => { const sp = pos; const bk = kids.length; const bs = spans.length; const m = ${s.steps.length ? s.steps.map(sc).join(' && ') : 'true'}; pos = sp; kids.length = bk; spans.length = bs; return !m; })()`
: `(() => { const sp = pos; const bk = kids.length; const m = ${s.steps.length ? s.steps.map(sc).join(' && ') : 'true'}; pos = sp; kids.length = bk; return !m; })()`;
case 'seq': return `(${s.steps.length ? s.steps.map(sc).join(' && ') : 'true'})`;
case 'sameLine': return `(() => { const t = peek(); return t !== null && !t.nl; })()`;
case 'suppress': return `(() => { _suppressNext = new Set([${s.connectors.map((c) => lidOf(ids, c)).join(', ')}]); const _r = (${s.steps.length ? s.steps.map(sc).join(' && ') : 'true'}); _suppressNext = null; return _r; })()`;
}
}
function predAltBody(branches: Step[][], ids: LexIdPlan, firsts?: FirstSig[], w = false): string {
const sc = (x: Step) => stepCond(x, ids, w);
// FIRST dispatch still only tries the matching arm; on half-failure restore like non-pred altBody.
const arms = branches.map((br, i) => {
const steps = br.length ? br.map(sc).join(' && ') : 'true';
const body = w
? `{ const sp = pos; const bk = kids.length; const bs = spans.length; if (${steps}) return true; pos = sp; kids.length = bk; spans.length = bs; }`
: `{ const sp = pos; const bk = kids.length; if (${steps}) return true; pos = sp; kids.length = bk; }`;
return `if (${firstCond(firsts![i], 't', ids)}) ${body}`;
}).join(' else ');
return `const t = peek(); if (t === null) return false; ${arms} return false;`;
}
/** Shape A: star(rule|alt(rule…)). Shape B: [opt(rule)]? star(seq(tok, opt(rule))). */
type ReusePlanA = { kind: 'A'; topOneBody: string };
type ReusePlanB = { kind: 'B'; hasHead: boolean; headRule: string | null; loopTok: string; loopRule: string };
type ReusePlan = ReusePlanA | ReusePlanB;
function matchLoopSeq(step: Step): { loopTok: string; loopRule: string } | null {
if (step.t !== 'seq' || step.steps.length !== 2) return null;
const [a, b] = step.steps;
if (a.t !== 'tok') return null;
if (b.t !== 'opt' || b.steps.length !== 1 || b.steps[0].t !== 'rule') return null;
return { loopTok: a.name, loopRule: (b.steps[0] as { t: 'rule'; name: string }).name };
}
function topReusePlan(ir: ParserIR): ReusePlan | null {
const entry = ir.rules.find((r) => r.name === ir.entry);
if (!entry || entry.kind !== 'rd' || entry.alts.length !== 1) return null;
const alt = entry.alts[0];
// Shape A (unchanged): sole step star(rule) or star(alt(rule…))
if (alt.length === 1 && alt[0].t === 'star') {
const step = alt[0].step;
if (step.t === 'rule') return { kind: 'A', topOneBody: ` return parse${step.name}();` };
if (step.t === 'alt') {
for (const br of step.branches) {
if (br.length !== 1 || br[0].t !== 'rule') return null;
}
const tries = step.branches.map((br) => {
const name = (br[0] as { t: 'rule'; name: string }).name;
return ` { const sp = pos; const n = parse${name}(); if (n !== null) return n; pos = sp; }`;
}).join('\n');
return { kind: 'A', topOneBody: `${tries}\n return null;` };
}
const loop = matchLoopSeq(step);
if (loop) return { kind: 'B', hasHead: false, headRule: null, ...loop };
return null;
}
// Shape B with optional head: [opt(rule R), star(seq(tok T, opt(rule R2)))]
if (alt.length === 2 && alt[0].t === 'opt' && alt[1].t === 'star') {
const hs = alt[0].steps;
if (hs.length !== 1 || hs[0].t !== 'rule') return null;
const loop = matchLoopSeq(alt[1].step);
if (!loop) return null;
return { kind: 'B', hasHead: true, headRule: hs[0].name, ...loop };
}
return null;
}
function rdRule(r: RdRule, ids: LexIdPlan): string {
if (r.predictive) {
const arm = (steps: Step[], i: number) => ` ${i === 0 ? 'if' : 'else if'} (${firstCond(r.altFirst[i], 't', ids)}) { const kids: Cst[] = []; if (${steps.map((x) => stepCond(x, ids)).join(' && ')}) return branch(${J(r.cstName)}, kids, save); }`;
return `function parse${r.name}(): Node | null {
const save = pos;
const t = peek(); if (t === null) return null;
${r.alts.map(arm).join(' ')}
pos = save;
return null;
}`;
}
const alt = (steps: Step[], i: number) => {
const body = `{ const kids: Cst[] = []; if (${steps.map((x) => stepCond(x, ids)).join(' && ')}) return branch(${J(r.cstName)}, kids, save); pos = save; }`;
if (!isGuardable(r.altFirst[i], r.alts.length)) return ` ${body}`;
return ` if (_ft !== null && ${firstCond(r.altFirst[i], '_ft', ids)}) ${body}`;
};
const needPeek = r.alts.some((_, i) => isGuardable(r.altFirst[i], r.alts.length));
return `function parse${r.name}(): Node | null {
const save = pos;
${needPeek ? ' const _ft = peek();\n' : ''}${r.alts.map(alt).join('\n')}
return null;
}`;
}
/** Builder-mode RD rule — same control flow as rdRule, returns Frame (span+handles). */
function rdRuleW(r: RdRule, ids: LexIdPlan): string {
if (r.predictive) {
const arm = (steps: Step[], i: number) => ` ${i === 0 ? 'if' : 'else if'} (${firstCond(r.altFirst[i], 't', ids)}) { const kids: any[] = []; const spans: BWSpan[] = []; if (${steps.map((x) => stepCond(x, ids, true)).join(' && ')}) return branchW(${J(r.cstName)}, kids, spans, save); }`;
return `function parse${r.name}W(): Frame | null {
const save = pos;
const t = peek(); if (t === null) return null;
${r.alts.map(arm).join(' ')}
pos = save;
return null;
}`;
}
const alt = (steps: Step[], i: number) => {
const body = `{ const kids: any[] = []; const spans: BWSpan[] = []; if (${steps.map((x) => stepCond(x, ids, true)).join(' && ')}) return branchW(${J(r.cstName)}, kids, spans, save); pos = save; }`;
if (!isGuardable(r.altFirst[i], r.alts.length)) return ` ${body}`;
return ` if (_ft !== null && ${firstCond(r.altFirst[i], '_ft', ids)}) ${body}`;
};
const needPeek = r.alts.some((_, i) => isGuardable(r.altFirst[i], r.alts.length));
return `function parse${r.name}W(): Frame | null {
const save = pos;
${needPeek ? ' const _ft = peek();\n' : ''}${r.alts.map(alt).join('\n')}
return null;
}`;
}
function topOneBodyW(plan: ReusePlanA): string {
return plan.topOneBody.replace(/parse([A-Za-z0-9_]+)\(\)/g, 'parse$1W()');
}
function rdEntryWithReuseW(r: RdRule, plan: ReusePlan, ids: LexIdPlan): string {
if (plan.kind === 'A') {
return `function parseTopOneW(): Frame | null {
${topOneBodyW(plan)}
}
function parse${r.name}W(): Frame | null {
const save = pos;
const kids: any[] = [];
const spans: BWSpan[] = [];
// Engine-side EntryMeta (R2): never mutate consumer handles.
const localE: EntryMeta[] = [];
for (;;) {
const sp = pos;
maxLook = 0;
const n = parseTopOneW();
if (n === null) { pos = sp; break; }
const ext = Math.max(n.tokEnd, maxLook);
localE.push({ tokStart: n.tokStart, tokEnd: n.tokEnd, ext, off: n.off, end: n.end, kidStart: spans.length, kidCount: 1 });
absorbFrame(kids, spans, n);
}
_entries = localE;
_entryHs = kids.slice();
return branchW(${J(r.cstName)}, kids, spans, save);
}`;
}
const headBlock = plan.hasHead && plan.headRule
? ` {
const pair = parseHeadSegW(kids, spans);
if (pair) { segs.push(pair.seg); localE.push(pair.meta); }
}
`
: '';
const headFn = plan.hasHead && plan.headRule
? `function parseHeadSegW(kids: any[], spans: BWSpan[]): { seg: Seg; meta: EntryMeta } | null {
maxLook = 0;
const kidStart = kids.length;
const before = kids.length;
const spanBefore = spans.length;
optW(() => callRuleW(parse${plan.headRule}W, kids, spans), kids, spans);
if (kids.length === before) return null;
const sp0 = spans[spanBefore]!;
const sp1 = spans[spans.length - 1]!;
const tokStart = sp0.tokStart;
const tokEnd = sp1.tokEnd;
const ext = Math.max(tokEnd, maxLook);
const meta: EntryMeta = { tokStart, tokEnd, ext, off: sp0.off, end: sp1.end, kidStart, kidCount: 1 };
return { seg: { kidStart, kidCount: 1, tokStart, tokEnd, ext }, meta };
}
`
: '';
return `${headFn}function parseLoopSegW(kids: any[], spans: BWSpan[]): { seg: Seg; meta: EntryMeta } | null {
const sp = pos;
const kidStart = kids.length;
const spanStart = spans.length;
maxLook = 0;
if (!matchTokW(${kidOf(ids, plan.loopTok)}, ${J(plan.loopTok)}, kids, spans)) { pos = sp; kids.length = kidStart; spans.length = spanStart; return null; }
optW(() => callRuleW(parse${plan.loopRule}W, kids, spans), kids, spans);
const leafSp = spans[spanStart]!;
const hasStmt = spans.length > spanStart + 1;
const tokEnd = hasStmt ? spans[spanStart + 1]!.tokEnd : leafSp.tokEnd;
const end = hasStmt ? spans[spanStart + 1]!.end : leafSp.end;
const ext = Math.max(tokEnd, maxLook);
const kidCount = kids.length - kidStart;
const meta: EntryMeta = { tokStart: leafSp.tokStart, tokEnd, ext, off: leafSp.off, end, kidStart, kidCount };
return { seg: { kidStart, kidCount, tokStart: leafSp.tokStart, tokEnd, ext }, meta };
}
function parse${r.name}W(): Frame | null {
const save = pos;
const kids: any[] = [];
const spans: BWSpan[] = [];
const segs: Seg[] = [];
const localE: EntryMeta[] = [];
${headBlock} for (;;) {
const pair = parseLoopSegW(kids, spans);
if (pair === null) break;
segs.push(pair.seg);
localE.push(pair.meta);
}
_segs = segs;
_entries = localE;
_entryHs = kids.slice();
return branchW(${J(r.cstName)}, kids, spans, save);
}`;
}
/** Entry rule that records per-top-kid EntryMeta (+ Node.ext oracle) via parseTopOne (shape A). */
function rdEntryWithReuseA(r: RdRule, plan: ReusePlanA, _ids: LexIdPlan): string {
return `type EntryMeta = { tokStart: number; tokEnd: number; ext: number; off: number; end: number; kidStart: number; kidCount: number };
let _entries: EntryMeta[] = [];
let _entryHs: any[] = [];
function parseTopOne(): Node | null {
${plan.topOneBody}
}
function parse${r.name}(): Node | null {
const save = pos;
const kids: Cst[] = [];
const localE: EntryMeta[] = [];
for (;;) {
const sp = pos;
maxLook = 0;
const n = parseTopOne();
if (n === null) { pos = sp; break; }
const ext = Math.max(n.tokEnd, maxLook);
n.ext = ext; // CST oracle for validate assert; reuse decisions read _entries
localE.push({ tokStart: n.tokStart, tokEnd: n.tokEnd, ext, off: n.offset, end: n.end, kidStart: kids.length, kidCount: 1 });
kids.push(n);
}
_entries = localE;
_entryHs = kids;
return branch(${J(r.cstName)}, kids, save);
}`;
}
/** Entry rule that builds a segment table for newline-interleaved kids (shape B). */
function rdEntryWithReuseB(r: RdRule, plan: ReusePlanB, ids: LexIdPlan): string {
const headBlock = plan.hasHead && plan.headRule
? ` {
const pair = parseHeadSeg(kids);
if (pair) { segs.push(pair.seg); localE.push(pair.meta); }
}
`
: '';
const headFn = plan.hasHead && plan.headRule
? `function parseHeadSeg(kids: Cst[]): { seg: Seg; meta: EntryMeta } | null {
maxLook = 0;
const kidStart = kids.length;
const before = kids.length;
opt(() => callRule(parse${plan.headRule}, kids), kids);
if (kids.length === before) return null;
const n = kids[before] as Node;
const ext = Math.max(n.tokEnd, maxLook);
const meta: EntryMeta = { tokStart: n.tokStart, tokEnd: n.tokEnd, ext, off: n.offset, end: n.end, kidStart, kidCount: 1 };
return { seg: { kidStart, kidCount: 1, tokStart: n.tokStart, tokEnd: n.tokEnd, ext }, meta };
}
`
: '';
return `type Seg = { kidStart: number; kidCount: number; tokStart: number; tokEnd: number; ext: number };
type EntryMeta = { tokStart: number; tokEnd: number; ext: number; off: number; end: number; kidStart: number; kidCount: number };
let _segs: Seg[] = [];
let _entries: EntryMeta[] = [];
let _entryHs: any[] = [];
${headFn}function parseLoopSeg(kids: Cst[]): { seg: Seg; meta: EntryMeta } | null {
const sp = pos;
const kidStart = kids.length;
maxLook = 0;
if (!matchTok(${kidOf(ids, plan.loopTok)}, ${J(plan.loopTok)}, kids)) { pos = sp; kids.length = kidStart; return null; }
opt(() => callRule(parse${plan.loopRule}, kids), kids);
const leaf = kids[kidStart]!;
const hasStmt = kids.length > kidStart + 1;
const tokEnd = hasStmt ? kids[kidStart + 1]!.tokEnd : leaf.tokEnd;
const end = hasStmt ? kids[kidStart + 1]!.end : leaf.end;
const ext = Math.max(tokEnd, maxLook);
const kidCount = kids.length - kidStart;
const meta: EntryMeta = { tokStart: leaf.tokStart, tokEnd, ext, off: leaf.offset, end, kidStart, kidCount };
return { seg: { kidStart, kidCount, tokStart: leaf.tokStart, tokEnd, ext }, meta };
}
function parse${r.name}(): Node | null {
const save = pos;
const kids: Cst[] = [];
const segs: Seg[] = [];
const localE: EntryMeta[] = [];
${headBlock} for (;;) {
const pair = parseLoopSeg(kids);
if (pair === null) break;
segs.push(pair.seg);
localE.push(pair.meta);
}
_segs = segs;
_entries = localE;
_entryHs = kids;
return branch(${J(r.cstName)}, kids, save);
}`;
}
function rdEntryWithReuse(r: RdRule, plan: ReusePlan, ids: LexIdPlan): string {
return plan.kind === 'A' ? rdEntryWithReuseA(r, plan, ids) : rdEntryWithReuseB(r, plan, ids);
}
function prattRule(r: PrattRule, tpl: TplCfg | null, ids: LexIdPlan): string {
const tplNud = tpl && r.nudToks.includes(tpl.token)
? ` if (t.kid === ${kidOf(ids, '$templateHead')}) { const node = matchTemplate(); return node === null ? null : { rule: ${J(r.cstName)}, children: [node], offset: node.offset, end: node.end, tokStart: node.tokStart, tokEnd: node.tokEnd }; }\n`
: '';
const BIN = `{ ${r.binary.map((b) => `${lidOf(ids, b.op)}: { lbp: ${b.lbp}, rbp: ${b.rbp} }`).join(', ')} }`;
const PRE = `{ ${r.prefix.map((p) => `${lidOf(ids, p.op)}: ${p.rbp}`).join(', ')} }`;
const atom = `new Set([${r.nudToks.map((k) => kidOf(ids, k)).join(', ')}])`;
const bracketNudBody = (b: Bracket) => `{
const save = pos; const kids: Cst[] = [];
if (${b.steps.map((x) => stepCond(x, ids)).join(' && ')}) return branch(${J(r.cstName)}, kids, save);
pos = save; // fall through to the next NUD alternative (e.g. another '${b.first}'-led form)
}`;
const bracketNudSwitch = (() => {
if (r.nudBrackets.length === 0) return '';
const groups = groupByPreserveOrder(r.nudBrackets, (b) => lidOf(ids, b.first));
return ` switch (t.lid) {
${groups.map((g) => ` case ${g.key}:
${g.members.map(({ item: b }) => ` ${bracketNudBody(b)}`).join('\n')}
break;`).join('\n')}
}`;
})();
const ledGuard = (accessTail: boolean, lbp: number | null, sameLine: boolean, nll: string[] | null, lid: number) => {
const parts: string[] = [];
if (accessTail) parts.push('!tailClosed');
if (lbp !== null) parts.push(`${lbp} > minBp`);
if (sameLine) parts.push('!t.nl');
if (nll) parts.push(`!${J(nll)}.includes(headLeafText(left))`);
parts.push(`(_suppressCur === null || !_suppressCur.has(${lid}))`);
return parts.join(' && ');
};
const ledBody = (b: Bracket) => `{
const ledSave = pos; const kids: Cst[] = [left];
if (${b.steps.map((x) => stepCond(x, ids)).join(' && ')}) { left = node(${J(r.cstName)}, kids); continue ledLoop; }
pos = ledSave; break ledLoop;
}`;
const ledSwitch = (() => {
if (r.leds.length === 0) return '';
const groups = groupByPreserveOrder(r.leds, (b) => lidOf(ids, b.first));
return ` switch (t.lid) {
${groups.map((g) => {
const lid = g.key as number;
const arms = g.members.map(({ item: b, index: i }) =>
` if (${ledGuard(r.ledAccessTail[i]!, r.ledLbp[i]!, r.ledSameLine[i]!, r.ledNotLeftLeaf[i]!, lid)}) ${ledBody(b)}`);
return ` case ${lid}:\n${arms.join('\n')}\n break;`;
}).join('\n')}
}`;
})();
const postfixTokSwitch = (() => {
if (r.postfixToks.length === 0) return '';
const groups = groupByPreserveOrder(r.postfixToks, (tok) => kidOf(ids, tok));
const hasTpl = !!(tpl && r.postfixToks.includes(tpl.token));
const tplPart = hasTpl ? `
if (!tailClosed && t.kid === ${kidOf(ids, '$templateHead')}) { const node = matchTemplate(); if (node !== null) { left = { rule: ${J(r.cstName)}, children: [left, node], offset: left.offset, end: node.end, tokStart: left.tokStart, tokEnd: pos }; continue ledLoop; } }` : '';
return ` switch (t.kid) {
${groups.map((g) => ` case ${g.key}:
if (!tailClosed) { const leaf: Leaf = { tokenType: tok_kind(t), offset: t.off, end: t.end, tokStart: pos, tokEnd: pos + 1 }; pos++; left = { rule: ${J(r.cstName)}, children: [left, leaf], offset: left.offset, end: leaf.end, tokStart: left.tokStart, tokEnd: pos }; continue ledLoop; }
break;`).join('\n')}
}${tplPart}`;
})();
const POST = `{ ${r.postfix.map((p) => `${lidOf(ids, p.op)}: ${p.lbp}`).join(', ')} }`;
return `const ${r.name}_BIN: Record<number, { lbp: number; rbp: number }> = ${BIN};
const ${r.name}_PRE: Record<number, number> = ${PRE};
const ${r.name}_POST: Record<number, number> = ${POST};
const ${r.name}_ATOM = ${atom};
function parse${r.name}(): Node | null {
const prev = _suppressCur; _suppressCur = _suppressNext; _suppressNext = null;
const r = ${r.name}_bp(0);
_suppressCur = prev;
return r;
}
function ${r.name}_bp(minBp: number): Node | null {
let left = ${r.name}_nud(minBp);
if (left === null) return null;
if (_capped) return left; // an assignment-level arrow admits no led
let tailClosed = false;
${(r.leds.length > 0 || r.postfixToks.length > 0) ? 'ledLoop: ' : ''}for (;;) {
const t = peek();
if (t === null) break;
${ledSwitch}
${postfixTokSwitch}
const post = ${r.name}_POST[t.lid];
if (!tailClosed && post !== undefined && post > minBp) { const opLeaf: Leaf = { tokenType: '$operator', offset: t.off, end: t.end, tokStart: pos, tokEnd: pos + 1 }; pos++; left = { rule: ${J(r.cstName)}, children: [left, opLeaf], offset: left.offset, end: t.end, tokStart: left.tokStart, tokEnd: pos }; tailClosed = true; continue; }
const info = ${r.name}_BIN[t.lid];
if (info === undefined || info.lbp <= minBp) break;
const ledSave = pos;
const opLeaf: Leaf = { tokenType: '$operator', offset: t.off, end: t.end, tokStart: pos, tokEnd: pos + 1 };
pos++;
const rhs = ${r.name}_bp(info.rbp);
if (rhs === null) { pos = ledSave; break; }
left = { rule: ${J(r.cstName)}, children: [left, opLeaf, rhs], offset: left.offset, end: rhs.end, tokStart: left.tokStart, tokEnd: pos };
}
return left;
}
function ${r.name}_nud(minBp: number): Node | null {
_capped = false;
const t = peek();
if (t === null) return null;
${r.nudCapped.map((c) => ` if (minBp < ${c.capBp}) { const save = pos; const kids: Cst[] = []; if (${c.steps.length ? c.steps.map((x) => stepCond(x, ids)).join(' && ') : 'true'}) { _capped = true; return branch(${J(r.cstName)}, kids, save); } pos = save; }`).join('\n')}
// Below is non-capped: a sub-parse may leave _capped set (e.g. grouping a capped arrow),
// so force it false after — only the capped arms above produce a capped node.
const _r = ((): Node | null => {
${tplNud} if (${r.name}_ATOM.has(t.kid)) { const leaf: Leaf = { tokenType: tok_kind(t), offset: t.off, end: t.end, tokStart: pos, tokEnd: pos + 1 }; pos++; return { rule: ${J(r.cstName)}, children: [leaf], offset: t.off, end: t.end, tokStart: leaf.tokStart, tokEnd: pos }; }
${bracketNudSwitch}
const pbp = ${r.name}_PRE[t.lid];
if (pbp !== undefined) {
const save = pos;
const opLeaf: Leaf = { tokenType: '$operator', offset: t.off, end: t.end, tokStart: pos, tokEnd: pos + 1 };
pos++;
const operand = ${r.name}_bp(pbp);
if (operand === null) { pos = save; return null; }
return { rule: ${J(r.cstName)}, children: [opLeaf, operand], offset: t.off, end: operand.end, tokStart: save, tokEnd: pos };
}
${r.nudSeqs.map((seq) => ` { const save = pos; const kids: Cst[] = []; if (${seq.length ? seq.map((x) => stepCond(x, ids)).join(' && ') : 'true'}) return branch(${J(r.cstName)}, kids, save); pos = save; }`).join('\n')}
return null;
})();
_capped = false;
return _r;
}`;
}
/** Builder-mode Pratt — reuses ${name}_BIN/_PRE/_POST/_ATOM tables from the CST emit. */
function prattRuleW(r: PrattRule, tpl: TplCfg | null, ids: LexIdPlan): string {
const cn = J(r.cstName);
const tplNud = tpl && r.nudToks.includes(tpl.token)
? ` if (t.kid === ${kidOf(ids, '$templateHead')}) { const node = matchTemplateW(); return node === null ? null : wrapUnaryW(${cn}, node); }\n`
: '';
const bracketNudBody = (b: Bracket) => `{
const save = pos; const kids: any[] = []; const spans: BWSpan[] = [];
if (${b.steps.map((x) => stepCond(x, ids, true)).join(' && ')}) return branchW(${cn}, kids, spans, save);
pos = save; // fall through to the next NUD alternative (e.g. another '${b.first}'-led form)
}`;
const bracketNudSwitch = (() => {
if (r.nudBrackets.length === 0) return '';
const groups = groupByPreserveOrder(r.nudBrackets, (b) => lidOf(ids, b.first));
return ` switch (t.lid) {
${groups.map((g) => ` case ${g.key}:
${g.members.map(({ item: b }) => ` ${bracketNudBody(b)}`).join('\n')}
break;`).join('\n')}
}`;
})();
const ledGuard = (accessTail: boolean, lbp: number | null, sameLine: boolean, nll: string[] | null, lid: number) => {
const parts: string[] = [];
if (accessTail) parts.push('!tailClosed');
if (lbp !== null) parts.push(`${lbp} > minBp`);
if (sameLine) parts.push('!t.nl');
if (nll) parts.push(`!${J(nll)}.includes(headLeafTextW(left))`);
parts.push(`(_suppressCur === null || !_suppressCur.has(${lid}))`);
return parts.join(' && ');
};
const ledBody = (b: Bracket) => `{
const ledSave = pos; const kids: any[] = []; const spans: BWSpan[] = [];
absorbFrame(kids, spans, left);
if (${b.steps.map((x) => stepCond(x, ids, true)).join(' && ')}) { left = nodeW(${cn}, kids, spans); continue ledLoop; }
pos = ledSave; break ledLoop;
}`;
const ledSwitch = (() => {
if (r.leds.length === 0) return '';
const groups = groupByPreserveOrder(r.leds, (b) => lidOf(ids, b.first));
return ` switch (t.lid) {
${groups.map((g) => {
const lid = g.key as number;