parseman 0.35.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/expect.d.ts +12 -0
- package/dist/combinators/expect.d.ts.map +1 -1
- 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 +1621 -55
- 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 +1621 -55
- 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 +1628 -62
- package/dist/plugin/index.cjs.map +4 -4
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +1628 -62
- 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/plugin/index.cjs
CHANGED
|
@@ -1125,7 +1125,7 @@ function captureError(ctx, error) {
|
|
|
1125
1125
|
|
|
1126
1126
|
// src/combinators/expect.ts
|
|
1127
1127
|
function deriveExpected(c) {
|
|
1128
|
-
return derive(c, /* @__PURE__ */ new Set());
|
|
1128
|
+
return [...new Set(derive(c, /* @__PURE__ */ new Set()))];
|
|
1129
1129
|
}
|
|
1130
1130
|
function derive(c, seen) {
|
|
1131
1131
|
const deriveExpected2 = (p) => derive(p, seen);
|
|
@@ -2435,6 +2435,12 @@ function rules(a, b) {
|
|
|
2435
2435
|
if (rule && !rule._meta.isTrivia) rule._meta.grammarScanSkip = options.scanSkip;
|
|
2436
2436
|
}
|
|
2437
2437
|
}
|
|
2438
|
+
if (options?.hostMode === "cst") {
|
|
2439
|
+
for (const key of Object.keys(definitions)) {
|
|
2440
|
+
const rule = cache[key];
|
|
2441
|
+
if (rule && !rule._meta.isTrivia) rule._meta.grammarHostMode = "cst";
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2438
2444
|
for (const key of Object.keys(definitions)) {
|
|
2439
2445
|
markUnusedValues(cache[key]);
|
|
2440
2446
|
}
|
|
@@ -2493,6 +2499,9 @@ function peek(combinator) {
|
|
|
2493
2499
|
}
|
|
2494
2500
|
|
|
2495
2501
|
// src/compiler/build-arity.ts
|
|
2502
|
+
function cstOutputHost(build) {
|
|
2503
|
+
return build?._parsemanCstOutput === true;
|
|
2504
|
+
}
|
|
2496
2505
|
var PARAM_LIST_RE = (
|
|
2497
2506
|
// (params) => ... | function name?(params) ... | single-ident arrow `x => ...`
|
|
2498
2507
|
/^(?:function\b[^(]*\(([^)]*)\)|\(([^)]*)\)\s*=>|([A-Za-z_$][\w$]*)\s*=>)/
|
|
@@ -2742,7 +2751,8 @@ function node(typeOrCombinator, combinatorOrBuild, buildOrOpts, maybeOpts) {
|
|
|
2742
2751
|
const def = unwrap || collapse || captureTrivia || trailingTrivia ? { ...baseDef, ...unwrap ? { unwrap: true } : {}, ...collapse ? { collapse: true } : {}, ...captureTrivia ? { captureTrivia: true } : {}, ...trailingTrivia ? { trailingTrivia: true } : {} } : baseDef;
|
|
2743
2752
|
const capturesTrivia = captureTrivia || trailingTrivia || (build ? buildReadsTrivia(def) : true);
|
|
2744
2753
|
const clonesState = build ? buildReadsState(def) : true;
|
|
2745
|
-
const
|
|
2754
|
+
const hasOwnFields = parserHasOwnFields(combinator);
|
|
2755
|
+
const capturesFields = hasOwnFields && (build ? buildReadsFields(def) : true);
|
|
2746
2756
|
const guardable = combinator._meta.firstSet.kind !== "any" && !matchesEmpty(combinator);
|
|
2747
2757
|
let failExpected;
|
|
2748
2758
|
return {
|
|
@@ -2757,28 +2767,32 @@ function node(typeOrCombinator, combinatorOrBuild, buildOrOpts, maybeOpts) {
|
|
|
2757
2767
|
}
|
|
2758
2768
|
return { ok: false, expected: failExpected, span: { start: pos, end: pos } };
|
|
2759
2769
|
}
|
|
2770
|
+
const hostCst = build !== void 0 && cstOutputHost(ctx.build);
|
|
2771
|
+
const effTrivia = capturesTrivia || hostCst;
|
|
2772
|
+
const effFields = capturesFields || hostCst && hasOwnFields;
|
|
2760
2773
|
const saved = beginCstNodeCapture(ctx);
|
|
2761
2774
|
const savedFields = ctx._fields;
|
|
2762
|
-
ctx._fields =
|
|
2775
|
+
ctx._fields = effFields ? [] : void 0;
|
|
2763
2776
|
const savedMask = ctx._triviaCaptureMask;
|
|
2764
2777
|
if (build === void 0 && ctx.build?._parsemanTriviaKinds !== void 0 && def.type !== void 0) {
|
|
2765
2778
|
ctx._triviaCaptureMask = ctx.build._parsemanTriviaKinds(def.type);
|
|
2766
2779
|
}
|
|
2767
|
-
if (!
|
|
2780
|
+
if (!effTrivia) ctx.captureTrivia = false;
|
|
2768
2781
|
let r = combinator.parse(input, pos, ctx);
|
|
2769
2782
|
if (r.ok && trailingTrivia && ctx.trivia) {
|
|
2770
2783
|
const end = consumeTrivia(input, r.span.end, ctx);
|
|
2771
2784
|
r = { ...r, span: { start: r.span.start, end } };
|
|
2772
2785
|
}
|
|
2773
|
-
const fields =
|
|
2786
|
+
const fields = effFields ? buildFieldMap(ctx._fields) : void 0;
|
|
2774
2787
|
ctx._fields = savedFields;
|
|
2775
2788
|
ctx._triviaCaptureMask = savedMask;
|
|
2776
2789
|
const { children: children2, rawChildren, triviaLog } = endCstNodeCapture(ctx, saved);
|
|
2777
2790
|
if (!r.ok) return r;
|
|
2778
2791
|
const st = clonesState && ctx.state !== void 0 ? Object.assign({}, ctx.state) : void 0;
|
|
2779
2792
|
const nodeType = def.type ?? missingInferredType();
|
|
2780
|
-
const cstOutput = ctx.build
|
|
2781
|
-
const
|
|
2793
|
+
const cstOutput = cstOutputHost(ctx.build);
|
|
2794
|
+
const hostState = clonesState ? st : ctx.state !== void 0 ? Object.assign({}, ctx.state) : void 0;
|
|
2795
|
+
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 };
|
|
2782
2796
|
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 };
|
|
2783
2797
|
if (saved.buf !== void 0 || saved.ch !== void 0) {
|
|
2784
2798
|
pushCstChild(ctx, built, rawEntry);
|
|
@@ -3029,7 +3043,24 @@ function leaf(root, fn) {
|
|
|
3029
3043
|
}
|
|
3030
3044
|
|
|
3031
3045
|
// src/version.ts
|
|
3032
|
-
var PARSEMAN_VERSION = "0.
|
|
3046
|
+
var PARSEMAN_VERSION = "0.37.0";
|
|
3047
|
+
|
|
3048
|
+
// src/cst/host-mode.ts
|
|
3049
|
+
var FUSED_HOST_MODE = /* @__PURE__ */ Symbol.for("parseman.fusedHostMode");
|
|
3050
|
+
var FUSED_HOST_ELIDED = /* @__PURE__ */ Symbol.for("parseman.fusedHostElided");
|
|
3051
|
+
function assertHostModeCompatible(mode, build, hostBranchElided = true) {
|
|
3052
|
+
const isCstHost = build?._parsemanCstOutput === true;
|
|
3053
|
+
if (mode === "ast" && isCstHost && hostBranchElided) {
|
|
3054
|
+
throw new Error(
|
|
3055
|
+
"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."
|
|
3056
|
+
);
|
|
3057
|
+
}
|
|
3058
|
+
if (mode === "cst" && !isCstHost) {
|
|
3059
|
+
throw new Error(
|
|
3060
|
+
'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.'
|
|
3061
|
+
);
|
|
3062
|
+
}
|
|
3063
|
+
}
|
|
3033
3064
|
|
|
3034
3065
|
// src/analysis/gating.ts
|
|
3035
3066
|
var isAny = (fs2) => fs2.kind === "any";
|
|
@@ -3229,11 +3260,34 @@ function analyzeGating(entry, opts) {
|
|
|
3229
3260
|
function analyzeGatingRules(ruleMap, opts) {
|
|
3230
3261
|
const raw = [];
|
|
3231
3262
|
const antiPatterns = [];
|
|
3263
|
+
const unanalysable = [];
|
|
3264
|
+
const seenUnanalysable = /* @__PURE__ */ new Set();
|
|
3232
3265
|
const visited = /* @__PURE__ */ new Set();
|
|
3266
|
+
const noteUnanalysable = (u) => {
|
|
3267
|
+
const key = `${u.rule}\0${u.kind}`;
|
|
3268
|
+
if (seenUnanalysable.has(key)) return;
|
|
3269
|
+
seenUnanalysable.add(key);
|
|
3270
|
+
unanalysable.push(u);
|
|
3271
|
+
};
|
|
3233
3272
|
const visit = (p, enclosingRule) => {
|
|
3234
3273
|
if (visited.has(p)) return;
|
|
3235
3274
|
visited.add(p);
|
|
3236
|
-
const
|
|
3275
|
+
const def = p?._def;
|
|
3276
|
+
if (def === null || typeof def !== "object") {
|
|
3277
|
+
noteUnanalysable(
|
|
3278
|
+
typeof p === "function" ? {
|
|
3279
|
+
rule: enclosingRule,
|
|
3280
|
+
kind: "fused-rule",
|
|
3281
|
+
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."
|
|
3282
|
+
} : {
|
|
3283
|
+
rule: enclosingRule,
|
|
3284
|
+
kind: "not-a-combinator",
|
|
3285
|
+
reason: `value of type ${p === null ? "null" : typeof p} is not a combinator and carries no _def descriptor.`
|
|
3286
|
+
}
|
|
3287
|
+
);
|
|
3288
|
+
return;
|
|
3289
|
+
}
|
|
3290
|
+
const d = def;
|
|
3237
3291
|
const rule = ruleNameOf(p) ?? enclosingRule;
|
|
3238
3292
|
if (d.tag === "choice") {
|
|
3239
3293
|
raw.push({ g: analyzeChoice(p, d, rule, opts?.resolveRef), rule });
|
|
@@ -3273,7 +3327,18 @@ function analyzeGatingRules(ruleMap, opts) {
|
|
|
3273
3327
|
const accepted = choices.filter((c) => c.gates === "no" && c.accepted);
|
|
3274
3328
|
const deferred = choices.filter((c) => c.gates === "no" && !c.accepted && c.deferred);
|
|
3275
3329
|
const acceptedUnused = [...accept].filter((id) => !usedAccept.has(id));
|
|
3276
|
-
return {
|
|
3330
|
+
return {
|
|
3331
|
+
totalChoices: choices.length,
|
|
3332
|
+
gated,
|
|
3333
|
+
recoverable,
|
|
3334
|
+
unanalysable,
|
|
3335
|
+
ungated,
|
|
3336
|
+
accepted,
|
|
3337
|
+
deferred,
|
|
3338
|
+
acceptedUnused,
|
|
3339
|
+
choices,
|
|
3340
|
+
antiPatterns
|
|
3341
|
+
};
|
|
3277
3342
|
}
|
|
3278
3343
|
function analyzeChoice(p, d, rule, resolve2) {
|
|
3279
3344
|
const arms = d.parsers;
|
|
@@ -3310,6 +3375,13 @@ function analyzeChoice(p, d, rule, resolve2) {
|
|
|
3310
3375
|
}
|
|
3311
3376
|
function formatGatingWarnings(report) {
|
|
3312
3377
|
const lines = [];
|
|
3378
|
+
if (report.unanalysable.length > 0) {
|
|
3379
|
+
lines.push(
|
|
3380
|
+
`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.`
|
|
3381
|
+
);
|
|
3382
|
+
for (const u of report.unanalysable)
|
|
3383
|
+
lines.push(` \xB7 ${u.rule} [${u.kind}]: ${u.reason}`);
|
|
3384
|
+
}
|
|
3313
3385
|
for (const c of report.ungated) {
|
|
3314
3386
|
lines.push(`parseman gating: choice @ ${c.id} is UNGATED [${c.strategy}] \u2014 no first-char dispatch; every position speculatively enters doomed arms.`);
|
|
3315
3387
|
for (const a of c.anyArms)
|
|
@@ -3325,6 +3397,1284 @@ function formatGatingWarnings(report) {
|
|
|
3325
3397
|
return lines;
|
|
3326
3398
|
}
|
|
3327
3399
|
|
|
3400
|
+
// src/analysis/duplication.ts
|
|
3401
|
+
var siteToString = (s) => s.path === "" ? s.rule : `${s.rule} \u203A ${s.path}`;
|
|
3402
|
+
function childrenOf(d) {
|
|
3403
|
+
switch (d.tag) {
|
|
3404
|
+
case "sequence":
|
|
3405
|
+
case "choice":
|
|
3406
|
+
return d.parsers;
|
|
3407
|
+
case "skip":
|
|
3408
|
+
return [d.main, d.skipped];
|
|
3409
|
+
case "sepBy":
|
|
3410
|
+
return [d.parser, d.separator];
|
|
3411
|
+
case "recover":
|
|
3412
|
+
return [d.parser, d.sentinel];
|
|
3413
|
+
case "scanTo":
|
|
3414
|
+
return [d.sentinel, ...d.skip];
|
|
3415
|
+
case "grammar":
|
|
3416
|
+
return d.triviaParser ? [d.parser, d.triviaParser] : [d.parser];
|
|
3417
|
+
// A `lazy` is a REFERENCE, not a subtree: hashing through it would make every
|
|
3418
|
+
// rule's shape include the whole reachable grammar. Treated as a leaf, keyed
|
|
3419
|
+
// by the rule name it refers to — which is also the right semantics, since two
|
|
3420
|
+
// productions referencing `g.Ident` really do fill that slot the same way.
|
|
3421
|
+
case "lazy":
|
|
3422
|
+
case "literal":
|
|
3423
|
+
case "regex":
|
|
3424
|
+
case "keywords":
|
|
3425
|
+
case "guard":
|
|
3426
|
+
case "unknown":
|
|
3427
|
+
return [];
|
|
3428
|
+
default: {
|
|
3429
|
+
const rec = d;
|
|
3430
|
+
return rec.parser ? [rec.parser] : [];
|
|
3431
|
+
}
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
var ruleNameOf2 = (p) => p._ruleName;
|
|
3435
|
+
var fnKey = (src, fn) => src ?? (typeof fn === "function" ? String(fn) : "");
|
|
3436
|
+
function payloadKey(p, d) {
|
|
3437
|
+
switch (d.tag) {
|
|
3438
|
+
case "literal":
|
|
3439
|
+
return `literal\0${d.value}\0${d.caseInsensitive}`;
|
|
3440
|
+
case "regex":
|
|
3441
|
+
return `regex\0${d.source}\0${d.flags}`;
|
|
3442
|
+
case "keywords":
|
|
3443
|
+
return `keywords\0${[...d.words].join("")}\0${d.caseInsensitive}\0${d.boundary ?? ""}`;
|
|
3444
|
+
case "lazy": {
|
|
3445
|
+
const n = ruleNameOf2(p);
|
|
3446
|
+
return n === void 0 ? `ref\0#${anonId(p)}` : `ref\0${n}`;
|
|
3447
|
+
}
|
|
3448
|
+
case "label":
|
|
3449
|
+
return `label\0${d.label}`;
|
|
3450
|
+
case "field":
|
|
3451
|
+
return `field\0${d.name}`;
|
|
3452
|
+
case "node":
|
|
3453
|
+
return `node\0${d.type ?? ""}\0${d.unwrap === true}\0${d.collapse === true}\0${fnKey(d.buildSrc, d.build)}`;
|
|
3454
|
+
case "transform":
|
|
3455
|
+
return `transform\0${fnKey(d.fnSrc, d.fn)}\0${d.recognitionOnly === true}`;
|
|
3456
|
+
case "leaf":
|
|
3457
|
+
return `leaf\0${fnKey(d.fnSrc, d.fn)}`;
|
|
3458
|
+
case "many":
|
|
3459
|
+
case "oneOrMore":
|
|
3460
|
+
return `${d.tag}\0${d.min}\0${d.max ?? ""}`;
|
|
3461
|
+
case "sepBy":
|
|
3462
|
+
return `sepBy\0${d.min}\0${d.max ?? ""}\0${d.trailing ?? ""}`;
|
|
3463
|
+
case "expect":
|
|
3464
|
+
return `expect\0${d.label ?? ""}\0${d.expected.join("")}`;
|
|
3465
|
+
case "scanTo":
|
|
3466
|
+
return `scanTo\0${d.raw}\0${d.orEOF}`;
|
|
3467
|
+
case "guard":
|
|
3468
|
+
return `guard\0${fnKey(d.predSrc, d.predicate)}`;
|
|
3469
|
+
case "withCtx":
|
|
3470
|
+
return `withCtx\0${d.extraSrc ?? safeJson(d.extra)}`;
|
|
3471
|
+
case "grammar":
|
|
3472
|
+
return `grammar\0${d.clearTrivia === true}\0${d.captureTrivia === true}\0${d.trackLines}`;
|
|
3473
|
+
default:
|
|
3474
|
+
return d.tag;
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
function safeJson(v2) {
|
|
3478
|
+
try {
|
|
3479
|
+
return JSON.stringify(v2) ?? String(v2);
|
|
3480
|
+
} catch {
|
|
3481
|
+
return "?";
|
|
3482
|
+
}
|
|
3483
|
+
}
|
|
3484
|
+
var anonCounter = 0;
|
|
3485
|
+
var anonIds = /* @__PURE__ */ new WeakMap();
|
|
3486
|
+
function anonId(p) {
|
|
3487
|
+
let id = anonIds.get(p);
|
|
3488
|
+
if (id === void 0) {
|
|
3489
|
+
id = ++anonCounter;
|
|
3490
|
+
anonIds.set(p, id);
|
|
3491
|
+
}
|
|
3492
|
+
return id;
|
|
3493
|
+
}
|
|
3494
|
+
var Interner = class {
|
|
3495
|
+
ids = /* @__PURE__ */ new Map();
|
|
3496
|
+
hole;
|
|
3497
|
+
constructor() {
|
|
3498
|
+
this.hole = this.of("\0HOLE\0");
|
|
3499
|
+
}
|
|
3500
|
+
of(key) {
|
|
3501
|
+
let id = this.ids.get(key);
|
|
3502
|
+
if (id === void 0) {
|
|
3503
|
+
id = this.ids.size;
|
|
3504
|
+
this.ids.set(key, id);
|
|
3505
|
+
}
|
|
3506
|
+
return id;
|
|
3507
|
+
}
|
|
3508
|
+
};
|
|
3509
|
+
var MAX_RENDER = 160;
|
|
3510
|
+
function render(p, depth = 3) {
|
|
3511
|
+
const d = p._def;
|
|
3512
|
+
const name = ruleNameOf2(p);
|
|
3513
|
+
switch (d.tag) {
|
|
3514
|
+
case "literal":
|
|
3515
|
+
return `literal('${d.value}')`;
|
|
3516
|
+
case "regex":
|
|
3517
|
+
return `regex(/${d.source}/${d.flags})`;
|
|
3518
|
+
case "keywords":
|
|
3519
|
+
return `keywords([${[...d.words].slice(0, 4).map((w) => `'${w}'`).join(", ")}${d.words.length > 4 ? ", \u2026" : ""}])`;
|
|
3520
|
+
case "lazy":
|
|
3521
|
+
return `g.${name ?? "?"}`;
|
|
3522
|
+
case "guard":
|
|
3523
|
+
return "gate(\u2026)";
|
|
3524
|
+
default:
|
|
3525
|
+
break;
|
|
3526
|
+
}
|
|
3527
|
+
if (depth <= 0) return `${d.tag}(\u2026)`;
|
|
3528
|
+
const kids = childrenOf(d).map((k) => render(k, depth - 1));
|
|
3529
|
+
switch (d.tag) {
|
|
3530
|
+
case "sequence":
|
|
3531
|
+
return `sequence(${kids.join(", ")})`;
|
|
3532
|
+
case "choice":
|
|
3533
|
+
return `choice(${kids.join(", ")})`;
|
|
3534
|
+
case "node":
|
|
3535
|
+
return `node(${d.type ? `'${d.type}', ` : ""}${kids[0] ?? ""})`;
|
|
3536
|
+
case "label":
|
|
3537
|
+
return `label('${d.label}', ${kids[0] ?? ""})`;
|
|
3538
|
+
case "field":
|
|
3539
|
+
return `field('${d.name}', ${kids[0] ?? ""})`;
|
|
3540
|
+
case "many":
|
|
3541
|
+
return `many(${kids[0] ?? ""}${d.min === 0 && d.max === void 0 ? "" : `, { min: ${d.min}${d.max === void 0 ? "" : `, max: ${d.max}`} }`})`;
|
|
3542
|
+
case "oneOrMore":
|
|
3543
|
+
return `oneOrMore(${kids[0] ?? ""}${d.min === 1 && d.max === void 0 ? "" : `, { min: ${d.min}${d.max === void 0 ? "" : `, max: ${d.max}`} }`})`;
|
|
3544
|
+
case "sepBy":
|
|
3545
|
+
return `sepBy(${kids[0] ?? ""}, ${kids[1] ?? ""})`;
|
|
3546
|
+
default:
|
|
3547
|
+
return `${d.tag}(${kids.join(", ")})`;
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
var clamp = (s) => s.length <= MAX_RENDER ? s : `${s.slice(0, MAX_RENDER - 1)}\u2026`;
|
|
3551
|
+
function segment(d, index) {
|
|
3552
|
+
switch (d.tag) {
|
|
3553
|
+
case "sequence":
|
|
3554
|
+
return `seq[${index}]`;
|
|
3555
|
+
case "choice":
|
|
3556
|
+
return `choice[${index}]`;
|
|
3557
|
+
case "node":
|
|
3558
|
+
return `node(${d.type ?? ""})`;
|
|
3559
|
+
case "label":
|
|
3560
|
+
return `label(${d.label})`;
|
|
3561
|
+
case "field":
|
|
3562
|
+
return `field(${d.name})`;
|
|
3563
|
+
case "sepBy":
|
|
3564
|
+
return index === 0 ? "sepBy.item" : "sepBy.sep";
|
|
3565
|
+
case "skip":
|
|
3566
|
+
return index === 0 ? "skip.main" : "skip.skipped";
|
|
3567
|
+
case "recover":
|
|
3568
|
+
return index === 0 ? "recover.body" : "recover.sentinel";
|
|
3569
|
+
case "scanTo":
|
|
3570
|
+
return index === 0 ? "scanTo.sentinel" : `scanTo.skip[${index - 1}]`;
|
|
3571
|
+
default:
|
|
3572
|
+
return d.tag;
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
3575
|
+
function alternationGroups(src) {
|
|
3576
|
+
const out = [];
|
|
3577
|
+
const stack = [{ branches: [], last: 0 }];
|
|
3578
|
+
let i = 0;
|
|
3579
|
+
while (i < src.length) {
|
|
3580
|
+
const c = src[i];
|
|
3581
|
+
if (c === "\\") {
|
|
3582
|
+
i += 2;
|
|
3583
|
+
continue;
|
|
3584
|
+
}
|
|
3585
|
+
if (c === "[") {
|
|
3586
|
+
let j = i + 1;
|
|
3587
|
+
if (src[j] === "^") j++;
|
|
3588
|
+
if (src[j] === "]") j++;
|
|
3589
|
+
while (j < src.length && src[j] !== "]") {
|
|
3590
|
+
if (src[j] === "\\") j++;
|
|
3591
|
+
j++;
|
|
3592
|
+
}
|
|
3593
|
+
i = j + 1;
|
|
3594
|
+
continue;
|
|
3595
|
+
}
|
|
3596
|
+
if (c === "(") {
|
|
3597
|
+
let open = i + 1;
|
|
3598
|
+
if (src[open] === "?") {
|
|
3599
|
+
const rest = src.slice(open);
|
|
3600
|
+
const m = /^\?(?::|=|!|<=|<!|<[^>]*>)/.exec(rest);
|
|
3601
|
+
open += m ? m[0].length : 1;
|
|
3602
|
+
}
|
|
3603
|
+
stack.push({ branches: [], last: open });
|
|
3604
|
+
i = open;
|
|
3605
|
+
continue;
|
|
3606
|
+
}
|
|
3607
|
+
if (c === ")") {
|
|
3608
|
+
const top = stack.pop();
|
|
3609
|
+
if (top !== void 0) {
|
|
3610
|
+
top.branches.push(src.slice(top.last, i));
|
|
3611
|
+
if (top.branches.length >= 2) out.push(top.branches);
|
|
3612
|
+
}
|
|
3613
|
+
i++;
|
|
3614
|
+
continue;
|
|
3615
|
+
}
|
|
3616
|
+
if (c === "|") {
|
|
3617
|
+
const top = stack[stack.length - 1];
|
|
3618
|
+
top.branches.push(src.slice(top.last, i));
|
|
3619
|
+
top.last = i + 1;
|
|
3620
|
+
i++;
|
|
3621
|
+
continue;
|
|
3622
|
+
}
|
|
3623
|
+
i++;
|
|
3624
|
+
}
|
|
3625
|
+
const root = stack[0];
|
|
3626
|
+
root.branches.push(src.slice(root.last));
|
|
3627
|
+
if (root.branches.length >= 2) out.push(root.branches);
|
|
3628
|
+
return out;
|
|
3629
|
+
}
|
|
3630
|
+
var WORD_RE_SRC = "-?[A-Za-z][A-Za-z0-9_-]*";
|
|
3631
|
+
var WORDS_RE = new RegExp(`^${WORD_RE_SRC}(?:\\|${WORD_RE_SRC})*$`);
|
|
3632
|
+
var VOCABULARY_MIN_WORDS = 3;
|
|
3633
|
+
function keywordRegexShape(source) {
|
|
3634
|
+
let s = source;
|
|
3635
|
+
if (s.startsWith("^")) s = s.slice(1);
|
|
3636
|
+
s = s.replace(/^\(\?<!\[[^\]]+\]\)/, "");
|
|
3637
|
+
let boundary = null;
|
|
3638
|
+
const tail = /(?:\(\?!\[([^\]]+)\]\)|\\b)$/.exec(s);
|
|
3639
|
+
if (tail !== null) {
|
|
3640
|
+
const cls = tail[1];
|
|
3641
|
+
if (cls !== void 0 && cls.startsWith("^")) return null;
|
|
3642
|
+
boundary = cls ?? "_0-9A-Za-z";
|
|
3643
|
+
s = s.slice(0, tail.index);
|
|
3644
|
+
}
|
|
3645
|
+
const grouped = /^\(\?:([^()]*)\)$/.exec(s);
|
|
3646
|
+
if (grouped !== null) s = grouped[1];
|
|
3647
|
+
if (s.endsWith("$")) s = s.slice(0, -1);
|
|
3648
|
+
if (!WORDS_RE.test(s)) return null;
|
|
3649
|
+
const words = s.split("|");
|
|
3650
|
+
if (boundary === null && words.length < VOCABULARY_MIN_WORDS) return null;
|
|
3651
|
+
return { words, boundary };
|
|
3652
|
+
}
|
|
3653
|
+
function boundaryMatches(boundary, ch2) {
|
|
3654
|
+
const cp = ch2.codePointAt(0);
|
|
3655
|
+
for (const m of charClassMembers(boundary)) {
|
|
3656
|
+
if (m === "\\w") {
|
|
3657
|
+
if (/[A-Za-z0-9_]/.test(ch2)) return true;
|
|
3658
|
+
continue;
|
|
3659
|
+
}
|
|
3660
|
+
if (m === "\\d") {
|
|
3661
|
+
if (/[0-9]/.test(ch2)) return true;
|
|
3662
|
+
continue;
|
|
3663
|
+
}
|
|
3664
|
+
if (m === "\\s") {
|
|
3665
|
+
if (/\s/.test(ch2)) return true;
|
|
3666
|
+
continue;
|
|
3667
|
+
}
|
|
3668
|
+
const range = /^(.|\\u[0-9a-f]{4})-(.|\\u[0-9a-f]{4})$/.exec(m);
|
|
3669
|
+
if (range !== null) {
|
|
3670
|
+
const dec = (t) => t.startsWith("\\u") ? parseInt(t.slice(2), 16) : t.codePointAt(0);
|
|
3671
|
+
if (cp >= dec(range[1]) && cp <= dec(range[2])) return true;
|
|
3672
|
+
continue;
|
|
3673
|
+
}
|
|
3674
|
+
if (m === ch2) return true;
|
|
3675
|
+
}
|
|
3676
|
+
return false;
|
|
3677
|
+
}
|
|
3678
|
+
function keywordAlternationHazards(words, boundary) {
|
|
3679
|
+
const out = [];
|
|
3680
|
+
for (let i = 0; i < words.length; i++) {
|
|
3681
|
+
for (let j = i + 1; j < words.length; j++) {
|
|
3682
|
+
const a = words[i], b = words[j];
|
|
3683
|
+
if (a.length >= b.length || !b.startsWith(a)) continue;
|
|
3684
|
+
const at = b[a.length];
|
|
3685
|
+
out.push({ shorter: a, longer: b, at, rescuedByBoundary: boundary !== null && boundaryMatches(boundary, at) });
|
|
3686
|
+
}
|
|
3687
|
+
}
|
|
3688
|
+
return out;
|
|
3689
|
+
}
|
|
3690
|
+
function analyzeDuplication(entry, opts) {
|
|
3691
|
+
return analyzeDuplicationRules([[ruleNameOf2(entry) ?? opts?.entryName ?? "<entry>", entry]], opts);
|
|
3692
|
+
}
|
|
3693
|
+
function assertAnalyzable(ruleMap) {
|
|
3694
|
+
for (const [name, rule] of ruleMap) {
|
|
3695
|
+
const def = rule?._def;
|
|
3696
|
+
if (def !== null && typeof def === "object" && typeof def.tag === "string") continue;
|
|
3697
|
+
throw new TypeError(
|
|
3698
|
+
`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.`
|
|
3699
|
+
);
|
|
3700
|
+
}
|
|
3701
|
+
}
|
|
3702
|
+
function analyzeDuplicationRules(ruleMap, opts) {
|
|
3703
|
+
assertAnalyzable(ruleMap);
|
|
3704
|
+
const minSize = opts?.minSize ?? 3;
|
|
3705
|
+
const maxFindings = opts?.maxFindings ?? 25;
|
|
3706
|
+
const interner = new Interner();
|
|
3707
|
+
const shapeCache = /* @__PURE__ */ new Map();
|
|
3708
|
+
const sizeCache = /* @__PURE__ */ new Map();
|
|
3709
|
+
const shapeOf = (p) => {
|
|
3710
|
+
const hit = shapeCache.get(p);
|
|
3711
|
+
if (hit !== void 0) return hit;
|
|
3712
|
+
const d = p._def;
|
|
3713
|
+
shapeCache.set(p, interner.hole);
|
|
3714
|
+
const kids = childrenOf(d);
|
|
3715
|
+
const id = interner.of(`${payloadKey(p, d)}|${kids.map(shapeOf).join(",")}`);
|
|
3716
|
+
shapeCache.set(p, id);
|
|
3717
|
+
return id;
|
|
3718
|
+
};
|
|
3719
|
+
const sizeOf = (p) => {
|
|
3720
|
+
const hit = sizeCache.get(p);
|
|
3721
|
+
if (hit !== void 0) return hit;
|
|
3722
|
+
sizeCache.set(p, 1);
|
|
3723
|
+
let n = 1;
|
|
3724
|
+
for (const k of childrenOf(p._def)) n += sizeOf(k);
|
|
3725
|
+
sizeCache.set(p, n);
|
|
3726
|
+
return n;
|
|
3727
|
+
};
|
|
3728
|
+
const visited = /* @__PURE__ */ new Map();
|
|
3729
|
+
const visit = (p, rule, path2, enclosingNode, enclosingReducer) => {
|
|
3730
|
+
if (visited.has(p)) return;
|
|
3731
|
+
const d = p._def;
|
|
3732
|
+
const own = ruleNameOf2(p);
|
|
3733
|
+
const here = own !== void 0 && own !== rule ? { rule: own, path: "" } : { rule, path: path2 };
|
|
3734
|
+
visited.set(p, { p, d, site: here, shape: shapeOf(p), size: sizeOf(p), enclosingNode, enclosingReducer });
|
|
3735
|
+
const inner = d.tag === "node" ? d.type ?? "(anonymous)" : enclosingNode;
|
|
3736
|
+
const innerReducer = enclosingReducer || d.tag === "node" && (d.build !== void 0 || d.buildSrc !== void 0) || d.tag === "transform" || d.tag === "leaf";
|
|
3737
|
+
const kids = childrenOf(d);
|
|
3738
|
+
kids.forEach((k, i) => {
|
|
3739
|
+
const seg = segment(d, i);
|
|
3740
|
+
visit(k, here.rule, here.path === "" ? seg : `${here.path} \u203A ${seg}`, inner, innerReducer);
|
|
3741
|
+
});
|
|
3742
|
+
if (d.tag === "lazy") {
|
|
3743
|
+
try {
|
|
3744
|
+
const target = d.thunk();
|
|
3745
|
+
visit(target, ruleNameOf2(target) ?? ruleNameOf2(p) ?? here.rule, "", null, false);
|
|
3746
|
+
} catch {
|
|
3747
|
+
}
|
|
3748
|
+
}
|
|
3749
|
+
};
|
|
3750
|
+
for (const [name, root] of ruleMap) visit(root, ruleNameOf2(root) ?? name, "", null, false);
|
|
3751
|
+
const accept = new Set(opts?.accept ?? []);
|
|
3752
|
+
const used = /* @__PURE__ */ new Set();
|
|
3753
|
+
const keep = (f) => {
|
|
3754
|
+
if (!accept.has(f.id)) return true;
|
|
3755
|
+
used.add(f.id);
|
|
3756
|
+
return false;
|
|
3757
|
+
};
|
|
3758
|
+
const duplicates = findExactDuplicates(visited, minSize);
|
|
3759
|
+
const nearDuplicates = findNearDuplicates(visited, interner, shapeOf, minSize);
|
|
3760
|
+
const regexFragments = findRegexFragments(visited);
|
|
3761
|
+
const regexClasses = findRegexClasses(visited);
|
|
3762
|
+
const overlaps = findOverlaps(visited, shapeOf, opts?.resolveRef);
|
|
3763
|
+
const rewrites = findRewrites(visited, shapeOf);
|
|
3764
|
+
const divergentNodes = findDivergentNodes(visited, shapeOf);
|
|
3765
|
+
const structureLoss = findStructureLoss(visited, opts?.resolveRef);
|
|
3766
|
+
const keywordRegexes = findKeywordRegexes(visited);
|
|
3767
|
+
const subsume = (fs2) => {
|
|
3768
|
+
const covered = /* @__PURE__ */ new Set();
|
|
3769
|
+
const surviving = /* @__PURE__ */ new Set();
|
|
3770
|
+
for (const f of [...fs2].sort((a, b) => b.savings - a.savings)) {
|
|
3771
|
+
if (f._members.every((m) => covered.has(m))) continue;
|
|
3772
|
+
surviving.add(f.id);
|
|
3773
|
+
for (const m of f._members) markSubtree(m, covered);
|
|
3774
|
+
}
|
|
3775
|
+
return surviving;
|
|
3776
|
+
};
|
|
3777
|
+
const survivingExact = subsume(duplicates);
|
|
3778
|
+
const survivingNear = subsume(nearDuplicates);
|
|
3779
|
+
const report = {
|
|
3780
|
+
duplicates: duplicates.filter((f) => survivingExact.has(f.id)).filter(keep).slice(0, maxFindings).map(stripMembers),
|
|
3781
|
+
nearDuplicates: nearDuplicates.filter((f) => survivingNear.has(f.id)).filter(keep).slice(0, maxFindings).map(stripMembers),
|
|
3782
|
+
regexFragments: regexFragments.filter(keep).slice(0, maxFindings),
|
|
3783
|
+
regexClasses: regexClasses.filter(keep).slice(0, maxFindings),
|
|
3784
|
+
overlaps: overlaps.filter(keep).slice(0, maxFindings),
|
|
3785
|
+
rewrites: rewrites.filter(keep).slice(0, maxFindings),
|
|
3786
|
+
divergentNodes: divergentNodes.filter(keep).slice(0, maxFindings),
|
|
3787
|
+
structureLoss: structureLoss.filter(keep).slice(0, maxFindings),
|
|
3788
|
+
keywordRegexes: keywordRegexes.filter(keep).slice(0, maxFindings),
|
|
3789
|
+
acceptedUnused: [...accept].filter((id) => !used.has(id)),
|
|
3790
|
+
stats: { rules: ruleMap.length, nodes: visited.size, shapes: new Set([...visited.values()].map((v2) => v2.shape)).size }
|
|
3791
|
+
};
|
|
3792
|
+
return report;
|
|
3793
|
+
}
|
|
3794
|
+
function markSubtree(p, into) {
|
|
3795
|
+
if (into.has(p)) return;
|
|
3796
|
+
into.add(p);
|
|
3797
|
+
for (const k of childrenOf(p._def)) markSubtree(k, into);
|
|
3798
|
+
}
|
|
3799
|
+
var stripMembers = (f) => {
|
|
3800
|
+
const { _members, ...rest } = f;
|
|
3801
|
+
void _members;
|
|
3802
|
+
return rest;
|
|
3803
|
+
};
|
|
3804
|
+
function findExactDuplicates(visited, minSize) {
|
|
3805
|
+
const byShape = /* @__PURE__ */ new Map();
|
|
3806
|
+
for (const v2 of visited.values()) {
|
|
3807
|
+
if (v2.size < minSize) continue;
|
|
3808
|
+
const list = byShape.get(v2.shape);
|
|
3809
|
+
if (list === void 0) byShape.set(v2.shape, [v2]);
|
|
3810
|
+
else list.push(v2);
|
|
3811
|
+
}
|
|
3812
|
+
const out = [];
|
|
3813
|
+
for (const group of byShape.values()) {
|
|
3814
|
+
if (group.length < 2) continue;
|
|
3815
|
+
const size = group[0].size;
|
|
3816
|
+
out.push({
|
|
3817
|
+
kind: "exact-duplicate",
|
|
3818
|
+
id: `exact-duplicate:${siteToString(group[0].site)}`,
|
|
3819
|
+
size,
|
|
3820
|
+
count: group.length,
|
|
3821
|
+
savings: (group.length - 1) * size,
|
|
3822
|
+
shape: clamp(render(group[0].p)),
|
|
3823
|
+
sites: group.map((g) => g.site),
|
|
3824
|
+
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}.`,
|
|
3825
|
+
_members: group.map((g) => g.p)
|
|
3826
|
+
});
|
|
3827
|
+
}
|
|
3828
|
+
return out.sort((a, b) => b.savings - a.savings);
|
|
3829
|
+
}
|
|
3830
|
+
function findNearDuplicates(visited, interner, shapeOf, minSize) {
|
|
3831
|
+
const holeCache = /* @__PURE__ */ new Map();
|
|
3832
|
+
const holesOf = (p) => {
|
|
3833
|
+
const hit = holeCache.get(p);
|
|
3834
|
+
if (hit !== void 0) return hit;
|
|
3835
|
+
holeCache.set(p, []);
|
|
3836
|
+
const d = p._def;
|
|
3837
|
+
const kids = childrenOf(d);
|
|
3838
|
+
const kidShapes = kids.map(shapeOf);
|
|
3839
|
+
const payload = payloadKey(p, d);
|
|
3840
|
+
const out2 = [];
|
|
3841
|
+
kids.forEach((k, i) => {
|
|
3842
|
+
for (const inner of [interner.hole, ...holesOf(k)]) {
|
|
3843
|
+
const arr = kidShapes.slice();
|
|
3844
|
+
arr[i] = inner;
|
|
3845
|
+
out2.push(interner.of(`${payload}|${arr.join(",")}`));
|
|
3846
|
+
}
|
|
3847
|
+
});
|
|
3848
|
+
holeCache.set(p, out2);
|
|
3849
|
+
return out2;
|
|
3850
|
+
};
|
|
3851
|
+
const byHole = /* @__PURE__ */ new Map();
|
|
3852
|
+
for (const v2 of visited.values()) {
|
|
3853
|
+
if (v2.size < minSize) continue;
|
|
3854
|
+
for (const h of holesOf(v2.p)) {
|
|
3855
|
+
const list = byHole.get(h);
|
|
3856
|
+
if (list === void 0) byHole.set(h, [v2]);
|
|
3857
|
+
else list.push(v2);
|
|
3858
|
+
}
|
|
3859
|
+
}
|
|
3860
|
+
const out = [];
|
|
3861
|
+
const seenGroups = /* @__PURE__ */ new Set();
|
|
3862
|
+
for (const group of byHole.values()) {
|
|
3863
|
+
if (group.length < 2) continue;
|
|
3864
|
+
const shapes = new Set(group.map((g) => g.shape));
|
|
3865
|
+
if (shapes.size < 2) continue;
|
|
3866
|
+
const perShape = /* @__PURE__ */ new Map();
|
|
3867
|
+
for (const g of group) if (!perShape.has(g.shape)) perShape.set(g.shape, g);
|
|
3868
|
+
const members = [...perShape.values()];
|
|
3869
|
+
const key = members.map((m) => m.shape).sort((a, b) => a - b).join(",");
|
|
3870
|
+
if (seenGroups.has(key)) continue;
|
|
3871
|
+
seenGroups.add(key);
|
|
3872
|
+
const slot = findDivergentSlot(members.map((m) => m.p), shapeOf);
|
|
3873
|
+
if (slot === null) continue;
|
|
3874
|
+
const sharedSize = Math.min(...members.map((m) => m.size)) - slot.slotSize;
|
|
3875
|
+
if (sharedSize < minSize) continue;
|
|
3876
|
+
out.push({
|
|
3877
|
+
kind: "near-duplicate",
|
|
3878
|
+
id: `near-duplicate:${siteToString(members[0].site)}`,
|
|
3879
|
+
sharedSize,
|
|
3880
|
+
count: members.length,
|
|
3881
|
+
savings: (members.length - 1) * sharedSize,
|
|
3882
|
+
shape: clamp(renderWithHole(members[0].p, slot.path)),
|
|
3883
|
+
slotPath: slot.path.map((i, k) => segment(slot.defs[k], i)).join(" \u203A "),
|
|
3884
|
+
variants: slot.variants.map((v2) => clamp(render(v2))),
|
|
3885
|
+
sites: members.map((m) => m.site),
|
|
3886
|
+
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.`,
|
|
3887
|
+
_members: members.map((m) => m.p)
|
|
3888
|
+
});
|
|
3889
|
+
}
|
|
3890
|
+
return out.sort((a, b) => b.savings - a.savings);
|
|
3891
|
+
}
|
|
3892
|
+
function findDivergentSlot(members, shapeOf) {
|
|
3893
|
+
const path2 = [];
|
|
3894
|
+
const defs = [];
|
|
3895
|
+
let cur = [...members];
|
|
3896
|
+
for (let guard2 = 0; guard2 < 64; guard2++) {
|
|
3897
|
+
const d0 = cur[0]._def;
|
|
3898
|
+
const kidLists = cur.map((c) => childrenOf(c._def));
|
|
3899
|
+
const arity = kidLists[0].length;
|
|
3900
|
+
if (kidLists.some((k) => k.length !== arity) || arity === 0) break;
|
|
3901
|
+
const diff = [];
|
|
3902
|
+
for (let i2 = 0; i2 < arity; i2++) {
|
|
3903
|
+
const s = shapeOf(kidLists[0][i2]);
|
|
3904
|
+
if (kidLists.some((k) => shapeOf(k[i2]) !== s)) diff.push(i2);
|
|
3905
|
+
}
|
|
3906
|
+
if (diff.length !== 1) break;
|
|
3907
|
+
const i = diff[0];
|
|
3908
|
+
path2.push(i);
|
|
3909
|
+
defs.push(d0);
|
|
3910
|
+
cur = kidLists.map((k) => k[i]);
|
|
3911
|
+
const nextArity = childrenOf(cur[0]._def).length;
|
|
3912
|
+
const samePayload = cur.every((c) => payloadKey(c, c._def) === payloadKey(cur[0], cur[0]._def));
|
|
3913
|
+
if (!samePayload || nextArity === 0) break;
|
|
3914
|
+
}
|
|
3915
|
+
if (path2.length === 0) return null;
|
|
3916
|
+
let slotSize = 0;
|
|
3917
|
+
const sizeOf = (p) => {
|
|
3918
|
+
let n = 1;
|
|
3919
|
+
for (const k of childrenOf(p._def)) n += sizeOf(k);
|
|
3920
|
+
return n;
|
|
3921
|
+
};
|
|
3922
|
+
for (const c of cur) slotSize = Math.max(slotSize, sizeOf(c));
|
|
3923
|
+
return { path: path2, defs, variants: cur, slotSize };
|
|
3924
|
+
}
|
|
3925
|
+
function renderWithHole(p, path2, depth = 0) {
|
|
3926
|
+
if (depth === path2.length) return "\u2039slot\u203A";
|
|
3927
|
+
const d = p._def;
|
|
3928
|
+
const kids = childrenOf(d);
|
|
3929
|
+
const idx = path2[depth];
|
|
3930
|
+
const parts = kids.map((k, i) => i === idx ? renderWithHole(k, path2, depth + 1) : render(k, 2));
|
|
3931
|
+
switch (d.tag) {
|
|
3932
|
+
case "sequence":
|
|
3933
|
+
return `sequence(${parts.join(", ")})`;
|
|
3934
|
+
case "choice":
|
|
3935
|
+
return `choice(${parts.join(", ")})`;
|
|
3936
|
+
case "node":
|
|
3937
|
+
return `node(${d.type ? `'${d.type}', ` : ""}${parts[0] ?? ""})`;
|
|
3938
|
+
default:
|
|
3939
|
+
return `${d.tag}(${parts.join(", ")})`;
|
|
3940
|
+
}
|
|
3941
|
+
}
|
|
3942
|
+
var MAX_RUN = 32;
|
|
3943
|
+
function findRegexFragments(visited) {
|
|
3944
|
+
const byRun = /* @__PURE__ */ new Map();
|
|
3945
|
+
for (const v2 of visited.values()) {
|
|
3946
|
+
const d = v2.d;
|
|
3947
|
+
if (d.tag !== "regex") continue;
|
|
3948
|
+
const runs = /* @__PURE__ */ new Set();
|
|
3949
|
+
for (const branches of alternationGroups(d.source)) {
|
|
3950
|
+
if (branches.length >= 2) runs.add(branches.join("|"));
|
|
3951
|
+
for (let i = 0; i < branches.length; i++) {
|
|
3952
|
+
for (let n = 2; n <= Math.min(MAX_RUN, branches.length - i); n++) {
|
|
3953
|
+
const run2 = branches.slice(i, i + n).join("|");
|
|
3954
|
+
if (run2.length < 4) continue;
|
|
3955
|
+
runs.add(run2);
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3958
|
+
}
|
|
3959
|
+
for (const run2 of runs) {
|
|
3960
|
+
let e = byRun.get(run2);
|
|
3961
|
+
if (e === void 0) {
|
|
3962
|
+
e = { occ: [], nodes: /* @__PURE__ */ new Set(), branches: run2.split("|").length };
|
|
3963
|
+
byRun.set(run2, e);
|
|
3964
|
+
}
|
|
3965
|
+
if (e.nodes.has(v2.p)) continue;
|
|
3966
|
+
e.nodes.add(v2.p);
|
|
3967
|
+
e.occ.push({ site: v2.site, source: d.source });
|
|
3968
|
+
}
|
|
3969
|
+
}
|
|
3970
|
+
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);
|
|
3971
|
+
const kept = [];
|
|
3972
|
+
for (const c of candidates) {
|
|
3973
|
+
if (kept.some((k) => k.e.occ.length >= c.e.occ.length && `|${k.run}|`.includes(`|${c.run}|`))) continue;
|
|
3974
|
+
kept.push(c);
|
|
3975
|
+
}
|
|
3976
|
+
return kept.map(({ run: run2, e }) => ({
|
|
3977
|
+
kind: "regex-fragment",
|
|
3978
|
+
id: `regex-fragment:${run2}`,
|
|
3979
|
+
fragment: run2,
|
|
3980
|
+
branches: e.branches,
|
|
3981
|
+
count: e.occ.length,
|
|
3982
|
+
savings: (e.occ.length - 1) * run2.length,
|
|
3983
|
+
sources: e.occ.map((o) => `/${o.source}/`),
|
|
3984
|
+
sites: e.occ.map((o) => o.site),
|
|
3985
|
+
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.`
|
|
3986
|
+
}));
|
|
3987
|
+
}
|
|
3988
|
+
function extractCharClasses(src) {
|
|
3989
|
+
const out = [];
|
|
3990
|
+
let i = 0;
|
|
3991
|
+
while (i < src.length) {
|
|
3992
|
+
const c = src[i];
|
|
3993
|
+
if (c === "\\") {
|
|
3994
|
+
i += 2;
|
|
3995
|
+
continue;
|
|
3996
|
+
}
|
|
3997
|
+
if (c !== "[") {
|
|
3998
|
+
i++;
|
|
3999
|
+
continue;
|
|
4000
|
+
}
|
|
4001
|
+
let j = i + 1;
|
|
4002
|
+
if (src[j] === "^") j++;
|
|
4003
|
+
if (src[j] === "]") j++;
|
|
4004
|
+
while (j < src.length && src[j] !== "]") {
|
|
4005
|
+
if (src[j] === "\\") j++;
|
|
4006
|
+
j++;
|
|
4007
|
+
}
|
|
4008
|
+
out.push(src.slice(i + 1, j));
|
|
4009
|
+
i = j + 1;
|
|
4010
|
+
}
|
|
4011
|
+
return out;
|
|
4012
|
+
}
|
|
4013
|
+
function charClassMembers(body) {
|
|
4014
|
+
const esc = (ch2) => {
|
|
4015
|
+
const cp = ch2.codePointAt(0);
|
|
4016
|
+
return cp >= 128 ? `\\u${cp.toString(16).padStart(4, "0")}` : ch2;
|
|
4017
|
+
};
|
|
4018
|
+
const atoms = [];
|
|
4019
|
+
let i = 0;
|
|
4020
|
+
while (i < body.length) {
|
|
4021
|
+
if (body[i] === "\\") {
|
|
4022
|
+
const m = /^\\(?:u\{([0-9a-fA-F]+)\}|u([0-9a-fA-F]{4})|x([0-9a-fA-F]{2}))/.exec(body.slice(i));
|
|
4023
|
+
if (m !== null) {
|
|
4024
|
+
const cp = parseInt(m[1] ?? m[2] ?? m[3], 16);
|
|
4025
|
+
atoms.push(cp >= 128 ? `\\u${cp.toString(16).padStart(4, "0")}` : String.fromCodePoint(cp));
|
|
4026
|
+
i += m[0].length;
|
|
4027
|
+
continue;
|
|
4028
|
+
}
|
|
4029
|
+
atoms.push(body.slice(i, i + 2));
|
|
4030
|
+
i += 2;
|
|
4031
|
+
continue;
|
|
4032
|
+
}
|
|
4033
|
+
atoms.push(esc(body[i]));
|
|
4034
|
+
i++;
|
|
4035
|
+
}
|
|
4036
|
+
const members = [];
|
|
4037
|
+
for (let k = 0; k < atoms.length; k++) {
|
|
4038
|
+
if (k + 2 < atoms.length && atoms[k + 1] === "-" && atoms[k + 2] !== void 0) {
|
|
4039
|
+
members.push(`${atoms[k]}-${atoms[k + 2]}`);
|
|
4040
|
+
k += 2;
|
|
4041
|
+
continue;
|
|
4042
|
+
}
|
|
4043
|
+
members.push(atoms[k]);
|
|
4044
|
+
}
|
|
4045
|
+
return members;
|
|
4046
|
+
}
|
|
4047
|
+
var CLASS_MIN_MEMBERS = 2;
|
|
4048
|
+
function findRegexClasses(visited) {
|
|
4049
|
+
const spellings = /* @__PURE__ */ new Map();
|
|
4050
|
+
for (const v2 of visited.values()) {
|
|
4051
|
+
if (v2.d.tag !== "regex") continue;
|
|
4052
|
+
for (const body of new Set(extractCharClasses(v2.d.source))) {
|
|
4053
|
+
const members = charClassMembers(body);
|
|
4054
|
+
if (members.length < CLASS_MIN_MEMBERS) continue;
|
|
4055
|
+
const key = [...new Set(members)].sort().join("");
|
|
4056
|
+
let s = spellings.get(key);
|
|
4057
|
+
if (s === void 0) {
|
|
4058
|
+
s = { source: body, members, key, nodes: /* @__PURE__ */ new Set(), sites: [] };
|
|
4059
|
+
spellings.set(key, s);
|
|
4060
|
+
}
|
|
4061
|
+
if (s.nodes.has(v2.p)) continue;
|
|
4062
|
+
s.nodes.add(v2.p);
|
|
4063
|
+
s.sites.push(v2.site);
|
|
4064
|
+
}
|
|
4065
|
+
}
|
|
4066
|
+
const MAX_DELTA = 3;
|
|
4067
|
+
const MIN_JACCARD = 0.6;
|
|
4068
|
+
const all = [...spellings.values()];
|
|
4069
|
+
const parent = all.map((_, i) => i);
|
|
4070
|
+
const find = (i) => {
|
|
4071
|
+
while (parent[i] !== i) {
|
|
4072
|
+
parent[i] = parent[parent[i]];
|
|
4073
|
+
i = parent[i];
|
|
4074
|
+
}
|
|
4075
|
+
return i;
|
|
4076
|
+
};
|
|
4077
|
+
const union2 = (a, b) => {
|
|
4078
|
+
const ra = find(a), rb = find(b);
|
|
4079
|
+
if (ra !== rb) parent[ra] = rb;
|
|
4080
|
+
};
|
|
4081
|
+
for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) {
|
|
4082
|
+
if (all[i].members.includes("^") !== all[j].members.includes("^")) continue;
|
|
4083
|
+
const A = new Set(all[i].members), B = new Set(all[j].members);
|
|
4084
|
+
let shared = 0;
|
|
4085
|
+
for (const m of A) if (B.has(m)) shared++;
|
|
4086
|
+
const delta = A.size - shared + (B.size - shared);
|
|
4087
|
+
const jaccard = shared / (shared + delta);
|
|
4088
|
+
if (shared >= 2 && delta > 0 && delta <= MAX_DELTA && jaccard >= MIN_JACCARD) union2(i, j);
|
|
4089
|
+
}
|
|
4090
|
+
const clusters = /* @__PURE__ */ new Map();
|
|
4091
|
+
all.forEach((_, i) => {
|
|
4092
|
+
const r = find(i);
|
|
4093
|
+
const list = clusters.get(r);
|
|
4094
|
+
if (list === void 0) clusters.set(r, [i]);
|
|
4095
|
+
else list.push(i);
|
|
4096
|
+
});
|
|
4097
|
+
const out = [];
|
|
4098
|
+
for (const idxs of clusters.values()) {
|
|
4099
|
+
const members = idxs.map((i) => all[i]).sort((a, b) => b.nodes.size - a.nodes.size);
|
|
4100
|
+
const total = members.reduce((n, m) => n + m.nodes.size, 0);
|
|
4101
|
+
const drifted = members.length > 1;
|
|
4102
|
+
if (!drifted && total < 2) continue;
|
|
4103
|
+
const base = new Set(members[0].members);
|
|
4104
|
+
const variants = members.map((m) => {
|
|
4105
|
+
const mine = new Set(m.members);
|
|
4106
|
+
const plus = [...mine].filter((x) => !base.has(x));
|
|
4107
|
+
const minus = [...base].filter((x) => !mine.has(x));
|
|
4108
|
+
return {
|
|
4109
|
+
source: m.source,
|
|
4110
|
+
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)",
|
|
4111
|
+
count: m.nodes.size,
|
|
4112
|
+
sites: m.sites
|
|
4113
|
+
};
|
|
4114
|
+
});
|
|
4115
|
+
const bmpCeiling = members.some((m) => m.members.some((x) => x.endsWith("-\\uffff")));
|
|
4116
|
+
out.push({
|
|
4117
|
+
kind: "regex-class",
|
|
4118
|
+
id: `regex-class:${members[0].key}`,
|
|
4119
|
+
canonical: members[0].source,
|
|
4120
|
+
variants,
|
|
4121
|
+
count: total,
|
|
4122
|
+
drifted,
|
|
4123
|
+
bmpCeiling,
|
|
4124
|
+
suggestion: [
|
|
4125
|
+
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.`,
|
|
4126
|
+
`Prefer the shared recognition surface where one already covers this class rather than a local extraction.`,
|
|
4127
|
+
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.` : "",
|
|
4128
|
+
`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.`
|
|
4129
|
+
].filter((s) => s !== "").join(" ")
|
|
4130
|
+
});
|
|
4131
|
+
}
|
|
4132
|
+
return out.sort((a, b) => Number(b.drifted) - Number(a.drifted) || b.count - a.count);
|
|
4133
|
+
}
|
|
4134
|
+
function intersects3(a, b) {
|
|
4135
|
+
if (a.kind === "any" || b.kind === "any") return true;
|
|
4136
|
+
if (a.kind === "empty" || b.kind === "empty") return false;
|
|
4137
|
+
for (const ra of a.ranges) for (const rb of b.ranges) if (ra.lo <= rb.hi && rb.lo <= ra.hi) return true;
|
|
4138
|
+
return false;
|
|
4139
|
+
}
|
|
4140
|
+
function intersection2(a, b) {
|
|
4141
|
+
if (a.kind === "any") return b;
|
|
4142
|
+
if (b.kind === "any") return a;
|
|
4143
|
+
if (a.kind === "empty" || b.kind === "empty") return { kind: "empty" };
|
|
4144
|
+
const ranges = [];
|
|
4145
|
+
for (const ra of a.ranges) for (const rb of b.ranges) {
|
|
4146
|
+
const lo = Math.max(ra.lo, rb.lo);
|
|
4147
|
+
const hi = Math.min(ra.hi, rb.hi);
|
|
4148
|
+
if (lo <= hi) ranges.push({ lo, hi });
|
|
4149
|
+
}
|
|
4150
|
+
return ranges.length === 0 ? { kind: "empty" } : { kind: "ranges", ranges };
|
|
4151
|
+
}
|
|
4152
|
+
function termsOf(arm) {
|
|
4153
|
+
let cur = arm;
|
|
4154
|
+
for (; ; ) {
|
|
4155
|
+
const d2 = cur._def;
|
|
4156
|
+
if (d2.tag === "node" || d2.tag === "transform" || d2.tag === "label" || d2.tag === "attempt" || d2.tag === "leaf") {
|
|
4157
|
+
cur = d2.parser;
|
|
4158
|
+
continue;
|
|
4159
|
+
}
|
|
4160
|
+
break;
|
|
4161
|
+
}
|
|
4162
|
+
const d = cur._def;
|
|
4163
|
+
return d.tag === "sequence" ? d.parsers : [cur];
|
|
4164
|
+
}
|
|
4165
|
+
function leadingRegex(arm) {
|
|
4166
|
+
const t = termsOf(arm)[0];
|
|
4167
|
+
return t !== void 0 && t._def.tag === "regex";
|
|
4168
|
+
}
|
|
4169
|
+
function findOverlaps(visited, shapeOf, resolve2) {
|
|
4170
|
+
const out = [];
|
|
4171
|
+
for (const v2 of visited.values()) {
|
|
4172
|
+
const d = v2.d;
|
|
4173
|
+
if (d.tag !== "choice") continue;
|
|
4174
|
+
const arms = d.parsers;
|
|
4175
|
+
const fs2 = arms.map((a) => firstSetOf(a, /* @__PURE__ */ new Set(), resolve2));
|
|
4176
|
+
const strategy = d.strategy;
|
|
4177
|
+
for (let i = 0; i < arms.length; i++) {
|
|
4178
|
+
for (let j = i + 1; j < arms.length; j++) {
|
|
4179
|
+
const A = fs2[i], B = fs2[j];
|
|
4180
|
+
if (A.kind === "any" || B.kind === "any") continue;
|
|
4181
|
+
if (!intersects3(A, B)) continue;
|
|
4182
|
+
const ta = termsOf(arms[i]), tb = termsOf(arms[j]);
|
|
4183
|
+
let shared = 0;
|
|
4184
|
+
while (shared < ta.length && shared < tb.length && shapeOf(ta[shared]) === shapeOf(tb[shared])) shared++;
|
|
4185
|
+
const handled = strategy?.tag === "sharedPrefix" && Array.isArray(strategy.members) && strategy.members.includes(i) && strategy.members.includes(j);
|
|
4186
|
+
const regexPair = leadingRegex(arms[i]) && leadingRegex(arms[j]);
|
|
4187
|
+
out.push({
|
|
4188
|
+
kind: "arm-overlap",
|
|
4189
|
+
id: `arm-overlap:${siteToString(v2.site)}:${i}-${j}`,
|
|
4190
|
+
site: v2.site,
|
|
4191
|
+
a: i,
|
|
4192
|
+
b: j,
|
|
4193
|
+
on: intersection2(A, B),
|
|
4194
|
+
sharedLeadingTerms: shared,
|
|
4195
|
+
sharedPrefix: shared > 0 ? clamp(ta.slice(0, shared).map((t) => render(t, 2)).join(", ")) : null,
|
|
4196
|
+
handledByStrategy: handled,
|
|
4197
|
+
regexPair,
|
|
4198
|
+
suggestion: overlapSuggestion(shared, handled, regexPair)
|
|
4199
|
+
});
|
|
4200
|
+
}
|
|
4201
|
+
}
|
|
4202
|
+
}
|
|
4203
|
+
return out.sort((a, b) => b.sharedLeadingTerms - a.sharedLeadingTerms);
|
|
4204
|
+
}
|
|
4205
|
+
function overlapSuggestion(shared, handled, regexPair) {
|
|
4206
|
+
if (shared > 0 && handled)
|
|
4207
|
+
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.`;
|
|
4208
|
+
if (shared > 0)
|
|
4209
|
+
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.`;
|
|
4210
|
+
if (regexPair)
|
|
4211
|
+
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.`;
|
|
4212
|
+
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.`;
|
|
4213
|
+
}
|
|
4214
|
+
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.";
|
|
4215
|
+
var PERF_NONE = "";
|
|
4216
|
+
function findRewrites(visited, shapeOf) {
|
|
4217
|
+
const out = [];
|
|
4218
|
+
const push = (f, at) => {
|
|
4219
|
+
const site = siteToString(f.site);
|
|
4220
|
+
out.push({ kind: "rewrite", id: `rewrite:${f.rewrite}:${site}${at === void 0 ? "" : `:${at}`}`, ...f });
|
|
4221
|
+
};
|
|
4222
|
+
for (const v2 of visited.values()) {
|
|
4223
|
+
const d = v2.d;
|
|
4224
|
+
const site = v2.site;
|
|
4225
|
+
if (d.tag === "optional" || d.tag === "many" || d.tag === "oneOrMore") {
|
|
4226
|
+
const inner = d.parser;
|
|
4227
|
+
const id = inner._def;
|
|
4228
|
+
const collapsed = collapseRepeat(d, id);
|
|
4229
|
+
if (collapsed !== null) {
|
|
4230
|
+
push({
|
|
4231
|
+
rewrite: "idempotent-nesting",
|
|
4232
|
+
site,
|
|
4233
|
+
from: clamp(render(v2.p, 2)),
|
|
4234
|
+
to: collapsed,
|
|
4235
|
+
astNeutral: false,
|
|
4236
|
+
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.",
|
|
4237
|
+
bug: id.tag === "optional" && d.tag === "many",
|
|
4238
|
+
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.`
|
|
4239
|
+
});
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
if ((d.tag === "choice" || d.tag === "sequence") && d.parsers.length === 1) {
|
|
4243
|
+
push({
|
|
4244
|
+
rewrite: "single-element",
|
|
4245
|
+
site,
|
|
4246
|
+
from: clamp(render(v2.p, 2)),
|
|
4247
|
+
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)`,
|
|
4248
|
+
astNeutral: d.tag === "choice",
|
|
4249
|
+
perf: d.tag === "choice" ? "a one-arm choice still emits its dispatch scaffolding." : PERF_NONE,
|
|
4250
|
+
bug: false,
|
|
4251
|
+
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."
|
|
4252
|
+
});
|
|
4253
|
+
}
|
|
4254
|
+
if (d.tag !== "choice") continue;
|
|
4255
|
+
const arms = d.parsers;
|
|
4256
|
+
const armShapes = arms.map(shapeOf);
|
|
4257
|
+
const strategy = d.strategy;
|
|
4258
|
+
for (let i = 0; i < arms.length; i++) for (let j = i + 1; j < arms.length; j++) {
|
|
4259
|
+
if (armShapes[i] !== armShapes[j]) continue;
|
|
4260
|
+
push({
|
|
4261
|
+
rewrite: "duplicate-arm",
|
|
4262
|
+
site,
|
|
4263
|
+
from: `choice(\u2026 arm[${i}] \u2026, arm[${j}] \u2026)`,
|
|
4264
|
+
to: `delete arm[${j}]`,
|
|
4265
|
+
astNeutral: true,
|
|
4266
|
+
perf: PERF_ARM,
|
|
4267
|
+
bug: true,
|
|
4268
|
+
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.`
|
|
4269
|
+
}, `${i}-${j}`);
|
|
4270
|
+
}
|
|
4271
|
+
for (let i = 0; i < arms.length; i++) for (let j = 0; j < arms.length; j++) {
|
|
4272
|
+
if (i >= j) continue;
|
|
4273
|
+
if (armShapes[i] === armShapes[j]) continue;
|
|
4274
|
+
const ta = termsOf(arms[i]), tb = termsOf(arms[j]);
|
|
4275
|
+
if (ta.length === 0 || ta.length >= tb.length) continue;
|
|
4276
|
+
let k = 0;
|
|
4277
|
+
while (k < ta.length && shapeOf(ta[k]) === shapeOf(tb[k])) k++;
|
|
4278
|
+
if (k !== ta.length) continue;
|
|
4279
|
+
push({
|
|
4280
|
+
rewrite: "shadowed-arm",
|
|
4281
|
+
site,
|
|
4282
|
+
from: `choice(\u2026 arm[${i}]=${clamp(render(arms[i], 2))}, \u2026 arm[${j}]=${clamp(render(arms[j], 2))} \u2026)`,
|
|
4283
|
+
to: `arm[${j}] is unreachable`,
|
|
4284
|
+
astNeutral: true,
|
|
4285
|
+
perf: PERF_ARM,
|
|
4286
|
+
bug: true,
|
|
4287
|
+
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.`
|
|
4288
|
+
}, `${i}-${j}`);
|
|
4289
|
+
}
|
|
4290
|
+
for (let i = 0; i + 1 < arms.length; i++) {
|
|
4291
|
+
const j = i + 1;
|
|
4292
|
+
const longer = termsOf(arms[i]), shorter = termsOf(arms[j]);
|
|
4293
|
+
const ordered = detectOptionalTerm(longer, shorter, shapeOf);
|
|
4294
|
+
const reversed = ordered === null ? detectOptionalTerm(shorter, longer, shapeOf) : null;
|
|
4295
|
+
const hit = ordered ?? reversed;
|
|
4296
|
+
if (hit === null) continue;
|
|
4297
|
+
const nodeWrapped = v2.enclosingNode ?? wrappingNodeType(arms[i]) ?? wrappingNodeType(arms[j]);
|
|
4298
|
+
const rest = hit.rest.map((t) => render(t, 2)).join(", ");
|
|
4299
|
+
const to = hit.where === "prefix" ? `sequence(optional(${render(hit.term, 2)}), ${rest})` : `sequence(${rest}, optional(${render(hit.term, 2)}))`;
|
|
4300
|
+
push({
|
|
4301
|
+
rewrite: hit.where === "prefix" ? "optional-prefix" : "optional-suffix",
|
|
4302
|
+
site,
|
|
4303
|
+
from: clamp(render(v2.p, 2)),
|
|
4304
|
+
to: clamp(to),
|
|
4305
|
+
astNeutral: false,
|
|
4306
|
+
perf: PERF_ARM,
|
|
4307
|
+
bug: false,
|
|
4308
|
+
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.`
|
|
4309
|
+
}, `${i}-${j}`);
|
|
4310
|
+
}
|
|
4311
|
+
for (let i = 0; i + 1 < arms.length; i++) {
|
|
4312
|
+
const j = i + 1;
|
|
4313
|
+
const ta = termsOf(arms[i]), tb = termsOf(arms[j]);
|
|
4314
|
+
if (ta.length < 2 || tb.length < 2) continue;
|
|
4315
|
+
let k = 0;
|
|
4316
|
+
while (k < ta.length - 1 && k < tb.length - 1 && shapeOf(ta[k]) === shapeOf(tb[k])) k++;
|
|
4317
|
+
if (k === 0) continue;
|
|
4318
|
+
const handled = strategy?.tag === "sharedPrefix" && Array.isArray(strategy.members) && strategy.members.includes(i) && strategy.members.includes(j);
|
|
4319
|
+
push({
|
|
4320
|
+
rewrite: "left-factor",
|
|
4321
|
+
site,
|
|
4322
|
+
from: `choice(sequence(${ta.map((t) => render(t, 1)).join(", ")}), sequence(${tb.map((t) => render(t, 1)).join(", ")}))`,
|
|
4323
|
+
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(", ")})))`),
|
|
4324
|
+
astNeutral: false,
|
|
4325
|
+
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,
|
|
4326
|
+
bug: false,
|
|
4327
|
+
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.`
|
|
4328
|
+
}, `${i}-${j}`);
|
|
4329
|
+
}
|
|
4330
|
+
}
|
|
4331
|
+
for (const v2 of visited.values()) {
|
|
4332
|
+
if (v2.d.tag !== "sequence") continue;
|
|
4333
|
+
const hit = detectHandRolledSepBy(v2.d.parsers, shapeOf);
|
|
4334
|
+
if (hit === null) continue;
|
|
4335
|
+
const captured = v2.d.parsers.some((t) => capturesPositionally(t));
|
|
4336
|
+
const verdict = captured ? "blocked-by-capture" : v2.enclosingReducer ? "reducer-stride-review" : "convertible";
|
|
4337
|
+
const to = `sepBy(${clamp(render(hit.item, 2))}, ${clamp(render(hit.sep, 2))}${hit.trailing ? `, { trailing: 'allow' }` : ""}, { min: ${hit.min} })`;
|
|
4338
|
+
out.push({
|
|
4339
|
+
kind: "rewrite",
|
|
4340
|
+
id: `rewrite:hand-rolled-sepby:${siteToString(v2.site)}`,
|
|
4341
|
+
rewrite: "hand-rolled-sepby",
|
|
4342
|
+
site: v2.site,
|
|
4343
|
+
sepByVerdict: verdict,
|
|
4344
|
+
from: clamp(render(v2.p, 3)),
|
|
4345
|
+
to: verdict === "convertible" ? to : `${to} \u2014 NOT APPLICABLE HERE (${verdict})`,
|
|
4346
|
+
astNeutral: false,
|
|
4347
|
+
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,
|
|
4348
|
+
bug: false,
|
|
4349
|
+
suggestion: `${SEPBY_SPELLED_OUT(hit.trailing)} ${SEPBY_VERDICT_TEXT[verdict](hit.trailing)}`
|
|
4350
|
+
});
|
|
4351
|
+
}
|
|
4352
|
+
return out;
|
|
4353
|
+
}
|
|
4354
|
+
function collapseRepeat(outer, inner) {
|
|
4355
|
+
const o = outer.tag, i = inner.tag;
|
|
4356
|
+
if (o === "optional" && i === "optional") return "optional(X)";
|
|
4357
|
+
if (o === "optional" && i === "many") return "many(X)";
|
|
4358
|
+
if (o === "many" && i === "many") return "many(X)";
|
|
4359
|
+
if (o === "many" && i === "optional") return "many(X)";
|
|
4360
|
+
if (o === "optional" && i === "oneOrMore" && inner.min === 1 && inner.max === void 0) return "many(X)";
|
|
4361
|
+
if (o === "many" && i === "oneOrMore" && inner.min === 1 && inner.max === void 0) return "many(X)";
|
|
4362
|
+
return null;
|
|
4363
|
+
}
|
|
4364
|
+
function wrappingNodeType(arm) {
|
|
4365
|
+
const d = arm._def;
|
|
4366
|
+
return d.tag === "node" ? d.type ?? "(anonymous)" : null;
|
|
4367
|
+
}
|
|
4368
|
+
function detectOptionalTerm(longer, shorter, shapeOf) {
|
|
4369
|
+
if (longer.length !== shorter.length + 1 || shorter.length === 0) return null;
|
|
4370
|
+
const same = (a, b) => a.length === b.length && a.every((x, i) => shapeOf(x) === shapeOf(b[i]));
|
|
4371
|
+
if (same(longer.slice(1), shorter)) return { where: "prefix", term: longer[0], rest: shorter };
|
|
4372
|
+
if (same(longer.slice(0, -1), shorter)) return { where: "suffix", term: longer[longer.length - 1], rest: shorter };
|
|
4373
|
+
return null;
|
|
4374
|
+
}
|
|
4375
|
+
var SEPBY_SPELLED_OUT = (trailing) => `this is \`sepBy(item, sep${trailing ? ", { trailing: 'allow' }" : ""})\` spelled out.`;
|
|
4376
|
+
var SEPBY_VERDICT_TEXT = {
|
|
4377
|
+
"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.",
|
|
4378
|
+
"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.",
|
|
4379
|
+
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]]\`.`
|
|
4380
|
+
};
|
|
4381
|
+
function capturesPositionally(p, seen = /* @__PURE__ */ new Set()) {
|
|
4382
|
+
if (seen.has(p)) return false;
|
|
4383
|
+
seen.add(p);
|
|
4384
|
+
const d = p._def;
|
|
4385
|
+
if (d.tag === "field" || d.tag === "label") return true;
|
|
4386
|
+
for (const k of childrenOf(d)) if (capturesPositionally(k, seen)) return true;
|
|
4387
|
+
return false;
|
|
4388
|
+
}
|
|
4389
|
+
function detectHandRolledSepBy(terms, shapeOf) {
|
|
4390
|
+
if (terms.length < 2 || terms.length > 3) return null;
|
|
4391
|
+
const item = terms[0];
|
|
4392
|
+
const rep = terms[1]._def;
|
|
4393
|
+
if (rep.tag !== "many" && rep.tag !== "oneOrMore") return null;
|
|
4394
|
+
if (rep.max !== void 0) return null;
|
|
4395
|
+
const innerDef = rep.parser._def;
|
|
4396
|
+
if (innerDef.tag !== "sequence" || innerDef.parsers.length !== 2) return null;
|
|
4397
|
+
const [sep2, repeated] = innerDef.parsers;
|
|
4398
|
+
if (shapeOf(repeated) !== shapeOf(item)) return null;
|
|
4399
|
+
let trailing = false;
|
|
4400
|
+
if (terms.length === 3) {
|
|
4401
|
+
const t = terms[2]._def;
|
|
4402
|
+
if (t.tag !== "optional" || shapeOf(t.parser) !== shapeOf(sep2)) return null;
|
|
4403
|
+
trailing = true;
|
|
4404
|
+
}
|
|
4405
|
+
return { item, sep: sep2, trailing, min: 1 + rep.min };
|
|
4406
|
+
}
|
|
4407
|
+
function bodyTermsOf(p) {
|
|
4408
|
+
let cur = p;
|
|
4409
|
+
for (; ; ) {
|
|
4410
|
+
const d2 = cur._def;
|
|
4411
|
+
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") {
|
|
4412
|
+
cur = d2.parser;
|
|
4413
|
+
continue;
|
|
4414
|
+
}
|
|
4415
|
+
break;
|
|
4416
|
+
}
|
|
4417
|
+
const d = cur._def;
|
|
4418
|
+
return d.tag === "sequence" ? d.parsers : [cur];
|
|
4419
|
+
}
|
|
4420
|
+
var MIN_SHARED_TERMS = 2;
|
|
4421
|
+
function findDivergentNodes(visited, shapeOf) {
|
|
4422
|
+
const byType = /* @__PURE__ */ new Map();
|
|
4423
|
+
for (const v2 of visited.values()) {
|
|
4424
|
+
if (v2.d.tag !== "node" || v2.d.type === void 0) continue;
|
|
4425
|
+
let m = byType.get(v2.d.type);
|
|
4426
|
+
if (m === void 0) {
|
|
4427
|
+
m = /* @__PURE__ */ new Map();
|
|
4428
|
+
byType.set(v2.d.type, m);
|
|
4429
|
+
}
|
|
4430
|
+
if (!m.has(v2.shape)) m.set(v2.shape, v2);
|
|
4431
|
+
}
|
|
4432
|
+
const out = [];
|
|
4433
|
+
for (const [type, m] of byType) {
|
|
4434
|
+
if (m.size < 2) continue;
|
|
4435
|
+
const members = [...m.values()];
|
|
4436
|
+
const termSets = members.map((v2) => bodyTermsOf(v2.p).map((t) => ({ id: shapeOf(t), text: clamp(render(t, 2)) })));
|
|
4437
|
+
const shared = termSets[0].filter((t) => termSets.every((set) => set.some((x) => x.id === t.id)));
|
|
4438
|
+
const uniqueShared = [...new Map(shared.map((t) => [t.id, t])).values()];
|
|
4439
|
+
if (uniqueShared.length < MIN_SHARED_TERMS) continue;
|
|
4440
|
+
const sharedIds = new Set(uniqueShared.map((t) => t.id));
|
|
4441
|
+
out.push({
|
|
4442
|
+
kind: "divergent-node",
|
|
4443
|
+
id: `divergent-node:${type}`,
|
|
4444
|
+
nodeType: type,
|
|
4445
|
+
count: members.length,
|
|
4446
|
+
sharedTerms: uniqueShared.map((t) => t.text),
|
|
4447
|
+
productions: members.map((v2, i) => ({
|
|
4448
|
+
shape: clamp(render(v2.p, 3)),
|
|
4449
|
+
site: v2.site,
|
|
4450
|
+
distinctTerms: termSets[i].filter((t) => !sharedIds.has(t.id)).map((t) => t.text)
|
|
4451
|
+
})),
|
|
4452
|
+
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.`
|
|
4453
|
+
});
|
|
4454
|
+
}
|
|
4455
|
+
return out.sort((a, b) => b.sharedTerms.length * b.count - a.sharedTerms.length * a.count);
|
|
4456
|
+
}
|
|
4457
|
+
function resolveArm(p) {
|
|
4458
|
+
let cur = p;
|
|
4459
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4460
|
+
for (; ; ) {
|
|
4461
|
+
if (seen.has(cur)) return cur;
|
|
4462
|
+
seen.add(cur);
|
|
4463
|
+
const d = cur._def;
|
|
4464
|
+
if (d.tag === "label" || d.tag === "attempt") {
|
|
4465
|
+
cur = d.parser;
|
|
4466
|
+
continue;
|
|
4467
|
+
}
|
|
4468
|
+
if (d.tag === "lazy") {
|
|
4469
|
+
try {
|
|
4470
|
+
cur = d.thunk();
|
|
4471
|
+
continue;
|
|
4472
|
+
} catch {
|
|
4473
|
+
return cur;
|
|
4474
|
+
}
|
|
4475
|
+
}
|
|
4476
|
+
return cur;
|
|
4477
|
+
}
|
|
4478
|
+
}
|
|
4479
|
+
function nestedNodeTypes(root, out, seen, isRoot) {
|
|
4480
|
+
if (seen.has(root)) return;
|
|
4481
|
+
seen.add(root);
|
|
4482
|
+
const d = root._def;
|
|
4483
|
+
if (d.tag === "leaf" || d.tag === "token") return;
|
|
4484
|
+
if (d.tag === "node" && !isRoot) out.add(d.type ?? "(anonymous)");
|
|
4485
|
+
if (d.tag === "lazy") {
|
|
4486
|
+
try {
|
|
4487
|
+
nestedNodeTypes(d.thunk(), out, seen, false);
|
|
4488
|
+
} catch {
|
|
4489
|
+
}
|
|
4490
|
+
return;
|
|
4491
|
+
}
|
|
4492
|
+
for (const k of childrenOf(d)) nestedNodeTypes(k, out, seen, false);
|
|
4493
|
+
}
|
|
4494
|
+
var MAX_LOST_TYPES = 8;
|
|
4495
|
+
function findStructureLoss(visited, resolve2) {
|
|
4496
|
+
const nestedCache = /* @__PURE__ */ new Map();
|
|
4497
|
+
const nested = (p) => {
|
|
4498
|
+
const hit = nestedCache.get(p);
|
|
4499
|
+
if (hit !== void 0) return hit;
|
|
4500
|
+
const out = /* @__PURE__ */ new Set();
|
|
4501
|
+
nestedNodeTypes(p, out, /* @__PURE__ */ new Set(), true);
|
|
4502
|
+
nestedCache.set(p, out);
|
|
4503
|
+
return out;
|
|
4504
|
+
};
|
|
4505
|
+
const findings = [];
|
|
4506
|
+
for (const v2 of visited.values()) {
|
|
4507
|
+
const d = v2.d;
|
|
4508
|
+
if (d.tag !== "choice") continue;
|
|
4509
|
+
const arms = d.parsers;
|
|
4510
|
+
const resolved = arms.map(resolveArm);
|
|
4511
|
+
const nodeTypes = resolved.map(wrappingNodeType);
|
|
4512
|
+
const fs2 = arms.map((a) => firstSetOf(a, /* @__PURE__ */ new Set(), resolve2));
|
|
4513
|
+
for (let i = 0; i < arms.length; i++) {
|
|
4514
|
+
if (d.gates[i] != null) continue;
|
|
4515
|
+
const type = nodeTypes[i] ?? null;
|
|
4516
|
+
if (type === null) continue;
|
|
4517
|
+
if (nested(resolved[i]).size !== 0) continue;
|
|
4518
|
+
const A = fs2[i];
|
|
4519
|
+
if (A.kind === "any") continue;
|
|
4520
|
+
for (let j = i + 1; j < arms.length; j++) {
|
|
4521
|
+
if (nodeTypes[j] !== type) continue;
|
|
4522
|
+
const B = fs2[j];
|
|
4523
|
+
if (B.kind === "any" || !intersects3(A, B)) continue;
|
|
4524
|
+
const lost = nested(resolved[j]);
|
|
4525
|
+
if (lost.size === 0) continue;
|
|
4526
|
+
const lostNodeTypes = [...lost].sort();
|
|
4527
|
+
findings.push({
|
|
4528
|
+
kind: "structure-loss",
|
|
4529
|
+
id: `structure-loss:${siteToString(v2.site)}:${i}-${j}`,
|
|
4530
|
+
site: v2.site,
|
|
4531
|
+
nodeType: type,
|
|
4532
|
+
earlier: i,
|
|
4533
|
+
later: j,
|
|
4534
|
+
on: intersection2(A, B),
|
|
4535
|
+
lostNodeTypes: lostNodeTypes.slice(0, MAX_LOST_TYPES),
|
|
4536
|
+
earlierShape: clamp(render(resolved[i], 3)),
|
|
4537
|
+
laterShape: clamp(render(resolved[j], 3)),
|
|
4538
|
+
suggestion: structureLossSuggestion(type, i, j, lostNodeTypes)
|
|
4539
|
+
});
|
|
4540
|
+
}
|
|
4541
|
+
}
|
|
4542
|
+
}
|
|
4543
|
+
return findings.sort((a, b) => b.lostNodeTypes.length - a.lostNodeTypes.length);
|
|
4544
|
+
}
|
|
4545
|
+
function structureLossSuggestion(type, i, j, lost) {
|
|
4546
|
+
const names = lost.slice(0, MAX_LOST_TYPES).map((t) => `\`${t}\``).join(", ");
|
|
4547
|
+
const more = lost.length > MAX_LOST_TYPES ? ` (and ${lost.length - MAX_LOST_TYPES} more)` : "";
|
|
4548
|
+
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.`;
|
|
4549
|
+
}
|
|
4550
|
+
function findKeywordRegexes(visited) {
|
|
4551
|
+
const armIndexOf = /* @__PURE__ */ new Map();
|
|
4552
|
+
for (const v2 of visited.values()) {
|
|
4553
|
+
if (v2.d.tag !== "choice") continue;
|
|
4554
|
+
v2.d.parsers.forEach((a, i) => {
|
|
4555
|
+
let cur = a;
|
|
4556
|
+
for (; ; ) {
|
|
4557
|
+
const cd = cur._def;
|
|
4558
|
+
if (cd.tag === "node" || cd.tag === "label" || cd.tag === "transform" || cd.tag === "leaf" || cd.tag === "attempt") {
|
|
4559
|
+
cur = cd.parser;
|
|
4560
|
+
continue;
|
|
4561
|
+
}
|
|
4562
|
+
break;
|
|
4563
|
+
}
|
|
4564
|
+
armIndexOf.set(cur, { owner: v2.p, index: i });
|
|
4565
|
+
});
|
|
4566
|
+
}
|
|
4567
|
+
const keywordArms = /* @__PURE__ */ new Map();
|
|
4568
|
+
for (const [arm, { owner }] of armIndexOf) {
|
|
4569
|
+
const d = arm._def;
|
|
4570
|
+
if (d.tag !== "regex" || keywordRegexShape(d.source) === null) continue;
|
|
4571
|
+
const list = keywordArms.get(owner) ?? [];
|
|
4572
|
+
list.push(armIndexOf.get(arm).index);
|
|
4573
|
+
keywordArms.set(owner, list);
|
|
4574
|
+
}
|
|
4575
|
+
const out = [];
|
|
4576
|
+
for (const v2 of visited.values()) {
|
|
4577
|
+
const d = v2.d;
|
|
4578
|
+
if (d.tag !== "regex") continue;
|
|
4579
|
+
const shape = keywordRegexShape(d.source);
|
|
4580
|
+
if (shape === null) continue;
|
|
4581
|
+
const ci = d.flags.includes("i");
|
|
4582
|
+
const unicode = d.flags.includes("u") || d.flags.includes("v");
|
|
4583
|
+
const own = armIndexOf.get(v2.p);
|
|
4584
|
+
const siblings = own === void 0 ? [] : (keywordArms.get(own.owner) ?? []).filter((i) => i !== own.index);
|
|
4585
|
+
const bq = (s) => `'${s.replace(/\\/g, "\\\\")}'`;
|
|
4586
|
+
const vocabulary = shape.words.length >= VOCABULARY_MIN_WORDS;
|
|
4587
|
+
const hazards = keywordAlternationHazards(shape.words, shape.boundary);
|
|
4588
|
+
const unrescued = hazards.filter((h) => !h.rescuedByBoundary);
|
|
4589
|
+
const longestFirst = shape.words.every((w, i) => i === 0 || shape.words[i - 1].length >= w.length);
|
|
4590
|
+
const shown = shape.words.length > 8 ? [...shape.words.slice(0, 6), "/* \u2026 */", shape.words[shape.words.length - 1]] : shape.words;
|
|
4591
|
+
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" : ""} })`;
|
|
4592
|
+
out.push({
|
|
4593
|
+
kind: "keyword-regex",
|
|
4594
|
+
id: `keyword-regex:${siteToString(v2.site)}`,
|
|
4595
|
+
site: v2.site,
|
|
4596
|
+
source: d.source,
|
|
4597
|
+
flags: d.flags,
|
|
4598
|
+
words: shape.words,
|
|
4599
|
+
boundary: shape.boundary,
|
|
4600
|
+
caseFoldRisk: ci && !unicode,
|
|
4601
|
+
siblingArms: siblings,
|
|
4602
|
+
vocabulary,
|
|
4603
|
+
longestFirst,
|
|
4604
|
+
hazards,
|
|
4605
|
+
bug: unrescued.length > 0,
|
|
4606
|
+
suggestion: [
|
|
4607
|
+
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.`,
|
|
4608
|
+
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.` : "",
|
|
4609
|
+
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.` : "",
|
|
4610
|
+
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.` : ""
|
|
4611
|
+
].filter((s) => s !== "").join(" ")
|
|
4612
|
+
});
|
|
4613
|
+
}
|
|
4614
|
+
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);
|
|
4615
|
+
}
|
|
4616
|
+
var sitesLine = (sites) => sites.slice(0, 6).map(siteToString).join("\n ") + (sites.length > 6 ? `
|
|
4617
|
+
\u2026 and ${sites.length - 6} more` : "");
|
|
4618
|
+
function formatDuplicationFindings(report) {
|
|
4619
|
+
const lines = [];
|
|
4620
|
+
for (const f of report.structureLoss) {
|
|
4621
|
+
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)}`);
|
|
4622
|
+
lines.push(` flat: ${f.earlierShape}`);
|
|
4623
|
+
lines.push(` rich: ${f.laterShape}`);
|
|
4624
|
+
lines.push(` lost: ${f.lostNodeTypes.map((t) => `\`${t}\``).join(", ")}`);
|
|
4625
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4626
|
+
}
|
|
4627
|
+
for (const f of report.rewrites) {
|
|
4628
|
+
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)"}`);
|
|
4629
|
+
lines.push(` from: ${f.from}`);
|
|
4630
|
+
lines.push(` to: ${f.to}`);
|
|
4631
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4632
|
+
if (f.perf !== "") lines.push(` perf: ${f.perf}`);
|
|
4633
|
+
}
|
|
4634
|
+
for (const f of report.divergentNodes) {
|
|
4635
|
+
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(", ")}`);
|
|
4636
|
+
for (const p of f.productions) lines.push(` ${siteToString(p.site)}
|
|
4637
|
+
${p.shape}
|
|
4638
|
+
unique to it: ${p.distinctTerms.length === 0 ? "(none)" : p.distinctTerms.map((t) => `\`${t}\``).join(", ")}`);
|
|
4639
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4640
|
+
}
|
|
4641
|
+
for (const f of report.keywordRegexes) {
|
|
4642
|
+
const src = f.source.length > 90 ? `${f.source.slice(0, 88)}\u2026` : f.source;
|
|
4643
|
+
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]" : ""}`);
|
|
4644
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4645
|
+
}
|
|
4646
|
+
for (const f of report.duplicates) {
|
|
4647
|
+
lines.push(`parseman duplication: ${f.count}\xD7 identical ${f.size}-node shape (saves ${f.savings} nodes) \u2014 ${f.shape}`);
|
|
4648
|
+
lines.push(` at: ${sitesLine(f.sites)}`);
|
|
4649
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4650
|
+
}
|
|
4651
|
+
for (const f of report.nearDuplicates) {
|
|
4652
|
+
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}`);
|
|
4653
|
+
lines.push(` slot: ${f.slotPath} \u2208 { ${f.variants.join(" | ")} }`);
|
|
4654
|
+
lines.push(` at: ${sitesLine(f.sites)}`);
|
|
4655
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4656
|
+
}
|
|
4657
|
+
for (const f of report.regexFragments) {
|
|
4658
|
+
lines.push(`parseman regex-fragment: \`${f.fragment}\` (${f.branches} branches) re-spelled in ${f.count} regex() terminals`);
|
|
4659
|
+
lines.push(` at: ${sitesLine(f.sites)}`);
|
|
4660
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4661
|
+
}
|
|
4662
|
+
for (const f of report.regexClasses) {
|
|
4663
|
+
lines.push(`parseman regex-class${f.drifted ? " DRIFT" : ""}: [${f.canonical}] across ${f.count} regex() terminals${f.bmpCeiling ? " [BMP ceiling]" : ""}`);
|
|
4664
|
+
for (const v2 of f.variants) lines.push(` [${v2.source}] \xD7${v2.count} ${v2.delta}
|
|
4665
|
+
${sitesLine(v2.sites)}`);
|
|
4666
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4667
|
+
}
|
|
4668
|
+
for (const f of report.overlaps) {
|
|
4669
|
+
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]" : ""}`);
|
|
4670
|
+
lines.push(` fix: ${f.suggestion}`);
|
|
4671
|
+
}
|
|
4672
|
+
return lines;
|
|
4673
|
+
}
|
|
4674
|
+
function duplicationFindingCount(report) {
|
|
4675
|
+
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;
|
|
4676
|
+
}
|
|
4677
|
+
|
|
3328
4678
|
// src/combinators/scanTo.ts
|
|
3329
4679
|
function resolveScanSkip(explicitSkip, raw, ctx) {
|
|
3330
4680
|
if (raw) return [];
|
|
@@ -6553,12 +7903,14 @@ function emitNode(def, ctx, pos) {
|
|
|
6553
7903
|
ctx.buildSrcs.push(def.buildSrc ?? null);
|
|
6554
7904
|
}
|
|
6555
7905
|
const i = ind(ctx);
|
|
6556
|
-
const
|
|
6557
|
-
|
|
6558
|
-
const
|
|
6559
|
-
const
|
|
7906
|
+
const cstOut = ctx.hostMode === "cst" && !structural;
|
|
7907
|
+
if (!structural && !cstOut) ctx.hostBranchElided = true;
|
|
7908
|
+
const capturesTrivia = cstOut || mkType !== null || def.captureTrivia === true || def.trailingTrivia === true || !structural && buildReadsTrivia(def);
|
|
7909
|
+
const clonesState = !structural && (cstOut || buildReadsState(def));
|
|
7910
|
+
const capturesChildren = !structural && (cstOut || mkType !== null || def.unwrap || def.collapse || buildReadsChildren(def));
|
|
7911
|
+
const capturesRaw = !structural && (cstOut || mkType !== null || buildReadsRaw(def));
|
|
6560
7912
|
const hasFields = parserHasOwnFields(def.parser);
|
|
6561
|
-
const capturesFields = hasFields && !structural && buildReadsFields(def);
|
|
7913
|
+
const capturesFields = hasFields && !structural && (cstOut || buildReadsFields(def));
|
|
6562
7914
|
const innerEnablesTriviaCapture = parserEnablesTriviaCapture(def.parser);
|
|
6563
7915
|
const chV = v(ctx, "_ch");
|
|
6564
7916
|
const rawV = v(ctx, "_raw");
|
|
@@ -6575,8 +7927,9 @@ function emitNode(def, ctx, pos) {
|
|
|
6575
7927
|
const profHoist = `${i}const ${pmV} = _ctx._pmProfile, ${recV} = ${pmV}?.phase === 'recognizer', ${capV} = ${pmV}?.phase === 'capture'`;
|
|
6576
7928
|
const profileRecognizer = recV;
|
|
6577
7929
|
const profileCapture = capV;
|
|
6578
|
-
const
|
|
6579
|
-
const
|
|
7930
|
+
const cstMode = ctx.hostMode === "cst";
|
|
7931
|
+
const directCstV = !structural && !cstMode && (!capturesChildren || !capturesRaw) ? v(ctx, "_dcst") : null;
|
|
7932
|
+
const directCstGate = directCstV === null ? "false" : profileCapture;
|
|
6580
7933
|
const structuralCapturesTrivia = structural && (def.captureTrivia === true || def.trailingTrivia === true);
|
|
6581
7934
|
const chNeededExpr = def.unwrap || def.collapse ? "true" : `(_ctx._pmReadsCh ??= (_ctx.build === undefined || _ctx.build._parsemanReadsChildren !== false || _ctx.build._parsemanCstCollapse !== undefined))`;
|
|
6582
7935
|
const chAlloc = def.unwrap || def.collapse ? `${profileRecognizer} ? undefined : []` : `${profileRecognizer} ? undefined : ((${profileCapture} || ${chNeededExpr}) ? [] : undefined)`;
|
|
@@ -6657,7 +8010,7 @@ ${i}const ${chV} = ${chAlloc}, ${rawV} = ${profileRecognizer} ? undefined : [],
|
|
|
6657
8010
|
const ndV = v(ctx, "_nd");
|
|
6658
8011
|
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})`;
|
|
6659
8012
|
const hostBuildExpr = `_ctx._pmProfile?.phase === 'host' && _ctx._pmProfile.hostCalls++, _ctx.build(${JSON.stringify(def.type)}, ${chV}, ${fObj}, { start: ${pos}, end: ${endVar} }, ${rawV}, ${tlV}, ${stV})`;
|
|
6660
|
-
const ndExpr = structural ? `_ctx.build !== undefined ? (${hostBuildExpr}) : (${buildExpr})` :
|
|
8013
|
+
const ndExpr = structural ? `_ctx.build !== undefined ? (${hostBuildExpr}) : (${buildExpr})` : cstOut ? hostBuildExpr : buildExpr;
|
|
6661
8014
|
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;
|
|
6662
8015
|
const unwrapExpr = `${chV}.length === 1 ? (${chV}[0] !== null && typeof ${chV}[0] === 'object' && ${chV}[0]._tag === 'leaf' ? ${chV}[0].value : ${chV}[0]) : (${ndExpr})`;
|
|
6663
8016
|
const collapseExpr = `${chV}.length === 1 ? ${chV}[0] : (${ndExpr})`;
|
|
@@ -7106,9 +8459,9 @@ function hasDirectBuildDef(p, seen = /* @__PURE__ */ new Set()) {
|
|
|
7106
8459
|
return false;
|
|
7107
8460
|
}
|
|
7108
8461
|
}
|
|
7109
|
-
return
|
|
8462
|
+
return childrenOf2(d).some((child) => hasDirectBuildDef(child, seen));
|
|
7110
8463
|
}
|
|
7111
|
-
function
|
|
8464
|
+
function childrenOf2(def) {
|
|
7112
8465
|
switch (def.tag) {
|
|
7113
8466
|
case "sequence":
|
|
7114
8467
|
case "choice":
|
|
@@ -7179,7 +8532,7 @@ function subtreeSizes(roots) {
|
|
|
7179
8532
|
const def = p._def;
|
|
7180
8533
|
let s = 1;
|
|
7181
8534
|
if (def.tag !== "lazy") {
|
|
7182
|
-
for (const child of
|
|
8535
|
+
for (const child of childrenOf2(def)) s += child._def.tag === "lazy" ? 1 : sz(child);
|
|
7183
8536
|
}
|
|
7184
8537
|
sizes.set(p, s);
|
|
7185
8538
|
return s;
|
|
@@ -7200,7 +8553,7 @@ function subtreeSizes(roots) {
|
|
|
7200
8553
|
return;
|
|
7201
8554
|
}
|
|
7202
8555
|
sz(p);
|
|
7203
|
-
for (const child of
|
|
8556
|
+
for (const child of childrenOf2(def)) visit(child);
|
|
7204
8557
|
};
|
|
7205
8558
|
for (const root of roots) visit(root);
|
|
7206
8559
|
return sizes;
|
|
@@ -7234,7 +8587,7 @@ function analyzeLazyUsageMulti(roots) {
|
|
|
7234
8587
|
if (isHoistableTag(def.tag)) {
|
|
7235
8588
|
counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
7236
8589
|
}
|
|
7237
|
-
for (const child of
|
|
8590
|
+
for (const child of childrenOf2(def)) walk2(child);
|
|
7238
8591
|
}
|
|
7239
8592
|
const rootsArr = [...roots];
|
|
7240
8593
|
for (const root of rootsArr) walk2(root);
|
|
@@ -7266,7 +8619,7 @@ function ruleDependencies(ruleMap) {
|
|
|
7266
8619
|
walk2(resolved, false);
|
|
7267
8620
|
return;
|
|
7268
8621
|
}
|
|
7269
|
-
for (const child of
|
|
8622
|
+
for (const child of childrenOf2(def)) walk2(child, false);
|
|
7270
8623
|
};
|
|
7271
8624
|
walk2(comb, true);
|
|
7272
8625
|
deps.set(name, [...found]);
|
|
@@ -7286,10 +8639,30 @@ function runGatingDiagnostic(combinator, opt) {
|
|
|
7286
8639
|
function runGatingDiagnosticRules(ruleMap, opt) {
|
|
7287
8640
|
return reportGating(opt, (o) => analyzeGatingRules(ruleMap, o));
|
|
7288
8641
|
}
|
|
7289
|
-
function runFusedGatingDiagnostic(getRuleMaps, opt) {
|
|
8642
|
+
function runFusedGatingDiagnostic(getRuleMaps, opt, getOpaque) {
|
|
7290
8643
|
if (resolveGatingLevel(opt) === "off") return void 0;
|
|
7291
8644
|
const ruleMaps = getRuleMaps();
|
|
7292
|
-
|
|
8645
|
+
const opaque = getOpaque?.() ?? [];
|
|
8646
|
+
const opaqueFindings = opaque.map((o) => ({
|
|
8647
|
+
rule: o.ruleNames.length > 0 ? o.ruleNames.join(", ") : `<artifact ${o.ns}>`,
|
|
8648
|
+
kind: "opaque-artifact",
|
|
8649
|
+
reason: `precompiled artifact "${o.ns}" carries compiled rule functions, not re-lowerable IR \u2014 its choices were not examined at this fuse.`
|
|
8650
|
+
}));
|
|
8651
|
+
if (!ruleMaps.some((map) => hasExternalRuleRef(map))) {
|
|
8652
|
+
if (opaqueFindings.length === 0) return void 0;
|
|
8653
|
+
return reportGating(opt, () => ({
|
|
8654
|
+
totalChoices: 0,
|
|
8655
|
+
gated: 0,
|
|
8656
|
+
recoverable: 0,
|
|
8657
|
+
unanalysable: opaqueFindings,
|
|
8658
|
+
ungated: [],
|
|
8659
|
+
accepted: [],
|
|
8660
|
+
deferred: [],
|
|
8661
|
+
acceptedUnused: [],
|
|
8662
|
+
choices: [],
|
|
8663
|
+
antiPatterns: []
|
|
8664
|
+
}));
|
|
8665
|
+
}
|
|
7293
8666
|
const winners = /* @__PURE__ */ new Map();
|
|
7294
8667
|
for (const map of ruleMaps) for (const [name, rule] of map) {
|
|
7295
8668
|
if (rule._def.tag === "lazy") {
|
|
@@ -7305,7 +8678,12 @@ function runFusedGatingDiagnostic(getRuleMaps, opt) {
|
|
|
7305
8678
|
return reportGating(opt, (o) => {
|
|
7306
8679
|
const deferredHere = new Set(analyzeGatingRules(entries, o).deferred.map((c) => c.id));
|
|
7307
8680
|
const fused = analyzeGatingRules(entries, { ...o, resolveRef: (name) => winners.get(name) });
|
|
7308
|
-
return {
|
|
8681
|
+
return {
|
|
8682
|
+
...fused,
|
|
8683
|
+
ungated: fused.ungated.filter((c) => deferredHere.has(c.id)),
|
|
8684
|
+
antiPatterns: [],
|
|
8685
|
+
unanalysable: [...fused.unanalysable, ...opaqueFindings]
|
|
8686
|
+
};
|
|
7309
8687
|
});
|
|
7310
8688
|
}
|
|
7311
8689
|
function reportGating(opt, analyze) {
|
|
@@ -7316,22 +8694,82 @@ function reportGating(opt, analyze) {
|
|
|
7316
8694
|
let report;
|
|
7317
8695
|
try {
|
|
7318
8696
|
report = analyze(analyzeOpts);
|
|
7319
|
-
} catch {
|
|
7320
|
-
|
|
8697
|
+
} catch (e) {
|
|
8698
|
+
const reason = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
8699
|
+
const failed = {
|
|
8700
|
+
totalChoices: 0,
|
|
8701
|
+
gated: 0,
|
|
8702
|
+
recoverable: 0,
|
|
8703
|
+
unanalysable: [{ rule: "<whole grammar>", kind: "not-a-combinator", reason: `gating analysis threw \u2014 ${reason}` }],
|
|
8704
|
+
ungated: [],
|
|
8705
|
+
accepted: [],
|
|
8706
|
+
deferred: [],
|
|
8707
|
+
acceptedUnused: [],
|
|
8708
|
+
choices: [],
|
|
8709
|
+
antiPatterns: []
|
|
8710
|
+
};
|
|
8711
|
+
const failLines = formatGatingWarnings(failed);
|
|
8712
|
+
if (level === "error") throw new Error(`parseman: gating analysis FAILED (no verdict available)
|
|
8713
|
+
${failLines.join("\n")}`);
|
|
8714
|
+
for (const l of failLines) console.warn(l);
|
|
8715
|
+
return failed;
|
|
7321
8716
|
}
|
|
7322
8717
|
const lines = formatGatingWarnings(report);
|
|
7323
8718
|
if (lines.length > 0) {
|
|
7324
|
-
if (level === "error") throw new Error(`parseman: ${report.ungated.length} ungated hot choice(s) / ${report.antiPatterns.length} anti-pattern(s)
|
|
8719
|
+
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)
|
|
7325
8720
|
${lines.join("\n")}`);
|
|
7326
8721
|
for (const l of lines) console.warn(l);
|
|
7327
8722
|
}
|
|
7328
8723
|
return report;
|
|
7329
8724
|
}
|
|
8725
|
+
function resolveDuplicationLevel(opt) {
|
|
8726
|
+
const explicit = typeof opt === "string" ? opt : opt?.level;
|
|
8727
|
+
if (explicit !== void 0) return explicit;
|
|
8728
|
+
const env = typeof process !== "undefined" ? process.env?.PARSEMAN_DUPLICATION : void 0;
|
|
8729
|
+
if (env === "off" || env === "warn" || env === "error") return env;
|
|
8730
|
+
return "off";
|
|
8731
|
+
}
|
|
8732
|
+
function reportDuplication(opt, analyze) {
|
|
8733
|
+
const level = resolveDuplicationLevel(opt);
|
|
8734
|
+
if (level === "off") return void 0;
|
|
8735
|
+
const obj = opt !== null && typeof opt === "object" ? opt : void 0;
|
|
8736
|
+
const analyzeOpts = obj === void 0 ? void 0 : {
|
|
8737
|
+
...obj.accept !== void 0 ? { accept: obj.accept } : {},
|
|
8738
|
+
...obj.minSize !== void 0 ? { minSize: obj.minSize } : {},
|
|
8739
|
+
...obj.maxFindings !== void 0 ? { maxFindings: obj.maxFindings } : {},
|
|
8740
|
+
...obj.entryName !== void 0 ? { entryName: obj.entryName } : {}
|
|
8741
|
+
};
|
|
8742
|
+
let report;
|
|
8743
|
+
try {
|
|
8744
|
+
report = analyze(analyzeOpts);
|
|
8745
|
+
} catch (err) {
|
|
8746
|
+
console.warn(
|
|
8747
|
+
`parseman: the duplication diagnostic could not run, so NOTHING was checked \u2014 this is not a clean result.
|
|
8748
|
+
${err instanceof Error ? err.message : String(err)}`
|
|
8749
|
+
);
|
|
8750
|
+
return void 0;
|
|
8751
|
+
}
|
|
8752
|
+
const lines = formatDuplicationFindings(report);
|
|
8753
|
+
if (lines.length > 0) {
|
|
8754
|
+
if (level === "error") throw new Error(`parseman: ${duplicationFindingCount(report)} duplication/overlap finding(s)
|
|
8755
|
+
${lines.join("\n")}`);
|
|
8756
|
+
for (const l of lines) console.warn(l);
|
|
8757
|
+
}
|
|
8758
|
+
return report;
|
|
8759
|
+
}
|
|
8760
|
+
function runDuplicationDiagnostic(combinator, opt) {
|
|
8761
|
+
return reportDuplication(opt, (o) => analyzeDuplication(combinator, o));
|
|
8762
|
+
}
|
|
8763
|
+
function runDuplicationDiagnosticRules(ruleMap, opt) {
|
|
8764
|
+
return reportDuplication(opt, (o) => analyzeDuplicationRules(ruleMap, o));
|
|
8765
|
+
}
|
|
7330
8766
|
function compile(combinator, mapFnSources, opts) {
|
|
7331
8767
|
const gatingReport = runGatingDiagnostic(combinator, opts?.gating);
|
|
8768
|
+
runDuplicationDiagnostic(combinator, opts?.duplication);
|
|
7332
8769
|
markUnusedValues(combinator);
|
|
7333
8770
|
const grammarTrivia = combinator._meta.grammarTrivia;
|
|
7334
8771
|
const grammarScanSkip = combinator._meta.grammarScanSkip;
|
|
8772
|
+
const grammarHostMode = combinator._meta.grammarHostMode;
|
|
7335
8773
|
const ctx = {
|
|
7336
8774
|
vars: 0,
|
|
7337
8775
|
indent: 1,
|
|
@@ -7351,6 +8789,7 @@ function compile(combinator, mapFnSources, opts) {
|
|
|
7351
8789
|
namedFnDecls: [],
|
|
7352
8790
|
capturing: hasNodeDef(combinator),
|
|
7353
8791
|
recovery: opts?.recovery ?? false,
|
|
8792
|
+
hostMode: opts?.hostMode ?? grammarHostMode ?? "ast",
|
|
7354
8793
|
...opts?.coverage ? { coverage: { plan: buildGrammarPlan(combinator), entry: combinator } } : {},
|
|
7355
8794
|
lazyUsage: analyzeLazyUsage(combinator),
|
|
7356
8795
|
...grammarTrivia ? { activeTrivia: grammarTrivia, triviaKindLabels: grammarTrivia._meta.triviaKindLabels } : {},
|
|
@@ -7423,6 +8862,7 @@ function compile(combinator, mapFnSources, opts) {
|
|
|
7423
8862
|
return fn(input, pos, ctx.runtimeParsers, ctx.mapFns, ctx.buildFns, defaultCtx);
|
|
7424
8863
|
},
|
|
7425
8864
|
parseWithContext(input, parseCtx, pos = 0) {
|
|
8865
|
+
assertHostModeCompatible(ctx.hostMode ?? "ast", parseCtx.build, !!ctx.hostBranchElided);
|
|
7426
8866
|
return fn(input, pos, ctx.runtimeParsers, ctx.mapFns, ctx.buildFns, parseCtx);
|
|
7427
8867
|
},
|
|
7428
8868
|
// Note: collects expect() errors via _errors. Unlike interpreter
|
|
@@ -7452,10 +8892,12 @@ function publicRuleWrapperSource(rule, fnSource) {
|
|
|
7452
8892
|
}
|
|
7453
8893
|
function compileRuleMap(ruleMap, opts) {
|
|
7454
8894
|
runGatingDiagnosticRules(ruleMap, opts?.gating);
|
|
8895
|
+
runDuplicationDiagnosticRules(ruleMap, opts?.duplication);
|
|
7455
8896
|
for (const [, rule] of ruleMap) markUnusedValues(rule);
|
|
7456
8897
|
const coverageWinners = opts?.coverage ? Object.fromEntries(ruleMap.filter(([, rule]) => rule._def.tag !== "lazy")) : void 0;
|
|
7457
8898
|
const grammarTrivia = opts?.trivia;
|
|
7458
8899
|
const grammarScanSkip = opts?.scanSkip ?? ruleMap.map(([, r]) => r._meta.grammarScanSkip).find(Boolean);
|
|
8900
|
+
const grammarHostMode = opts?.hostMode ?? ruleMap.map(([, r]) => r._meta.grammarHostMode).find(Boolean);
|
|
7459
8901
|
const ctx = {
|
|
7460
8902
|
vars: 0,
|
|
7461
8903
|
indent: 1,
|
|
@@ -7475,6 +8917,7 @@ function compileRuleMap(ruleMap, opts) {
|
|
|
7475
8917
|
namedFnDecls: [],
|
|
7476
8918
|
capturing: ruleMap.some(([, rule]) => hasNodeDef(rule)),
|
|
7477
8919
|
recovery: opts?.recovery ?? false,
|
|
8920
|
+
hostMode: grammarHostMode ?? "ast",
|
|
7478
8921
|
...opts?.coverage ? { coverage: { plan: buildGrammarPlan(ruleMap.map(([, rule]) => rule), coverageWinners) } } : {},
|
|
7479
8922
|
lazyUsage: analyzeLazyUsageMulti(ruleMap.map(([, rule]) => rule)),
|
|
7480
8923
|
...grammarTrivia ? { activeTrivia: grammarTrivia, triviaKindLabels: grammarTrivia._meta.triviaKindLabels } : {},
|
|
@@ -7565,15 +9008,22 @@ function compileRuleMap(ruleMap, opts) {
|
|
|
7565
9008
|
return {
|
|
7566
9009
|
keys: perEntry.map((e) => e.key),
|
|
7567
9010
|
replacement,
|
|
9011
|
+
// Reported so the MACRO can stamp the emitted map, exactly as `fusedBody` stamps a
|
|
9012
|
+
// fused one. Without it a `rules()` artifact carries no mode and every driver-side
|
|
9013
|
+
// host check passes vacuously — see `withHostMode` in the plugin.
|
|
9014
|
+
hostMode: ctx.hostMode ?? "ast",
|
|
9015
|
+
hostBranchElided: !!ctx.hostBranchElided,
|
|
7568
9016
|
...ctx.coverage === void 0 ? {} : { coverageDefinitions: ctx.coverage.plan.definitions }
|
|
7569
9017
|
};
|
|
7570
9018
|
}
|
|
7571
9019
|
function compileLinkable(ruleMapArg, ns, opts) {
|
|
7572
9020
|
if (!ns) throw new Error("compileLinkable: ns must be a non-empty namespace");
|
|
7573
9021
|
if (opts?.gating !== void 0) runGatingDiagnosticRules(ruleMapArg, opts.gating);
|
|
9022
|
+
if (opts?.duplication !== void 0) runDuplicationDiagnosticRules(ruleMapArg, opts.duplication);
|
|
7574
9023
|
for (const [, rule] of ruleMapArg) markUnusedValues(rule);
|
|
7575
9024
|
const grammarTrivia = opts?.trivia ?? ruleMapArg.map(([, r]) => r._meta.grammarTrivia).find(Boolean);
|
|
7576
9025
|
const grammarScanSkip = opts?.scanSkip ?? ruleMapArg.map(([, r]) => r._meta.grammarScanSkip).find(Boolean);
|
|
9026
|
+
const grammarHostMode = opts?.hostMode ?? ruleMapArg.map(([, r]) => r._meta.grammarHostMode).find(Boolean);
|
|
7577
9027
|
const ruleMap = ruleMapArg.filter(([, val]) => {
|
|
7578
9028
|
const d = val._def;
|
|
7579
9029
|
if (d.tag !== "lazy") return true;
|
|
@@ -7607,6 +9057,7 @@ function compileLinkable(ruleMapArg, ns, opts) {
|
|
|
7607
9057
|
// merely returning their scalar parse values.
|
|
7608
9058
|
capturing: opts?.captureTerminals === true || ruleMap.some(([, rule]) => hasNodeDef(rule)),
|
|
7609
9059
|
recovery: opts?.recovery ?? false,
|
|
9060
|
+
hostMode: grammarHostMode ?? "ast",
|
|
7610
9061
|
...opts?.coverage ? { coverage: { plan: opts.coverage } } : {},
|
|
7611
9062
|
lazyUsage: analyzeLazyUsageMulti(ruleMap.map(([, rule]) => rule)),
|
|
7612
9063
|
ns,
|
|
@@ -7657,7 +9108,7 @@ function compileLinkable(ruleMapArg, ns, opts) {
|
|
|
7657
9108
|
scanExternal(resolved);
|
|
7658
9109
|
return;
|
|
7659
9110
|
}
|
|
7660
|
-
for (const child of
|
|
9111
|
+
for (const child of childrenOf2(def)) scanExternal(child);
|
|
7661
9112
|
};
|
|
7662
9113
|
for (const [, rule] of ruleMap) scanExternal(rule);
|
|
7663
9114
|
}
|
|
@@ -7762,6 +9213,8 @@ function compileLinkable(ruleMapArg, ns, opts) {
|
|
|
7762
9213
|
deps: ruleDependencies(ruleMap),
|
|
7763
9214
|
needsEmptyTl: !!ctx.needsEmptyTl,
|
|
7764
9215
|
needsHostReads: !!ctx.needsHostReads,
|
|
9216
|
+
hostMode: ctx.hostMode ?? "ast",
|
|
9217
|
+
hostBranchElided: !!ctx.hostBranchElided,
|
|
7765
9218
|
hasDirectBuilders: ruleMap.some(([, rule]) => hasDirectBuildDef(rule)),
|
|
7766
9219
|
isRecognitionOnly: !hasSemanticReduction(ruleMap.map(([, rule]) => rule), externalRefs),
|
|
7767
9220
|
mfFns: mfSrcs ? [] : ctx.mapFns,
|
|
@@ -7784,7 +9237,7 @@ function hasExternalRuleRef(ruleMap) {
|
|
|
7784
9237
|
if (resolved === void 0) return p._ruleName !== void 0;
|
|
7785
9238
|
return visit(resolved);
|
|
7786
9239
|
}
|
|
7787
|
-
return
|
|
9240
|
+
return childrenOf2(def).some(visit);
|
|
7788
9241
|
};
|
|
7789
9242
|
return ruleMap.some(([, rule]) => visit(rule));
|
|
7790
9243
|
}
|
|
@@ -7806,7 +9259,7 @@ function hasSemanticReduction(roots, externalRefs) {
|
|
|
7806
9259
|
return true;
|
|
7807
9260
|
}
|
|
7808
9261
|
}
|
|
7809
|
-
return
|
|
9262
|
+
return childrenOf2(def).some(visit);
|
|
7810
9263
|
};
|
|
7811
9264
|
return roots.some(visit);
|
|
7812
9265
|
}
|
|
@@ -7875,7 +9328,7 @@ function withCtx(extra, combinator) {
|
|
|
7875
9328
|
}
|
|
7876
9329
|
|
|
7877
9330
|
// src/compiler/ir-serialize.ts
|
|
7878
|
-
function
|
|
9331
|
+
function childrenOf3(def) {
|
|
7879
9332
|
switch (def.tag) {
|
|
7880
9333
|
case "sequence":
|
|
7881
9334
|
case "choice":
|
|
@@ -7914,7 +9367,7 @@ function childrenOf2(def) {
|
|
|
7914
9367
|
return [];
|
|
7915
9368
|
}
|
|
7916
9369
|
}
|
|
7917
|
-
var
|
|
9370
|
+
var ruleNameOf3 = (c) => c._ruleName;
|
|
7918
9371
|
function lazyTarget(c) {
|
|
7919
9372
|
if (c._def.tag !== "lazy") return null;
|
|
7920
9373
|
try {
|
|
@@ -8112,18 +9565,18 @@ var Serializer = class {
|
|
|
8112
9565
|
if (seen.has(c)) return;
|
|
8113
9566
|
seen.add(c);
|
|
8114
9567
|
if (c._def.tag === "lazy") {
|
|
8115
|
-
if (
|
|
9568
|
+
if (ruleNameOf3(c) !== void 0) throw new Unserializable("scanSkip unit references a grammar rule");
|
|
8116
9569
|
const target = lazyTarget(c);
|
|
8117
9570
|
if (target) this.assertNoRuleRef(target, seen);
|
|
8118
9571
|
return;
|
|
8119
9572
|
}
|
|
8120
|
-
for (const child of
|
|
9573
|
+
for (const child of childrenOf3(c._def)) this.assertNoRuleRef(child, seen);
|
|
8121
9574
|
}
|
|
8122
9575
|
/** A `rules()` map wraps each rule value in a named `lazy` proxy; the real body is
|
|
8123
9576
|
* its target (compileLinkable unwraps the same way). A ref INSIDE a body stays a
|
|
8124
9577
|
* `g[name]` ref — only the top-level entry is unwrapped. */
|
|
8125
9578
|
body(c) {
|
|
8126
|
-
return c._def.tag === "lazy" &&
|
|
9579
|
+
return c._def.tag === "lazy" && ruleNameOf3(c) !== void 0 ? lazyTarget(c) ?? c : c;
|
|
8127
9580
|
}
|
|
8128
9581
|
run() {
|
|
8129
9582
|
for (const [, c] of this.ruleMap) this.analyze(this.body(c), /* @__PURE__ */ new Set());
|
|
@@ -8165,7 +9618,7 @@ ${outerDecls.map((d) => " " + d).join("\n")}
|
|
|
8165
9618
|
analyze(c, active) {
|
|
8166
9619
|
const def = c._def;
|
|
8167
9620
|
if (def.tag === "lazy") {
|
|
8168
|
-
if (
|
|
9621
|
+
if (ruleNameOf3(c) !== void 0) return;
|
|
8169
9622
|
const target = lazyTarget(c);
|
|
8170
9623
|
if (!target) throw new Unserializable("unresolved unnamed ref");
|
|
8171
9624
|
if (active.has(target)) {
|
|
@@ -8181,7 +9634,7 @@ ${outerDecls.map((d) => " " + d).join("\n")}
|
|
|
8181
9634
|
this.counts.set(c, (this.counts.get(c) ?? 0) + 1);
|
|
8182
9635
|
if ((this.counts.get(c) ?? 0) > 1) return;
|
|
8183
9636
|
active.add(c);
|
|
8184
|
-
for (const child of
|
|
9637
|
+
for (const child of childrenOf3(def)) this.analyze(child, active);
|
|
8185
9638
|
active.delete(c);
|
|
8186
9639
|
}
|
|
8187
9640
|
/** Reference `c`: a const var if it has one (emitting its decl first), else inline.
|
|
@@ -8217,7 +9670,7 @@ ${outerDecls.map((d) => " " + d).join("\n")}
|
|
|
8217
9670
|
const kid = (x) => this.ref(x, selfOf);
|
|
8218
9671
|
switch (def.tag) {
|
|
8219
9672
|
case "lazy": {
|
|
8220
|
-
if (
|
|
9673
|
+
if (ruleNameOf3(c) !== void 0) return `g[${JSON.stringify(ruleNameOf3(c))}]`;
|
|
8221
9674
|
const target = lazyTarget(c);
|
|
8222
9675
|
if (selfOf && target === selfOf.comb) return selfOf.var;
|
|
8223
9676
|
return this.ref(target, selfOf);
|
|
@@ -8391,7 +9844,23 @@ function fusedBody(pieces) {
|
|
|
8391
9844
|
...[...winner].map(([k, p]) => p.ruleFns.get(k))
|
|
8392
9845
|
];
|
|
8393
9846
|
const wrapperEntries = [...winner].map(([k, p]) => `${JSON.stringify(k)}: ${p.wrappers.get(k)}`);
|
|
8394
|
-
const
|
|
9847
|
+
const { mode, elided } = hostModeOfPieces(pieces);
|
|
9848
|
+
const rawBody = [
|
|
9849
|
+
...lines,
|
|
9850
|
+
"const _map = {",
|
|
9851
|
+
wrapperEntries.join(",\n"),
|
|
9852
|
+
"}",
|
|
9853
|
+
`Object.defineProperty(_map, Symbol.for(${JSON.stringify(FUSED_HOST_MODE.description)}), { value: ${JSON.stringify(mode)}, enumerable: false })`,
|
|
9854
|
+
`Object.defineProperty(_map, Symbol.for(${JSON.stringify(FUSED_HOST_ELIDED.description)}), { value: ${JSON.stringify(elided)}, enumerable: false })`,
|
|
9855
|
+
// …and on each rule FUNCTION, because `run(map.Rule, …)` is handed the rule, not the
|
|
9856
|
+
// map, and would otherwise have nothing to check against. Done once at fuse time,
|
|
9857
|
+
// before any rule has been called, so it costs nothing per parse.
|
|
9858
|
+
"for (const _k of Object.keys(_map)) {",
|
|
9859
|
+
` Object.defineProperty(_map[_k], Symbol.for(${JSON.stringify(FUSED_HOST_MODE.description)}), { value: ${JSON.stringify(mode)}, enumerable: false })`,
|
|
9860
|
+
` Object.defineProperty(_map[_k], Symbol.for(${JSON.stringify(FUSED_HOST_ELIDED.description)}), { value: ${JSON.stringify(elided)}, enumerable: false })`,
|
|
9861
|
+
"}",
|
|
9862
|
+
"return _map"
|
|
9863
|
+
].join("\n");
|
|
8395
9864
|
const ANY2 = { kind: "any" };
|
|
8396
9865
|
const EMPTY3 = { kind: "empty" };
|
|
8397
9866
|
const recipes = /* @__PURE__ */ new Map();
|
|
@@ -8450,6 +9919,16 @@ function fusedBody(pieces) {
|
|
|
8450
9919
|
}
|
|
8451
9920
|
return { body, env };
|
|
8452
9921
|
}
|
|
9922
|
+
function hostModeOfPieces(pieces) {
|
|
9923
|
+
const mode = pieces.find((p) => p.hostMode !== void 0 && p.hostMode !== "ast")?.hostMode ?? "ast";
|
|
9924
|
+
const elided = pieces.filter((p) => p.hostBranchElided === true);
|
|
9925
|
+
if (mode === "cst" && elided.length > 0) {
|
|
9926
|
+
throw new Error(
|
|
9927
|
+
`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.`
|
|
9928
|
+
);
|
|
9929
|
+
}
|
|
9930
|
+
return { mode, elided: elided.length > 0 };
|
|
9931
|
+
}
|
|
8453
9932
|
function emitFusedSource(pieces) {
|
|
8454
9933
|
const { body, env } = fusedBody(pieces);
|
|
8455
9934
|
if (Object.keys(env).length > 0) {
|
|
@@ -8462,11 +9941,23 @@ ${body}
|
|
|
8462
9941
|
function isIRPiece(p) {
|
|
8463
9942
|
return !!p && typeof p === "object" && typeof p.ir === "string" && typeof p.ns === "string" && !("ruleFns" in p);
|
|
8464
9943
|
}
|
|
8465
|
-
function
|
|
9944
|
+
function once(fn) {
|
|
9945
|
+
let done = false;
|
|
9946
|
+
let value;
|
|
9947
|
+
return () => {
|
|
9948
|
+
if (!done) {
|
|
9949
|
+
value = fn();
|
|
9950
|
+
done = true;
|
|
9951
|
+
}
|
|
9952
|
+
return value;
|
|
9953
|
+
};
|
|
9954
|
+
}
|
|
9955
|
+
function materializePiece(p, trivia2, captureTerminals = false, hostMode) {
|
|
8466
9956
|
if (!isIRPiece(p)) return p;
|
|
8467
9957
|
const pieces = compileLinkable(evalRuleMapIR(p.ir), p.ns, {
|
|
8468
9958
|
...trivia2 ? { trivia: trivia2 } : {},
|
|
8469
|
-
...captureTerminals ? { captureTerminals: true } : {}
|
|
9959
|
+
...captureTerminals ? { captureTerminals: true } : {},
|
|
9960
|
+
...hostMode ? { hostMode } : {}
|
|
8470
9961
|
});
|
|
8471
9962
|
if (!pieces) throw new Error(`compose: carried IR for ns "${p.ns}" could not be re-lowered`);
|
|
8472
9963
|
return pieces;
|
|
@@ -9566,6 +11057,23 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9566
11057
|
for (const n of names) allNames.add(n);
|
|
9567
11058
|
}
|
|
9568
11059
|
if (macroImports.length === 0) return null;
|
|
11060
|
+
const factoryDecls = /* @__PURE__ */ new Map();
|
|
11061
|
+
for (const stmt of body) {
|
|
11062
|
+
const decl = stmt.type === "ExportNamedDeclaration" ? stmt.declaration : stmt;
|
|
11063
|
+
if (decl?.type !== "VariableDeclaration") continue;
|
|
11064
|
+
if (decl.kind !== "const") continue;
|
|
11065
|
+
for (const d of decl.declarations) {
|
|
11066
|
+
const id2 = d.id;
|
|
11067
|
+
const init = d.init;
|
|
11068
|
+
if (id2.type !== "Identifier" || !id2.name || !init) continue;
|
|
11069
|
+
if (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression") {
|
|
11070
|
+
factoryDecls.set(id2.name, {
|
|
11071
|
+
fn: init,
|
|
11072
|
+
declaredAt: d.end
|
|
11073
|
+
});
|
|
11074
|
+
}
|
|
11075
|
+
}
|
|
11076
|
+
}
|
|
9569
11077
|
const scope = /* @__PURE__ */ new Map();
|
|
9570
11078
|
const replacements = [];
|
|
9571
11079
|
const warnings = [];
|
|
@@ -9588,20 +11096,28 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9588
11096
|
const arg0 = args[0];
|
|
9589
11097
|
const arg1 = args[1];
|
|
9590
11098
|
const optionsFirst = arg0?.type === "ObjectExpression";
|
|
9591
|
-
const
|
|
9592
|
-
if (!
|
|
11099
|
+
const factoryArgRaw = optionsFirst ? arg1 : arg0;
|
|
11100
|
+
if (!factoryArgRaw) {
|
|
9593
11101
|
warn(init.start, `${label2}: rules() needs a factory argument`);
|
|
9594
11102
|
return null;
|
|
9595
11103
|
}
|
|
11104
|
+
const namedFactory = factoryArgRaw.type === "Identifier" ? factoryDecls.get(factoryArgRaw.name) : void 0;
|
|
11105
|
+
const factoryArg = namedFactory !== void 0 && namedFactory.declaredAt <= init.start ? namedFactory.fn : factoryArgRaw;
|
|
11106
|
+
const optionsArg = optionsFirst ? arg0 : arg1;
|
|
11107
|
+
const optionValue = (name) => optionsArg?.type === "ObjectExpression" ? (optionsArg.properties ?? []).find(
|
|
11108
|
+
(p) => p.key?.name === name
|
|
11109
|
+
)?.value : void 0;
|
|
11110
|
+
const hostModeValue = optionValue("hostMode");
|
|
11111
|
+
const gHostMode = hostModeValue?.type === "Literal" ? hostModeValue.value : void 0;
|
|
11112
|
+
if (hostModeValue !== void 0 && gHostMode !== "ast" && gHostMode !== "cst") {
|
|
11113
|
+
warn(init.start, `${label2}: rules({ hostMode }) must be the literal 'ast' or 'cst'`);
|
|
11114
|
+
return null;
|
|
11115
|
+
}
|
|
9596
11116
|
const ruleMap = evaluateParserFactory(factoryArg, scope, code, []);
|
|
9597
11117
|
if (!ruleMap) {
|
|
9598
11118
|
warn(init.start, `${label2}: rules(...) factory isn't statically evaluable`);
|
|
9599
11119
|
return null;
|
|
9600
11120
|
}
|
|
9601
|
-
const optionsArg = optionsFirst ? arg0 : arg1;
|
|
9602
|
-
const optionValue = (name) => optionsArg?.type === "ObjectExpression" ? (optionsArg.properties ?? []).find(
|
|
9603
|
-
(p) => p.key?.name === name
|
|
9604
|
-
)?.value : void 0;
|
|
9605
11121
|
const triviaValue = optionValue("trivia");
|
|
9606
11122
|
const gTrivia = triviaValue ? evaluateExpr(triviaValue, scope, code, []) : void 0;
|
|
9607
11123
|
const scanSkipValue = optionValue("scanSkip");
|
|
@@ -9614,13 +11130,29 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9614
11130
|
}
|
|
9615
11131
|
}
|
|
9616
11132
|
}
|
|
11133
|
+
if (gHostMode === "cst") {
|
|
11134
|
+
for (const rule of ruleMap.values()) {
|
|
11135
|
+
if (rule && !rule._meta.isTrivia) {
|
|
11136
|
+
;
|
|
11137
|
+
rule._meta.grammarHostMode = "cst";
|
|
11138
|
+
}
|
|
11139
|
+
}
|
|
11140
|
+
}
|
|
9617
11141
|
return { ruleMap, ...gTrivia ? { trivia: gTrivia } : {}, ...gScanSkip ? { scanSkip: gScanSkip } : {} };
|
|
9618
11142
|
};
|
|
9619
11143
|
const compileRulesFactory = (init, label2) => {
|
|
9620
11144
|
const evaluated = evaluateRulesFactory(init, label2);
|
|
9621
11145
|
if (!evaluated) return null;
|
|
9622
11146
|
const compiled = compileRuleMap([...evaluated.ruleMap], { ...evaluated.trivia ? { trivia: evaluated.trivia } : {}, ...evaluated.scanSkip ? { scanSkip: evaluated.scanSkip } : {}, recovery, coverage: grammarCoverage });
|
|
9623
|
-
return {
|
|
11147
|
+
return {
|
|
11148
|
+
replacement: compiled?.replacement ?? null,
|
|
11149
|
+
ruleMap: evaluated.ruleMap,
|
|
11150
|
+
hostMode: compiled?.hostMode ?? "ast",
|
|
11151
|
+
hostBranchElided: compiled?.hostBranchElided ?? false,
|
|
11152
|
+
...compiled?.coverageDefinitions ? { coverageDefinitions: compiled.coverageDefinitions } : {},
|
|
11153
|
+
...evaluated.trivia ? { trivia: evaluated.trivia } : {},
|
|
11154
|
+
...evaluated.scanSkip ? { scanSkip: evaluated.scanSkip } : {}
|
|
11155
|
+
};
|
|
9624
11156
|
};
|
|
9625
11157
|
const isRulesCall = (init) => init.type === "CallExpression" && init.callee.type === "Identifier" && init.callee.name === "rules";
|
|
9626
11158
|
const isComposeCall = (init) => init.type === "CallExpression" && init.callee.type === "Identifier" && init.callee.name === "compose";
|
|
@@ -9635,7 +11167,7 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9635
11167
|
const mapLit = (m, stripVals = false) => `new Map([${[...m].map(
|
|
9636
11168
|
([k, v2]) => `[${JSON.stringify(k)}, ${JSON.stringify(stripVals && typeof v2 === "string" ? stripIndent(v2) : v2)}]`
|
|
9637
11169
|
).join(", ")}])`;
|
|
9638
|
-
return `{ v: ${JSON.stringify(p.v)}, ns: ${JSON.stringify(p.ns)}, keys: ${JSON.stringify(p.keys)}, prelude: ${JSON.stringify(p.prelude.map(stripIndent))}, ruleFns: ${mapLit(p.ruleFns, true)}, wrappers: ${mapLit(p.wrappers, true)}, firstSets: ${mapLit(p.firstSets)}, nullable: ${p.nullable ? mapLit(p.nullable) : "new Map()"}, firstSetRecipes: ${p.firstSetRecipes ? mapLit(p.firstSetRecipes) : "new Map()"}, deps: ${mapLit(p.deps)}, needsEmptyTl: ${p.needsEmptyTl}, needsHostReads: ${p.needsHostReads}, hasDirectBuilders: ${p.hasDirectBuilders === true}, isRecognitionOnly: ${p.isRecognitionOnly === true}, mfFns: [], buildFns: [] }`;
|
|
11170
|
+
return `{ v: ${JSON.stringify(p.v)}, ns: ${JSON.stringify(p.ns)}, keys: ${JSON.stringify(p.keys)}, prelude: ${JSON.stringify(p.prelude.map(stripIndent))}, ruleFns: ${mapLit(p.ruleFns, true)}, wrappers: ${mapLit(p.wrappers, true)}, firstSets: ${mapLit(p.firstSets)}, nullable: ${p.nullable ? mapLit(p.nullable) : "new Map()"}, firstSetRecipes: ${p.firstSetRecipes ? mapLit(p.firstSetRecipes) : "new Map()"}, deps: ${mapLit(p.deps)}, hostMode: ${JSON.stringify(p.hostMode ?? "ast")}, hostBranchElided: ${p.hostBranchElided === true}, needsEmptyTl: ${p.needsEmptyTl}, needsHostReads: ${p.needsHostReads}, hasDirectBuilders: ${p.hasDirectBuilders === true}, isRecognitionOnly: ${p.isRecognitionOnly === true}, mfFns: [], buildFns: [] }`;
|
|
9639
11171
|
};
|
|
9640
11172
|
const isSpread = (it) => "__spreadLocal" in it;
|
|
9641
11173
|
const isIR = (it) => "ir" in it && !("ruleFns" in it);
|
|
@@ -9643,6 +11175,7 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9643
11175
|
const serializeList = (list) => `[${list.map(serializeItem).join(", ")}]`;
|
|
9644
11176
|
const withCarriedPieces = (grammarExpr, list) => `/* @__PURE__ */ Object.defineProperty(${grammarExpr}, Symbol.for('parseman.composedPieces'), { value: ${serializeList(list)}, enumerable: false })`;
|
|
9645
11177
|
const withLeafMarker = (grammarExpr) => `/* @__PURE__ */ Object.defineProperty(${grammarExpr}, Symbol.for('parseman.leafComposed'), { value: true, enumerable: false })`;
|
|
11178
|
+
const withHostMode = (grammarExpr, mode, elided) => `/* @__PURE__ */ (m => { for (const k of Object.keys(m)) { Object.defineProperty(m[k], Symbol.for('parseman.fusedHostMode'), { value: ${JSON.stringify(mode)}, enumerable: false }); Object.defineProperty(m[k], Symbol.for('parseman.fusedHostElided'), { value: ${JSON.stringify(elided)}, enumerable: false }) } Object.defineProperty(m, Symbol.for('parseman.fusedHostMode'), { value: ${JSON.stringify(mode)}, enumerable: false }); Object.defineProperty(m, Symbol.for('parseman.fusedHostElided'), { value: ${JSON.stringify(elided)}, enumerable: false }); return m })(${grammarExpr})`;
|
|
9646
11179
|
const withCoverageDefinitions = (grammarExpr, definitions) => !grammarCoverage ? grammarExpr : `/* @__PURE__ */ Object.defineProperty(${grammarExpr}, Symbol.for('parseman.grammarCoverageDefinitions'), { value: Object.freeze(${JSON.stringify(definitions)}.map(Object.freeze)), enumerable: false })`;
|
|
9647
11180
|
const emittedCoverageDefinitions = (source) => {
|
|
9648
11181
|
const ids = /* @__PURE__ */ new Set();
|
|
@@ -9702,29 +11235,38 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9702
11235
|
importedPiecesCache.set(localName, result2);
|
|
9703
11236
|
return result2;
|
|
9704
11237
|
};
|
|
9705
|
-
const materializeCarried = (items, composing, captureTerminals = false) => {
|
|
11238
|
+
const materializeCarried = (items, composing, captureTerminals = false, hostMode) => {
|
|
9706
11239
|
const out = [];
|
|
9707
11240
|
for (const it of items) {
|
|
9708
11241
|
if (isSpread(it)) {
|
|
9709
|
-
for (const p of importedPieces(it.__spreadLocal) ?? []) out.push(materializePiece(p, composing, captureTerminals));
|
|
11242
|
+
for (const p of importedPieces(it.__spreadLocal) ?? []) out.push(materializePiece(p, composing, captureTerminals, hostMode));
|
|
9710
11243
|
} else if (isIR(it)) {
|
|
9711
|
-
out.push(materializePiece(it, composing, captureTerminals));
|
|
11244
|
+
out.push(materializePiece(it, composing, captureTerminals, hostMode));
|
|
9712
11245
|
} else {
|
|
9713
11246
|
out.push(it);
|
|
9714
11247
|
}
|
|
9715
11248
|
}
|
|
9716
11249
|
return out;
|
|
9717
11250
|
};
|
|
9718
|
-
const
|
|
9719
|
-
const
|
|
11251
|
+
const carriedRuleMapsDetailed = (items) => {
|
|
11252
|
+
const maps = [];
|
|
11253
|
+
const opaque = [];
|
|
9720
11254
|
const add = (it) => {
|
|
9721
|
-
if (isIR(it))
|
|
11255
|
+
if (isIR(it)) {
|
|
11256
|
+
maps.push(evalRuleMapIR(it.ir));
|
|
11257
|
+
return;
|
|
11258
|
+
}
|
|
11259
|
+
const o = it;
|
|
11260
|
+
opaque.push({
|
|
11261
|
+
ns: o.ns ?? "<unknown>",
|
|
11262
|
+
ruleNames: o.ruleFns instanceof Map ? [...o.ruleFns.keys()] : []
|
|
11263
|
+
});
|
|
9722
11264
|
};
|
|
9723
11265
|
for (const it of items) {
|
|
9724
11266
|
if (isSpread(it)) for (const p of importedPieces(it.__spreadLocal) ?? []) add(p);
|
|
9725
11267
|
else add(it);
|
|
9726
11268
|
}
|
|
9727
|
-
return
|
|
11269
|
+
return { maps, opaque };
|
|
9728
11270
|
};
|
|
9729
11271
|
const materializeLeafCoverage = (items, localRules, localNs, composing, captureTerminals = false) => {
|
|
9730
11272
|
const sources = [];
|
|
@@ -9762,6 +11304,7 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9762
11304
|
const ns = nsFor(label2);
|
|
9763
11305
|
const ir = serializeRuleMap(entries, scanSkip);
|
|
9764
11306
|
if (ir) return { carried: [{ ns, ir }] };
|
|
11307
|
+
warn(0, `${label2}: rule map could not be serialized to IR; carrying FULL pieces instead. The artifact is correct but larger, and a downstream compose cannot re-lower it. Re-run with PARSEMAN_IR_DEBUG=1 to print the exact combinator that blocked serialization.`);
|
|
9765
11308
|
const p = compileLinkable(entries, ns, { ...composing ? { trivia: composing } : {}, ...scanSkip ? { scanSkip } : {}, recovery });
|
|
9766
11309
|
return p ? { carried: [p] } : null;
|
|
9767
11310
|
};
|
|
@@ -9849,6 +11392,15 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9849
11392
|
return null;
|
|
9850
11393
|
}
|
|
9851
11394
|
const elements = arr.elements;
|
|
11395
|
+
const cOptions = init.arguments[1];
|
|
11396
|
+
const cHostModeValue = cOptions?.type === "ObjectExpression" ? (cOptions.properties ?? []).find(
|
|
11397
|
+
(p) => p.key?.name === "hostMode"
|
|
11398
|
+
)?.value : void 0;
|
|
11399
|
+
const cHostMode = cHostModeValue?.type === "Literal" ? cHostModeValue.value : void 0;
|
|
11400
|
+
if (cHostModeValue !== void 0 && cHostMode !== "ast" && cHostMode !== "cst") {
|
|
11401
|
+
warn(init.start, "compose({ hostMode }) must be the literal 'ast' or 'cst'");
|
|
11402
|
+
return null;
|
|
11403
|
+
}
|
|
9852
11404
|
const composing = composingTrivia(elements);
|
|
9853
11405
|
const carried = [];
|
|
9854
11406
|
for (let i = 0; i < elements.length; i++) {
|
|
@@ -9859,8 +11411,13 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9859
11411
|
}
|
|
9860
11412
|
carried.push(...r.carried);
|
|
9861
11413
|
}
|
|
9862
|
-
|
|
9863
|
-
|
|
11414
|
+
const detailed = once(() => carriedRuleMapsDetailed(carried));
|
|
11415
|
+
runFusedGatingDiagnostic(
|
|
11416
|
+
() => detailed().maps,
|
|
11417
|
+
void 0,
|
|
11418
|
+
() => detailed().opaque
|
|
11419
|
+
);
|
|
11420
|
+
const pieces = materializeCarried(carried, composing, false, cHostMode);
|
|
9864
11421
|
try {
|
|
9865
11422
|
return { replacement: emitFusedSource(pieces), carried, ...composing ? { trivia: composing } : {} };
|
|
9866
11423
|
} catch (e) {
|
|
@@ -9908,7 +11465,12 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
9908
11465
|
}
|
|
9909
11466
|
try {
|
|
9910
11467
|
const localNs = nsFor(`composeLeaf${init.start}`);
|
|
9911
|
-
|
|
11468
|
+
const detailedLeaf = once(() => carriedRuleMapsDetailed(carried));
|
|
11469
|
+
runFusedGatingDiagnostic(
|
|
11470
|
+
() => [...detailedLeaf().maps, [...localRules]],
|
|
11471
|
+
void 0,
|
|
11472
|
+
() => detailedLeaf().opaque
|
|
11473
|
+
);
|
|
9912
11474
|
const plainLocalPiece = compileLinkable([...localRules], localNs, { ...composing ? { trivia: composing } : {}, ...localScanSkip ? { scanSkip: localScanSkip } : {}, recovery });
|
|
9913
11475
|
if (!plainLocalPiece) {
|
|
9914
11476
|
warn(init.start, "composeLeaf(): local rules could not be statically compiled");
|
|
@@ -10029,6 +11591,9 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
10029
11591
|
source,
|
|
10030
11592
|
compiledRules.coverageDefinitions?.length ? compiledRules.coverageDefinitions : emittedCoverageDefinitions(source)
|
|
10031
11593
|
);
|
|
11594
|
+
if (compiledRules.replacement !== null) {
|
|
11595
|
+
replacement = withHostMode(replacement, compiledRules.hostMode, compiledRules.hostBranchElided);
|
|
11596
|
+
}
|
|
10032
11597
|
if (exportPrefix && pieces && !pieces.mfFns.length && !pieces.buildFns.length) {
|
|
10033
11598
|
const ir = serializeRuleMap([...compiledRules.ruleMap], compiledRules.scanSkip);
|
|
10034
11599
|
replacement = withCarriedPieces(replacement, [ir ? { ns, ir } : pieces]);
|
|
@@ -10071,6 +11636,7 @@ function transformMacro(code, id, moduleAliases = /* @__PURE__ */ new Set([PARSE
|
|
|
10071
11636
|
scope.set(varName, combiArray);
|
|
10072
11637
|
continue;
|
|
10073
11638
|
}
|
|
11639
|
+
if (factoryDecls.has(varName)) continue;
|
|
10074
11640
|
warn(init.start, `"${varName}" references a parseman macro import but isn't a statically-evaluable combinator`);
|
|
10075
11641
|
continue;
|
|
10076
11642
|
}
|