diff --git a/docs/ALLOCATIONS.md b/docs/ALLOCATIONS.md index 38f1b19d..136e78d1 100644 --- a/docs/ALLOCATIONS.md +++ b/docs/ALLOCATIONS.md @@ -26,20 +26,20 @@ returns. Tokens: each target's own `tokenize` count. Nodes: rule nodes of the re | target | grammar | input | mode | tokens | nodes | allocations | per token | per node | bytes | B per token | B per node | result allocs | result bytes | overhead bytes | |:--|:--|:--|:--|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:| -| ts | typescript | acorn.js | parse | 42,251 | 28,638 | 139,665 | 3.31 | 4.88 | 4,618,136 | 109.3 | 161.3 | 79,491 | 2,313,619 | 2,304,517 | -| ts | typescript | acorn.js | parseWith | 42,251 | 28,638 | 139,665 | 3.31 | 4.88 | 4,618,136 | 109.3 | 161.3 | 79,491 | 2,313,619 | 2,304,517 | -| ts | typescript | lib.es5.d.ts | parse | 13,659 | 7,182 | 43,680 | 3.20 | 6.08 | 1,436,340 | 105.2 | 200.0 | 20,313 | 591,395 | 844,945 | -| ts | typescript | lib.es5.d.ts | parseWith | 13,659 | 7,182 | 43,680 | 3.20 | 6.08 | 1,436,340 | 105.2 | 200.0 | 20,313 | 591,395 | 844,945 | -| ts | typescript | _tsserver.js | parse | 4,932 | 3,139 | 15,943 | 3.23 | 5.08 | 537,368 | 109.0 | 171.2 | 8,673 | 252,250 | 285,118 | -| ts | typescript | _tsserver.js | parseWith | 4,932 | 3,139 | 15,943 | 3.23 | 5.08 | 537,368 | 109.0 | 171.2 | 8,673 | 252,250 | 285,118 | -| ts | typescript | _tsserver.js ×4 | parse | 19,728 | 12,553 | 63,693 | 3.23 | 5.07 | 2,103,920 | 106.6 | 167.6 | 34,686 | 1,008,865 | 1,095,055 | -| ts | typescript | _tsserver.js ×4 | parseWith | 19,728 | 12,553 | 63,693 | 3.23 | 5.07 | 2,103,920 | 106.6 | 167.6 | 34,686 | 1,008,865 | 1,095,055 | -| ts | javascript | acorn.js | parse | 42,051 | 32,239 | 146,763 | 3.49 | 4.55 | 4,819,100 | 114.6 | 149.5 | 86,693 | 2,515,039 | 2,304,061 | -| ts | javascript | acorn.js | parseWith | 42,051 | 32,239 | 146,763 | 3.49 | 4.55 | 4,819,100 | 114.6 | 149.5 | 86,693 | 2,515,039 | 2,304,061 | -| ts | javascript | _tsserver.js | parse | 4,928 | 3,411 | 16,587 | 3.37 | 4.86 | 555,420 | 112.7 | 162.8 | 9,217 | 267,394 | 288,026 | -| ts | javascript | _tsserver.js | parseWith | 4,928 | 3,411 | 16,587 | 3.37 | 4.86 | 555,420 | 112.7 | 162.8 | 9,217 | 267,394 | 288,026 | -| ts | javascript | _tsserver.js ×4 | parse | 19,712 | 13,641 | 66,269 | 3.36 | 4.86 | 2,176,128 | 110.4 | 159.5 | 36,862 | 1,069,439 | 1,106,689 | -| ts | javascript | _tsserver.js ×4 | parseWith | 19,712 | 13,641 | 66,269 | 3.36 | 4.86 | 2,176,128 | 110.4 | 159.5 | 36,862 | 1,069,439 | 1,106,689 | +| ts | typescript | acorn.js | parse | 42,251 | 28,638 | 159,870 | 3.78 | 5.58 | 5,263,936 | 124.6 | 183.8 | 99,327 | 2,948,317 | 2,315,619 | +| ts | typescript | acorn.js | parseWith | 42,251 | 28,638 | 159,870 | 3.78 | 5.58 | 5,263,936 | 124.6 | 183.8 | 99,327 | 2,948,317 | 2,315,619 | +| ts | typescript | lib.es5.d.ts | parse | 13,659 | 7,182 | 52,393 | 3.84 | 7.30 | 1,712,924 | 125.4 | 238.5 | 28,023 | 836,284 | 876,640 | +| ts | typescript | lib.es5.d.ts | parseWith | 13,659 | 7,182 | 52,393 | 3.84 | 7.30 | 1,712,924 | 125.4 | 238.5 | 28,023 | 836,284 | 876,640 | +| ts | typescript | _tsserver.js | parse | 4,932 | 3,139 | 18,563 | 3.76 | 5.91 | 621,168 | 125.9 | 197.9 | 11,206 | 333,261 | 287,907 | +| ts | typescript | _tsserver.js | parseWith | 4,932 | 3,139 | 18,563 | 3.76 | 5.91 | 621,168 | 125.9 | 197.9 | 11,206 | 333,261 | 287,907 | +| ts | typescript | _tsserver.js ×4 | parse | 19,728 | 12,553 | 74,173 | 3.76 | 5.91 | 2,439,120 | 123.6 | 194.3 | 44,818 | 1,332,916 | 1,106,204 | +| ts | typescript | _tsserver.js ×4 | parseWith | 19,728 | 12,553 | 74,173 | 3.76 | 5.91 | 2,439,120 | 123.6 | 194.3 | 44,818 | 1,332,916 | 1,106,204 | +| ts | javascript | acorn.js | parse | 42,051 | 32,239 | 166,694 | 3.96 | 5.17 | 5,457,020 | 129.8 | 169.3 | 106,529 | 3,149,490 | 2,307,530 | +| ts | javascript | acorn.js | parseWith | 42,051 | 32,239 | 166,694 | 3.96 | 5.17 | 5,457,020 | 129.8 | 169.3 | 106,529 | 3,149,490 | 2,307,530 | +| ts | javascript | _tsserver.js | parse | 4,928 | 3,411 | 19,197 | 3.90 | 5.63 | 638,752 | 129.6 | 187.3 | 11,750 | 348,191 | 290,561 | +| ts | javascript | _tsserver.js | parseWith | 4,928 | 3,411 | 19,197 | 3.90 | 5.63 | 638,752 | 129.6 | 187.3 | 11,750 | 348,191 | 290,561 | +| ts | javascript | _tsserver.js ×4 | parse | 19,712 | 13,641 | 76,709 | 3.89 | 5.62 | 2,509,456 | 127.3 | 184.0 | 46,994 | 1,392,635 | 1,116,821 | +| ts | javascript | _tsserver.js ×4 | parseWith | 19,712 | 13,641 | 76,709 | 3.89 | 5.62 | 2,509,456 | 127.3 | 184.0 | 46,994 | 1,392,635 | 1,116,821 | | js | typescript | acorn.js | fresh | 42,251 | 28,813 | 5,161 | 0.12 | 0.18 | 14,643,756 | 346.6 | 508.2 | - | - | - | | js | typescript | acorn.js | reuse | 42,251 | 28,813 | 4,992 | 0.12 | 0.17 | 234,424 | 5.5 | 8.1 | - | - | - | | js | typescript | lib.es5.d.ts | fresh | 13,659 | 7,692 | 7,008 | 0.51 | 0.91 | 2,790,368 | 204.3 | 362.8 | - | - | - | @@ -54,25 +54,25 @@ returns. Tokens: each target's own `tokenize` count. Nodes: rule nodes of the re | js | javascript | _tsserver.js | reuse | 4,928 | 3,535 | 318 | 0.06 | 0.09 | 15,176 | 3.1 | 4.3 | - | - | - | | js | javascript | _tsserver.js ×4 | fresh | 19,712 | 14,137 | 1,386 | 0.07 | 0.10 | 6,416,748 | 325.5 | 453.9 | - | - | - | | js | javascript | _tsserver.js ×4 | reuse | 19,712 | 14,137 | 1,245 | 0.06 | 0.09 | 59,744 | 3.0 | 4.2 | - | - | - | -| go | typescript | acorn.js | fresh | 42,251 | 28,638 | 83 | 0.00 | 0.00 | 9,249,920 | 218.9 | 323.0 | 3 | 2,072,576 | 7,177,344 | +| go | typescript | acorn.js | fresh | 42,251 | 28,638 | 85 | 0.00 | 0.00 | 9,671,168 | 228.9 | 337.7 | 3 | 2,154,496 | 7,516,672 | | go | typescript | acorn.js | reuse | 42,251 | 28,638 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | | go | typescript | acorn.js | slim-reuse | 42,251 | 11,491 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | -| go | typescript | lib.es5.d.ts | fresh | 13,659 | 7,233 | 73 | 0.01 | 0.01 | 2,117,280 | 155.0 | 292.7 | 3 | 548,864 | 1,568,416 | +| go | typescript | lib.es5.d.ts | fresh | 13,659 | 7,233 | 75 | 0.01 | 0.01 | 2,289,312 | 167.6 | 316.5 | 3 | 589,824 | 1,699,488 | | go | typescript | lib.es5.d.ts | reuse | 13,659 | 7,233 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | | go | typescript | lib.es5.d.ts | slim-reuse | 13,659 | 3,112 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | -| go | typescript | _tsserver.js | fresh | 4,932 | 3,185 | 60 | 0.01 | 0.02 | 718,496 | 145.7 | 225.6 | 3 | 225,280 | 493,216 | +| go | typescript | _tsserver.js | fresh | 4,932 | 3,185 | 61 | 0.01 | 0.02 | 759,456 | 154.0 | 238.4 | 3 | 237,568 | 521,888 | | go | typescript | _tsserver.js | reuse | 4,932 | 3,185 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | | go | typescript | _tsserver.js | slim-reuse | 4,932 | 1,372 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | -| go | typescript | _tsserver.js ×4 | fresh | 19,728 | 12,737 | 78 | 0.00 | 0.01 | 3,710,624 | 188.1 | 291.3 | 3 | 901,120 | 2,809,504 | +| go | typescript | _tsserver.js ×4 | fresh | 19,728 | 12,737 | 79 | 0.00 | 0.01 | 3,841,696 | 194.7 | 301.6 | 3 | 933,888 | 2,907,808 | | go | typescript | _tsserver.js ×4 | reuse | 19,728 | 12,737 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | | go | typescript | _tsserver.js ×4 | slim-reuse | 19,728 | 5,485 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | -| go | javascript | acorn.js | fresh | 42,051 | 32,239 | 83 | 0.00 | 0.00 | 9,249,920 | 220.0 | 286.9 | 3 | 2,072,576 | 7,177,344 | +| go | javascript | acorn.js | fresh | 42,051 | 32,239 | 85 | 0.00 | 0.00 | 9,671,168 | 230.0 | 300.0 | 3 | 2,154,496 | 7,516,672 | | go | javascript | acorn.js | reuse | 42,051 | 32,239 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | | go | javascript | acorn.js | slim-reuse | 42,051 | 11,491 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | -| go | javascript | _tsserver.js | fresh | 4,928 | 3,411 | 60 | 0.01 | 0.02 | 718,496 | 145.8 | 210.6 | 3 | 225,280 | 493,216 | +| go | javascript | _tsserver.js | fresh | 4,928 | 3,411 | 61 | 0.01 | 0.02 | 759,456 | 154.1 | 222.6 | 3 | 237,568 | 521,888 | | go | javascript | _tsserver.js | reuse | 4,928 | 3,411 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | | go | javascript | _tsserver.js | slim-reuse | 4,928 | 1,367 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | -| go | javascript | _tsserver.js ×4 | fresh | 19,712 | 13,641 | 79 | 0.00 | 0.01 | 4,251,296 | 215.7 | 311.7 | 3 | 1,015,808 | 3,235,488 | +| go | javascript | _tsserver.js ×4 | fresh | 19,712 | 13,641 | 81 | 0.00 | 0.01 | 4,554,400 | 231.0 | 333.9 | 3 | 1,089,536 | 3,464,864 | | go | javascript | _tsserver.js ×4 | reuse | 19,712 | 13,641 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | | go | javascript | _tsserver.js ×4 | slim-reuse | 19,712 | 5,465 | 0 | 0.00 | 0.00 | 0 | 0.0 | 0.0 | 0 | 0 | 0 | @@ -80,12 +80,12 @@ returns. Tokens: each target's own `tokenize` count. Nodes: rule nodes of the re | kind | site (literals folded) | in functions | allocations | per token | modeled bytes | share | in result | |:--|:--|--:|--:|--:|--:|--:|--:| -| object | `{ off, end, nl, kid, lid }` | 1 | 42,251 | 1.00 | 1,352,032 | 29.3% | 0 | -| .slice() → array | `_hs.slice(b, _n)` | 1 | 28,916 | 0.68 | 898,372 | 19.5% | 28,638 | -| object | `{ rule, children, offset: off, end }` | 1 | 28,915 | 0.68 | 809,620 | 17.5% | 28,638 | -| object | `{ tokenType, offset: off, end }` | 1 | 23,031 | 0.55 | 644,868 | 14.0% | 22,215 | -| array growth | `toks.push(mk_tok(off, end, pendingNl, kid, lid))` | 1 | 18 | 0.00 | 607,924 | 13.2% | 0 | -| .slice() → string | `src.slice(pos, e)` | 1 | 16,248 | 0.38 | 300,424 | 6.5% | 0 | +| object | `{ off, end, nl, kid, lid }` | 1 | 42,251 | 1.00 | 1,352,032 | 25.7% | 0 | +| object | `{ tokenType, offset: off, end }` | 1 | 43,236 | 1.02 | 1,210,608 | 23.0% | 42,051 | +| .slice() → array | `_hs.slice(b, _n)` | 1 | 28,916 | 0.68 | 978,432 | 18.6% | 28,638 | +| object | `{ rule, children, offset: off, end }` | 1 | 28,915 | 0.68 | 809,620 | 15.4% | 28,638 | +| array growth | `toks.push(mk_tok(off, end, pendingNl, kid, lid))` | 1 | 18 | 0.00 | 607,924 | 11.5% | 0 | +| .slice() → string | `src.slice(pos, e)` | 1 | 16,248 | 0.38 | 300,424 | 5.7% | 0 | | .slice() → string | `_src.slice(t.off, u.end)` | 1 | 203 | 0.00 | 3,248 | 0.1% | 0 | | .slice() → string | `_src.slice(_sp[b * _SW + N], _sp[b * _SW + N])` | 1 | 72 | 0.00 | 1,240 | 0.0% | 0 | | array growth | `localE.push({ tokStart: _sp[s + N]!, tokEnd: pos, ext: Math.max(pos...` | 1 | 1 | 0.00 | 76 | 0.0% | 0 | @@ -100,12 +100,12 @@ returns. Tokens: each target's own `tokenize` count. Nodes: rule nodes of the re | kind | site (literals folded) | in functions | allocations | per token | modeled bytes | share | in result | |:--|:--|--:|--:|--:|--:|--:|--:| -| object | `{ off, end, nl, kid, lid }` | 1 | 42,251 | 1.00 | 1,352,032 | 29.3% | 0 | -| .slice() → array | `_hs.slice(b, _n)` | 1 | 28,916 | 0.68 | 898,372 | 19.5% | 28,638 | -| object | `{ rule, children, offset: off, end }` | 1 | 28,915 | 0.68 | 809,620 | 17.5% | 28,638 | -| object | `{ tokenType, offset: off, end }` | 1 | 23,031 | 0.55 | 644,868 | 14.0% | 22,215 | -| array growth | `toks.push(mk_tok(off, end, pendingNl, kid, lid))` | 1 | 18 | 0.00 | 607,924 | 13.2% | 0 | -| .slice() → string | `src.slice(pos, e)` | 1 | 16,248 | 0.38 | 300,424 | 6.5% | 0 | +| object | `{ off, end, nl, kid, lid }` | 1 | 42,251 | 1.00 | 1,352,032 | 25.7% | 0 | +| object | `{ tokenType, offset: off, end }` | 1 | 43,236 | 1.02 | 1,210,608 | 23.0% | 42,051 | +| .slice() → array | `_hs.slice(b, _n)` | 1 | 28,916 | 0.68 | 978,432 | 18.6% | 28,638 | +| object | `{ rule, children, offset: off, end }` | 1 | 28,915 | 0.68 | 809,620 | 15.4% | 28,638 | +| array growth | `toks.push(mk_tok(off, end, pendingNl, kid, lid))` | 1 | 18 | 0.00 | 607,924 | 11.5% | 0 | +| .slice() → string | `src.slice(pos, e)` | 1 | 16,248 | 0.38 | 300,424 | 5.7% | 0 | | .slice() → string | `_src.slice(t.off, u.end)` | 1 | 203 | 0.00 | 3,248 | 0.1% | 0 | | .slice() → string | `_src.slice(_sp[b * _SW + N], _sp[b * _SW + N])` | 1 | 72 | 0.00 | 1,240 | 0.0% | 0 | | array growth | `localE.push({ tokStart: _sp[s + N]!, tokEnd: pos, ext: Math.max(pos...` | 1 | 1 | 0.00 | 76 | 0.0% | 0 | @@ -156,14 +156,15 @@ returns. Tokens: each target's own `tokenize` count. Nodes: rule nodes of the re | array | `[source]` | 1 | 1 | 0.00 | 28 | 0.0% | - | | .slice() → array | `lexEmptyPops.slice()` | 1 | 1 | 0.00 | 16 | 0.0% | - | -## Where: go target, fresh, typescript grammar, acorn.js (top 5 of 5 sites by bytes) +## Where: go target, fresh, typescript grammar, acorn.js (top 6 of 6 sites by bytes) | site (innermost function in the parser package) | allocations | bytes | share | |:--|--:|--:|--:| -| `(*engine).finish` | 47 | 5,829,088 | 63.0% | -| `lexFrom.func2` | 26 | 3,413,248 | 36.9% | -| `(*engine).pushLeaf` | 6 | 7,424 | 0.1% | -| `(*engine).matchTok` | 3 | 112 | 0.0% | +| `(*engine).finish` | 48 | 6,244,960 | 64.6% | +| `lexFrom.func2` | 26 | 3,413,248 | 35.3% | +| `(*engine).matchLit` | 7 | 7,344 | 0.1% | +| `(*engine).pushLeaf` | 2 | 5,440 | 0.1% | +| `(*engine).matchTok` | 1 | 128 | 0.0% | | `(*engine).parseProgram` | 1 | 48 | 0.0% | ## Where: go target, reuse, typescript grammar, acorn.js (top 0 of 0 sites by bytes) diff --git a/docs/CORRECTNESS.md b/docs/CORRECTNESS.md index 6e152b42..787ef038 100644 --- a/docs/CORRECTNESS.md +++ b/docs/CORRECTNESS.md @@ -76,7 +76,8 @@ lowering member each printer implements (`src/target-{ts,go,rust}.ts`: the TS `p native and builder forms, the Rust `prattRule`; the recovery interpreter `src/ir/recovery-family.ts` reads the same facts from its table, and `test/ir-engine.ts` mirrors them), and the list rows in `test/portable-cases.ts` that exercise it. **V** means the exercising rows are in those lists, -which compare every target with the interpreter, verdict and CST (gate +which compare every target with the interpreter, verdict and CST byte for byte (until +`land/lossless-cst` only the tree of rule nodes; gate `emit-parity/portable-targets/lists`), and each row's verdict was checked against tsc (and acorn for JavaScript). **R** means the row was argued from the code: the mechanism has no portable counterpart, so there is nothing to compare. **W** means the argument has a witness that fails if diff --git a/docs/MEASUREMENT.md b/docs/MEASUREMENT.md index 757c03be..a23b80a4 100644 --- a/docs/MEASUREMENT.md +++ b/docs/MEASUREMENT.md @@ -166,6 +166,36 @@ Reuse mode is the like-for-like mode for memory: one `CstBuilder` kept across pa (`parse_with`) against one oxc `Allocator` `reset()` before each parse; fresh mode is a new builder / allocator per parse. +### The default tree keeps every token (2026-11-29, `land/lossless-cst`) + +Since this landing the default CST of the Rust, Go and TS targets holds every token as a leaf, +punctuation included, as the interpreter's always did. From #56 until this landing it dropped the +punctuation leaves, so every row below this section was measured on a tree without them: a CST +that was not lossless. Keeping them costs the Rust parse 2% to 5% more instructions on the real +inputs (`dense-semi.ts`, which is almost all `;`, 24%), the Go direct engine about 4%; the TS target +executes about 1% fewer blocks but makes 14% to 20% more allocations (one object per leaf; Go fresh +parses allocate 4% to 8% more bytes, `docs/ALLOCATIONS.md`). Instructions per parse, +`measure-profile` full scope, run 46290960497 (A = master 118bee29, M = the landing), monogram ÷ oxc: + +| input | reuse, A | reuse, M | fresh, A | fresh, M | +|:--|--:|--:|--:|--:| +| `checker.ts` | 0.896 | 0.915 | 0.900 | 0.919 | +| `typescript.js` | 0.893 | 0.914 | 0.894 | 0.914 | +| `parser.ts` | 0.891 | 0.914 | 0.907 | 0.938 | +| `typescript.d.ts` | 0.997 | 1.034 | 1.014 | 1.053 | +| 2 MB synthetic file | 0.921 | 0.957 | 0.923 | 0.960 | +| non-ASCII-heavy file | 0.879 | 0.895 | 0.913 | 0.923 | +| `gen-textmate.ts` | 0.924 | 0.947 | 0.942 | 0.967 | +| `typescript.ts` | 0.725 | 0.746 | 0.788 | 0.826 | +| dense `;` | 0.957 | 1.191 | 0.959 | 1.194 | +| dense `a+a+…` | 0.809 | 0.787 | 0.811 | 0.788 | +| `jsx-corpus.tsx` | 1.346 | 1.409 | 1.391 | 1.446 | +| `jsx-corpus.jsx` | 1.224 | 1.287 | 1.348 | 1.433 | + +On `checker.ts` monogram now runs 106.8M instructions per parse in reuse mode (was 104.6M), oxc +116.7M. `typescript.d.ts` crosses above oxc: 3.4% more in reuse mode (was 0.3% less). Time was not +re-measured. + ### monogram `bf18adc` (2026-11-23) Time: `measure-bench` run 45244727475 (both modes on AMD EPYC 9V74). Instructions: @@ -386,6 +416,12 @@ that excess is T2 - C, the slot overhead beyond the CST builder it replaces. The constructs at accept sites) all remove T2. No step can remove T1. The typed build's floor is P + T1 = 18.5M fresh, below the lower bound. +Since `land/lossless-cst` the CST build keeps the punctuation leaves (measure-profile run 46290960497): +16,610,344 instructions fresh and 16,122,636 reuse on checker.cov.ts (was 16,466,918 and 15,865,035), +the typed build unchanged at 23,575,738 and 22,219,465, so the typed build is +41.9% / +37.8% against +it (was +43.2% / +40.1%). A converter then reads every punctuation token from the CST and needs no +re-read of the text; the parts above were not split again. + ## Recorded result: element dialects (TSX and JSX) `measure-profile` run 45129600578 (AMD EPYC 7763), M = master `d326d65`. Per token: Rust and Go diff --git a/docs/TARGETS.md b/docs/TARGETS.md index 1c00787a..8e1e2c0b 100644 --- a/docs/TARGETS.md +++ b/docs/TARGETS.md @@ -72,7 +72,7 @@ interpreter's extension is the one to narrow. Parity (`test/portable-targets.ts`, every CI run; the same counts for TypeScript, Go and Rust): -| grammar | accept / reject ≡ interpreter | one-character edits ≡ fresh parse | parity corpus ≡ interpreter (verdict, rule skeleton, token stream) | +| grammar | accept / reject ≡ interpreter | one-character edits ≡ fresh parse | parity corpus ≡ interpreter (verdict, CST, token stream) | |---|---|---|---| | typescriptreact | 35 / 13 | 5,731 | 11,346 (generated, plus tsc's JSX conformance cases) | | javascriptreact | 19 / 9 | 2,182 | 11,427 | @@ -162,9 +162,8 @@ listed in [ROADMAP.md](ROADMAP.md#1-one-portable-engine-one-shared-runtime-descr deleted, inserted or replaced; the rejected mutants, TS target). DAMAGE: the share whose `$error` nodes (all of them) hold more than N tokens. The FALLBACK share: an `$error` child of the root (an entry skipped whole). STABILITY: the share whose tree outside the damaged region is - the original text's (`test/recovery-contract.ts` `damage`). Both trees are parseTotal's with - every token a leaf, punctuation included (`FULL_BUILDER`, `test/portable-harness.ts`; the gate - checks on every mutant that this tree is the default CST plus its punctuation leaves). By hand, + the original text's (`test/recovery-contract.ts` `damage`). Both trees are parseTotal's default + CST, which holds every token as a leaf, punctuation included. By hand, for `while (a) b;` with `: ` inserted at offset 6, repaired `while $error(:) (a) b;`: 1. The edit's span is `[6, 8)` in the mutant (the inserted text; a deleted text is the empty span at its offset), widened over any mutant token it touches; the REGION is that span widened @@ -184,8 +183,8 @@ listed in [ROADMAP.md](ROADMAP.md#1-one-portable-engine-one-shared-runtime-descr | grammar (rejected mutants) | damage N = 1 | N = 3 | N = 5 | stable | fallback | |---|---|---|---|---|---| - | javascript (776) | 21.9% | 10.8% | 6.3% | 61.2% | 28.0% | - | typescript (1836) | 27.0% | 13.5% | 8.8% | 58.4% | 27.9% | + | javascript (781) | 22.0% | 10.8% | 6.3% | 60.8% | 28.4% | + | typescript (1838) | 27.2% | 13.5% | 8.9% | 58.4% | 28.0% | Earlier versions of this table gave 76 to 80% stable. That measure often compared nothing: it skipped every entry that crossed the region (each entry reached to the next one's first leaf, the @@ -210,6 +209,15 @@ listed in [ROADMAP.md](ROADMAP.md#1-one-portable-engine-one-shared-runtime-descr whenever the Doc's tokens do. The walk is one function in `src/ir/lex-family.ts` (TRIVIA_FN), and `test/portable-corpus.ts` checks it on every grammar that has comments. - The `tsTarget` CST carries spans only: a leaf is located by its `offset`/`end`. +- The default CST of every target (TS `parse` / `cstBuilder`, Go and Rust `CstBuilder`) holds + every token as a leaf, punctuation included (`$punct`, beside `$keyword`, `$operator` and the + token kinds), and is the interpreter's tree byte for byte (Go and Rust offsets in bytes). From + #56 until `land/lossless-cst` the TS, Go and Rust default CST dropped the punctuation leaves; + code that read a node's children by index then counts them again (`f(1)`'s call node now has + `(` and `)` among its children). `SlimBuilder` (Go, Rust) is a deliberately smaller tree: it + keeps rule nodes and token-kind leaves only (no `$punct`, `$keyword` or `$operator` leaf) and + splices a node of one child into its parent. It is the builder the profile job's `Go builder` + row parses into, to measure the builder engine. - Lexers scan every `>` alone (so `>>` closing two type-argument lists is two tokens). At an operator site the parser composes `>>`, `>>>`, `>=`, `>>=`, `>>>=` from adjacent `>`, `>` and `=` tokens, so an operator leaf at a `>` spans that run of `tokenize(src)` tokens and @@ -276,9 +284,11 @@ emit to TypeScript, Go and Rust. That includes the `[Await]/[Yield]` context (ru the interpreter, one context word in these parsers), left recursion, the regex/division and template state machines, arrow functions, and the TS type grammar. -[`test/portable-targets.ts`](../test/portable-targets.ts) compiles and runs all three on every -CI run, for the two real grammars plus focused fixtures. Every emitted parser must agree with -the reference interpreter on accept/reject and, where both accept, on the tree of rule nodes. +The portable-targets gates ([`test/portable-harness.ts`](../test/portable-harness.ts) and its +classes) compile and run all three on every CI run, for the two real grammars plus focused +fixtures. Every emitted parser must agree with the reference interpreter on accept/reject and, +where both accept, on the default CST byte for byte (every token a leaf, Go and Rust byte offsets +read as UTF-16 units). The inputs are hand-written accept/reject lists and a corpus derived from each grammar: - generated inputs, and one-token mutants of them; diff --git a/docs/TESTING.md b/docs/TESTING.md index 8e9e249a..5dc0db4e 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -230,7 +230,7 @@ CACHE: an entry per sha-256 of the emitted sources, the build command and the to for 24 h or above 3 GB); `test/portable-cases.ts` the grammars and their hand-written lists; one file per class: `portable-lists.ts` (lists, jsTarget on them, tok-spans, Unicode, default prefix, empty entry), `portable-edits.ts` (one-character edits, edit sessions), `portable-corpus.ts` (the parity -corpus: verdict, skeleton, tokens, literal ids, Doc; sharded by grammar in `check.ts`), +corpus: verdict, CST byte for byte, tokens, literal ids, Doc; sharded by grammar in `check.ts`), `portable-recovery.ts` (total parsing). `--grammars=a,b` (or `PORTABLE_GRAMMARS`) and `PORTABLE_TARGETS=go,rust` narrow a run. diff --git a/src/ir/parser-ir.ts b/src/ir/parser-ir.ts index c4ea4669..abe53274 100644 --- a/src/ir/parser-ir.ts +++ b/src/ir/parser-ir.ts @@ -2602,7 +2602,7 @@ export type LexIdPlan = { lids: string[]; // lids[0]='' = "not any literal"; then puncts (longest-first), then the other non-word texts, then the words (each lexicographically) gtComps: string[]; // ir.gtComps: lids composed from single-character tokens, never lexed /** The first word lid: a literal matched in the tree is a `$keyword` leaf exactly when its text - * is a word (isKeywordLiteral; `$punct`, never a leaf, otherwise), and the words are the lids + * is a word (isKeywordLiteral; a `$punct` leaf otherwise), and the words are the lids * from here on, so a target tells the two apart by its lid and no site passes the type. */ kwLid: number; }; @@ -2965,7 +2965,7 @@ export function lidWordByte(b: number): boolean { /** Resolve kid for a known kind; 0 if not in the plan. */ /** The lid of a `sep` step's delimiter. A target matches it as a literal like any other, so it - * is a `$punct` (never a leaf) because it is not a word; a word delimiter is refused here rather + * is a `$punct` leaf because it is not a word; a word delimiter is refused here rather * than given a type of its own. */ export function sepDelimLid(plan: LexIdPlan, delim: string): number { const lid = lidOf(plan, delim); @@ -3034,16 +3034,13 @@ export type ArenaIdPlan = { ruleNames: string[]; // RULE_NAMES — CST rule labels }; -/** Sentinel tt_id for $punct (trivia — never stored as a leaf). Not an index into ttNames. */ -export const TT_SKIP_PUNCT = 255; - -/** Collect every ttype text that push_leaf / match_lit|match_tok may emit (excluding $punct). */ +/** Collect every ttype text that push_leaf / match_lit|match_tok may emit. */ function collectStepTtypes(steps: Step[], out: Set): void { for (const s of steps) { switch (s.t) { - case 'lit': if (s.ttype !== '$punct') out.add(s.ttype); break; + case 'lit': out.add(s.ttype); break; case 'tok': out.add(s.name); break; - case 'altlit': for (const o of s.opts) if (o.ttype !== '$punct') out.add(o.ttype); break; + case 'altlit': for (const o of s.opts) out.add(o.ttype); break; case 'sep': collectStepTtypes([s.elem], out); break; case 'ctx': collectStepTtypes(s.steps, out); break; case 'star': collectStepTtypes([s.step], out); break; @@ -3056,7 +3053,7 @@ function collectStepTtypes(steps: Step[], out: Set): void { /** * Build TT_NAMES + RULE_NAMES for arena slim encoding. - * TT_NAMES = kids 全体 ∪ {$keyword,$operator,$templateHead,$templateMiddle,$templateTail} + * TT_NAMES = kids 全体 ∪ {$keyword,$operator,$templateHead,$templateMiddle,$templateTail,$punct} * ∪ other push_leaf ttypes collected from the IR (exhaustive). * RULE_NAMES = every rule cstName ∪ {$template} when templates are enabled. */ @@ -3064,7 +3061,7 @@ export function buildArenaIdPlan(ir: ParserIR, lexIds: LexIdPlan): ArenaIdPlan { const ttNames = [...lexIds.kids]; const seenTt = new Set(ttNames); const addTt = (s: string) => { if (!seenTt.has(s)) { seenTt.add(s); ttNames.push(s); } }; - for (const s of ['$keyword', '$operator', '$templateHead', '$templateMiddle', '$templateTail']) addTt(s); + for (const s of ['$keyword', '$operator', '$templateHead', '$templateMiddle', '$templateTail', '$punct']) addTt(s); const fromSteps = new Set(); for (const r of ir.rules) { @@ -3096,9 +3093,8 @@ export function buildArenaIdPlan(ir: ParserIR, lexIds: LexIdPlan): ArenaIdPlan { return { ttNames, ruleNames }; } -/** Resolve tt_id for a leaf tokenType; throws if missing (codegen bug). $punct → TT_SKIP_PUNCT. */ +/** Resolve tt_id for a leaf tokenType; throws if missing (codegen bug). */ export function ttIdOf(plan: ArenaIdPlan, ttype: string): number { - if (ttype === '$punct') return TT_SKIP_PUNCT; const i = plan.ttNames.indexOf(ttype); if (i < 0) throw new Error(`ttIdOf: unknown ttype ${JSON.stringify(ttype)}`); return i; diff --git a/src/targets/target-go.ts b/src/targets/target-go.ts index 71d4437b..a6d335af 100644 --- a/src/targets/target-go.ts +++ b/src/targets/target-go.ts @@ -11,7 +11,7 @@ // warmed parser allocates ~nothing per parse. import { type ParserIR, type MarkForm, type RdRule, type PrattRule, type NodeCap, type Step, type LexTok, type NewlineCfg, type FirstSig, type Guard, type Dispatch, type LexFirstBytes, type LexIdPlan, type ArenaIdPlan, type ReusePlan, type AssignTargetsIR } from '../ir/parser-ir.ts'; import type { ArmForm } from '../ir/assign-targets.ts'; -import { prattTail, hasRebind, nudLowForm, hasUnaryNud, demandTwinCond, demandLids, DEFER_SHIFT, type DemandIR, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, ctxWordBits, ctxWord, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, TT_SKIP_PUNCT, tplHoleRules, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; +import { prattTail, hasRebind, nudLowForm, hasUnaryNud, demandTwinCond, demandLids, DEFER_SHIFT, type DemandIR, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, ctxWordBits, ctxWord, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, tplHoleRules, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; import type { Grammar } from '../grammar/types.ts'; import { defineParserTarget, type SharedAlgorithms } from './define-parser-target.ts'; import type { EmitOptions } from './target.ts'; @@ -210,7 +210,7 @@ const goLibAs = (key: string, name: string): string => (goLib(key), name); const goLibFn = (name: string, text: string): string => (goNeed(name) ? text : ''); function goSteps(ids: LexIdPlan, f: GoForm, recv: string, e: GoEngine, ar?: ArenaIdPlan): StepLowering { // A literal's leaf type (litTt, decided here): a word is a $keyword leaf, anything else $punct. - const litTt = (lid: number) => (lid >= ids.kwLid ? ttIdOf(ar!, '$keyword') : TT_SKIP_PUNCT); + const litTt = (lid: number) => (lid >= ids.kwLid ? ttIdOf(ar!, '$keyword') : ttIdOf(ar!, '$punct')); const fn = (cond: string) => `func() bool { return ${cond} }`; const L: StepLowering = { inner: () => L, @@ -427,11 +427,10 @@ func mkTok(off, end int, nl bool, kid, lid uint16) Tok { return Tok{Off: uint32( function renderArenaTablesGo(ar: ArenaIdPlan, ids: LexIdPlan): string { return `var TT_NAMES = []string{${ar.ttNames.map(J).join(', ')}} var RULE_NAMES = []string{${ar.ruleNames.map(J).join(', ')}} -const TT_SKIP_PUNCT = ${TT_SKIP_PUNCT} // lidKw: the first word lid (LexIdPlan.kwLid). A literal from here on is a $keyword leaf, one -// before it a $punct (no leaf); litTt is its leaf type id. +// before it a $punct leaf; litTt is its leaf type id. const lidKw = ${ids.kwLid} -${goLibFn('litTt', `func litTt(lid uint16) uint16 { if lid >= lidKw { return ${ttIdOf(ar, '$keyword')} }; return TT_SKIP_PUNCT } +${goLibFn('litTt', `func litTt(lid uint16) uint16 { if lid >= lidKw { return ${ttIdOf(ar, '$keyword')} }; return ${ttIdOf(ar, '$punct')} } `)}`; } @@ -2849,14 +2848,8 @@ ${goLibFn('inCtxWords', `func inCtxWords(ctx uint8, t *Tok) bool { return false$ function emitBuilderAddonGo(ir: ParserIR, ids: LexIdPlan, ar: ArenaIdPlan, shared: SharedAlgorithms, recovery = false): string { const reuse = ir.reuse; - const dropTtIds = ['$punct', '$keyword', '$operator'] - .map((n) => { - try { return ttIdOf(ar, n); } catch { return null; } - }) - .filter((x): x is number => x !== null); - const punctId = TT_SKIP_PUNCT; // The leaf types SlimBuilder never keeps: its Leaf's switch and its drop table (dropsLeaves). - const slimDropIdList = [...new Set([...dropTtIds, punctId])]; + const slimDropIdList = ['$punct', '$keyword', '$operator'].map((n) => ttIdOf(ar, n)); const slimDropIds = slimDropIdList.join(', '); // Selection: *CstBuilder parses with the direct engine (parseWithCst); other Builders use the // builder engine parserW. Why two engines: measured 2026-11-22 on 7fe75f9 (measure-profile, @@ -2944,7 +2937,6 @@ func (b *CstBuilder) Checkpoint() (nb, kb int) { return len(b.Nodes), len(b.Kids func (b *CstBuilder) Restore(nb, kb int) { b.Nodes = b.Nodes[:nb]; b.Kids = b.Kids[:kb] } func (b *CstBuilder) Leaf(scratch *[]int32, ttId uint16, tokIdx, off, end uint32) bool { \t_ = off; _ = end -\tif ttId == ${punctId} { return false } \t*scratch = append(*scratch, encodeLeaf(tokIdx, uint8(ttId))) \treturn true } @@ -3934,7 +3926,6 @@ func decodeLeaf(v int32) (tokIdx uint32, ttId uint8) { } ${gtRuntimeGo(ids, ar)} ${goLibFn('pushLeaf', `func (p *engine) pushLeaf(ttId uint8, tokIdx uint32) { -\tif ttId == TT_SKIP_PUNCT { return } \tp.scratch = append(p.scratch, encodeLeaf(tokIdx, ttId)) } `)} @@ -3972,7 +3963,7 @@ ${goLibFn('matchLit', `func (p *engine) matchLit(lid uint16) bool { \ti := p.pos \tp.peekEnd = i + 1 // the probe is a peek (TS/Rust matchLit go through peek()) \tif i >= len(p.toks) || p.toks[i].Lid != lid { return false } -\tif lid >= lidKw { p.scratch = append(p.scratch, encodeLeaf(uint32(i), ${ttIdOf(ar, '$keyword')})) } +\tif lid >= lidKw { p.scratch = append(p.scratch, encodeLeaf(uint32(i), ${ttIdOf(ar, '$keyword')})) } else { p.scratch = append(p.scratch, encodeLeaf(uint32(i), ${ttIdOf(ar, '$punct')})) } \tp.pos = i + 1 \treturn true } diff --git a/src/targets/target-rust.ts b/src/targets/target-rust.ts index bb7846e0..d3d0d3af 100644 --- a/src/targets/target-rust.ts +++ b/src/targets/target-rust.ts @@ -14,7 +14,7 @@ import { dropUnreferencedRs } from './rs-unreferenced.ts'; import { type ParserIR, type RdRule, type PrattRule, type NodeCap, type RuleIR, type NudRef, type Step, type Alt, type LexTok, type NewlineCfg, type FirstSig, type Guard, type LeadTest, type Dispatch, type LexFirstBytes, type LexIdPlan, type ArenaIdPlan, type ReusePlan, type AssignTargetsIR } from '../ir/parser-ir.ts'; import type { ArmForm } from '../ir/assign-targets.ts'; -import { prattTail, hasRebind, nudLowForm, demandTwinCond, demandLids, DEFER_SHIFT, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, ctxWordBits, ctxWord, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, TT_SKIP_PUNCT, isFirstGuardable, groupByPreserveOrder, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; +import { prattTail, hasRebind, nudLowForm, demandTwinCond, demandLids, DEFER_SHIFT, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, ctxWordBits, ctxWord, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, isFirstGuardable, groupByPreserveOrder, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; import type { Grammar } from '../grammar/types.ts'; import { defineParserTarget, type SharedAlgorithms } from './define-parser-target.ts'; import type { EmitOptions } from './target.ts'; @@ -218,7 +218,7 @@ function gtRuntimeRust(ids: LexIdPlan): string { }).join(''); const leads = compLeadLids(ids); return `const GT_LID: u16 = ${leads.length > 0 ? leads[0] : 'u16::MAX'};${leads.length > 1 ? `\nconst GT_LID2: u16 = ${leads[1]};` : ''} -/// The first word lid (LexIdPlan.kwLid): a literal from here on is a \`$keyword\` leaf, one before it a \`$punct\` (no leaf). +/// The first word lid (LexIdPlan.kwLid): a literal from here on is a \`$keyword\` leaf, one before it a \`$punct\` leaf. const LID_KW: u16 = ${ids.kwLid}; #[inline(always)] fn gt_step(a: u16, b: u16) -> u16 { match (a, b) { ${arms}_ => 0 } } #[inline] @@ -2299,15 +2299,9 @@ function emitParserMachine(ir: ParserIR, ids: LexIdPlan, ar: ArenaIdPlan, shapeB } ` : ''; - const dropTtIds = ['$punct', '$keyword', '$operator'] - .map((n) => { - try { return ttIdOf(ar, n); } catch { return null; } - }) - .filter((x): x is number => x !== null); - const punctId = TT_SKIP_PUNCT; - const slimDropMatch = dropTtIds.length - ? dropTtIds.map((id) => `${id}`).join(' | ') - : 'u16::MAX'; + const punctId = ttIdOf(ar, '$punct'); + // The leaf types SlimBuilder never keeps (its leaf's match). + const slimDropMatch = ['$punct', '$keyword', '$operator'].map((n) => ttIdOf(ar, n)).join(' | '); return `// ─── Builder API ───────────────────────────────────────────────────────────── // Builder is pure / bottom-up. Backtracking truncates scratch (+ optional arena @@ -2524,7 +2518,6 @@ ${reuse ? ` #[inline(always)] fn restore(&mut self, ck: (usize, usize)) { self.nodes.truncate(ck.0); self.kids.truncate(ck.1); } #[inline(always)] fn leaf(&mut self, scratch: &mut Vec, tt_id: u16, tok_idx: u32, _off: u32, _end: u32) -> bool { - if tt_id == ${punctId} { return false; } scratch.push(encode_leaf(tok_idx, tt_id as u8)); true } @@ -2647,7 +2640,6 @@ impl Builder for SlimBuilder { #[inline(always)] fn leaf(&mut self, scratch: &mut Vec, tt_id: u16, tok_idx: u32, _off: u32, _end: u32) -> bool { match tt_id { ${slimDropMatch} => return false, _ => {} } - if tt_id == ${punctId} { return false; } scratch.push(encode_leaf(tok_idx, tt_id as u8)); true } diff --git a/src/targets/target-ts.ts b/src/targets/target-ts.ts index 3b256a1c..70365727 100644 --- a/src/targets/target-ts.ts +++ b/src/targets/target-ts.ts @@ -1288,7 +1288,11 @@ function _dfix(p: number, ok: boolean): boolean { } ${ir.rules.filter((r): r is PrattRule => r.kind === 'pratt' && demandLids(r, ids, D).length > 0).map((r) => `function ${r.name}_demand(op: number, form: number, p0: number, stop: number): boolean { if (${demandLids(r, ids, D).map((l) => `op !== ${l}`).join(' && ')}) return true; - return (_twinForm(${twinOf('form')}, p0, stop) & ${D.pass}) !== 0; + // The re-parse reads operators of its own: the operator read here (_opN, _opEnd) is kept for its leaf. + const n = _opN, e = _opEnd; + const ok = (_twinForm(${twinOf('form')}, p0, stop) & ${D.pass}) !== 0; + _opN = n; _opEnd = e; + return ok; }`).join('\n')}`; } function engineRuntime(ir: ParserIR, ids: LexIdPlan): string { @@ -1503,7 +1507,6 @@ ${matchTemplateW}${lookFns(ir, ids)}${sharedFns(ir, ids, 'w')}${sharedFns(ir, id /** The default builder: the CST (plain Node / Leaf objects); parse() is parseWith(src, cstBuilder). */ export const cstBuilder: Builder = { leaf(tokenType, _kid, _lid, off, end) { - if (tokenType === '$punct') return null; return { tokenType, offset: off, end }; }, node(rule, children, off, end) { @@ -3876,7 +3879,7 @@ if (_editFast || process.argv.includes('edit-session')) { node: (rule, children) => ({ name: rule, s: children.length > 0 ? children[0]!.s : pos, e: pos, kids: children }), }); if (_root === null) { process.stderr.write('parse error\\n'); process.exit(1); } - for (const k of _root.kids) if (k.name !== '$punct') process.stdout.write(k.name + '\\t' + k.s + '\\t' + k.e + '\\n'); + for (const k of _root.kids) process.stdout.write(k.name + '\\t' + k.s + '\\t' + k.e + '\\n'); process.stdout.write('total\\t0\\t' + pos + '\\n'); } else { const _root = parse(_raw); diff --git a/test/builder-reuse.ts b/test/builder-reuse.ts index 9e5bb80b..d19831b5 100644 --- a/test/builder-reuse.ts +++ b/test/builder-reuse.ts @@ -963,9 +963,6 @@ func (b *MirrorBuilder) Restore(nb, kb int) { b.Nodes = b.Nodes[:nb]; b.Ki func (b *MirrorBuilder) Leaf(scratch *[]int32, ttId uint16, tokIdx, off, end uint32) bool { _ = off _ = end - if ttId == TT_SKIP_PUNCT { - return false - } *scratch = append(*scratch, encodeLeaf(tokIdx, uint8(ttId))) return true } diff --git a/test/ir-engine.ts b/test/ir-engine.ts index 1e5ffefc..535e171d 100644 --- a/test/ir-engine.ts +++ b/test/ir-engine.ts @@ -34,7 +34,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { const lidOf = (t: string) => { const i = ids.lids.indexOf(t); return i >= 0 ? i : 0; }; const kidOf = (k: string) => { const i = ids.kids.indexOf(k); return i >= 0 ? i : 0; }; const ttIdOf = (tt: string) => ar.ttNames.indexOf(tt); - const PUNCT = -1, TT_KEYWORD = ttIdOf('$keyword'), TT_OPERATOR = ttIdOf('$operator'); + const PUNCT = ttIdOf('$punct'), TT_KEYWORD = ttIdOf('$keyword'), TT_OPERATOR = ttIdOf('$operator'); const GT_LEADS = new Set(ir.gtComps.map((c) => lidOf(c[0]!))); // the composites' leads ('>', '<': compositeLeads) const gtCompSet = new Set(ir.gtComps); const gtStep = (a: number, b: number): number => { const c = ids.lids[a]! + ids.lids[b]!; return gtCompSet.has(c) ? lidOf(c) : 0; }; @@ -75,7 +75,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { const reset = (m: Mark) => { pos = m.pos; scratch.length = m.sb; restore(m.ck); }; // A binary operator composed of several `>` tokens: its leaf spans them (by its first token). const opEnd = new Map(); - const pushLeaf = (tt: number, i: number) => { if (tt !== PUNCT) scratch.push(-(i * 256 + tt) - 1); }; + const pushLeaf = (tt: number, i: number) => { scratch.push(-(i * 256 + tt) - 1); }; function finish(rule: number, sb: number): Sp { nodes.push({ rule, kids: scratch.slice(sb) }); scratch.length = sb; diff --git a/test/newline-mode.ts b/test/newline-mode.ts index b128e045..d9e27814 100644 --- a/test/newline-mode.ts +++ b/test/newline-mode.ts @@ -220,13 +220,8 @@ const gT = defineGrammar({ const file = join(dirE, 'envspec-lines.ts'); writeFileSync(file, emitParser(gT, tsTarget)); const p = await import(file + '?v=' + Date.now()); - // The whole CST, punctuation leaves included (the module's cstBuilder leaves them out). - const full = { - leaf: (tokenType: string, _k: number, _l: number, offset: number, end: number) => ({ tokenType, offset, end }), - node: (rule: string, children: unknown[], offset: number, end: number) => ({ rule, children, offset, end }), - }; for (const src of ['A=1\n\nB=2\n', '\n\nA=1', 'A=fn(1,\n2)\nB=3', 'A=1\n# note\nB=2', 'A=1\r\n\r\nB=2']) { - const cst = p.parseWith(src, full); + const cst = p.parse(src); check(`lines: emitted engine ≡ interpreter for ${JSON.stringify(src)}`, cst !== null && JSON.stringify(cst) === JSON.stringify(parseT(src))); } } diff --git a/test/parser-ir-library.ts b/test/parser-ir-library.ts index 14a4a9c6..f15a3a38 100644 --- a/test/parser-ir-library.ts +++ b/test/parser-ir-library.ts @@ -116,7 +116,7 @@ else { // Builder needs — no generated rule helper or lexer constant. const GO_API = new Set(['Tokenize', 'Token', 'LexError', 'Error', 'Tok', 'Node', 'Edit', 'Align', 'EntryMeta', 'Doc', 'NewDoc', 'DocWith', 'NewDocWith', 'Document', 'SetValidate', 'Text', 'Root', 'Builder', 'Shifter', 'CstBuilder', 'SlimBuilder', 'Checkpoint', 'Restore', 'Leaf', 'Finish', 'SpanOf', 'HeadSpan', 'Shift', - 'ParseWith', 'CstJSONWith', 'SlimJSONWith', 'CstJSON', 'TT_NAMES', 'RULE_NAMES', 'TT_SKIP_PUNCT', + 'ParseWith', 'CstJSONWith', 'SlimJSONWith', 'CstJSON', 'TT_NAMES', 'RULE_NAMES', // A builder that keeps the engine's buffers between parses (Rust: Builder::workspace_mut, Workspace). 'Workspace', 'WorkspaceOwner']); const exported = [...goSrc.matchAll(/^(?:func (?:\([^)]*\) )?|type |var |const )([A-Z]\w*)/gm)].map((x) => x[1]!); diff --git a/test/parser-ir-split.ts b/test/parser-ir-split.ts index 7777a991..5594bb72 100644 --- a/test/parser-ir-split.ts +++ b/test/parser-ir-split.ts @@ -135,7 +135,7 @@ const SESSIONS = [curated, random]; // The curated session's first 20 edits: 18 at statement boundaries, then `>>` → `> >` → `>>`. const edits = curated.edits.slice(0, 20); const mirror: B = { - leaf: (tt, _k, _l, off, end) => (tt === '$punct' ? null : { tt, off, end }), + leaf: (tt, _k, _l, off, end) => ({ tt, off, end }), node: (r, c, off, end) => ({ r, c, off, end }), shift: (h, bd) => { const go = (x: any) => { x.off += bd; x.end += bd; if (x.c) x.c.forEach(go); }; go(h); return h; }, }; @@ -235,7 +235,6 @@ type spanB struct { } func (b *spanB) Leaf(scratch *[]int32, ttId uint16, tokIdx, off, end uint32) bool { - if ttId == uint16(TT_SKIP_PUNCT) { return false } b.L = append(b.L, lf{ttId, off, end}) *scratch = append(*scratch, ^int32(len(b.L)-1)) return true diff --git a/test/portable-corpus.ts b/test/portable-corpus.ts index 3085c3a1..e1e5d63b 100644 --- a/test/portable-corpus.ts +++ b/test/portable-corpus.ts @@ -2,11 +2,11 @@ // (test/parity-corpus.ts — the generated inputs, their one-token mutants, the refused-operand // matrix and the token edges; non-ASCII and line-terminator texts for the ECMAScript grammars; // tsc's JSX conformance cases for the JSX ones). Every engine gives each input the oracle's verdict -// and, when it accepts, the oracle's rule skeleton; every lexer gives the oracle lexer's token +// and, when it accepts, the oracle's CST byte for byte; every lexer gives the oracle lexer's token // stream (kind, text, newline-before; text rather than offsets, whose units differ by target), or // fails on it as the oracle lexer does; literal ids are the table's; the Doc path ≡ a fresh parse. import { buildLexIdPlan, elementTokens, portableIR } from '../src/ir/parser-ir.ts'; -import { canon, errText, finish, gate, parityCorpus, prepareAll, skeleton, unLid, type TokStream } from './portable-harness.ts'; +import { cstInOracleForm, errText, finish, gate, parityCorpus, prepareAll, unLid, type TokStream } from './portable-harness.ts'; import { CASES } from './portable-cases.ts'; @@ -34,7 +34,7 @@ let corpusMs = 0, corpusInputs = 0; for (const p of await prepareAll()) { const { c, grammar, runners, oracleOut, tokenize } = p; - // ── Parity corpus: every runner ≡ the oracle on verdict, and on the rule skeleton when both accept ── + // ── Parity corpus: every runner ≡ the oracle on verdict, and on the CST, byte for byte, when both accept ── { const t0 = Date.now(); const inputs = parityCorpus(p); @@ -60,7 +60,7 @@ for (const p of await prepareAll()) { const w = want[i], g = got[i]; let what = ''; if (w.ok !== g.ok) what = `oracle ${w.ok ? 'accepts' : 'rejects'}, ${r.label} ${g.ok ? 'accepts' : 'rejects'}`; - else if (w.ok && g.ok && canon(skeleton(w.cst)) !== canon(skeleton(g.cst))) what = 'both accept, rule skeletons differ'; + else if (w.ok && g.ok && w.cst !== cstInOracleForm(g.cst, input.src, r.utf8Edits)) what = 'both accept, the CSTs differ'; // A target that died in its lexer agrees with the oracle only when the oracle's // rejection is a lexer error too (its parser's own rejections all begin `Parse error`). else if (!w.ok && !g.ok && g.err !== undefined && g.err !== '' && r.label !== 'typescript' && (w.err ?? '').startsWith('Parse error')) what = `oracle rejects in its parser, ${r.label} failed before parsing (${g.err})`; @@ -73,7 +73,7 @@ for (const p of await prepareAll()) { by.set(key, (by.get(key) ?? 0) + 1); if (samples.length < 12) samples.push(`${key} — ${JSON.stringify(input.src.length > 100 ? input.src.slice(0, 100) + '…' : input.src)}`); }); - console.log(` ${c.grammar}/${r.label}: corpus ${inputs.length - bad}/${inputs.length} ≡ oracle (verdict + rule skeleton + token stream)`); + console.log(` ${c.grammar}/${r.label}: corpus ${inputs.length - bad}/${inputs.length} ≡ oracle (verdict + CST + token stream)`); known.forEach((e, k) => { if (!mine[k]) return; console.log(` expected-fail: ${knownHits[k]} inputs disagree${e.inputs ? ` (of ${e.inputs.length} listed)` : ''} — ${e.reason}`); @@ -163,4 +163,4 @@ for (const p of await prepareAll()) { } console.log(` parity corpus: ${corpusInputs} inputs over ${CASES.length} grammars, ${(corpusMs / 1000).toFixed(1)}s`); -finish('the parity corpus (verdict, rule skeleton, token stream, literal ids, Doc)'); +finish('the parity corpus (verdict, CST, token stream, literal ids, Doc)'); diff --git a/test/portable-harness.ts b/test/portable-harness.ts index 9d8e3607..9054373c 100644 --- a/test/portable-harness.ts +++ b/test/portable-harness.ts @@ -4,10 +4,9 @@ // grammar of test/portable-cases.ts is rendered to TypeScript, Go, and Rust; the Go/Rust sources // are COMPILED and RUN, and each parser's outcome is compared against the createParser oracle. // -// The gates check ACCEPT/REJECT PARITY, not byte-identical CST: the portable targets are free to -// use a different internal node shape (arena, compressed CST) as long as they agree with the -// oracle on what parses and what fails; a rule-skeleton snapshot of each accepted input guards -// against semantic drift. +// The gates check ACCEPT/REJECT PARITY and, on each accepted input, the CST byte for byte: every +// target's default CST is the oracle's (every token a leaf, punctuation included), read in the +// oracle's form (cstInOracleForm: canonical JSON, offsets in UTF-16 units). // // The checks are split into classes, one gate (one process) each, run in parallel by // test/check.ts; this module is what they share: @@ -16,8 +15,8 @@ // of the recovery emission, the empty-entry refusal; // - test/portable-edits.ts edited ≡ fresh: exhaustive one-character edits and the edit // sessions (token alignment, reuse, fast ≡ validated); -// - test/portable-corpus.ts the PARITY CORPUS (test/parity-corpus.ts): verdict, rule -// skeleton, token stream, literal ids, the Doc path; +// - test/portable-corpus.ts the PARITY CORPUS (test/parity-corpus.ts): verdict, CST, +// token stream, literal ids, the Doc path; // - test/portable-recovery.ts total parsing (parseTotal) on the corpus and a mutation corpus. // A class may run a subset of the grammars (`--grammars=a,b`, or PORTABLE_GRAMMARS=a,b), which is // how check.ts shards the long ones. @@ -77,20 +76,30 @@ export const sortKeys = (o: unknown): unknown => : o; export const canon = (o: unknown) => JSON.stringify(sortKeys(o)); -// Rule-node skeleton: the tree of rule labels with all leaves (trivia/punct/semantic tokens) -// stripped. Two CSTs that differ only in their leaves — e.g. after Phase 5's trivia compression -// — share a skeleton; a semantic restructure (a node relabeled, merged, or dropped) does not. -// A node is a RULE node iff it carries a non-empty `rule` label (Rust leaves use rule:""; TS -// leaves omit the key entirely), so this is target-agnostic over the canon'd JSON. -export const skelObj = (o: unknown): unknown => { - if (Array.isArray(o)) return o.map(skelObj).filter((x) => x !== null); - if (o && typeof o === 'object') { - const r = (o as { rule?: string }).rule; - if (r && r !== '') return { r, k: skelObj((o as { children?: unknown }).children ?? []) }; +// Each UTF-8 byte offset of src (and its end) -> its UTF-16 unit offset. +export function utf16Offsets(src: string): number[] { + const u16: number[] = []; + for (let i = 0; i < src.length; i++) { + const c = src.codePointAt(i)!; + const n = c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + for (let k = 0; k < n; k++) u16.push(i); + if (c >= 0x10000) i++; } - return null; -}; -export const skeleton = (cstStr: string) => skelObj(JSON.parse(cstStr)); + u16.push(src.length); + return u16; +} +/** A runner's CST JSON in the oracle's form: canonical, offsets in UTF-16 units (`utf8`: the + * runner's are UTF-8 bytes, Go / Rust), so it compares with the oracle's byte for byte. */ +export function cstInOracleForm(cst: string, src: string, utf8: boolean): string { + if (!utf8) return canon(JSON.parse(cst)); + const u16 = utf16Offsets(src); + const walk = (x: unknown): unknown => { + if (Array.isArray(x)) return x.map(walk); + if (x && typeof x === 'object') return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, (k === 'offset' || k === 'end') && typeof v === 'number' ? u16[v] : walk(v)])); + return x; + }; + return canon(walk(JSON.parse(cst))); +} export const TMP = scratchDir('portable-targets'); export const have = (cmd: string, args: string[]) => { try { execFileSync(cmd, args, { stdio: 'pipe' }); return true; } catch { return false; } }; @@ -212,7 +221,7 @@ export const __tok_spans = (src: string): string | null => { } catch { return null; } if (_root === null) return null; let out = ''; - for (const k of _root.kids) if (k.name !== '$punct') out += k.name + '\\t' + k.s + '\\t' + k.e + '\\n'; + for (const k of _root.kids) out += k.name + '\\t' + k.s + '\\t' + k.e + '\\n'; return out + 'total\\t0\\t' + pos + '\\n'; }; `; @@ -323,14 +332,6 @@ export type Runner = { lexToks?: (src: string) => { off: number; end: number; kind: string; text: string; lid: number }[] | null; /** (TS target) the tokens total parsing reads (tokenizeTotal: a total lex), or null where none is emitted or it stops. */ lexTotal?: (src: string) => { off: number; end: number; kind: string; text: string; lid: number }[] | null; - /** (TS target) parseTotal's tree built by FULL_BUILDER (every token a leaf), canonical JSON; undefined: no tree. */ - totalLeaves?: (src: string) => string | undefined; -}; -/** A builder that keeps every token as a leaf, punctuation included (cstBuilder drops `$punct`): - * each node then spans the tokens the parse attributed to it (recovery-contract.ts damage). */ -export const FULL_BUILDER = { - leaf: (tokenType: string, _kid: number, _lid: number, offset: number, end: number) => ({ tokenType, offset, end }), - node: (rule: string, children: unknown[], offset: number, end: number) => ({ rule, children, offset, end }), }; // One parseTotal outcome: accepted (a tree and no diagnostic), whether it gave a tree, each // diagnostic as [off, end, message, relOff, relEnd, relMessage] (relOff -1: no related location), @@ -414,15 +415,7 @@ export function triviaBatch(cmd: string, srcs: string[]): (TriviaRow[] | null)[] if (src.includes('\0')) return null; const line = lines[li++]!; if (line === '!') return null; - // a UTF-8 byte offset -> its UTF-16 unit offset - const u16: number[] = []; - for (let i = 0; i < src.length; i++) { - const c = src.codePointAt(i)!; - const n = c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - for (let k = 0; k < n; k++) u16.push(i); - if (c >= 0x10000) i++; - } - u16.push(src.length); + const u16 = utf16Offsets(src); const v = JSON.parse(line) as number[]; const rows: TriviaRow[] = []; for (let i = 0; i < v.length; i += 3) rows.push([v[i + 2]!, u16[v[i]!]!, u16[v[i + 1]!]!]); @@ -439,7 +432,7 @@ export const applyEdits = (init: string, batches: EditBatch[]): string => { // ── Unicode on the real javascript grammar ── // Every target accepts the oracle's non-ASCII inputs (no panic / no silent reject) with the same -// rule skeleton, rejects what it rejects with the same primary lexer message, and an edit next +// CST, byte for byte, rejects what it rejects with the same primary lexer message, and an edit next // to a multi-byte character (go/rust Doc.edit offsets are UTF-8 bytes) ≡ a fresh parse. export const UNICODE_ACCEPT: string[] = [ // template head / middle / tail each carry non-ASCII @@ -604,7 +597,6 @@ export async function prepareAll(cases: Case[] = selectedCases()): Promise srcs.map((src) => tsInterp(tsLib, src, depth)), lexToks: (src) => { try { return tsLib.tokenize(src).map((t) => ({ off: t.off, end: t.end, kind: t.kind, text: t.text, lid: t.lid })); } catch { return null; } }, lexTotal: (src) => { try { return (tsLib.tokenizeTotal ?? tsLib.tokenize)(src).map((t) => ({ off: t.off, end: t.end, kind: t.kind, text: t.text, lid: t.lid })); } catch { return null; } }, - totalLeaves: (src) => { const t = tsLib.parseTotal(src, FULL_BUILDER); return t.root === null ? undefined : canon(t.root); }, }]; const native: Pending['native'] = []; if (HAS_GO && nativeFor(c, 'go') && (!TARGETS_ONLY || TARGETS_ONLY.includes('go'))) { diff --git a/test/portable-lists.ts b/test/portable-lists.ts index fd8f226a..3a8eb529 100644 --- a/test/portable-lists.ts +++ b/test/portable-lists.ts @@ -1,7 +1,6 @@ // Gate class of the portable targets (test/portable-harness.ts): the HAND-WRITTEN LISTS. On each // grammar's accept / reject lists (test/portable-cases.ts) every target gives the oracle's verdict -// and, when it accepts, the oracle's rule skeleton; the jsTarget parser (target-js.ts) gives the -// oracle's CST byte for byte. Also: tok-spans (the token ranges each top-level kid consumed, the +// and, when it accepts, the oracle's CST byte for byte, as the jsTarget parser (target-js.ts) does. Also: tok-spans (the token ranges each top-level kid consumed, the // same in every target and a partition of the stream), the Unicode corpus of the javascript // grammar, the recovery emission's default prefix, and the refusal of an entry rule that must // choose its empty alternative. @@ -18,7 +17,7 @@ import { cachedEmit } from './emit-cache.ts'; import { ROOT } from './gate-deps.ts'; import { relative } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { applyEdits, canon, errText, gate, finish, prepareAll, primaryLexMsg, runTokSpans, UNICODE_ACCEPT, skeleton, type EditBatch, type Outcome, type Runner } from './portable-harness.ts'; +import { applyEdits, canon, errText, gate, finish, prepareAll, primaryLexMsg, runTokSpans, UNICODE_ACCEPT, cstInOracleForm, type EditBatch, type Outcome, type Runner } from './portable-harness.ts'; /** Reject cases. `lexMsg` set ⇒ expect that primary lexer message (≡ oracle). */ const UNICODE_REJECT: { src: string; lexMsg: string | null }[] = [ @@ -86,13 +85,13 @@ function unicodeParity(r: Runner, oracleOut: (src: string) => Outcome): void { continue; } acc++; - if (canon(skeleton(want.cst)) !== canon(skeleton(got.cst))) { + if (want.cst !== cstInOracleForm(got.cst!, src, r.utf8Edits)) { snap++; gate.failures++; - console.log(` javascript/unicode/${r.label}: SHAPE drift on ${JSON.stringify(src)}`); + console.log(` javascript/unicode/${r.label}: CST differs on ${JSON.stringify(src)}`); } } - console.log(` javascript/unicode/${r.label}: ${acc}/${UNICODE_ACCEPT.length} accept ≡ oracle${snap ? ` · ${snap} shape drift` : ''}`); + console.log(` javascript/unicode/${r.label}: ${acc}/${UNICODE_ACCEPT.length} accept ≡ oracle CST${snap ? ` · ${snap} CST differs` : ''}`); let rej = 0; for (const { src, lexMsg } of UNICODE_REJECT) { @@ -348,17 +347,15 @@ for (const { c, grammar, runners, oracleOut, dir, emitted } of await prepareAll( const want = oracleOut(src), got = accOut[i]!; if (want.ok && got.ok) { acc++; - // Shape snapshot on every accepted input: the rule-node skeleton (rule labels tree, - // trivia/punct leaves stripped) must match the oracle's. Robust to leaf-level CST - // compression (Phase 5) but catches semantic restructure (a node becoming a different - // rule / merging / disappearing) — e.g. the rust prefix arm once dropped its operand - // subtree, visible only on inputs beyond the first two. - if (src && canon(skeleton(want.cst)) !== canon(skeleton(got.cst))) { + // The CST of every accepted input is the oracle's, byte for byte (every token a leaf). + const mine = cstInOracleForm(got.cst, src, r.utf8Edits); + if (want.cst !== mine) { snap++; gate.failures++; - console.log(` ${c.grammar}/${r.label}: SHAPE drift on ${JSON.stringify(src)}`); - console.log(` want ${canon(skeleton(want.cst)).slice(0, 160)}`); - console.log(` got ${canon(skeleton(got.cst)).slice(0, 160)}`); + const at = [...want.cst].findIndex((ch, k) => ch !== mine[k]); + console.log(` ${c.grammar}/${r.label}: CST differs on ${JSON.stringify(src)}`); + console.log(` want …${want.cst.slice(Math.max(0, at - 60), at + 100)}`); + console.log(` got …${mine.slice(Math.max(0, at - 60), at + 100)}`); } continue; } @@ -371,7 +368,7 @@ for (const { c, grammar, runners, oracleOut, dir, emitted } of await prepareAll( gate.failures++; console.log(` ${c.grammar}/${r.label}: REJECT mismatch on ${JSON.stringify(src)} (oracle ok=${want.ok}, ${r.label} ok=${got.ok})`); } - console.log(` ${c.grammar}/${r.label}: ${acc}/${c.accept.length} accept ≡ oracle · ${rej}/${c.reject.length} reject ≡ oracle${snap ? ` · ${snap} shape drift` : ''}`); + console.log(` ${c.grammar}/${r.label}: ${acc}/${c.accept.length} accept ≡ oracle CST · ${rej}/${c.reject.length} reject ≡ oracle${snap ? ` · ${snap} CST differs` : ''}`); // A demand context's re-parses (src/ir/reparse-family.ts): each nested one starts inside the one // around it, so the work per demand operator is bounded by the nesting depth (the counter of // those that do not; the fixture's nested rows exercise it). diff --git a/test/portable-recovery.ts b/test/portable-recovery.ts index adefb417..08f06039 100644 --- a/test/portable-recovery.ts +++ b/test/portable-recovery.ts @@ -3,7 +3,7 @@ import type { Grammar } from '../src/grammar/types.ts'; import { mutationEdits, type Mutant } from './mutation-corpus.ts'; import { CURATED_TS } from './emit-corpus.ts'; import { ECMASCRIPT, canon, finish, gate, parityCorpus, prepareAll, selectedCases, primaryLexMsg, type Case, type DiagRow, type Outcome, type Runner, type Total } from './portable-harness.ts'; -import { checkContract, damage, sameTreeWithPunct, summarize, withOperandSamples, type ContractRow } from './recovery-contract.ts'; +import { checkContract, damage, summarize, withOperandSamples, type ContractRow } from './recovery-contract.ts'; import { RM_MAX_BARS } from '../src/ir/recovery-family.ts'; import type { Tok } from './parity-corpus.ts'; import { portableIR, type PortableFacts } from '../src/ir/parser-ir.ts'; @@ -275,17 +275,13 @@ function recoveryClass(c: Case, grammar: Grammar, runners: Runner[], oracleOut: (s) => oracleOut(s).ok, bad, (k) => lexed && k === 'missing-only' && !greedy.includes(srcs[i]!)); if (greedy.includes(srcs[i]!)) { if (row && row.p10 === 'missing-only' && !row.p10ok) p10Failing.add(srcs[i]!), p10Lists.forEach(([, l], j) => { if (l.includes(srcs[i]!)) p10Hits[j]!++; }); } const m = editOf.get(srcs[i]!), o = m && got[index.get(m.orig) ?? -1]; - if (row && m && o?.ok && o.cst !== undefined) { - const full = r.totalLeaves!(srcs[i]!), ofull = r.totalLeaves!(m.orig); - if (full === undefined || ofull === undefined || !sameTreeWithPunct(JSON.parse(g.cst), JSON.parse(full)) || !sameTreeWithPunct(JSON.parse(o.cst), JSON.parse(ofull))) bad.push(`damage: the every-token tree is not the CST with its punctuation — ${at(i)}`); - else Object.assign(row, damage(JSON.parse(full), JSON.parse(ofull), toks, m.at, m.del, srcs[i]!.length - m.orig.length)); - } + if (row && m && o?.ok && o.cst !== undefined) Object.assign(row, damage(JSON.parse(g.cst), JSON.parse(o.cst), toks, m.at, m.del, srcs[i]!.length - m.orig.length)); if (mutantSet.has(srcs[i]!)) rows.push(row); } }); - if (r.totalLeaves) for (const [orig, src, at0, del, want] of DAMAGE_CASES[c.grammar] ?? []) { - const full = r.totalLeaves(src), ofull = r.totalLeaves(orig), toks = r.lexToks!(src); - const got = full !== undefined && ofull !== undefined && toks !== null ? damage(JSON.parse(full), JSON.parse(ofull), toks, at0, del, src.length - orig.length).stable : undefined; + if (r.lexToks) for (const [orig, src, at0, del, want] of DAMAGE_CASES[c.grammar] ?? []) { + const [t, ot] = r.total([src, orig]), toks = r.lexToks(src); + const got = t!.cst !== undefined && ot!.cst !== undefined && toks !== null ? damage(JSON.parse(t!.cst), JSON.parse(ot!.cst), toks, at0, del, src.length - orig.length).stable : undefined; if (got !== want) bad.push(`damage: ${JSON.stringify(src)} (from ${JSON.stringify(orig)}) is ${got === undefined ? 'unmeasured' : got ? 'stable' : 'unstable'}, its repair ${want ? 'keeps' : 'changes'} the tree outside the damaged region`); } if (r.lexToks) { @@ -436,16 +432,15 @@ function lexTotalClass(c: Case, runners: Runner[], tokenize: (s: string) => Tok[ for (const [a, b] of skip) if (!g.errors.some((e) => e[0] <= a && e[1] >= b && e[2].startsWith('unexpected'))) bad.push(`no diagnostic skips [${a}, ${b}) — ${at}`); const leaves = leavesOf(JSON.parse(g.cst) as J); // Between the unterminated tokens (and the skipped characters) lies text a fresh lex reads: each - // leaf there is one of its tokens and each of its tokens that is no punctuation is a leaf (the - // CST keeps a punctuation leaf only inside an `$error`). With the unterminated spans exact, the + // leaf there is one of its tokens and each of its tokens is a leaf. With the unterminated spans exact, the // input is covered: by those spans, and by stretches of tokens, whitespace and comments. const stops = [...unterm, ...skip, ...esc].sort((x, y) => x[0] - y[0]); [[0, 0] as [number, number], ...stops].forEach(([, b], k) => { const next = k < stops.length ? stops[k]![0] : src.length; - const fresh = tokenize(src.slice(b, next)).map((t) => ({ span: JSON.stringify([b + t.offset, b + t.offset + t.text.length]), punct: t.type === '' || t.type === '$punct' })); + const fresh = tokenize(src.slice(b, next)).map((t) => JSON.stringify([b + t.offset, b + t.offset + t.text.length])); const mine = new Set(leaves.filter(([o]) => o >= b && o < next).map((l) => JSON.stringify(l))); - const all = new Set(fresh.map((f) => f.span)); - const stray = [...mine].filter((l) => !all.has(l)), lost = fresh.filter((f) => !f.punct && !mine.has(f.span)).map((f) => f.span); + const all = new Set(fresh); + const stray = [...mine].filter((l) => !all.has(l)), lost = fresh.filter((f) => !mine.has(f)); if (stray.length || lost.length) bad.push(`in [${b}, ${next}): leaves no fresh lex has ${stray.join(' ')}; its tokens no leaf is ${lost.join(' ')} — ${at}`); }); }); diff --git a/test/portable-wide.ts b/test/portable-wide.ts index 3cf7644f..4a792fd5 100644 --- a/test/portable-wide.ts +++ b/test/portable-wide.ts @@ -3,7 +3,7 @@ // of test262 through every runner, against the interpreter. import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { createParser } from '../src/interpreter/interpreter.ts'; -import { canon, ECMASCRIPT, errText, finish, gate, prepareAll, selectedCases, skelObj, skeleton, type Case, type Runner } from './portable-harness.ts'; +import { canon, cstInOracleForm, ECMASCRIPT, errText, finish, gate, prepareAll, selectedCases, type Case, type Runner } from './portable-harness.ts'; // Every rule level interpreted (test/portable-recovery.ts INTERP_ALL). const INTERP_ALL = 1 << 30; @@ -11,8 +11,7 @@ const INTERP_ALL = 1 << 30; // The parity corpus holds what the grammar derives and what someone wrote down; the interpreter is // also checked on two external corpora (conformance/js-corpus and conformance/test262), and the // portable parsers must give every file of them the interpreter's verdict and, when both accept, -// its rule skeleton (the tree of rule nodes; the leaves are the lexer's, whose token streams the -// parity corpus compares). Each file is one input, its text whole: +// its CST byte for byte. Each file is one input, its text whole: // - the tsc conformance corpus (/tmp/ts-repo/tests/cases/conformance, every .ts file), for the // TypeScript grammar and, read as JavaScript like conformance/js-corpus does, the JavaScript one; // - test262 (/tmp/test262 at test/test262.sha, every test under test/language and @@ -72,8 +71,8 @@ function wideClass(c: Case, runners: Runner[], oracle: { parse: (src: string) => const chunk = files.slice(i, i + WIDE_CHUNK); const srcs = chunk.map((f) => readFileSync(f, 'utf8')); const o0 = Date.now(); - const want = srcs.map((src): { ok: boolean; skel?: string; stack?: boolean } => { - try { return { ok: true, skel: canon(skelObj(JSON.parse(canon(oracle.parse(src))))) }; } catch (e) { return { ok: false, stack: errText(e).includes('Maximum call stack') }; } + const want = srcs.map((src): { ok: boolean; cst?: string; stack?: boolean } => { + try { return { ok: true, cst: canon(oracle.parse(src)) }; } catch (e) { return { ok: false, stack: errText(e).includes('Maximum call stack') }; } }); oracleMs += Date.now() - o0; accepted += want.filter((w) => w.ok).length; @@ -87,7 +86,7 @@ function wideClass(c: Case, runners: Runner[], oracle: { parse: (src: string) => chunk.forEach((_f, j) => { const w = want[j]!, g = got[j]!; if (w.stack) return; // the interpreter's own stack, not a verdict - if (w.ok !== g.ok || (w.ok && g.ok && w.skel !== canon(skeleton(g.cst)))) { disagree[j]!.push(r.label); off.set(r.label, off.get(r.label)! + 1); } + if (w.ok !== g.ok || (w.ok && g.ok && w.cst !== cstInOracleForm(g.cst!, srcs[j]!, r.utf8Edits))) { disagree[j]!.push(r.label); off.set(r.label, off.get(r.label)! + 1); } }); } if (tsr) { @@ -106,7 +105,7 @@ function wideClass(c: Case, runners: Runner[], oracle: { parse: (src: string) => }); } console.log(` ${c.grammar}: wide corpus ${name}: ${files.length} files (${accepted} accepted by the interpreter, ${(oracleMs / 1000).toFixed(1)}s)`); - for (const r of runners) console.log(` ${c.grammar}/${r.label}: wide corpus ${name}: ${files.length - off.get(r.label)!}/${files.length} ≡ interpreter (verdict + rule skeleton), ${(ms.get(r.label)! / 1000).toFixed(1)}s`); + for (const r of runners) console.log(` ${c.grammar}/${r.label}: wide corpus ${name}: ${files.length - off.get(r.label)!}/${files.length} ≡ interpreter (verdict + CST), ${(ms.get(r.label)! / 1000).toFixed(1)}s`); if (tsr) { console.log(` ${c.grammar}/typescript: wide corpus ${name}: the recovery interpreter (forced) ≡ the native parse (verdict + tree) on ${files.length - interpOff}/${files.length}, ${(interpMs / 1000).toFixed(1)}s`); gate.failures += interpOff; @@ -152,4 +151,4 @@ function wideRecordCheck(): void { for (const p of await prepareAll(selectedCases().filter((c) => ECMASCRIPT.has(c.grammar)))) wideClass(p.c, p.runners, createParser(p.grammar)); wideRecordCheck(); -finish('the wide corpora (every file of the tsc conformance corpus and test262: verdict, rule skeleton)'); +finish('the wide corpora (every file of the tsc conformance corpus and test262: verdict, CST)'); diff --git a/test/recovery-contract.ts b/test/recovery-contract.ts index b000494b..28c6fed3 100644 --- a/test/recovery-contract.ts +++ b/test/recovery-contract.ts @@ -1,8 +1,7 @@ // The recovered-tree contract (recovery-1/DESIGN.md section 1), checked on one parseTotal outcome of // a rejected input, and its measurements. Used by the recovery class (test/portable-recovery.ts). // P1 a root; P4 lossless: leaves in order, non-overlapping, each a token (or the tokens of a composed -// operator), every non-punctuation -// token a leaf (the CST keeps no punctuation leaf outside an `$error`); a `$missing` is zero-width +// operator), every token a leaf; a `$missing` is zero-width // with no children; a node's span is its children's; P5 one diagnostic per repair node, in tree // order, at its span (`expected …` for a `$missing`, `unexpected …` for an `$error`); // P10 repair validity: each `$missing` replaced by its literal (or a sample token of its kind) @@ -54,7 +53,7 @@ export function checkContract(src: string, toks: Tok[], root: Node | null, error last = l.end; } const covered = (t: Tok) => leaves.some((l) => l.offset <= t.off && t.end <= l.end); - const lost = toks.filter((t) => t.kind !== '' && !covered(t)); + const lost = toks.filter((t) => !covered(t)); if (lost.length) bad.push(`P4: token ${JSON.stringify(lost[0]!.text)} at ${lost[0]!.off} is no leaf — ${at(src)}`); // P5 if (reps.length !== errors.length) bad.push(`P5: ${reps.length} repair nodes, ${errors.length} diagnostics — ${at(src)}`); @@ -112,10 +111,9 @@ export function checkContract(src: string, toks: Tok[], root: Node | null, error * The CST names a node by its rule, not its alternative, so that content is what tells a call * `g()` from a parenthesis `( $missing )`, a tag's template (`a?.` skipped) from a template, a * name from a member name (`$missing '.'` before `x`). - * Both trees must hold EVERY token as a leaf, punctuation included (FULL_BUILDER in - * test/portable-harness.ts): an entry's extent is then its own tokens, as the parse attributed - * them; the default CST keeps no punctuation leaf, so a statement's ';' or a leading '(' would - * belong to no entry and an entry's extent would be a guess. */ + * Both trees hold every token as a leaf, punctuation included (the default CST): an entry's + * extent is then its own tokens, as the parse attributed them, a statement's ';' or a leading + * '(' included. */ export function damage(root: Node, orig: Node, toks: Tok[], at: number, del: number, delta: number): { errTokens: number; stable: boolean } { // The edit: the original's [at, at + del) is the mutant's [at, at + del + delta) (an insertion's // trailing space included), widened over a mutant token it touches (a deletion that joins two @@ -179,18 +177,6 @@ export function damage(root: Node, orig: Node, toks: Tok[], at: number, del: num && eq(side(root, mCut, (y) => y.off >= hi), side(orig, oCut, (y) => y.off >= ohi)); return { errTokens, stable }; } -/** damage's precondition: the every-token tree is the default CST's (the same nodes, the same - * leaves) with the punctuation leaves added. The default keeps a `$punct` leaf only inside an - * `$error`, and a node's span there is its first and last leaf's, so node spans are not compared. */ -export function sameTreeWithPunct(def: Node, full: Node): boolean { - const bare = (x: Node, inErr: boolean): string => { - if (x.children === undefined) return `${x.tokenType}@${x.offset}-${x.end}`; - const err = inErr || x.rule === '$error'; - return `${x.rule}(${x.children.filter((y) => err || y.tokenType !== '$punct').map((y) => bare(y, err)).join(',')})`; - }; - return bare(def, false) === bare(full, false); -} - const q = (xs: number[], p: number): number => { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(p * s.length))]!; }; const mpm = (xs: number[], f = (x: number) => String(x)) => `median ${f(q(xs, 0.5))}, p90 ${f(q(xs, 0.9))}, max ${f(q(xs, 1))}`; /** The measurements over the rejected inputs (the coordinator's (a)-(c)). */