parseman 0.36.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -19
- package/dist/analysis/duplication.d.ts +421 -0
- package/dist/analysis/duplication.d.ts.map +1 -0
- package/dist/analysis/gating.d.ts +25 -0
- package/dist/analysis/gating.d.ts.map +1 -1
- package/dist/analysis/grammar.d.ts +12 -0
- package/dist/analysis/grammar.d.ts.map +1 -0
- package/dist/combinators/parser.d.ts +26 -0
- package/dist/combinators/parser.d.ts.map +1 -1
- package/dist/compiler/build-arity.d.ts +12 -0
- package/dist/compiler/build-arity.d.ts.map +1 -1
- package/dist/compiler/codegen.d.ts +43 -1
- package/dist/compiler/codegen.d.ts.map +1 -1
- package/dist/compiler/linker.d.ts +64 -7
- package/dist/compiler/linker.d.ts.map +1 -1
- package/dist/cst/host-mode.d.ts +43 -0
- package/dist/cst/host-mode.d.ts.map +1 -0
- package/dist/functional/doc.d.ts.map +1 -1
- package/dist/functional/run.d.ts.map +1 -1
- package/dist/index.cjs +1620 -54
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1620 -54
- package/dist/index.js.map +4 -4
- package/dist/language-service/index.cjs +37 -1
- package/dist/language-service/index.cjs.map +3 -3
- package/dist/language-service/index.js +37 -1
- package/dist/language-service/index.js.map +3 -3
- package/dist/oracle/corpus.d.ts +32 -0
- package/dist/oracle/corpus.d.ts.map +1 -0
- package/dist/oracle/digest.d.ts +21 -0
- package/dist/oracle/digest.d.ts.map +1 -0
- package/dist/oracle/identity.d.ts +117 -0
- package/dist/oracle/identity.d.ts.map +1 -0
- package/dist/oracle/index.cjs +423 -0
- package/dist/oracle/index.cjs.map +7 -0
- package/dist/oracle/index.d.ts +37 -0
- package/dist/oracle/index.d.ts.map +1 -0
- package/dist/oracle/index.js +400 -0
- package/dist/oracle/index.js.map +7 -0
- package/dist/plugin/index.cjs +1627 -61
- package/dist/plugin/index.cjs.map +4 -4
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +1627 -61
- package/dist/plugin/index.js.map +4 -4
- package/dist/run/index.cjs +23 -0
- package/dist/run/index.cjs.map +3 -3
- package/dist/run/index.js +23 -0
- package/dist/run/index.js.map +3 -3
- package/dist/spec/index.cjs +2977 -56
- package/dist/spec/index.cjs.map +4 -4
- package/dist/spec/index.js +2977 -56
- package/dist/spec/index.js.map +4 -4
- package/dist/spec/model.d.ts.map +1 -1
- package/dist/types.d.ts +7 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +10 -3
package/dist/index.cjs
CHANGED
|
@@ -26,8 +26,12 @@ __export(index_exports, {
|
|
|
26
26
|
absoluteSpanCST: () => absoluteSpanCST,
|
|
27
27
|
absolutize: () => absolutize,
|
|
28
28
|
absolutizeCST: () => absolutizeCST,
|
|
29
|
+
alternationGroups: () => alternationGroups,
|
|
30
|
+
analyzeDuplication: () => analyzeDuplication,
|
|
31
|
+
analyzeDuplicationRules: () => analyzeDuplicationRules,
|
|
29
32
|
analyzeGating: () => analyzeGating,
|
|
30
33
|
analyzeGatingRules: () => analyzeGatingRules,
|
|
34
|
+
analyzeGrammarGating: () => analyzeGrammarGating,
|
|
31
35
|
annotateSpan: () => annotateSpan,
|
|
32
36
|
applyEdit: () => applyEdit,
|
|
33
37
|
attempt: () => attempt,
|
|
@@ -36,6 +40,7 @@ __export(index_exports, {
|
|
|
36
40
|
buildLineIndex: () => buildLineIndex,
|
|
37
41
|
buildOffsetIndex: () => buildOffsetIndex,
|
|
38
42
|
buildTriviaIndex: () => buildTriviaIndex,
|
|
43
|
+
charClassMembers: () => charClassMembers,
|
|
39
44
|
choice: () => choice,
|
|
40
45
|
collectLeafSlots: () => collectLeafSlots,
|
|
41
46
|
commentsIn: () => commentsIn,
|
|
@@ -50,9 +55,12 @@ __export(index_exports, {
|
|
|
50
55
|
createGrammarTraceSink: () => createGrammarTraceSink,
|
|
51
56
|
createVisitor: () => createVisitor,
|
|
52
57
|
cstBuildHost: () => cstBuildHost,
|
|
58
|
+
duplicationFindingCount: () => duplicationFindingCount,
|
|
53
59
|
expect: () => expect,
|
|
60
|
+
extractCharClasses: () => extractCharClasses,
|
|
54
61
|
field: () => field,
|
|
55
62
|
firstSetToString: () => firstSetToString,
|
|
63
|
+
formatDuplicationFindings: () => formatDuplicationFindings,
|
|
56
64
|
formatGatingWarnings: () => formatGatingWarnings,
|
|
57
65
|
gapIsSignificant: () => gapIsSignificant,
|
|
58
66
|
gapText: () => gapText,
|
|
@@ -62,6 +70,8 @@ __export(index_exports, {
|
|
|
62
70
|
indentMixed: () => indentMixed,
|
|
63
71
|
indentWidth: () => indentWidth,
|
|
64
72
|
isParseError: () => isParseError,
|
|
73
|
+
keywordAlternationHazards: () => keywordAlternationHazards,
|
|
74
|
+
keywordRegexShape: () => keywordRegexShape,
|
|
65
75
|
keywords: () => keywords,
|
|
66
76
|
label: () => label,
|
|
67
77
|
leaf: () => leaf,
|
|
@@ -92,6 +102,7 @@ __export(index_exports, {
|
|
|
92
102
|
sepBy: () => sepBy,
|
|
93
103
|
sequence: () => sequence,
|
|
94
104
|
shiftAbsolute: () => shiftAbsolute,
|
|
105
|
+
siteToString: () => siteToString,
|
|
95
106
|
skip: () => skip,
|
|
96
107
|
token: () => token,
|
|
97
108
|
transform: () => transform,
|
|
@@ -2505,6 +2516,12 @@ function rules(a, b) {
|
|
|
2505
2516
|
if (rule && !rule._meta.isTrivia) rule._meta.grammarScanSkip = options.scanSkip;
|
|
2506
2517
|
}
|
|
2507
2518
|
}
|
|
2519
|
+
if (options?.hostMode === "cst") {
|
|
2520
|
+
for (const key of Object.keys(definitions)) {
|
|
2521
|
+
const rule = cache[key];
|
|
2522
|
+
if (rule && !rule._meta.isTrivia) rule._meta.grammarHostMode = "cst";
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2508
2525
|
for (const key of Object.keys(definitions)) {
|
|
2509
2526
|
markUnusedValues(cache[key]);
|
|
2510
2527
|
}
|
|
@@ -2563,6 +2580,9 @@ function peek(combinator) {
|
|
|
2563
2580
|
}
|
|
2564
2581
|
|
|
2565
2582
|
// src/compiler/build-arity.ts
|
|
2583
|
+
function cstOutputHost(build) {
|
|
2584
|
+
return build?._parsemanCstOutput === true;
|
|
2585
|
+
}
|
|
2566
2586
|
var PARAM_LIST_RE = (
|
|
2567
2587
|
// (params) => ... | function name?(params) ... | single-ident arrow `x => ...`
|
|
2568
2588
|
/^(?:function\b[^(]*\(([^)]*)\)|\(([^)]*)\)\s*=>|([A-Za-z_$][\w$]*)\s*=>)/
|
|
@@ -2812,7 +2832,8 @@ function node(typeOrCombinator, combinatorOrBuild, buildOrOpts, maybeOpts) {
|
|
|
2812
2832
|
const def = unwrap || collapse || captureTrivia || trailingTrivia ? { ...baseDef, ...unwrap ? { unwrap: true } : {}, ...collapse ? { collapse: true } : {}, ...captureTrivia ? { captureTrivia: true } : {}, ...trailingTrivia ? { trailingTrivia: true } : {} } : baseDef;
|
|
2813
2833
|
const capturesTrivia = captureTrivia || trailingTrivia || (build ? buildReadsTrivia(def) : true);
|
|
2814
2834
|
const clonesState = build ? buildReadsState(def) : true;
|
|
2815
|
-
const
|
|
2835
|
+
const hasOwnFields = parserHasOwnFields(combinator);
|
|
2836
|
+
const capturesFields = hasOwnFields && (build ? buildReadsFields(def) : true);
|
|
2816
2837
|
const guardable = combinator._meta.firstSet.kind !== "any" && !matchesEmpty(combinator);
|
|
2817
2838
|
let failExpected;
|
|
2818
2839
|
return {
|
|
@@ -2827,28 +2848,32 @@ function node(typeOrCombinator, combinatorOrBuild, buildOrOpts, maybeOpts) {
|
|
|
2827
2848
|
}
|
|
2828
2849
|
return { ok: false, expected: failExpected, span: { start: pos, end: pos } };
|
|
2829
2850
|
}
|
|
2851
|
+
const hostCst = build !== void 0 && cstOutputHost(ctx.build);
|
|
2852
|
+
const effTrivia = capturesTrivia || hostCst;
|
|
2853
|
+
const effFields = capturesFields || hostCst && hasOwnFields;
|
|
2830
2854
|
const saved = beginCstNodeCapture(ctx);
|
|
2831
2855
|
const savedFields = ctx._fields;
|
|
2832
|
-
ctx._fields =
|
|
2856
|
+
ctx._fields = effFields ? [] : void 0;
|
|
2833
2857
|
const savedMask = ctx._triviaCaptureMask;
|
|
2834
2858
|
if (build === void 0 && ctx.build?._parsemanTriviaKinds !== void 0 && def.type !== void 0) {
|
|
2835
2859
|
ctx._triviaCaptureMask = ctx.build._parsemanTriviaKinds(def.type);
|
|
2836
2860
|
}
|
|
2837
|
-
if (!
|
|
2861
|
+
if (!effTrivia) ctx.captureTrivia = false;
|
|
2838
2862
|
let r = combinator.parse(input, pos, ctx);
|
|
2839
2863
|
if (r.ok && trailingTrivia && ctx.trivia) {
|
|
2840
2864
|
const end = consumeTrivia(input, r.span.end, ctx);
|
|
2841
2865
|
r = { ...r, span: { start: r.span.start, end } };
|
|
2842
2866
|
}
|
|
2843
|
-
const fields =
|
|
2867
|
+
const fields = effFields ? buildFieldMap(ctx._fields) : void 0;
|
|
2844
2868
|
ctx._fields = savedFields;
|
|
2845
2869
|
ctx._triviaCaptureMask = savedMask;
|
|
2846
2870
|
const { children: children2, rawChildren, triviaLog } = endCstNodeCapture(ctx, saved);
|
|
2847
2871
|
if (!r.ok) return r;
|
|
2848
2872
|
const st = clonesState && ctx.state !== void 0 ? Object.assign({}, ctx.state) : void 0;
|
|
2849
2873
|
const nodeType = def.type ?? missingInferredType();
|
|
2850
|
-
const cstOutput = ctx.build
|
|
2851
|
-
const
|
|
2874
|
+
const cstOutput = cstOutputHost(ctx.build);
|
|
2875
|
+
const hostState = clonesState ? st : ctx.state !== void 0 ? Object.assign({}, ctx.state) : void 0;
|
|
2876
|
+
const built = unwrap && children2.length === 1 ? unwrapChild(children2[0]) : collapse && children2.length === 1 ? children2[0] : !build && ctx.build?._parsemanCstCollapse && children2.length === 1 && rawChildren.length === 1 && ctx.build._parsemanCstCollapse(nodeType, children2[0], children2, rawChildren) ? children2[0] : build ? cstOutput && ctx.build ? ctx.build(nodeType, children2, fields, r.span, rawChildren, triviaLog, hostState) : build(children2, fields, r.span, rawChildren, triviaLog, st) : ctx.build ? ctx.build(nodeType, children2, fields, r.span, rawChildren, triviaLog, st) : { _tag: "node", type: nodeType, span: { start: r.span.start, end: r.span.end }, state: st ?? null, children: children2 };
|
|
2852
2877
|
const rawEntry = isCstChild(built) ? built : { _tag: "leaf", value: typeof built === "string" ? built : typeof built === "object" && built !== null ? input.slice(r.span.start, r.span.end) : "", span: r.span };
|
|
2853
2878
|
if (saved.buf !== void 0 || saved.ch !== void 0) {
|
|
2854
2879
|
pushCstChild(ctx, built, rawEntry);
|
|
@@ -3126,7 +3151,24 @@ function leaf(root, fn) {
|
|
|
3126
3151
|
}
|
|
3127
3152
|
|
|
3128
3153
|
// src/version.ts
|
|
3129
|
-
var PARSEMAN_VERSION = "0.
|
|
3154
|
+
var PARSEMAN_VERSION = "0.37.0";
|
|
3155
|
+
|
|
3156
|
+
// src/cst/host-mode.ts
|
|
3157
|
+
var FUSED_HOST_MODE = /* @__PURE__ */ Symbol.for("parseman.fusedHostMode");
|
|
3158
|
+
var FUSED_HOST_ELIDED = /* @__PURE__ */ Symbol.for("parseman.fusedHostElided");
|
|
3159
|
+
function assertHostModeCompatible(mode, build, hostBranchElided = true) {
|
|
3160
|
+
const isCstHost = build?._parsemanCstOutput === true;
|
|
3161
|
+
if (mode === "ast" && isCstHost && hostBranchElided) {
|
|
3162
|
+
throw new Error(
|
|
3163
|
+
"parseman: this parser was compiled for host mode \"ast\" (the default), so its nodes build through their own `build` callbacks and no positioned-CST branch was emitted. It cannot be driven with a positioned-CST host (cstBuildHost / a language-service host). Compile a second artifact from the SAME grammar with `compile(grammar, { hostMode: 'cst' })` \u2014 or, under the macro, a second `rules({ hostMode: 'cst' }, factory)` call site \u2014 and drive that one instead."
|
|
3164
|
+
);
|
|
3165
|
+
}
|
|
3166
|
+
if (mode === "cst" && !isCstHost) {
|
|
3167
|
+
throw new Error(
|
|
3168
|
+
'parseman: this parser was compiled for host mode "cst", so every node builds through a positioned-CST `ctx.build` host. Pass one (e.g. `{ build: cstBuildHost }`), or use an artifact compiled with the default `hostMode: "ast"` to get the grammar\'s own AST.'
|
|
3169
|
+
);
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3130
3172
|
|
|
3131
3173
|
// src/analysis/gating.ts
|
|
3132
3174
|
var isAny = (fs) => fs.kind === "any";
|
|
@@ -3326,11 +3368,34 @@ function analyzeGating(entry, opts) {
|
|
|
3326
3368
|
function analyzeGatingRules(ruleMap, opts) {
|
|
3327
3369
|
const raw = [];
|
|
3328
3370
|
const antiPatterns = [];
|
|
3371
|
+
const unanalysable = [];
|
|
3372
|
+
const seenUnanalysable = /* @__PURE__ */ new Set();
|
|
3329
3373
|
const visited = /* @__PURE__ */ new Set();
|
|
3374
|
+
const noteUnanalysable = (u) => {
|
|
3375
|
+
const key = `${u.rule}\0${u.kind}`;
|
|
3376
|
+
if (seenUnanalysable.has(key)) return;
|
|
3377
|
+
seenUnanalysable.add(key);
|
|
3378
|
+
unanalysable.push(u);
|
|
3379
|
+
};
|
|
3330
3380
|
const visit = (p, enclosingRule) => {
|
|
3331
3381
|
if (visited.has(p)) return;
|
|
3332
3382
|
visited.add(p);
|
|
3333
|
-
const
|
|
3383
|
+
const def = p?._def;
|
|
3384
|
+
if (def === null || typeof def !== "object") {
|
|
3385
|
+
noteUnanalysable(
|
|
3386
|
+
typeof p === "function" ? {
|
|
3387
|
+
rule: enclosingRule,
|
|
3388
|
+
kind: "fused-rule",
|
|
3389
|
+
reason: "fused rule function \u2014 a compose()/fuse result has no combinator graph. Analyze the composed grammar itself (analyzeGrammarGating) so the carried IR is re-lowered first."
|
|
3390
|
+
} : {
|
|
3391
|
+
rule: enclosingRule,
|
|
3392
|
+
kind: "not-a-combinator",
|
|
3393
|
+
reason: `value of type ${p === null ? "null" : typeof p} is not a combinator and carries no _def descriptor.`
|
|
3394
|
+
}
|
|
3395
|
+
);
|
|
3396
|
+
return;
|
|
3397
|
+
}
|
|
3398
|
+
const d = def;
|
|
3334
3399
|
const rule = ruleNameOf(p) ?? enclosingRule;
|
|
3335
3400
|
if (d.tag === "choice") {
|
|
3336
3401
|
raw.push({ g: analyzeChoice(p, d, rule, opts?.resolveRef), rule });
|
|
@@ -3370,7 +3435,18 @@ function analyzeGatingRules(ruleMap, opts) {
|
|
|
3370
3435
|
const accepted = choices.filter((c) => c.gates === "no" && c.accepted);
|
|
3371
3436
|
const deferred = choices.filter((c) => c.gates === "no" && !c.accepted && c.deferred);
|
|
3372
3437
|
const acceptedUnused = [...accept].filter((id) => !usedAccept.has(id));
|
|
3373
|
-
return {
|
|
3438
|
+
return {
|
|
3439
|
+
totalChoices: choices.length,
|
|
3440
|
+
gated,
|
|
3441
|
+
recoverable,
|
|
3442
|
+
unanalysable,
|
|
3443
|
+
ungated,
|
|
3444
|
+
accepted,
|
|
3445
|
+
deferred,
|
|
3446
|
+
acceptedUnused,
|
|
3447
|
+
choices,
|
|
3448
|
+
antiPatterns
|
|
3449
|
+
};
|
|
3374
3450
|
}
|
|
3375
3451
|
function analyzeChoice(p, d, rule, resolve) {
|
|
3376
3452
|
const arms = d.parsers;
|
|
@@ -3407,6 +3483,13 @@ function analyzeChoice(p, d, rule, resolve) {
|
|
|
3407
3483
|
}
|
|
3408
3484
|
function formatGatingWarnings(report) {
|
|
3409
3485
|
const lines = [];
|
|
3486
|
+
if (report.unanalysable.length > 0) {
|
|
3487
|
+
lines.push(
|
|
3488
|
+
`parseman gating: ${report.unanalysable.length} rule(s) UNANALYSABLE \u2014 this report is PARTIAL (${report.totalChoices} choice(s) examined). An empty finding list below does NOT mean the grammar is clean.`
|
|
3489
|
+
);
|
|
3490
|
+
for (const u of report.unanalysable)
|
|
3491
|
+
lines.push(` \xB7 ${u.rule} [${u.kind}]: ${u.reason}`);
|
|
3492
|
+
}
|
|
3410
3493
|
for (const c of report.ungated) {
|
|
3411
3494
|
lines.push(`parseman gating: choice @ ${c.id} is UNGATED [${c.strategy}] \u2014 no first-char dispatch; every position speculatively enters doomed arms.`);
|
|
3412
3495
|
for (const a of c.anyArms)
|
|
@@ -3422,6 +3505,1284 @@ function formatGatingWarnings(report) {
|
|
|
3422
3505
|
return lines;
|
|
3423
3506
|
}
|
|
3424
3507
|
|
|
3508
|
+
// src/analysis/duplication.ts
|
|
3509
|
+
var siteToString = (s) => s.path === "" ? s.rule : `${s.rule} \u203A ${s.path}`;
|
|
3510
|
+
function childrenOf(d) {
|
|
3511
|
+
switch (d.tag) {
|
|
3512
|
+
case "sequence":
|
|
3513
|
+
case "choice":
|
|
3514
|
+
return d.parsers;
|
|
3515
|
+
case "skip":
|
|
3516
|
+
return [d.main, d.skipped];
|
|
3517
|
+
case "sepBy":
|
|
3518
|
+
return [d.parser, d.separator];
|
|
3519
|
+
case "recover":
|
|
3520
|
+
return [d.parser, d.sentinel];
|
|
3521
|
+
case "scanTo":
|
|
3522
|
+
return [d.sentinel, ...d.skip];
|
|
3523
|
+
case "grammar":
|
|
3524
|
+
return d.triviaParser ? [d.parser, d.triviaParser] : [d.parser];
|
|
3525
|
+
// A `lazy` is a REFERENCE, not a subtree: hashing through it would make every
|
|
3526
|
+
// rule's shape include the whole reachable grammar. Treated as a leaf, keyed
|
|
3527
|
+
// by the rule name it refers to — which is also the right semantics, since two
|
|
3528
|
+
// productions referencing `g.Ident` really do fill that slot the same way.
|
|
3529
|
+
case "lazy":
|
|
3530
|
+
case "literal":
|
|
3531
|
+
case "regex":
|
|
3532
|
+
case "keywords":
|
|
3533
|
+
case "guard":
|
|
3534
|
+
case "unknown":
|
|
3535
|
+
return [];
|
|
3536
|
+
default: {
|
|
3537
|
+
const rec = d;
|
|
3538
|
+
return rec.parser ? [rec.parser] : [];
|
|
3539
|
+
}
|
|
3540
|
+
}
|
|
3541
|
+
}
|
|
3542
|
+
var ruleNameOf2 = (p) => p._ruleName;
|
|
3543
|
+
var fnKey = (src, fn) => src ?? (typeof fn === "function" ? String(fn) : "");
|
|
3544
|
+
function payloadKey(p, d) {
|
|
3545
|
+
switch (d.tag) {
|
|
3546
|
+
case "literal":
|
|
3547
|
+
return `literal\0${d.value}\0${d.caseInsensitive}`;
|
|
3548
|
+
case "regex":
|
|
3549
|
+
return `regex\0${d.source}\0${d.flags}`;
|
|
3550
|
+
case "keywords":
|
|
3551
|
+
return `keywords\0${[...d.words].join("")}\0${d.caseInsensitive}\0${d.boundary ?? ""}`;
|
|
3552
|
+
case "lazy": {
|
|
3553
|
+
const n = ruleNameOf2(p);
|
|
3554
|
+
return n === void 0 ? `ref\0#${anonId(p)}` : `ref\0${n}`;
|
|
3555
|
+
}
|
|
3556
|
+
case "label":
|
|
3557
|
+
return `label\0${d.label}`;
|
|
3558
|
+
case "field":
|
|
3559
|
+
return `field\0${d.name}`;
|
|
3560
|
+
case "node":
|
|
3561
|
+
return `node\0${d.type ?? ""}\0${d.unwrap === true}\0${d.collapse === true}\0${fnKey(d.buildSrc, d.build)}`;
|
|
3562
|
+
case "transform":
|
|
3563
|
+
return `transform\0${fnKey(d.fnSrc, d.fn)}\0${d.recognitionOnly === true}`;
|
|
3564
|
+
case "leaf":
|
|
3565
|
+
return `leaf\0${fnKey(d.fnSrc, d.fn)}`;
|
|
3566
|
+
case "many":
|
|
3567
|
+
case "oneOrMore":
|
|
3568
|
+
return `${d.tag}\0${d.min}\0${d.max ?? ""}`;
|
|
3569
|
+
case "sepBy":
|
|
3570
|
+
return `sepBy\0${d.min}\0${d.max ?? ""}\0${d.trailing ?? ""}`;
|
|
3571
|
+
case "expect":
|
|
3572
|
+
return `expect\0${d.label ?? ""}\0${d.expected.join("")}`;
|
|
3573
|
+
case "scanTo":
|
|
3574
|
+
return `scanTo\0${d.raw}\0${d.orEOF}`;
|
|
3575
|
+
case "guard":
|
|
3576
|
+
return `guard\0${fnKey(d.predSrc, d.predicate)}`;
|
|
3577
|
+
case "withCtx":
|
|
3578
|
+
return `withCtx\0${d.extraSrc ?? safeJson(d.extra)}`;
|
|
3579
|
+
case "grammar":
|
|
3580
|
+
return `grammar\0${d.clearTrivia === true}\0${d.captureTrivia === true}\0${d.trackLines}`;
|
|
3581
|
+
default:
|
|
3582
|
+
return d.tag;
|
|
3583
|
+
}
|
|
3584
|
+
}
|
|
3585
|
+
function safeJson(v2) {
|
|
3586
|
+
try {
|
|
3587
|
+
return JSON.stringify(v2) ?? String(v2);
|
|
3588
|
+
} catch {
|
|
3589
|
+
return "?";
|
|
3590
|
+
}
|
|
3591
|
+
}
|
|
3592
|
+
var anonCounter = 0;
|
|
3593
|
+
var anonIds = /* @__PURE__ */ new WeakMap();
|
|
3594
|
+
function anonId(p) {
|
|
3595
|
+
let id = anonIds.get(p);
|
|
3596
|
+
if (id === void 0) {
|
|
3597
|
+
id = ++anonCounter;
|
|
3598
|
+
anonIds.set(p, id);
|
|
3599
|
+
}
|
|
3600
|
+
return id;
|
|
3601
|
+
}
|
|
3602
|
+
var Interner = class {
|
|
3603
|
+
ids = /* @__PURE__ */ new Map();
|
|
3604
|
+
hole;
|
|
3605
|
+
constructor() {
|
|
3606
|
+
this.hole = this.of("\0HOLE\0");
|
|
3607
|
+
}
|
|
3608
|
+
of(key) {
|
|
3609
|
+
let id = this.ids.get(key);
|
|
3610
|
+
if (id === void 0) {
|
|
3611
|
+
id = this.ids.size;
|
|
3612
|
+
this.ids.set(key, id);
|
|
3613
|
+
}
|
|
3614
|
+
return id;
|
|
3615
|
+
}
|
|
3616
|
+
};
|
|
3617
|
+
var MAX_RENDER = 160;
|
|
3618
|
+
function render(p, depth = 3) {
|
|
3619
|
+
const d = p._def;
|
|
3620
|
+
const name = ruleNameOf2(p);
|
|
3621
|
+
switch (d.tag) {
|
|
3622
|
+
case "literal":
|
|
3623
|
+
return `literal('${d.value}')`;
|
|
3624
|
+
case "regex":
|
|
3625
|
+
return `regex(/${d.source}/${d.flags})`;
|
|
3626
|
+
case "keywords":
|
|
3627
|
+
return `keywords([${[...d.words].slice(0, 4).map((w) => `'${w}'`).join(", ")}${d.words.length > 4 ? ", \u2026" : ""}])`;
|
|
3628
|
+
case "lazy":
|
|
3629
|
+
return `g.${name ?? "?"}`;
|
|
3630
|
+
case "guard":
|
|
3631
|
+
return "gate(\u2026)";
|
|
3632
|
+
default:
|
|
3633
|
+
break;
|
|
3634
|
+
}
|
|
3635
|
+
if (depth <= 0) return `${d.tag}(\u2026)`;
|
|
3636
|
+
const kids = childrenOf(d).map((k) => render(k, depth - 1));
|
|
3637
|
+
switch (d.tag) {
|
|
3638
|
+
case "sequence":
|
|
3639
|
+
return `sequence(${kids.join(", ")})`;
|
|
3640
|
+
case "choice":
|
|
3641
|
+
return `choice(${kids.join(", ")})`;
|
|
3642
|
+
case "node":
|
|
3643
|
+
return `node(${d.type ? `'${d.type}', ` : ""}${kids[0] ?? ""})`;
|
|
3644
|
+
case "label":
|
|
3645
|
+
return `label('${d.label}', ${kids[0] ?? ""})`;
|
|
3646
|
+
case "field":
|
|
3647
|
+
return `field('${d.name}', ${kids[0] ?? ""})`;
|
|
3648
|
+
case "many":
|
|
3649
|
+
return `many(${kids[0] ?? ""}${d.min === 0 && d.max === void 0 ? "" : `, { min: ${d.min}${d.max === void 0 ? "" : `, max: ${d.max}`} }`})`;
|
|
3650
|
+
case "oneOrMore":
|
|
3651
|
+
return `oneOrMore(${kids[0] ?? ""}${d.min === 1 && d.max === void 0 ? "" : `, { min: ${d.min}${d.max === void 0 ? "" : `, max: ${d.max}`} }`})`;
|
|
3652
|
+
case "sepBy":
|
|
3653
|
+
return `sepBy(${kids[0] ?? ""}, ${kids[1] ?? ""})`;
|
|
3654
|
+
default:
|
|
3655
|
+
return `${d.tag}(${kids.join(", ")})`;
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
var clamp = (s) => s.length <= MAX_RENDER ? s : `${s.slice(0, MAX_RENDER - 1)}\u2026`;
|
|
3659
|
+
function segment(d, index) {
|
|
3660
|
+
switch (d.tag) {
|
|
3661
|
+
case "sequence":
|
|
3662
|
+
return `seq[${index}]`;
|
|
3663
|
+
case "choice":
|
|
3664
|
+
return `choice[${index}]`;
|
|
3665
|
+
case "node":
|
|
3666
|
+
return `node(${d.type ?? ""})`;
|
|
3667
|
+
case "label":
|
|
3668
|
+
return `label(${d.label})`;
|
|
3669
|
+
case "field":
|
|
3670
|
+
return `field(${d.name})`;
|
|
3671
|
+
case "sepBy":
|
|
3672
|
+
return index === 0 ? "sepBy.item" : "sepBy.sep";
|
|
3673
|
+
case "skip":
|
|
3674
|
+
return index === 0 ? "skip.main" : "skip.skipped";
|
|
3675
|
+
case "recover":
|
|
3676
|
+
return index === 0 ? "recover.body" : "recover.sentinel";
|
|
3677
|
+
case "scanTo":
|
|
3678
|
+
return index === 0 ? "scanTo.sentinel" : `scanTo.skip[${index - 1}]`;
|
|
3679
|
+
default:
|
|
3680
|
+
return d.tag;
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
function alternationGroups(src) {
|
|
3684
|
+
const out = [];
|
|
3685
|
+
const stack = [{ branches: [], last: 0 }];
|
|
3686
|
+
let i = 0;
|
|
3687
|
+
while (i < src.length) {
|
|
3688
|
+
const c = src[i];
|
|
3689
|
+
if (c === "\\") {
|
|
3690
|
+
i += 2;
|
|
3691
|
+
continue;
|
|
3692
|
+
}
|
|
3693
|
+
if (c === "[") {
|
|
3694
|
+
let j = i + 1;
|
|
3695
|
+
if (src[j] === "^") j++;
|
|
3696
|
+
if (src[j] === "]") j++;
|
|
3697
|
+
while (j < src.length && src[j] !== "]") {
|
|
3698
|
+
if (src[j] === "\\") j++;
|
|
3699
|
+
j++;
|
|
3700
|
+
}
|
|
3701
|
+
i = j + 1;
|
|
3702
|
+
continue;
|
|
3703
|
+
}
|
|
3704
|
+
if (c === "(") {
|
|
3705
|
+
let open = i + 1;
|
|
3706
|
+
if (src[open] === "?") {
|
|
3707
|
+
const rest = src.slice(open);
|
|
3708
|
+
const m = /^\?(?::|=|!|<=|<!|<[^>]*>)/.exec(rest);
|
|
3709
|
+
open += m ? m[0].length : 1;
|
|
3710
|
+
}
|
|
3711
|
+
stack.push({ branches: [], last: open });
|
|
3712
|
+
i = open;
|
|
3713
|
+
continue;
|
|
3714
|
+
}
|
|
3715
|
+
if (c === ")") {
|
|
3716
|
+
const top = stack.pop();
|
|
3717
|
+
if (top !== void 0) {
|
|
3718
|
+
top.branches.push(src.slice(top.last, i));
|
|
3719
|
+
if (top.branches.length >= 2) out.push(top.branches);
|
|
3720
|
+
}
|
|
3721
|
+
i++;
|
|
3722
|
+
continue;
|
|
3723
|
+
}
|
|
3724
|
+
if (c === "|") {
|
|
3725
|
+
const top = stack[stack.length - 1];
|
|
3726
|
+
top.branches.push(src.slice(top.last, i));
|
|
3727
|
+
top.last = i + 1;
|
|
3728
|
+
i++;
|
|
3729
|
+
continue;
|
|
3730
|
+
}
|
|
3731
|
+
i++;
|
|
3732
|
+
}
|
|
3733
|
+
const root = stack[0];
|
|
3734
|
+
root.branches.push(src.slice(root.last));
|
|
3735
|
+
if (root.branches.length >= 2) out.push(root.branches);
|
|
3736
|
+
return out;
|
|
3737
|
+
}
|
|
3738
|
+
var WORD_RE_SRC = "-?[A-Za-z][A-Za-z0-9_-]*";
|
|
3739
|
+
var WORDS_RE = new RegExp(`^${WORD_RE_SRC}(?:\\|${WORD_RE_SRC})*$`);
|
|
3740
|
+
var VOCABULARY_MIN_WORDS = 3;
|
|
3741
|
+
function keywordRegexShape(source) {
|
|
3742
|
+
let s = source;
|
|
3743
|
+
if (s.startsWith("^")) s = s.slice(1);
|
|
3744
|
+
s = s.replace(/^\(\?<!\[[^\]]+\]\)/, "");
|
|
3745
|
+
let boundary = null;
|
|
3746
|
+
const tail = /(?:\(\?!\[([^\]]+)\]\)|\\b)$/.exec(s);
|
|
3747
|
+
if (tail !== null) {
|
|
3748
|
+
const cls = tail[1];
|
|
3749
|
+
if (cls !== void 0 && cls.startsWith("^")) return null;
|
|
3750
|
+
boundary = cls ?? "_0-9A-Za-z";
|
|
3751
|
+
s = s.slice(0, tail.index);
|
|
3752
|
+
}
|
|
3753
|
+
const grouped = /^\(\?:([^()]*)\)$/.exec(s);
|
|
3754
|
+
if (grouped !== null) s = grouped[1];
|
|
3755
|
+
if (s.endsWith("$")) s = s.slice(0, -1);
|
|
3756
|
+
if (!WORDS_RE.test(s)) return null;
|
|
3757
|
+
const words = s.split("|");
|
|
3758
|
+
if (boundary === null && words.length < VOCABULARY_MIN_WORDS) return null;
|
|
3759
|
+
return { words, boundary };
|
|
3760
|
+
}
|
|
3761
|
+
function boundaryMatches(boundary, ch2) {
|
|
3762
|
+
const cp = ch2.codePointAt(0);
|
|
3763
|
+
for (const m of charClassMembers(boundary)) {
|
|
3764
|
+
if (m === "\\w") {
|
|
3765
|
+
if (/[A-Za-z0-9_]/.test(ch2)) return true;
|
|
3766
|
+
continue;
|
|
3767
|
+
}
|
|
3768
|
+
if (m === "\\d") {
|
|
3769
|
+
if (/[0-9]/.test(ch2)) return true;
|
|
3770
|
+
continue;
|
|
3771
|
+
}
|
|
3772
|
+
if (m === "\\s") {
|
|
3773
|
+
if (/\s/.test(ch2)) return true;
|
|
3774
|
+
continue;
|
|
3775
|
+
}
|
|
3776
|
+
const range = /^(.|\\u[0-9a-f]{4})-(.|\\u[0-9a-f]{4})$/.exec(m);
|
|
3777
|
+
if (range !== null) {
|
|
3778
|
+
const dec = (t) => t.startsWith("\\u") ? parseInt(t.slice(2), 16) : t.codePointAt(0);
|
|
3779
|
+
if (cp >= dec(range[1]) && cp <= dec(range[2])) return true;
|
|
3780
|
+
continue;
|
|
3781
|
+
}
|
|
3782
|
+
if (m === ch2) return true;
|
|
3783
|
+
}
|
|
3784
|
+
return false;
|
|
3785
|
+
}
|
|
3786
|
+
function keywordAlternationHazards(words, boundary) {
|
|
3787
|
+
const out = [];
|
|
3788
|
+
for (let i = 0; i < words.length; i++) {
|
|
3789
|
+
for (let j = i + 1; j < words.length; j++) {
|
|
3790
|
+
const a = words[i], b = words[j];
|
|
3791
|
+
if (a.length >= b.length || !b.startsWith(a)) continue;
|
|
3792
|
+
const at = b[a.length];
|
|
3793
|
+
out.push({ shorter: a, longer: b, at, rescuedByBoundary: boundary !== null && boundaryMatches(boundary, at) });
|
|
3794
|
+
}
|
|
3795
|
+
}
|
|
3796
|
+
return out;
|
|
3797
|
+
}
|
|
3798
|
+
function analyzeDuplication(entry, opts) {
|
|
3799
|
+
return analyzeDuplicationRules([[ruleNameOf2(entry) ?? opts?.entryName ?? "<entry>", entry]], opts);
|
|
3800
|
+
}
|
|
3801
|
+
function assertAnalyzable(ruleMap) {
|
|
3802
|
+
for (const [name, rule] of ruleMap) {
|
|
3803
|
+
const def = rule?._def;
|
|
3804
|
+
if (def !== null && typeof def === "object" && typeof def.tag === "string") continue;
|
|
3805
|
+
throw new TypeError(
|
|
3806
|
+
`analyzeDuplicationRules: rule '${name}' is not a combinator (no _def). This analysis walks the COMBINATOR TREE; the value returned by compose()/composeLeaf() is a fused, already-compiled artifact whose entries are parse functions. Pass the rules() map itself (or the map given to compileRuleMap/compileLinkable) instead \u2014 for a composed grammar, analyze each piece's own rules() map.`
|
|
3807
|
+
);
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
function analyzeDuplicationRules(ruleMap, opts) {
|
|
3811
|
+
assertAnalyzable(ruleMap);
|
|
3812
|
+
const minSize = opts?.minSize ?? 3;
|
|
3813
|
+
const maxFindings = opts?.maxFindings ?? 25;
|
|
3814
|
+
const interner = new Interner();
|
|
3815
|
+
const shapeCache = /* @__PURE__ */ new Map();
|
|
3816
|
+
const sizeCache = /* @__PURE__ */ new Map();
|
|
3817
|
+
const shapeOf = (p) => {
|
|
3818
|
+
const hit = shapeCache.get(p);
|
|
3819
|
+
if (hit !== void 0) return hit;
|
|
3820
|
+
const d = p._def;
|
|
3821
|
+
shapeCache.set(p, interner.hole);
|
|
3822
|
+
const kids = childrenOf(d);
|
|
3823
|
+
const id = interner.of(`${payloadKey(p, d)}|${kids.map(shapeOf).join(",")}`);
|
|
3824
|
+
shapeCache.set(p, id);
|
|
3825
|
+
return id;
|
|
3826
|
+
};
|
|
3827
|
+
const sizeOf = (p) => {
|
|
3828
|
+
const hit = sizeCache.get(p);
|
|
3829
|
+
if (hit !== void 0) return hit;
|
|
3830
|
+
sizeCache.set(p, 1);
|
|
3831
|
+
let n = 1;
|
|
3832
|
+
for (const k of childrenOf(p._def)) n += sizeOf(k);
|
|
3833
|
+
sizeCache.set(p, n);
|
|
3834
|
+
return n;
|
|
3835
|
+
};
|
|
3836
|
+
const visited = /* @__PURE__ */ new Map();
|
|
3837
|
+
const visit = (p, rule, path, enclosingNode, enclosingReducer) => {
|
|
3838
|
+
if (visited.has(p)) return;
|
|
3839
|
+
const d = p._def;
|
|
3840
|
+
const own = ruleNameOf2(p);
|
|
3841
|
+
const here = own !== void 0 && own !== rule ? { rule: own, path: "" } : { rule, path };
|
|
3842
|
+
visited.set(p, { p, d, site: here, shape: shapeOf(p), size: sizeOf(p), enclosingNode, enclosingReducer });
|
|
3843
|
+
const inner = d.tag === "node" ? d.type ?? "(anonymous)" : enclosingNode;
|
|
3844
|
+
const innerReducer = enclosingReducer || d.tag === "node" && (d.build !== void 0 || d.buildSrc !== void 0) || d.tag === "transform" || d.tag === "leaf";
|
|
3845
|
+
const kids = childrenOf(d);
|
|
3846
|
+
kids.forEach((k, i) => {
|
|
3847
|
+
const seg = segment(d, i);
|
|
3848
|
+
visit(k, here.rule, here.path === "" ? seg : `${here.path} \u203A ${seg}`, inner, innerReducer);
|
|
3849
|
+
});
|
|
3850
|
+
if (d.tag === "lazy") {
|
|
3851
|
+
try {
|
|
3852
|
+
const target = d.thunk();
|
|
3853
|
+
visit(target, ruleNameOf2(target) ?? ruleNameOf2(p) ?? here.rule, "", null, false);
|
|
3854
|
+
} catch {
|
|
3855
|
+
}
|
|
3856
|
+
}
|
|
3857
|
+
};
|
|
3858
|
+
for (const [name, root] of ruleMap) visit(root, ruleNameOf2(root) ?? name, "", null, false);
|
|
3859
|
+
const accept = new Set(opts?.accept ?? []);
|
|
3860
|
+
const used = /* @__PURE__ */ new Set();
|
|
3861
|
+
const keep = (f) => {
|
|
3862
|
+
if (!accept.has(f.id)) return true;
|
|
3863
|
+
used.add(f.id);
|
|
3864
|
+
return false;
|
|
3865
|
+
};
|
|
3866
|
+
const duplicates = findExactDuplicates(visited, minSize);
|
|
3867
|
+
const nearDuplicates = findNearDuplicates(visited, interner, shapeOf, minSize);
|
|
3868
|
+
const regexFragments = findRegexFragments(visited);
|
|
3869
|
+
const regexClasses = findRegexClasses(visited);
|
|
3870
|
+
const overlaps = findOverlaps(visited, shapeOf, opts?.resolveRef);
|
|
3871
|
+
const rewrites = findRewrites(visited, shapeOf);
|
|
3872
|
+
const divergentNodes = findDivergentNodes(visited, shapeOf);
|
|
3873
|
+
const structureLoss = findStructureLoss(visited, opts?.resolveRef);
|
|
3874
|
+
const keywordRegexes = findKeywordRegexes(visited);
|
|
3875
|
+
const subsume = (fs) => {
|
|
3876
|
+
const covered = /* @__PURE__ */ new Set();
|
|
3877
|
+
const surviving = /* @__PURE__ */ new Set();
|
|
3878
|
+
for (const f of [...fs].sort((a, b) => b.savings - a.savings)) {
|
|
3879
|
+
if (f._members.every((m) => covered.has(m))) continue;
|
|
3880
|
+
surviving.add(f.id);
|
|
3881
|
+
for (const m of f._members) markSubtree(m, covered);
|
|
3882
|
+
}
|
|
3883
|
+
return surviving;
|
|
3884
|
+
};
|
|
3885
|
+
const survivingExact = subsume(duplicates);
|
|
3886
|
+
const survivingNear = subsume(nearDuplicates);
|
|
3887
|
+
const report = {
|
|
3888
|
+
duplicates: duplicates.filter((f) => survivingExact.has(f.id)).filter(keep).slice(0, maxFindings).map(stripMembers),
|
|
3889
|
+
nearDuplicates: nearDuplicates.filter((f) => survivingNear.has(f.id)).filter(keep).slice(0, maxFindings).map(stripMembers),
|
|
3890
|
+
regexFragments: regexFragments.filter(keep).slice(0, maxFindings),
|
|
3891
|
+
regexClasses: regexClasses.filter(keep).slice(0, maxFindings),
|
|
3892
|
+
overlaps: overlaps.filter(keep).slice(0, maxFindings),
|
|
3893
|
+
rewrites: rewrites.filter(keep).slice(0, maxFindings),
|
|
3894
|
+
divergentNodes: divergentNodes.filter(keep).slice(0, maxFindings),
|
|
3895
|
+
structureLoss: structureLoss.filter(keep).slice(0, maxFindings),
|
|
3896
|
+
keywordRegexes: keywordRegexes.filter(keep).slice(0, maxFindings),
|
|
3897
|
+
acceptedUnused: [...accept].filter((id) => !used.has(id)),
|
|
3898
|
+
stats: { rules: ruleMap.length, nodes: visited.size, shapes: new Set([...visited.values()].map((v2) => v2.shape)).size }
|
|
3899
|
+
};
|
|
3900
|
+
return report;
|
|
3901
|
+
}
|
|
3902
|
+
function markSubtree(p, into) {
|
|
3903
|
+
if (into.has(p)) return;
|
|
3904
|
+
into.add(p);
|
|
3905
|
+
for (const k of childrenOf(p._def)) markSubtree(k, into);
|
|
3906
|
+
}
|
|
3907
|
+
var stripMembers = (f) => {
|
|
3908
|
+
const { _members, ...rest } = f;
|
|
3909
|
+
void _members;
|
|
3910
|
+
return rest;
|
|
3911
|
+
};
|
|
3912
|
+
function findExactDuplicates(visited, minSize) {
|
|
3913
|
+
const byShape = /* @__PURE__ */ new Map();
|
|
3914
|
+
for (const v2 of visited.values()) {
|
|
3915
|
+
if (v2.size < minSize) continue;
|
|
3916
|
+
const list = byShape.get(v2.shape);
|
|
3917
|
+
if (list === void 0) byShape.set(v2.shape, [v2]);
|
|
3918
|
+
else list.push(v2);
|
|
3919
|
+
}
|
|
3920
|
+
const out = [];
|
|
3921
|
+
for (const group of byShape.values()) {
|
|
3922
|
+
if (group.length < 2) continue;
|
|
3923
|
+
const size = group[0].size;
|
|
3924
|
+
out.push({
|
|
3925
|
+
kind: "exact-duplicate",
|
|
3926
|
+
id: `exact-duplicate:${siteToString(group[0].site)}`,
|
|
3927
|
+
size,
|
|
3928
|
+
count: group.length,
|
|
3929
|
+
savings: (group.length - 1) * size,
|
|
3930
|
+
shape: clamp(render(group[0].p)),
|
|
3931
|
+
sites: group.map((g) => g.site),
|
|
3932
|
+
suggestion: `${group.length} DISTINCT instances build this identical ${size}-node shape. Bind it to one const and reference that \u2014 hoisting removes ${(group.length - 1) * size} nodes and makes a future edit land in one place instead of ${group.length}.`,
|
|
3933
|
+
_members: group.map((g) => g.p)
|
|
3934
|
+
});
|
|
3935
|
+
}
|
|
3936
|
+
return out.sort((a, b) => b.savings - a.savings);
|
|
3937
|
+
}
|
|
3938
|
+
function findNearDuplicates(visited, interner, shapeOf, minSize) {
|
|
3939
|
+
const holeCache = /* @__PURE__ */ new Map();
|
|
3940
|
+
const holesOf = (p) => {
|
|
3941
|
+
const hit = holeCache.get(p);
|
|
3942
|
+
if (hit !== void 0) return hit;
|
|
3943
|
+
holeCache.set(p, []);
|
|
3944
|
+
const d = p._def;
|
|
3945
|
+
const kids = childrenOf(d);
|
|
3946
|
+
const kidShapes = kids.map(shapeOf);
|
|
3947
|
+
const payload = payloadKey(p, d);
|
|
3948
|
+
const out2 = [];
|
|
3949
|
+
kids.forEach((k, i) => {
|
|
3950
|
+
for (const inner of [interner.hole, ...holesOf(k)]) {
|
|
3951
|
+
const arr = kidShapes.slice();
|
|
3952
|
+
arr[i] = inner;
|
|
3953
|
+
out2.push(interner.of(`${payload}|${arr.join(",")}`));
|
|
3954
|
+
}
|
|
3955
|
+
});
|
|
3956
|
+
holeCache.set(p, out2);
|
|
3957
|
+
return out2;
|
|
3958
|
+
};
|
|
3959
|
+
const byHole = /* @__PURE__ */ new Map();
|
|
3960
|
+
for (const v2 of visited.values()) {
|
|
3961
|
+
if (v2.size < minSize) continue;
|
|
3962
|
+
for (const h of holesOf(v2.p)) {
|
|
3963
|
+
const list = byHole.get(h);
|
|
3964
|
+
if (list === void 0) byHole.set(h, [v2]);
|
|
3965
|
+
else list.push(v2);
|
|
3966
|
+
}
|
|
3967
|
+
}
|
|
3968
|
+
const out = [];
|
|
3969
|
+
const seenGroups = /* @__PURE__ */ new Set();
|
|
3970
|
+
for (const group of byHole.values()) {
|
|
3971
|
+
if (group.length < 2) continue;
|
|
3972
|
+
const shapes = new Set(group.map((g) => g.shape));
|
|
3973
|
+
if (shapes.size < 2) continue;
|
|
3974
|
+
const perShape = /* @__PURE__ */ new Map();
|
|
3975
|
+
for (const g of group) if (!perShape.has(g.shape)) perShape.set(g.shape, g);
|
|
3976
|
+
const members = [...perShape.values()];
|
|
3977
|
+
const key = members.map((m) => m.shape).sort((a, b) => a - b).join(",");
|
|
3978
|
+
if (seenGroups.has(key)) continue;
|
|
3979
|
+
seenGroups.add(key);
|
|
3980
|
+
const slot = findDivergentSlot(members.map((m) => m.p), shapeOf);
|
|
3981
|
+
if (slot === null) continue;
|
|
3982
|
+
const sharedSize = Math.min(...members.map((m) => m.size)) - slot.slotSize;
|
|
3983
|
+
if (sharedSize < minSize) continue;
|
|
3984
|
+
out.push({
|
|
3985
|
+
kind: "near-duplicate",
|
|
3986
|
+
id: `near-duplicate:${siteToString(members[0].site)}`,
|
|
3987
|
+
sharedSize,
|
|
3988
|
+
count: members.length,
|
|
3989
|
+
savings: (members.length - 1) * sharedSize,
|
|
3990
|
+
shape: clamp(renderWithHole(members[0].p, slot.path)),
|
|
3991
|
+
slotPath: slot.path.map((i, k) => segment(slot.defs[k], i)).join(" \u203A "),
|
|
3992
|
+
variants: slot.variants.map((v2) => clamp(render(v2))),
|
|
3993
|
+
sites: members.map((m) => m.site),
|
|
3994
|
+
suggestion: `${members.length} productions share this ${sharedSize}-node scaffolding and differ ONLY at \`${slot.path.map((i, k) => segment(slot.defs[k], i)).join(" \u203A ")}\`. That is one production whose varying slot is a \`choice(${slot.variants.map((v2) => clamp(render(v2, 1))).join(", ")})\` \u2014 not ${members.length} copies of the scaffolding. Re-check the AST: a single production emits one node type where the clones may emit several.`,
|
|
3995
|
+
_members: members.map((m) => m.p)
|
|
3996
|
+
});
|
|
3997
|
+
}
|
|
3998
|
+
return out.sort((a, b) => b.savings - a.savings);
|
|
3999
|
+
}
|
|
4000
|
+
function findDivergentSlot(members, shapeOf) {
|
|
4001
|
+
const path = [];
|
|
4002
|
+
const defs = [];
|
|
4003
|
+
let cur = [...members];
|
|
4004
|
+
for (let guard2 = 0; guard2 < 64; guard2++) {
|
|
4005
|
+
const d0 = cur[0]._def;
|
|
4006
|
+
const kidLists = cur.map((c) => childrenOf(c._def));
|
|
4007
|
+
const arity = kidLists[0].length;
|
|
4008
|
+
if (kidLists.some((k) => k.length !== arity) || arity === 0) break;
|
|
4009
|
+
const diff = [];
|
|
4010
|
+
for (let i2 = 0; i2 < arity; i2++) {
|
|
4011
|
+
const s = shapeOf(kidLists[0][i2]);
|
|
4012
|
+
if (kidLists.some((k) => shapeOf(k[i2]) !== s)) diff.push(i2);
|
|
4013
|
+
}
|
|
4014
|
+
if (diff.length !== 1) break;
|
|
4015
|
+
const i = diff[0];
|
|
4016
|
+
path.push(i);
|
|
4017
|
+
defs.push(d0);
|
|
4018
|
+
cur = kidLists.map((k) => k[i]);
|
|
4019
|
+
const nextArity = childrenOf(cur[0]._def).length;
|
|
4020
|
+
const samePayload = cur.every((c) => payloadKey(c, c._def) === payloadKey(cur[0], cur[0]._def));
|
|
4021
|
+
if (!samePayload || nextArity === 0) break;
|
|
4022
|
+
}
|
|
4023
|
+
if (path.length === 0) return null;
|
|
4024
|
+
let slotSize = 0;
|
|
4025
|
+
const sizeOf = (p) => {
|
|
4026
|
+
let n = 1;
|
|
4027
|
+
for (const k of childrenOf(p._def)) n += sizeOf(k);
|
|
4028
|
+
return n;
|
|
4029
|
+
};
|
|
4030
|
+
for (const c of cur) slotSize = Math.max(slotSize, sizeOf(c));
|
|
4031
|
+
return { path, defs, variants: cur, slotSize };
|
|
4032
|
+
}
|
|
4033
|
+
function renderWithHole(p, path, depth = 0) {
|
|
4034
|
+
if (depth === path.length) return "\u2039slot\u203A";
|
|
4035
|
+
const d = p._def;
|
|
4036
|
+
const kids = childrenOf(d);
|
|
4037
|
+
const idx = path[depth];
|
|
4038
|
+
const parts = kids.map((k, i) => i === idx ? renderWithHole(k, path, depth + 1) : render(k, 2));
|
|
4039
|
+
switch (d.tag) {
|
|
4040
|
+
case "sequence":
|
|
4041
|
+
return `sequence(${parts.join(", ")})`;
|
|
4042
|
+
case "choice":
|
|
4043
|
+
return `choice(${parts.join(", ")})`;
|
|
4044
|
+
case "node":
|
|
4045
|
+
return `node(${d.type ? `'${d.type}', ` : ""}${parts[0] ?? ""})`;
|
|
4046
|
+
default:
|
|
4047
|
+
return `${d.tag}(${parts.join(", ")})`;
|
|
4048
|
+
}
|
|
4049
|
+
}
|
|
4050
|
+
var MAX_RUN = 32;
|
|
4051
|
+
function findRegexFragments(visited) {
|
|
4052
|
+
const byRun = /* @__PURE__ */ new Map();
|
|
4053
|
+
for (const v2 of visited.values()) {
|
|
4054
|
+
const d = v2.d;
|
|
4055
|
+
if (d.tag !== "regex") continue;
|
|
4056
|
+
const runs = /* @__PURE__ */ new Set();
|
|
4057
|
+
for (const branches of alternationGroups(d.source)) {
|
|
4058
|
+
if (branches.length >= 2) runs.add(branches.join("|"));
|
|
4059
|
+
for (let i = 0; i < branches.length; i++) {
|
|
4060
|
+
for (let n = 2; n <= Math.min(MAX_RUN, branches.length - i); n++) {
|
|
4061
|
+
const run2 = branches.slice(i, i + n).join("|");
|
|
4062
|
+
if (run2.length < 4) continue;
|
|
4063
|
+
runs.add(run2);
|
|
4064
|
+
}
|
|
4065
|
+
}
|
|
4066
|
+
}
|
|
4067
|
+
for (const run2 of runs) {
|
|
4068
|
+
let e = byRun.get(run2);
|
|
4069
|
+
if (e === void 0) {
|
|
4070
|
+
e = { occ: [], nodes: /* @__PURE__ */ new Set(), branches: run2.split("|").length };
|
|
4071
|
+
byRun.set(run2, e);
|
|
4072
|
+
}
|
|
4073
|
+
if (e.nodes.has(v2.p)) continue;
|
|
4074
|
+
e.nodes.add(v2.p);
|
|
4075
|
+
e.occ.push({ site: v2.site, source: d.source });
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
const candidates = [...byRun.entries()].filter(([, e]) => e.occ.length >= 2).map(([run2, e]) => ({ run: run2, e, savings: (e.occ.length - 1) * run2.length })).sort((a, b) => b.e.occ.length - a.e.occ.length || b.savings - a.savings || b.run.length - a.run.length);
|
|
4079
|
+
const kept = [];
|
|
4080
|
+
for (const c of candidates) {
|
|
4081
|
+
if (kept.some((k) => k.e.occ.length >= c.e.occ.length && `|${k.run}|`.includes(`|${c.run}|`))) continue;
|
|
4082
|
+
kept.push(c);
|
|
4083
|
+
}
|
|
4084
|
+
return kept.map(({ run: run2, e }) => ({
|
|
4085
|
+
kind: "regex-fragment",
|
|
4086
|
+
id: `regex-fragment:${run2}`,
|
|
4087
|
+
fragment: run2,
|
|
4088
|
+
branches: e.branches,
|
|
4089
|
+
count: e.occ.length,
|
|
4090
|
+
savings: (e.occ.length - 1) * run2.length,
|
|
4091
|
+
sources: e.occ.map((o) => `/${o.source}/`),
|
|
4092
|
+
sites: e.occ.map((o) => o.site),
|
|
4093
|
+
suggestion: `this ${e.branches}-branch alternation is re-spelled in ${e.occ.length} DISTINCT regex() terminals. Hoist it to one shared source string and interpolate it (\`new RegExp(\\\`\u2026\\\${OP}\u2026\\\`)\`) or lift the shared part into its own terminal \u2014 an edit to the operator set currently has to land in ${e.occ.length} places, and the analysis cannot tell you when one of them drifts.`
|
|
4094
|
+
}));
|
|
4095
|
+
}
|
|
4096
|
+
function extractCharClasses(src) {
|
|
4097
|
+
const out = [];
|
|
4098
|
+
let i = 0;
|
|
4099
|
+
while (i < src.length) {
|
|
4100
|
+
const c = src[i];
|
|
4101
|
+
if (c === "\\") {
|
|
4102
|
+
i += 2;
|
|
4103
|
+
continue;
|
|
4104
|
+
}
|
|
4105
|
+
if (c !== "[") {
|
|
4106
|
+
i++;
|
|
4107
|
+
continue;
|
|
4108
|
+
}
|
|
4109
|
+
let j = i + 1;
|
|
4110
|
+
if (src[j] === "^") j++;
|
|
4111
|
+
if (src[j] === "]") j++;
|
|
4112
|
+
while (j < src.length && src[j] !== "]") {
|
|
4113
|
+
if (src[j] === "\\") j++;
|
|
4114
|
+
j++;
|
|
4115
|
+
}
|
|
4116
|
+
out.push(src.slice(i + 1, j));
|
|
4117
|
+
i = j + 1;
|
|
4118
|
+
}
|
|
4119
|
+
return out;
|
|
4120
|
+
}
|
|
4121
|
+
function charClassMembers(body) {
|
|
4122
|
+
const esc = (ch2) => {
|
|
4123
|
+
const cp = ch2.codePointAt(0);
|
|
4124
|
+
return cp >= 128 ? `\\u${cp.toString(16).padStart(4, "0")}` : ch2;
|
|
4125
|
+
};
|
|
4126
|
+
const atoms = [];
|
|
4127
|
+
let i = 0;
|
|
4128
|
+
while (i < body.length) {
|
|
4129
|
+
if (body[i] === "\\") {
|
|
4130
|
+
const m = /^\\(?:u\{([0-9a-fA-F]+)\}|u([0-9a-fA-F]{4})|x([0-9a-fA-F]{2}))/.exec(body.slice(i));
|
|
4131
|
+
if (m !== null) {
|
|
4132
|
+
const cp = parseInt(m[1] ?? m[2] ?? m[3], 16);
|
|
4133
|
+
atoms.push(cp >= 128 ? `\\u${cp.toString(16).padStart(4, "0")}` : String.fromCodePoint(cp));
|
|
4134
|
+
i += m[0].length;
|
|
4135
|
+
continue;
|
|
4136
|
+
}
|
|
4137
|
+
atoms.push(body.slice(i, i + 2));
|
|
4138
|
+
i += 2;
|
|
4139
|
+
continue;
|
|
4140
|
+
}
|
|
4141
|
+
atoms.push(esc(body[i]));
|
|
4142
|
+
i++;
|
|
4143
|
+
}
|
|
4144
|
+
const members = [];
|
|
4145
|
+
for (let k = 0; k < atoms.length; k++) {
|
|
4146
|
+
if (k + 2 < atoms.length && atoms[k + 1] === "-" && atoms[k + 2] !== void 0) {
|
|
4147
|
+
members.push(`${atoms[k]}-${atoms[k + 2]}`);
|
|
4148
|
+
k += 2;
|
|
4149
|
+
continue;
|
|
4150
|
+
}
|
|
4151
|
+
members.push(atoms[k]);
|
|
4152
|
+
}
|
|
4153
|
+
return members;
|
|
4154
|
+
}
|
|
4155
|
+
var CLASS_MIN_MEMBERS = 2;
|
|
4156
|
+
function findRegexClasses(visited) {
|
|
4157
|
+
const spellings = /* @__PURE__ */ new Map();
|
|
4158
|
+
for (const v2 of visited.values()) {
|
|
4159
|
+
if (v2.d.tag !== "regex") continue;
|
|
4160
|
+
for (const body of new Set(extractCharClasses(v2.d.source))) {
|
|
4161
|
+
const members = charClassMembers(body);
|
|
4162
|
+
if (members.length < CLASS_MIN_MEMBERS) continue;
|
|
4163
|
+
const key = [...new Set(members)].sort().join("");
|
|
4164
|
+
let s = spellings.get(key);
|
|
4165
|
+
if (s === void 0) {
|
|
4166
|
+
s = { source: body, members, key, nodes: /* @__PURE__ */ new Set(), sites: [] };
|
|
4167
|
+
spellings.set(key, s);
|
|
4168
|
+
}
|
|
4169
|
+
if (s.nodes.has(v2.p)) continue;
|
|
4170
|
+
s.nodes.add(v2.p);
|
|
4171
|
+
s.sites.push(v2.site);
|
|
4172
|
+
}
|
|
4173
|
+
}
|
|
4174
|
+
const MAX_DELTA = 3;
|
|
4175
|
+
const MIN_JACCARD = 0.6;
|
|
4176
|
+
const all = [...spellings.values()];
|
|
4177
|
+
const parent = all.map((_, i) => i);
|
|
4178
|
+
const find = (i) => {
|
|
4179
|
+
while (parent[i] !== i) {
|
|
4180
|
+
parent[i] = parent[parent[i]];
|
|
4181
|
+
i = parent[i];
|
|
4182
|
+
}
|
|
4183
|
+
return i;
|
|
4184
|
+
};
|
|
4185
|
+
const union2 = (a, b) => {
|
|
4186
|
+
const ra = find(a), rb = find(b);
|
|
4187
|
+
if (ra !== rb) parent[ra] = rb;
|
|
4188
|
+
};
|
|
4189
|
+
for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) {
|
|
4190
|
+
if (all[i].members.includes("^") !== all[j].members.includes("^")) continue;
|
|
4191
|
+
const A = new Set(all[i].members), B = new Set(all[j].members);
|
|
4192
|
+
let shared = 0;
|
|
4193
|
+
for (const m of A) if (B.has(m)) shared++;
|
|
4194
|
+
const delta = A.size - shared + (B.size - shared);
|
|
4195
|
+
const jaccard = shared / (shared + delta);
|
|
4196
|
+
if (shared >= 2 && delta > 0 && delta <= MAX_DELTA && jaccard >= MIN_JACCARD) union2(i, j);
|
|
4197
|
+
}
|
|
4198
|
+
const clusters = /* @__PURE__ */ new Map();
|
|
4199
|
+
all.forEach((_, i) => {
|
|
4200
|
+
const r = find(i);
|
|
4201
|
+
const list = clusters.get(r);
|
|
4202
|
+
if (list === void 0) clusters.set(r, [i]);
|
|
4203
|
+
else list.push(i);
|
|
4204
|
+
});
|
|
4205
|
+
const out = [];
|
|
4206
|
+
for (const idxs of clusters.values()) {
|
|
4207
|
+
const members = idxs.map((i) => all[i]).sort((a, b) => b.nodes.size - a.nodes.size);
|
|
4208
|
+
const total = members.reduce((n, m) => n + m.nodes.size, 0);
|
|
4209
|
+
const drifted = members.length > 1;
|
|
4210
|
+
if (!drifted && total < 2) continue;
|
|
4211
|
+
const base = new Set(members[0].members);
|
|
4212
|
+
const variants = members.map((m) => {
|
|
4213
|
+
const mine = new Set(m.members);
|
|
4214
|
+
const plus = [...mine].filter((x) => !base.has(x));
|
|
4215
|
+
const minus = [...base].filter((x) => !mine.has(x));
|
|
4216
|
+
return {
|
|
4217
|
+
source: m.source,
|
|
4218
|
+
delta: m === members[0] ? "(reference)" : `${plus.map((p) => `+\`${p}\``).join(" ")}${plus.length > 0 && minus.length > 0 ? " " : ""}${minus.map((p) => `-\`${p}\``).join(" ")}` || "(same members, different spelling)",
|
|
4219
|
+
count: m.nodes.size,
|
|
4220
|
+
sites: m.sites
|
|
4221
|
+
};
|
|
4222
|
+
});
|
|
4223
|
+
const bmpCeiling = members.some((m) => m.members.some((x) => x.endsWith("-\\uffff")));
|
|
4224
|
+
out.push({
|
|
4225
|
+
kind: "regex-class",
|
|
4226
|
+
id: `regex-class:${members[0].key}`,
|
|
4227
|
+
canonical: members[0].source,
|
|
4228
|
+
variants,
|
|
4229
|
+
count: total,
|
|
4230
|
+
drifted,
|
|
4231
|
+
bmpCeiling,
|
|
4232
|
+
suggestion: [
|
|
4233
|
+
drifted ? `${members.length} NEARLY-identical spellings of one class, across ${total} regex() terminals. They differ by ${variants.slice(1).map((v2) => v2.delta).join("; ")} \u2014 which is drift, not intent, unless every difference is deliberate. Two classes this close cannot be told apart by reading, so one of them is probably wrong and the tests cannot say which.` : `this class is re-spelled in ${total} DISTINCT regex() terminals. Extract it once \u2014 a named sub-leaf, or an interpolated source constant \u2014 so a range fix lands in one place. Re-spelling is how the near-identical variants elsewhere in this report came to exist.`,
|
|
4234
|
+
`Prefer the shared recognition surface where one already covers this class rather than a local extraction.`,
|
|
4235
|
+
bmpCeiling ? `The class tops out at U+FFFF, so astral-plane characters (emoji, many CJK extensions) fall OUTSIDE it. Widening the ceiling is exactly the kind of edit that has to reach every spelling.` : "",
|
|
4236
|
+
`Single-regex hygiene (duplicate class members, obscure ranges, a missing \`u\` flag) is \`eslint-plugin-regexp\`'s job and is not duplicated here \u2014 it sees one regex at a time, which is why it cannot see this.`
|
|
4237
|
+
].filter((s) => s !== "").join(" ")
|
|
4238
|
+
});
|
|
4239
|
+
}
|
|
4240
|
+
return out.sort((a, b) => Number(b.drifted) - Number(a.drifted) || b.count - a.count);
|
|
4241
|
+
}
|
|
4242
|
+
function intersects3(a, b) {
|
|
4243
|
+
if (a.kind === "any" || b.kind === "any") return true;
|
|
4244
|
+
if (a.kind === "empty" || b.kind === "empty") return false;
|
|
4245
|
+
for (const ra of a.ranges) for (const rb of b.ranges) if (ra.lo <= rb.hi && rb.lo <= ra.hi) return true;
|
|
4246
|
+
return false;
|
|
4247
|
+
}
|
|
4248
|
+
function intersection2(a, b) {
|
|
4249
|
+
if (a.kind === "any") return b;
|
|
4250
|
+
if (b.kind === "any") return a;
|
|
4251
|
+
if (a.kind === "empty" || b.kind === "empty") return { kind: "empty" };
|
|
4252
|
+
const ranges = [];
|
|
4253
|
+
for (const ra of a.ranges) for (const rb of b.ranges) {
|
|
4254
|
+
const lo = Math.max(ra.lo, rb.lo);
|
|
4255
|
+
const hi = Math.min(ra.hi, rb.hi);
|
|
4256
|
+
if (lo <= hi) ranges.push({ lo, hi });
|
|
4257
|
+
}
|
|
4258
|
+
return ranges.length === 0 ? { kind: "empty" } : { kind: "ranges", ranges };
|
|
4259
|
+
}
|
|
4260
|
+
function termsOf(arm) {
|
|
4261
|
+
let cur = arm;
|
|
4262
|
+
for (; ; ) {
|
|
4263
|
+
const d2 = cur._def;
|
|
4264
|
+
if (d2.tag === "node" || d2.tag === "transform" || d2.tag === "label" || d2.tag === "attempt" || d2.tag === "leaf") {
|
|
4265
|
+
cur = d2.parser;
|
|
4266
|
+
continue;
|
|
4267
|
+
}
|
|
4268
|
+
break;
|
|
4269
|
+
}
|
|
4270
|
+
const d = cur._def;
|
|
4271
|
+
return d.tag === "sequence" ? d.parsers : [cur];
|
|
4272
|
+
}
|
|
4273
|
+
function leadingRegex(arm) {
|
|
4274
|
+
const t = termsOf(arm)[0];
|
|
4275
|
+
return t !== void 0 && t._def.tag === "regex";
|
|
4276
|
+
}
|
|
4277
|
+
function findOverlaps(visited, shapeOf, resolve) {
|
|
4278
|
+
const out = [];
|
|
4279
|
+
for (const v2 of visited.values()) {
|
|
4280
|
+
const d = v2.d;
|
|
4281
|
+
if (d.tag !== "choice") continue;
|
|
4282
|
+
const arms = d.parsers;
|
|
4283
|
+
const fs = arms.map((a) => firstSetOf(a, /* @__PURE__ */ new Set(), resolve));
|
|
4284
|
+
const strategy = d.strategy;
|
|
4285
|
+
for (let i = 0; i < arms.length; i++) {
|
|
4286
|
+
for (let j = i + 1; j < arms.length; j++) {
|
|
4287
|
+
const A = fs[i], B = fs[j];
|
|
4288
|
+
if (A.kind === "any" || B.kind === "any") continue;
|
|
4289
|
+
if (!intersects3(A, B)) continue;
|
|
4290
|
+
const ta = termsOf(arms[i]), tb = termsOf(arms[j]);
|
|
4291
|
+
let shared = 0;
|
|
4292
|
+
while (shared < ta.length && shared < tb.length && shapeOf(ta[shared]) === shapeOf(tb[shared])) shared++;
|
|
4293
|
+
const handled = strategy?.tag === "sharedPrefix" && Array.isArray(strategy.members) && strategy.members.includes(i) && strategy.members.includes(j);
|
|
4294
|
+
const regexPair = leadingRegex(arms[i]) && leadingRegex(arms[j]);
|
|
4295
|
+
out.push({
|
|
4296
|
+
kind: "arm-overlap",
|
|
4297
|
+
id: `arm-overlap:${siteToString(v2.site)}:${i}-${j}`,
|
|
4298
|
+
site: v2.site,
|
|
4299
|
+
a: i,
|
|
4300
|
+
b: j,
|
|
4301
|
+
on: intersection2(A, B),
|
|
4302
|
+
sharedLeadingTerms: shared,
|
|
4303
|
+
sharedPrefix: shared > 0 ? clamp(ta.slice(0, shared).map((t) => render(t, 2)).join(", ")) : null,
|
|
4304
|
+
handledByStrategy: handled,
|
|
4305
|
+
regexPair,
|
|
4306
|
+
suggestion: overlapSuggestion(shared, handled, regexPair)
|
|
4307
|
+
});
|
|
4308
|
+
}
|
|
4309
|
+
}
|
|
4310
|
+
}
|
|
4311
|
+
return out.sort((a, b) => b.sharedLeadingTerms - a.sharedLeadingTerms);
|
|
4312
|
+
}
|
|
4313
|
+
function overlapSuggestion(shared, handled, regexPair) {
|
|
4314
|
+
if (shared > 0 && handled)
|
|
4315
|
+
return `the arms spell ${shared} identical leading term(s). parseman's \`sharedPrefix\` strategy already recognizes that prefix ONCE at runtime, so this costs nothing at parse time \u2014 it is a READABILITY finding: left-factoring into \`sequence(prefix, choice(\u2026))\` says in the grammar what the compiler had to infer.`;
|
|
4316
|
+
if (shared > 0)
|
|
4317
|
+
return `the arms spell ${shared} identical leading term(s) but do NOT qualify for the \`sharedPrefix\` strategy (it needs every arm to be a bare \`sequence\` starting with the same concrete terminal). Left-factor into \`sequence(prefix, choice(\u2026))\` \u2014 that both removes the re-spelling and lets the inner choice dispatch on its own first char.`;
|
|
4318
|
+
if (regexPair)
|
|
4319
|
+
return `two regex() arms whose character classes intersect. Nothing dispatches between them: the first is tried, and on failure the second re-scans the same position. Two regexes that can start on the same char are usually one terminal \u2014 merge them, or make the distinction explicit with a leading literal.`;
|
|
4320
|
+
return `the arms can start on the same character, so the choice cannot dispatch between them: on those chars the first arm is entered speculatively and rolled back before the second is tried. Give the arms disjoint leading terminals, or left-factor the common part out.`;
|
|
4321
|
+
}
|
|
4322
|
+
var PERF_ARM = "removes a speculative arm: on every input position reaching this choice, the deleted arm no longer costs a ctx save, a child-array push and a rollback before the surviving arm is tried. The saving scales with how often the choice is reached and how much the doomed arm consumes before failing.";
|
|
4323
|
+
var PERF_NONE = "";
|
|
4324
|
+
function findRewrites(visited, shapeOf) {
|
|
4325
|
+
const out = [];
|
|
4326
|
+
const push = (f, at) => {
|
|
4327
|
+
const site = siteToString(f.site);
|
|
4328
|
+
out.push({ kind: "rewrite", id: `rewrite:${f.rewrite}:${site}${at === void 0 ? "" : `:${at}`}`, ...f });
|
|
4329
|
+
};
|
|
4330
|
+
for (const v2 of visited.values()) {
|
|
4331
|
+
const d = v2.d;
|
|
4332
|
+
const site = v2.site;
|
|
4333
|
+
if (d.tag === "optional" || d.tag === "many" || d.tag === "oneOrMore") {
|
|
4334
|
+
const inner = d.parser;
|
|
4335
|
+
const id = inner._def;
|
|
4336
|
+
const collapsed = collapseRepeat(d, id);
|
|
4337
|
+
if (collapsed !== null) {
|
|
4338
|
+
push({
|
|
4339
|
+
rewrite: "idempotent-nesting",
|
|
4340
|
+
site,
|
|
4341
|
+
from: clamp(render(v2.p, 2)),
|
|
4342
|
+
to: collapsed,
|
|
4343
|
+
astNeutral: false,
|
|
4344
|
+
perf: "the outer wrapper still runs its own bookkeeping (and, for `many(optional(X))`, guards a zero-width iteration on every pass) for a nullability the inner combinator already has.",
|
|
4345
|
+
bug: id.tag === "optional" && d.tag === "many",
|
|
4346
|
+
suggestion: `\`${clamp(render(v2.p, 2))}\` is exactly \`${collapsed}\`. ${id.tag === "optional" && d.tag === "many" ? "The nested form is also a zero-width-iteration hazard: the inner `optional` succeeds consuming nothing, which the repeat has to detect and break on every pass." : ""} Candidate \u2014 verify AST identity: the collapsed form produces ONE level of array/undefined where the nested form produces two.`
|
|
4347
|
+
});
|
|
4348
|
+
}
|
|
4349
|
+
}
|
|
4350
|
+
if ((d.tag === "choice" || d.tag === "sequence") && d.parsers.length === 1) {
|
|
4351
|
+
push({
|
|
4352
|
+
rewrite: "single-element",
|
|
4353
|
+
site,
|
|
4354
|
+
from: clamp(render(v2.p, 2)),
|
|
4355
|
+
to: d.tag === "choice" ? clamp(render(d.parsers[0], 2)) : `${clamp(render(d.parsers[0], 2))} (note: sequence() of one still wraps its value in a 1-tuple)`,
|
|
4356
|
+
astNeutral: d.tag === "choice",
|
|
4357
|
+
perf: d.tag === "choice" ? "a one-arm choice still emits its dispatch scaffolding." : PERF_NONE,
|
|
4358
|
+
bug: false,
|
|
4359
|
+
suggestion: d.tag === "choice" ? "a `choice` with one arm IS that arm \u2014 the wrapper only adds dispatch scaffolding. Safe to unwrap (choice forwards its arm value unchanged)." : "a `sequence` with one element only exists to build a 1-tuple. If nothing reads that tuple, drop the wrapper \u2014 CANDIDATE, verify AST identity first."
|
|
4360
|
+
});
|
|
4361
|
+
}
|
|
4362
|
+
if (d.tag !== "choice") continue;
|
|
4363
|
+
const arms = d.parsers;
|
|
4364
|
+
const armShapes = arms.map(shapeOf);
|
|
4365
|
+
const strategy = d.strategy;
|
|
4366
|
+
for (let i = 0; i < arms.length; i++) for (let j = i + 1; j < arms.length; j++) {
|
|
4367
|
+
if (armShapes[i] !== armShapes[j]) continue;
|
|
4368
|
+
push({
|
|
4369
|
+
rewrite: "duplicate-arm",
|
|
4370
|
+
site,
|
|
4371
|
+
from: `choice(\u2026 arm[${i}] \u2026, arm[${j}] \u2026)`,
|
|
4372
|
+
to: `delete arm[${j}]`,
|
|
4373
|
+
astNeutral: true,
|
|
4374
|
+
perf: PERF_ARM,
|
|
4375
|
+
bug: true,
|
|
4376
|
+
suggestion: `arm[${i}] and arm[${j}] are the SAME shape (\`${clamp(render(arms[i], 2))}\`). Under ordered choice arm[${i}] always wins, so arm[${j}] is unreachable \u2014 delete it. This is AST-neutral by construction: an arm that can never be selected contributes nothing to any parse.`
|
|
4377
|
+
}, `${i}-${j}`);
|
|
4378
|
+
}
|
|
4379
|
+
for (let i = 0; i < arms.length; i++) for (let j = 0; j < arms.length; j++) {
|
|
4380
|
+
if (i >= j) continue;
|
|
4381
|
+
if (armShapes[i] === armShapes[j]) continue;
|
|
4382
|
+
const ta = termsOf(arms[i]), tb = termsOf(arms[j]);
|
|
4383
|
+
if (ta.length === 0 || ta.length >= tb.length) continue;
|
|
4384
|
+
let k = 0;
|
|
4385
|
+
while (k < ta.length && shapeOf(ta[k]) === shapeOf(tb[k])) k++;
|
|
4386
|
+
if (k !== ta.length) continue;
|
|
4387
|
+
push({
|
|
4388
|
+
rewrite: "shadowed-arm",
|
|
4389
|
+
site,
|
|
4390
|
+
from: `choice(\u2026 arm[${i}]=${clamp(render(arms[i], 2))}, \u2026 arm[${j}]=${clamp(render(arms[j], 2))} \u2026)`,
|
|
4391
|
+
to: `arm[${j}] is unreachable`,
|
|
4392
|
+
astNeutral: true,
|
|
4393
|
+
perf: PERF_ARM,
|
|
4394
|
+
bug: true,
|
|
4395
|
+
suggestion: `arm[${i}] is a strict prefix of arm[${j}] and comes FIRST. Whenever arm[${j}] would match, arm[${i}] also matches, and ordered choice commits to it \u2014 so arm[${j}] can never be selected. Either swap them (longest first) or fold arm[${j}]'s extra terms into arm[${i}] as \`optional(\u2026)\`. Verify by hand where a \`not()\`/\`gate()\` in arm[${i}] makes its success input-dependent in a way this static check cannot see.`
|
|
4396
|
+
}, `${i}-${j}`);
|
|
4397
|
+
}
|
|
4398
|
+
for (let i = 0; i + 1 < arms.length; i++) {
|
|
4399
|
+
const j = i + 1;
|
|
4400
|
+
const longer = termsOf(arms[i]), shorter = termsOf(arms[j]);
|
|
4401
|
+
const ordered = detectOptionalTerm(longer, shorter, shapeOf);
|
|
4402
|
+
const reversed = ordered === null ? detectOptionalTerm(shorter, longer, shapeOf) : null;
|
|
4403
|
+
const hit = ordered ?? reversed;
|
|
4404
|
+
if (hit === null) continue;
|
|
4405
|
+
const nodeWrapped = v2.enclosingNode ?? wrappingNodeType(arms[i]) ?? wrappingNodeType(arms[j]);
|
|
4406
|
+
const rest = hit.rest.map((t) => render(t, 2)).join(", ");
|
|
4407
|
+
const to = hit.where === "prefix" ? `sequence(optional(${render(hit.term, 2)}), ${rest})` : `sequence(${rest}, optional(${render(hit.term, 2)}))`;
|
|
4408
|
+
push({
|
|
4409
|
+
rewrite: hit.where === "prefix" ? "optional-prefix" : "optional-suffix",
|
|
4410
|
+
site,
|
|
4411
|
+
from: clamp(render(v2.p, 2)),
|
|
4412
|
+
to: clamp(to),
|
|
4413
|
+
astNeutral: false,
|
|
4414
|
+
perf: PERF_ARM,
|
|
4415
|
+
bug: false,
|
|
4416
|
+
suggestion: `these two arms differ only by a ${hit.where === "prefix" ? "leading" : "trailing"} \`${clamp(render(hit.term, 2))}\`, so the choice is exactly \`${clamp(to)}\` \u2014 same language, one arm instead of two.${reversed !== null ? ` NOTE THE ORDER: the shorter arm is FIRST, so under ordered choice the longer arm is only reachable when the shorter one fails \u2014 check that is what you meant.` : ""} CANDIDATE \u2014 verify AST identity before applying:${nodeWrapped === null ? "" : ` this sits under \`node('${nodeWrapped}')\`, and`} the two forms produce different child arrays (two children vs. one child plus an absent optional). If a build fn or a downstream consumer reads children positionally, the rewrite MOVES the tree.`
|
|
4417
|
+
}, `${i}-${j}`);
|
|
4418
|
+
}
|
|
4419
|
+
for (let i = 0; i + 1 < arms.length; i++) {
|
|
4420
|
+
const j = i + 1;
|
|
4421
|
+
const ta = termsOf(arms[i]), tb = termsOf(arms[j]);
|
|
4422
|
+
if (ta.length < 2 || tb.length < 2) continue;
|
|
4423
|
+
let k = 0;
|
|
4424
|
+
while (k < ta.length - 1 && k < tb.length - 1 && shapeOf(ta[k]) === shapeOf(tb[k])) k++;
|
|
4425
|
+
if (k === 0) continue;
|
|
4426
|
+
const handled = strategy?.tag === "sharedPrefix" && Array.isArray(strategy.members) && strategy.members.includes(i) && strategy.members.includes(j);
|
|
4427
|
+
push({
|
|
4428
|
+
rewrite: "left-factor",
|
|
4429
|
+
site,
|
|
4430
|
+
from: `choice(sequence(${ta.map((t) => render(t, 1)).join(", ")}), sequence(${tb.map((t) => render(t, 1)).join(", ")}))`,
|
|
4431
|
+
to: clamp(`sequence(${ta.slice(0, k).map((t) => render(t, 2)).join(", ")}, choice(sequence(${ta.slice(k).map((t) => render(t, 1)).join(", ")}), sequence(${tb.slice(k).map((t) => render(t, 1)).join(", ")})))`),
|
|
4432
|
+
astNeutral: false,
|
|
4433
|
+
perf: handled ? "NONE \u2014 parseman's `sharedPrefix` choice strategy already recognizes this prefix once and replays it, so the runtime cost is identical. This is a readability finding." : PERF_ARM,
|
|
4434
|
+
bug: false,
|
|
4435
|
+
suggestion: `arm[${i}] and arm[${j}] spell the same ${k} leading term(s). ${handled ? "The `sharedPrefix` strategy already collapses this AT RUNTIME, so left-factoring buys readability, not speed \u2014 but writing it out means the next reader does not have to trust the optimizer." : "Left-factor to `sequence(prefix, choice(tailA, tailB))`: the prefix is then recognized once and the inner choice dispatches on its own first char."} CANDIDATE \u2014 verify AST identity: factoring nests the tails one level deeper in the value.`
|
|
4436
|
+
}, `${i}-${j}`);
|
|
4437
|
+
}
|
|
4438
|
+
}
|
|
4439
|
+
for (const v2 of visited.values()) {
|
|
4440
|
+
if (v2.d.tag !== "sequence") continue;
|
|
4441
|
+
const hit = detectHandRolledSepBy(v2.d.parsers, shapeOf);
|
|
4442
|
+
if (hit === null) continue;
|
|
4443
|
+
const captured = v2.d.parsers.some((t) => capturesPositionally(t));
|
|
4444
|
+
const verdict = captured ? "blocked-by-capture" : v2.enclosingReducer ? "reducer-stride-review" : "convertible";
|
|
4445
|
+
const to = `sepBy(${clamp(render(hit.item, 2))}, ${clamp(render(hit.sep, 2))}${hit.trailing ? `, { trailing: 'allow' }` : ""}, { min: ${hit.min} })`;
|
|
4446
|
+
out.push({
|
|
4447
|
+
kind: "rewrite",
|
|
4448
|
+
id: `rewrite:hand-rolled-sepby:${siteToString(v2.site)}`,
|
|
4449
|
+
rewrite: "hand-rolled-sepby",
|
|
4450
|
+
site: v2.site,
|
|
4451
|
+
sepByVerdict: verdict,
|
|
4452
|
+
from: clamp(render(v2.p, 3)),
|
|
4453
|
+
to: verdict === "convertible" ? to : `${to} \u2014 NOT APPLICABLE HERE (${verdict})`,
|
|
4454
|
+
astNeutral: false,
|
|
4455
|
+
perf: verdict === "convertible" ? "the hand-rolled form allocates a tuple per repetition (`sequence(sep, item)`) and a wrapper array around them; `sepBy` builds the item list directly." : PERF_NONE,
|
|
4456
|
+
bug: false,
|
|
4457
|
+
suggestion: `${SEPBY_SPELLED_OUT(hit.trailing)} ${SEPBY_VERDICT_TEXT[verdict](hit.trailing)}`
|
|
4458
|
+
});
|
|
4459
|
+
}
|
|
4460
|
+
return out;
|
|
4461
|
+
}
|
|
4462
|
+
function collapseRepeat(outer, inner) {
|
|
4463
|
+
const o = outer.tag, i = inner.tag;
|
|
4464
|
+
if (o === "optional" && i === "optional") return "optional(X)";
|
|
4465
|
+
if (o === "optional" && i === "many") return "many(X)";
|
|
4466
|
+
if (o === "many" && i === "many") return "many(X)";
|
|
4467
|
+
if (o === "many" && i === "optional") return "many(X)";
|
|
4468
|
+
if (o === "optional" && i === "oneOrMore" && inner.min === 1 && inner.max === void 0) return "many(X)";
|
|
4469
|
+
if (o === "many" && i === "oneOrMore" && inner.min === 1 && inner.max === void 0) return "many(X)";
|
|
4470
|
+
return null;
|
|
4471
|
+
}
|
|
4472
|
+
function wrappingNodeType(arm) {
|
|
4473
|
+
const d = arm._def;
|
|
4474
|
+
return d.tag === "node" ? d.type ?? "(anonymous)" : null;
|
|
4475
|
+
}
|
|
4476
|
+
function detectOptionalTerm(longer, shorter, shapeOf) {
|
|
4477
|
+
if (longer.length !== shorter.length + 1 || shorter.length === 0) return null;
|
|
4478
|
+
const same = (a, b) => a.length === b.length && a.every((x, i) => shapeOf(x) === shapeOf(b[i]));
|
|
4479
|
+
if (same(longer.slice(1), shorter)) return { where: "prefix", term: longer[0], rest: shorter };
|
|
4480
|
+
if (same(longer.slice(0, -1), shorter)) return { where: "suffix", term: longer[longer.length - 1], rest: shorter };
|
|
4481
|
+
return null;
|
|
4482
|
+
}
|
|
4483
|
+
var SEPBY_SPELLED_OUT = (trailing) => `this is \`sepBy(item, sep${trailing ? ", { trailing: 'allow' }" : ""})\` spelled out.`;
|
|
4484
|
+
var SEPBY_VERDICT_TEXT = {
|
|
4485
|
+
"blocked-by-capture": () => "BLOCKED: the repetition CAPTURES its separator (`field`/`label`), which `sepBy` cannot express \u2014 it yields items and discards separators, so byte-faithful layout replay is lost. Leave this site alone; read it as a parseman gap (a separator-capturing repeat), not as work.",
|
|
4486
|
+
"reducer-stride-review": () => "NEEDS REVIEW, not conversion: an enclosing `node()`/`transform()` reducer reads this repetition's children, and a left-associating reducer typically STRIDES BY TWO over `[item, sep, item, sep, \u2026]` and re-emits the operator text. `sepBy` yields a FLAT ITEM list with the separators gone, so the reducer has to be rewritten in the same change or the tree moves. Convert only together with the reducer.",
|
|
4487
|
+
convertible: (trailing) => `No separator capture, and no enclosing reducer reads these children \u2014 this site is convertible. Beyond the ${trailing ? "four" : "three"} combinators it replaces, \`sepBy\` carries the right NULLABILITY: \`min: 0\` (the default) matches empty and does NOT gate as a choice arm, \`min: 1\` does \u2014 a distinction the hand-rolled shape leaves implicit and gets wrong silently. Still check the consumer: \`sepBy\` yields a flat item list where the hand-rolled form yields \`[first, [[sep, item], \u2026]]\`.`
|
|
4488
|
+
};
|
|
4489
|
+
function capturesPositionally(p, seen = /* @__PURE__ */ new Set()) {
|
|
4490
|
+
if (seen.has(p)) return false;
|
|
4491
|
+
seen.add(p);
|
|
4492
|
+
const d = p._def;
|
|
4493
|
+
if (d.tag === "field" || d.tag === "label") return true;
|
|
4494
|
+
for (const k of childrenOf(d)) if (capturesPositionally(k, seen)) return true;
|
|
4495
|
+
return false;
|
|
4496
|
+
}
|
|
4497
|
+
function detectHandRolledSepBy(terms, shapeOf) {
|
|
4498
|
+
if (terms.length < 2 || terms.length > 3) return null;
|
|
4499
|
+
const item = terms[0];
|
|
4500
|
+
const rep = terms[1]._def;
|
|
4501
|
+
if (rep.tag !== "many" && rep.tag !== "oneOrMore") return null;
|
|
4502
|
+
if (rep.max !== void 0) return null;
|
|
4503
|
+
const innerDef = rep.parser._def;
|
|
4504
|
+
if (innerDef.tag !== "sequence" || innerDef.parsers.length !== 2) return null;
|
|
4505
|
+
const [sep, repeated] = innerDef.parsers;
|
|
4506
|
+
if (shapeOf(repeated) !== shapeOf(item)) return null;
|
|
4507
|
+
let trailing = false;
|
|
4508
|
+
if (terms.length === 3) {
|
|
4509
|
+
const t = terms[2]._def;
|
|
4510
|
+
if (t.tag !== "optional" || shapeOf(t.parser) !== shapeOf(sep)) return null;
|
|
4511
|
+
trailing = true;
|
|
4512
|
+
}
|
|
4513
|
+
return { item, sep, trailing, min: 1 + rep.min };
|
|
4514
|
+
}
|
|
4515
|
+
function bodyTermsOf(p) {
|
|
4516
|
+
let cur = p;
|
|
4517
|
+
for (; ; ) {
|
|
4518
|
+
const d2 = cur._def;
|
|
4519
|
+
if (d2.tag === "node" || d2.tag === "grammar" || d2.tag === "transform" || d2.tag === "label" || d2.tag === "attempt" || d2.tag === "leaf" || d2.tag === "token" || d2.tag === "expect" || d2.tag === "field") {
|
|
4520
|
+
cur = d2.parser;
|
|
4521
|
+
continue;
|
|
4522
|
+
}
|
|
4523
|
+
break;
|
|
4524
|
+
}
|
|
4525
|
+
const d = cur._def;
|
|
4526
|
+
return d.tag === "sequence" ? d.parsers : [cur];
|
|
4527
|
+
}
|
|
4528
|
+
var MIN_SHARED_TERMS = 2;
|
|
4529
|
+
function findDivergentNodes(visited, shapeOf) {
|
|
4530
|
+
const byType = /* @__PURE__ */ new Map();
|
|
4531
|
+
for (const v2 of visited.values()) {
|
|
4532
|
+
if (v2.d.tag !== "node" || v2.d.type === void 0) continue;
|
|
4533
|
+
let m = byType.get(v2.d.type);
|
|
4534
|
+
if (m === void 0) {
|
|
4535
|
+
m = /* @__PURE__ */ new Map();
|
|
4536
|
+
byType.set(v2.d.type, m);
|
|
4537
|
+
}
|
|
4538
|
+
if (!m.has(v2.shape)) m.set(v2.shape, v2);
|
|
4539
|
+
}
|
|
4540
|
+
const out = [];
|
|
4541
|
+
for (const [type, m] of byType) {
|
|
4542
|
+
if (m.size < 2) continue;
|
|
4543
|
+
const members = [...m.values()];
|
|
4544
|
+
const termSets = members.map((v2) => bodyTermsOf(v2.p).map((t) => ({ id: shapeOf(t), text: clamp(render(t, 2)) })));
|
|
4545
|
+
const shared = termSets[0].filter((t) => termSets.every((set) => set.some((x) => x.id === t.id)));
|
|
4546
|
+
const uniqueShared = [...new Map(shared.map((t) => [t.id, t])).values()];
|
|
4547
|
+
if (uniqueShared.length < MIN_SHARED_TERMS) continue;
|
|
4548
|
+
const sharedIds = new Set(uniqueShared.map((t) => t.id));
|
|
4549
|
+
out.push({
|
|
4550
|
+
kind: "divergent-node",
|
|
4551
|
+
id: `divergent-node:${type}`,
|
|
4552
|
+
nodeType: type,
|
|
4553
|
+
count: members.length,
|
|
4554
|
+
sharedTerms: uniqueShared.map((t) => t.text),
|
|
4555
|
+
productions: members.map((v2, i) => ({
|
|
4556
|
+
shape: clamp(render(v2.p, 3)),
|
|
4557
|
+
site: v2.site,
|
|
4558
|
+
distinctTerms: termSets[i].filter((t) => !sharedIds.has(t.id)).map((t) => t.text)
|
|
4559
|
+
})),
|
|
4560
|
+
suggestion: `\`${type}\` is built by ${members.length} structurally different productions that nevertheless spell ${uniqueShared.length} identical term(s) (${uniqueShared.map((t) => `\`${t.text}\``).join(", ")}) \u2014 they are variants of ONE shape, not ${members.length} constructs. Nothing keeps them in sync: an edit to the ${type} shape has to land in all ${members.length}, and no test fails when it lands in one. Fold them into a single production whose varying part is a \`choice\`, or, if the variants exist for a parse-order reason (a fast path tried first), say so at the definition \u2014 the cost of the split is that a reader cannot tell which it is.`
|
|
4561
|
+
});
|
|
4562
|
+
}
|
|
4563
|
+
return out.sort((a, b) => b.sharedTerms.length * b.count - a.sharedTerms.length * a.count);
|
|
4564
|
+
}
|
|
4565
|
+
function resolveArm(p) {
|
|
4566
|
+
let cur = p;
|
|
4567
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4568
|
+
for (; ; ) {
|
|
4569
|
+
if (seen.has(cur)) return cur;
|
|
4570
|
+
seen.add(cur);
|
|
4571
|
+
const d = cur._def;
|
|
4572
|
+
if (d.tag === "label" || d.tag === "attempt") {
|
|
4573
|
+
cur = d.parser;
|
|
4574
|
+
continue;
|
|
4575
|
+
}
|
|
4576
|
+
if (d.tag === "lazy") {
|
|
4577
|
+
try {
|
|
4578
|
+
cur = d.thunk();
|
|
4579
|
+
continue;
|
|
4580
|
+
} catch {
|
|
4581
|
+
return cur;
|
|
4582
|
+
}
|
|
4583
|
+
}
|
|
4584
|
+
return cur;
|
|
4585
|
+
}
|
|
4586
|
+
}
|
|
4587
|
+
function nestedNodeTypes(root, out, seen, isRoot) {
|
|
4588
|
+
if (seen.has(root)) return;
|
|
4589
|
+
seen.add(root);
|
|
4590
|
+
const d = root._def;
|
|
4591
|
+
if (d.tag === "leaf" || d.tag === "token") return;
|
|
4592
|
+
if (d.tag === "node" && !isRoot) out.add(d.type ?? "(anonymous)");
|
|
4593
|
+
if (d.tag === "lazy") {
|
|
4594
|
+
try {
|
|
4595
|
+
nestedNodeTypes(d.thunk(), out, seen, false);
|
|
4596
|
+
} catch {
|
|
4597
|
+
}
|
|
4598
|
+
return;
|
|
4599
|
+
}
|
|
4600
|
+
for (const k of childrenOf(d)) nestedNodeTypes(k, out, seen, false);
|
|
4601
|
+
}
|
|
4602
|
+
var MAX_LOST_TYPES = 8;
|
|
4603
|
+
function findStructureLoss(visited, resolve) {
|
|
4604
|
+
const nestedCache = /* @__PURE__ */ new Map();
|
|
4605
|
+
const nested = (p) => {
|
|
4606
|
+
const hit = nestedCache.get(p);
|
|
4607
|
+
if (hit !== void 0) return hit;
|
|
4608
|
+
const out = /* @__PURE__ */ new Set();
|
|
4609
|
+
nestedNodeTypes(p, out, /* @__PURE__ */ new Set(), true);
|
|
4610
|
+
nestedCache.set(p, out);
|
|
4611
|
+
return out;
|
|
4612
|
+
};
|
|
4613
|
+
const findings = [];
|
|
4614
|
+
for (const v2 of visited.values()) {
|
|
4615
|
+
const d = v2.d;
|
|
4616
|
+
if (d.tag !== "choice") continue;
|
|
4617
|
+
const arms = d.parsers;
|
|
4618
|
+
const resolved = arms.map(resolveArm);
|
|
4619
|
+
const nodeTypes = resolved.map(wrappingNodeType);
|
|
4620
|
+
const fs = arms.map((a) => firstSetOf(a, /* @__PURE__ */ new Set(), resolve));
|
|
4621
|
+
for (let i = 0; i < arms.length; i++) {
|
|
4622
|
+
if (d.gates[i] != null) continue;
|
|
4623
|
+
const type = nodeTypes[i] ?? null;
|
|
4624
|
+
if (type === null) continue;
|
|
4625
|
+
if (nested(resolved[i]).size !== 0) continue;
|
|
4626
|
+
const A = fs[i];
|
|
4627
|
+
if (A.kind === "any") continue;
|
|
4628
|
+
for (let j = i + 1; j < arms.length; j++) {
|
|
4629
|
+
if (nodeTypes[j] !== type) continue;
|
|
4630
|
+
const B = fs[j];
|
|
4631
|
+
if (B.kind === "any" || !intersects3(A, B)) continue;
|
|
4632
|
+
const lost = nested(resolved[j]);
|
|
4633
|
+
if (lost.size === 0) continue;
|
|
4634
|
+
const lostNodeTypes = [...lost].sort();
|
|
4635
|
+
findings.push({
|
|
4636
|
+
kind: "structure-loss",
|
|
4637
|
+
id: `structure-loss:${siteToString(v2.site)}:${i}-${j}`,
|
|
4638
|
+
site: v2.site,
|
|
4639
|
+
nodeType: type,
|
|
4640
|
+
earlier: i,
|
|
4641
|
+
later: j,
|
|
4642
|
+
on: intersection2(A, B),
|
|
4643
|
+
lostNodeTypes: lostNodeTypes.slice(0, MAX_LOST_TYPES),
|
|
4644
|
+
earlierShape: clamp(render(resolved[i], 3)),
|
|
4645
|
+
laterShape: clamp(render(resolved[j], 3)),
|
|
4646
|
+
suggestion: structureLossSuggestion(type, i, j, lostNodeTypes)
|
|
4647
|
+
});
|
|
4648
|
+
}
|
|
4649
|
+
}
|
|
4650
|
+
}
|
|
4651
|
+
return findings.sort((a, b) => b.lostNodeTypes.length - a.lostNodeTypes.length);
|
|
4652
|
+
}
|
|
4653
|
+
function structureLossSuggestion(type, i, j, lost) {
|
|
4654
|
+
const names = lost.slice(0, MAX_LOST_TYPES).map((t) => `\`${t}\``).join(", ");
|
|
4655
|
+
const more = lost.length > MAX_LOST_TYPES ? ` (and ${lost.length - MAX_LOST_TYPES} more)` : "";
|
|
4656
|
+
return `arm[${i}] and arm[${j}] both build \`${type}\` and can start on the same character, so on every input BOTH accept, arm[${i}] wins \u2014 and arm[${i}] contains no \`node()\`, so it yields a \`${type}\` over bare leaves. arm[${j}] would have built ${names}${more} there. The parse still succeeds and the span is still right; only the tree shape changes, and only on the inputs arm[${i}] happens to accept \u2014 so a suite that asserts "it parses" and an output diff both stay green while every consumer of the tree (language service, formatter, refactor) silently loses those nodes on the commonest inputs. Decide which tree is the contract: if the structured one is, DELETE arm[${i}] or move it after arm[${j}]; if the flat one is, it must be flat for ALL inputs of this shape, not just the ones arm[${i}] matches \u2014 a fast path that is not tree-neutral is not a fast path.`;
|
|
4657
|
+
}
|
|
4658
|
+
function findKeywordRegexes(visited) {
|
|
4659
|
+
const armIndexOf = /* @__PURE__ */ new Map();
|
|
4660
|
+
for (const v2 of visited.values()) {
|
|
4661
|
+
if (v2.d.tag !== "choice") continue;
|
|
4662
|
+
v2.d.parsers.forEach((a, i) => {
|
|
4663
|
+
let cur = a;
|
|
4664
|
+
for (; ; ) {
|
|
4665
|
+
const cd = cur._def;
|
|
4666
|
+
if (cd.tag === "node" || cd.tag === "label" || cd.tag === "transform" || cd.tag === "leaf" || cd.tag === "attempt") {
|
|
4667
|
+
cur = cd.parser;
|
|
4668
|
+
continue;
|
|
4669
|
+
}
|
|
4670
|
+
break;
|
|
4671
|
+
}
|
|
4672
|
+
armIndexOf.set(cur, { owner: v2.p, index: i });
|
|
4673
|
+
});
|
|
4674
|
+
}
|
|
4675
|
+
const keywordArms = /* @__PURE__ */ new Map();
|
|
4676
|
+
for (const [arm, { owner }] of armIndexOf) {
|
|
4677
|
+
const d = arm._def;
|
|
4678
|
+
if (d.tag !== "regex" || keywordRegexShape(d.source) === null) continue;
|
|
4679
|
+
const list = keywordArms.get(owner) ?? [];
|
|
4680
|
+
list.push(armIndexOf.get(arm).index);
|
|
4681
|
+
keywordArms.set(owner, list);
|
|
4682
|
+
}
|
|
4683
|
+
const out = [];
|
|
4684
|
+
for (const v2 of visited.values()) {
|
|
4685
|
+
const d = v2.d;
|
|
4686
|
+
if (d.tag !== "regex") continue;
|
|
4687
|
+
const shape = keywordRegexShape(d.source);
|
|
4688
|
+
if (shape === null) continue;
|
|
4689
|
+
const ci = d.flags.includes("i");
|
|
4690
|
+
const unicode = d.flags.includes("u") || d.flags.includes("v");
|
|
4691
|
+
const own = armIndexOf.get(v2.p);
|
|
4692
|
+
const siblings = own === void 0 ? [] : (keywordArms.get(own.owner) ?? []).filter((i) => i !== own.index);
|
|
4693
|
+
const bq = (s) => `'${s.replace(/\\/g, "\\\\")}'`;
|
|
4694
|
+
const vocabulary = shape.words.length >= VOCABULARY_MIN_WORDS;
|
|
4695
|
+
const hazards = keywordAlternationHazards(shape.words, shape.boundary);
|
|
4696
|
+
const unrescued = hazards.filter((h) => !h.rescuedByBoundary);
|
|
4697
|
+
const longestFirst = shape.words.every((w, i) => i === 0 || shape.words[i - 1].length >= w.length);
|
|
4698
|
+
const shown = shape.words.length > 8 ? [...shape.words.slice(0, 6), "/* \u2026 */", shape.words[shape.words.length - 1]] : shape.words;
|
|
4699
|
+
const call = shape.words.length === 1 ? `word(${bq(shape.words[0])}, ${bq(shape.boundary ?? "_0-9A-Za-z")}${ci ? ", { caseInsensitive: true }" : ""})` : `keywords([${shown.map((w) => w === "/* \u2026 */" ? w : bq(w)).join(", ")}], { boundary: ${bq(shape.boundary ?? "_0-9A-Za-z")}${ci ? ", caseInsensitive: true" : ""} })`;
|
|
4700
|
+
out.push({
|
|
4701
|
+
kind: "keyword-regex",
|
|
4702
|
+
id: `keyword-regex:${siteToString(v2.site)}`,
|
|
4703
|
+
site: v2.site,
|
|
4704
|
+
source: d.source,
|
|
4705
|
+
flags: d.flags,
|
|
4706
|
+
words: shape.words,
|
|
4707
|
+
boundary: shape.boundary,
|
|
4708
|
+
caseFoldRisk: ci && !unicode,
|
|
4709
|
+
siblingArms: siblings,
|
|
4710
|
+
vocabulary,
|
|
4711
|
+
longestFirst,
|
|
4712
|
+
hazards,
|
|
4713
|
+
bug: unrescued.length > 0,
|
|
4714
|
+
suggestion: [
|
|
4715
|
+
vocabulary ? `this regex enumerates a FIXED VOCABULARY of ${shape.words.length} literal words${shape.words.length > 20 ? " \u2014 the alternation is long enough that nobody re-reads it" : ""}. A regex enumerating a fixed vocabulary is a keyword set written the hard way. Use \`${call}\` \u2014 it exposes an EXACT first-set that \`choice\` can dispatch on (the alternation exposes none), it owns the boundary so it is not re-spelled per word, it sorts LONGEST-FIRST by construction, and it lowers to a single charCodeAt scan.` : `\`regex(/${d.source}/${d.flags})\` hand-rolls a keyword and its word boundary. Use \`${call}\` \u2014 it owns the boundary (so \`${shape.boundary ?? ""}\` is not re-spelled per keyword), exposes an EXACT first-set that \`choice\` can dispatch on, and lowers to the same charCodeAt scan.`,
|
|
4716
|
+
unrescued.length > 0 ? `LIVE BUG \u2014 the alternation is ordered so ${unrescued.length} later alternative(s) can NEVER match: ${unrescued.slice(0, 3).map((h) => `\`${h.shorter}\` precedes \`${h.longer}\` and nothing rejects the following \`${h.at}\``).join("; ")}${unrescued.length > 3 ? `, and ${unrescued.length - 3} more` : ""}. Regex alternation is FIRST-match, not longest-match, and with no boundary guard to force a backtrack the shorter branch wins outright. \`keywords()\` cannot express this bug: it sorts longest-first.` : hazards.length > 0 ? `ORDERING HAZARD (currently harmless): ${hazards.length} earlier alternative(s) are strict prefixes of later ones \u2014 e.g. \`${hazards[0].shorter}\` before \`${hazards[0].longer}\`. Regex alternation is first-match, so these work ONLY because the trailing boundary guard rejects the next character and the engine backtracks into the longer branch. That correctness rests on a hand-maintained order plus a guard that happens to cover the right characters; \`keywords()\` sorts longest-first by construction and does not depend on either.` : !longestFirst && vocabulary ? `The alternation is not in longest-first order. It is correct today${shape.boundary === null ? "" : " (the boundary guard forces a backtrack where it matters)"}, but the ordering is hand-maintained and nothing checks it \u2014 adding a word that extends an existing one is a silent bug. \`keywords()\` sorts longest-first by construction.` : "",
|
|
4717
|
+
ci && !unicode ? `CORRECTNESS, not style: \`/i\` without \`/u\` does NOT fold case the way \`{c, toUpperCase(c), toLowerCase(c)}\` suggests \u2014 67 BMP code points fold in ways those three miss (\u03C2/\u03C3, \xB5/\u03BC, the \u01C4\u01C5\u01C6 digraphs, combining iota subscript). parseman fixed exactly this INSIDE \`keywords()\` (see combinators/case-fold.ts); a hand-rolled copy never received the fix, so its first-set is unsound for those inputs.` : "",
|
|
4718
|
+
siblings.length > 0 ? `arm[${own?.index}] here sits alongside arm(s) [${siblings.join(", ")}] in the same \`choice\`, which are also hand-rolled keywords. A single \`keywords([\u2026])\` replaces the whole group and gives longest-match dispatch across it \u2014 which is what that combinator exists for.` : ""
|
|
4719
|
+
].filter((s) => s !== "").join(" ")
|
|
4720
|
+
});
|
|
4721
|
+
}
|
|
4722
|
+
return out.sort((a, b) => Number(b.bug) - Number(a.bug) || b.hazards.length - a.hazards.length || b.words.length - a.words.length || b.siblingArms.length - a.siblingArms.length);
|
|
4723
|
+
}
|
|
4724
|
+
var sitesLine = (sites) => sites.slice(0, 6).map(siteToString).join("\n ") + (sites.length > 6 ? `
|
|
4725
|
+
\u2026 and ${sites.length - 6} more` : "");
|
|
4726
|
+
function formatDuplicationFindings(report) {
|
|
4727
|
+
const lines = [];
|
|
4728
|
+
for (const f of report.structureLoss) {
|
|
4729
|
+
lines.push(`parseman BUG [structure-loss] @ ${siteToString(f.site)}: arm[${f.earlier}] flattens \`${f.nodeType}\` where arm[${f.later}] structures it, on ${firstSetToString(f.on)}`);
|
|
4730
|
+
lines.push(` flat: ${f.earlierShape}`);
|
|
4731
|
+
lines.push(` rich: ${f.laterShape}`);
|
|
4732
|
+
lines.push(` lost: ${f.lostNodeTypes.map((t) => `\`${t}\``).join(", ")}`);
|
|
4733
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4734
|
+
}
|
|
4735
|
+
for (const f of report.rewrites) {
|
|
4736
|
+
lines.push(`parseman ${f.bug ? "BUG" : "rewrite"} [${f.rewrite}${f.sepByVerdict === void 0 ? "" : `/${f.sepByVerdict}`}] @ ${siteToString(f.site)}${f.astNeutral ? "" : " (candidate \u2014 verify AST identity)"}`);
|
|
4737
|
+
lines.push(` from: ${f.from}`);
|
|
4738
|
+
lines.push(` to: ${f.to}`);
|
|
4739
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4740
|
+
if (f.perf !== "") lines.push(` perf: ${f.perf}`);
|
|
4741
|
+
}
|
|
4742
|
+
for (const f of report.divergentNodes) {
|
|
4743
|
+
lines.push(`parseman divergent-node: \`${f.nodeType}\` is built by ${f.count} different productions sharing ${f.sharedTerms.length} term(s): ${f.sharedTerms.map((t) => `\`${t}\``).join(", ")}`);
|
|
4744
|
+
for (const p of f.productions) lines.push(` ${siteToString(p.site)}
|
|
4745
|
+
${p.shape}
|
|
4746
|
+
unique to it: ${p.distinctTerms.length === 0 ? "(none)" : p.distinctTerms.map((t) => `\`${t}\``).join(", ")}`);
|
|
4747
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4748
|
+
}
|
|
4749
|
+
for (const f of report.keywordRegexes) {
|
|
4750
|
+
const src = f.source.length > 90 ? `${f.source.slice(0, 88)}\u2026` : f.source;
|
|
4751
|
+
lines.push(`parseman ${f.bug ? "BUG " : ""}keyword-regex @ ${siteToString(f.site)}: /${src}/${f.flags}${f.vocabulary ? ` [${f.words.length} literal words${f.longestFirst ? "" : ", NOT longest-first"}]` : ""}${f.hazards.length > 0 ? ` [${f.hazards.length} prefix hazard(s)${f.bug ? ", UNRESCUED" : ""}]` : ""}${f.caseFoldRisk ? " [CASE-FOLD RISK]" : ""}`);
|
|
4752
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4753
|
+
}
|
|
4754
|
+
for (const f of report.duplicates) {
|
|
4755
|
+
lines.push(`parseman duplication: ${f.count}\xD7 identical ${f.size}-node shape (saves ${f.savings} nodes) \u2014 ${f.shape}`);
|
|
4756
|
+
lines.push(` at: ${sitesLine(f.sites)}`);
|
|
4757
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4758
|
+
}
|
|
4759
|
+
for (const f of report.nearDuplicates) {
|
|
4760
|
+
lines.push(`parseman near-duplication: ${f.count} clones of a ${f.sharedSize}-node shape differing at ONE slot (saves ${f.savings} nodes) \u2014 ${f.shape}`);
|
|
4761
|
+
lines.push(` slot: ${f.slotPath} \u2208 { ${f.variants.join(" | ")} }`);
|
|
4762
|
+
lines.push(` at: ${sitesLine(f.sites)}`);
|
|
4763
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4764
|
+
}
|
|
4765
|
+
for (const f of report.regexFragments) {
|
|
4766
|
+
lines.push(`parseman regex-fragment: \`${f.fragment}\` (${f.branches} branches) re-spelled in ${f.count} regex() terminals`);
|
|
4767
|
+
lines.push(` at: ${sitesLine(f.sites)}`);
|
|
4768
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4769
|
+
}
|
|
4770
|
+
for (const f of report.regexClasses) {
|
|
4771
|
+
lines.push(`parseman regex-class${f.drifted ? " DRIFT" : ""}: [${f.canonical}] across ${f.count} regex() terminals${f.bmpCeiling ? " [BMP ceiling]" : ""}`);
|
|
4772
|
+
for (const v2 of f.variants) lines.push(` [${v2.source}] \xD7${v2.count} ${v2.delta}
|
|
4773
|
+
${sitesLine(v2.sites)}`);
|
|
4774
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4775
|
+
}
|
|
4776
|
+
for (const f of report.overlaps) {
|
|
4777
|
+
lines.push(`parseman overlap @ ${siteToString(f.site)}: arm[${f.a}] \u2229 arm[${f.b}] on ${firstSetToString(f.on)}${f.sharedPrefix === null ? "" : ` \u2014 shared prefix: ${f.sharedPrefix}`}${f.handledByStrategy ? " [sharedPrefix strategy already handles this]" : ""}`);
|
|
4778
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4779
|
+
}
|
|
4780
|
+
return lines;
|
|
4781
|
+
}
|
|
4782
|
+
function duplicationFindingCount(report) {
|
|
4783
|
+
return report.duplicates.length + report.nearDuplicates.length + report.regexFragments.length + report.regexClasses.length + report.overlaps.length + report.rewrites.length + report.divergentNodes.length + report.structureLoss.length + report.keywordRegexes.length;
|
|
4784
|
+
}
|
|
4785
|
+
|
|
3425
4786
|
// src/combinators/scanTo.ts
|
|
3426
4787
|
function resolveScanSkip(explicitSkip, raw, ctx) {
|
|
3427
4788
|
if (raw) return [];
|
|
@@ -6642,12 +8003,14 @@ function emitNode(def, ctx, pos) {
|
|
|
6642
8003
|
ctx.buildSrcs.push(def.buildSrc ?? null);
|
|
6643
8004
|
}
|
|
6644
8005
|
const i = ind(ctx);
|
|
6645
|
-
const
|
|
6646
|
-
|
|
6647
|
-
const
|
|
6648
|
-
const
|
|
8006
|
+
const cstOut = ctx.hostMode === "cst" && !structural;
|
|
8007
|
+
if (!structural && !cstOut) ctx.hostBranchElided = true;
|
|
8008
|
+
const capturesTrivia = cstOut || mkType !== null || def.captureTrivia === true || def.trailingTrivia === true || !structural && buildReadsTrivia(def);
|
|
8009
|
+
const clonesState = !structural && (cstOut || buildReadsState(def));
|
|
8010
|
+
const capturesChildren = !structural && (cstOut || mkType !== null || def.unwrap || def.collapse || buildReadsChildren(def));
|
|
8011
|
+
const capturesRaw = !structural && (cstOut || mkType !== null || buildReadsRaw(def));
|
|
6649
8012
|
const hasFields = parserHasOwnFields(def.parser);
|
|
6650
|
-
const capturesFields = hasFields && !structural && buildReadsFields(def);
|
|
8013
|
+
const capturesFields = hasFields && !structural && (cstOut || buildReadsFields(def));
|
|
6651
8014
|
const innerEnablesTriviaCapture = parserEnablesTriviaCapture(def.parser);
|
|
6652
8015
|
const chV = v(ctx, "_ch");
|
|
6653
8016
|
const rawV = v(ctx, "_raw");
|
|
@@ -6664,8 +8027,9 @@ function emitNode(def, ctx, pos) {
|
|
|
6664
8027
|
const profHoist = `${i}const ${pmV} = _ctx._pmProfile, ${recV} = ${pmV}?.phase === 'recognizer', ${capV} = ${pmV}?.phase === 'capture'`;
|
|
6665
8028
|
const profileRecognizer = recV;
|
|
6666
8029
|
const profileCapture = capV;
|
|
6667
|
-
const
|
|
6668
|
-
const
|
|
8030
|
+
const cstMode = ctx.hostMode === "cst";
|
|
8031
|
+
const directCstV = !structural && !cstMode && (!capturesChildren || !capturesRaw) ? v(ctx, "_dcst") : null;
|
|
8032
|
+
const directCstGate = directCstV === null ? "false" : profileCapture;
|
|
6669
8033
|
const structuralCapturesTrivia = structural && (def.captureTrivia === true || def.trailingTrivia === true);
|
|
6670
8034
|
const chNeededExpr = def.unwrap || def.collapse ? "true" : `(_ctx._pmReadsCh ??= (_ctx.build === undefined || _ctx.build._parsemanReadsChildren !== false || _ctx.build._parsemanCstCollapse !== undefined))`;
|
|
6671
8035
|
const chAlloc = def.unwrap || def.collapse ? `${profileRecognizer} ? undefined : []` : `${profileRecognizer} ? undefined : ((${profileCapture} || ${chNeededExpr}) ? [] : undefined)`;
|
|
@@ -6746,7 +8110,7 @@ ${i}const ${chV} = ${chAlloc}, ${rawV} = ${profileRecognizer} ? undefined : [],
|
|
|
6746
8110
|
const ndV = v(ctx, "_nd");
|
|
6747
8111
|
const buildExpr = structural ? `{ _tag: 'node', type: ${JSON.stringify(def.type)}, span: { start: ${pos}, end: ${endVar} }, state: ${stV} ?? null, children: ${chV} }` : mkType ? emitInlineMkNodeExpr(mkType, chV, rawV, pos, endVar, tlV) : `${buildRef(ctx)}[${buildIdx}](${chV}, ${fObj}, { start: ${pos}, end: ${endVar} }, ${rawV}, ${tlV}, ${stV})`;
|
|
6748
8112
|
const hostBuildExpr = `_ctx._pmProfile?.phase === 'host' && _ctx._pmProfile.hostCalls++, _ctx.build(${JSON.stringify(def.type)}, ${chV}, ${fObj}, { start: ${pos}, end: ${endVar} }, ${rawV}, ${tlV}, ${stV})`;
|
|
6749
|
-
const ndExpr = structural ? `_ctx.build !== undefined ? (${hostBuildExpr}) : (${buildExpr})` :
|
|
8113
|
+
const ndExpr = structural ? `_ctx.build !== undefined ? (${hostBuildExpr}) : (${buildExpr})` : cstOut ? hostBuildExpr : buildExpr;
|
|
6750
8114
|
const hostCollapseExpr = structural ? `_ctx.build !== undefined && _ctx.build._parsemanCstCollapse !== undefined && ${chV}.length === 1 && ${rawV}.length === 1 && _ctx.build._parsemanCstCollapse(${JSON.stringify(def.type)}, ${chV}[0], ${chV}, ${rawV}) ? ${chV}[0] : (${ndExpr})` : ndExpr;
|
|
6751
8115
|
const unwrapExpr = `${chV}.length === 1 ? (${chV}[0] !== null && typeof ${chV}[0] === 'object' && ${chV}[0]._tag === 'leaf' ? ${chV}[0].value : ${chV}[0]) : (${ndExpr})`;
|
|
6752
8116
|
const collapseExpr = `${chV}.length === 1 ? ${chV}[0] : (${ndExpr})`;
|
|
@@ -7195,9 +8559,9 @@ function hasDirectBuildDef(p, seen = /* @__PURE__ */ new Set()) {
|
|
|
7195
8559
|
return false;
|
|
7196
8560
|
}
|
|
7197
8561
|
}
|
|
7198
|
-
return
|
|
8562
|
+
return childrenOf2(d).some((child) => hasDirectBuildDef(child, seen));
|
|
7199
8563
|
}
|
|
7200
|
-
function
|
|
8564
|
+
function childrenOf2(def) {
|
|
7201
8565
|
switch (def.tag) {
|
|
7202
8566
|
case "sequence":
|
|
7203
8567
|
case "choice":
|
|
@@ -7268,7 +8632,7 @@ function subtreeSizes(roots) {
|
|
|
7268
8632
|
const def = p._def;
|
|
7269
8633
|
let s = 1;
|
|
7270
8634
|
if (def.tag !== "lazy") {
|
|
7271
|
-
for (const child of
|
|
8635
|
+
for (const child of childrenOf2(def)) s += child._def.tag === "lazy" ? 1 : sz(child);
|
|
7272
8636
|
}
|
|
7273
8637
|
sizes.set(p, s);
|
|
7274
8638
|
return s;
|
|
@@ -7289,7 +8653,7 @@ function subtreeSizes(roots) {
|
|
|
7289
8653
|
return;
|
|
7290
8654
|
}
|
|
7291
8655
|
sz(p);
|
|
7292
|
-
for (const child of
|
|
8656
|
+
for (const child of childrenOf2(def)) visit(child);
|
|
7293
8657
|
};
|
|
7294
8658
|
for (const root of roots) visit(root);
|
|
7295
8659
|
return sizes;
|
|
@@ -7323,7 +8687,7 @@ function analyzeLazyUsageMulti(roots) {
|
|
|
7323
8687
|
if (isHoistableTag(def.tag)) {
|
|
7324
8688
|
counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
7325
8689
|
}
|
|
7326
|
-
for (const child of
|
|
8690
|
+
for (const child of childrenOf2(def)) walk2(child);
|
|
7327
8691
|
}
|
|
7328
8692
|
const rootsArr = [...roots];
|
|
7329
8693
|
for (const root of rootsArr) walk2(root);
|
|
@@ -7355,7 +8719,7 @@ function ruleDependencies(ruleMap) {
|
|
|
7355
8719
|
walk2(resolved, false);
|
|
7356
8720
|
return;
|
|
7357
8721
|
}
|
|
7358
|
-
for (const child of
|
|
8722
|
+
for (const child of childrenOf2(def)) walk2(child, false);
|
|
7359
8723
|
};
|
|
7360
8724
|
walk2(comb, true);
|
|
7361
8725
|
deps.set(name, [...found]);
|
|
@@ -7375,10 +8739,30 @@ function runGatingDiagnostic(combinator, opt) {
|
|
|
7375
8739
|
function runGatingDiagnosticRules(ruleMap, opt) {
|
|
7376
8740
|
return reportGating(opt, (o) => analyzeGatingRules(ruleMap, o));
|
|
7377
8741
|
}
|
|
7378
|
-
function runFusedGatingDiagnostic(getRuleMaps, opt) {
|
|
8742
|
+
function runFusedGatingDiagnostic(getRuleMaps, opt, getOpaque) {
|
|
7379
8743
|
if (resolveGatingLevel(opt) === "off") return void 0;
|
|
7380
8744
|
const ruleMaps = getRuleMaps();
|
|
7381
|
-
|
|
8745
|
+
const opaque = getOpaque?.() ?? [];
|
|
8746
|
+
const opaqueFindings = opaque.map((o) => ({
|
|
8747
|
+
rule: o.ruleNames.length > 0 ? o.ruleNames.join(", ") : `<artifact ${o.ns}>`,
|
|
8748
|
+
kind: "opaque-artifact",
|
|
8749
|
+
reason: `precompiled artifact "${o.ns}" carries compiled rule functions, not re-lowerable IR \u2014 its choices were not examined at this fuse.`
|
|
8750
|
+
}));
|
|
8751
|
+
if (!ruleMaps.some((map) => hasExternalRuleRef(map))) {
|
|
8752
|
+
if (opaqueFindings.length === 0) return void 0;
|
|
8753
|
+
return reportGating(opt, () => ({
|
|
8754
|
+
totalChoices: 0,
|
|
8755
|
+
gated: 0,
|
|
8756
|
+
recoverable: 0,
|
|
8757
|
+
unanalysable: opaqueFindings,
|
|
8758
|
+
ungated: [],
|
|
8759
|
+
accepted: [],
|
|
8760
|
+
deferred: [],
|
|
8761
|
+
acceptedUnused: [],
|
|
8762
|
+
choices: [],
|
|
8763
|
+
antiPatterns: []
|
|
8764
|
+
}));
|
|
8765
|
+
}
|
|
7382
8766
|
const winners = /* @__PURE__ */ new Map();
|
|
7383
8767
|
for (const map of ruleMaps) for (const [name, rule] of map) {
|
|
7384
8768
|
if (rule._def.tag === "lazy") {
|
|
@@ -7394,7 +8778,12 @@ function runFusedGatingDiagnostic(getRuleMaps, opt) {
|
|
|
7394
8778
|
return reportGating(opt, (o) => {
|
|
7395
8779
|
const deferredHere = new Set(analyzeGatingRules(entries, o).deferred.map((c) => c.id));
|
|
7396
8780
|
const fused = analyzeGatingRules(entries, { ...o, resolveRef: (name) => winners.get(name) });
|
|
7397
|
-
return {
|
|
8781
|
+
return {
|
|
8782
|
+
...fused,
|
|
8783
|
+
ungated: fused.ungated.filter((c) => deferredHere.has(c.id)),
|
|
8784
|
+
antiPatterns: [],
|
|
8785
|
+
unanalysable: [...fused.unanalysable, ...opaqueFindings]
|
|
8786
|
+
};
|
|
7398
8787
|
});
|
|
7399
8788
|
}
|
|
7400
8789
|
function reportGating(opt, analyze) {
|
|
@@ -7405,22 +8794,82 @@ function reportGating(opt, analyze) {
|
|
|
7405
8794
|
let report;
|
|
7406
8795
|
try {
|
|
7407
8796
|
report = analyze(analyzeOpts);
|
|
7408
|
-
} catch {
|
|
7409
|
-
|
|
8797
|
+
} catch (e) {
|
|
8798
|
+
const reason = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
8799
|
+
const failed = {
|
|
8800
|
+
totalChoices: 0,
|
|
8801
|
+
gated: 0,
|
|
8802
|
+
recoverable: 0,
|
|
8803
|
+
unanalysable: [{ rule: "<whole grammar>", kind: "not-a-combinator", reason: `gating analysis threw \u2014 ${reason}` }],
|
|
8804
|
+
ungated: [],
|
|
8805
|
+
accepted: [],
|
|
8806
|
+
deferred: [],
|
|
8807
|
+
acceptedUnused: [],
|
|
8808
|
+
choices: [],
|
|
8809
|
+
antiPatterns: []
|
|
8810
|
+
};
|
|
8811
|
+
const failLines = formatGatingWarnings(failed);
|
|
8812
|
+
if (level === "error") throw new Error(`parseman: gating analysis FAILED (no verdict available)
|
|
8813
|
+
${failLines.join("\n")}`);
|
|
8814
|
+
for (const l of failLines) console.warn(l);
|
|
8815
|
+
return failed;
|
|
7410
8816
|
}
|
|
7411
8817
|
const lines = formatGatingWarnings(report);
|
|
7412
8818
|
if (lines.length > 0) {
|
|
7413
|
-
if (level === "error") throw new Error(`parseman: ${report.ungated.length} ungated hot choice(s) / ${report.antiPatterns.length} anti-pattern(s)
|
|
8819
|
+
if (level === "error") throw new Error(`parseman: ${report.ungated.length} ungated hot choice(s) / ${report.antiPatterns.length} anti-pattern(s) / ${report.unanalysable.length} unanalysable rule(s)
|
|
8820
|
+
${lines.join("\n")}`);
|
|
8821
|
+
for (const l of lines) console.warn(l);
|
|
8822
|
+
}
|
|
8823
|
+
return report;
|
|
8824
|
+
}
|
|
8825
|
+
function resolveDuplicationLevel(opt) {
|
|
8826
|
+
const explicit = typeof opt === "string" ? opt : opt?.level;
|
|
8827
|
+
if (explicit !== void 0) return explicit;
|
|
8828
|
+
const env = typeof process !== "undefined" ? process.env?.PARSEMAN_DUPLICATION : void 0;
|
|
8829
|
+
if (env === "off" || env === "warn" || env === "error") return env;
|
|
8830
|
+
return "off";
|
|
8831
|
+
}
|
|
8832
|
+
function reportDuplication(opt, analyze) {
|
|
8833
|
+
const level = resolveDuplicationLevel(opt);
|
|
8834
|
+
if (level === "off") return void 0;
|
|
8835
|
+
const obj = opt !== null && typeof opt === "object" ? opt : void 0;
|
|
8836
|
+
const analyzeOpts = obj === void 0 ? void 0 : {
|
|
8837
|
+
...obj.accept !== void 0 ? { accept: obj.accept } : {},
|
|
8838
|
+
...obj.minSize !== void 0 ? { minSize: obj.minSize } : {},
|
|
8839
|
+
...obj.maxFindings !== void 0 ? { maxFindings: obj.maxFindings } : {},
|
|
8840
|
+
...obj.entryName !== void 0 ? { entryName: obj.entryName } : {}
|
|
8841
|
+
};
|
|
8842
|
+
let report;
|
|
8843
|
+
try {
|
|
8844
|
+
report = analyze(analyzeOpts);
|
|
8845
|
+
} catch (err) {
|
|
8846
|
+
console.warn(
|
|
8847
|
+
`parseman: the duplication diagnostic could not run, so NOTHING was checked \u2014 this is not a clean result.
|
|
8848
|
+
${err instanceof Error ? err.message : String(err)}`
|
|
8849
|
+
);
|
|
8850
|
+
return void 0;
|
|
8851
|
+
}
|
|
8852
|
+
const lines = formatDuplicationFindings(report);
|
|
8853
|
+
if (lines.length > 0) {
|
|
8854
|
+
if (level === "error") throw new Error(`parseman: ${duplicationFindingCount(report)} duplication/overlap finding(s)
|
|
7414
8855
|
${lines.join("\n")}`);
|
|
7415
8856
|
for (const l of lines) console.warn(l);
|
|
7416
8857
|
}
|
|
7417
8858
|
return report;
|
|
7418
8859
|
}
|
|
8860
|
+
function runDuplicationDiagnostic(combinator, opt) {
|
|
8861
|
+
return reportDuplication(opt, (o) => analyzeDuplication(combinator, o));
|
|
8862
|
+
}
|
|
8863
|
+
function runDuplicationDiagnosticRules(ruleMap, opt) {
|
|
8864
|
+
return reportDuplication(opt, (o) => analyzeDuplicationRules(ruleMap, o));
|
|
8865
|
+
}
|
|
7419
8866
|
function compile(combinator, mapFnSources, opts) {
|
|
7420
8867
|
const gatingReport = runGatingDiagnostic(combinator, opts?.gating);
|
|
8868
|
+
runDuplicationDiagnostic(combinator, opts?.duplication);
|
|
7421
8869
|
markUnusedValues(combinator);
|
|
7422
8870
|
const grammarTrivia = combinator._meta.grammarTrivia;
|
|
7423
8871
|
const grammarScanSkip = combinator._meta.grammarScanSkip;
|
|
8872
|
+
const grammarHostMode = combinator._meta.grammarHostMode;
|
|
7424
8873
|
const ctx = {
|
|
7425
8874
|
vars: 0,
|
|
7426
8875
|
indent: 1,
|
|
@@ -7440,6 +8889,7 @@ function compile(combinator, mapFnSources, opts) {
|
|
|
7440
8889
|
namedFnDecls: [],
|
|
7441
8890
|
capturing: hasNodeDef(combinator),
|
|
7442
8891
|
recovery: opts?.recovery ?? false,
|
|
8892
|
+
hostMode: opts?.hostMode ?? grammarHostMode ?? "ast",
|
|
7443
8893
|
...opts?.coverage ? { coverage: { plan: buildGrammarPlan(combinator), entry: combinator } } : {},
|
|
7444
8894
|
lazyUsage: analyzeLazyUsage(combinator),
|
|
7445
8895
|
...grammarTrivia ? { activeTrivia: grammarTrivia, triviaKindLabels: grammarTrivia._meta.triviaKindLabels } : {},
|
|
@@ -7512,6 +8962,7 @@ function compile(combinator, mapFnSources, opts) {
|
|
|
7512
8962
|
return fn(input, pos, ctx.runtimeParsers, ctx.mapFns, ctx.buildFns, defaultCtx);
|
|
7513
8963
|
},
|
|
7514
8964
|
parseWithContext(input, parseCtx, pos = 0) {
|
|
8965
|
+
assertHostModeCompatible(ctx.hostMode ?? "ast", parseCtx.build, !!ctx.hostBranchElided);
|
|
7515
8966
|
return fn(input, pos, ctx.runtimeParsers, ctx.mapFns, ctx.buildFns, parseCtx);
|
|
7516
8967
|
},
|
|
7517
8968
|
// Note: collects expect() errors via _errors. Unlike interpreter
|
|
@@ -7542,9 +8993,11 @@ function publicRuleWrapperSource(rule, fnSource) {
|
|
|
7542
8993
|
function compileLinkable(ruleMapArg, ns, opts) {
|
|
7543
8994
|
if (!ns) throw new Error("compileLinkable: ns must be a non-empty namespace");
|
|
7544
8995
|
if (opts?.gating !== void 0) runGatingDiagnosticRules(ruleMapArg, opts.gating);
|
|
8996
|
+
if (opts?.duplication !== void 0) runDuplicationDiagnosticRules(ruleMapArg, opts.duplication);
|
|
7545
8997
|
for (const [, rule] of ruleMapArg) markUnusedValues(rule);
|
|
7546
8998
|
const grammarTrivia = opts?.trivia ?? ruleMapArg.map(([, r]) => r._meta.grammarTrivia).find(Boolean);
|
|
7547
8999
|
const grammarScanSkip = opts?.scanSkip ?? ruleMapArg.map(([, r]) => r._meta.grammarScanSkip).find(Boolean);
|
|
9000
|
+
const grammarHostMode = opts?.hostMode ?? ruleMapArg.map(([, r]) => r._meta.grammarHostMode).find(Boolean);
|
|
7548
9001
|
const ruleMap = ruleMapArg.filter(([, val]) => {
|
|
7549
9002
|
const d = val._def;
|
|
7550
9003
|
if (d.tag !== "lazy") return true;
|
|
@@ -7578,6 +9031,7 @@ function compileLinkable(ruleMapArg, ns, opts) {
|
|
|
7578
9031
|
// merely returning their scalar parse values.
|
|
7579
9032
|
capturing: opts?.captureTerminals === true || ruleMap.some(([, rule]) => hasNodeDef(rule)),
|
|
7580
9033
|
recovery: opts?.recovery ?? false,
|
|
9034
|
+
hostMode: grammarHostMode ?? "ast",
|
|
7581
9035
|
...opts?.coverage ? { coverage: { plan: opts.coverage } } : {},
|
|
7582
9036
|
lazyUsage: analyzeLazyUsageMulti(ruleMap.map(([, rule]) => rule)),
|
|
7583
9037
|
ns,
|
|
@@ -7628,7 +9082,7 @@ function compileLinkable(ruleMapArg, ns, opts) {
|
|
|
7628
9082
|
scanExternal(resolved);
|
|
7629
9083
|
return;
|
|
7630
9084
|
}
|
|
7631
|
-
for (const child of
|
|
9085
|
+
for (const child of childrenOf2(def)) scanExternal(child);
|
|
7632
9086
|
};
|
|
7633
9087
|
for (const [, rule] of ruleMap) scanExternal(rule);
|
|
7634
9088
|
}
|
|
@@ -7733,6 +9187,8 @@ function compileLinkable(ruleMapArg, ns, opts) {
|
|
|
7733
9187
|
deps: ruleDependencies(ruleMap),
|
|
7734
9188
|
needsEmptyTl: !!ctx.needsEmptyTl,
|
|
7735
9189
|
needsHostReads: !!ctx.needsHostReads,
|
|
9190
|
+
hostMode: ctx.hostMode ?? "ast",
|
|
9191
|
+
hostBranchElided: !!ctx.hostBranchElided,
|
|
7736
9192
|
hasDirectBuilders: ruleMap.some(([, rule]) => hasDirectBuildDef(rule)),
|
|
7737
9193
|
isRecognitionOnly: !hasSemanticReduction(ruleMap.map(([, rule]) => rule), externalRefs),
|
|
7738
9194
|
mfFns: mfSrcs ? [] : ctx.mapFns,
|
|
@@ -7755,7 +9211,7 @@ function hasExternalRuleRef(ruleMap) {
|
|
|
7755
9211
|
if (resolved === void 0) return p._ruleName !== void 0;
|
|
7756
9212
|
return visit(resolved);
|
|
7757
9213
|
}
|
|
7758
|
-
return
|
|
9214
|
+
return childrenOf2(def).some(visit);
|
|
7759
9215
|
};
|
|
7760
9216
|
return ruleMap.some(([, rule]) => visit(rule));
|
|
7761
9217
|
}
|
|
@@ -7777,7 +9233,7 @@ function hasSemanticReduction(roots, externalRefs) {
|
|
|
7777
9233
|
return true;
|
|
7778
9234
|
}
|
|
7779
9235
|
}
|
|
7780
|
-
return
|
|
9236
|
+
return childrenOf2(def).some(visit);
|
|
7781
9237
|
};
|
|
7782
9238
|
return roots.some(visit);
|
|
7783
9239
|
}
|
|
@@ -7846,7 +9302,7 @@ function withCtx(extra, combinator) {
|
|
|
7846
9302
|
}
|
|
7847
9303
|
|
|
7848
9304
|
// src/compiler/ir-serialize.ts
|
|
7849
|
-
function
|
|
9305
|
+
function childrenOf3(def) {
|
|
7850
9306
|
switch (def.tag) {
|
|
7851
9307
|
case "sequence":
|
|
7852
9308
|
case "choice":
|
|
@@ -7885,7 +9341,7 @@ function childrenOf2(def) {
|
|
|
7885
9341
|
return [];
|
|
7886
9342
|
}
|
|
7887
9343
|
}
|
|
7888
|
-
var
|
|
9344
|
+
var ruleNameOf3 = (c) => c._ruleName;
|
|
7889
9345
|
function lazyTarget(c) {
|
|
7890
9346
|
if (c._def.tag !== "lazy") return null;
|
|
7891
9347
|
try {
|
|
@@ -8083,18 +9539,18 @@ var Serializer = class {
|
|
|
8083
9539
|
if (seen.has(c)) return;
|
|
8084
9540
|
seen.add(c);
|
|
8085
9541
|
if (c._def.tag === "lazy") {
|
|
8086
|
-
if (
|
|
9542
|
+
if (ruleNameOf3(c) !== void 0) throw new Unserializable("scanSkip unit references a grammar rule");
|
|
8087
9543
|
const target = lazyTarget(c);
|
|
8088
9544
|
if (target) this.assertNoRuleRef(target, seen);
|
|
8089
9545
|
return;
|
|
8090
9546
|
}
|
|
8091
|
-
for (const child of
|
|
9547
|
+
for (const child of childrenOf3(c._def)) this.assertNoRuleRef(child, seen);
|
|
8092
9548
|
}
|
|
8093
9549
|
/** A `rules()` map wraps each rule value in a named `lazy` proxy; the real body is
|
|
8094
9550
|
* its target (compileLinkable unwraps the same way). A ref INSIDE a body stays a
|
|
8095
9551
|
* `g[name]` ref — only the top-level entry is unwrapped. */
|
|
8096
9552
|
body(c) {
|
|
8097
|
-
return c._def.tag === "lazy" &&
|
|
9553
|
+
return c._def.tag === "lazy" && ruleNameOf3(c) !== void 0 ? lazyTarget(c) ?? c : c;
|
|
8098
9554
|
}
|
|
8099
9555
|
run() {
|
|
8100
9556
|
for (const [, c] of this.ruleMap) this.analyze(this.body(c), /* @__PURE__ */ new Set());
|
|
@@ -8136,7 +9592,7 @@ ${outerDecls.map((d) => " " + d).join("\n")}
|
|
|
8136
9592
|
analyze(c, active) {
|
|
8137
9593
|
const def = c._def;
|
|
8138
9594
|
if (def.tag === "lazy") {
|
|
8139
|
-
if (
|
|
9595
|
+
if (ruleNameOf3(c) !== void 0) return;
|
|
8140
9596
|
const target = lazyTarget(c);
|
|
8141
9597
|
if (!target) throw new Unserializable("unresolved unnamed ref");
|
|
8142
9598
|
if (active.has(target)) {
|
|
@@ -8152,7 +9608,7 @@ ${outerDecls.map((d) => " " + d).join("\n")}
|
|
|
8152
9608
|
this.counts.set(c, (this.counts.get(c) ?? 0) + 1);
|
|
8153
9609
|
if ((this.counts.get(c) ?? 0) > 1) return;
|
|
8154
9610
|
active.add(c);
|
|
8155
|
-
for (const child of
|
|
9611
|
+
for (const child of childrenOf3(def)) this.analyze(child, active);
|
|
8156
9612
|
active.delete(c);
|
|
8157
9613
|
}
|
|
8158
9614
|
/** Reference `c`: a const var if it has one (emitting its decl first), else inline.
|
|
@@ -8188,7 +9644,7 @@ ${outerDecls.map((d) => " " + d).join("\n")}
|
|
|
8188
9644
|
const kid = (x) => this.ref(x, selfOf);
|
|
8189
9645
|
switch (def.tag) {
|
|
8190
9646
|
case "lazy": {
|
|
8191
|
-
if (
|
|
9647
|
+
if (ruleNameOf3(c) !== void 0) return `g[${JSON.stringify(ruleNameOf3(c))}]`;
|
|
8192
9648
|
const target = lazyTarget(c);
|
|
8193
9649
|
if (selfOf && target === selfOf.comb) return selfOf.var;
|
|
8194
9650
|
return this.ref(target, selfOf);
|
|
@@ -8288,8 +9744,12 @@ ${outerDecls.map((d) => " " + d).join("\n")}
|
|
|
8288
9744
|
|
|
8289
9745
|
// src/compiler/linker.ts
|
|
8290
9746
|
var _nsCounter = 0;
|
|
8291
|
-
function linkable(rulesMap, ns, trivia2) {
|
|
8292
|
-
const pieces = compileLinkable(
|
|
9747
|
+
function linkable(rulesMap, ns, trivia2, hostMode) {
|
|
9748
|
+
const pieces = compileLinkable(
|
|
9749
|
+
Object.entries(rulesMap),
|
|
9750
|
+
ns ?? `_lk${_nsCounter++}_`,
|
|
9751
|
+
{ ...trivia2 ? { trivia: trivia2 } : {}, ...hostMode ? { hostMode } : {} }
|
|
9752
|
+
);
|
|
8293
9753
|
if (!pieces) throw new Error("linkable(): this grammar cannot be compiled to a linkable artifact (contains a runtime-only parser fallback)");
|
|
8294
9754
|
return pieces;
|
|
8295
9755
|
}
|
|
@@ -8351,7 +9811,23 @@ function fusedBody(pieces) {
|
|
|
8351
9811
|
...[...winner].map(([k, p]) => p.ruleFns.get(k))
|
|
8352
9812
|
];
|
|
8353
9813
|
const wrapperEntries = [...winner].map(([k, p]) => `${JSON.stringify(k)}: ${p.wrappers.get(k)}`);
|
|
8354
|
-
const
|
|
9814
|
+
const { mode, elided } = hostModeOfPieces(pieces);
|
|
9815
|
+
const rawBody = [
|
|
9816
|
+
...lines,
|
|
9817
|
+
"const _map = {",
|
|
9818
|
+
wrapperEntries.join(",\n"),
|
|
9819
|
+
"}",
|
|
9820
|
+
`Object.defineProperty(_map, Symbol.for(${JSON.stringify(FUSED_HOST_MODE.description)}), { value: ${JSON.stringify(mode)}, enumerable: false })`,
|
|
9821
|
+
`Object.defineProperty(_map, Symbol.for(${JSON.stringify(FUSED_HOST_ELIDED.description)}), { value: ${JSON.stringify(elided)}, enumerable: false })`,
|
|
9822
|
+
// …and on each rule FUNCTION, because `run(map.Rule, …)` is handed the rule, not the
|
|
9823
|
+
// map, and would otherwise have nothing to check against. Done once at fuse time,
|
|
9824
|
+
// before any rule has been called, so it costs nothing per parse.
|
|
9825
|
+
"for (const _k of Object.keys(_map)) {",
|
|
9826
|
+
` Object.defineProperty(_map[_k], Symbol.for(${JSON.stringify(FUSED_HOST_MODE.description)}), { value: ${JSON.stringify(mode)}, enumerable: false })`,
|
|
9827
|
+
` Object.defineProperty(_map[_k], Symbol.for(${JSON.stringify(FUSED_HOST_ELIDED.description)}), { value: ${JSON.stringify(elided)}, enumerable: false })`,
|
|
9828
|
+
"}",
|
|
9829
|
+
"return _map"
|
|
9830
|
+
].join("\n");
|
|
8355
9831
|
const ANY2 = { kind: "any" };
|
|
8356
9832
|
const EMPTY3 = { kind: "empty" };
|
|
8357
9833
|
const recipes = /* @__PURE__ */ new Map();
|
|
@@ -8410,19 +9886,78 @@ function fusedBody(pieces) {
|
|
|
8410
9886
|
}
|
|
8411
9887
|
return { body, env };
|
|
8412
9888
|
}
|
|
9889
|
+
function hostModeOfPieces(pieces) {
|
|
9890
|
+
const mode = pieces.find((p) => p.hostMode !== void 0 && p.hostMode !== "ast")?.hostMode ?? "ast";
|
|
9891
|
+
const elided = pieces.filter((p) => p.hostBranchElided === true);
|
|
9892
|
+
if (mode === "cst" && elided.length > 0) {
|
|
9893
|
+
throw new Error(
|
|
9894
|
+
`compose: cannot build a positioned-CST artifact from pieces that were compiled for host mode "ast" \u2014 ${elided.map((p) => `"${p.ns}"`).join(", ")} ${elided.length === 1 ? "dropped its" : "dropped their"} direct builders' CST branch, so ${elided.length === 1 ? "it" : "they"} would return AST objects inside the CST. An already-compiled piece keeps the mode it was built with; only pieces carried as IR are re-lowered by this compose. Re-compile ${elided.length === 1 ? "it" : "them"} with hostMode: 'cst', or pass the source grammar so it can be re-lowered.`
|
|
9895
|
+
);
|
|
9896
|
+
}
|
|
9897
|
+
return { mode, elided: elided.length > 0 };
|
|
9898
|
+
}
|
|
8413
9899
|
function fuseRules(pieces) {
|
|
8414
9900
|
const { body, env } = fusedBody(pieces);
|
|
8415
9901
|
return new Function("_env", body)(env);
|
|
8416
9902
|
}
|
|
9903
|
+
function fusedHostModeOf(registry) {
|
|
9904
|
+
const m = registry[FUSED_HOST_MODE];
|
|
9905
|
+
return m === "cst" ? "cst" : "ast";
|
|
9906
|
+
}
|
|
9907
|
+
function fusedHostElidedOf(registry) {
|
|
9908
|
+
return registry[FUSED_HOST_ELIDED] === true;
|
|
9909
|
+
}
|
|
8417
9910
|
var COMPOSED_PIECES = /* @__PURE__ */ Symbol.for("parseman.composedPieces");
|
|
9911
|
+
function composedPiecesOf(grammar) {
|
|
9912
|
+
const pieces = grammar[COMPOSED_PIECES];
|
|
9913
|
+
return Array.isArray(pieces) ? pieces : void 0;
|
|
9914
|
+
}
|
|
8418
9915
|
var LEAF_COMPOSED = /* @__PURE__ */ Symbol.for("parseman.leafComposed");
|
|
8419
9916
|
var COMPOSED_TRIVIA = /* @__PURE__ */ Symbol.for("parseman.composedTrivia");
|
|
8420
9917
|
var COMPOSED_COVERAGE_RULES = /* @__PURE__ */ Symbol.for("parseman.composedCoverageRules");
|
|
8421
9918
|
function isIRPiece(p) {
|
|
8422
9919
|
return !!p && typeof p === "object" && typeof p.ir === "string" && typeof p.ns === "string" && !("ruleFns" in p);
|
|
8423
9920
|
}
|
|
8424
|
-
function
|
|
8425
|
-
|
|
9921
|
+
function once(fn) {
|
|
9922
|
+
let done = false;
|
|
9923
|
+
let value;
|
|
9924
|
+
return () => {
|
|
9925
|
+
if (!done) {
|
|
9926
|
+
value = fn();
|
|
9927
|
+
done = true;
|
|
9928
|
+
}
|
|
9929
|
+
return value;
|
|
9930
|
+
};
|
|
9931
|
+
}
|
|
9932
|
+
function carriedRuleMapsDetailed(carried) {
|
|
9933
|
+
const maps = [];
|
|
9934
|
+
const opaque = [];
|
|
9935
|
+
for (const p of carried) {
|
|
9936
|
+
if (isIRPiece(p)) {
|
|
9937
|
+
maps.push(evalRuleMapIR(p.ir));
|
|
9938
|
+
continue;
|
|
9939
|
+
}
|
|
9940
|
+
const ruleFns = p.ruleFns;
|
|
9941
|
+
opaque.push({ ns: p.ns, ruleNames: ruleFns instanceof Map ? [...ruleFns.keys()] : [] });
|
|
9942
|
+
}
|
|
9943
|
+
return { maps, opaque };
|
|
9944
|
+
}
|
|
9945
|
+
function recoverComposedRules(grammar) {
|
|
9946
|
+
const carried = composedPiecesOf(grammar);
|
|
9947
|
+
if (carried === void 0) return void 0;
|
|
9948
|
+
const { maps, opaque } = carriedRuleMapsDetailed(carried);
|
|
9949
|
+
const rules2 = /* @__PURE__ */ new Map();
|
|
9950
|
+
for (const map of maps) for (const [name, rule] of map) {
|
|
9951
|
+
if (rule._def.tag === "lazy") {
|
|
9952
|
+
try {
|
|
9953
|
+
rule._def.thunk();
|
|
9954
|
+
} catch {
|
|
9955
|
+
continue;
|
|
9956
|
+
}
|
|
9957
|
+
}
|
|
9958
|
+
rules2.set(name, rule);
|
|
9959
|
+
}
|
|
9960
|
+
return { rules: rules2, opaque };
|
|
8426
9961
|
}
|
|
8427
9962
|
function coverageRulesOf(carried) {
|
|
8428
9963
|
const winners = {};
|
|
@@ -8445,11 +9980,12 @@ function coverageRulesOf(carried) {
|
|
|
8445
9980
|
function composedCoverageRules(grammar) {
|
|
8446
9981
|
return grammar[COMPOSED_COVERAGE_RULES];
|
|
8447
9982
|
}
|
|
8448
|
-
function materializePiece(p, trivia2, captureTerminals = false) {
|
|
9983
|
+
function materializePiece(p, trivia2, captureTerminals = false, hostMode) {
|
|
8449
9984
|
if (!isIRPiece(p)) return p;
|
|
8450
9985
|
const pieces = compileLinkable(evalRuleMapIR(p.ir), p.ns, {
|
|
8451
9986
|
...trivia2 ? { trivia: trivia2 } : {},
|
|
8452
|
-
...captureTerminals ? { captureTerminals: true } : {}
|
|
9987
|
+
...captureTerminals ? { captureTerminals: true } : {},
|
|
9988
|
+
...hostMode ? { hostMode } : {}
|
|
8453
9989
|
});
|
|
8454
9990
|
if (!pieces) throw new Error(`compose: carried IR for ns "${p.ns}" could not be re-lowered`);
|
|
8455
9991
|
return pieces;
|
|
@@ -8462,7 +9998,7 @@ function nextComposeNs(used) {
|
|
|
8462
9998
|
used.add(ns);
|
|
8463
9999
|
return ns;
|
|
8464
10000
|
}
|
|
8465
|
-
function itemCarried(item, used, trivia2) {
|
|
10001
|
+
function itemCarried(item, used, trivia2, hostMode) {
|
|
8466
10002
|
const carried = item[COMPOSED_PIECES];
|
|
8467
10003
|
if (Array.isArray(carried)) {
|
|
8468
10004
|
const items = carried;
|
|
@@ -8488,7 +10024,7 @@ function itemCarried(item, used, trivia2) {
|
|
|
8488
10024
|
});
|
|
8489
10025
|
const scanSkip = entries.map(([, val]) => val._meta.grammarScanSkip).find(Boolean);
|
|
8490
10026
|
const ir = serializeRuleMap(entries, scanSkip);
|
|
8491
|
-
return ir ? [{ ns, ir }] : [linkable(map, ns, trivia2)];
|
|
10027
|
+
return ir ? [{ ns, ir }] : [linkable(map, ns, trivia2, hostMode)];
|
|
8492
10028
|
}
|
|
8493
10029
|
function composingTriviaOf(items) {
|
|
8494
10030
|
for (let i = items.length - 1; i >= 0; i--) {
|
|
@@ -8501,15 +10037,20 @@ function composingTriviaOf(items) {
|
|
|
8501
10037
|
}
|
|
8502
10038
|
return void 0;
|
|
8503
10039
|
}
|
|
8504
|
-
function compose(items) {
|
|
10040
|
+
function compose(items, opts) {
|
|
8505
10041
|
if (items.some((item) => item[LEAF_COMPOSED] === true)) {
|
|
8506
10042
|
throw new Error("compose: a composeLeaf() result is terminal and cannot be composed again");
|
|
8507
10043
|
}
|
|
8508
10044
|
const used = /* @__PURE__ */ new Set();
|
|
8509
10045
|
const trivia2 = composingTriviaOf(items);
|
|
8510
|
-
const carried = items.flatMap((item) => itemCarried(item, used, trivia2));
|
|
8511
|
-
|
|
8512
|
-
|
|
10046
|
+
const carried = items.flatMap((item) => itemCarried(item, used, trivia2, opts?.hostMode));
|
|
10047
|
+
const detailed = once(() => carriedRuleMapsDetailed(carried));
|
|
10048
|
+
runFusedGatingDiagnostic(
|
|
10049
|
+
() => detailed().maps,
|
|
10050
|
+
void 0,
|
|
10051
|
+
() => detailed().opaque
|
|
10052
|
+
);
|
|
10053
|
+
const pieces = carried.map((p) => materializePiece(p, trivia2, false, opts?.hostMode));
|
|
8513
10054
|
const map = fuseRules(pieces);
|
|
8514
10055
|
Object.defineProperty(map, COMPOSED_PIECES, { value: carried, enumerable: false });
|
|
8515
10056
|
if (trivia2) Object.defineProperty(map, COMPOSED_TRIVIA, { value: trivia2, enumerable: false });
|
|
@@ -8521,6 +10062,23 @@ function composeLeaf(_items) {
|
|
|
8521
10062
|
throw new Error("composeLeaf(): requires Parseman macro lowering; runtime composition is forbidden");
|
|
8522
10063
|
}
|
|
8523
10064
|
|
|
10065
|
+
// src/analysis/grammar.ts
|
|
10066
|
+
function analyzeGrammarGating(grammar, opts) {
|
|
10067
|
+
const recovered = recoverComposedRules(grammar);
|
|
10068
|
+
if (recovered === void 0) {
|
|
10069
|
+
return analyzeGatingRules(Object.entries(grammar), opts);
|
|
10070
|
+
}
|
|
10071
|
+
const { rules: winners, opaque } = recovered;
|
|
10072
|
+
const entries = [...winners];
|
|
10073
|
+
const report = analyzeGatingRules(entries, { ...opts, resolveRef: (name) => winners.get(name) });
|
|
10074
|
+
const fromOpaque = opaque.map((o) => ({
|
|
10075
|
+
rule: o.ruleNames.length > 0 ? o.ruleNames.join(", ") : `<artifact ${o.ns}>`,
|
|
10076
|
+
kind: "opaque-artifact",
|
|
10077
|
+
reason: `precompiled artifact "${o.ns}" carries compiled rule functions, not re-lowerable IR \u2014 its choices cannot be examined. Recompile the contributing grammar so it carries IR (the macro emits IR by default) to bring it back into analysis.`
|
|
10078
|
+
}));
|
|
10079
|
+
return fromOpaque.length === 0 ? report : { ...report, unanalysable: [...report.unanalysable, ...fromOpaque] };
|
|
10080
|
+
}
|
|
10081
|
+
|
|
8524
10082
|
// src/combinators/gate.ts
|
|
8525
10083
|
function gate(predicate) {
|
|
8526
10084
|
const meta = {
|
|
@@ -8653,7 +10211,8 @@ function editNode(node2, at, delta, parentBase, parentShift, stats) {
|
|
|
8653
10211
|
}
|
|
8654
10212
|
|
|
8655
10213
|
// src/functional/doc.ts
|
|
8656
|
-
function mkCtx(
|
|
10214
|
+
function mkCtx(rawState, build, tolerant) {
|
|
10215
|
+
const state = rawState ?? void 0;
|
|
8657
10216
|
return tolerant ? { trackLines: false, state, build, _tolerant: true, _rec: REC, _errors: [] } : { trackLines: false, state, build };
|
|
8658
10217
|
}
|
|
8659
10218
|
function asRuleFn(entry) {
|
|
@@ -9050,6 +10609,7 @@ function collectEmbeddedErrors(node2, base, out) {
|
|
|
9050
10609
|
function parseDoc(registry, rootRule, input, opts = {}) {
|
|
9051
10610
|
const entry = registry[rootRule];
|
|
9052
10611
|
if (!entry) throw new Error(`No rule '${rootRule}' in registry`);
|
|
10612
|
+
assertHostModeCompatible(fusedHostModeOf(registry), opts.build, fusedHostElidedOf(registry));
|
|
9053
10613
|
const ctx = mkCtx(opts.state, opts.build, !!opts.tolerant);
|
|
9054
10614
|
const r = asRuleFn(entry)(input, 0, ctx);
|
|
9055
10615
|
if (r.ok) {
|
|
@@ -9075,6 +10635,12 @@ function runOnce(entry, input, options, phase, profileState) {
|
|
|
9075
10635
|
const skipGlobalSinks = phase === "recognizer" || phase === "capture";
|
|
9076
10636
|
const grammarTrivia = typeof entry !== "function" ? entry._meta.grammarTrivia : void 0;
|
|
9077
10637
|
const grammarScanSkip = typeof entry !== "function" ? entry._meta.grammarScanSkip : void 0;
|
|
10638
|
+
const stamped = entry;
|
|
10639
|
+
assertHostModeCompatible(
|
|
10640
|
+
typeof entry === "function" ? stamped[FUSED_HOST_MODE] ?? "ast" : entry._meta.grammarHostMode ?? "ast",
|
|
10641
|
+
options.build,
|
|
10642
|
+
typeof entry === "function" && stamped[FUSED_HOST_ELIDED] === true
|
|
10643
|
+
);
|
|
9078
10644
|
const ctx = {
|
|
9079
10645
|
trackLines: false,
|
|
9080
10646
|
...skipGlobalSinks ? { _pmProfile: profile } : { _triviaLog: triviaLog, _errors: errors, ...profile === void 0 ? {} : { _pmProfile: profile } },
|