parseman 0.43.0 → 0.45.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/dist/analysis/diagnose.d.ts +118 -0
- package/dist/analysis/diagnose.d.ts.map +1 -0
- package/dist/analysis/gating.d.ts +9 -9
- package/dist/analysis/gating.d.ts.map +1 -1
- package/dist/analysis/grammar.d.ts.map +1 -1
- package/dist/combinators/attempt.d.ts.map +1 -1
- package/dist/combinators/choice.d.ts.map +1 -1
- package/dist/combinators/dispatch.d.ts +19 -1
- package/dist/combinators/dispatch.d.ts.map +1 -1
- package/dist/combinators/expect.d.ts.map +1 -1
- package/dist/combinators/first-set.d.ts.map +1 -1
- package/dist/combinators/grammar.d.ts +7 -0
- package/dist/combinators/grammar.d.ts.map +1 -1
- package/dist/combinators/map.d.ts +11 -0
- package/dist/combinators/map.d.ts.map +1 -1
- package/dist/combinators/node.d.ts +19 -0
- package/dist/combinators/node.d.ts.map +1 -1
- package/dist/combinators/token.d.ts +3 -2
- package/dist/combinators/token.d.ts.map +1 -1
- package/dist/combinators/trivia-skip.d.ts +1 -0
- package/dist/combinators/trivia-skip.d.ts.map +1 -1
- package/dist/compiler/build-arity.d.ts +28 -0
- package/dist/compiler/build-arity.d.ts.map +1 -1
- package/dist/compiler/codegen.d.ts +80 -60
- package/dist/compiler/codegen.d.ts.map +1 -1
- package/dist/compiler/degradation.d.ts +123 -0
- package/dist/compiler/degradation.d.ts.map +1 -0
- package/dist/compiler/fields.d.ts.map +1 -1
- package/dist/compiler/grammar-coverage-ids.d.ts.map +1 -1
- package/dist/compiler/inline-build.d.ts.map +1 -1
- package/dist/compiler/ir-serialize.d.ts.map +1 -1
- package/dist/compiler/linker.d.ts +1 -1
- package/dist/compiler/linker.d.ts.map +1 -1
- package/dist/compiler/scannable-run.d.ts +1 -1
- package/dist/compiler/scannable-run.d.ts.map +1 -1
- package/dist/compiler/trivia-fast-path.d.ts +4 -3
- package/dist/compiler/trivia-fast-path.d.ts.map +1 -1
- package/dist/coverage.d.ts +13 -0
- package/dist/coverage.d.ts.map +1 -1
- package/dist/cst/reflection.d.ts.map +1 -1
- package/dist/cst/trivia-entries.d.ts +15 -9
- package/dist/cst/trivia-entries.d.ts.map +1 -1
- package/dist/cst/trivia-kinds.d.ts +15 -11
- package/dist/cst/trivia-kinds.d.ts.map +1 -1
- package/dist/functional/run.d.ts +22 -16
- package/dist/functional/run.d.ts.map +1 -1
- package/dist/index.cjs +2131 -1594
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +6 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2131 -1594
- package/dist/index.js.map +4 -4
- package/dist/language-service/index.cjs +201 -132
- package/dist/language-service/index.cjs.map +4 -4
- package/dist/language-service/index.js +201 -132
- package/dist/language-service/index.js.map +4 -4
- package/dist/oracle/digest.d.ts +132 -6
- package/dist/oracle/digest.d.ts.map +1 -1
- package/dist/oracle/index.cjs +136 -305
- package/dist/oracle/index.cjs.map +4 -4
- package/dist/oracle/index.d.ts +43 -31
- package/dist/oracle/index.d.ts.map +1 -1
- package/dist/oracle/index.js +136 -305
- package/dist/oracle/index.js.map +4 -4
- package/dist/plugin/evaluator.d.ts +3 -0
- package/dist/plugin/evaluator.d.ts.map +1 -1
- package/dist/plugin/index.cjs +2333 -1721
- package/dist/plugin/index.cjs.map +4 -4
- package/dist/plugin/index.d.ts +18 -0
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +2333 -1721
- package/dist/plugin/index.js.map +4 -4
- package/dist/plugin/reducer-resolver.d.ts +41 -0
- package/dist/plugin/reducer-resolver.d.ts.map +1 -0
- package/dist/run/index.cjs +185 -132
- package/dist/run/index.cjs.map +3 -3
- package/dist/run/index.d.ts +1 -1
- package/dist/run/index.d.ts.map +1 -1
- package/dist/run/index.js +185 -132
- package/dist/run/index.js.map +3 -3
- package/dist/spec/index.cjs +1637 -1322
- package/dist/spec/index.cjs.map +4 -4
- package/dist/spec/index.js +1637 -1322
- package/dist/spec/index.js.map +4 -4
- package/dist/spec/model.d.ts.map +1 -1
- package/dist/types.d.ts +31 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +7 -3
- package/dist/combinators/guard.d.ts +0 -8
- package/dist/combinators/guard.d.ts.map +0 -1
- package/dist/cst/offset-model.d.ts +0 -119
- package/dist/cst/offset-model.d.ts.map +0 -1
- package/dist/oracle/corpus.d.ts +0 -32
- package/dist/oracle/corpus.d.ts.map +0 -1
- package/dist/oracle/identity.d.ts +0 -117
- package/dist/oracle/identity.d.ts.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/oracle/index.ts", "../../src/oracle/digest.ts"
|
|
4
|
-
"sourcesContent": ["/**\n * `parseman/oracle` \u2014 an AST-identity oracle for grammar refactors.\n *\n * Turns \"is this rule collapse safe?\" from a judgement call into an accept/reject:\n * digest a corpus through your parse entry points before and after the change,\n * and compare.\n *\n * import { loadCorpus, digestCorpus, compareReports, formatComparison } from 'parseman/oracle'\n *\n * const { entries } = loadCorpus({\n * base: repoRoot,\n * roots: ['test/fixtures', 'corpus'],\n * extensions: ['.less', '.css'],\n * })\n * const report = digestCorpus(\n * [\n * { name: 'ast', parse: source => parse(source) },\n * { name: 'cst', parse: source => parseCst(source) },\n * ],\n * entries,\n * )\n * // \u2026edit the grammar, REBUILD, run again\u2026\n * console.log(formatComparison(compareReports(before, after)))\n *\n * Node-only: it hashes with `node:crypto` and reads files with `node:fs`. It is a\n * development gate, so it is a separate entry point and nothing in it reaches the\n * browser-capable `parseman` bundle.\n *\n * See `docs/guide/identity-oracle.md` for the operating discipline \u2014 in\n * particular why you must digest the BUILT artifact and rebuild between edits.\n */\nexport { digestCorpus, compareReports, formatComparison, HARNESS_DIGEST } from './identity.ts'\nexport type {\n Surface,\n CorpusEntry,\n SurfaceReport,\n IdentityReport,\n DigestOptions,\n SurfaceComparison,\n IdentityComparison,\n} from './identity.ts'\nexport { loadCorpus } from './corpus.ts'\nexport type { LoadCorpusOptions, LoadedCorpus } from './corpus.ts'\nexport { canonicalize, DIGEST_FORMAT } from './digest.ts'\n", "/**\n * The canonical projection and the hashing the identity oracle is built on.\n *\n * Everything here exists to make ONE claim trustworthy: \"this grammar change did\n * not move the tree.\" That claim is only worth as much as the projection behind\n * it, so the rules below are stated rather than left to `JSON.stringify`, which\n * silently collapses several distinctions a grammar refactor can actually move:\n *\n * | value | `JSON.stringify` | here |\n * |------------------------|------------------|-----------------|\n * | `{ a: undefined }` | `{}` | distinct from `{}` |\n * | `NaN` / `\u00B1Infinity` | `null` | each distinct |\n * | `-0` | `0` | distinct from `0` |\n * | `new Map([[1, 2]])` | `{}` | entries, in order |\n * | `new Set([1])` | `{}` | members, in order |\n * | `new Foo({ x: 1 })` | `{\"x\":1}` | tagged `Foo` |\n *\n * A refactor that starts emitting `undefined` where it used to omit a key, or\n * that swaps one node class for another with the same fields, is a tree move.\n * An oracle that cannot see it is worse than no oracle, because it certifies.\n *\n * ## Key order does not matter; array and Map/Set order does\n *\n * Object keys are sorted, so property INSERTION order \u2014 which a refactor churns\n * constantly and which no consumer observes \u2014 never moves a digest. Array\n * elements and Map/Set entries keep their order, because those orders are the\n * output.\n *\n * ## Sharing is not a cycle\n *\n * A node reachable by two paths is written out twice, in full. Only a genuine\n * back-edge into the CURRENT path is abbreviated, and it records the DISTANCE to\n * the ancestor it points at, so a self-reference and a reference to the root are\n * different digests. (Marking every repeat as a cycle \u2014 the easy version \u2014 makes\n * the digest depend on traversal order for any DAG, which parse trees with\n * interned or shared subtrees routinely are.)\n *\n * ## Own ENUMERABLE keys only\n *\n * `Object.keys`, deliberately, not `getOwnPropertyNames`. The oracle answers \"did\n * the OUTPUT move\" and non-enumerable properties are engine bookkeeping a\n * consumer never sees \u2014 parseman's own carried CST pieces among them. Hashing\n * them would make a consumer's grammar digest move when parseman's internals\n * change, which is precisely the wrong sensitivity for a grammar-refactor gate.\n *\n * ## Tokens, not concatenation\n *\n * Every value writes one or more self-contained tokens joined by NUL. Writing\n * `#1` then `#2` into a single buffer would be indistinguishable from `#12`; a\n * projection with an ambiguity in it is a projection that can be made to lie.\n * Strings are JSON-escaped, so no token can contain a raw NUL.\n */\nimport { createHash } from 'node:crypto'\n\n/**\n * Bump when the token grammar below changes in a way that alters output for any\n * input. It is a coarse, human-readable companion to the behavioural harness\n * digest \u2014 the harness digest is what actually enforces this, but a reader\n * comparing two reports should not have to diff hex to see that the format moved.\n */\nexport const DIGEST_FORMAT = 1\n\nconst str = (s: string): string => JSON.stringify(s)\n\nconst tagOf = (v: object): string => {\n const ctor = (v as { constructor?: unknown }).constructor\n return typeof ctor === 'function' && typeof ctor.name === 'string' ? ctor.name : ''\n}\n\nfunction writeScalar(v: unknown, out: string[]): void {\n switch (typeof v) {\n case 'undefined':\n out.push('u')\n return\n case 'boolean':\n out.push(v ? 'T' : 'F')\n return\n case 'bigint':\n out.push(`n${v}`)\n return\n case 'string':\n out.push(`s${str(v)}`)\n return\n // TODO(oracle-callable-identity): a callable is projected by NAME and a symbol by\n // DESCRIPTION, so two distinct same-named functions \u2014 or two same-description\n // symbols \u2014 digest identically, and a change between them reads as \"identical\".\n // This is a real hole in a tool whose whole claim is paranoia, and it is left open\n // deliberately: closing it means either hashing `Function.prototype.toString()`,\n // which flips the digest on a comment edit inside a builder, or REFUSING to digest\n // any value carrying a callable, which rejects legitimate ASTs that park a callback\n // on a node. Both are worse than the hole for some caller, and picking between them\n // is a product decision, not a bug fix. Documented under \"What it is not\" in\n // `docs/guide/identity-oracle.md` so no reader infers a guarantee that is not here.\n case 'symbol':\n out.push(`y${str(v.description ?? '')}`)\n return\n case 'function':\n out.push(`f${str(v.name)}`)\n return\n case 'number':\n if (Number.isNaN(v)) out.push('#nan')\n else if (v === Number.POSITIVE_INFINITY) out.push('#inf')\n else if (v === Number.NEGATIVE_INFINITY) out.push('#-inf')\n else if (Object.is(v, -0)) out.push('#-0')\n // Number\u2192string is exact and round-trips in JS, so this loses nothing.\n else out.push(`#${v}`)\n return\n default:\n // `typeof null`. Distinct from `undefined`, which is `'u'`.\n out.push('z')\n }\n}\n\nfunction write(v: unknown, path: Map<object, number>, depth: number, out: string[]): void {\n // Everything that is not a live object reference is written here, so the rest\n // of the function has `v: object` and needs no assertion to index or key on it.\n if (typeof v !== 'object' || v === null) {\n writeScalar(v, out)\n return\n }\n\n const seenAt = path.get(v)\n if (seenAt !== undefined) {\n // Distance to the ancestor, not its identity: a self-reference and a\n // reference to the root must not hash the same.\n out.push(`^${depth - seenAt}`)\n return\n }\n path.set(v, depth)\n\n if (Array.isArray(v)) {\n out.push('[')\n // `for..of` rather than indexing so a sparse hole reads as the `undefined`\n // it is, consistently with a present `undefined` \u2014 the distinction between\n // a hole and an explicit undefined is not observable output.\n for (const item of v) write(item, path, depth + 1, out)\n out.push(']')\n } else if (v instanceof Map) {\n out.push('M')\n for (const [k, val] of v) {\n write(k, path, depth + 1, out)\n write(val, path, depth + 1, out)\n }\n out.push('}')\n } else if (v instanceof Set) {\n out.push('S')\n for (const item of v) write(item, path, depth + 1, out)\n out.push('}')\n } else if (v instanceof Date) {\n out.push(`D${v.getTime()}`)\n } else if (v instanceof RegExp) {\n out.push(`R${str(v.source)}${str(v.flags)}`)\n } else {\n const tag = tagOf(v)\n out.push(`{${str(tag === 'Object' ? '' : tag)}`)\n for (const k of Object.keys(v).sort()) {\n out.push(`k${str(k)}`)\n write((v as Record<string, unknown>)[k], path, depth + 1, out)\n }\n out.push('}')\n }\n\n path.delete(v)\n}\n\n/**\n * The canonical token string for a value. Exported because a moved digest is\n * only actionable if you can see WHAT moved: diff two canonical strings and the\n * answer is a line, not a hex mismatch.\n */\nexport function canonicalize(value: unknown): string {\n const out: string[] = []\n write(value, new Map(), 0, out)\n return out.join('\\u0000')\n}\n\n/** Full 64-hex sha256 of a string. */\nexport function hash(payload: string): string {\n return createHash('sha256').update(payload).digest('hex')\n}\n\n/**\n * Per-entry fingerprint width. 64 bits over any realistic corpus is far below\n * the collision floor, and a report a human has to read stays readable.\n */\nexport const FINGERPRINT_HEX = 16\n", "/**\n * The AST-identity oracle: an accept/reject gate for grammar refactors.\n *\n * ## What it is for\n *\n * \"Collapse these two near-duplicate rules\" is a judgement call until something\n * can answer \"did the tree move?\" mechanically. This answers it: run a corpus\n * through your parse entry points before and after the change, digest the\n * results, compare. Identical digests mean the refactor is output-neutral and can\n * land on its own merits. Different digests mean it is not a refactor \u2014 it is a\n * semantics change, and needs the decision that goes with one.\n *\n * It is a differential, not a correctness check. It says the output did not move;\n * it says nothing about whether the output was right to begin with.\n *\n * ## Failures are part of the contract\n *\n * A parse that throws, and a parse that returns a failure result, are both\n * hashed. Error behaviour IS behaviour: a change that turns a hard rejection into\n * a silent accept has moved the grammar's contract as surely as one that renames\n * a node. A corpus with a healthy number of rejections in it is a FEATURE \u2014 feed\n * it your invalid inputs on purpose. What matters is that the throw counts and\n * the digests do not move.\n *\n * ## Measure what SHIPS\n *\n * Digest the artifact your consumers get. For a macro-compiled grammar that means\n * the BUILT output, rebuilt between edits \u2014 a macro-fallback build runs the\n * interpreter, and the interpreter and the compiled artifact are not guaranteed\n * to agree on every tree. A digest taken on a fallback build certifies something\n * nobody runs. This module cannot check that for you; your build can, and should.\n *\n * ## The harness cannot drift silently\n *\n * A digest that moves because the HARNESS changed, rather than the grammar, is\n * worse than no oracle: it either invents a regression or, far worse, hides one.\n * Three things prevent it:\n *\n * 1. Every report carries {@link HARNESS_DIGEST} \u2014 a behavioural fingerprint of\n * this harness, produced by running it over a frozen canary corpus that\n * exercises every payload-shaping decision it makes.\n * 2. {@link compareReports} REFUSES to compare two reports whose harness\n * digests differ. It returns `incomparable`, never `identical` and never\n * `moved`. A drifted harness produces an error, not a verdict.\n * 3. Parseman's own suite pins `HARNESS_DIGEST` to a literal constant, so\n * changing the projection requires editing that constant in a reviewed diff.\n * There is no edit to this file that changes a digest and stays quiet.\n *\n * ## Nondeterminism is caught, not hashed\n *\n * A grammar whose output depends on `Map` iteration over object identity, a\n * timestamp, or a counter produces a digest that moves every run \u2014 which reads\n * exactly like a regression. {@link digestCorpus} re-parses a sample of the\n * corpus and fails loudly if any entry does not reproduce. An oracle that cannot\n * be trusted should say so rather than emit a number.\n */\nimport { canonicalize, hash, DIGEST_FORMAT, FINGERPRINT_HEX } from './digest.ts'\n\n/**\n * One parse entry point under test.\n *\n * Declare EVERY shipped surface, not just the one you are editing. A refactor\n * that touches one grammar should move neither, and the untouched surface is a\n * free control: if it moves too, the harness or the corpus moved, not the rule\n * you edited.\n */\nexport type Surface = {\n /** Stable identifier. Renaming a surface changes its aggregate, deliberately. */\n name: string\n /** Called once per corpus entry. May return anything, and may throw. */\n parse: (source: string, id: string) => unknown\n}\n\nexport type CorpusEntry = {\n /**\n * Stable, RELATIVE identifier \u2014 a path relative to a base, not an absolute\n * one. An absolute path makes the digest depend on the checkout directory,\n * which means two machines can never agree.\n */\n id: string\n source: string\n}\n\nexport type SurfaceReport = {\n name: string\n /** sha256 over every entry's fingerprint, in id order. The gate. */\n aggregate: string\n /** How many entries threw. Expected to be non-zero; expected not to MOVE. */\n threw: number\n}\n\nexport type IdentityReport = {\n format: number\n /** Behavioural fingerprint of the harness that produced this report. */\n harness: string\n entries: number\n surfaces: SurfaceReport[]\n /** entry id \u2192 surface name \u2192 16-hex fingerprint. Diff this to localise a move. */\n perEntry: Record<string, Record<string, string>>\n}\n\nexport type DigestOptions = {\n /**\n * Project a thrown value into something hashable. The default keeps an Error's\n * `name` and `message`.\n *\n * Override when your messages embed anything machine-specific \u2014 an absolute\n * path, a wall-clock time, a memory address. Those make a digest that cannot\n * be compared across machines, and the symptom is a gate that fails for\n * everyone except its author.\n */\n projectError?: (thrown: unknown, id: string, surface: string) => unknown\n /**\n * How many entries to re-parse to prove the grammar is deterministic. Sampled\n * evenly across the corpus, not from the front. `0` disables the check; do that\n * only if you have another reason to trust it.\n */\n determinismSample?: number\n}\n\nconst defaultProjectError = (thrown: unknown): unknown =>\n thrown instanceof Error ? { name: thrown.name, message: thrown.message } : { thrown }\n\n/**\n * The `OK:` / `ERR:` discriminator.\n *\n * Not decoration, and not droppable: it keeps a successful parse and a thrown\n * error in disjoint hash spaces. Without it a surface that returns exactly the\n * projected error shape hashes identically to one that threw it, and the single\n * most important thing this oracle detects \u2014 an error becoming an accept \u2014 is\n * the thing it stops detecting.\n */\nfunction payload(surface: Surface, entry: CorpusEntry, options: DigestOptions): { text: string; threw: boolean } {\n try {\n return { text: `OK:${canonicalize(surface.parse(entry.source, entry.id))}`, threw: false }\n } catch (thrown) {\n const project = options.projectError ?? defaultProjectError\n return { text: `ERR:${canonicalize(project(thrown, entry.id, surface.name))}`, threw: true }\n }\n}\n\nconst fingerprint = (text: string): string => hash(text).slice(0, FINGERPRINT_HEX)\n\n/**\n * Run every surface over every entry and produce the report.\n *\n * The corpus is sorted by id, so the aggregate does not depend on the order the\n * caller happened to list files in. The aggregate covers the ids as well as the\n * fingerprints, so a corpus that quietly SHRANK \u2014 a root that stopped resolving,\n * a glob that stopped matching \u2014 moves the aggregate instead of producing a\n * smaller, greener gate. {@link compareReports} then tells you it was the corpus.\n */\nexport function digestCorpus(\n surfaces: readonly Surface[],\n corpus: readonly CorpusEntry[],\n options: DigestOptions = {},\n): IdentityReport {\n if (surfaces.length === 0) throw new Error('digestCorpus: no surfaces \u2014 there is nothing to compare.')\n const names = new Set<string>()\n for (const s of surfaces) {\n if (names.has(s.name)) throw new Error(`digestCorpus: duplicate surface name ${JSON.stringify(s.name)}.`)\n names.add(s.name)\n }\n\n const entries = [...corpus].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n for (let n = 1; n < entries.length; n++) {\n if (entries[n]!.id === entries[n - 1]!.id) {\n throw new Error(`digestCorpus: duplicate corpus id ${JSON.stringify(entries[n]!.id)}.`)\n }\n }\n\n const perEntry: Record<string, Record<string, string>> = {}\n const threw: Record<string, number> = {}\n const texts: Map<string, string>[] = []\n for (const s of surfaces) threw[s.name] = 0\n\n for (const entry of entries) {\n const row: Record<string, string> = {}\n const rowTexts = new Map<string, string>()\n for (const s of surfaces) {\n const result = payload(s, entry, options)\n if (result.threw) threw[s.name]!++\n row[s.name] = fingerprint(result.text)\n rowTexts.set(s.name, result.text)\n }\n perEntry[entry.id] = row\n texts.push(rowTexts)\n }\n\n verifyDeterminism(surfaces, entries, texts, options)\n\n return {\n format: DIGEST_FORMAT,\n harness: HARNESS_DIGEST,\n entries: entries.length,\n surfaces: surfaces.map(s => ({\n name: s.name,\n // The surface NAME is inside its own aggregate: two surfaces that happen\n // to agree on every entry must still have distinct aggregates, or a\n // report that swapped them would compare equal.\n aggregate: hash(\n [`surface:${s.name}`, ...entries.map(e => `${e.id}:${perEntry[e.id]![s.name]}`)].join('\\n'),\n ),\n threw: threw[s.name]!,\n })),\n perEntry,\n }\n}\n\nfunction verifyDeterminism(\n surfaces: readonly Surface[],\n entries: readonly CorpusEntry[],\n texts: ReadonlyArray<Map<string, string>>,\n options: DigestOptions,\n): void {\n const want = options.determinismSample ?? 32\n if (want <= 0 || entries.length === 0) return\n const stride = Math.max(1, Math.floor(entries.length / Math.min(want, entries.length)))\n for (let n = 0; n < entries.length; n += stride) {\n const entry = entries[n]!\n for (const s of surfaces) {\n if (payload(s, entry, options).text === texts[n]!.get(s.name)) continue\n throw new Error(\n `digestCorpus: surface ${JSON.stringify(s.name)} is NOT DETERMINISTIC on ${JSON.stringify(entry.id)} \u2014 `\n + 'two parses of the same source produced different output. Every digest from this grammar would move on '\n + 'its own, so a comparison against it cannot mean anything. Usual causes: a timestamp or counter in the '\n + 'output, iteration over a keyed-by-object Map, or a node carrying a reference to mutable shared state.',\n )\n }\n }\n}\n\nexport type SurfaceComparison = {\n name: string\n before: string | null\n after: string | null\n equal: boolean\n /** Entry ids whose fingerprint moved on this surface. Empty when equal. */\n moved: string[]\n beforeThrew: number | null\n afterThrew: number | null\n}\n\nexport type IdentityComparison = {\n /**\n * `identical` \u2014 output-neutral, the refactor is accepted.\n * `moved` \u2014 the output changed; this is not a refactor.\n * `incomparable` \u2014 the two reports cannot be compared at all. Never a pass.\n */\n verdict: 'identical' | 'moved' | 'incomparable'\n reason: string | null\n addedEntries: string[]\n removedEntries: string[]\n surfaces: SurfaceComparison[]\n}\n\n/**\n * Compare two reports.\n *\n * Refuses \u2014 `incomparable`, with a reason \u2014 when the two were not produced by the\n * same harness over comparable inputs. That is the whole point: the failure mode\n * this guards against is a harness change that quietly re-baselines every recorded\n * digest, and the only defence is that mismatched provenance can never come out\n * as a verdict about the grammar.\n *\n * A corpus that gained or lost entries is reported but is NOT by itself\n * incomparable \u2014 the surviving entries still carry a real signal, and telling you\n * \"1 entry disappeared, the other 4,300 are unchanged\" is more useful than\n * refusing. The verdict still reflects the difference.\n */\nexport function compareReports(before: IdentityReport, after: IdentityReport): IdentityComparison {\n if (before.harness !== after.harness) {\n return incomparable(\n `harness drift: reports were produced by DIFFERENT versions of the identity harness `\n + `(${before.harness.slice(0, 12)}\u2026 vs ${after.harness.slice(0, 12)}\u2026). Their digests are not comparable, `\n + `and treating them as such would either invent a regression or hide one. Re-run BOTH sides on one harness.`,\n )\n }\n if (before.format !== after.format) {\n return incomparable(`digest format ${before.format} vs ${after.format} \u2014 re-run both sides on one version.`)\n }\n\n const beforeIds = new Set(Object.keys(before.perEntry))\n const afterIds = new Set(Object.keys(after.perEntry))\n const addedEntries = [...afterIds].filter(id => !beforeIds.has(id)).sort()\n const removedEntries = [...beforeIds].filter(id => !afterIds.has(id)).sort()\n const shared = [...beforeIds].filter(id => afterIds.has(id)).sort()\n\n const byName = new Map<string, { before?: SurfaceReport; after?: SurfaceReport }>()\n for (const s of before.surfaces) byName.set(s.name, { ...byName.get(s.name), before: s })\n for (const s of after.surfaces) byName.set(s.name, { ...byName.get(s.name), after: s })\n\n const surfaces: SurfaceComparison[] = [...byName.entries()]\n .sort(([a], [b]) => (a < b ? -1 : 1))\n .map(([name, pair]) => {\n const moved = pair.before && pair.after\n ? shared.filter(id => before.perEntry[id]![name] !== after.perEntry[id]![name])\n : []\n return {\n name,\n before: pair.before?.aggregate ?? null,\n after: pair.after?.aggregate ?? null,\n equal: pair.before !== undefined && pair.after !== undefined && pair.before.aggregate === pair.after.aggregate,\n moved,\n beforeThrew: pair.before?.threw ?? null,\n afterThrew: pair.after?.threw ?? null,\n }\n })\n\n const identical =\n addedEntries.length === 0 && removedEntries.length === 0 && surfaces.every(s => s.equal)\n return { verdict: identical ? 'identical' : 'moved', reason: null, addedEntries, removedEntries, surfaces }\n}\n\nfunction incomparable(reason: string): IdentityComparison {\n return { verdict: 'incomparable', reason, addedEntries: [], removedEntries: [], surfaces: [] }\n}\n\n/** Human-readable rendering of a comparison, for a CLI or a CI log. */\nexport function formatComparison(c: IdentityComparison, options: { maxMoved?: number } = {}): string {\n if (c.verdict === 'incomparable') return `INCOMPARABLE \u2014 ${c.reason ?? 'unknown reason'}`\n const max = options.maxMoved ?? 10\n const lines: string[] = []\n for (const s of c.surfaces) {\n if (s.before === null) lines.push(` + surface ${s.name} (added)`)\n else if (s.after === null) lines.push(` - surface ${s.name} (removed)`)\n else if (s.equal) lines.push(` = ${s.name} ${s.before.slice(0, 16)}\u2026 threw=${s.afterThrew}`)\n else {\n lines.push(\n ` ! ${s.name} ${s.before.slice(0, 16)}\u2026 -> ${s.after.slice(0, 16)}\u2026 `\n + `threw ${s.beforeThrew} -> ${s.afterThrew} (${s.moved.length} entries moved)`,\n )\n for (const id of s.moved.slice(0, max)) lines.push(` ${id}`)\n if (s.moved.length > max) lines.push(` \u2026 and ${s.moved.length - max} more`)\n }\n }\n if (c.addedEntries.length > 0) lines.push(` corpus GAINED ${c.addedEntries.length} entries`)\n if (c.removedEntries.length > 0) {\n lines.push(\n ` corpus LOST ${c.removedEntries.length} entries \u2014 a differential over a SMALLER corpus is a weaker gate, `\n + `not a passing one`,\n )\n }\n return [c.verdict === 'identical' ? 'IDENTICAL \u2014 output-neutral' : 'MOVED \u2014 this is not a refactor', ...lines]\n .join('\\n')\n}\n\n/**\n * The frozen canary.\n *\n * One entry per decision {@link canonicalize} and {@link payload} make. Any edit\n * that changes what this harness produces for ANY input changes what it produces\n * for one of these, and therefore changes {@link HARNESS_DIGEST}.\n *\n * It deliberately builds its values by hand rather than by parsing anything: the\n * harness fingerprint must move when the HARNESS moves and at no other time. If\n * it ran a real grammar, every combinator change in this repo would re-baseline\n * it, and a fingerprint that moves for unrelated reasons is one people learn to\n * update without reading.\n */\nfunction canaryReport(): IdentityReport {\n class Tagged {\n x: number\n constructor(x: number) {\n this.x = x\n }\n }\n const shared = { shared: true }\n const cyclic: Record<string, unknown> = { name: 'root' }\n cyclic.self = cyclic\n cyclic.child = { up: cyclic }\n\n const values: Record<string, unknown> = {\n 'a/scalars': [0, -0, 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, 10n, true, false, null],\n 'b/absent': [{ a: undefined }, {}, { a: null }, [undefined], []],\n 'c/key-order': [{ a: 1, b: 2 }, { b: 2, a: 1 }],\n 'd/collections': [new Map([['k', 1], ['j', 2]]), new Set([1, 2]), new Date(0), /ab+c/giu],\n 'e/tagged': [new Tagged(1), { x: 1 }],\n 'f/sharing': { left: shared, right: shared },\n 'g/cycle': cyclic,\n 'h/text': ['', 'a\\u0000b', 'a b', '\"quoted\"', '\\\\'],\n 'i/callable': [function named() {}, Symbol('sym')],\n }\n\n const surfaces: Surface[] = [\n { name: 'value', parse: (_source, id) => values[id] },\n {\n name: 'thrower',\n parse: (_source, id) => {\n if (id === 'a/scalars') throw new TypeError('canary')\n if (id === 'b/absent') throw 'a bare string' // eslint-disable-line no-throw-literal\n return { id }\n },\n },\n ]\n\n const corpus: CorpusEntry[] = Object.keys(values).map(id => ({ id, source: id }))\n // Built inline rather than through digestCorpus() so the harness digest does\n // not have to exist before it is computed.\n const perEntry: Record<string, Record<string, string>> = {}\n const threw: Record<string, number> = { value: 0, thrower: 0 }\n for (const entry of [...corpus].sort((a, b) => (a.id < b.id ? -1 : 1))) {\n const row: Record<string, string> = {}\n for (const s of surfaces) {\n const result = payload(s, entry, {})\n if (result.threw) threw[s.name]!++\n row[s.name] = fingerprint(result.text)\n }\n perEntry[entry.id] = row\n }\n const ids = Object.keys(perEntry).sort()\n return {\n format: DIGEST_FORMAT,\n harness: '',\n entries: ids.length,\n surfaces: surfaces.map(s => ({\n name: s.name,\n aggregate: hash([`surface:${s.name}`, ...ids.map(id => `${id}:${perEntry[id]![s.name]}`)].join('\\n')),\n threw: threw[s.name]!,\n })),\n perEntry,\n }\n}\n\n/**\n * Behavioural fingerprint of this harness, embedded in every report it produces.\n *\n * Parseman's suite pins this to a literal. If you change the projection, that\n * test fails and the constant has to be updated in the same diff \u2014 which is the\n * point. There is no quiet edit here.\n */\nexport const HARNESS_DIGEST: string = (() => {\n const canary = canaryReport()\n return hash(\n [`format:${DIGEST_FORMAT}`, ...canary.surfaces.map(s => `${s.name}:${s.aggregate}:${s.threw}`)].join('\\n'),\n )\n})()\n", "/**\n * Loading a file corpus for the identity oracle.\n *\n * Small, and here rather than left to each consumer, because the two ways to get\n * this wrong both produce a gate that looks fine:\n *\n * - **Absolute ids.** An id derived from an absolute path bakes the checkout\n * directory into every digest, so two machines \u2014 or one machine and its CI \u2014\n * can never agree, and the first cross-machine comparison reads as a total\n * regression. Ids here are always relative to an explicit `base`.\n * - **A root that silently is not there.** A corpus root behind an optional\n * dependency, or a path that moved, yields a SMALLER corpus and therefore a\n * different-but-plausible aggregate. Missing roots throw by default; opt out\n * and you get them listed back so the report can record what was skipped.\n *\n * Symlinks are followed (a workspace corpus usually lives behind one), with\n * realpath cycle detection, and the listing is sorted, so the result does not\n * depend on directory order.\n */\nimport { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'\nimport { join, relative, resolve, sep } from 'node:path'\nimport type { CorpusEntry } from './identity.ts'\n\nexport type LoadCorpusOptions = {\n /** Ids are relative to this directory. Required \u2014 see the note above. */\n base: string\n /** Directories to walk, relative to `base` (or absolute). */\n roots: readonly string[]\n /** File extensions to include, with the dot: `['.less', '.css']`. */\n extensions: readonly string[]\n /**\n * Skip files larger than this. A handful of enormous generated fixtures can\n * dominate the runtime of a gate meant to be run on every edit.\n */\n maxBytes?: number\n /**\n * Directories never descended into. An entry with no `/` matches a directory\n * NAME anywhere; an entry containing `/` matches a path suffix, in POSIX form,\n * relative to the root being walked \u2014 so `node_modules/.cache` skips the cache\n * without skipping the package tree around it.\n */\n ignoreDirs?: readonly string[]\n /** Tolerate a root that does not exist, reporting it in `missingRoots`. */\n allowMissingRoots?: boolean\n}\n\nexport type LoadedCorpus = {\n entries: CorpusEntry[]\n /** Roots that did not resolve. Non-empty only with `allowMissingRoots`. */\n missingRoots: string[]\n /** Files skipped for exceeding `maxBytes`, by id. */\n skippedLarge: string[]\n}\n\nconst DEFAULT_IGNORE = ['.git', 'node_modules/.cache']\n\nexport function loadCorpus(options: LoadCorpusOptions): LoadedCorpus {\n const base = resolve(options.base)\n const ignoreDirs = options.ignoreDirs ?? DEFAULT_IGNORE\n // A NAME pattern matches any directory so called; a PATH pattern (one containing\n // a separator) matches a suffix of the path relative to the root. Splitting them\n // here rather than testing `Set.has(item.name)` is the whole fix for a default\n // that read `node_modules/.cache` and matched nothing: a basename is never equal\n // to a path, so the declared exclusion silently admitted every cache file it\n // named \u2014 and a digest that includes a local build cache is exactly the\n // filesystem-dependent reading this module exists to prevent.\n const ignoreNames = new Set(ignoreDirs.filter(d => !d.includes('/')))\n const ignorePaths = ignoreDirs\n .filter(d => d.includes('/'))\n .map(d => d.replace(/^\\.?\\/+/, '').replace(/\\/+$/, ''))\n const maxBytes = options.maxBytes ?? Number.POSITIVE_INFINITY\n const exts = new Set(options.extensions.map(e => e.toLowerCase()))\n\n const missingRoots: string[] = []\n const skippedLarge: string[] = []\n // Keyed by REALPATH, so one physical file reached through two aliased roots is\n // one entry. The value is the id we keep; see the tie-break at the insert site.\n const files = new Map<string, string>()\n\n const isIgnored = (name: string, relFromRoot: string): boolean => {\n if (ignoreNames.has(name)) return true\n return ignorePaths.some(p => relFromRoot === p || relFromRoot.endsWith(`/${p}`))\n }\n\n const walk = (dir: string, root: string, visited: Set<string>): void => {\n let real: string\n try {\n real = realpathSync(dir)\n } catch {\n return\n }\n // Cycle detection only, and scoped to THIS root's traversal. A set shared across\n // roots made the second of two aliased roots return here immediately, so it\n // contributed nothing and swapping the root order changed every id it owned.\n if (visited.has(real)) return\n visited.add(real)\n for (const item of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {\n const full = join(dir, item.name)\n if (isIgnored(item.name, relative(root, full).split(sep).join('/'))) continue\n // A symlink reports neither isDirectory nor isFile, so stat through it.\n let isDir = item.isDirectory()\n let isFile = item.isFile()\n let size = 0\n if (item.isSymbolicLink() || (!isDir && !isFile)) {\n try {\n const st = statSync(full)\n isDir = st.isDirectory()\n isFile = st.isFile()\n size = st.size\n } catch {\n continue\n }\n }\n if (isDir) {\n walk(full, root, visited)\n continue\n }\n if (!isFile) continue\n const dot = item.name.lastIndexOf('.')\n if (dot < 0 || !exts.has(item.name.slice(dot).toLowerCase())) continue\n if (size === 0) {\n try {\n size = statSync(full).size\n } catch {\n continue\n }\n }\n if (size > maxBytes) {\n skippedLarge.push(idOf(base, full))\n continue\n }\n // One physical file can be reached through several aliased roots. Keep the\n // SMALLEST id rather than the first one seen, so the corpus is a function of\n // the files and the base alone \u2014 not of the order `roots` happens to be in.\n let realFile: string\n try {\n realFile = realpathSync(full)\n } catch {\n continue\n }\n const id = idOf(base, full)\n const existing = files.get(realFile)\n if (existing === undefined || id < existing) files.set(realFile, id)\n }\n }\n\n for (const root of options.roots) {\n const full = resolve(base, root)\n try {\n if (!statSync(full).isDirectory()) throw new Error('not a directory')\n } catch {\n if (!options.allowMissingRoots) {\n throw new Error(\n `loadCorpus: root ${JSON.stringify(root)} does not resolve to a directory (${full}). A corpus that `\n + 'quietly shrank produces a different aggregate that looks like a grammar change. Fix the root, or pass '\n + 'allowMissingRoots and record `missingRoots` alongside the digest.',\n )\n }\n missingRoots.push(root)\n continue\n }\n walk(full, full, new Set())\n }\n\n const entries = [...files.values()]\n .sort()\n .map(id => ({ id, source: readFileSync(resolve(base, id), 'utf8') }))\n return { entries, missingRoots, skippedLarge: skippedLarge.sort() }\n}\n\n/** Always POSIX-separated, so a Windows run and a POSIX run agree. */\nfunction idOf(base: string, full: string): string {\n return relative(base, full).split(sep).join('/')\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoDA,yBAA2B;AAQpB,IAAM,gBAAgB;AAE7B,IAAM,MAAM,CAAC,MAAsB,KAAK,UAAU,CAAC;AAEnD,IAAM,QAAQ,CAAC,MAAsB;AACnC,QAAM,OAAQ,EAAgC;AAC9C,SAAO,OAAO,SAAS,cAAc,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;AACnF;AAEA,SAAS,YAAY,GAAY,KAAqB;AACpD,UAAQ,OAAO,GAAG;AAAA,IAChB,KAAK;AACH,UAAI,KAAK,GAAG;AACZ;AAAA,IACF,KAAK;AACH,UAAI,KAAK,IAAI,MAAM,GAAG;AACtB;AAAA,IACF,KAAK;AACH,UAAI,KAAK,IAAI,CAAC,EAAE;AAChB;AAAA,IACF,KAAK;AACH,UAAI,KAAK,IAAI,IAAI,CAAC,CAAC,EAAE;AACrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAWF,KAAK;AACH,UAAI,KAAK,IAAI,IAAI,EAAE,eAAe,EAAE,CAAC,EAAE;AACvC;AAAA,IACF,KAAK;AACH,UAAI,KAAK,IAAI,IAAI,EAAE,IAAI,CAAC,EAAE;AAC1B;AAAA,IACF,KAAK;AACH,UAAI,OAAO,MAAM,CAAC,EAAG,KAAI,KAAK,MAAM;AAAA,eAC3B,MAAM,OAAO,kBAAmB,KAAI,KAAK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,WAAO,0BAAQ,MAAM,IAAI;AAC/B,QAAI;AACF,UAAI,KAAC,yBAAS,IAAI,EAAE,YAAY,EAAG,OAAM,IAAI,MAAM,iBAAiB;AAAA,IACtE,QAAQ;AACN,UAAI,CAAC,QAAQ,mBAAmB;AAC9B,cAAM,IAAI;AAAA,UACR,oBAAoB,KAAK,UAAU,IAAI,CAAC,qCAAqC,IAAI;AAAA,QAGnF;AAAA,MACF;AACA,mBAAa,KAAK,IAAI;AACtB;AAAA,IACF;AACA,SAAK,MAAM,MAAM,oBAAI,IAAI,CAAC;AAAA,EAC5B;AAEA,QAAM,UAAU,CAAC,GAAG,MAAM,OAAO,CAAC,EAC/B,KAAK,EACL,IAAI,SAAO,EAAE,IAAI,YAAQ,iCAAa,0BAAQ,MAAM,EAAE,GAAG,MAAM,EAAE,EAAE;AACtE,SAAO,EAAE,SAAS,cAAc,cAAc,aAAa,KAAK,EAAE;AACpE;AAGA,SAAS,KAAK,MAAc,MAAsB;AAChD,aAAO,2BAAS,MAAM,IAAI,EAAE,MAAM,oBAAG,EAAE,KAAK,GAAG;AACjD;",
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": ["../../src/oracle/index.ts", "../../src/oracle/digest.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * `parseman/oracle` \u2014 deterministic serialization of a parse result.\n *\n * Turns \"is this rule collapse safe?\" from a judgement call into an accept/reject.\n * Digest your parse output before and after the change and compare the two\n * digests: equal means the refactor is output-neutral and can land on its own\n * merits; different means it is not a refactor, it is a semantics change, and\n * needs the decision that goes with one.\n *\n * import { digestInto } from 'parseman/oracle'\n * import { createHash } from 'node:crypto'\n *\n * const sha = createHash('sha256')\n * digestInto(sha, parse(source))\n * const digest = sha.digest('hex')\n *\n * It is a differential, not a correctness check. It says the output did not move;\n * it says nothing about whether the output was right to begin with.\n *\n * ## Why the projection is here and the harness is not\n *\n * Deciding what the canonical byte stream IS depends on parseman's node shapes\n * and on nothing else \u2014 which distinctions a refactor can move, and which are\n * bookkeeping no consumer observes. No consumer can get that right, so it lives\n * here, and every grammar author needs it whatever they are building.\n *\n * Walking a corpus, folding per-entry digests into an aggregate, three-way\n * verdicts and report formatting used to live here too, as `loadCorpus`,\n * `digestCorpus`, `compareReports` and `formatComparison`. Those do not help\n * anyone build or diagnose a grammar: they are one consumer's regression-suite\n * plumbing, and they only mean anything with that consumer's corpus roots and\n * committed baseline in hand. They now live with the suite that needs them \u2014\n * jess's is `packages/syntax/less/less-parser/test/identity-oracle/`, a\n * reasonable model to copy. Two things are worth carrying over: keep an\n * `OK:`/`ERR:` prefix so a successful parse and a thrown error stay in disjoint\n * hash spaces, and keep \"the grammar rejected this input\" and \"the digest could\n * not be computed\" on separate channels \u2014 the second is a fact about the TOOL,\n * and reporting it as the first is how a gate lies.\n *\n * Node-only: it hashes with `node:crypto`. It is a development gate, so it is a\n * separate entry point and nothing in it reaches the browser-capable `parseman`\n * bundle.\n *\n * See `docs/guide/identity-oracle.md` for the operating discipline \u2014 in\n * particular why you must digest the BUILT artifact and rebuild between edits.\n */\nexport {\n canonicalize,\n digestInto,\n digestValue,\n CanonicalBudgetError,\n DEFAULT_MAX_VISITS,\n DIGEST_FORMAT,\n} from './digest.ts'\nexport type { CanonicalOptions, DigestTarget } from './digest.ts'\n", "/**\n * The canonical projection and the hashing the identity oracle is built on.\n *\n * Everything here exists to make ONE claim trustworthy: \"this grammar change did\n * not move the tree.\" That claim is only worth as much as the projection behind\n * it, so the rules below are stated rather than left to `JSON.stringify`, which\n * silently collapses several distinctions a grammar refactor can actually move:\n *\n * | value | `JSON.stringify` | here |\n * |------------------------|------------------|-----------------|\n * | `{ a: undefined }` | `{}` | distinct from `{}` |\n * | `NaN` / `\u00B1Infinity` | `null` | each distinct |\n * | `-0` | `0` | distinct from `0` |\n * | `new Map([[1, 2]])` | `{}` | entries, in order |\n * | `new Set([1])` | `{}` | members, in order |\n * | `new Foo({ x: 1 })` | `{\"x\":1}` | tagged `Foo` |\n *\n * A refactor that starts emitting `undefined` where it used to omit a key, or\n * that swaps one node class for another with the same fields, is a tree move.\n * An oracle that cannot see it is worse than no oracle, because it certifies.\n *\n * ## Key order does not matter; array and Map/Set order does\n *\n * Object keys are sorted, so property INSERTION order \u2014 which a refactor churns\n * constantly and which no consumer observes \u2014 never moves a digest. Array\n * elements and Map/Set entries keep their order, because those orders are the\n * output.\n *\n * ## Sharing is not a cycle\n *\n * A node reachable by two paths is written out twice, in full. Only a genuine\n * back-edge into the CURRENT path is abbreviated, and it records the DISTANCE to\n * the ancestor it points at, so a self-reference and a reference to the root are\n * different digests. (Marking every repeat as a cycle \u2014 the easy version \u2014 makes\n * the digest depend on traversal order for any DAG, which parse trees with\n * interned or shared subtrees routinely are.)\n *\n * The cost of that choice is stated plainly, because it has now bitten a\n * consumer: writing a shared subtree once per PATH is EXPONENTIAL in sharing\n * depth. A node referenced from two places at each of `d` levels is written\n * `2^d` times. See {@link DEFAULT_MAX_VISITS} for the backstop and for why the\n * obvious fix is a format change rather than a patch.\n *\n * ## Own ENUMERABLE keys only\n *\n * `Object.keys`, deliberately, not `getOwnPropertyNames`. The oracle answers \"did\n * the OUTPUT move\" and non-enumerable properties are engine bookkeeping a\n * consumer never sees \u2014 parseman's own carried CST pieces among them. Hashing\n * them would make a consumer's grammar digest move when parseman's internals\n * change, which is precisely the wrong sensitivity for a grammar-refactor gate.\n *\n * ## Tokens, not concatenation\n *\n * Every value writes one or more self-contained tokens joined by NUL. Writing\n * `#1` then `#2` into a single buffer would be indistinguishable from `#12`; a\n * projection with an ambiguity in it is a projection that can be made to lie.\n * Strings are JSON-escaped, so no token can contain a raw NUL.\n *\n * ## The projection is streamed, never materialised\n *\n * {@link digestInto} walks a value and pushes the token stream at a caller-owned\n * hash. Nothing accumulates, so there is no maximum-string-length ceiling and no\n * corpus size at which the digest stops being takeable. {@link canonicalize}\n * still builds the string, because reading it is its entire purpose \u2014 but it is\n * a debugging aid, not the path a gate runs on.\n */\nimport { createHash } from 'node:crypto'\n\n/**\n * Bump when the token grammar below changes in a way that alters output for any\n * input. It is a coarse, human-readable companion to the behavioural harness\n * digest \u2014 the harness digest is what actually enforces this, but a reader\n * comparing two reports should not have to diff hex to see that the format moved.\n */\nexport const DIGEST_FORMAT = 1\n\n/**\n * The token separator, in one place.\n *\n * {@link canonicalize} joins with it and {@link StreamSink} interleaves it, and\n * they MUST agree \u2014 the equality of those two byte streams is what lets a\n * streamed digest reproduce one taken from the string form. Sharing the constant\n * is how that stops being a thing anyone has to remember.\n */\nconst SEPARATOR = String.fromCharCode(0)\n\nconst str = (s: string): string => JSON.stringify(s)\n\nconst tagOf = (v: object): string => {\n const ctor = (v as { constructor?: unknown }).constructor\n return typeof ctor === 'function' && typeof ctor.name === 'string' ? ctor.name : ''\n}\n\n/**\n * Where canonical tokens go.\n *\n * Two implementations describing the SAME byte stream: {@link ArraySink}\n * materialises it, {@link StreamSink} pushes it at a hash and forgets it.\n */\ntype CanonicalSink = {\n push(token: string): void\n}\n\n/** Collects tokens so {@link canonicalize} can join them. */\nclass ArraySink implements CanonicalSink {\n readonly tokens: string[] = []\n\n push(token: string): void {\n this.tokens.push(token)\n }\n}\n\n/**\n * Anything that absorbs a stream of text. Node's `crypto.Hash` satisfies it, and\n * so does a three-line test double.\n *\n * The CALLER supplies this, and therefore owns the algorithm and the result.\n * Deciding what the canonical byte stream IS depends on parseman's node shapes\n * and on nothing else; deciding that you wanted sha256-hex does not.\n */\nexport type DigestTarget = {\n update(chunk: string): void\n}\n\n/**\n * Pushes the canonical token stream at a {@link DigestTarget} without ever\n * materialising it.\n *\n * The bytes written are exactly what {@link canonicalize} would have returned \u2014\n * the separator goes BETWEEN tokens, never after \u2014 so hashing either gives the\n * same digest. That equality is not an implementation detail, it is the entire\n * safety argument for streaming: every digest ever recorded stays reproducible.\n * `test/unit/oracle-digest.test.ts` asserts it directly over the canary shapes.\n *\n * Tokens are buffered and flushed in blocks rather than written one at a time:\n * one `update()` per token is a call into native code per AST node. Flushing\n * only ever happens at a token boundary and tokens are whole JS strings, so a\n * surrogate pair can never be split across two `update()` calls \u2014 which would\n * encode to different UTF-8 bytes than the joined string does.\n */\nclass StreamSink implements CanonicalSink {\n private readonly target: DigestTarget\n private buffer: string[] = []\n private buffered = 0\n private started = false\n\n constructor(target: DigestTarget) {\n this.target = target\n }\n\n /**\n * Write text that is NOT a canonical token and takes no separator \u2014 the\n * `OK:` / `ERR:` discriminator, which the string form concatenates onto the\n * front rather than joining.\n */\n prefix(text: string): void {\n if (text === '') return\n this.buffer.push(text)\n this.buffered += text.length\n }\n\n push(token: string): void {\n if (this.started) {\n this.buffer.push(SEPARATOR)\n this.buffered += 1\n } else {\n this.started = true\n }\n this.buffer.push(token)\n this.buffered += token.length\n if (this.buffered >= FLUSH_CHARS) this.flush()\n }\n\n flush(): void {\n if (this.buffer.length === 0) return\n this.target.update(this.buffer.join(''))\n this.buffer = []\n this.buffered = 0\n }\n}\n\n/**\n * How much token text to accumulate before handing a block to the target. Large\n * enough that per-call overhead disappears, small enough that the extra live\n * memory is a rounding error next to the tree being walked.\n */\nconst FLUSH_CHARS = 1 << 16\n\n/**\n * Raised when a walk exceeds its visit budget.\n *\n * A distinct class, and deliberately NOT an ordinary `Error` a caller might\n * lump in with a parse failure: this says the TOOL gave up, which is the\n * opposite of a fact about the grammar.\n */\nexport class CanonicalBudgetError extends Error {\n override readonly name = 'CanonicalBudgetError'\n\n constructor(budget: number, projected?: number) {\n super(\n `canonicalize: exceeded ${budget} visits. The value is not merely large \u2014 it is almost certainly a DAG being `\n + 'unrolled. This projection writes a shared subtree once per PATH that reaches it (see \"Sharing is not a '\n + 'cycle\"), so a node referenced from two places at each of d levels costs 2^d. Deduplicate the shared '\n + 'structure, or raise `maxVisits` if the value really is that big.'\n + (projected === undefined\n ? ''\n : ` Refused EARLY: the walk was projected to visit ${projected} objects, so it could not have finished `\n + 'under this budget however long it ran. See {@link projectVisits}.'),\n )\n }\n}\n\n/**\n * Default visit budget.\n *\n * A backstop against unbounded work, not a correctness feature. Any walk that\n * finishes under budget writes exactly the bytes it always did, so this cannot\n * move a recorded digest \u2014 which is the only reason it can be added to a shipped\n * format at all.\n *\n * It is NOT a fix for the underlying asymmetry. The fix is to dedupe by node\n * IDENTITY instead of by ancestor path, and that rewrites the byte stream for\n * every value with any sharing in it: `{ left: shared, right: shared }` stops\n * being two full writes and becomes a back-reference. That invalidates every\n * digest, every committed baseline, and {@link DIGEST_FORMAT} itself. It is a\n * format decision for the owner, not something to slip in behind a bug fix.\n *\n * ## The tempting middle road does not exist\n *\n * Stated because it looks obviously right and is obviously right about the wrong\n * thing: memoise the canonical BYTES of a subtree by node identity, splice the\n * cached bytes in at each of the two places, and you get the identical output\n * with the work done once. It is sound \u2014 a subtree's bytes depend only on the\n * subtree, except for a back-edge leaving it, which is exactly the case\n * {@link projectVisits} declines \u2014 and it does not help.\n *\n * It does not help because the walk is ALREADY linear in its own output, and it\n * is the OUTPUT that is exponential: a depth-`d` two-way unroll writes 33\u00B72^d\n * chars, measured, and every one of them has to reach the hash. Caching removes\n * re-derivation, of which there is a constant factor's worth; it cannot remove\n * bytes the format requires. At depth 40 that is 36 TB of canonical text \u2014 7\n * hours of sha256 at the 1.37 Gchar/s this machine manages, with traversal,\n * allocation and splicing all free. Depth 40 has no answer to compute quickly.\n * There is only refusing quickly, which is what the probe does.\n */\nexport const DEFAULT_MAX_VISITS = 100_000_000\n\n/**\n * Object visits to spend before the walk stops to ask whether it can possibly\n * finish. Zero cost below it, so nothing a gate actually digests ever pays.\n *\n * A million visits is ~0.4s of walking on the machine this was measured on \u2014\n * far past any real parse tree, far short of the 49 SECONDS an exponential\n * unroll used to spend before {@link DEFAULT_MAX_VISITS} noticed.\n */\nconst EXPANSION_PROBE_VISITS = 1_000_000\n\n/**\n * Distinct objects the probe will look at before giving up on answering.\n *\n * A value with more distinct nodes than this is genuinely enormous rather than\n * DAG-shaped, and the probe has nothing useful to say about it \u2014 an unrolling\n * DAG is tiny in DISTINCT nodes (depth 40 is 41 of them) and huge only in paths.\n * Capping here is what keeps the probe from becoming a second full walk: the cap\n * is what the probe costs, once, in the worst case, and giving up early costs\n * only the old behaviour.\n */\nconst EXPANSION_PROBE_NODES = 200_000\n\n/**\n * How far past the budget a projection must land before it is acted on.\n *\n * The projection re-reads the value \u2014 including any getters \u2014 so it is a\n * measurement of the value, not of the walk, and a value that answers\n * differently the second time can make it wrong. A margin this wide means only\n * an order-of-magnitude disagreement can refuse a walk that would have\n * finished; anything nearer the line falls through to the walk itself, which is\n * the authority. Erring costs time, never bytes.\n */\nconst EXPANSION_PROBE_MARGIN = 4\n\ntype WriteState = {\n readonly path: Map<object, number>\n readonly sink: CanonicalSink\n readonly budget: number\n readonly root: unknown\n visits: number\n /**\n * The value of {@link visits} at which to run the probe, or `-1` to never run\n * it. Exact equality, so it fires once and is then unreachable.\n */\n probeAt: number\n}\n\n/**\n * The number of objects {@link write} will visit for `root`, or `undefined` if\n * that cannot be answered cheaply and exactly.\n *\n * This counts what the walk counts \u2014 one per object visit, zero for a scalar,\n * one for a back-edge \u2014 but MEMOISED by node identity, so a shared subtree is\n * counted once instead of once per path. That is the whole trick: counting the\n * work is linear in DISTINCT nodes even when doing the work is exponential in\n * paths.\n *\n * It answers `undefined` rather than guessing whenever the count could be wrong\n * in the direction that matters:\n *\n * - **A back-edge.** Whether a node abbreviates to `^n` depends on the ancestor\n * set at the moment it is reached, so for a cyclic value a memoised count is\n * not context-free and can come out HIGH. Any back-edge at all abandons the\n * answer.\n * - **Too many distinct nodes.** {@link EXPANSION_PROBE_NODES}, above.\n * - **A throw.** A getter, a Proxy trap, or the added stack depth of running a\n * recursive count on top of an in-progress recursive walk. None of these are\n * the probe's business to diagnose; not answering is always available.\n */\nfunction projectVisits(root: unknown): number | undefined {\n const memo = new Map<object, number>()\n const path = new Set<object>()\n let nodes = 0\n let usable = true\n\n const count = (v: unknown): number => {\n if (typeof v !== 'object' || v === null) return 0\n if (path.has(v)) {\n usable = false\n return 1\n }\n const done = memo.get(v)\n if (done !== undefined) return done\n if (++nodes > EXPANSION_PROBE_NODES) {\n usable = false\n return 1\n }\n\n path.add(v)\n // Mirrors `write`'s child enumeration exactly. Key ORDER is irrelevant to a\n // count, so this does not sort; nothing else here may drift from `write`.\n let total = 1\n if (Array.isArray(v)) {\n for (const item of v) total += count(item)\n } else if (v instanceof Map) {\n for (const [k, val] of v) total += count(k) + count(val)\n } else if (v instanceof Set) {\n for (const item of v) total += count(item)\n } else if (!(v instanceof Date) && !(v instanceof RegExp)) {\n for (const k of Object.keys(v)) total += count((v as Record<string, unknown>)[k])\n }\n path.delete(v)\n\n memo.set(v, total)\n return total\n }\n\n try {\n const total = count(root)\n return usable ? total : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Stop a walk that provably cannot finish, at the point it has proved expensive.\n *\n * The budget is a backstop that only notices after the work is done, and for an\n * exponential unroll \"after\" is minutes. This asks the cheap question instead \u2014\n * how many visits would the whole walk take \u2014 and refuses immediately when the\n * answer is far past the budget the walk is already spending.\n *\n * The OUTCOME is unchanged: a walk projected past its budget is a walk that\n * raises {@link CanonicalBudgetError}, so this moves nothing but the clock. It\n * cannot move a digest, because no walk it stops was ever going to produce one.\n */\nfunction probeExpansion(state: WriteState): void {\n state.probeAt = -1\n const projected = projectVisits(state.root)\n if (projected !== undefined && projected / EXPANSION_PROBE_MARGIN > state.budget) {\n throw new CanonicalBudgetError(state.budget, projected)\n }\n}\n\nfunction writeScalar(v: unknown, out: CanonicalSink): void {\n switch (typeof v) {\n case 'undefined':\n out.push('u')\n return\n case 'boolean':\n out.push(v ? 'T' : 'F')\n return\n case 'bigint':\n out.push(`n${v}`)\n return\n case 'string':\n out.push(`s${str(v)}`)\n return\n // TODO(oracle-callable-identity): a callable is projected by NAME and a symbol by\n // DESCRIPTION, so two distinct same-named functions \u2014 or two same-description\n // symbols \u2014 digest identically, and a change between them reads as \"identical\".\n // This is a real hole in a tool whose whole claim is paranoia, and it is left open\n // deliberately: closing it means either hashing `Function.prototype.toString()`,\n // which flips the digest on a comment edit inside a builder, or REFUSING to digest\n // any value carrying a callable, which rejects legitimate ASTs that park a callback\n // on a node. Both are worse than the hole for some caller, and picking between them\n // is a product decision, not a bug fix. Documented under \"What it is not\" in\n // `docs/guide/identity-oracle.md` so no reader infers a guarantee that is not here.\n case 'symbol':\n out.push(`y${str(v.description ?? '')}`)\n return\n case 'function':\n out.push(`f${str(v.name)}`)\n return\n case 'number':\n if (Number.isNaN(v)) out.push('#nan')\n else if (v === Number.POSITIVE_INFINITY) out.push('#inf')\n else if (v === Number.NEGATIVE_INFINITY) out.push('#-inf')\n else if (Object.is(v, -0)) out.push('#-0')\n // Number\u2192string is exact and round-trips in JS, so this loses nothing.\n else out.push(`#${v}`)\n return\n default:\n // `typeof null`. Distinct from `undefined`, which is `'u'`.\n out.push('z')\n }\n}\n\nfunction write(v: unknown, state: WriteState, depth: number): void {\n const out = state.sink\n // Everything that is not a live object reference is written here, so the rest\n // of the function has `v: object` and needs no assertion to index or key on it.\n if (typeof v !== 'object' || v === null) {\n writeScalar(v, out)\n return\n }\n\n // Counted per OBJECT visit, not per token: the runaway this guards against is\n // re-walking structure, and scalars cannot re-walk anything.\n if (--state.visits < 0) throw new CanonicalBudgetError(state.budget)\n // One equality against a number already in a register, on a path that already\n // does three Map operations. Fires at most once per walk; `-1` is unreachable.\n if (state.visits === state.probeAt) probeExpansion(state)\n\n const path = state.path\n const seenAt = path.get(v)\n if (seenAt !== undefined) {\n // Distance to the ancestor, not its identity: a self-reference and a\n // reference to the root must not hash the same.\n out.push(`^${depth - seenAt}`)\n return\n }\n path.set(v, depth)\n\n if (Array.isArray(v)) {\n out.push('[')\n // `for..of` rather than indexing so a sparse hole reads as the `undefined`\n // it is, consistently with a present `undefined` \u2014 the distinction between\n // a hole and an explicit undefined is not observable output.\n for (const item of v) write(item, state, depth + 1)\n out.push(']')\n } else if (v instanceof Map) {\n out.push('M')\n for (const [k, val] of v) {\n write(k, state, depth + 1)\n write(val, state, depth + 1)\n }\n out.push('}')\n } else if (v instanceof Set) {\n out.push('S')\n for (const item of v) write(item, state, depth + 1)\n out.push('}')\n } else if (v instanceof Date) {\n out.push(`D${v.getTime()}`)\n } else if (v instanceof RegExp) {\n out.push(`R${str(v.source)}${str(v.flags)}`)\n } else {\n const tag = tagOf(v)\n out.push(`{${str(tag === 'Object' ? '' : tag)}`)\n for (const k of Object.keys(v).sort()) {\n out.push(`k${str(k)}`)\n write((v as Record<string, unknown>)[k], state, depth + 1)\n }\n out.push('}')\n }\n\n path.delete(v)\n}\n\n/** Options shared by every entry point that walks a value. */\nexport type CanonicalOptions = {\n /**\n * Maximum object visits before {@link CanonicalBudgetError}. Defaults to\n * {@link DEFAULT_MAX_VISITS}. A walk that finishes under budget is byte-for-byte\n * unaffected, so this can never change a digest.\n *\n * MUST be a non-negative safe integer. `NaN`, `Infinity`, a negative and a\n * fractional value are all REJECTED rather than clamped \u2014 see\n * {@link newState} for why a bad budget is a thrown error and not a shrug.\n */\n maxVisits?: number | undefined\n}\n\n/**\n * Build the walk state, validating the budget before anything is written.\n *\n * The budget is spent with `--visits < 0`, and that comparison is silently\n * FALSE for `NaN` \u2014 so `maxVisits: NaN` did not raise the ceiling, it removed\n * it, and the walk it was supposed to bound ran to the OOM the budget exists to\n * prevent. `Infinity` is the same wish spelled honestly and gets the same\n * refusal, because an unbounded walk is not an option this offers. A fraction\n * never reaches `-1` cleanly either.\n *\n * So the budget is checked once, here, where the option is read: a bad number is\n * a caller mistake and says so, rather than turning into a hang under load.\n */\nfunction newState(sink: CanonicalSink, options: CanonicalOptions | undefined, root: unknown): WriteState {\n const budget = options?.maxVisits ?? DEFAULT_MAX_VISITS\n if (!Number.isSafeInteger(budget) || budget < 0) {\n throw new RangeError(\n `canonicalize: maxVisits must be a non-negative safe integer, received ${String(budget)}. `\n + 'A non-finite or fractional budget does not raise the ceiling, it REMOVES it \u2014 the budget is spent with '\n + '`--visits < 0`, which is false forever for NaN and never reached for Infinity \u2014 so the walk this bounds '\n + 'would run unbounded into the OOM the budget exists to prevent.',\n )\n }\n // A budget too small to reach the probe never reaches it: the walk raises\n // CanonicalBudgetError first, exactly as it always did.\n const probeAt = budget >= EXPANSION_PROBE_VISITS ? budget - EXPANSION_PROBE_VISITS : -1\n return { path: new Map(), sink, budget, root, visits: budget, probeAt }\n}\n\n/**\n * The canonical token string for a value. Exported because a moved digest is\n * only actionable if you can see WHAT moved: diff two canonical strings and the\n * answer is a line, not a hex mismatch.\n *\n * This MATERIALISES the projection, so it is bounded by the maximum JS string\n * length and by available memory. Use it to explain a move you already know\n * about; take the digest itself with {@link digestInto}, which is bounded by\n * neither.\n */\nexport function canonicalize(value: unknown, options?: CanonicalOptions): string {\n const out = new ArraySink()\n write(value, newState(out, options, value), 0)\n return out.tokens.join(SEPARATOR)\n}\n\n/**\n * Stream a value's canonical projection into a caller-owned hash.\n *\n * This is the primitive: deterministic serialization of ONE parse result, which\n * is the part only parseman can do \u2014 it is parseman's node shapes that decide\n * which distinctions are semantically meaningful. The caller brings the hash and\n * keeps the result, so the algorithm, the encoding and the digest width are all\n * theirs.\n *\n * ```ts\n * const sha = createHash('sha256')\n * digestInto(sha, tree)\n * const digest = sha.digest('hex')\n * ```\n *\n * `prefix` is written ahead of the first token with NO separator, for callers\n * that discriminate one digest space from another (parseman's own oracle writes\n * `OK:` or `ERR:`). Pass `''` when there is nothing to discriminate.\n *\n * Equivalent to `hash(prefix + canonicalize(value))`, and preferable in every\n * case where you do not need to READ the projection.\n *\n * ## Two sharp edges, stated because the target is YOURS\n *\n * **A throw leaves the target written-to.** The token stream is pushed at\n * `target` as the walk proceeds, so a {@link CanonicalBudgetError}, a throwing\n * getter, or any other failure mid-walk leaves an ARBITRARY PREFIX of the\n * projection already absorbed. The hash object is then polluted: its digest is\n * neither the value's nor anything else's, and it is not recoverable \u2014 a\n * `crypto.Hash` cannot be rewound. On any throw, DISCARD the target and start a\n * fresh one. {@link digestValue} does exactly that by owning its hash for a\n * single call.\n *\n * **Two calls against one target concatenate with NO delimiter.** There is no\n * record separator between calls: `digestInto(t, a); digestInto(t, b)` writes\n * exactly `canonicalize(a) + canonicalize(b)`, with nothing in between. That is\n * ambiguous across the call boundary \u2014 the byte stream does not record where one\n * value ended, so a differently-split sequence can produce the identical stream\n * and therefore the identical digest. Concretely, `digestInto(t, 1);\n * digestInto(t, 2)` and the single call `digestInto(t, 2, '#1')` both write\n * `#1#2`. (Within ONE call the projection is unambiguous \u2014 every token is\n * self-contained and NUL-joined; it is only the seam between calls that is not.)\n *\n * This is DOCUMENTED rather than fixed. Any delimiter at the seam \u2014 written\n * before, after, or between \u2014 changes the bytes some existing caller already\n * hashes, and moving a recorded digest is a {@link DIGEST_FORMAT} decision for\n * the owner, not a patch. Callers hashing a SEQUENCE should digest a wrapper\n * value (`digestInto(t, [a, b])`), or write their own unambiguous separator\n * between calls, or use one target per value.\n */\nexport function digestInto(\n target: DigestTarget,\n value: unknown,\n prefix = '',\n options?: CanonicalOptions,\n): void {\n const sink = new StreamSink(target)\n sink.prefix(prefix)\n write(value, newState(sink, options, value), 0)\n sink.flush()\n}\n\n/**\n * Full 64-hex sha256 of a value's canonical projection, streamed.\n *\n * The convenience wrapper over {@link digestInto} for the common case.\n * Identical to `sha256(prefix + canonicalize(value))` for every value the\n * latter can survive, and unbounded where it is not.\n */\nexport function digestValue(value: unknown, prefix = '', options?: CanonicalOptions): string {\n const sha = createHash('sha256')\n digestInto(sha, value, prefix, options)\n return sha.digest('hex')\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkEA,yBAA2B;AAQpB,IAAM,gBAAgB;AAU7B,IAAM,YAAY,OAAO,aAAa,CAAC;AAEvC,IAAM,MAAM,CAAC,MAAsB,KAAK,UAAU,CAAC;AAEnD,IAAM,QAAQ,CAAC,MAAsB;AACnC,QAAM,OAAQ,EAAgC;AAC9C,SAAO,OAAO,SAAS,cAAc,OAAO,KAAK,S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zF;AAAA,EACF;AAGA,QAAM,UAAU,UAAU,yBAAyB,SAAS,yBAAyB;AACrF,SAAO,EAAE,MAAM,oBAAI,IAAI,GAAG,MAAM,QAAQ,MAAM,QAAQ,QAAQ,QAAQ;AACxE;AAYO,SAAS,aAAa,OAAgB,SAAoC;AAC/E,QAAM,MAAM,IAAI,UAAU;AAC1B,QAAM,OAAO,SAAS,KAAK,SAAS,KAAK,GAAG,CAAC;AAC7C,SAAO,IAAI,OAAO,KAAK,SAAS;AAClC;AAoDO,SAAS,WACd,QACA,OACA,SAAS,IACT,SACM;AACN,QAAM,OAAO,IAAI,WAAW,MAAM;AAClC,OAAK,OAAO,MAAM;AAClB,QAAM,OAAO,SAAS,MAAM,SAAS,KAAK,GAAG,CAAC;AAC9C,OAAK,MAAM;AACb;AASO,SAAS,YAAY,OAAgB,SAAS,IAAI,SAAoC;AAC3F,QAAM,UAAM,+BAAW,QAAQ;AAC/B,aAAW,KAAK,OAAO,QAAQ,OAAO;AACtC,SAAO,IAAI,OAAO,KAAK;AACzB;",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
package/dist/oracle/index.d.ts
CHANGED
|
@@ -1,37 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `parseman/oracle` —
|
|
3
|
-
*
|
|
4
|
-
* Turns "is this rule collapse safe?" from a judgement call into an accept/reject
|
|
5
|
-
*
|
|
6
|
-
* and
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* const
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
2
|
+
* `parseman/oracle` — deterministic serialization of a parse result.
|
|
3
|
+
*
|
|
4
|
+
* Turns "is this rule collapse safe?" from a judgement call into an accept/reject.
|
|
5
|
+
* Digest your parse output before and after the change and compare the two
|
|
6
|
+
* digests: equal means the refactor is output-neutral and can land on its own
|
|
7
|
+
* merits; different means it is not a refactor, it is a semantics change, and
|
|
8
|
+
* needs the decision that goes with one.
|
|
9
|
+
*
|
|
10
|
+
* import { digestInto } from 'parseman/oracle'
|
|
11
|
+
* import { createHash } from 'node:crypto'
|
|
12
|
+
*
|
|
13
|
+
* const sha = createHash('sha256')
|
|
14
|
+
* digestInto(sha, parse(source))
|
|
15
|
+
* const digest = sha.digest('hex')
|
|
16
|
+
*
|
|
17
|
+
* It is a differential, not a correctness check. It says the output did not move;
|
|
18
|
+
* it says nothing about whether the output was right to begin with.
|
|
19
|
+
*
|
|
20
|
+
* ## Why the projection is here and the harness is not
|
|
21
|
+
*
|
|
22
|
+
* Deciding what the canonical byte stream IS depends on parseman's node shapes
|
|
23
|
+
* and on nothing else — which distinctions a refactor can move, and which are
|
|
24
|
+
* bookkeeping no consumer observes. No consumer can get that right, so it lives
|
|
25
|
+
* here, and every grammar author needs it whatever they are building.
|
|
26
|
+
*
|
|
27
|
+
* Walking a corpus, folding per-entry digests into an aggregate, three-way
|
|
28
|
+
* verdicts and report formatting used to live here too, as `loadCorpus`,
|
|
29
|
+
* `digestCorpus`, `compareReports` and `formatComparison`. Those do not help
|
|
30
|
+
* anyone build or diagnose a grammar: they are one consumer's regression-suite
|
|
31
|
+
* plumbing, and they only mean anything with that consumer's corpus roots and
|
|
32
|
+
* committed baseline in hand. They now live with the suite that needs them —
|
|
33
|
+
* jess's is `packages/syntax/less/less-parser/test/identity-oracle/`, a
|
|
34
|
+
* reasonable model to copy. Two things are worth carrying over: keep an
|
|
35
|
+
* `OK:`/`ERR:` prefix so a successful parse and a thrown error stay in disjoint
|
|
36
|
+
* hash spaces, and keep "the grammar rejected this input" and "the digest could
|
|
37
|
+
* not be computed" on separate channels — the second is a fact about the TOOL,
|
|
38
|
+
* and reporting it as the first is how a gate lies.
|
|
39
|
+
*
|
|
40
|
+
* Node-only: it hashes with `node:crypto`. It is a development gate, so it is a
|
|
41
|
+
* separate entry point and nothing in it reaches the browser-capable `parseman`
|
|
42
|
+
* bundle.
|
|
28
43
|
*
|
|
29
44
|
* See `docs/guide/identity-oracle.md` for the operating discipline — in
|
|
30
45
|
* particular why you must digest the BUILT artifact and rebuild between edits.
|
|
31
46
|
*/
|
|
32
|
-
export {
|
|
33
|
-
export type {
|
|
34
|
-
export { loadCorpus } from './corpus.ts';
|
|
35
|
-
export type { LoadCorpusOptions, LoadedCorpus } from './corpus.ts';
|
|
36
|
-
export { canonicalize, DIGEST_FORMAT } from './digest.ts';
|
|
47
|
+
export { canonicalize, digestInto, digestValue, CanonicalBudgetError, DEFAULT_MAX_VISITS, DIGEST_FORMAT, } from './digest.ts';
|
|
48
|
+
export type { CanonicalOptions, DigestTarget } from './digest.ts';
|
|
37
49
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oracle/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oracle/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,OAAO,EACL,YAAY,EACZ,UAAU,EACV,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,aAAa,GACd,MAAM,aAAa,CAAA;AACpB,YAAY,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA"}
|