Repository navigation
Expand file tree
/
Copy pathshape2-eval.ts
More file actions
1263 lines (1220 loc) · 70.8 KB
/
Copy pathshape2-eval.ts
File metadata and controls
1263 lines (1220 loc) · 70.8 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 REFERENCE INTERPRETER of ShapeSpec v2 (src/shape/shape2-schema.ts): (spec, interpreter CST) ->
// value. It is the executable definition printers will be checked against, so it is written to
// be small and obviously correct, not fast: an arm is found by a backtracking match of the CST
// node's children against the grammar's arms in declaration order (greedy repetitions, the
// first arm that consumes every child wins: the parser's own tie-break), and every name comes
// from the one deriver (src/grammar/grammar-names.ts).
//
// defineShape(grammar, spec) type-checks the spec against the grammar and rejects anything
// outside the calculus (ShapeSpecError lists every problem)
// evaluateShape(shape, cst, src) the value of a CST node (a Program, or any node: e.g. a Stmt)
// shapeCoverage(shape) which (rule, arm) pairs the spec maps; what a left-out one does
// dependencies(shape) per (rule, arm): which inherited attributes its value reads
import type { CstChild, CstLeaf, CstNode } from '../interpreter/interpreter.ts';
import type { Grammar, RuleDecl, RuleExpr, TemplateDelimiters } from '../grammar/types.ts';
import { isKeywordLiteral, ZERO_WIDTH_MARKERS } from '../grammar/grammar-utils.ts';
import { nameRule, OP_FORM_CHILDREN, type RuleNames } from '../grammar/grammar-names.ts';
import { COOK } from './shape-cook.ts';
import { COOK_FNS, OPERATORS, nodeKeysOf, type TermTag, type InhAttr, type InhEq, type Scalar, type ShapeSpec, type Span, type Term, type ThreadEq } from './shape2-schema.ts';
// ── Values ──
/** A node value: ONE flat object, its kind and span under the shape's node keys (ShapeSpec.node:
* by default `kind`, `start`, `end`), then its fields in the term's order (an absent one left out). */
export type ShapeNode = { [key: string]: ShapeValue };
export type ShapeValue = ShapeNode | ShapeValue[] | Scalar | { record: Record<string, ShapeValue> };
/** The spec is outside the calculus or not typed against the grammar: every problem, each
* `<where>: <what>` (where = the spec table, the rule.arm, and the path into the term). */
export class ShapeSpecError extends Error {
readonly problems: string[];
constructor(shape: string, grammar: string, problems: string[]) {
super(`shape ${JSON.stringify(shape)} does not fit grammar ${JSON.stringify(grammar)} (${problems.length} problem${problems.length > 1 ? 's' : ''}):\n ${problems.join('\n ')}`);
this.problems = problems;
}
}
/** Evaluation reached an arm the (non-total) spec does not map. */
export class ShapeUnmapped extends Error {
readonly rule: string;
readonly arm: string;
constructor(rule: string, arm: string) { super(`shape: ${rule}.${arm} is not mapped (map it, or see shapeCoverage for every arm left out)`); this.rule = rule; this.arm = arm; }
}
/** `name` is not among `names`: the names, in full when they are few, else the nearest ones. */
export function nearest(names: Iterable<string>, name: string): string {
const all = [...names];
if (all.length === 0) return 'there are none';
if (all.length <= 16) return `${all.length === 1 ? 'the only one is' : 'they are'}: ${all.join(', ')}`;
const near = all.map((n) => [n, editDistance(n.toLowerCase(), name.toLowerCase())] as const).sort((a, b) => a[1] - b[1]).slice(0, 5).map(([n]) => n);
return `nearest: ${near.join(', ')} (of ${all.length})`;
}
function editDistance(a: string, b: string): number {
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
const cur = [i];
for (let j = 1; j <= b.length; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
prev = cur;
}
return prev[b.length];
}
// ── The static view of an arm: its named children ──
export type SlotKind = 'node' | 'leaf' | 'branch';
export type Card = 'one' | 'opt' | 'many';
/** A named child. `quants`: the repetitions / optionals around it inside its scope, outer first.
* `delims`: a template part's opening and closing delimiters (the `{ inside }` span). */
export type Slot = { name: string; kind: SlotKind; rule?: string; node: RuleExpr; quants: RuleExpr[]; branches?: Map<string, ScopeInfo>; delims?: [string, string] };
export type ScopeInfo = { where: string; slots: Map<string, Slot> };
export type ArmInfo = ScopeInfo & { rule: string; arm: string; form?: 'binary' | 'prefix' | 'postfix'; items?: RuleExpr[] };
const ZERO_WIDTH = ZERO_WIDTH_MARKERS;
const isList = (q: RuleExpr): boolean => q.type === 'sep' || (q.type === 'quantifier' && q.kind !== '?');
export const cardOf = (quants: RuleExpr[]): Card => (quants.some(isList) ? 'many' : quants.length ? 'opt' : 'one');
export type GrammarView = {
rules: Map<string, RuleDecl>; tokens: Set<string>; templates: Map<string, TemplateDelimiters>; arms: Map<string, ArmInfo[]>;
names: Map<string, RuleNames>;
/** Each structural alternation's branch scopes, in branch order. */
branchScopes: Map<RuleExpr, ScopeInfo[]>;
/** Each template reference's fixed scope structure (see TemplateView). */
templateViews: Map<RuleExpr, TemplateView>;
expressionRule?: string;
};
/** A TEMPLATE reference (a `template` token) is read as a fixed inline alternation:
* noSubstitution quasi (the whole token: a leaf)
* substitution head (a leaf), then one iteration per hole: expr (the hole's rule node:
* the reference's `hole` rule, else the grammar's expression rule) and part,
* an alternation `middle` / `tail` holding the leaf `literal`
* The nodes below are this view's own (no grammar node holds them); every part leaf carries its
* delimiters from the token's template config, for the `{ inside }` span. A hole is a fresh
* expression context: its node takes every inherited attribute's DEFAULT. */
type TemplateView = {
noSub: ScopeInfo; sub: ScopeInfo; middle: ScopeInfo; tail: ScopeInfo;
quasi: RuleExpr; head: RuleExpr; iter: RuleExpr; expr: RuleExpr; part: RuleExpr; middleLit: RuleExpr; tailLit: RuleExpr;
};
function templateView(where: string, token: TemplateDelimiters, holeRule: string): TemplateView {
const leaf = (value: string): RuleExpr => ({ type: 'literal', value });
const quasi = leaf('$quasi'), head = leaf('$templateHead'), middleLit = leaf('$templateMiddle'), tailLit = leaf('$templateTail');
const expr: RuleExpr = { type: 'ref', name: holeRule };
const part: RuleExpr = { type: 'alt', items: [middleLit, tailLit] };
const iter: RuleExpr = { type: 'quantifier', kind: '+', body: { type: 'seq', items: [expr, part] } } as RuleExpr;
const slot = (name: string, node: RuleExpr, quants: RuleExpr[], delims: [string, string]): [string, Slot] => [name, { name, kind: 'leaf', node, quants, delims }];
const middle: ScopeInfo = { where: `${where}.substitution part.middle`, slots: new Map([slot('literal', middleLit, [], [token.interpClose, token.interpOpen])]) };
const tail: ScopeInfo = { where: `${where}.substitution part.tail`, slots: new Map([slot('literal', tailLit, [], [token.interpClose, token.open])]) };
const noSub: ScopeInfo = { where: `${where}.noSubstitution`, slots: new Map([slot('quasi', quasi, [], [token.open, token.open])]) };
const sub: ScopeInfo = {
where: `${where}.substitution`, slots: new Map<string, Slot>([
slot('head', head, [], [token.open, token.interpOpen]),
['expr', { name: 'expr', kind: 'node', rule: holeRule, node: expr, quants: [iter] }],
['part', { name: 'part', kind: 'branch', node: part, quants: [iter], branches: new Map([['middle', middle], ['tail', tail]]) }],
]),
};
return { noSub, sub, middle, tail, quasi, head, iter, expr, part, middleLit, tailLit };
}
function viewOf(grammar: Grammar): GrammarView {
const g: GrammarView = {
rules: new Map(grammar.rules.map((r) => [r.name, r])),
tokens: new Set(grammar.tokens.map((t) => t.name)),
templates: new Map(grammar.tokens.filter((t) => t.template).map((t) => [t.name, t.template!])),
arms: new Map(),
names: new Map(),
branchScopes: new Map(),
templateViews: new Map(),
expressionRule: grammar.expressionRule,
};
for (const r of grammar.rules) g.arms.set(r.name, armsOf(g, r));
return g;
}
function armsOf(g: GrammarView, rule: RuleDecl): ArmInfo[] {
const names = nameRule(rule);
g.names.set(rule.name, names);
const alts = rule.body.type === 'alt' ? rule.body.items : [rule.body];
const out: ArmInfo[] = [];
const opMarker = (e: RuleExpr): boolean => e.type === 'op' || e.type === 'prefix' || e.type === 'postfix';
for (const alt of alts) {
const raw = alt.type === 'seq' ? alt.items : [alt];
const items = raw[0]?.type === 'notLeftLeaf' ? raw.slice(1) : raw;
if (items.some(opMarker)) continue;
const arm = names.armOf.get(alt)!.name;
const info: ArmInfo = { rule: rule.name, arm, where: `${rule.name}.${arm}`, slots: new Map(), items };
for (const it of items) walk(g, names, it, [], info);
out.push(info);
}
if (names.ops) {
for (const form of ['binary', 'prefix', 'postfix'] as const) {
const arm = names.ops[form];
const info: ArmInfo = { rule: rule.name, arm, where: `${rule.name}.${arm}`, slots: new Map(), form };
for (const nm of OP_FORM_CHILDREN[form]) {
info.slots.set(nm, nm === 'op'
? { name: nm, kind: 'leaf', node: { type: 'literal', value: '' }, quants: [] }
: { name: nm, kind: 'node', rule: rule.name, node: { type: 'ref', name: rule.name }, quants: [] });
}
out.push(info);
}
}
return out;
}
function walk(g: GrammarView, names: RuleNames, it: RuleExpr, quants: RuleExpr[], scope: ScopeInfo): void {
const add = (kind: SlotKind, rule?: string, branches?: Map<string, ScopeInfo>): void => {
const slot = names.childOf.get(it);
if (!slot) return;
scope.slots.set(slot.name, { name: slot.name, kind, rule, node: it, quants, branches });
};
switch (it.type) {
case 'ref': {
const delims = g.templates.get(it.name);
if (delims) {
const holeRule = it.hole ?? g.expressionRule;
if (!holeRule) throw new Error(`shape2: ${scope.where}: the template ${it.name} has no hole rule (the grammar declares no expression rule)`);
const v = templateView(`${scope.where} ${names.childOf.get(it)?.name ?? it.name}`, delims, holeRule);
g.templateViews.set(it, v);
add('branch', undefined, new Map([['noSubstitution', v.noSub], ['substitution', v.sub]]));
} else if (g.tokens.has(it.name)) add('leaf');
else add('node', it.name);
return;
}
case 'literal': add('leaf'); return;
case 'group': walk(g, names, it.body, quants, scope); return;
case 'seq': for (const s of it.items) walk(g, names, s, quants, scope); return;
case 'quantifier': walk(g, names, it.body, [...quants, it], scope); return;
case 'sep': walk(g, names, it.element, [...quants, it], scope); return;
case 'alt': {
if (it.items.length > 0 && it.items.every((x) => x.type === 'literal')) { add('leaf'); return; }
const branches = new Map<string, ScopeInfo>();
for (const b of it.items) {
const bn = names.armOf.get(b)!.name;
const bs: ScopeInfo = { where: `${scope.where} ${names.childOf.get(it)!.name}.${bn}`, slots: new Map() };
walk(g, names, b, [], bs);
branches.set(bn, bs);
}
g.branchScopes.set(it, [...branches.values()]);
add('branch', undefined, branches);
return;
}
default:
if (!ZERO_WIDTH.has(it.type)) throw new Error(`shape2: unexpected grammar item ${it.type}`);
}
}
// ── Matching a CST node to its arm ──
type Item =
| { k: 'node'; node: CstNode; hole?: true }
| { k: 'leaf'; leaf: CstLeaf }
| { k: 'branch'; name: string; info: ScopeInfo; frame: Frame; start: number; end: number };
/** What one scope (an arm, a branch, one iteration) matched: its captures by grammar node, and
* the iterations of each repetition / optional directly inside it. */
type Frame = { caps: Map<RuleExpr, Item>; iters: Map<RuleExpr, Frame[]> };
const newFrame = (): Frame => ({ caps: new Map(), iters: new Map() });
type Matched = { info: ArmInfo; frame: Frame };
const isLeaf = (c: CstChild | undefined): c is CstLeaf => c !== undefined && 'tokenType' in c;
const spanOfItem = (it: Item): { start: number; end: number } =>
it.k === 'node' ? { start: it.node.offset, end: it.node.end }
: it.k === 'leaf' ? { start: it.leaf.offset, end: it.leaf.end }
: { start: it.start, end: it.end };
/** A template reference's item: the fixed alternation of TemplateView over the token (a leaf: no
* substitution) or the `$template` node the parser builds (head, then hole / middle pairs, then
* the last hole and the tail). */
function templateItem(v: TemplateView, c: CstChild): Item {
const frame = newFrame();
if (isLeaf(c)) {
frame.caps.set(v.quasi, { k: 'leaf', leaf: c });
return { k: 'branch', name: 'noSubstitution', info: v.noSub, frame, start: c.offset, end: c.end };
}
const kids = c.children;
frame.caps.set(v.head, { k: 'leaf', leaf: kids[0] as CstLeaf });
const its: Frame[] = [];
for (let k = 1; k < kids.length; k += 2) {
const it = newFrame();
it.caps.set(v.expr, { k: 'node', node: kids[k] as CstNode, hole: true });
const lit = kids[k + 1] as CstLeaf;
const tail = lit.tokenType === '$templateTail';
const pf = newFrame();
pf.caps.set(tail ? v.tailLit : v.middleLit, { k: 'leaf', leaf: lit });
it.caps.set(v.part, { k: 'branch', name: tail ? 'tail' : 'middle', info: tail ? v.tail : v.middle, frame: pf, start: lit.offset, end: lit.end });
its.push(it);
}
frame.iters.set(v.iter, its);
return { k: 'branch', name: 'substitution', info: v.sub, frame, start: c.offset, end: c.end };
}
function matchArm(g: GrammarView, n: CstNode, src: string): Matched {
const arms = g.arms.get(n.rule);
if (!arms) throw new Error(`shape2: no rule ${n.rule} in the grammar`);
const kids = n.children;
const opAt = kids.findIndex((c) => isLeaf(c) && c.tokenType === '$operator');
if (opAt >= 0) {
const form = kids.length === 3 ? 'binary' : opAt === 0 ? 'prefix' : 'postfix';
const info = arms.find((a) => a.form === form)!;
const frame = newFrame();
OP_FORM_CHILDREN[form].forEach((nm, i) => {
const s = info.slots.get(nm)!;
frame.caps.set(s.node, nm === 'op' ? { k: 'leaf', leaf: kids[i] as CstLeaf } : { k: 'node', node: kids[i] as CstNode });
});
return { info, frame };
}
const names = g.names.get(n.rule)!;
for (const info of arms) {
if (!info.items) continue;
const frame = newFrame();
if (seqM(info.items, 0, 0, frame, (i) => i === kids.length)) return { info, frame };
}
throw new Error(`shape2: no arm of ${n.rule} matches the CST node at ${n.offset}..${n.end}`);
function seqM(items: RuleExpr[], k: number, i: number, f: Frame, done: (i: number) => boolean): boolean {
if (k === items.length) return done(i);
return m(items[k], i, f, (j) => seqM(items, k + 1, j, f, done));
}
function cap(e: RuleExpr, f: Frame, item: Item, i: number, done: (i: number) => boolean): boolean {
const named = names.childOf.has(e);
if (named) f.caps.set(e, item);
if (done(i)) return true;
if (named) f.caps.delete(e);
return false;
}
function iterate(q: RuleExpr, f: Frame, its: Frame[], done: () => boolean): boolean {
f.iters.set(q, its);
if (done()) return true;
f.iters.delete(q);
return false;
}
function m(e: RuleExpr, i: number, f: Frame, done: (i: number) => boolean): boolean {
const c = kids[i];
switch (e.type) {
case 'literal': {
const tt = isKeywordLiteral(e.value) ? '$keyword' : '$punct';
if (!isLeaf(c) || c.tokenType !== tt || src.slice(c.offset, c.end) !== e.value) return false;
return cap(e, f, { k: 'leaf', leaf: c }, i + 1, done);
}
case 'ref': {
if (c === undefined) return false;
if (g.tokens.has(e.name)) {
if (isLeaf(c) ? c.tokenType !== e.name : !(g.templates.has(e.name) && c.rule === '$template')) return false;
const v = g.templateViews.get(e);
return cap(e, f, v ? templateItem(v, c) : { k: 'leaf', leaf: c as CstLeaf }, i + 1, done);
}
if (isLeaf(c) || c.rule !== e.name) return false;
return cap(e, f, { k: 'node', node: c }, i + 1, done);
}
case 'group': return m(e.body, i, f, done);
case 'seq': return seqM(e.items, 0, i, f, done);
case 'alt': {
if (e.items.length > 0 && e.items.every((x) => x.type === 'literal')) {
for (const x of e.items) {
const tt = isKeywordLiteral((x as { value: string }).value) ? '$keyword' : '$punct';
if (isLeaf(c) && c.tokenType === tt && src.slice(c.offset, c.end) === (x as { value: string }).value) {
return cap(e, f, { k: 'leaf', leaf: c }, i + 1, done);
}
}
return false;
}
const tags = names.branches.get(e)!;
for (let b = 0; b < e.items.length; b++) {
const bf = newFrame();
const ok = m(e.items[b], i, bf, (j) => {
const start = j > i ? kids[i].offset : (c?.offset ?? n.end);
const end = j > i ? kids[j - 1].end : start;
return cap(e, f, { k: 'branch', name: tags[b].name, info: g.branchScopes.get(e)![b], frame: bf, start, end }, j, done);
});
if (ok) return true;
}
return false;
}
case 'quantifier': {
const min = e.kind === '+' ? 1 : 0;
const max = e.kind === '?' ? 1 : Infinity;
const its: Frame[] = [];
const loop = (j: number): boolean => {
if (its.length < max) {
const it = newFrame();
const more = m(e.body, j, it, (j2) => {
if (j2 === j) return false; // a zero-width iteration ends the repetition
its.push(it);
if (loop(j2)) return true;
its.pop();
return false;
});
if (more) return true;
}
return its.length >= min && iterate(e, f, [...its], () => done(j));
};
return loop(i);
}
case 'sep': {
// element (delimiter element)* delimiter?, or nothing (the parsers' sep).
const its: Frame[] = [];
const isDelim = (j: number): boolean => {
const d = kids[j];
return isLeaf(d) && d.tokenType === (isKeywordLiteral(e.delimiter) ? '$keyword' : '$punct') && src.slice(d.offset, d.end) === e.delimiter;
};
const element = (j: number): boolean => {
const it = newFrame();
return m(e.element, j, it, (j2) => {
its.push(it);
if (isDelim(j2) && (element(j2 + 1) || iterate(e, f, [...its], () => done(j2 + 1)))) return true;
if (iterate(e, f, [...its], () => done(j2))) return true;
its.pop();
return false;
});
};
return element(i) || iterate(e, f, [], () => done(i));
}
default:
if (ZERO_WIDTH.has(e.type)) return done(i);
throw new Error(`shape2: unexpected grammar item ${e.type}`);
}
}
}
/** A slot's items under a frame: `quants` are the slot's repetitions below that frame. An absent
* optional is `undefined` (a hole inside a repetition) or nothing (when a repetition is inside). */
function collect(f: Frame, quants: RuleExpr[], node: RuleExpr): (Item | undefined)[] {
if (quants.length === 0) return [f.caps.get(node)];
const [q, ...rest] = quants;
const its = f.iters.get(q) ?? [];
if (q.type === 'quantifier' && q.kind === '?' && its.length === 0) return rest.some(isList) ? [] : [undefined];
return its.flatMap((it) => collect(it, rest, node));
}
// ── Loading: the static check ──
/** An inherited equation that reads a leaf to the RIGHT of the child it hands context to (not
* L-attributed): a parser that builds nodes as it goes has built that child before it reads the
* deciding leaf. `reads`: those leaves. */
export type RightDependent = { rule: string; arm: string; child: string; attr: string; reads: string[] };
/** A shape: its spec, checked once against its grammar (`defineShape`). Every consumer (the
* evaluator, coverage, the dependency analysis, and the emitted builders next) reads this, never
* an unchecked spec. */
export type Shape = { spec: ShapeSpec; source: Grammar; grammar: GrammarView; rightDependent: RightDependent[] };
/** A static scope: an arm, a branch, or one iteration (`base`: the repetitions consumed to reach
* it), with the variables bound around it. */
type SScope = { info: ScopeInfo; base: RuleExpr[]; outer?: SScope; vars: Set<string>; nodeVars?: Set<string> };
const startsWith = (a: RuleExpr[], p: RuleExpr[]): boolean => p.every((q, i) => a[i] === q);
function resolveStatic(s: SScope, name: string): { slot: Slot; card: Card; scope: SScope } | undefined {
const slot = s.info.slots.get(name);
if (slot && startsWith(slot.quants, s.base)) return { slot, card: cardOf(slot.quants.slice(s.base.length)), scope: s };
return s.outer ? resolveStatic(s.outer, name) : undefined;
}
/** The child names a term in scope `s` can read: its own, then the enclosing scopes'. */
function visibleNames(s: SScope): string[] {
const out: string[] = [];
for (let x: SScope | undefined = s; x; x = x.outer) for (const [n, sl] of x.info.slots) if (startsWith(sl.quants, x.base) && !out.includes(n)) out.push(n);
return out;
}
const hasVar = (s: SScope, name: string): boolean => s.vars.has(name) || (s.outer ? hasVar(s.outer, name) : false);
/** Whether `name` is bound (innermost binding first) to a nodes attribute. */
const hasNodesVar = (s: SScope, name: string): boolean => s.vars.has(name) ? (s.nodeVars?.has(name) ?? false) : (s.outer ? hasNodesVar(s.outer, name) : false);
type Ty = 'string' | 'number' | 'bool' | 'null' | 'node' | 'list' | 'nodes' | 'record' | 'any';
/** Check `spec` against `grammar` and return the shape. The grammar's TYPE carries its rule names
* (`Grammar<R>` from defineGrammar), so a rule key that is not one is a TypeScript error; every
* other name (arm, child, attribute, field) and every term is checked here, and every problem is
* reported at once (ShapeSpecError). An arm the spec leaves out is UNMAPPED: evaluating it throws
* ShapeUnmapped (it is never passed through implicitly: a pass-through is written `child(x)`);
* with `total: true` a left-out arm of a mapped rule is a load error instead. */
export function defineShape<const R extends string>(grammar: Grammar & { rules: readonly { name: R }[] }, spec: ShapeSpec<NoInfer<R>>): Shape;
export function defineShape(grammar: Grammar, spec: ShapeSpec): Shape {
const keys = nodeKeysOf(spec);
const nodeKeyNames = [keys.kind, keys.start, keys.end];
const g = viewOf(grammar);
const problems: string[] = [];
const err = (where: string, msg: string): void => { problems.push(`${where}: ${msg}`); };
const syns = spec.synthesized ?? {};
const inhs = spec.inherited ?? {};
const armIn = (rule: string, arm: string): ArmInfo | undefined => g.arms.get(rule)?.find((a) => a.arm === arm);
const known = new Set(Object.keys(OPERATORS));
const rightDependent: RightDependent[] = [];
// The RECORD-VALUED rules (see `get` in shape2-schema.ts): rule -> its field names.
const recordRules = new Map<string, Set<string>>();
for (const [rule, arms] of Object.entries(spec.rules ?? {})) {
if (arms === null || typeof arms !== 'object') continue;
const terms = Object.entries(arms as Record<string, Term>);
const recs = terms.filter(([, t]) => t?.t === 'record');
if (recs.length === 0) continue;
if (recs.length < terms.length) { err(`rules ${rule}`, `a record-valued rule maps every arm to a record (${terms.filter(([, t]) => t?.t !== 'record').map(([a]) => a).join(', ')} ${terms.length - recs.length > 1 ? 'are' : 'is'} not)`); continue; }
const fieldsOf = (t: Term): string => Object.keys((t as { fields: object }).fields ?? {}).sort().join(', ');
const want = fieldsOf(recs[0][1]);
for (const [a, t] of recs) if (fieldsOf(t) !== want) err(`rules ${rule}.${a}`, `a record-valued rule's arms all have the same fields (${recs[0][0]}: ${want}; ${a}: ${fieldsOf(t)}); write \`absent\` for a field an arm has no value for`);
recordRules.set(rule, new Set(Object.keys((recs[0][1] as { fields: object }).fields ?? {})));
}
// Every rule / arm key must exist; under `total` every arm of a mapped rule must be mapped.
const eachArmKey = (where: string, table: Record<string, Record<string, unknown>>, visit: (a: ArmInfo, v: unknown, w: string) => void): void => {
for (const [rule, arms] of Object.entries(table)) {
if (!g.arms.has(rule)) { err(`${where} ${rule}`, `the grammar has no rule ${rule} (${nearest(g.arms.keys(), rule)})`); continue; }
if (arms === null || typeof arms !== 'object') { err(`${where} ${rule}`, 'must map arm names to terms'); continue; }
for (const [arm, v] of Object.entries(arms)) {
const a = armIn(rule, arm);
if (!a) { err(`${where} ${rule}.${arm}`, `${rule} has no arm ${arm} (its arms: ${nearest(g.arms.get(rule)!.map((x) => x.arm), arm)})`); continue; }
visit(a, v, `${where} ${rule}.${arm}`);
}
}
};
eachArmKey('rules', spec.rules, (a, v, w) => term(v, { info: a, base: [], vars: new Set() }, w, 'value', a));
if (spec.total) {
for (const rule of Object.keys(spec.rules)) for (const a of g.arms.get(rule) ?? []) {
if (!(a.arm in spec.rules[rule])) err(`rules ${rule}.${a.arm}`, 'not mapped (the spec is total)');
}
}
for (const [attr, d] of Object.entries(syns)) {
eachArmKey(`synthesized ${attr}`, d.rules, (a, v, w) => {
const ty = term(v, { info: a, base: [], vars: new Set() }, w, 'syn', a);
if (!scalarOk(ty, d.type)) err(w, `a ${d.type} attribute's equation has type ${ty}`);
});
}
for (const [attr, d] of Object.entries(inhs)) {
if (d.type === 'nodes') { nodesAttr(attr, d); continue; }
eachArmKey(`inherited ${attr}`, d.rules, (a, v, w) => {
if (v === null || typeof v !== 'object') { err(w, 'must map child names to equations'); return; }
const eqs = Object.entries(v as Record<string, InhEq>);
if (eqs.length > 1 && eqs.some(([, e]) => e?.t === 'thread')) err(w, `an arm threading ${attr} has no other equation for it (its elements take the threaded state)`);
for (const [kid, eq] of eqs) {
if (eq?.t === 'thread') { threadEq(a, kid, eq, d, `${w}.${kid}`); continue; }
const r = findSlotAnywhere(a, kid);
if (!r) err(`${w}.${kid}`, `${a.where} has no child ${kid} (its children: ${nearest(slotOrder(a).keys(), kid)})`);
else if (r.kind !== 'node') err(`${w}.${kid}`, `the child ${kid} is a ${r.kind}; only a rule node has inherited attributes`);
const e = eq as Term;
if (e?.t === 'const') { if (!scalarOk(constTy(e.value), d.type)) err(`${w}.${kid}`, `a ${d.type} attribute's equation is ${JSON.stringify(e.value)}`); }
else if (e?.t === 'inh') { if (!(e.attr in inhs)) err(`${w}.${kid}`, `no inherited attribute ${e.attr}`); else if (inhs[e.attr].type !== d.type) err(`${w}.${kid}`, `copies ${e.attr} (${inhs[e.attr].type}) into a ${d.type} attribute`); }
else {
// A scalar over the parent arm's own LEAVES and its inherited attributes (INH_EQ_OPS).
const reads = new Set<string>();
const ty = term(e, { info: a, base: [], vars: new Set() }, `${w}.${kid}`, 'inheq', a, reads);
if (!scalarOk(ty, d.type)) err(`${w}.${kid}`, `a ${d.type} attribute's equation has type ${ty}`);
if (r) {
const order = slotOrder(a);
const right = [...reads].filter((nm) => (order.get(nm) ?? -1) > (order.get(kid) ?? Infinity)).sort();
if (right.length) rightDependent.push({ rule: a.rule, arm: a.arm, child: kid, attr, reads: right });
}
}
}
});
if (!scalarOk(constTy(d.default), d.type)) err(`inherited ${attr}`, `default ${JSON.stringify(d.default)} is not a ${d.type}`);
}
// A scalar attribute's `inh` copy or thread init of a nodes attribute fails the type check above
// (`copies modifiers (nodes) into a bool attribute`).
if (problems.length) throw new ShapeSpecError(spec.name, grammar.name, problems);
return { spec, source: grammar, grammar: g, rightDependent };
/** A node-valued attribute (NodesAttr): every equation is a list built from children strictly
* to the LEFT of the child it feeds (so L-attributed by construction: never right-dependent). */
function nodesAttr(attr: string, d: InhAttr): void {
if ('default' in d && !(Array.isArray(d.default) && d.default.length === 0)) err(`inherited ${attr}`, `a nodes attribute's default is the empty list (it has no other), not ${JSON.stringify(d.default)}`);
eachArmKey(`inherited ${attr}`, d.rules, (a, v, w) => {
if (v === null || typeof v !== 'object') { err(w, 'must map child names to equations'); return; }
const order = slotRanges(a);
for (const [kid, eq] of Object.entries(v as Record<string, InhEq>)) {
const at = `${w}.${kid}`;
if (eq?.t === 'thread') { err(at, `a nodes attribute is not threaded (its equation is a list built from the children left of ${kid})`); continue; }
const r = findSlotAnywhere(a, kid);
if (!r) { err(at, `${a.where} has no child ${kid} (its children: ${nearest(slotOrder(a).keys(), kid)})`); continue; }
if (r.kind !== 'node') { err(at, `the child ${kid} is a ${r.kind}; only a rule node has inherited attributes`); continue; }
const reads = new Set<Slot>();
const ty = term(eq, { info: a, base: [], vars: new Set() }, at, 'nodeseq', a, undefined, reads);
if (ty !== 'list' && ty !== 'any') err(at, `a nodes attribute's equation is a list (of the nodes it hands ${kid}), not a ${ty}`);
const fed = order.get(r)!;
for (const s of reads) {
const o = order.get(s);
if (o && o.last >= fed.first) err(at, `reads ${s.name}, which is not to the LEFT of ${kid}: a nodes attribute is built from what the parser has consumed before it calls ${kid} (L-attributed by construction)`);
}
}
});
}
/** A threaded equation: on a repeated child of the arm's own scope; `init` as any inherited
* equation; `next` a scalar of the attribute's type over the accumulator and the element. */
function threadEq(a: ArmInfo, kid: string, eq: ThreadEq, d: InhAttr, w: string): void {
const slot = a.slots.get(kid);
const at = slot ? slot.quants.map(isList).lastIndexOf(true) : -1;
if (!slot) { err(w, `thread: ${a.where} has no child ${kid} of its own (a thread runs over a repetition of the arm itself; its children: ${nearest(a.slots.keys(), kid)})`); return; }
if (at < 0) { err(w, `thread: ${kid} is not repeated; a thread runs over the elements of a repetition`); return; }
if (slot.kind !== 'node' && slot.kind !== 'branch') err(w, `thread: ${kid} is a ${slot.kind}; the elements must hold rule nodes`);
const init = eq.init as Term;
if (init?.t === 'const') { if (!scalarOk(constTy(init.value), d.type)) err(`${w} init`, `a ${d.type} attribute's initial state is ${JSON.stringify(init.value)}`); }
else if (init?.t === 'inh') { if (!(init.attr in inhs)) err(`${w} init`, `no inherited attribute ${init.attr}`); else if (inhs[init.attr].type !== d.type) err(`${w} init`, `copies ${init.attr} (${inhs[init.attr].type}) into a ${d.type} attribute`); }
else err(`${w} init`, 'a thread\'s initial state is a constant or `inh` of the parent\'s attribute');
if (typeof eq.acc !== 'string') { err(w, 'thread: acc is a variable name'); return; }
const ty = term(eq.next, { info: a, base: slot.quants.slice(0, at + 1), vars: new Set([eq.acc]) }, `${w} next`, 'thread', a);
if (!scalarOk(ty, d.type)) err(`${w} next`, `a ${d.type} attribute's next state has type ${ty}`);
}
function findSlotAnywhere(s: ScopeInfo, name: string): Slot | undefined {
const own = s.slots.get(name);
if (own) return own;
for (const sl of s.slots.values()) for (const b of sl.branches?.values() ?? []) {
const r = findSlotAnywhere(b, name);
if (r) return r;
}
return undefined;
}
/** Check one term in a scope; returns its type. `ctx`: a value term, or a synthesized
* attribute's equation (scalars over the subtree only). */
/** `slotReads`: in a nodes equation, every slot the term reads (children, leaves, spans,
* repetitions). `allowNodes`: this position may hold a nodes-typed term (a `spread` item, a
* `let` value); anywhere else one is a load error (a nodes attribute is placed, never read). */
function term(raw: unknown, s: SScope, w: string, ctx: 'value' | 'syn' | 'thread' | 'inheq' | 'nodeseq', arm: ArmInfo, reads?: Set<string>, slotReads?: Set<Slot>, allowNodes = false): Ty {
const ty = term1(raw, s, w, ctx, arm, reads, slotReads);
if (ty === 'nodes' && !allowNodes) err(w, 'a nodes attribute (or a variable bound to one) is placed only: as a `spread` item of a list, a span endpoint, or under `present`; it is never read as a value');
return ty;
}
function term1(raw: unknown, s: SScope, w: string, ctx: 'value' | 'syn' | 'thread' | 'inheq' | 'nodeseq', arm: ArmInfo, reads?: Set<string>, slotReads?: Set<Slot>): Ty {
if (typeof raw === 'function') { err(w, 'a function is not a term: the calculus has no escape to code (v2 has no `custom`)'); return 'any'; }
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) { err(w, `${JSON.stringify(raw)} is not a term`); return 'any'; }
const e = raw as Term;
if (!known.has(e.t)) { err(w, `\`${String((e as { t: unknown }).t)}\` is not an operator of the calculus (${[...known].join(', ')})`); return 'any'; }
if (ctx === 'nodeseq' && NODES_EQ_EXCLUDED.has(e.t)) { err(w, `\`${e.t}\` cannot appear in a nodes attribute's equation (a list of nodes built from the children left of the child it feeds)`); return 'any'; }
if (ctx === 'syn' && !OPERATORS[e.t].synAttr) { err(w, `\`${e.t}\` cannot appear in a synthesized attribute's equation (scalars over the subtree only)`); return 'any'; }
if (ctx === 'thread' && !OPERATORS[e.t].synAttr && e.t !== 'var') { err(w, `\`${e.t}\` cannot appear in a thread's next state (a scalar over the state and the element's own children only)`); return 'any'; }
if (ctx === 'inheq' && !INH_EQ_OPS.has(e.t)) { err(w, `\`${e.t}\` cannot appear in an inherited equation (a scalar over the parent arm's own leaves and its inherited attributes: ${[...INH_EQ_OPS].join(', ')})`); return 'any'; }
if (ctx === 'inheq' && (e.t === 'text' || e.t === 'cook' || e.t === 'present' || e.t === 'armOf' || e.t === 'branch')) {
const nm = (e as { name?: string }).name;
const r = nm === undefined ? undefined : resolveStatic(s, nm);
if (nm === undefined) err(w, `${e.t} of the whole arm reads its subtrees; an inherited equation reads named leaves only`);
else if (r) {
const leafy = r.slot.kind === 'leaf' || (r.slot.kind === 'branch' && (e.t === 'armOf' || e.t === 'branch') && leavesOnly(r.slot));
if (!leafy) err(w, `${e.t}(${nm}): ${nm} is a ${r.slot.kind}${r.slot.kind === 'branch' ? ' holding a rule node' : ''}; an inherited equation reads the parent's own leaves only (never into a sibling subtree)`);
if (r.scope.info === arm) reads?.add(nm);
}
}
const sub = (x: unknown, at: string, sc: SScope = s, allowNodes = false): Ty => term(x, sc, `${w} ${at}`, ctx, arm, reads, slotReads, allowNodes);
const need = (x: unknown, at: string, want: Ty): void => {
const ty = sub(x, at);
if (ty !== want && ty !== 'any') err(`${w} ${at}`, `must be a ${want}, is a ${ty}`);
};
const slotOf = (name: unknown, op: string): { slot: Slot; card: Card; scope: SScope } | undefined => {
if (typeof name !== 'string') { err(w, `${op}: a child name is a string`); return undefined; }
const r = resolveStatic(s, name);
if (!r && ctx === 'thread' && findSlotAnywhere(arm, name)) err(w, `${op}(${name}): ${name} is not in the element: a thread's next state reads only the element's own children (no other sibling)`);
else if (!r) err(w, `${op}(${name}): ${s.info.where} has no child ${name} (its children: ${nearest(visibleNames(s), name)})`);
if (r) slotReads?.add(r.slot);
return r;
};
switch (e.t) {
case 'const': return constTy(e.value);
case 'absent': return 'any';
case 'child': {
const r = slotOf(e.name, 'child');
if (!r) return 'any';
if (r.slot.kind === 'leaf') err(w, `child(${e.name}): ${e.name} is a leaf, which has no value of its own: use text / cook, or build a node with its span`);
if (r.slot.kind === 'branch') err(w, `child(${e.name}): ${e.name} is an inline alternation: use branch(${e.name}, {...})`);
if (r.slot.rule && recordRules.has(r.slot.rule)) err(w, `child(${e.name}): ${r.slot.rule} is record-valued (an interface, not a node): read its fields with get(${e.name}, field)`);
return r.card === 'many' ? 'list' : 'any';
}
case 'get': {
const r = slotOf(e.name, 'get');
if (!r) return 'any';
if (r.slot.kind !== 'node') { err(w, `get(${e.name}, ${e.field}): ${e.name} is a ${r.slot.kind}; only a child of a record-valued rule is projectable`); return 'any'; }
if (r.card === 'many') err(w, `get(${e.name}, ${e.field}): ${e.name} is a list`);
const fields = recordRules.get(r.slot.rule!);
if (!fields) err(w, `get(${e.name}, ${e.field}): ${r.slot.rule} is not record-valued; a node's fields are not projectable`);
else if (!fields.has(e.field)) err(w, `get(${e.name}, ${e.field}): ${r.slot.rule} has no field ${e.field} (its fields: ${[...fields].join(', ')})`);
return 'any';
}
case 'text': {
if (e.name === undefined) return 'string';
const r = slotOf(e.name, 'text');
if (r && r.card === 'many') err(w, `text(${e.name}): ${e.name} is a list; text takes one child`);
return 'string';
}
case 'cook': {
if (!(COOK_FNS as readonly string[]).includes(e.fn)) err(w, `cook: ${JSON.stringify(e.fn)} is not a cooking function of the calculus (${COOK_FNS.join(', ')})`);
const r = slotOf(e.name, 'cook');
if (r && r.slot.kind !== 'leaf') err(w, `cook(${e.fn}, ${e.name}): ${e.name} is a ${r.slot.kind}; cooking reads one leaf`);
if (r && r.card === 'many') err(w, `cook(${e.fn}, ${e.name}): ${e.name} is a list; cooking reads one leaf`);
return e.fn === 'numberValue' || e.fn === 'tsNumericLiteralFlags' || e.fn === 'tsTemplateFlags' ? 'number' : e.fn === 'hasExtendedUnicodeEscape' ? 'bool' : e.fn === 'templateCooked' ? 'any' : 'string';
}
case 'present': {
// `present(v)` of a variable bound to a nodes attribute: whether the list is non-empty.
if (typeof e.name === 'string' && hasVar(s, e.name)) {
if (!hasNodesVar(s, e.name)) err(w, `present(${e.name}): ${e.name} is a variable not bound to a nodes attribute; present tests a child, or whether a nodes variable is non-empty`);
return 'bool';
}
const r = slotOf(e.name, 'present');
if (r && r.card === 'one') err(w, `present(${e.name}): ${e.name} is a required child (always present)`);
return 'bool';
}
case 'armOf': {
const r = slotOf(e.name, 'armOf');
if (r && r.slot.kind !== 'node' && r.slot.kind !== 'branch') err(w, `armOf(${e.name}): ${e.name} is a ${r.slot.kind}; only a rule node or an inline alternation has an arm`);
if (r && r.card === 'many') err(w, `armOf(${e.name}): ${e.name} is a list`);
return 'string';
}
case 'syn': {
const d = syns[e.attr];
if (!d) { err(w, `syn: no synthesized attribute ${e.attr} (the spec's: ${nearest(Object.keys(syns), e.attr)})`); return 'any'; }
if (e.name === undefined) {
if (ctx === 'syn') err(w, `syn(${e.attr}) of the node itself inside an equation is a cycle`);
if (ctx === 'thread') err(w, `syn(${e.attr}) of the parent inside a thread's next state: the next state reads the element's own children only`);
return d.type === 'bool' ? 'bool' : d.type;
}
const r = slotOf(e.name, 'syn');
if (r && r.slot.kind !== 'node') err(w, `syn(${e.attr}, ${e.name}): ${e.name} is a ${r.slot.kind}; only a rule node has attributes`);
if (r && r.card === 'many') err(w, `syn(${e.attr}, ${e.name}): ${e.name} is a list`);
return d.type === 'bool' ? 'bool' : d.type;
}
case 'inh': {
const d = inhs[e.attr];
if (!d) { err(w, `inh: no inherited attribute ${e.attr} (the spec's: ${nearest(Object.keys(inhs), e.attr)})`); return 'any'; }
return d.type;
}
case 'node': {
need(e.type, 'type', 'string');
if (e.fields === null || typeof e.fields !== 'object') err(w, 'node: fields is a record of terms');
else for (const [k, x] of Object.entries(e.fields)) {
if (nodeKeyNames.includes(k)) err(`${w}.${k}`, `node: the field ${k} is one of the node keys (${nodeKeyNames.join(', ')}; ShapeSpec.node)`);
sub(x, `.${k}`);
}
if (e.span !== undefined) span(e.span, s, w, slotReads);
return 'node';
}
case 'record':
for (const [k, x] of Object.entries(e.fields ?? {})) sub(x, `.${k}`);
return 'record';
case 'list':
(e.items ?? []).forEach((x, i) => {
if (x !== null && typeof x === 'object' && 'spread' in x) {
const ty = sub(x.spread, `[${i}]...`, s, true);
if (ty !== 'list' && ty !== 'nodes' && ty !== 'any') err(`${w} [${i}]`, `spread of a ${ty}; spread takes a list`);
} else sub(x, `[${i}]`);
});
return 'list';
case 'dropLastIf': {
need(e.cond, 'cond', 'bool');
const ty = sub(e.list, 'list');
if (ty !== 'list') err(`${w} list`, `dropLastIf takes a list (a list, map or repeated child), not a ${ty}`);
return 'list';
}
case 'match': {
need(e.on, 'on', 'string');
const tys = Object.entries(e.cases ?? {}).map(([k, x]) => sub(x, `case ${JSON.stringify(k)}`));
if (e.else !== undefined) tys.push(sub(e.else, 'else'));
return join(tys);
}
case 'if': need(e.cond, 'cond', 'bool'); return join([sub(e.then, 'then'), sub(e.else, 'else')]);
case 'and': case 'or': (e.args ?? []).forEach((x, i) => need(x, `${e.t}[${i}]`, 'bool')); return 'bool';
case 'not': need(e.arg, 'not', 'bool'); return 'bool';
case 'orElse': return join([sub(e.of, 'of'), sub(e.else, 'else')]);
case 'branch': {
const r = slotOf(e.name, 'branch');
if (!r) return 'any';
if (r.slot.kind !== 'branch') { err(w, `branch(${e.name}): ${e.name} is a ${r.slot.kind}, not an inline alternation`); return 'any'; }
if (r.card === 'many') err(w, `branch(${e.name}): ${e.name} is a list: map over it`);
const tys: Ty[] = [];
for (const [bn, x] of Object.entries(e.cases ?? {})) {
const info = r.slot.branches!.get(bn);
if (!info) { err(w, `branch(${e.name}): no branch ${bn} (its branches: ${nearest(r.slot.branches!.keys(), bn)})`); continue; }
tys.push(sub(x, `case ${bn}`, { info, base: [], outer: s, vars: new Set() }));
}
if (spec.total) for (const bn of r.slot.branches!.keys()) if (!(bn in (e.cases ?? {}))) err(w, `branch(${e.name}): branch ${bn} not mapped (the spec is total)`);
return join(tys);
}
case 'map': case 'fold': {
const r = slotOf(e.over, e.t);
if (!r) return 'any';
const inner = r.slot.quants.slice(r.scope.base.length);
const at = inner.map(isList).lastIndexOf(true);
if (at < 0) { err(w, `${e.t}(${e.over}): ${e.over} is not repeated`); return 'any'; }
const it: SScope = { info: r.scope.info, base: [...r.scope.base, ...inner.slice(0, at + 1)], outer: s, vars: new Set() };
if (e.t === 'map') { sub(e.body, 'body', it); return 'list'; }
sub(e.init, 'init');
it.vars.add(e.acc);
sub(e.body, 'body', it);
return 'any';
}
case 'let': {
const vt = sub(e.value, 'value', s, true);
const nodeVars = new Set([...(s.nodeVars ?? [])].filter((x) => x !== e.name));
if (vt === 'nodes') nodeVars.add(e.name);
return sub(e.body, 'body', { info: s.info, base: s.base, outer: s.outer, vars: new Set([...s.vars, e.name]), nodeVars });
}
case 'var':
if (!hasVar(s, e.name)) err(w, `var(${e.name}) is not bound here`);
return hasNodesVar(s, e.name) ? 'nodes' : 'any';
}
}
function span(sp: Span, s: SScope, w: string, slotReads?: Set<Slot>): void {
if (sp !== null && typeof sp === 'object' && 'inside' in sp) {
const nm = sp.inside;
if (typeof nm !== 'string') { err(w, 'span.inside is a child name'); return; }
const r = resolveStatic(s, nm);
if (r) slotReads?.add(r.slot);
if (!r) err(w, `span.inside: ${s.info.where} has no child ${nm} (its children: ${nearest(visibleNames(s), nm)})`);
else if (!r.slot.delims) err(w, `span.inside: ${nm} is not a delimited template part (a template's quasi / head / literal)`);
else if (r.card !== 'one') err(w, `span.inside: ${nm} is ${r.card === 'opt' ? 'optional' : 'a list'}`);
return;
}
if (sp !== null && typeof sp === 'object' && 'after' in sp) {
const nm = sp.after;
if (typeof nm !== 'string') { err(w, 'span.after is a child or variable name'); return; }
if (hasVar(s, nm)) return;
const r = resolveStatic(s, nm);
if (r) slotReads?.add(r.slot);
if (!r) err(w, `span.after: ${s.info.where} has no child or variable ${nm} (its children: ${nearest(visibleNames(s), nm)})`);
else if (r.card !== 'one') err(w, `span.after: ${nm} is ${r.card === 'opt' ? 'optional' : 'a list'}, so it can be absent: a zero-width node sits after a token that is always there`);
return;
}
for (const k of ['from', 'to'] as const) {
const nm = sp?.[k];
if (typeof nm !== 'string') { err(w, `span.${k} is a child or variable name`); continue; }
if (hasVar(s, nm)) continue;
const r = resolveStatic(s, nm);
if (r) slotReads?.add(r.slot);
else err(w, `span.${k}: ${s.info.where} has no child or variable ${nm} (its children: ${nearest(visibleNames(s), nm)})`);
}
}
}
/** The operators an inherited equation may use beyond a constant / copy: a scalar over the
* parent arm's own LEAF children (text / cook / present, armOf / branch of an alternation of
* leaves) and the parent's inherited attributes. Never `syn` or anything that reads into a
* sibling subtree: at worst a LEAF to the right of the child decides its context. */
const INH_EQ_OPS = new Set<TermTag>(['const', 'inh', 'text', 'cook', 'present', 'armOf', 'branch', 'match', 'if', 'and', 'or', 'not', 'orElse']);
/** Whether every slot of a branch slot's scopes, recursively, is a leaf. */
function leavesOnly(slot: Slot): boolean {
return [...slot.branches!.values()].every((b) => [...b.slots.values()].every((x) => x.kind === 'leaf' || (x.kind === 'branch' && leavesOnly(x))));
}
/** The order of an arm's named children as the CST holds them (a branch before the children of
* its branches): the left-to-right order an inherited equation is classified by. */
function slotOrder(a: ScopeInfo): Map<string, number> {
const out = new Map<string, number>();
const visit = (sc: ScopeInfo): void => {
for (const sl of sc.slots.values()) {
if (!out.has(sl.name)) out.set(sl.name, out.size);
for (const b of sl.branches?.values() ?? []) visit(b);
}
};
visit(a);
return out;
}
/** Each slot's place in the CST order of an arm (`slotOrder`'s walk, by slot): `first` is its
* own index, `last` the last index of the slots inside it (a branch's children). A read of slot
* R is to the LEFT of slot K when `R.last < K.first`; a branch that holds K is not. */
function slotRanges(a: ScopeInfo): Map<Slot, { first: number; last: number }> {
const out = new Map<Slot, { first: number; last: number }>();
let n = 0;
const visit = (sc: ScopeInfo): void => {
for (const sl of sc.slots.values()) {
const r = { first: n++, last: 0 };
out.set(sl, r);
for (const b of sl.branches?.values() ?? []) visit(b);
r.last = n - 1;
}
};
visit(a);
return out;
}
/** The operators a nodes attribute's equation may not use: it builds a list of nodes from the
* parent arm's children (left of the fed child), its leaves and its inherited attributes. */
const NODES_EQ_EXCLUDED = new Set<TermTag>(['syn', 'get', 'fold', 'let', 'var', 'dropLastIf', 'record']);
const constTy = (v: unknown): Ty => (v === null ? 'null' : typeof v === 'string' ? 'string' : typeof v === 'number' ? 'number' : typeof v === 'boolean' ? 'bool' : 'any');
const scalarOk = (ty: Ty, want: string): boolean => ty === 'any' || ty === want;
const join = (tys: Ty[]): Ty => (tys.length && tys.every((t) => t === tys[0]) ? tys[0] : 'any');
// ── Evaluation ──
/** A node's inherited attributes: scalars, and the node lists of the nodes attributes. */
type Inh = Record<string, Scalar | ShapeValue[]>;
/** A run-time scope: what `SScope` is statically, over a matched frame. */
type RScope = { info: ScopeInfo; base: RuleExpr[]; frame: Frame; outer?: RScope; vars: Map<string, Bound>; m: Matched; node: CstNode; inh: Inh };
type Bound = { value: ShapeValue | undefined; start: number; end: number };
/** The value of `cst` (the root: its context is every inherited attribute's default). */
export function evaluateShape(loaded: Shape, cst: CstNode, src: string): ShapeValue | undefined {
return evaluator(loaded, cst, src)(cst);
}
/** An evaluator over one tree: the value of any node under `root`, in the context its
* ancestors (and, through a thread, its left siblings) give it. Matches and attributes are
* memoised across calls. */
export function evaluator(loaded: Shape, root: CstNode, src: string): (n: CstNode) => ShapeValue | undefined {
const { spec, grammar: g } = loaded;
const keys = nodeKeysOf(spec);
const isNode = (v: ShapeValue | undefined): v is ShapeNode => v !== null && typeof v === 'object' && !Array.isArray(v) && keys.kind in v;
const matches = new WeakMap<CstNode, Matched>();
const synMemo = new WeakMap<CstNode, Map<string, Scalar>>();
const threadMemo = new WeakMap<CstNode, Map<string, Map<CstNode, Scalar>>>();
const inhMemo = new WeakMap<CstNode, Inh>();
const nodesAttrs = Object.entries(spec.inherited ?? {}).filter(([, d]) => d.type === 'nodes').map(([k]) => k);
/** The nodes attributes each node's arm has read (placed, or handed on). */
const placed = new WeakMap<CstNode, Set<string>>();
const kidNames = new WeakMap<CstNode, Map<CstNode, string>>();
let parents: WeakMap<CstNode, CstNode> | undefined;
const inhs = spec.inherited ?? {};
const defaultOf = (d: InhAttr): Scalar | ShapeValue[] => (d.type === 'nodes' ? [] : d.default);
const rootInh: Inh = Object.fromEntries(Object.entries(inhs).map(([k, d]) => [k, defaultOf(d)]));
function matched(n: CstNode): Matched {
let r = matches.get(n);
if (!r) { r = matchArm(g, n, src); matches.set(n, r); }
return r;
}
function scopeOf(n: CstNode, inh: Inh): RScope {
const m = matched(n);
return { info: m.info, base: [], frame: m.frame, vars: new Map(), m, node: n, inh };
}
function valueOf(n: CstNode, inh: Inh): ShapeValue | undefined {
const s = scopeOf(n, inh);
const t = spec.rules[n.rule]?.[s.m.info.arm];
if (t === undefined) throw new ShapeUnmapped(n.rule, s.m.info.arm);
const val = ev(t, s);
// A node handed a non-empty nodes attribute must PLACE it (read it, or hand it on): an arm
// that drops it would build a node without them. Such a node is outside the mapped subset.
for (const attr of nodesAttrs) {
if ((inh[attr] as ShapeValue[]).length > 0 && !placed.get(n)?.has(attr)) throw new ShapeUnmapped(n.rule, `${s.m.info.arm} (handed ${attr})`);
}
return val;
}
function synOf(n: CstNode, attr: string): Scalar {
let memo = synMemo.get(n);
if (!memo) { memo = new Map(); synMemo.set(n, memo); }
if (memo.has(attr)) return memo.get(attr)!;
const d = spec.synthesized![attr];
const s = scopeOf(n, {});
const eq = d.rules[n.rule]?.[s.m.info.arm];
let val: Scalar;
if (eq !== undefined) val = ev(eq, s) as Scalar;
else if (d.default !== undefined) val = d.default;
else throw new Error(`shape2: synthesized ${attr} has no equation for ${n.rule}.${s.m.info.arm} and no default`);
memo.set(attr, val);
return val;
}
/** The inherited attributes a parent (scope `s`, in its arm) hands its child `kid`, named
* `name`: by the arm's thread when it threads the attribute, else by the child's equation. */
function inhFor(s: RScope, name: string, kid: CstNode): Inh {
const out: Inh = {};
for (const [attr, d] of Object.entries(inhs)) {
const eqs = d.rules[s.m.info.rule]?.[s.m.info.arm];
const th = eqs && Object.entries(eqs).find(([, e]) => e.t === 'thread');
if (th) {
const states = threadStates(s, attr, th[0], th[1] as ThreadEq);
out[attr] = states.has(kid) ? states.get(kid)! : defaultOf(d);
continue;
}
const eq = eqs?.[name] as Term | undefined;
out[attr] = eq === undefined ? defaultOf(d) : (ev(eq, s) as Scalar | ShapeValue[]);
}
return out;
}
/** The state a thread hands each rule node of each element of the repetition holding `over`. */
function threadStates(s: RScope, attr: string, over: string, eq: ThreadEq): Map<CstNode, Scalar> {
let byAttr = threadMemo.get(s.node);
if (!byAttr) { byAttr = new Map(); threadMemo.set(s.node, byAttr); }
const memo = byAttr.get(attr);
if (memo) return memo;
const arm = scopeOf(s.node, s.inh);
const slot = arm.info.slots.get(over)!;
const base = slot.quants.slice(0, slot.quants.map(isList).lastIndexOf(true) + 1);
const out = new Map<CstNode, Scalar>();
let state = ev(eq.init as Term, arm) as Scalar;
for (const f of iterFrames(arm.frame, base)) {
for (const n of nodesIn(arm.info, base, f)) out.set(n, state);
const acc: Bound = { value: state, start: s.node.offset, end: s.node.end };
state = ev(eq.next, { info: arm.info, base, frame: f, vars: new Map([[eq.acc, acc]]), m: arm.m, node: s.node, inh: s.inh }) as Scalar;
}
byAttr.set(attr, out);
return out;
}
/** The rule nodes one scope's frame holds (with the branches taken inside it). */
function nodesIn(info: ScopeInfo, base: RuleExpr[], f: Frame): CstNode[] {
const out: CstNode[] = [];
for (const slot of info.slots.values()) {
if (!startsWith(slot.quants, base)) continue;
for (const it of collect(f, slot.quants.slice(base.length), slot.node)) {
if (it?.k === 'node') out.push(it.node);
else if (it?.k === 'branch') out.push(...nodesIn(it.info, [], it.frame));
}
}
return out;
}
/** The name of each rule-node child of `p` (in its arm, or in a branch it took). */
function namesOfKids(p: CstNode): Map<CstNode, string> {
let out = kidNames.get(p);
if (out) return out;
out = new Map();
const visit = (info: ScopeInfo, f: Frame): void => {
for (const slot of info.slots.values()) for (const it of collect(f, slot.quants, slot.node)) {
if (it?.k === 'node') out!.set(it.node, slot.name);
else if (it?.k === 'branch') visit(it.info, it.frame);
}
};
const m = matched(p);
visit(m.info, m.frame);
kidNames.set(p, out);
return out;
}
/** A node's inherited attributes, from the root down. */
function inhOf(n: CstNode): Inh {
const memo = inhMemo.get(n);
if (memo) return memo;
if (!parents) {
parents = new WeakMap();
const walk = (x: CstNode): void => { for (const k of x.children) if (!isLeaf(k)) { parents!.set(k, x); walk(k); } };
walk(root);
}
const p = parents.get(n);
let out: Inh;
// A template hole is a fresh expression context: every inherited attribute's default.
if (p?.rule === '$template') out = rootInh;
else if (p === undefined) {
if (n !== root) throw new Error(`shape2: the node at ${n.offset}..${n.end} is not under the evaluator's root`);
out = rootInh;
} else {
const name = namesOfKids(p).get(n);
if (name === undefined) throw new Error(`shape2: the node at ${n.offset}..${n.end} is not a named child of its ${p.rule} parent`);
out = inhFor(scopeOf(p, inhOf(p)), name, n);
}
inhMemo.set(n, out);
return out;
}
function resolve(s: RScope, name: string): { items: (Item | undefined)[]; card: Card; scope: RScope } {
const slot = s.info.slots.get(name);
if (slot && startsWith(slot.quants, s.base)) {
const rest = slot.quants.slice(s.base.length);
return { items: collect(s.frame, rest, slot.node), card: cardOf(rest), scope: s };
}
if (!s.outer) throw new Error(`shape2: no child ${name}`);
return resolve(s.outer, name);
}
const lookupVar = (s: RScope, name: string): Bound | undefined => s.vars.get(name) ?? (s.outer ? lookupVar(s.outer, name) : undefined);
const one = (s: RScope, name: string): Item | undefined => resolve(s, name).items[0];
const textOf = (it: Item): string => { const sp = spanOfItem(it); return src.slice(sp.start, sp.end); };
/** The value of one child item, seen from the scope that holds it. */
function itemValue(it: Item | undefined, holder: RScope, name: string): ShapeValue | undefined {
if (it === undefined) return undefined;
if (it.k !== 'node') throw new Error(`shape2: child ${name} is a ${it.k}`);
return valueOf(it.node, it.hole ? rootInh : inhFor(holder, name, it.node));
}
function spanEdge(s: RScope, name: string, edge: 'start' | 'end'): number {
const b = lookupVar(s, name);
if (b) return b[edge];
const items = resolve(s, name).items.filter((x): x is Item => x !== undefined);