parseman 0.46.0 → 0.47.1

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.
Files changed (316) hide show
  1. package/README.md +8 -3
  2. package/dist/analysis/choice-cost-render.d.ts +12 -4
  3. package/dist/analysis/choice-cost-render.d.ts.map +1 -1
  4. package/dist/analysis/choice-cost.d.ts +2 -2
  5. package/dist/analysis/choice-cost.d.ts.map +1 -1
  6. package/dist/analysis/commitment.d.ts +131 -0
  7. package/dist/analysis/commitment.d.ts.map +1 -0
  8. package/dist/analysis/diagnostics.cjs +10339 -7787
  9. package/dist/analysis/diagnostics.cjs.map +3 -4
  10. package/dist/analysis/diagnostics.d.ts +2 -2
  11. package/dist/analysis/diagnostics.js +10339 -7787
  12. package/dist/analysis/diagnostics.js.map +3 -4
  13. package/dist/analysis/duplication.d.ts.map +1 -1
  14. package/dist/analysis/fix.d.ts +3 -3
  15. package/dist/analysis/fix.d.ts.map +1 -1
  16. package/dist/analysis/format-number.d.ts +23 -0
  17. package/dist/analysis/format-number.d.ts.map +1 -0
  18. package/dist/analysis/gating.d.ts +39 -2
  19. package/dist/analysis/gating.d.ts.map +1 -1
  20. package/dist/analysis/rebuild.d.ts.map +1 -1
  21. package/dist/analysis/terminal.d.ts +5 -2
  22. package/dist/analysis/terminal.d.ts.map +1 -1
  23. package/dist/cli/index.cjs +10924 -8506
  24. package/dist/cli/index.cjs.map +3 -4
  25. package/dist/cli/index.js +10924 -8506
  26. package/dist/cli/index.js.map +3 -4
  27. package/dist/combinators/adjacency.d.ts +100 -0
  28. package/dist/combinators/adjacency.d.ts.map +1 -0
  29. package/dist/combinators/choice.d.ts.map +1 -1
  30. package/dist/combinators/completions.d.ts.map +1 -1
  31. package/dist/combinators/dispatch.d.ts +8 -1
  32. package/dist/combinators/dispatch.d.ts.map +1 -1
  33. package/dist/combinators/expect.d.ts.map +1 -1
  34. package/dist/combinators/first-set.d.ts.map +1 -1
  35. package/dist/combinators/gate.d.ts.map +1 -1
  36. package/dist/combinators/grammar.d.ts +22 -0
  37. package/dist/combinators/grammar.d.ts.map +1 -1
  38. package/dist/combinators/literal.d.ts +8 -0
  39. package/dist/combinators/literal.d.ts.map +1 -1
  40. package/dist/combinators/map.d.ts +0 -1
  41. package/dist/combinators/map.d.ts.map +1 -1
  42. package/dist/combinators/node.d.ts +13 -3
  43. package/dist/combinators/node.d.ts.map +1 -1
  44. package/dist/combinators/parser.d.ts +1 -1
  45. package/dist/combinators/parser.d.ts.map +1 -1
  46. package/dist/combinators/ref.d.ts.map +1 -1
  47. package/dist/combinators/regex.d.ts +1 -16
  48. package/dist/combinators/regex.d.ts.map +1 -1
  49. package/dist/combinators/repeat.d.ts +30 -2
  50. package/dist/combinators/repeat.d.ts.map +1 -1
  51. package/dist/combinators/scanTo.d.ts +71 -1
  52. package/dist/combinators/scanTo.d.ts.map +1 -1
  53. package/dist/combinators/sequence.d.ts.map +1 -1
  54. package/dist/combinators/token.d.ts.map +1 -1
  55. package/dist/combinators/trivia-boundary.d.ts +26 -0
  56. package/dist/combinators/trivia-boundary.d.ts.map +1 -0
  57. package/dist/combinators/trivia-skip.d.ts +45 -1
  58. package/dist/combinators/trivia-skip.d.ts.map +1 -1
  59. package/dist/combinators/withCtx.d.ts.map +1 -1
  60. package/dist/compiler/compile-linkable-table.d.ts +104 -0
  61. package/dist/compiler/compile-linkable-table.d.ts.map +1 -0
  62. package/dist/compiler/degradation.d.ts +0 -2
  63. package/dist/compiler/degradation.d.ts.map +1 -1
  64. package/dist/compiler/fields.d.ts +13 -0
  65. package/dist/compiler/fields.d.ts.map +1 -1
  66. package/dist/compiler/grammar-coverage-ids.d.ts +5 -5
  67. package/dist/compiler/grammar-coverage-ids.d.ts.map +1 -1
  68. package/dist/compiler/ir-serialize.d.ts.map +1 -1
  69. package/dist/compiler/linker.d.ts +47 -53
  70. package/dist/compiler/linker.d.ts.map +1 -1
  71. package/dist/compiler/token-alphabet.d.ts +81 -0
  72. package/dist/compiler/token-alphabet.d.ts.map +1 -0
  73. package/dist/compiler/token-dispatch.d.ts +95 -0
  74. package/dist/compiler/token-dispatch.d.ts.map +1 -0
  75. package/dist/compiler/token-scanner.d.ts +53 -0
  76. package/dist/compiler/token-scanner.d.ts.map +1 -0
  77. package/dist/compiler/value-usage.d.ts.map +1 -1
  78. package/dist/coverage.d.ts +1 -1
  79. package/dist/coverage.d.ts.map +1 -1
  80. package/dist/cst/capture-buffer.d.ts +35 -0
  81. package/dist/cst/capture-buffer.d.ts.map +1 -1
  82. package/dist/cst/reflection-attach.d.ts +8 -0
  83. package/dist/cst/reflection-attach.d.ts.map +1 -0
  84. package/dist/cst/reflection-symbols.d.ts +10 -0
  85. package/dist/cst/reflection-symbols.d.ts.map +1 -0
  86. package/dist/cst/reflection.d.ts +2 -4
  87. package/dist/cst/reflection.d.ts.map +1 -1
  88. package/dist/cst/root-trivia-scope.d.ts +26 -0
  89. package/dist/cst/root-trivia-scope.d.ts.map +1 -0
  90. package/dist/cst/trivia-charscan.d.ts +18 -0
  91. package/dist/cst/trivia-charscan.d.ts.map +1 -0
  92. package/dist/cst/trivia-kinds.d.ts +19 -0
  93. package/dist/cst/trivia-kinds.d.ts.map +1 -1
  94. package/dist/functional/doc.d.ts.map +1 -1
  95. package/dist/functional/run-tabled.d.ts +12 -0
  96. package/dist/functional/run-tabled.d.ts.map +1 -0
  97. package/dist/functional/run.d.ts +25 -42
  98. package/dist/functional/run.d.ts.map +1 -1
  99. package/dist/grammar-metadata.d.ts +3 -0
  100. package/dist/grammar-metadata.d.ts.map +1 -0
  101. package/dist/index.cjs +9290 -7181
  102. package/dist/index.cjs.map +3 -4
  103. package/dist/index.d.ts +18 -9
  104. package/dist/index.d.ts.map +1 -1
  105. package/dist/index.js +9300 -7191
  106. package/dist/index.js.map +3 -4
  107. package/dist/language-service/index.cjs +313 -121
  108. package/dist/language-service/index.cjs.map +3 -4
  109. package/dist/language-service/index.js +313 -121
  110. package/dist/language-service/index.js.map +3 -4
  111. package/dist/oracle/index.cjs.map +0 -1
  112. package/dist/oracle/index.js.map +0 -1
  113. package/dist/parse-context.d.ts +49 -0
  114. package/dist/parse-context.d.ts.map +1 -0
  115. package/dist/plugin/evaluator.d.ts +40 -1
  116. package/dist/plugin/evaluator.d.ts.map +1 -1
  117. package/dist/plugin/index.cjs +11175 -9534
  118. package/dist/plugin/index.cjs.map +3 -4
  119. package/dist/plugin/index.d.ts.map +1 -1
  120. package/dist/plugin/index.js +11175 -9534
  121. package/dist/plugin/index.js.map +3 -4
  122. package/dist/regex/classes.d.ts +28 -0
  123. package/dist/regex/classes.d.ts.map +1 -1
  124. package/dist/regex/first-set.d.ts +14 -0
  125. package/dist/regex/first-set.d.ts.map +1 -1
  126. package/dist/run/index.cjs +136 -51
  127. package/dist/run/index.cjs.map +2 -3
  128. package/dist/run/index.js +136 -51
  129. package/dist/run/index.js.map +2 -3
  130. package/dist/spec/index.cjs +2934 -1611
  131. package/dist/spec/index.cjs.map +3 -4
  132. package/dist/spec/index.js +2934 -1611
  133. package/dist/spec/index.js.map +3 -4
  134. package/dist/spec/model.d.ts +8 -0
  135. package/dist/spec/model.d.ts.map +1 -1
  136. package/dist/table/assemble.d.ts +307 -0
  137. package/dist/table/assemble.d.ts.map +1 -0
  138. package/dist/table/cell.d.ts +42 -0
  139. package/dist/table/cell.d.ts.map +1 -0
  140. package/dist/table/child-slots.d.ts +30 -0
  141. package/dist/table/child-slots.d.ts.map +1 -0
  142. package/dist/table/compile-rule-map.d.ts +136 -0
  143. package/dist/table/compile-rule-map.d.ts.map +1 -0
  144. package/dist/table/compile.d.ts +56 -0
  145. package/dist/table/compile.d.ts.map +1 -0
  146. package/dist/table/duplication-hook.d.ts +32 -0
  147. package/dist/table/duplication-hook.d.ts.map +1 -0
  148. package/dist/table/emit-assembly.d.ts +139 -0
  149. package/dist/table/emit-assembly.d.ts.map +1 -0
  150. package/dist/table/emit.d.ts +113 -0
  151. package/dist/table/emit.d.ts.map +1 -0
  152. package/dist/table/encode-baseline.d.ts +16 -0
  153. package/dist/table/encode-baseline.d.ts.map +1 -0
  154. package/dist/table/encode.d.ts +71 -0
  155. package/dist/table/encode.d.ts.map +1 -0
  156. package/dist/table/exec-baseline.d.ts +9 -0
  157. package/dist/table/exec-baseline.d.ts.map +1 -0
  158. package/dist/table/exec.d.ts +72 -0
  159. package/dist/table/exec.d.ts.map +1 -0
  160. package/dist/table/fold.d.ts +25 -0
  161. package/dist/table/fold.d.ts.map +1 -0
  162. package/dist/table/index.cjs +11463 -0
  163. package/dist/table/index.cjs.map +6 -0
  164. package/dist/table/index.d.ts +100 -0
  165. package/dist/table/index.d.ts.map +1 -0
  166. package/dist/table/index.js +11440 -0
  167. package/dist/table/index.js.map +6 -0
  168. package/dist/table/inspect.d.ts +17 -0
  169. package/dist/table/inspect.d.ts.map +1 -0
  170. package/dist/table/ops.d.ts +453 -0
  171. package/dist/table/ops.d.ts.map +1 -0
  172. package/dist/table/program.d.ts +496 -0
  173. package/dist/table/program.d.ts.map +1 -0
  174. package/dist/table/run-support.d.ts +38 -0
  175. package/dist/table/run-support.d.ts.map +1 -0
  176. package/dist/{compiler/scannable-run.d.ts → table/scan-shapes.d.ts} +14 -13
  177. package/dist/table/scan-shapes.d.ts.map +1 -0
  178. package/dist/table/site-labels.d.ts +58 -0
  179. package/dist/table/site-labels.d.ts.map +1 -0
  180. package/dist/table/stamp.d.ts +70 -0
  181. package/dist/table/stamp.d.ts.map +1 -0
  182. package/dist/types.d.ts +80 -24
  183. package/dist/types.d.ts.map +1 -1
  184. package/dist/version.d.ts +1 -1
  185. package/package.json +26 -2
  186. package/src/analysis/choice-cost-gate.ts +359 -0
  187. package/src/analysis/choice-cost-render.ts +293 -0
  188. package/src/analysis/choice-cost.ts +1008 -0
  189. package/src/analysis/commitment.ts +557 -0
  190. package/src/analysis/corpus.ts +130 -0
  191. package/src/analysis/diagnose-render.ts +625 -0
  192. package/src/analysis/diagnose.ts +317 -0
  193. package/src/analysis/diagnostics.ts +33 -0
  194. package/src/analysis/duplication.ts +1955 -0
  195. package/src/analysis/fix-render.ts +217 -0
  196. package/src/analysis/fix.ts +669 -0
  197. package/src/analysis/format-number.ts +31 -0
  198. package/src/analysis/gating.ts +792 -0
  199. package/src/analysis/grammar.ts +72 -0
  200. package/src/analysis/rebuild.ts +287 -0
  201. package/src/analysis/terminal.ts +336 -0
  202. package/src/cli/index.ts +413 -0
  203. package/src/combinators/adjacency.ts +171 -0
  204. package/src/combinators/attempt.ts +41 -0
  205. package/src/combinators/case-fold.ts +90 -0
  206. package/src/combinators/choice.ts +466 -0
  207. package/src/combinators/completions.ts +64 -0
  208. package/src/combinators/dispatch.ts +358 -0
  209. package/src/combinators/expect.ts +159 -0
  210. package/src/combinators/first-set.ts +348 -0
  211. package/src/combinators/gate.ts +50 -0
  212. package/src/combinators/grammar.ts +272 -0
  213. package/src/combinators/keywords.ts +145 -0
  214. package/src/combinators/literal.ts +102 -0
  215. package/src/combinators/map.ts +106 -0
  216. package/src/combinators/node.ts +345 -0
  217. package/src/combinators/not.ts +55 -0
  218. package/src/combinators/parser.ts +266 -0
  219. package/src/combinators/peek.ts +63 -0
  220. package/src/combinators/probe.ts +25 -0
  221. package/src/combinators/ref.ts +109 -0
  222. package/src/combinators/regex.ts +170 -0
  223. package/src/combinators/repeat.ts +561 -0
  224. package/src/combinators/scanTo.ts +393 -0
  225. package/src/combinators/sequence.ts +237 -0
  226. package/src/combinators/token.ts +120 -0
  227. package/src/combinators/trivia-boundary.ts +48 -0
  228. package/src/combinators/trivia-skip.ts +852 -0
  229. package/src/combinators/withCtx.ts +45 -0
  230. package/src/compiler/build-arity.ts +330 -0
  231. package/src/compiler/compile-linkable-table.ts +209 -0
  232. package/src/compiler/degradation.ts +266 -0
  233. package/src/compiler/fields.ts +191 -0
  234. package/src/compiler/grammar-coverage-ids.ts +129 -0
  235. package/src/compiler/ir-serialize.ts +615 -0
  236. package/src/compiler/linker.ts +954 -0
  237. package/src/compiler/token-alphabet.ts +209 -0
  238. package/src/compiler/token-dispatch.ts +353 -0
  239. package/src/compiler/token-scanner.ts +318 -0
  240. package/src/compiler/value-usage.ts +147 -0
  241. package/src/coverage.ts +383 -0
  242. package/src/cst/capture-buffer.ts +297 -0
  243. package/src/cst/host-mode.ts +69 -0
  244. package/src/cst/reflection-attach.ts +11 -0
  245. package/src/cst/reflection-symbols.ts +9 -0
  246. package/src/cst/reflection.ts +149 -0
  247. package/src/cst/relative-spans.ts +207 -0
  248. package/src/cst/root-trivia-scope.ts +30 -0
  249. package/src/cst/trivia-charscan.ts +312 -0
  250. package/src/cst/trivia-entries.ts +285 -0
  251. package/src/cst/trivia-index.ts +131 -0
  252. package/src/cst/trivia-kinds.ts +358 -0
  253. package/src/cst/types.ts +76 -0
  254. package/src/cst/walk.ts +101 -0
  255. package/src/functional/doc.ts +959 -0
  256. package/src/functional/run-tabled.ts +153 -0
  257. package/src/functional/run.ts +558 -0
  258. package/src/grammar-metadata.ts +2 -0
  259. package/src/index.ts +189 -0
  260. package/src/language-service/index.ts +221 -0
  261. package/src/line-index.ts +131 -0
  262. package/src/oracle/digest.ts +620 -0
  263. package/src/oracle/index.ts +55 -0
  264. package/src/parse-context.ts +91 -0
  265. package/src/plugin/direct-builder-static.ts +102 -0
  266. package/src/plugin/evaluator.ts +1505 -0
  267. package/src/plugin/free-identifiers.ts +338 -0
  268. package/src/plugin/index.ts +2281 -0
  269. package/src/plugin/reducer-resolver.ts +606 -0
  270. package/src/recovery/scan.ts +155 -0
  271. package/src/regex/classes.ts +183 -0
  272. package/src/regex/first-set.ts +316 -0
  273. package/src/run/index.ts +31 -0
  274. package/src/spec/ebnf.ts +128 -0
  275. package/src/spec/index.ts +54 -0
  276. package/src/spec/model.ts +636 -0
  277. package/src/spec/railroad-lib.ts +559 -0
  278. package/src/spec/railroad.ts +256 -0
  279. package/src/table/assemble.ts +3006 -0
  280. package/src/table/cell.ts +42 -0
  281. package/src/table/child-slots.ts +113 -0
  282. package/src/table/compile-rule-map.ts +336 -0
  283. package/src/table/compile.ts +244 -0
  284. package/src/table/duplication-hook.ts +89 -0
  285. package/src/table/emit-assembly.ts +1777 -0
  286. package/src/table/emit.ts +429 -0
  287. package/src/table/encode-baseline.ts +340 -0
  288. package/src/table/encode.ts +1569 -0
  289. package/src/table/exec-baseline.ts +537 -0
  290. package/src/table/exec.ts +1680 -0
  291. package/src/table/fold.ts +38 -0
  292. package/src/table/index.ts +108 -0
  293. package/src/table/inspect.ts +52 -0
  294. package/src/table/ops.ts +467 -0
  295. package/src/table/program.ts +876 -0
  296. package/src/table/run-support.ts +66 -0
  297. package/src/table/scan-shapes.ts +1578 -0
  298. package/src/table/site-labels.ts +228 -0
  299. package/src/table/stamp.ts +229 -0
  300. package/src/types.ts +563 -0
  301. package/src/version.ts +16 -0
  302. package/dist/compiler/codegen.d.ts +0 -334
  303. package/dist/compiler/codegen.d.ts.map +0 -1
  304. package/dist/compiler/inline-build.d.ts +0 -11
  305. package/dist/compiler/inline-build.d.ts.map +0 -1
  306. package/dist/compiler/inline-callback.d.ts +0 -21
  307. package/dist/compiler/inline-callback.d.ts.map +0 -1
  308. package/dist/compiler/line-index.d.ts +0 -2
  309. package/dist/compiler/line-index.d.ts.map +0 -1
  310. package/dist/compiler/module-hoist.d.ts +0 -106
  311. package/dist/compiler/module-hoist.d.ts.map +0 -1
  312. package/dist/compiler/scannable-run.d.ts.map +0 -1
  313. package/dist/compiler/scannable-terminal.d.ts +0 -23
  314. package/dist/compiler/scannable-terminal.d.ts.map +0 -1
  315. package/dist/compiler/trivia-fast-path.d.ts +0 -38
  316. package/dist/compiler/trivia-fast-path.d.ts.map +0 -1
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/combinators/first-set.ts", "../../src/combinators/ref.ts", "../../src/compiler/value-usage.ts", "../../src/line-index.ts", "../../src/cst/capture-buffer.ts", "../../src/cst/trivia-kinds.ts", "../../src/combinators/grammar.ts", "../../src/cst/reflection.ts", "../../src/combinators/parser.ts", "../../src/recovery/scan.ts", "../../src/combinators/expect.ts", "../../src/regex/classes.ts", "../../src/combinators/trivia-skip.ts", "../../src/combinators/choice.ts", "../../src/analysis/duplication.ts", "../../src/combinators/probe.ts", "../../src/combinators/literal.ts", "../../src/combinators/regex.ts", "../../src/combinators/sequence.ts", "../../src/combinators/repeat.ts", "../../src/combinators/map.ts", "../../src/combinators/scanTo.ts", "../../src/compiler/degradation.ts", "../../src/cst/trivia-entries.ts", "../../src/compiler/scannable-run.ts", "../../src/compiler/trivia-fast-path.ts", "../../src/compiler/build-arity.ts", "../../src/compiler/inline-build.ts", "../../src/compiler/fields.ts", "../../src/combinators/case-fold.ts", "../../src/combinators/keywords.ts", "../../src/combinators/dispatch.ts", "../../src/combinators/attempt.ts", "../../src/combinators/not.ts", "../../src/combinators/peek.ts", "../../src/combinators/node.ts", "../../src/combinators/token.ts", "../../src/combinators/withCtx.ts", "../../src/compiler/ir-serialize.ts", "../../src/compiler/linker.ts", "../../src/spec/model.ts", "../../src/spec/ebnf.ts", "../../src/spec/railroad-lib.ts", "../../src/spec/railroad.ts", "../../src/spec/index.ts"],
4
- "sourcesContent": ["import type { CharRange, FirstSet, Combinator, ParserDef } from '../types.ts'\n\n/**\n * Resolve a NAMED cross-artifact rule reference (`g.Foo`) whose own thunk does not\n * resolve \u2014 the shared-shape hole, bound by name at fuse time.\n *\n * A shape module compiles `Ratio: sequence(g.Value, \u2026)` without defining `Value`, so\n * that `lazy`'s thunk throws and every first-set through it degrades to `any`. Once\n * the shape is FUSED with a dialect that defines `Value`, the hole is bound \u2014 pass a\n * resolver over the fused winner map and the first-set is the real one.\n *\n * Only NAMED refs are resolvable: an unnamed `ref()` that was never `.define()`d\n * carries no name for anyone to bind, so it stays `any`.\n */\nexport type RefResolver = (name: string) => Combinator<unknown> | undefined\n\n/** The `resolve`-supplied target for an unresolvable NAMED lazy, if any. */\nfunction resolveNamedRef(p: Combinator<unknown>, resolve: RefResolver | undefined): Combinator<unknown> | undefined {\n if (resolve === undefined) return undefined\n const name = (p as unknown as { _ruleName?: string })._ruleName\n return name === undefined ? undefined : resolve(name)\n}\n\nexport function union(a: FirstSet, b: FirstSet): FirstSet {\n if (a.kind === 'any' || b.kind === 'any') return { kind: 'any' }\n if (a.kind === 'empty') return b\n if (b.kind === 'empty') return a\n return { kind: 'ranges', ranges: mergeRanges([...a.ranges, ...b.ranges]) }\n}\n\nexport function intersects(a: FirstSet, b: FirstSet): boolean {\n if (a.kind === 'any' || b.kind === 'any') return true\n if (a.kind === 'empty' || b.kind === 'empty') return false\n for (const ra of a.ranges) {\n for (const rb of b.ranges) {\n if (ra.lo <= rb.hi && rb.lo <= ra.hi) return true\n }\n }\n return false\n}\n\nexport function fromChar(code: number): FirstSet {\n return { kind: 'ranges', ranges: [{ lo: code, hi: code }] }\n}\n\n/**\n * True when `combinator`'s first set admits the code point at `input[pos]` (or its\n * first set is `any`). The runtime counterpart of codegen's `firstSetCond` guard \u2014\n * used by the interpreter's first-set fail-fast in `optional`/`many`/`attempt`/\n * `node` to reject a doomed sub-parse before doing any setup. Returns `false` at EOF.\n */\nexport function startsFirstSet(combinator: Combinator<unknown>, input: string, pos: number): boolean {\n const fs = combinator._meta.firstSet\n if (fs.kind === 'any') return true\n if (fs.kind === 'empty') return false\n const code = input.codePointAt(pos)\n if (code === undefined) return false\n for (const r of fs.ranges) if (code >= r.lo && code <= r.hi) return true\n return false\n}\n\nexport function fromRange(lo: number, hi: number): FirstSet {\n return { kind: 'ranges', ranges: [{ lo, hi }] }\n}\n\nexport function any(): FirstSet {\n return { kind: 'any' }\n}\n\nexport function empty(): FirstSet {\n return { kind: 'empty' }\n}\n\n/**\n * Can this parser SUCCEED consuming zero characters (nullable / matches-empty)?\n * Used to compute a sound sequence first-set: a nullable leading term lets the\n * NEXT term's first chars start the whole sequence. MUST err toward `true` when\n * unsure \u2014 over-estimating nullability only widens the (over-approximated) first\n * set, which stays sound; under-estimating would drop valid start chars and make\n * first-char dispatch skip a matching arm.\n */\nexport function matchesEmpty(\n p: Combinator<unknown>,\n seen: Set<Combinator<unknown>> = new Set(),\n resolve?: RefResolver,\n): boolean {\n // Cycle guard: a mutually-nullable ref cycle (e.g. `A = oneOrMore(B); B = oneOrMore(A)`)\n // would recurse forever. Treat a re-entered node as nullable \u2014 the safe (`true`)\n // default, consistent with the err-toward-true contract below.\n if (seen.has(p)) return true\n seen.add(p)\n const me = (c: Combinator<unknown>): boolean => matchesEmpty(c, seen, resolve)\n const d = p._def as ParserDef\n switch (d.tag) {\n case 'literal': return d.value.length === 0\n case 'keywords': return false\n // The routed token itself is the selector's match, never empty; a fallback can be.\n case 'routed': return d.fallback === undefined ? false : me(d.fallback)\n case 'regex':\n // Precise: does the pattern admit a zero-length match? (`a*`, `a?`, `a|`, \u2026)\n try { const m = new RegExp(d.source).exec(''); return m != null && m[0] === '' }\n catch { return true }\n case 'many':\n case 'optional':\n case 'not':\n case 'peek': return true // zero repetitions / absent / lookahead\n // Default `sepBy` is `(item (sep item)*)?` \u2014 it MATCHES THE EMPTY STRING.\n // Any `min >= 1` requires that many ITEMS, so it is nullable only when the\n // item is. (Keying this off `min === 1` reported every `{ min: 2 }` list as\n // nullable \u2014 safe, but wrong, and it put a bogus `nullable-prefix` note on\n // the gating diagnostic for a list that can never match empty.)\n case 'sepBy': return d.min >= 1 ? me(d.parser) : true\n case 'oneOrMore': return me(d.parser)\n case 'sequence': return d.parsers.every(me)\n case 'choice':\n return d.parsers.some(me)\n case 'dispatch':\n return me(d.selector)\n case 'transform':\n case 'label':\n case 'trivia':\n case 'token':\n case 'leaf':\n case 'expect':\n case 'withCtx':\n case 'node':\n case 'grammar':\n case 'recover': return me(d.parser)\n case 'skip': return me(d.main)\n case 'lazy':\n try { return me(d.thunk()) }\n catch { const t = resolveNamedRef(p, resolve); return t ? me(t) : true }\n default: return true // scanTo / guard / unknown \u2192 assume nullable (safe)\n }\n}\n\n/**\n * A ZERO-WIDTH ASSERTION never consumes input, so it contributes NOTHING to a\n * sequence's first-set \u2014 the first consumed char comes from the following\n * non-nullable term. `not(X)` reports `firstSet: any()` (it cannot know what it\n * forbids), which would otherwise poison a sequence's first-set to `any` and kill\n * first-char dispatch of the whole arm. Skipping its contribution is SOUND: a\n * first-set used for dispatch gating must stay a correct SUPERSET of the rule's\n * true first chars, and `not(X) Y` can only start with a char in firstSet(Y) \u2014 the\n * assertion only NARROWS the language (it forbids a full match ahead), it never\n * widens the set of possible first chars beyond Y. So firstSet(Y) is a sound (and\n * tighter) superset.\n *\n * The POSITIVE lookahead `peek(X)` is zero-width too, but it is NOT in this\n * predicate: unlike `not`, it knows what it requires, so its first-set is a real\n * constraint that must be INTERSECTED into the sequence's set rather than dropped\n * (see `isPositiveLookahead` and `sequenceFirstSet`).\n */\nexport function isZeroWidthAssertion(p: Combinator<unknown>): boolean {\n return (p._def as ParserDef).tag === 'not'\n}\n\n/**\n * A POSITIVE zero-width assertion (`peek(X)`). It consumes nothing, so like\n * `not(X)` it does not contribute a first char of its own \u2014 but it does REQUIRE\n * that X match here, so `peek(X) Y` can only start with a char in\n * firstSet(X) \u2229 firstSet(Y). That intersection is what makes a leading `peek()`\n * gate its choice arm; `not(not(X))`, the only previous spelling, reports `any()`\n * and poisons the dispatch instead.\n *\n * Soundness: first-sets are SUPERSETS of the true first chars, and\n * (A \u2287 a) \u2227 (B \u2287 b) \u21D2 A \u2229 B \u2287 a \u2229 b \u2014 so intersecting stays a superset and can\n * never skip a real match. A NULLABLE body succeeds on the empty string and\n * therefore constrains nothing; `peek()` reports `any()` in that case, which the\n * intersection treats as \"no constraint\".\n */\nexport function isPositiveLookahead(p: Combinator<unknown>): boolean {\n return (p._def as ParserDef).tag === 'peek'\n}\n\n/** Intersect a lookahead constraint into an accumulator; `any` = no constraint. */\nfunction narrowBy(acc: FirstSet | null, constraint: FirstSet): FirstSet | null {\n if (constraint.kind === 'any') return acc\n if (acc === null) return constraint\n if (acc.kind === 'any') return constraint\n if (acc.kind === 'empty' || constraint.kind === 'empty') return { kind: 'empty' }\n const ranges: CharRange[] = []\n for (const a of acc.ranges) for (const b of constraint.ranges) {\n const lo = Math.max(a.lo, b.lo)\n const hi = Math.min(a.hi, b.hi)\n if (lo <= hi) ranges.push({ lo, hi })\n }\n return ranges.length === 0 ? { kind: 'empty' } : { kind: 'ranges', ranges }\n}\n\n/**\n * Apply the accumulated `peek()` constraints to a sequence's first-set. When the\n * consuming terms contributed NOTHING (the sequence is all zero-width/nullable,\n * e.g. a bare `peek(X)` arm), the assertion IS the first-set: the sequence can\n * only succeed \u2014 even zero-width \u2014 where X matches.\n */\nfunction applyAssertion(fs: FirstSet, assertion: FirstSet | null): FirstSet {\n if (assertion === null) return fs\n if (fs.kind === 'empty') return assertion\n return narrowBy(fs, assertion) ?? fs\n}\n\n/**\n * First-set of a sequence: union each term's first-set through the NULLABLE\n * PREFIX \u2014 a leading `optional(\u2026)` / `many(\u2026)` / nullable term can be skipped, so\n * the sequence can begin with a LATER term's first char. Stop at (and include)\n * the first non-nullable term. (`parsers[0].firstSet` alone under-approximates\n * and silently breaks first-char dispatch \u2014 see the InterpolatedSelector bug.)\n * A leading zero-width assertion (`not(\u2026)`) is nullable but contributes NOTHING to\n * the first-set (see `isZeroWidthAssertion`) \u2014 its `any` must not poison the union.\n */\nexport function sequenceFirstSet(parsers: readonly Combinator<unknown>[]): FirstSet {\n let fs: FirstSet = empty()\n let assertion: FirstSet | null = null\n for (const p of parsers) {\n if (isPositiveLookahead(p)) {\n // Zero-width but CONSTRAINING: intersect, keep scanning (it consumes nothing).\n assertion = narrowBy(assertion, p._meta.firstSet)\n continue\n }\n if (!isZeroWidthAssertion(p)) fs = union(fs, p._meta.firstSet)\n if (!matchesEmpty(p)) return applyAssertion(fs, assertion)\n }\n return applyAssertion(fs, assertion)\n}\n\n/**\n * Deep first-set that RESOLVES `lazy`/`ref` combinators to their targets. The\n * combinators bake `_meta.firstSet` at CONSTRUCTION, when a `ref()` still reads\n * `any()` (define() never updates it) \u2014 so a `choice`/`sequence` built over refs\n * caches a spuriously-`any` first-set and loses first-char dispatch. Recomputing\n * here, following refs, recovers the real set. Over-approximates on cycles /\n * unknown constructs (returns `any`) \u2014 always sound: a wider set only means \"try\n * this arm for more first chars\", never skips a real match.\n *\n * SOUND ONLY where refs are FINAL (monolithic compile). Under compose OVERRIDE a\n * referenced rule can be replaced with a WIDER first-set, so a baked deep set\n * would wrongly skip valid input \u2014 the compose path defers dispatch to fuse time.\n *\n * `resolve` binds NAMED cross-artifact holes (`g.Foo`) against a fused winner map \u2014\n * see `RefResolver`. Diagnostic-only today: it is what lets the gating analysis ask\n * the question at the site where the hole actually HAS an answer.\n */\nexport function firstSetOf(\n p: Combinator<unknown>,\n seen: Set<Combinator<unknown>> = new Set(),\n resolve?: RefResolver,\n): FirstSet {\n if (seen.has(p)) return any() // cycle \u2192 any (safe over-approximation)\n seen.add(p)\n const fs = (c: Combinator<unknown>): FirstSet => firstSetOf(c, seen, resolve)\n const empties = (c: Combinator<unknown>): boolean => matchesEmpty(c, new Set(), resolve)\n const d = p._def as ParserDef\n switch (d.tag) {\n case 'literal':\n case 'regex':\n case 'keywords': return p._meta.firstSet // terminals: no refs, cached set is exact\n case 'dispatch': return fs(d.selector)\n case 'lazy':\n try { return fs(d.thunk()) }\n catch { const t = resolveNamedRef(p, resolve); return t ? fs(t) : any() }\n case 'choice': {\n let out: FirstSet = empty()\n for (const arm of d.parsers) out = union(out, fs(arm))\n return out\n }\n case 'sequence': {\n // Union through the nullable prefix (a leading nullable term lets a later\n // term's first chars start the sequence) \u2014 ref-resolving `sequenceFirstSet`.\n // A leading zero-width assertion (`not`) contributes nothing (its `any` would\n // poison the union) but is still nullable, so keep scanning past it. A\n // positive `peek()` is zero-width AND constraining \u2192 intersect.\n let out: FirstSet = empty()\n let assertion: FirstSet | null = null\n for (const term of d.parsers) {\n if (isPositiveLookahead(term)) { assertion = narrowBy(assertion, fs(term)); continue }\n if (!isZeroWidthAssertion(term)) out = union(out, fs(term))\n if (!empties(term)) return applyAssertion(out, assertion)\n }\n return applyAssertion(out, assertion)\n }\n case 'peek': {\n // Deep-resolve the body: a `ref()` reads `any()` at CONSTRUCTION, so the\n // shallow `_meta.firstSet` baked into the assertion would lose the gate.\n const inner = d.parser\n return empties(inner) ? any() : fs(inner)\n }\n case 'oneOrMore':\n case 'many':\n case 'optional':\n case 'transform':\n case 'label':\n case 'trivia':\n case 'token':\n case 'leaf':\n case 'node':\n case 'grammar':\n case 'expect': return fs(d.parser)\n case 'sepBy': return fs(d.parser) // both min 0 and min 1 start with the item\n case 'skip': return fs(d.main)\n default: return p._meta.firstSet // not / scanTo / guard / withCtx / recover / unknown\n }\n}\n\nfunction mergeRanges(ranges: CharRange[]): CharRange[] {\n if (ranges.length === 0) return []\n const sorted = [...ranges].sort((a, b) => a.lo - b.lo)\n // Always copy \u2014 never alias input objects\n const out: CharRange[] = [{ lo: sorted[0]!.lo, hi: sorted[0]!.hi }]\n for (let i = 1; i < sorted.length; i++) {\n const top = out[out.length - 1]!\n const cur = sorted[i]!\n if (cur.lo <= top.hi + 1) {\n if (cur.hi > top.hi) top.hi = cur.hi\n } else {\n out.push({ lo: cur.lo, hi: cur.hi })\n }\n }\n return out\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { any } from './first-set.ts'\n\n/**\n * Create a forward-declared parser slot for mutually recursive grammars.\n *\n * Because JS evaluates arguments eagerly, you can't reference a variable\n * before it's declared. ref() creates a placeholder you fill in later:\n *\n * const value = ref<JSONValue>()\n * const array = transform(sequence(literal('['), sepBy(value, literal(',')), literal(']')), ...)\n * const object = transform(sequence(literal('{'), sepBy(pair, literal(',')), literal('}')), ...)\n * value.define(choice(object, array, string, number, bool, nullVal))\n *\n * Unlike lazy(() => x), you use the ref directly \u2014 no wrapping at each call site.\n */\nexport function ref<T>(): Combinator<T> & { define(p: Combinator<T>): void } {\n let resolved: Combinator<T> | null = null\n\n const meta: ParserMeta = {\n firstSet: any(),\n canMatchNewline: true,\n isTrivia: false,\n }\n\n const slot = {\n _tag: 'lazy' as const,\n _meta: meta,\n _def: {\n tag: 'lazy' as const,\n thunk: () => {\n if (!resolved) throw new Error('ref<T>() used before .define() was called')\n return resolved as Combinator<unknown>\n },\n },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T> {\n if (!resolved) throw new Error('ref<T>() used before .define() was called')\n return resolved.parse(input, pos, ctx)\n },\n define(p: Combinator<T>): void {\n if (resolved) throw new Error('ref<T>() already defined')\n resolved = p\n meta.firstSet = p._meta.firstSet\n meta.canMatchNewline = p._meta.canMatchNewline\n meta.isTrivia = p._meta.isTrivia\n if (p._meta.triviaKindLabels !== undefined) meta.triviaKindLabels = p._meta.triviaKindLabels\n else delete meta.triviaKindLabels\n if (p._meta.disjoint !== undefined) meta.disjoint = p._meta.disjoint\n else delete meta.disjoint\n },\n }\n\n return slot\n}\n", "import type { Combinator, ParserDef } from '../types.ts'\n\n/**\n * Dead-value analysis (shared by the interpreter and codegen). A container\n * combinator \u2014 `many` / `oneOrMore` / `optional` / `sequence` \u2014 builds an\n * aggregate value (array / tuple / nullable). Under a `node()`, the node builds\n * from the *captured children*, never from that aggregate, so the aggregate is\n * built and thrown away. This pass marks those containers `valueUnused`; the\n * interpreter and the emitter then skip building the aggregate entirely (the\n * elements still parse and self-capture, so trees are identical).\n *\n * Walks ONE combinator tree (a single rule body, or a standalone root), stopping\n * at `lazy`/ref boundaries \u2014 other rules are analyzed on their own root. Starts\n * `consumed = true` (a rule's own value is assumed read \u2014 conservative); `node()`\n * flips it to false for its inner parser; `transform` forces it true (its map fn\n * reads the value). Sharing-safe: any `consumed = true` visit wins and is sticky,\n * so a container reachable from BOTH a consuming and a non-consuming site keeps\n * its aggregate (never wrongly elided).\n *\n * Soundness: a container is marked ONLY when every path to it passes through a\n * `node()` (value-discarding) without an intervening value-reader \u2014 i.e. its\n * aggregate provably isn't observed. Idempotent; safe to re-run.\n */\nexport function markUnusedValues(root: Combinator<unknown>): void {\n const seenConsumed = new WeakSet<Combinator<unknown>>()\n const seenUnconsumed = new WeakSet<Combinator<unknown>>()\n\n const mark = (def: { valueUnused?: boolean }, consumed: boolean): void => {\n if (consumed) def.valueUnused = false\n else if (def.valueUnused !== false) def.valueUnused = true\n }\n\n const visit = (c: Combinator<unknown>, consumed: boolean): void => {\n const seen = consumed ? seenConsumed : seenUnconsumed\n if (seen.has(c)) return\n seen.add(c)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion\n const def = c._def as ParserDef & { valueUnused?: boolean }\n\n switch (def.tag) {\n case 'many':\n case 'oneOrMore':\n mark(def, consumed)\n visit(def.parser, consumed)\n return\n case 'optional':\n // `optional` returns `inner | null` \u2014 no aggregate array/tuple to elide, so\n // it carries no valueUnused flag. Still descend so an inner many/sequence\n // under a node() is analyzed (it benefits even when its optional wrapper\n // doesn't).\n visit(def.parser, consumed)\n return\n case 'sequence':\n mark(def, consumed)\n for (const p of def.parsers) visit(p, consumed)\n return\n case 'choice':\n // value is the winning arm's value \u2014 propagate consumed to each arm.\n for (const p of def.parsers) visit(p, consumed)\n return\n case 'dispatch':\n visit(def.selector, consumed)\n for (const entry of def.cases) visit(entry.parser, consumed)\n if (def.matchers) for (const entry of def.matchers) visit(entry.parser, consumed)\n if (def.otherwise) visit(def.otherwise, consumed)\n return\n case 'node':\n // builds from captured children, NOT the inner parser value.\n visit(def.parser, false)\n return\n case 'transform':\n // the map fn reads the value \u2192 always consumed.\n visit(def.parser, true)\n return\n case 'field':\n // the field capture records the parsed value \u2192 always consumed.\n visit(def.parser, true)\n return\n case 'skip':\n visit(def.main, consumed) // returns main's value\n visit(def.skipped, false) // skipped value is discarded\n return\n case 'sepBy':\n // sepBy is NOT elided (no valueUnused), so it always builds its array and\n // therefore always reads each item's value \u2014 regardless of whether sepBy's\n // OWN value is observed. Item parser is unconditionally consumed.\n visit(def.parser, true)\n visit(def.separator, false)\n return\n case 'not':\n case 'peek':\n visit(def.parser, false) // lookahead \u2014 value never observed\n return\n case 'grammar':\n visit(def.parser, consumed)\n if (def.triviaParser) visit(def.triviaParser, false)\n return\n case 'recover':\n visit(def.parser, consumed)\n visit(def.sentinel, false)\n return\n case 'token':\n // token() returns the matched source slice, not the wrapped parser value.\n // Its child still parses and captures one outer token leaf; inner aggregate\n // values such as sequence tuples are unobserved and can be elided.\n visit(def.parser, false)\n return\n case 'label':\n case 'trivia':\n case 'attempt':\n case 'withCtx':\n case 'expect':\n visit(def.parser, consumed) // single-child pass-through wrappers\n return\n case 'leaf':\n // The reducer observes the complete inner value even when its own result\n // is immediately captured by a node().\n visit(def.parser, true)\n return\n case 'lazy':\n // An INNER ref boundary \u2014 a distinct rule, analyzed on its own root. Don't\n // descend (and never call thunk(): an external ref would throw). A ref at\n // the ROOT of a rule is different \u2014 it wraps this rule's own body \u2014 and is\n // resolved by resolveRoot() before the walk starts.\n return\n default:\n // literal / regex / keywords / guard / scanTo / unknown \u2014 no container child.\n return\n }\n }\n\n // A rule's root is often a `ref()`/`lazy` wrapping the real body \u2014 that is how\n // rules() and compose() store forward-referenced and composed rules. Walking\n // that lazy directly hits the boundary case and marks nothing, so resolve a\n // ROOT lazy to its defined body first. Inner lazies (references to OTHER rules)\n // stay boundaries \u2014 each rule is analyzed from its own resolved root.\n const resolveRoot = (c: Combinator<unknown>): Combinator<unknown> => {\n const guard = new Set<Combinator<unknown>>()\n let cur = c\n while (!guard.has(cur)) {\n const d = cur._def as ParserDef\n if (d.tag !== 'lazy') return cur\n guard.add(cur)\n try { cur = d.thunk() } catch { return c } // undefined ref \u2192 leave as-is\n }\n return cur\n }\n\n visit(resolveRoot(root), true)\n}\n", "import type { Span } from './types.ts'\n\n/**\n * Precomputed index of newline positions for O(log n) offset->line/col lookup.\n * lineStarts[i] is the byte offset of the first character on line i+1.\n */\nexport type LineIndex = { lineStarts: number[] }\ntype LineTrackingContext = {\n trackLines?: boolean | undefined\n _lineIndex?: LineIndex | undefined\n _lineStarts?: number[] | undefined\n _lineScannedTo?: number | undefined\n}\n\nexport function createLineIndex(): LineIndex {\n return { lineStarts: [0] }\n}\n\nexport function buildLineIndex(input: string): LineIndex {\n const lineStarts = [0]\n for (let i = 0; i < input.length; i++) {\n if (input.charCodeAt(i) === 10) lineStarts.push(i + 1)\n }\n return { lineStarts }\n}\n\n/**\n * Record newline offsets for a matched range. Intended for optional parsers that\n * collect line starts while they consume terminals. The collector is deliberately\n * append-only: speculative parses never roll it back. Normalize once at the\n * driver boundary before doing offset->line/column lookup.\n */\nexport function recordLineRange(index: LineIndex, input: string, start: number, end: number): void {\n const lineStarts = index.lineStarts\n for (let i = start; i < end; i++) {\n if (input.charCodeAt(i) === 10) lineStarts.push(i + 1)\n }\n}\n\n/**\n * Records newlines from the context high-water mark through `end`. The start\n * argument is only a caller hint: append-only tracking uses `_lineScannedTo` so\n * overlapping calls can backfill gaps without double-scanning committed ranges.\n */\nexport function recordLineRangeFromContext(\n ctx: LineTrackingContext,\n input: string,\n _startHint: number,\n end: number,\n): void {\n if (!ctx.trackLines) return\n const from = ctx._lineScannedTo ?? 0\n if (end <= from) return\n const index = ctx._lineIndex ?? (ctx._lineStarts ? { lineStarts: ctx._lineStarts } : undefined)\n if (!index) return\n recordLineRange(index, input, from, end)\n ctx._lineScannedTo = end\n}\n\nexport function normalizeLineIndex(index: LineIndex): LineIndex {\n const starts = index.lineStarts\n starts.sort((a, b) => a - b)\n let write = 0\n for (let read = 0; read < starts.length; read++) {\n const value = starts[read]!\n if (write === 0 || starts[write - 1] !== value) starts[write++] = value\n }\n starts.length = write\n if (starts.length === 0 || starts[0] !== 0) starts.unshift(0)\n return index\n}\n\nexport function offsetToLineCol(\n index: LineIndex,\n offset: number\n): { line: number; col: number } {\n const { lineStarts } = index\n let lo = 0\n let hi = lineStarts.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (lineStarts[mid]! <= offset) lo = mid\n else hi = mid - 1\n }\n return { line: lo + 1, col: offset - lineStarts[lo]! + 1 }\n}\n\n/** Fills startLine/startColumn/endLine/endColumn on a span in-place. */\nexport function annotateSpan(span: Span, index: LineIndex): Span {\n const s = offsetToLineCol(index, span.start)\n const e = offsetToLineCol(index, span.end)\n return {\n ...span,\n startLine: s.line,\n startColumn: s.col,\n endLine: e.line,\n endColumn: e.col,\n }\n}\n\nexport function annotateSpanFromLineContext(\n span: Span,\n ctx: LineTrackingContext,\n): Span {\n if (!ctx.trackLines) return span\n const index = ctx._lineIndex ?? (ctx._lineStarts ? { lineStarts: ctx._lineStarts } : undefined)\n return index ? annotateSpan(span, index) : span\n}\n\nfunction isSpan(value: unknown): value is Span {\n return !!value\n && typeof value === 'object'\n && typeof (value as { start?: unknown }).start === 'number'\n && typeof (value as { end?: unknown }).end === 'number'\n}\n\n/** Annotate every span-shaped object reachable from a parse result value. */\nexport function annotateTreeSpans<T>(value: T, index: LineIndex, seen: WeakSet<object> = new WeakSet()): T {\n if (!value || typeof value !== 'object') return value\n if (seen.has(value)) return value\n seen.add(value)\n\n const obj = value as Record<string, unknown>\n if (isSpan(obj.span)) obj.span = annotateSpan(obj.span, index)\n\n for (const key of Object.keys(obj)) {\n const child = obj[key]\n if (child && typeof child === 'object') annotateTreeSpans(child, index, seen)\n }\n return value\n}\n", "import type { ParseContext, Span } from '../types.ts'\nimport { annotateSpanFromLineContext } from '../line-index.ts'\n\n/** Lazy per-node capture state \u2014 arrays materialized on first push. */\nexport type CstCaptureBuf = {\n single?: unknown | undefined\n ch?: unknown[] | undefined\n rawSingle?: unknown | undefined\n raw?: unknown[] | undefined\n tl?: number[] | undefined\n}\n\nconst EMPTY: unknown[] = []\nconst EMPTY_TL: number[] = []\n\nexport function cstCaptureActive(ctx: ParseContext): boolean {\n return ctx._cstBuf !== undefined || ctx._cstLeaves !== undefined\n}\n\nexport type CstNodeCaptureSaved = {\n ch: ParseContext['_cstChildren']\n lv: ParseContext['_cstLeaves']\n raw: ParseContext['_cstRawChildren']\n tl: ParseContext['_cstTriviaLog']\n cap: boolean | undefined\n buf: CstCaptureBuf | undefined\n}\n\nexport function beginCstNodeCapture(ctx: ParseContext): CstNodeCaptureSaved {\n const saved: CstNodeCaptureSaved = {\n ch: ctx._cstChildren,\n lv: ctx._cstLeaves,\n raw: ctx._cstRawChildren,\n tl: ctx._cstTriviaLog,\n cap: ctx.captureTrivia,\n buf: ctx._cstBuf,\n }\n ctx._cstBuf = {}\n ctx._cstChildren = undefined\n ctx._cstLeaves = undefined\n ctx._cstRawChildren = undefined\n ctx._cstTriviaLog = undefined\n ctx.captureTrivia = true\n return saved\n}\n\nexport function finishCstBuf(buf: CstCaptureBuf | undefined): {\n children: unknown[]\n rawChildren: unknown[]\n triviaLog: number[]\n} {\n if (!buf) return { children: EMPTY, rawChildren: EMPTY, triviaLog: EMPTY_TL }\n const children = buf.ch ?? (buf.single !== undefined ? [buf.single] : EMPTY)\n const rawChildren = buf.raw ?? (buf.rawSingle !== undefined ? [buf.rawSingle] : EMPTY)\n const triviaLog = buf.tl ?? EMPTY_TL\n return { children, rawChildren, triviaLog }\n}\n\nexport function endCstNodeCapture(\n ctx: ParseContext,\n saved: CstNodeCaptureSaved,\n): { children: unknown[]; rawChildren: unknown[]; triviaLog: number[] } {\n const materialized = finishCstBuf(ctx._cstBuf)\n ctx._cstBuf = saved.buf\n ctx._cstChildren = saved.ch\n ctx._cstLeaves = saved.lv\n ctx._cstRawChildren = saved.raw\n ctx._cstTriviaLog = saved.tl\n ctx.captureTrivia = saved.cap\n return materialized\n}\n\nexport function pushCstLeaf(ctx: ParseContext, leaf: unknown): void {\n if (!ctx.trackLines) {\n pushCstChild(ctx, leaf, leaf)\n return\n }\n const annotated = leaf && typeof leaf === 'object' && (leaf as { span?: unknown }).span\n ? { ...(leaf as Record<string, unknown>), span: annotateSpanFromLineContext((leaf as { span: Span }).span, ctx) }\n : leaf\n pushCstChild(ctx, annotated, annotated)\n}\n\n/** Record a built sub-node into the active collector (children vs rawChildren may differ). */\nexport function pushCstChild(ctx: ParseContext, built: unknown, rawEntry: unknown): void {\n const b = ctx._cstBuf\n if (b) {\n if (b.ch) b.ch.push(built)\n else if (b.single !== undefined) { b.ch = [b.single, built]; b.single = undefined }\n else b.single = built\n\n if (b.raw) b.raw.push(rawEntry)\n else if (b.rawSingle !== undefined) { b.raw = [b.rawSingle, rawEntry]; b.rawSingle = undefined }\n else b.rawSingle = rawEntry\n return\n }\n if (ctx._cstChildren) ctx._cstChildren.push(built)\n else if (ctx._cstLeaves) ctx._cstLeaves.push(built)\n if (ctx._cstRawChildren) ctx._cstRawChildren.push(rawEntry)\n}\n\nexport function cstRawLen(ctx: ParseContext): number {\n const b = ctx._cstBuf\n if (b) {\n if (b.raw) return b.raw.length\n return b.rawSingle !== undefined ? 1 : 0\n }\n return ctx._cstRawChildren?.length ?? 0\n}\n\nexport function cstLeavesLen(ctx: ParseContext): number {\n const b = ctx._cstBuf\n if (b) {\n if (b.ch) return b.ch.length\n return b.single !== undefined ? 1 : 0\n }\n return ctx._cstLeaves?.length ?? 0\n}\n\nexport function cstTlLen(ctx: ParseContext): number {\n const b = ctx._cstBuf\n if (b) return b.tl?.length ?? 0\n return ctx._cstTriviaLog?.length ?? 0\n}\n\nexport type CstRollbackMark = { raw: number; tlog: number; leaves: number; fields: number; errors: number }\n\nexport function saveCstMark(ctx: ParseContext): CstRollbackMark {\n return {\n raw: cstRawLen(ctx),\n tlog: cstTlLen(ctx),\n leaves: cstLeavesLen(ctx),\n fields: ctx._fields?.length ?? 0,\n // Speculative rollback must truncate the flat recovery-error sink in lockstep\n // with the CST leaves: a branch that recovered (pushing a ParseError to\n // ctx._errors AND embedding it as a CST child via captureError) then failed\n // must remove BOTH, or the flat error survives as a GHOST that a tree walk\n // can't see (flat run().errors would disagree with the embedded set).\n errors: ctx._errors?.length ?? 0,\n }\n}\n\nfunction rollbackBufList(\n b: CstCaptureBuf,\n keyMulti: 'ch' | 'raw',\n keySingle: 'single' | 'rawSingle',\n len: number,\n): void {\n const arr = b[keyMulti]\n if (arr) {\n if (len === 0) b[keyMulti] = undefined\n else if (len === 1) { b[keySingle] = arr[0]; b[keyMulti] = undefined }\n // Guarded like every other truncation \u2014 see rollbackCstCapture. This is the\n // buffered node-capture path, so it is reached only by the INTERPRETER (the\n // compiled engine inlines its own capture and never calls here), and it is\n // where the redundant-store rate is highest: over a backtracking fixture\n // this branch ran 32,800 times and 31,198 of those \u2014 95% \u2014 restored a\n // length that had not moved.\n else if (arr.length !== len) arr.length = len\n return\n }\n if (len === 0) b[keySingle] = undefined\n}\n\nexport function rollbackCstCapture(ctx: ParseContext, mark: CstRollbackMark): void {\n // Truncate the flat recovery-error sink alongside the CST, so a rolled-back\n // speculative branch leaves no ghost error (see saveCstMark). Guarded on a\n // present sink + a defined mark (rollbackTrivia forwards the same field).\n //\n // Each truncation is guarded on `length !== mark`, mirroring the compiled\n // engine (codegen.ts `captureRestoreBody`). Assigning `array.length` runs V8's\n // length setter \u2014 a backing-store trim decision \u2014 and costs the same when the\n // value is unchanged, which is the overwhelmingly common case here: a\n // speculative branch that captured nothing still pays for every store. The\n // compare is an in-object load. Both engines must carry the guard or the\n // interpreted path silently keeps the cost the compiled path shed.\n if (ctx._errors && mark.errors !== undefined && ctx._errors.length !== mark.errors) ctx._errors.length = mark.errors\n const b = ctx._cstBuf\n if (b) {\n rollbackBufList(b, 'raw', 'rawSingle', mark.raw)\n rollbackBufList(b, 'ch', 'single', mark.leaves)\n if (b.tl) {\n if (mark.tlog === 0) b.tl = undefined\n else if (b.tl.length !== mark.tlog) b.tl.length = mark.tlog\n }\n if (ctx._fields && ctx._fields.length !== mark.fields) ctx._fields.length = mark.fields\n return\n }\n if (ctx._cstRawChildren && ctx._cstRawChildren.length !== mark.raw) ctx._cstRawChildren.length = mark.raw\n if (ctx._cstTriviaLog && ctx._cstTriviaLog.length !== mark.tlog) ctx._cstTriviaLog.length = mark.tlog\n if (ctx._cstLeaves && ctx._cstLeaves.length !== mark.leaves) ctx._cstLeaves.length = mark.leaves\n if (ctx._fields && ctx._fields.length !== mark.fields) ctx._fields.length = mark.fields\n}\n\nexport function pushCstTriviaEntry(\n ctx: ParseContext,\n start: number,\n end: number,\n kindIndex?: number,\n): void {\n const insertIdx = cstRawLen(ctx)\n const b = ctx._cstBuf\n const withKind = ctx.triviaKindLabels !== undefined && kindIndex !== undefined\n if (b) {\n if (!b.tl) {\n b.tl = withKind ? [start, end, insertIdx, kindIndex] : [start, end, insertIdx]\n } else if (withKind) {\n b.tl.push(start, end, insertIdx, kindIndex)\n } else {\n b.tl.push(start, end, insertIdx)\n }\n return\n }\n if (ctx._cstTriviaLog) {\n if (withKind) ctx._cstTriviaLog.push(start, end, insertIdx, kindIndex)\n else ctx._cstTriviaLog.push(start, end, insertIdx)\n }\n}\n\nexport function pushTriviaLogEntry(\n ctx: ParseContext,\n start: number,\n end: number,\n kindIndex?: number,\n): void {\n if (!ctx._triviaLog) return\n if (ctx.triviaKindLabels !== undefined && kindIndex !== undefined) {\n ctx._triviaLog.push(start, end, kindIndex)\n } else {\n ctx._triviaLog.push(start, end)\n }\n}\n\nexport function cstDeferredTriviaActive(ctx: ParseContext): boolean {\n return ctx._triviaLog !== undefined || ctx._cstBuf !== undefined || ctx._cstTriviaLog !== undefined\n}\n", "import type { Combinator, ParseContext } from '../types.ts'\nimport { pushCstTriviaEntry, pushTriviaLogEntry } from './capture-buffer.ts'\nimport { startsFirstSet } from '../combinators/first-set.ts'\n\nexport type TriviaChunk = { start: number; end: number; kindIndex: number }\n\nexport type LabeledTriviaSpec = {\n readonly labels: readonly string[]\n readonly arms: ReadonlyArray<{ label: string; kindIndex: number; parser: Combinator<unknown> }>\n readonly minRepeats: number\n}\n\nconst labeledTriviaSpecs = new WeakMap<Combinator<unknown>, LabeledTriviaSpec | null>()\n\nfunction unwrapTrivia(p: Combinator<unknown>): Combinator<unknown> {\n let cur = p\n while (cur._def.tag === 'trivia') cur = cur._def.parser\n return cur\n}\n\n/** Strip `label()` wrapper; returns inner parser for matching. */\nexport function peelLabel(p: Combinator<unknown>): { label: string; parser: Combinator<unknown> } | null {\n if (p._def.tag === 'label') return { label: p._def.label, parser: p._def.parser }\n return null\n}\n\n/**\n * When every trivia arm is `label(name, parser)` inside `oneOrMore(choice(\u2026))`\n * (or a single labeled arm), return the label table and matchers.\n */\nexport function analyzeLabeledTrivia(trivia: Combinator<unknown>): LabeledTriviaSpec | null {\n const cached = labeledTriviaSpecs.get(trivia)\n if (cached !== undefined) return cached\n\n let core = unwrapTrivia(trivia)\n let minRepeats = 1\n\n if (core._def.tag === 'oneOrMore') {\n core = core._def.parser\n minRepeats = 1\n } else if (core._def.tag === 'many') {\n core = core._def.parser\n minRepeats = 0\n }\n\n const arms: LabeledTriviaSpec['arms'][number][] = []\n\n if (core._def.tag === 'choice') {\n for (let i = 0; i < core._def.parsers.length; i++) {\n const peeled = peelLabel(core._def.parsers[i]!)\n if (!peeled) {\n labeledTriviaSpecs.set(trivia, null)\n return null\n }\n arms.push({ label: peeled.label, kindIndex: i, parser: peeled.parser })\n }\n } else {\n const peeled = peelLabel(core)\n if (!peeled) {\n labeledTriviaSpecs.set(trivia, null)\n return null\n }\n arms.push({ label: peeled.label, kindIndex: 0, parser: peeled.parser })\n }\n\n const spec = {\n labels: arms.map(a => a.label),\n arms,\n minRepeats,\n }\n labeledTriviaSpecs.set(trivia, spec)\n return spec\n}\n\n/** Label table on a `trivia()` combinator, if all arms are labeled. */\nexport function triviaKindLabels(trivia: Combinator<unknown> | undefined): readonly string[] | undefined {\n if (!trivia) return undefined\n const fromMeta = trivia._meta.triviaKindLabels\n if (fromMeta) return fromMeta\n return analyzeLabeledTrivia(trivia)?.labels\n}\n\nfunction matchArmAt(\n input: string,\n pos: number,\n arm: Combinator<unknown>,\n state: unknown,\n): { end: number } | null {\n // The first-set check is structural Parseman metadata. It neither assigns\n // meaning to a label nor recognizes a particular comment form; it avoids\n // entering arms whose own grammar proves they cannot start at this offset.\n if (!startsFirstSet(arm, input, pos)) return null\n const r = arm.parse(input, pos, { trackLines: false, state })\n if (!r.ok || r.span.end <= pos) return null\n return { end: r.span.end }\n}\n\n/**\n * Scan maximal labeled trivia chunks (PEG `oneOrMore(choice(\u2026))` semantics).\n * Each successful arm match becomes one entry with that arm's kind index.\n */\nexport function scanLabeledTriviaChunks(\n input: string,\n cur: number,\n spec: LabeledTriviaSpec,\n state?: unknown,\n): { end: number; chunks: TriviaChunk[] } {\n const chunks: TriviaChunk[] = []\n let pos = cur\n\n while (pos < input.length) {\n let matched: { end: number; kindIndex: number } | null = null\n for (const arm of spec.arms) {\n const m = matchArmAt(input, pos, arm.parser, state)\n if (m) {\n matched = { end: m.end, kindIndex: arm.kindIndex }\n break\n }\n }\n if (!matched) break\n chunks.push({ start: pos, end: matched.end, kindIndex: matched.kindIndex })\n pos = matched.end\n }\n\n if (chunks.length < spec.minRepeats) {\n return { end: cur, chunks: [] }\n }\n return { end: pos, chunks }\n}\n\n/**\n * Scan labeled trivia when no caller will retain individual chunks. This is the\n * ordinary skip path for a classified grammar: labels remain available for an\n * explicit capture request, but merely having labels must not allocate one\n * `{ start, end, kindIndex }` object per whitespace/comment run.\n */\nexport function scanLabeledTriviaEnd(\n input: string,\n cur: number,\n spec: LabeledTriviaSpec,\n state?: unknown,\n): number {\n let pos = cur\n let count = 0\n\n while (pos < input.length) {\n let matched: { end: number } | null = null\n for (const arm of spec.arms) {\n matched = matchArmAt(input, pos, arm.parser, state)\n if (matched) break\n }\n if (!matched) break\n pos = matched.end\n count++\n }\n\n return count < spec.minRepeats ? cur : pos\n}\n\n/**\n * Visit classified trivia matches without constructing per-match objects. The\n * visitor is only invoked after one or more arms matched, which is the shape\n * used by `classifiedTrivia()`; callers with a stronger repeat minimum keep\n * the buffered scanner so an unsuccessful minimum cannot leak a partial run.\n */\nexport function visitLabeledTrivia(\n input: string,\n cur: number,\n spec: LabeledTriviaSpec,\n state: unknown | undefined,\n visit: (start: number, end: number, kindIndex: number) => void,\n): number | undefined {\n if (spec.minRepeats > 1) return undefined\n let pos = cur\n let count = 0\n\n while (pos < input.length) {\n let matched: { end: number; kindIndex: number } | null = null\n for (const arm of spec.arms) {\n const match = matchArmAt(input, pos, arm.parser, state)\n if (match) {\n matched = { end: match.end, kindIndex: arm.kindIndex }\n break\n }\n }\n if (!matched) break\n visit(pos, matched.end, matched.kindIndex)\n pos = matched.end\n count++\n }\n\n return count < spec.minRepeats ? cur : pos\n}\n\nexport function recordTriviaChunks(ctx: ParseContext, chunks: readonly TriviaChunk[]): void {\n const kinds = ctx.triviaKindLabels\n const mask = ctx._triviaCaptureMask\n const rootLog = ctx._rootTriviaLog\n const rootKinds = ctx._rootTriviaKindIndex\n const rootMark = rootLog?.length ?? 0\n for (const ch of chunks) {\n // Global trivia log: always complete (never kind-filtered).\n pushTriviaLogEntry(ctx, ch.start, ch.end, kinds ? ch.kindIndex : undefined)\n const rootKindIndex = ctx._rootTriviaCapture === false || rootLog === undefined || rootKinds === undefined || kinds === undefined\n ? -1\n : (rootKinds[kinds[ch.kindIndex] ?? ''] ?? -1)\n if (rootKindIndex >= 0) {\n // Fill the enclosing committed gap after the scanner has consumed every\n // chunk. A selected marker therefore carries its exact authored context\n // without recording any whitespace-only chunk.\n rootLog!.push(0, 0, ch.start, ch.end, rootKindIndex)\n }\n // Per-node CST log: honour the kind mask when both a mask and labels are\n // present, so a host can capture (e.g.) comments only without logging every\n // whitespace run. No mask / no labels \u2192 capture everything, as before.\n if (ctx.captureTrivia && (ctx._cstBuf !== undefined || ctx._cstTriviaLog !== undefined)) {\n if (mask === undefined || kinds === undefined || (mask & (1 << ch.kindIndex)) !== 0) {\n pushCstTriviaEntry(ctx, ch.start, ch.end, kinds ? ch.kindIndex : undefined)\n }\n }\n }\n if (rootLog !== undefined && rootLog.length !== rootMark && chunks.length > 0) {\n const start = chunks[0]!.start\n const end = chunks[chunks.length - 1]!.end\n for (let offset = rootMark; offset < rootLog.length; offset += 5) {\n rootLog[offset] = start\n rootLog[offset + 1] = end\n }\n }\n}\n\n/**\n * Resolve a per-node trivia capture mask (`ctx._triviaCaptureMask`) from a trivia\n * label table and the kind names a host wants to keep. Returns `undefined` when\n * `labels` is absent (nothing to key on \u2192 capture everything).\n *\n * Names in `keep` that aren't in `labels` are **ignored by design**: `keep` is\n * often a dialect-independent list (e.g. `['blockComment', 'lineComment']`) applied\n * to a grammar whose trivia only defines some of them (CSS has no `lineComment`) \u2014\n * so an unknown name is a normal cross-dialect no-op, not necessarily a typo, and\n * is not worth a warning that would cry wolf on legitimate superset lists. An empty\n * `keep` (or one where nothing matches) yields `0`, which means \"capture NO trivia\n * into per-node logs\" \u2014 an intentional, valid state (the global `_triviaLog` is\n * unaffected either way). If you expect comments and get an empty per-node log,\n * check the name against the grammar's `triviaKindLabels`.\n */\nexport function triviaKindMask(\n labels: readonly string[] | undefined,\n keep: readonly string[],\n): number | undefined {\n if (!labels) return undefined\n let mask = 0\n for (const name of keep) {\n const idx = labels.indexOf(name)\n if (idx >= 0) mask |= 1 << idx\n }\n return mask\n}\n", "import type { Combinator, ParseContext, ParseResult, ParseFail, ParseError } from '../types.ts'\nimport { createLineIndex, recordLineRange, normalizeLineIndex, annotateSpan, type LineIndex } from '../line-index.ts'\nimport { markUnusedValues } from '../compiler/value-usage.ts'\nimport { triviaKindMask } from '../cst/trivia-kinds.ts'\n\nexport type ParseOptions = {\n trackLines?: boolean\n /**\n * Enable the error-collection channel. When true, recovery points (expect(), and\n * tolerant list recovery) collect their ParseErrors into a side-channel array\n * rather than only embedding them in the value tree. The returned ParseOk will\n * have an `errors` field listing all recovered errors. Top-level parse failures\n * (where nothing recovered) still return ParseFail as usual.\n */\n recover?: boolean\n}\n\nexport type ParserOptions = ParseOptions & {\n /**\n * Trivia parser for this scope. Three states:\n * - a Combinator \u2192 skip this trivia between sequence/repeat terms\n * - `undefined` \u2192 inherit the enclosing scope's trivia (no change)\n * - `null` \u2192 CLEAR trivia: no trivia skipped, so terms must be contiguous.\n * Re-enable inside a nested region with another parser({ trivia }).\n */\n trivia?: Combinator<unknown> | null\n /**\n * Declare that this local trivia scope intentionally does not preserve\n * selected root categories. Required only by\n * `rootTrivia: { select }` when the scope does not use\n * `classifiedTrivia()`.\n */\n rootCapture?: 'opaque'\n /** Record consumed trivia as CSTTrivia tokens in rawChildren. Default: skip. */\n captureTrivia?: boolean\n /**\n * Restrict PER-NODE CST trivia capture to these trivia kinds (label names from\n * the trivia's `label()` arms). Whitespace and any other unlisted kind is still\n * skipped over but NOT recorded into a node's `triviaLog` \u2014 so a host that only\n * consumes (say) comments pays nothing to log every whitespace run. The global\n * trivia log is unaffected. Requires labeled trivia; ignored otherwise.\n */\n captureTriviaKinds?: readonly string[]\n}\n\nexport interface ParsemanParser<T> extends Combinator<T> {\n parse(input: string): ParseResult<T>\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T>\n}\n\nfunction annotateResultLines<T, R extends ParseResult<T>>(result: R, index: LineIndex): R {\n const annotated = { ...result, span: annotateSpan(result.span, index) } as R\n const errors = (annotated as { errors?: ParseError[] }).errors\n if (errors) {\n ;(annotated as { errors: ParseError[] }).errors = errors.map(error => ({\n ...error,\n span: annotateSpan(error.span, index),\n }))\n }\n return annotated\n}\n\nfunction createParseLineContext(input: string, pos: number): { lineIndex: LineIndex; lineScannedTo: number } {\n const lineIndex = createLineIndex()\n if (pos > 0) recordLineRange(lineIndex, input, 0, pos)\n return { lineIndex, lineScannedTo: pos }\n}\n\nexport function parser<T>(opts: ParserOptions, root: Combinator<T>): ParsemanParser<T> {\n const clearTrivia = opts.trivia === null\n const opaqueRootCapture = opts.rootCapture === 'opaque'\n if (opaqueRootCapture && opts.trivia === undefined) {\n throw new TypeError('parser({ rootCapture: \\'opaque\\' }) requires an explicit trivia scope.')\n }\n return {\n _tag: 'grammar',\n _meta: {\n ...root._meta,\n // Trivia classification describes this grammar's own active trivia\n // scope. A directly nested grammar may have classified trivia of its\n // own, but that must not advertise classification for this wrapper.\n triviaKindLabels: undefined,\n rootTriviaClassified: undefined,\n ...(opts.trivia?._meta?.triviaKindLabels ? { triviaKindLabels: opts.trivia._meta.triviaKindLabels } : {}),\n ...(opts.trivia?._meta?.rootTriviaClassified ? { rootTriviaClassified: true as const } : {}),\n },\n _def: {\n tag: 'grammar',\n parser: root as Combinator<unknown>,\n triviaParser: clearTrivia ? undefined : (opts.trivia ?? undefined),\n clearTrivia,\n ...(opaqueRootCapture ? { rootCapture: 'opaque' as const } : {}),\n ...(opts.captureTrivia ? { captureTrivia: true } : {}),\n trackLines: opts.trackLines ?? false,\n },\n parse(input: string, pos?: number, _ctx?: ParseContext): ParseResult<T> {\n if (_ctx?._rootTriviaStrictScopes && opts.trivia !== undefined && opts.trivia !== null\n && !opts.trivia._meta.rootTriviaClassified && !opaqueRootCapture) {\n throw new TypeError(\n 'parser(): selected root trivia requires classifiedTrivia() for every local trivia scope, or rootCapture: \\'opaque\\'.',\n )\n }\n const trackLines = opts.trackLines ?? _ctx?.trackLines ?? false\n const lineContext = trackLines && _ctx?._lineIndex === undefined && _ctx?._lineStarts === undefined\n ? createParseLineContext(input, pos ?? 0)\n : undefined\n const lineIndex = trackLines\n ? (_ctx?._lineIndex ?? (_ctx?._lineStarts ? { lineStarts: _ctx._lineStarts } : lineContext!.lineIndex))\n : undefined\n // Preserve any CST collectors / capture flag from the caller (e.g. an\n // enclosing node()), layering this grammar's trivia on top. Without this,\n // a parser() nested inside a node() would drop the node's child collectors.\n const ctx: ParseContext = {\n ..._ctx,\n trackLines,\n ...(lineIndex ? { _lineIndex: lineIndex } : {}),\n ...(lineContext ? { _lineScannedTo: lineContext.lineScannedTo } : {}),\n // trivia: null clears (contiguous terms); a Combinator sets; undefined inherits.\n ...(clearTrivia ? {\n trivia: undefined,\n triviaKindLabels: undefined,\n } : opts.trivia != null ? {\n trivia: opts.trivia,\n ...(opts.trivia._meta.triviaKindLabels\n ? { triviaKindLabels: opts.trivia._meta.triviaKindLabels }\n : {}),\n } : {}),\n ...(opts.captureTrivia || _ctx?.captureTrivia ? { captureTrivia: true } : {}),\n // Kind-filter for per-node capture. Resolve against this scope's trivia\n // labels \u2014 this parser's own trivia if it declares one, else the INHERITED\n // labels (`_ctx.triviaKindLabels`), so captureTriviaKinds still applies when\n // trivia is inherited rather than re-declared here. No labels \u2192 undefined\n // (capture all).\n ...(opts.captureTriviaKinds && !clearTrivia\n ? { _triviaCaptureMask: triviaKindMask(opts.trivia?._meta.triviaKindLabels ?? _ctx?.triviaKindLabels, opts.captureTriviaKinds) }\n : {}),\n // This is a property of the local trivia scope, not a post-parse filter:\n // nested recognition can still skip its trivia, but selected root rows\n // must never be written for an explicitly opaque region.\n ...(opaqueRootCapture ? { _rootTriviaCapture: false } : {}),\n }\n const result = root.parse(input, pos ?? 0, ctx)\n if (trackLines && _ctx && ctx._lineScannedTo !== undefined) {\n _ctx._lineScannedTo = Math.max(_ctx._lineScannedTo ?? 0, ctx._lineScannedTo)\n }\n return lineIndex ? annotateResultLines(result, normalizeLineIndex(lineIndex)) : result\n },\n } as ParsemanParser<T>\n}\n\n/**\n * Run `root` with the active trivia cleared \u2014 no trivia is skipped between its\n * sequence/repeat terms, so they must be contiguous in the input. (Trivia is\n * whatever parser({ trivia }) installed \u2014 often whitespace/comments, but it is\n * grammar-defined.) The inverse of parser({ trivia }); re-enable trivia in a\n * nested region with another parser({ trivia }).\n *\n * Wrap the WHOLE contiguous run: an enclosing sequence skips trivia *before* a\n * term runs, so wrapping just the inner part would let leading trivia through.\n *\n * For a static glued token just use one literal/regex; reach for noTrivia when a\n * glued part is a structured sub-rule \u2014 e.g. a head glued to a `[subscript]`\n * whose interior still allows trivia. Turn trivia back on for a region by nesting\n * another parser({ trivia }) (innermost wins, reverts on exit); put the WHOLE\n * spaced region \u2014 including its leading `[` \u2014 inside it, since sequence skips\n * trivia only between terms, not before its first:\n *\n * // `arr[i + 1]` \u2014 `arr` touches `[`, but the subscript is a spaced expr:\n * noTrivia(sequence(name,\n * parser({ trivia: ws }, sequence(literal('['), expr, literal(']')))))\n */\nexport function noTrivia<T>(root: Combinator<T>): ParsemanParser<T> {\n return parser({ trivia: null }, root)\n}\n\n// Roots already run through dead-value analysis, so a hot parse loop doesn't\n// re-walk the tree. (A `rules()` grammar was analyzed at build; a bare combinator\n// passed straight to parse() is analyzed once here.)\nconst _analyzed = new WeakSet<Combinator<unknown>>()\n\nexport function parse<T>(\n combinator: Combinator<T>,\n input: string,\n opts: ParseOptions = {}\n): ParseResult<T> {\n if (!_analyzed.has(combinator)) {\n _analyzed.add(combinator)\n markUnusedValues(combinator)\n }\n const trackLines = opts.trackLines ?? combinator._meta.grammarTrackLines ?? false\n const lineContext = trackLines ? createParseLineContext(input, 0) : undefined\n const lineIndex = lineContext?.lineIndex\n const _errors = opts.recover ? [] : undefined\n // In recovery mode also track the furthest-position failure, so the caller can\n // report \"where it got stuck + what was expected\" even when a permissive top\n // rule succeeds with unconsumed trailing input. Off by default (it adds\n // bookkeeping to every failed alternative).\n const _probe = opts.recover ? { offset: input.length, best: null as ParseFail | null } : undefined\n // Grammar-level ambient trivia declared via rules({ trivia }, factory): install\n // it as ctx.trivia so it's ambient (interpreter). parser/noTrivia override locally.\n const grammarTrivia = combinator._meta.grammarTrivia\n const grammarScanSkip = combinator._meta.grammarScanSkip\n const ctx: ParseContext = {\n trackLines,\n ...(lineIndex ? { _lineIndex: lineIndex } : {}),\n ...(lineContext ? { _lineScannedTo: lineContext.lineScannedTo } : {}),\n ...(grammarTrivia !== undefined\n ? { trivia: grammarTrivia, ...(grammarTrivia._meta.triviaKindLabels ? { triviaKindLabels: grammarTrivia._meta.triviaKindLabels } : {}) }\n : {}),\n ...(grammarScanSkip !== undefined ? { scanSkip: grammarScanSkip } : {}),\n ...(_errors !== undefined ? { _errors } : {}),\n ...(_probe !== undefined ? { _probe } : {}),\n }\n const result = combinator.parse(input, 0, ctx)\n if (!result.ok) return lineIndex ? annotateResultLines(result, normalizeLineIndex(lineIndex)) : result\n const withErrors = _errors !== undefined\n ? { ...result, errors: _errors, furthestFail: _probe?.best ?? null }\n : result\n return lineIndex ? annotateResultLines(withErrors, normalizeLineIndex(lineIndex)) : withErrors\n}\n", "import type { Combinator, ParserDef } from '../types.ts'\n\nexport const GRAMMAR_REFLECTION: unique symbol = Symbol.for('parseman.grammarReflection') as never\nexport const NODE_TYPE: unique symbol = Symbol.for('parseman.type.nodeType') as never\nexport const NODE_TAG: unique symbol = Symbol.for('parseman.type.nodeTag') as never\n\nexport type GrammarNodeReflection = {\n type: string\n tags: readonly string[]\n}\n\nexport type GrammarReflection = {\n nodes: readonly GrammarNodeReflection[]\n}\n\nexport type GrammarWithReflection<\n NodeType extends string = string,\n NodeTag extends string = string,\n> = {\n readonly [GRAMMAR_REFLECTION]?: GrammarReflection\n readonly [NODE_TYPE]?: NodeType\n readonly [NODE_TAG]?: NodeTag\n}\n\ntype NodeDef = Extract<ParserDef, { tag: 'node' }>\n\nfunction childrenOf(def: ParserDef): readonly Combinator<unknown>[] {\n switch (def.tag) {\n case 'sequence':\n case 'choice':\n return def.parsers\n case 'dispatch':\n return [\n def.selector,\n ...def.cases.map(c => c.parser),\n ...(def.matchers ? def.matchers.map(c => c.parser) : []),\n ...(def.otherwise ? [def.otherwise] : []),\n ]\n case 'many':\n case 'oneOrMore':\n case 'optional':\n case 'attempt':\n case 'transform':\n case 'trivia':\n case 'token':\n case 'leaf':\n case 'label':\n case 'field':\n case 'not':\n case 'peek':\n case 'node':\n case 'withCtx':\n case 'recover':\n case 'expect':\n return [def.parser]\n case 'grammar':\n return def.triviaParser ? [def.parser, def.triviaParser] : [def.parser]\n case 'sepBy':\n return [def.parser, def.separator]\n case 'skip':\n return [def.main, def.skipped]\n case 'scanTo':\n return [def.sentinel, ...def.skip]\n case 'routed':\n return def.fallback ? [def.fallback] : []\n case 'literal':\n case 'regex':\n case 'keywords':\n case 'guard':\n case 'lazy':\n case 'unknown':\n return []\n }\n}\n\nfunction addNode(out: Map<string, string[]>, def: NodeDef): void {\n if (def.type === undefined) return\n const existing = out.get(def.type)\n if (existing === undefined) {\n out.set(def.type, def.tags === undefined ? [] : [...def.tags])\n return\n }\n if (def.tags === undefined) return\n for (const tag of def.tags) {\n if (!existing.includes(tag)) existing.push(tag)\n }\n}\n\nfunction collectFromCombinator(\n parser: Combinator<unknown>,\n out: Map<string, string[]>,\n seen: Set<Combinator<unknown>>,\n followLazy = true,\n): void {\n if (seen.has(parser)) return\n seen.add(parser)\n const def = parser._def\n if (def.tag === 'lazy') {\n if (followLazy) {\n try { collectFromCombinator(def.thunk(), out, seen, followLazy) } catch {}\n }\n return\n }\n if (def.tag === 'node') addNode(out, def)\n for (const child of childrenOf(def)) collectFromCombinator(child, out, seen, followLazy)\n}\n\nexport function collectGrammarReflection(\n ruleMap: ReadonlyArray<readonly [string, Combinator<unknown>]>,\n opts?: { followLazy?: boolean },\n): GrammarReflection {\n const byType = new Map<string, string[]>()\n const followLazy = opts?.followLazy !== false\n for (const [, rule] of ruleMap) {\n if (!followLazy && rule._def.tag === 'lazy') {\n try {\n const resolved = rule._def.thunk()\n if (resolved._def.tag !== 'lazy') collectFromCombinator(resolved, byType, new Set(), false)\n } catch {}\n continue\n }\n collectFromCombinator(rule, byType, new Set(), followLazy)\n }\n return { nodes: [...byType].map(([type, tags]) => ({ type, tags })) }\n}\n\nexport function mergeGrammarReflections(reflections: readonly GrammarReflection[]): GrammarReflection {\n const byType = new Map<string, string[]>()\n for (const reflection of reflections) {\n for (const node of reflection.nodes) {\n const tags = byType.get(node.type)\n if (tags === undefined) {\n byType.set(node.type, [...node.tags])\n continue\n }\n for (const tag of node.tags) {\n if (!tags.includes(tag)) tags.push(tag)\n }\n }\n }\n return { nodes: [...byType].map(([type, tags]) => ({ type, tags })) }\n}\n\nexport function attachGrammarReflection<T extends object>(grammar: T, reflection: GrammarReflection): T {\n Object.defineProperty(grammar, GRAMMAR_REFLECTION, { value: reflection, enumerable: false, configurable: true })\n return grammar\n}\n\nexport function grammarReflectionOf(grammar: object): GrammarReflection | undefined {\n return (grammar as GrammarWithReflection)[GRAMMAR_REFLECTION]\n}\n\nexport function grammarReflectionSource(reflection: GrammarReflection): string {\n return `{ nodes: ${JSON.stringify(reflection.nodes)} }`\n}\n", "import type { Combinator } from '../types.ts'\nimport type { HostMode } from '../compiler/codegen.ts'\nimport { ref } from './ref.ts'\nimport { markUnusedValues } from '../compiler/value-usage.ts'\nimport { parser as grammarParser } from './grammar.ts'\nimport { attachGrammarReflection, collectGrammarReflection, NODE_TAG, NODE_TYPE, type GrammarWithReflection } from '../cst/reflection.ts'\n\n/**\n * Non-enumerable key on a `rules()` result holding the factory's declaration\n * order (the returned object's key order), which differs from the result's own\n * reference-creation key order. Read by `parseman/spec` for source-order output.\n */\nexport const RULE_ORDER = '__parsemanRuleOrder'\n\nfunction tagRule(r: Combinator<unknown>, key: string): void {\n ;(r as unknown as { _ruleName?: string })._ruleName = key\n if (r._def.tag === 'node' && r._def.type === undefined) r._def.type = key\n}\n\ntype DefinableRef = Combinator<unknown> & { define(p: Combinator<unknown>): void }\n\nfunction isDefinableRef(v: unknown): v is DefinableRef {\n return !!v\n && typeof v === 'object'\n && '_def' in v\n && (v as { _def: { tag?: string } })._def.tag === 'lazy'\n && typeof (v as { define?: unknown }).define === 'function'\n}\n\nfunction ruleNameOf(r: Combinator<unknown>): string | undefined {\n return (r as unknown as { _ruleName?: string })._ruleName\n}\n\nfunction isNamedRuleRefForAnotherRule(r: Combinator<unknown>, key: string): boolean {\n const name = r._def.tag === 'lazy' ? ruleNameOf(r) : undefined\n return name !== undefined && name !== key\n}\n\n/**\n * Define named grammar rules without forward declarations.\n *\n * Pass a factory that receives all rule names as references (via a Proxy)\n * and returns a record of combinators. rules() handles creating ref()\n * placeholders and wiring them up \u2014 the user never sees ref() at all.\n *\n * const { value } = rules(g => ({\n * value: choice(g.object, g.array, str, num, bool, nil),\n * object: transform(sequence('{', sepBy(g.pair, ','), '}'), Object.fromEntries),\n * array: transform(sequence('[', sepBy(g.value, ','), ']'), ([, items]) => items),\n * pair: transform(sequence(g.key, literal(':'), g.value), ([k,, v]) => [k, v]),\n * }))\n *\n * Not every name in the factory must appear in the returned object \u2014 local helpers\n * (like `comma`, `key`) can be plain const inside the factory and composed normally.\n * Only names that OTHER rules reference via `g.xxx` need to be in the returned record.\n *\n * TypeScript: use an explicit type parameter for full type safety on `g`:\n * rules<{ value: Combinator<JSONValue>; array: Combinator<JSONValue[]> }>(g => ({ ... }))\n * Without it, `g.*` accesses are typed as `any` but the return is still inferred.\n */\n/**\n * Grammar-level options for `rules()`. Parity with `parser({...})`, but declared\n * ONCE for the whole grammar instead of wrapped around a scope. `trivia` becomes\n * the ambient trivia for every rule (installed at the parse entry, inherited\n * everywhere, incremental parse included); `parser({trivia})` / `noTrivia` still\n * override it locally for a sub-region.\n */\nexport type RulesOptions = {\n /** Ambient trivia for the whole grammar. See `parser({ trivia })` for the shape\n * (`null` clears it \u2014 equivalent to omitting it at the grammar level). */\n trivia?: Combinator<unknown> | null\n /**\n * Ambient scan-skip for the whole grammar: opaque non-trivia units (strings,\n * balanced brackets, \u2026) that a `scanTo`/`balanced` with no explicit `skip`\n * consults so a sentinel hidden inside one is never matched. Declared ONCE here\n * and inherited everywhere, mirroring `trivia`. `null`/absent = none.\n */\n scanSkip?: Combinator<unknown>[] | null\n /**\n * Compile-time host mode for this grammar, same meaning as `compile(g, { hostMode })`\n * and `compose(items, { hostMode })`: `'ast'` (default) emits each direct builder's\n * own result and NO positioned-CST branch; `'cst'` builds every node through the\n * `ctx.build` host and captures unconditionally.\n *\n * Declaring it HERE is what lets ONE grammar source serve both consumers under the\n * macro, which cannot take a compile option any other way:\n *\n * ```ts\n * const factory = (g: any) => ({ \u2026 })\n * export const grammar = rules({ trivia: rw }, factory)\n * export const cstGrammar = rules({ trivia: rw, hostMode: 'cst' }, factory)\n * ```\n *\n * Two call sites over one factory, so the macro emits two independent top-level\n * artifacts and each bundle tree-shakes away the one it does not import. Neither\n * pays the other's cost \u2014 which is the whole reason host mode is a compile-time\n * decision rather than a per-node runtime read.\n *\n * The INTERPRETER routes dynamically off the host and does not need this; it is\n * still recorded, so `run()` can refuse a mismatched host once per parse instead of\n * quietly producing the wrong tree shape.\n */\n hostMode?: HostMode\n /**\n * Compile-time line tracking for this grammar. Under the macro this emits a\n * separate line-aware artifact from the same factory; the default artifact\n * remains free of line-tracking helpers and branches.\n */\n trackLines?: boolean\n}\n\n// Options-first, mirroring `parser({ opts }, combinator)` \u2014 set once on the grammar\n// vs scope it locally, same options in the same position. The bare `rules(factory)`\n// form is unchanged. The impl also tolerates the legacy `rules(factory, opts)` order.\ntype RuleNodeType<K extends string, C> =\n C extends { readonly [NODE_TYPE]?: infer T extends string }\n ? [T] extends [never] ? K : T\n : K\n\ntype RuleNodeTag<C> =\n C extends { readonly [NODE_TAG]?: infer Tag extends string } ? Tag : never\n\ntype RuleMapNodeType<T extends Record<string, Combinator<unknown>>> = {\n [K in keyof T & string]: RuleNodeType<K, T[K]>\n}[keyof T & string]\n\ntype RuleMapNodeTag<T extends Record<string, Combinator<unknown>>> = {\n [K in keyof T & string]: RuleNodeTag<T[K]>\n}[keyof T & string]\n\ntype RulesResult<T extends Record<string, Combinator<unknown>>> =\n T & GrammarWithReflection<RuleMapNodeType<T>, RuleMapNodeTag<T>>\n\nexport function rules<T extends Record<string, Combinator<unknown>>>(factory: (self: any) => T): RulesResult<T>\nexport function rules<T extends Record<string, Combinator<unknown>>>(options: RulesOptions, factory: (self: any) => T): RulesResult<T>\nexport function rules<T extends Record<string, Combinator<unknown>>>(\n a: ((self: any) => T) | RulesOptions,\n b?: (self: any) => T,\n): RulesResult<T> {\n const factory = (typeof a === 'function' ? a : b) as (self: any) => T\n const options = (typeof a === 'function' ? b : a) as RulesOptions | undefined\n const cache: Partial<T> = {}\n\n // Proxy: accessing any property creates a ref() placeholder on first touch.\n const proxy = new Proxy(cache, {\n get(target, key) {\n if (typeof key !== 'string') return undefined\n const record = target as Record<string, Combinator<unknown>>\n if (!(key in record)) {\n const r = ref()\n // Tag the placeholder with its rule name so the linkable compiler can\n // emit a by-name `_r_<key>` call for a reference to a rule defined in\n // ANOTHER artifact (resolved at fuse time) \u2014 see compileLinkable.\n tagRule(r, key)\n record[key] = r\n }\n return record[key]\n },\n })\n\n // Evaluate all rule definitions. JavaScript evaluates object-literal values\n // left-to-right, so any `g.ruleName` access inside triggers placeholder creation\n // before the rule's own parser is built \u2014 enabling forward references.\n const definitions = factory(proxy)\n\n // Fill each ref with its actual definition, or store directly if never accessed via proxy.\n for (const key of Object.keys(definitions)) {\n const placeholder = (cache as Record<string, Combinator<unknown>>)[key]\n const parser = (definitions as Record<string, Combinator<unknown>>)[key]!\n if (placeholder === parser) {\n throw new Error(`rules(): rule \"${key}\" cannot be a direct alias to itself`)\n }\n if (isDefinableRef(placeholder)) {\n if (!isNamedRuleRefForAnotherRule(parser, key)) tagRule(parser, key)\n placeholder.define(parser)\n // Propagate actual first-set so later choices wrapping this ref get correct dispatch.\n placeholder._meta.firstSet = parser._meta.firstSet\n placeholder._meta.canMatchNewline = parser._meta.canMatchNewline\n } else if (isNamedRuleRefForAnotherRule(parser, key)) {\n const alias = ref()\n tagRule(alias, key)\n alias.define(parser)\n alias._meta.firstSet = parser._meta.firstSet\n alias._meta.canMatchNewline = parser._meta.canMatchNewline\n ;(cache as Record<string, Combinator<unknown>>)[key] = alias\n } else {\n tagRule(parser, key)\n ;(cache as Record<string, Combinator<unknown>>)[key] = parser\n }\n }\n\n // Declare the grammar-level ambient trivia on every rule, so parsing ANY rule\n // as an entry installs it (run()/parse() read this), and the macro can seed the\n // compiled map. `parser({trivia})` / `noTrivia` still override it locally.\n // `!= null`: a `trivia: null` grammar clears trivia \u2014 same as omitting it at the\n // grammar level \u2014 so store nothing (and never write null, which has no `_meta`).\n if (options?.trivia != null) {\n for (const key of Object.keys(definitions)) {\n const rule = (cache as Record<string, Combinator<unknown>>)[key]\n // Skip trivia rules (e.g. the grammar's `rw`, returned so the driver can\n // reach it as `g.rw`): a trivia rule must never carry ambient trivia, or it\n // would recursively skip trivia within itself. Mirrors the codegen guard.\n if (rule && !rule._meta.isTrivia) (rule._meta as { grammarTrivia?: Combinator<unknown> }).grammarTrivia = options.trivia\n }\n }\n\n // Grammar-level ambient scan-skip, mirroring the trivia stamp above: every\n // non-trivia rule carries it so any parse entry installs `ctx.scanSkip` and the\n // compiled map can seed it. `!= null` so `scanSkip: null` clears (stores nothing).\n if (options?.scanSkip != null) {\n for (const key of Object.keys(definitions)) {\n const rule = (cache as Record<string, Combinator<unknown>>)[key]\n if (rule && !rule._meta.isTrivia) (rule._meta as { grammarScanSkip?: Combinator<unknown>[] }).grammarScanSkip = options.scanSkip\n }\n }\n\n // Grammar-level host mode, mirroring the two stamps above. Only `'cst'` is recorded:\n // `'ast'` is the default everywhere, so stamping it would put a field on every rule of\n // every grammar to say \"unchanged\". Trivia rules are skipped for the same reason as\n // above \u2014 they build no nodes, so the mode is meaningless on them.\n if (options?.hostMode === 'cst') {\n for (const key of Object.keys(definitions)) {\n const rule = (cache as Record<string, Combinator<unknown>>)[key]\n if (rule && !rule._meta.isTrivia) (rule._meta as { grammarHostMode?: HostMode }).grammarHostMode = 'cst'\n }\n }\n\n if (options?.trackLines === true) {\n for (const key of Object.keys(definitions)) {\n const rule = (cache as Record<string, Combinator<unknown>>)[key]\n if (rule && !rule._meta.isTrivia) (rule._meta as { grammarTrackLines?: true }).grammarTrackLines = true\n }\n for (const key of Object.keys(definitions)) {\n const rule = (cache as Record<string, Combinator<unknown>>)[key]\n if (rule && !rule._meta.isTrivia && rule._def.tag !== 'grammar') {\n const wrapped = grammarParser({ trackLines: true }, rule)\n tagRule(wrapped, key)\n ;(wrapped._meta as { grammarTrackLines?: true }).grammarTrackLines = true\n ;(cache as Record<string, Combinator<unknown>>)[key] = wrapped\n }\n }\n }\n\n // Dead-value analysis: mark container aggregates that only feed a node()'s\n // capture so the interpreter (and, via the same flag, the compiled output) skips\n // building them. Each rule is its own root \u2014 refs are boundaries (see value-usage).\n for (const key of Object.keys(definitions)) {\n markUnusedValues((cache as Record<string, Combinator<unknown>>)[key]!)\n }\n\n // Record the factory's DECLARATION order (the returned object's key order).\n // `cache`'s own key order is reference-creation order \u2014 a Proxy artifact \u2014 so\n // it can lead with an internal rule instead of the entry rule. Consumers that\n // want the order the author actually wrote (e.g. `parseman/spec`) read this.\n // Non-enumerable, so Object.keys / spread / for-in over the grammar are\n // unaffected and every existing consumer sees exactly the rules it did before.\n Object.defineProperty(cache, RULE_ORDER, {\n value: Object.keys(definitions),\n enumerable: false,\n configurable: true,\n })\n attachGrammarReflection(cache, collectGrammarReflection(Object.keys(definitions).map(key => [key, (cache as Record<string, Combinator<unknown>>)[key]!])))\n\n return cache as RulesResult<T>\n}\n", "import type { Combinator, FirstSet, ParseContext, ParseError, ParseResult, RecoveryHelpers } from '../types.ts'\nimport { cstCaptureActive, pushCstChild } from '../cst/capture-buffer.ts'\nimport { annotateSpanFromLineContext, recordLineRangeFromContext } from '../line-index.ts'\n\n/**\n * Recovery MECHANISM \u2014 sync-source-agnostic. These primitives implement \"scan\n * forward to a sync token and emit a ParseError\" and \"is the sync token here?\".\n * They are deliberately independent of WHERE the sync sentinel comes from: the\n * grammar never carries recovery config. Sync points are inferred automatically\n * from grammar structure (see `infer.ts`) and may be overridden externally by the\n * language service via `ctx._listSync`. This is the salvaged core of the old\n * `combinators/recover-scan.ts`.\n */\n\n/**\n * Run `sentinel` at `pos` as PURE lookahead: succeed/fail only, with every\n * side-effecting sink suppressed (CST leaves/children/trivia, the trivia log,\n * the recovery error sink, and the completions probe). A recovery scan probes the\n * sentinel at many positions and must not capture leaves, log trivia, or pollute\n * `completionsAt`'s furthest-failure set as a byproduct of looking ahead.\n */\nfunction probeAt(sentinel: Combinator<unknown>, input: string, pos: number, ctx: ParseContext): boolean {\n const s = {\n _probe: ctx._probe, _errors: ctx._errors,\n _cstLeaves: ctx._cstLeaves, _cstChildren: ctx._cstChildren, _cstRawChildren: ctx._cstRawChildren,\n _cstTriviaLog: ctx._cstTriviaLog, _triviaLog: ctx._triviaLog, _rootTriviaLog: ctx._rootTriviaLog, _fields: ctx._fields, _cstBuf: ctx._cstBuf,\n _tolerant: ctx._tolerant, _sync: ctx._sync,\n }\n ctx._probe = undefined; ctx._errors = undefined\n ctx._cstLeaves = undefined; ctx._cstChildren = undefined; ctx._cstRawChildren = undefined\n ctx._cstTriviaLog = undefined; ctx._triviaLog = undefined; ctx._rootTriviaLog = undefined; ctx._fields = undefined; ctx._cstBuf = undefined\n // A sentinel is pure lookahead: it must not itself enter tolerant recovery (nor\n // read a stale outer `_sync`). Otherwise a sentinel that composes many/sepBy would\n // run recovery on every probed position \u2014 wasted work, and it could resync to the\n // enclosing list's sync token. Cleared here and restored in `finally`.\n ctx._tolerant = undefined; ctx._sync = undefined\n try {\n return sentinel.parse(input, pos, ctx).ok\n } finally {\n ctx._probe = s._probe; ctx._errors = s._errors\n ctx._cstLeaves = s._cstLeaves; ctx._cstChildren = s._cstChildren; ctx._cstRawChildren = s._cstRawChildren\n ctx._cstTriviaLog = s._cstTriviaLog; ctx._triviaLog = s._triviaLog; ctx._rootTriviaLog = s._rootTriviaLog; ctx._fields = s._fields; ctx._cstBuf = s._cstBuf\n ctx._tolerant = s._tolerant; ctx._sync = s._sync\n }\n}\n\n/**\n * Combine two recovery sentinels into one that matches when either does \u2014 used by\n * tolerant `sepBy` to resync to its own separator OR the enclosing delimiter. Cold\n * path only; a bare wrapper so we don't pull `choice()` (and its analysis) in.\n */\nexport function orSentinel(\n a: Combinator<unknown>,\n b: Combinator<unknown> | undefined,\n): Combinator<unknown> {\n if (b === undefined) return a\n return {\n _tag: 'orSentinel',\n _meta: { firstSet: { kind: 'any' }, canMatchNewline: false, isTrivia: false },\n _def: { tag: 'unknown' },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<unknown> {\n const ra = a.parse(input, pos, ctx)\n if (ra.ok) return ra\n return b.parse(input, pos, ctx)\n },\n }\n}\n\n/**\n * A lightweight zero-width sentinel that \"matches\" (succeeds, consuming nothing)\n * when the input code point at `pos` starts the given first set. Sync inference\n * builds one from a list's follow set so a nested list can resync to the enclosing\n * delimiter with no grammar annotation. Returns `null` when the first set is `any`\n * or `empty` (no usable inference).\n */\nexport function firstSetSentinel(fs: FirstSet): Combinator<null> | null {\n if (fs.kind !== 'ranges' || fs.ranges.length === 0) return null\n const ranges = fs.ranges\n return {\n _tag: 'firstSetSentinel',\n _meta: { firstSet: fs, canMatchNewline: false, isTrivia: false },\n _def: { tag: 'unknown' },\n parse(input: string, pos: number): ParseResult<null> {\n const code = pos < input.length ? input.codePointAt(pos) : undefined\n if (code !== undefined) {\n for (const r of ranges) {\n if (code >= r.lo && code <= r.hi) return { ok: true, value: null, span: { start: pos, end: pos } }\n }\n }\n return { ok: false, expected: [], span: { start: pos, end: pos } }\n },\n }\n}\n\n/**\n * Cold-path recovery scan shared by tolerant `many()` / `sepBy()`. Scans forward\n * from `from` until `sync` matches (or EOF) \u2014 probing the sentinel as pure\n * lookahead \u2014 emits a {@link ParseError} spanning the skipped range, and pushes it\n * to `ctx._errors`. The sync token is NOT consumed; the caller's loop resumes from\n * `end`. Only ever reached after an element has failed, so entirely off the hot path.\n *\n * The caller owns the loop guard: `sepBy` progress is driven by its separator (a\n * zero-width error for a missing element is fine); `many` checks `matchesAt(sync)`\n * itself and breaks when sitting on the terminator, so a zero-width failure can\n * never spin.\n */\nexport function recoverScan(\n input: string,\n from: number,\n ctx: ParseContext,\n sync: Combinator<unknown>,\n expected: string[],\n): { error: ParseError; end: number } {\n let scanPos = from\n while (scanPos < input.length && !probeAt(sync, input, scanPos, ctx)) scanPos++\n const span = { start: from, end: scanPos }\n if (ctx.trackLines) recordLineRangeFromContext(ctx, input, from, scanPos)\n const error: ParseError = { _tag: 'parseError', span: ctx.trackLines ? annotateSpanFromLineContext(span, ctx) : span, expected }\n ctx._errors?.push(error)\n return { error, end: scanPos }\n}\n\n/**\n * Does `sentinel` match at `pos` (pure lookahead)? Used by the tolerant list loops\n * to detect \"we are sitting on the sync/terminator token\" without consuming it or\n * capturing anything.\n */\nexport function matchesAt(\n sentinel: Combinator<unknown>,\n input: string,\n pos: number,\n ctx: ParseContext,\n): boolean {\n return probeAt(sentinel, input, pos, ctx)\n}\n\n/**\n * Embed a recovered error as a `parseError` CST child at the recovery point, so the\n * error lives IN the tree (rides reused subtrees across incremental edits; a tree\n * walk finds every diagnostic) \u2014 not only in the flat `ctx._errors` side-channel.\n * No-op when CST capture is off (value/AST mode). Both the interpreter list loops\n * and the compiled recovery branches call this (the latter via `_ctx._rec.capture`),\n * so the embedded node is identical on both paths.\n */\nexport function captureError(ctx: ParseContext, error: ParseError): void {\n if (cstCaptureActive(ctx)) pushCstChild(ctx, error, error)\n}\n\n/**\n * The recovery-helper bundle handed to a tolerant parse via `ctx._rec`. A COMPILED\n * grammar can't import these, so the driver (`run`, `parseDoc`) injects them; the\n * interpreter list loops read the same bundle, guaranteeing byte-identical recovery\n * across paths. Shared here so every driver installs the exact same instance.\n */\nexport const REC: RecoveryHelpers = { scan: recoverScan, at: matchesAt, or: orSentinel, sentinel: firstSetSentinel, capture: captureError }\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta, ParseError } from '../types.ts'\nimport { captureError } from '../recovery/scan.ts'\nimport { annotateSpanFromLineContext } from '../line-index.ts'\nimport { matchesEmpty, isZeroWidthAssertion } from './first-set.ts'\n\nexport type { ParseError }\n\n/**\n * Statically derive the \"expected\" token set from a combinator's structure,\n * so a failure can name what it wanted without running anything:\n *\n * literal('}') -> ['\"}\"']\n * keywords(['a','b']) -> ['\"a\"', '\"b\"']\n * choice(x, y) -> expected(x) ++ expected(y) (all alternatives)\n * sequence(a, b, \u2026) -> expected(a) ++ \u2026 through the NULLABLE prefix\n * label('s', x) -> ['s'] (an explicit name wins)\n *\n * This is what lets expect() report a meaningful, IDENTICAL expectation in both\n * the interpreter and the compiled output (the compiled path does not rebuild the\n * runtime `expected` array, so it reads this precomputed set instead).\n *\n * The result is DEDUPLICATED. Deriving through a nullable prefix re-reaches the\n * same token from several terms \u2014 a value grammar whose leading terms are all\n * optional names its value-start set once per term \u2014 and an expectation list that\n * offers `\"@{\"` five times is wrong for a reader and expensive for a parser: a\n * choice that loses every arm materializes `[...arm0, ...arm1, \u2026]` at runtime, and\n * those arrays feed the enclosing choice's concat in turn, so duplicates compound\n * multiplicatively up the nesting. On jess's Less grammar the un-deduped sets cost\n * 32% of parse time on `benchmark.less` (medians 20.7 \u2192 14.2 ms over 100\n * interleaved pairs, 99/100 wins, min 19.1 \u2192 13.0), which is the whole of the Less\n * regression 0.35.0 shipped. Dedup is not an optimisation bolted onto the\n * derivation \u2014 a SET is what the derivation always meant.\n */\nexport function deriveExpected(c: Combinator<unknown>): string[] {\n return [...new Set(derive(c, new Set()))]\n}\n\nfunction derive(c: Combinator<unknown>, seen: Set<Combinator<unknown>>): string[] {\n const deriveExpected = (p: Combinator<unknown>): string[] => derive(p, seen)\n const def = c._def\n switch (def.tag) {\n case 'literal': return [JSON.stringify(def.value)]\n case 'regex': return [`/${def.source}/`]\n case 'keywords': return def.words.map(w => JSON.stringify(w))\n case 'label': return [def.label]\n case 'choice': return def.parsers.flatMap(deriveExpected)\n case 'dispatch': return deriveExpected(def.selector)\n // Union through the NULLABLE prefix, mirroring `sequenceFirstSet`. A leading\n // `optional(\u2026)`/`many(\u2026)` can match nothing, so the term after it is equally\n // able to fail first \u2014 deriving from term 0 alone named a token the parse\n // never actually required. A leading `not(\u2026)` is zero-width and contributes\n // nothing (its own expectation is about what must NOT be here), but it is\n // nullable, so keep scanning past it. Stop at the first term that must match.\n case 'sequence': {\n const out: string[] = []\n for (const term of def.parsers) {\n if (!isZeroWidthAssertion(term)) out.push(...deriveExpected(term))\n if (!matchesEmpty(term)) break\n }\n return out\n }\n case 'attempt': return deriveExpected(def.parser)\n // Delegating wrappers whose first-token failure is their inner parser's \u2014 must\n // pass through so a start-failure (and the first-set-miss fast-path in attempt/\n // node, which reads this) names the real expected token, not the wrapper tag.\n case 'field':\n case 'withCtx':\n case 'recover': return deriveExpected(def.parser)\n case 'skip': return deriveExpected(def.main)\n case 'expect': return def.expected\n case 'node':\n case 'grammar':\n case 'trivia':\n case 'token':\n case 'leaf':\n case 'optional':\n case 'many':\n case 'oneOrMore':\n case 'transform':\n case 'not':\n case 'peek': return deriveExpected(def.parser)\n // A bare routed() can only fail as \"there is no routed token here\". With a\n // fallback, THAT is the branch that can fail, so its expectations are the useful\n // ones \u2014 the routed path either succeeds or is not taken.\n case 'routed': return def.fallback === undefined ? ['routed()'] : deriveExpected(def.fallback)\n case 'lazy': {\n // An EXTERNAL ref (a rule from a composed base grammar) has no local\n // definition yet \u2014 its `thunk()` throws until fusion supplies it. Fall back\n // to the rule name as the expected label instead of descending.\n const name = (c as { _ruleName?: string })._ruleName\n // Cycle guard: a RECURSIVE rule re-enters its own definition forever. Reaching\n // one is newly possible now that `sequence` derives through a nullable prefix\n // (`list = choice('end', sequence(optional(item), list))` \u2014 term-0-only\n // derivation used to stop short of the self-reference). Falling back to the rule\n // name, exactly as for an unresolved external ref, cuts the cycle. Removed again\n // on the way out, so a rule referenced twice NON-cyclically still derives fully.\n if (seen.has(c)) return name ? [name] : []\n seen.add(c)\n try { return deriveExpected(def.thunk()) }\n catch { return name ? [name] : [] }\n finally { seen.delete(c) }\n }\n default: return []\n }\n}\n\n/**\n * Required-token combinator. Tries `combinator`; on success returns it verbatim.\n * On failure it does NOT fail \u2014 it records a {@link ParseError} (the statically\n * derived expected set, or `label` when given) into `ctx._errors` and RECOVERS IN\n * PLACE, returning a zero-width success so the enclosing sequence continues as if\n * the token were present.\n *\n * Use it to mark required delimiters/terminators (`}` `)` `;`, a selector before a\n * block) so a missing one is reported with position + expectation rather than\n * aborting the whole parse or being silently swallowed by a catch-all.\n *\n * sequence(literal('{'), declList, expect(literal('}')))\n *\n * Errors are only collected when the parse runs with `{ recover: true }`; without\n * it, expect() still recovers in place but records nothing (zero overhead beyond\n * the inner attempt).\n */\nexport function expect<T>(combinator: Combinator<T>, label?: string): Combinator<T | ParseError> {\n const expected = label !== undefined ? [label] : deriveExpected(combinator)\n const meta: ParserMeta = {\n firstSet: combinator._meta.firstSet,\n canMatchNewline: combinator._meta.canMatchNewline,\n isTrivia: false,\n }\n return {\n _tag: 'expect',\n _meta: meta,\n _def: { tag: 'expect', parser: combinator as Combinator<unknown>, label, expected },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T | ParseError> {\n const result = combinator.parse(input, pos, ctx)\n if (result.ok) return result as ParseResult<T | ParseError>\n const span = { start: pos, end: pos }\n const error: ParseError = { _tag: 'parseError', span: ctx.trackLines ? annotateSpanFromLineContext(span, ctx) : span, expected }\n ctx._errors?.push(error)\n // Embed the missing-token error as a `parseError` CST child (no-op when CST\n // capture is off), so it rides the tree exactly like list-recovery errors \u2014\n // a tree walk finds every diagnostic and the error survives incremental\n // reuse, rather than living only in the flat ctx._errors side-channel. Gated\n // on tolerant like the list-recovery embed sites, so a strict CST build is\n // byte-identical to before (and stays in parity with the compiled path,\n // which can only embed when the recovery bundle `_rec` is installed).\n if (ctx._tolerant) captureError(ctx, error)\n return { ok: true, value: error, span: { start: pos, end: pos } }\n },\n }\n}\n\n/** True when `value` is a recovery {@link ParseError} node. */\nexport function isParseError(value: unknown): value is ParseError {\n return typeof value === 'object' && value !== null && (value as ParseError)._tag === 'parseError'\n}\n", "/**\n * Low-level regex char-class primitives, shared by every hand-rolled regex\n * analysis in the codebase \u2014 the interpreter's first-set walker\n * (`./first-set.ts`), `regex()`'s short-scan fast path, and codegen's scannable\n * lowering (`../compiler/scannable-run.ts`). Kept dependency-free (no combinator,\n * no codegen imports) so it lands in even the leanest interpreter bundle.\n *\n * Everything here parses a regex STRUCTURE to code-point ranges; nothing encodes\n * a specific byte meaning (\"this is whitespace\"). `\\d`/`\\w` lower to their ASCII\n * ranges (correct for the default, non-`u` engine); `\\s` uses the fixed\n * `SPACE_RANGES` set (unaffected by the `u` flag).\n */\n\n/** Single-char escapes whose code point is fixed regardless of context. */\nexport const CLASS_ESCAPES: Record<string, number> = { t: 9, n: 10, r: 13, f: 12, v: 11, '0': 0 }\n\n/**\n * `\\s`'s code-point set per the spec's `WhiteSpace` + `LineTerminator`\n * productions \u2014 TAB/LF/VT/FF/CR, SPACE, NBSP, and the Unicode `Zs` space\n * separators. Fixed regardless of the `u` flag, so always safe to lower.\n */\nexport const SPACE_RANGES: Array<[number, number]> = [\n [9, 13], [32, 32], [160, 160], [5760, 5760], [8192, 8202],\n [8232, 8232], [8233, 8233], [8239, 8239], [8287, 8287], [12288, 12288], [65279, 65279],\n]\n\n/**\n * ASCII code-point ranges for the shorthand classes we lower. `\\d`/`\\w` are\n * ASCII-only in the default (non-`u`) engine; `\\s` maps to `SPACE_RANGES`.\n */\nexport function shorthandRanges(ch: 'd' | 'w' | 's'): Array<[number, number]> {\n if (ch === 'd') return [[48, 57]]\n if (ch === 's') return SPACE_RANGES\n // Order matches the canonical `scannable-run` lowering (underscore last), so\n // `ScanShape` output and generated code stay byte-identical. Membership is\n // order-independent (ranges are iterated / the FirstSet union sorts), so the\n // non-sorted order is purely representational \u2014 see PR #16 discussion.\n return [[48, 57], [65, 90], [97, 122], [95, 95]]\n}\n\n/** `\\uXXXX` at `body[i]` \u2192 its code point and the index past it, or null. */\nexport function readUnicodeEscape(body: string, i: number): { cp: number; next: number } | null {\n if (body[i] !== '\\\\' || body[i + 1] !== 'u') return null\n const hex = body.slice(i + 2, i + 6)\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null\n return { cp: Number.parseInt(hex, 16), next: i + 6 }\n}\n\ntype ClassAtom = { cp: number } | { set: Array<[number, number]> }\n\n/**\n * Parse a regex char-class body (the chars BETWEEN `[` and `]`, negation `^`\n * already stripped by the caller) to code-point ranges. `\\d`/`\\w`/`\\s` expand to\n * their ranges; `\\uXXXX` and the fixed single-char escapes resolve to their code\n * point; any other letter escape (`\\D`, `\\W`, `\\S`, `\\b`, \u2026) returns null rather\n * than being mis-read as a literal letter, so callers fall back to a safe\n * over-approximation instead of a wrong set.\n */\nexport function parseClassRanges(body: string): Array<[number, number]> | null {\n const ranges: Array<[number, number]> = []\n let i = 0\n const readAtom = (): ClassAtom | null => {\n const ch = body[i]\n if (ch === undefined) return null\n if (ch === '\\\\') {\n const uni = readUnicodeEscape(body, i)\n if (uni) {\n i = uni.next\n return { cp: uni.cp }\n }\n const e = body[i + 1]\n if (e === undefined) return null\n i += 2\n if (e in CLASS_ESCAPES) return { cp: CLASS_ESCAPES[e]! }\n if (e === 'd' || e === 'w' || e === 's') return { set: shorthandRanges(e) }\n // Any other letter escape is a class we can't safely lower (\\D, \\W, \\S, \u2026).\n if ((e >= 'a' && e <= 'z') || (e >= 'A' && e <= 'Z')) return null\n return { cp: e.codePointAt(0)! }\n }\n i += ch.length\n return { cp: ch.codePointAt(0)! }\n }\n while (i < body.length) {\n const lo = readAtom()\n if (lo === null) return null\n if ('set' in lo) {\n ranges.push(...lo.set)\n continue\n }\n if (body[i] === '-' && body[i + 1] !== undefined && body[i + 1] !== ']') {\n i += 1\n const hi = readAtom()\n if (hi === null || 'set' in hi) return null\n ranges.push([lo.cp, hi.cp])\n } else {\n ranges.push([lo.cp, lo.cp])\n }\n }\n return ranges.length ? ranges : null\n}\n", "import type { Combinator, ParseContext, ParseFail, ParseResult } from '../types.ts'\nimport { parseClassRanges } from '../regex/classes.ts'\nimport {\n analyzeLabeledTrivia,\n recordTriviaChunks,\n scanLabeledTriviaEnd,\n scanLabeledTriviaChunks,\n visitLabeledTrivia,\n} from '../cst/trivia-kinds.ts'\nimport {\n pushCstTriviaEntry,\n pushTriviaLogEntry,\n rollbackCstCapture,\n saveCstMark,\n} from '../cst/capture-buffer.ts'\nimport { recordLineRangeFromContext } from '../line-index.ts'\n\n/**\n * Result of scanning trivia: the position after it, plus a `commit()` that\n * records the matched trivia tokens into the active rawChildren collector.\n * Recording is deferred so callers that may reject the following item (e.g.\n * many()/oneOrMore() retries) can advance speculatively without recording\n * trivia that doesn't actually sit between two accepted items.\n */\nexport type TriviaScan = { end: number; commit: () => void }\n\n/** Saved lengths for rolling back speculative trivia commits. */\nexport type TriviaRollbackMark = { raw: number; tlog: number; leaves: number; fields: number; errors: number; log: number; rootLog: number }\n\nconst NOOP_COMMIT = () => {}\ntype FastTriviaScanner = (input: string, cur: number) => number\nconst fastTriviaCache = new WeakMap<Combinator<unknown>, FastTriviaScanner | null>()\n\n/** True when trivia recording must be deferred until the following term commits. */\nexport function needsDeferredTriviaCommit(ctx: ParseContext): boolean {\n return ctx._triviaLog !== undefined || ctx._rootTriviaLog !== undefined || ctx._cstBuf !== undefined || ctx._cstTriviaLog !== undefined\n}\n\nexport function saveTriviaMark(ctx: ParseContext): TriviaRollbackMark {\n const m = saveCstMark(ctx)\n return {\n raw: m.raw,\n tlog: m.tlog,\n leaves: m.leaves,\n fields: m.fields,\n errors: m.errors,\n log: ctx._triviaLog ? ctx._triviaLog.length : 0,\n rootLog: ctx._rootTriviaLog ? ctx._rootTriviaLog.length : 0,\n }\n}\n\nexport function rollbackTrivia(ctx: ParseContext, mark: TriviaRollbackMark): void {\n rollbackCstCapture(ctx, { raw: mark.raw, tlog: mark.tlog, leaves: mark.leaves, fields: mark.fields, errors: mark.errors })\n // Guarded like every other truncation \u2014 see rollbackCstCapture.\n if (ctx._triviaLog && ctx._triviaLog.length !== mark.log) ctx._triviaLog.length = mark.log\n if (ctx._rootTriviaLog && ctx._rootTriviaLog.length !== mark.rootLog) ctx._rootTriviaLog.length = mark.rootLog\n}\n\nfunction parseTriviaNoCapture(\n triviaP: Combinator<unknown>,\n input: string,\n cur: number,\n ctx: ParseContext,\n): ParseResult<unknown> {\n const probeCtx: ParseContext = {\n trackLines: ctx.trackLines,\n state: ctx.state,\n ...(ctx._lineIndex ? { _lineIndex: ctx._lineIndex } : {}),\n ...(ctx._lineStarts ? { _lineStarts: ctx._lineStarts } : {}),\n ...(ctx._lineScannedTo !== undefined ? { _lineScannedTo: ctx._lineScannedTo } : {}),\n }\n const result = triviaP.parse(input, cur, probeCtx)\n ctx._lineScannedTo = probeCtx._lineScannedTo\n return result\n}\n\n/**\n * A ZERO-WIDTH LOOKAHEAD's mark: everything `saveTriviaMark` covers, plus the\n * completions probe's current best failure.\n *\n * `_probe` is a sink like any other \u2014 `failAt` (probe.ts) replaces\n * `ctx._probe.best` whenever a failure lands at or before the cursor \u2014 but it is\n * deliberately NOT part of `rollbackTrivia`, because most rollbacks must leave it\n * alone. A failed `choice` arm or `sequence` term SHOULD keep its contribution:\n * merging the expectations of alternatives that failed at the cursor is exactly\n * how `completionsAt` builds its set.\n *\n * A lookahead is the exception. `peek`/`not` consume nothing on EITHER outcome\n * and promise to leave no observable trace, so expectations raised INSIDE the\n * probe are not reachable from the enclosing grammar at the cursor:\n * `peek(sequence(literal('a'), literal('zzz')))` over `\"ab\"` offered `\"zzz\"` as\n * the ONLY completion, though no input can ever reach it there.\n */\nexport type LookaheadMark = TriviaRollbackMark & { probeBest: ParseFail | null }\n\nexport function saveLookaheadMark(ctx: ParseContext): LookaheadMark {\n return { ...saveTriviaMark(ctx), probeBest: ctx._probe ? ctx._probe.best : null }\n}\n\nexport function rollbackLookahead(ctx: ParseContext, mark: LookaheadMark): void {\n rollbackTrivia(ctx, mark)\n if (ctx._probe) ctx._probe.best = mark.probeBest\n}\n\nfunction scanWithLabels(input: string, cur: number, ctx: ParseContext): TriviaScan {\n const triviaP = ctx.trivia!\n const spec = analyzeLabeledTrivia(triviaP)\n if (!spec) return { end: cur, commit: NOOP_COMMIT }\n\n const log = ctx._triviaLog\n const rootLog = ctx._rootTriviaLog\n const rootKinds = ctx._rootTriviaKindIndex\n const captureTl = ctx.captureTrivia && (ctx._cstBuf !== undefined || ctx._cstTriviaLog !== undefined)\n const mask = ctx._triviaCaptureMask\n let fullRows: number[] | undefined\n let rootRows: number[] | undefined\n let cstRows: number[] | undefined\n const visitedEnd = visitLabeledTrivia(input, cur, spec, ctx.state, (start, matchEnd, kindIndex) => {\n if (log !== undefined) (fullRows ??= []).push(start, matchEnd, kindIndex)\n const selectedKind = rootLog === undefined || rootKinds === undefined || ctx._rootTriviaCapture === false\n ? undefined\n : rootKinds[spec.labels[kindIndex] ?? '']\n if (selectedKind !== undefined) (rootRows ??= []).push(start, matchEnd, selectedKind)\n if (captureTl && (mask === undefined || (mask & (1 << kindIndex)) !== 0)) {\n (cstRows ??= []).push(start, matchEnd, kindIndex)\n }\n })\n if (visitedEnd !== undefined) {\n if (visitedEnd === cur) return { end: cur, commit: NOOP_COMMIT }\n return {\n end: visitedEnd,\n commit: () => {\n if (fullRows !== undefined && log !== undefined) log.push(...fullRows)\n if (rootRows !== undefined && rootLog !== undefined) {\n for (let i = 0; i < rootRows.length; i += 3) {\n rootLog.push(cur, visitedEnd, rootRows[i]!, rootRows[i + 1]!, rootRows[i + 2]!)\n }\n }\n if (cstRows !== undefined) {\n for (let i = 0; i < cstRows.length; i += 3) {\n pushCstTriviaEntry(ctx, cstRows[i]!, cstRows[i + 1]!, cstRows[i + 2]!)\n }\n }\n },\n }\n }\n\n const { end, chunks } = scanLabeledTriviaChunks(input, cur, spec, ctx.state)\n if (end === cur) return { end: cur, commit: NOOP_COMMIT }\n\n return {\n end,\n commit: () => recordTriviaChunks(ctx, chunks),\n }\n}\n\n/** Skip classified trivia without constructing retained chunk records. */\nfunction skipWithLabels(input: string, cur: number, ctx: ParseContext): number {\n const spec = analyzeLabeledTrivia(ctx.trivia!)\n if (spec) return scanLabeledTriviaEnd(input, cur, spec, ctx.state)\n const tr = parseTriviaNoCapture(ctx.trivia!, input, cur, ctx)\n return tr.ok && tr.span.end > cur ? tr.span.end : cur\n}\n\n/**\n * Skip trivia at `cur` and return the new position. No recording, no wrapper\n * object \u2014 use between sequence/repeat terms when CST trivia capture is off.\n */\nexport function advanceTrivia(input: string, cur: number, ctx: ParseContext): number {\n const triviaP = ctx.trivia\n if (!triviaP) return cur\n if (!ctx.trackLines) {\n const fast = fastTriviaScanner(triviaP)\n if (fast) return fast(input, cur)\n if (ctx.triviaKindLabels) return skipWithLabels(input, cur, ctx)\n const tr = triviaP.parse(input, cur, { trackLines: ctx.trackLines, state: ctx.state })\n return tr.ok && tr.span.end > cur ? tr.span.end : cur\n }\n const trackTriviaLines = ctx.trackLines && triviaP._meta.canMatchNewline\n const fast = fastTriviaScanner(triviaP)\n if (fast) {\n const end = fast(input, cur)\n if (trackTriviaLines) recordLineRangeFromContext(ctx, input, cur, end)\n return end\n }\n if (ctx.triviaKindLabels) {\n const end = skipWithLabels(input, cur, ctx)\n if (trackTriviaLines) recordLineRangeFromContext(ctx, input, cur, end)\n return end\n }\n const tr = parseTriviaNoCapture(triviaP, input, cur, ctx)\n return tr.ok && tr.span.end > cur ? tr.span.end : cur\n}\n\n/**\n * Scan trivia at `cur` using `ctx.trivia`, WITHOUT recording it. Returns the\n * position after the trivia (or `cur` if none) and a `commit()` to record it.\n */\nexport function scanTrivia(input: string, cur: number, ctx: ParseContext): TriviaScan {\n const triviaP = ctx.trivia\n if (!triviaP) return { end: cur, commit: NOOP_COMMIT }\n\n const log = ctx._triviaLog\n const rootLog = ctx._rootTriviaLog\n const captureTl = ctx.captureTrivia && (ctx._cstBuf !== undefined || ctx._cstTriviaLog !== undefined)\n if (!ctx.trackLines) {\n const fast = !ctx.triviaKindLabels ? fastTriviaScanner(triviaP) : null\n if (fast && log === undefined && !captureTl) {\n return { end: fast(input, cur), commit: NOOP_COMMIT }\n }\n\n if (ctx.triviaKindLabels && (log !== undefined || rootLog !== undefined || captureTl)) {\n return scanWithLabels(input, cur, ctx)\n }\n\n if (ctx.triviaKindLabels) return { end: skipWithLabels(input, cur, ctx), commit: NOOP_COMMIT }\n\n if (log !== undefined || rootLog !== undefined || captureTl) {\n const tr = triviaP.parse(input, cur, {\n trackLines: log !== undefined ? false : ctx.trackLines,\n state: ctx.state,\n })\n if (!tr.ok || tr.span.end === cur) return { end: cur, commit: NOOP_COMMIT }\n const end = tr.span.end\n return {\n end,\n commit: () => {\n pushTriviaLogEntry(ctx, cur, end)\n if (captureTl) pushCstTriviaEntry(ctx, cur, end)\n },\n }\n }\n\n const tr = triviaP.parse(input, cur, { trackLines: ctx.trackLines, state: ctx.state })\n return { end: tr.ok ? tr.span.end : cur, commit: NOOP_COMMIT }\n }\n const trackTriviaLines = ctx.trackLines && triviaP._meta.canMatchNewline\n\n const fast = !ctx.triviaKindLabels ? fastTriviaScanner(triviaP) : null\n if (fast && log === undefined && !captureTl) {\n const end = fast(input, cur)\n if (trackTriviaLines) recordLineRangeFromContext(ctx, input, cur, end)\n return { end, commit: NOOP_COMMIT }\n }\n\n if (ctx.triviaKindLabels && (log !== undefined || rootLog !== undefined || captureTl)) {\n const scan = scanWithLabels(input, cur, ctx)\n if (trackTriviaLines) recordLineRangeFromContext(ctx, input, cur, scan.end)\n return scan\n }\n\n if (ctx.triviaKindLabels) {\n const end = skipWithLabels(input, cur, ctx)\n if (trackTriviaLines) recordLineRangeFromContext(ctx, input, cur, end)\n return { end, commit: NOOP_COMMIT }\n }\n\n if (log !== undefined || rootLog !== undefined || captureTl) {\n const tr = parseTriviaNoCapture(triviaP, input, cur, ctx)\n if (!tr.ok || tr.span.end === cur) return { end: cur, commit: NOOP_COMMIT }\n const end = tr.span.end\n return {\n end,\n commit: () => {\n pushTriviaLogEntry(ctx, cur, end)\n if (captureTl) pushCstTriviaEntry(ctx, cur, end)\n },\n }\n }\n\n const tr = parseTriviaNoCapture(triviaP, input, cur, ctx)\n return { end: tr.ok ? tr.span.end : cur, commit: NOOP_COMMIT }\n}\n\n/**\n * Consume trivia at `cur`, recording it immediately. For callers that always\n * accept the trivia between two committed terms (e.g. sequence/sepBy).\n */\nexport function consumeTrivia(input: string, cur: number, ctx: ParseContext): number {\n if (!needsDeferredTriviaCommit(ctx)) return advanceTrivia(input, cur, ctx)\n const scan = scanTrivia(input, cur, ctx)\n scan.commit()\n return scan.end\n}\n\nfunction fastTriviaScanner(trivia: Combinator<unknown>): FastTriviaScanner | null {\n const cached = fastTriviaCache.get(trivia)\n if (cached !== undefined) return cached\n const scanner = buildFastTriviaScanner(trivia)\n fastTriviaCache.set(trivia, scanner)\n return scanner\n}\n\nfunction buildFastTriviaScanner(trivia: Combinator<unknown>): FastTriviaScanner | null {\n const core = trivia._def.tag === 'trivia' ? trivia._def.parser : trivia\n const direct = regexTriviaScanner(core)\n if (direct) return direct\n\n const repeat = core._def.tag === 'oneOrMore' || (core._def.tag === 'many' && core._def.min >= 1)\n ? core._def.parser\n : null\n if (!repeat) return null\n\n const one = regexTriviaScanner(repeat)\n if (one) return loopScanner([one])\n\n if (repeat._def.tag !== 'choice') return null\n const arms = repeat._def.parsers.map(regexTriviaScanner)\n if (arms.some(s => s === null)) return null\n return loopScanner(arms as FastTriviaScanner[])\n}\n\nfunction loopScanner(arms: FastTriviaScanner[]): FastTriviaScanner {\n return (input, cur) => {\n let pos = cur\n scan: while (pos < input.length) {\n for (const arm of arms) {\n const end = arm(input, pos)\n if (end > pos) {\n pos = end\n continue scan\n }\n }\n break\n }\n return pos\n }\n}\n\nfunction regexTriviaScanner(parser: Combinator<unknown>): FastTriviaScanner | null {\n if (parser._def.tag !== 'regex' || parser._def.flags) return null\n const source = parser._def.source\n return classRunSource(source)\n ?? altStarSource(source)\n}\n\nfunction inRanges(cp: number, ranges: Array<[number, number]>): boolean {\n for (let i = 0; i < ranges.length; i++) {\n const r = ranges[i]!\n if (cp >= r[0] && cp <= r[1]) return true\n }\n return false\n}\n\n/** Greedy scanner for a positive char-class body (`^`-negated bodies are rejected upstream). */\nfunction classScanner(classBody: string): FastTriviaScanner | null {\n const ranges = parseClassRanges(classBody)\n if (!ranges) return null\n return (input, cur) => {\n let pos = cur\n while (pos < input.length && inRanges(input.charCodeAt(pos), ranges)) pos++\n return pos\n }\n}\n\n/** Scanner for a `C[^\\n\\r]*` arm \u2014 consumes its leader through a line break. */\nfunction untilLineBreakScanner(leaderCode: number): FastTriviaScanner {\n return (input, cur) => {\n if (input.charCodeAt(cur) !== leaderCode) return cur\n let pos = cur + 1\n while (pos < input.length) {\n const cc = input.charCodeAt(pos)\n if (cc === 10 || cc === 13) break\n pos++\n }\n return pos\n }\n}\n\n/** A bare positive char-class run `[class]*` / `[class]+` (`[ \\t\\n\\r,]*`, \u2026). */\nfunction classRunSource(source: string): FastTriviaScanner | null {\n const m = /^\\[([^\\]^](?:[^\\]]|\\\\.)*)\\][*+]$/.exec(source)\n return m ? classScanner(m[1]!) : null\n}\n\n/**\n * One alternation arm of a `(?:\u2026)*` trivia group: a positive char-class run\n * `[class]` (a trailing `+`/`*` is redundant under the enclosing loop) or a line\n * line-terminated arm `C[^\\n\\r]*` (`C` = one literal leader char, maybe escaped). Anything\n * else is unclassifiable \u2192 no fast path, never a wrong one.\n */\ntype TriviaArm =\n | { kind: 'class'; ranges: Array<[number, number]> }\n | { kind: 'untilLineBreak'; code: number }\n\nfunction classifyTriviaArm(arm: string): TriviaArm | null {\n const cls = /^\\[([^\\]^](?:[^\\]]|\\\\.)*)\\][*+]?$/.exec(arm)\n if (cls) {\n const ranges = parseClassRanges(cls[1]!)\n return ranges ? { kind: 'class', ranges } : null\n }\n const lc = /^(\\\\?.)\\[\\^\\\\n\\\\r\\]\\*$/.exec(arm)\n if (lc) {\n const marker = lc[1]!\n return { kind: 'untilLineBreak', code: (marker.length === 2 ? marker[1]! : marker[0]!).charCodeAt(0) }\n }\n return null\n}\n\nfunction armScanner(arm: TriviaArm): FastTriviaScanner {\n if (arm.kind === 'untilLineBreak') return untilLineBreakScanner(arm.code)\n const ranges = arm.ranges\n return (input, cur) => {\n let pos = cur\n while (pos < input.length && inRanges(input.charCodeAt(pos), ranges)) pos++\n return pos\n }\n}\n\n/**\n * A single tight loop over a merged char-class range list plus (usually one)\n * line-terminated leader \u2014 the fast form of `(?:[class]|C[^\\n\\r]*)*`. Requires the\n * caller to have checked marker/class disjointness (so a bare merged scan\n * matches the regex regardless of arm order).\n */\nfunction fusedTriviaScanner(ranges: Array<[number, number]>, leaders: number[]): FastTriviaScanner {\n const c0 = leaders[0]!\n const single = leaders.length === 1\n return (input, cur) => {\n let pos = cur\n const len = input.length\n for (;;) {\n const c = input.charCodeAt(pos)\n if (pos < len && inRanges(c, ranges)) { pos++; continue }\n if (single ? c === c0 : leaders.includes(c)) {\n pos++\n while (pos < len) {\n const cc = input.charCodeAt(pos)\n if (cc === 10 || cc === 13) break\n pos++\n }\n continue\n }\n break\n }\n return pos\n }\n}\n\n/** Split a `(?:\u2026)*` body on top-level `|`, respecting `[\u2026]`; bail on nested groups. */\nfunction splitTopLevelAlts(body: string): string[] | null {\n const arms: string[] = []\n let inClass = false\n let start = 0\n for (let i = 0; i < body.length; i++) {\n const c = body[i]\n if (c === '\\\\') { i++; continue }\n if (inClass) { if (c === ']') inClass = false; continue }\n if (c === '[') inClass = true\n else if (c === '(') return null // nested group \u2014 leave it to RegExp.exec\n else if (c === '|') { arms.push(body.slice(start, i)); start = i + 1 }\n }\n arms.push(body.slice(start))\n return arms\n}\n\n/**\n * Trivia written as a single regex alternation-star, `(?:arm|arm|\u2026)*` \u2014 e.g.\n * `(?:[ \\t\\n\\r,]|#[^\\n\\r]*)*`. Arms are classified independently and\n * order-independently: char-class arms merge into one range list and line-terminated\n * leaders are collected, so `(?:#\u2026|[class])*` scans the same as `(?:[class]|#\u2026)*`.\n * The common (disjoint) case compiles to one fused loop; a leader that also sits\n * inside a class is the one spot where arm order matters, so that falls back to\n * the ordered `loopScanner`.\n */\nfunction altStarSource(source: string): FastTriviaScanner | null {\n const m = /^\\(\\?:(.*)\\)[*+]$/.exec(source)\n if (!m) return null\n const armSrcs = splitTopLevelAlts(m[1]!)\n if (!armSrcs || armSrcs.length < 2) return null\n const arms: TriviaArm[] = []\n for (const src of armSrcs) {\n const arm = classifyTriviaArm(src)\n if (!arm) return null\n arms.push(arm)\n }\n const ranges: Array<[number, number]> = []\n const leaders: number[] = []\n for (const arm of arms) {\n if (arm.kind === 'class') ranges.push(...arm.ranges)\n else leaders.push(arm.code)\n }\n if (leaders.some(code => inRanges(code, ranges))) {\n return loopScanner(arms.map(armScanner)) // order-significant overlap\n }\n if (leaders.length === 0) return armScanner({ kind: 'class', ranges })\n return fusedTriviaScanner(ranges, leaders)\n}\n", "import type {\n Combinator, ParseContext, ParseResult, ParserMeta, FirstSet,\n AutoNotCheck, CharRange, ChoiceStrategy, GatedArm,\n} from '../types.ts'\nimport { union, intersects, matchesEmpty } from './first-set.ts'\nimport { deriveExpected } from './expect.ts'\nimport { rollbackTrivia, saveTriviaMark } from './trivia-skip.ts'\n\ntype ArmParser<T> = T extends GatedArm<infer U> ? Combinator<U> : T extends Combinator<infer U> ? Combinator<U> : never\ntype UnionArms<T extends (Combinator<unknown> | GatedArm<unknown>)[]> = {\n [K in keyof T]: ArmParser<T[K]>\n}[number] extends Combinator<infer U> ? U : never\n\nexport function choice<T extends [Combinator<unknown> | GatedArm<unknown>, ...(Combinator<unknown> | GatedArm<unknown>)[]]>(\n ...args: T\n): Combinator<UnionArms<T>> {\n // Unwrap gated arms into (parser, gate) pairs\n const parsers = args.map(a => ('gate' in a ? a.combinator : a)) as Combinator<unknown>[]\n const gates = args.map(a => ('gate' in a ? a.gate : null)) as (((state: unknown) => boolean) | null)[]\n\n const hasGates = gates.some(g => g !== null)\n\n // O(1) first-char dispatch is sound when arms are pairwise-disjoint in their\n // first char AND no arm can match empty. Non-nullability is what makes a GATED\n // arm keep its dispatch slot: a gated arm is normally *skipped* so a later arm\n // can retry the same position \u2014 but if every arm is non-nullable and first-sets\n // are disjoint, no later arm can match this first char, so \"skip the gate then\n // retry\" is exactly \"dispatch to this arm, check its gate, and fail the choice\n // if the gate is false\". Every OTHER first char dispatches as before and never\n // touches the gate. A nullable arm matches at ANY position (zero-width), so\n // first-char dispatch can't represent it \u2192 such choices stay on firstMatch.\n // (Requiring non-nullability universally also tightens the ungated path, which\n // was already unsound for a nullable-but-first-set-disjoint arm; in practice no\n // ungated disjoint choice has a nullable arm, so codegen output is unchanged.)\n const disjoint = areDisjoint(parsers.map(p => p._meta.firstSet))\n && parsers.every(p => !matchesEmpty(p))\n\n let combined: FirstSet = { kind: 'empty' }\n for (const p of parsers) combined = union(combined, p._meta.firstSet)\n\n const meta: ParserMeta = {\n firstSet: combined,\n canMatchNewline: parsers.some(p => p._meta.canMatchNewline),\n isTrivia: false,\n disjoint,\n }\n\n // A disjoint choice dispatches by first char (gated arms check their gate inside\n // the dispatched branch); a NON-disjoint gated choice falls to firstMatch \u2014 the\n // greedy/longest-first strategies are incompatible with per-arm predicates.\n const strategy = (disjoint || hasGates) ? null : detectStrategy(parsers)\n // `sharedPrefix` is a `firstMatch` specialization \u2014 the interpreter runs it via\n // the firstMatch loop below, and codegen falls back to firstMatch under\n // coverage/recovery/linkable \u2014 so it needs the same auto-not table computed.\n const autoNot = (!disjoint && !hasGates && (strategy?.tag === 'firstMatch' || strategy?.tag === 'sharedPrefix'))\n ? computeAutoNot(parsers)\n : parsers.map(() => null)\n\n // Runtime state for each strategy (built once, reused on every parse call):\n let greedyLitMap: Map<string, number> | null = null\n let sortedParsers: Combinator<unknown>[] | null = null\n const asciiDispatch = disjoint ? buildAsciiDispatch(parsers) : null\n\n if (strategy?.tag === 'greedyClassify') {\n greedyLitMap = new Map()\n for (let i = 0; i < parsers.length; i++) {\n if (i === strategy.superIndex) continue\n const litVal = getCoreLiteralValue(parsers[i]!)\n if (litVal !== null) greedyLitMap.set(litVal, i)\n }\n } else if (strategy?.tag === 'literalsLongestFirst') {\n sortedParsers = strategy.sortedIndices.map(i => parsers[i]!)\n }\n\n return {\n _tag: 'choice',\n _meta: meta,\n _def: {\n tag: 'choice',\n parsers,\n gates,\n disjoint,\n strategy: strategy ?? { tag: 'firstMatch' },\n autoNot,\n },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<UnionArms<T>> {\n const expected: string[] = []\n\n // \u2500\u2500 Disjoint: O(1) first-char dispatch (arms may be gated) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (disjoint && pos < input.length) {\n const code = input.codePointAt(pos)!\n let idx = code < 128 ? asciiDispatch![code]! : -1\n if (idx < 0) {\n for (let i = 0; i < parsers.length; i++) {\n if (inFirstSet(code, parsers[i]!._meta.firstSet)) { idx = i; break }\n }\n }\n if (idx >= 0) {\n const gate = gates[idx]\n if (gate && !gate(ctx.state)) {\n // Gate blocks this arm. Disjointness + non-nullable arms guarantee no\n // OTHER arm can match this first char, so skip-and-retry is exactly\n // fail-the-choice \u2014 we must not fall through to another arm.\n return { ok: false, expected: deriveExpected(parsers[idx]!), span: { start: pos, end: pos } }\n }\n const result = parsers[idx]!.parse(input, pos, ctx)\n if (result.ok) return result as ParseResult<UnionArms<T>>\n expected.push(...result.expected)\n if (result.committed) return { ok: false, expected, span: { start: pos, end: pos }, committed: true }\n return { ok: false, expected, span: { start: pos, end: pos } }\n }\n return {\n ok: false,\n expected: parsers.flatMap(p => {\n const r = p.parse(input, pos, ctx)\n return r.ok ? [] : r.expected\n }),\n span: { start: pos, end: pos },\n }\n }\n\n // \u2500\u2500 greedyClassify: run one regex, classify by string equality \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // One parse call total. No backtracking.\n if (strategy?.tag === 'greedyClassify') {\n const superResult = parsers[strategy.superIndex]!.parse(input, pos, ctx)\n if (!superResult.ok) return superResult as ParseResult<UnionArms<T>>\n\n const end = superResult.span.end\n const litIdx = greedyLitMap!.get(input.slice(pos, end))\n if (litIdx !== undefined) {\n const litVal = getCoreLiteralValue(parsers[litIdx]!)!\n const value = applyTransforms(parsers[litIdx]!, litVal, { start: pos, end })\n return { ok: true, value: value as UnionArms<T>, span: { start: pos, end } }\n }\n return superResult as ParseResult<UnionArms<T>>\n }\n\n // \u2500\u2500 literalsLongestFirst: sorted descending by length, no backtracking \u2500\n if (strategy?.tag === 'literalsLongestFirst') {\n for (const p of sortedParsers!) {\n const r = p.parse(input, pos, ctx)\n if (r.ok) return r as ParseResult<UnionArms<T>>\n expected.push(...r.expected)\n }\n return { ok: false, expected, span: { start: pos, end: pos } }\n }\n\n // \u2500\u2500 firstMatch (+ gated arms): try each arm in order, skipping gated-off arms \u2500\u2500\n for (let i = 0; i < parsers.length; i++) {\n if (gates[i] && !gates[i]!(ctx.state)) continue // gate blocks this arm\n // Save leaf-array lengths so a failed/rejected arm can be rolled back.\n const mark = saveTriviaMark(ctx)\n const result = parsers[i]!.parse(input, pos, ctx)\n if (!result.ok) {\n rollbackTrivia(ctx, mark)\n expected.push(...result.expected)\n if (result.committed) return { ok: false, expected, span: result.span, committed: true }\n continue\n }\n const checks = autoNot[i]\n if (checks && autoNotFires(input, result.span.end, checks)) {\n rollbackTrivia(ctx, mark)\n continue\n }\n return result as ParseResult<UnionArms<T>>\n }\n return { ok: false, expected, span: { start: pos, end: pos } }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Strategy detection\n// ---------------------------------------------------------------------------\n\nfunction detectStrategy(parsers: Combinator<unknown>[]): ChoiceStrategy {\n // greedyClassify: exactly one regex arm whose regex matches every literal arm's\n // value exactly (and can potentially match more). All other arms must be literals.\n const regexIndices: number[] = []\n const literalIndices: number[] = []\n for (let i = 0; i < parsers.length; i++) {\n if (getCoreRegexDef(parsers[i]!) !== null) regexIndices.push(i)\n else if (getCoreLiteralValue(parsers[i]!) !== null) literalIndices.push(i)\n }\n\n if (\n regexIndices.length === 1 &&\n literalIndices.length === parsers.length - 1 &&\n literalIndices.length > 0\n ) {\n const superIndex = regexIndices[0]!\n const regexDef = getCoreRegexDef(parsers[superIndex]!)!\n const flags = 'y' + regexDef.flags.replace(/[gy]/g, '')\n const re = new RegExp(regexDef.source, flags)\n const allSubsumed = literalIndices.every(i => {\n const litVal = getCoreLiteralValue(parsers[i]!)!\n re.lastIndex = 0\n const m = re.exec(litVal)\n return m !== null && m[0] === litVal\n })\n if (allSubsumed) return { tag: 'greedyClassify', superIndex }\n }\n\n // literalsLongestFirst: every arm is a literal \u2014 try longest first, no backtracking\n if (parsers.length === literalIndices.length) {\n const sortedIndices = [...literalIndices].sort((a, b) =>\n getCoreLiteralValue(parsers[b]!)!.length - getCoreLiteralValue(parsers[a]!)!.length\n )\n return { tag: 'literalsLongestFirst', sortedIndices }\n }\n\n // sharedPrefix: EVERY arm is a bare sequence beginning with the SAME concrete\n // leading literal/regex \u2014 the compiler parses that left factor once. Detected\n // last (its shape is disjoint from the literal-only strategies above).\n const shared = detectSharedPrefix(parsers)\n if (shared !== null) return shared\n\n return { tag: 'firstMatch' }\n}\n\n/**\n * A stable structural key for a bare leading terminal (concrete literal/regex),\n * or `null` when the term is NOT a shareable concrete prefix. Deliberately\n * conservative: only an UNWRAPPED literal (case-sensitive) or regex qualifies \u2014\n * a transform/label/ref/node wrapper changes the value/capture shape and must NOT\n * be left-factored (correctness first; the strategy is opt-in like greedyClassify).\n */\nfunction bareLeadingTermKey(term: Combinator<unknown>): string | null {\n const d = term._def\n if (d.tag === 'literal' && !d.caseInsensitive) return `L:${d.value}`\n // `JSON.stringify` of the pair, not a delimiter join. `source` is arbitrary regex text\n // and can contain any character, so a collision here would judge two structurally\n // DIFFERENT regexes identical and left-factor arms that must not share a prefix \u2014 a\n // correctness bug in the generated parser, not a missed optimization. A JSON array is\n // injective by construction, so no argument about which delimiter cannot occur in a\n // regex source is needed. It is also printable: this was a RAW 0x00 byte, which made\n // the whole file binary to `git diff` and invisible to `grep -rn` (see\n // `scripts/check-control-bytes.mjs`). Runs once per choice when its strategy is chosen,\n // never per match.\n if (d.tag === 'regex') return `R:${JSON.stringify([d.source, d.flags])}`\n // Two lead shapes look eligible and are deliberately NOT. Both were tried and\n // measured; see test/unit/routed-fallback.test.ts, which pins the exclusions.\n //\n // `routed()` \u2014 a bare routed() IS a single-leaf terminal (it reads the\n // dispatch-consumed token, pushes exactly ONE leaf, skips no trivia, runs no\n // sub-parse), so it is replay-safe and admitting it here is correct. It is\n // excluded because it does not PAY. The strategy trades a duplicated lead scan for\n // a prescan plus a prefix-matched flag; routed()'s emission is a context read and\n // one comparison, so there is nothing worth factoring out. Measured on\n // `dispatch(name, when(k, choice(sequence(routed(), tail_i)...)))`, emitted bytes\n // with the strategy MINUS without it: +242 (2 arms), +260 (4), +296 (8) \u2014 it costs\n // more at every width and never crosses over. The same measurement on the\n // regex-lead shape the strategy was built for: -468 (2 arms), -1597 (4), -3846 (8).\n // A routed lead also shares only the ROUTED token; when the expensive shared work\n // is the next term (a prelude), that term is what needs factoring, not this one.\n //\n // `routed(fallback)` \u2014 not a leaf at all: on the fallback path it runs a whole\n // sub-parse, so replaying it as a once-recognized leaf would be wrong, and two\n // routed() with DIFFERENT fallbacks are not interchangeable to begin with.\n //\n // A `lazy` ref lead \u2014 excluded for correctness, not for want of a key. The\n // once-only prescan runs with `ctx.capturing = false`, which suppresses capture\n // only for code emitted HERE (emitLeafCapture, codegen.ts). A ref compiles to a\n // call into a function body generated under its OWN ctx (emitLazy), so its\n // captures and trivia writes would happen during the prescan and then AGAIN in\n // each arm. Replaying a ref needs recorded-and-spliced capture state, not the\n // variable reuse a terminal replay gets away with.\n return null\n}\n\n/**\n * Detect the pure single-group shared-prefix shape: at least two arms, EVERY arm\n * a bare `sequence` with \u22652 terms, and every arm's FIRST term the same concrete\n * literal/regex (identical source/flags or literal string). Returns the plan with\n * a representative prefix combinator (the first arm's leading term \u2014 all members'\n * leading terms are structurally identical, so any one emits identical code),\n * else `null`. Mixed / multi-group / wrapped shapes are conservatively skipped and\n * fall through to `firstMatch`.\n */\nfunction detectSharedPrefix(parsers: Combinator<unknown>[]): ChoiceStrategy | null {\n if (parsers.length < 2) return null\n let key: string | null = null\n let prefix: Combinator<unknown> | null = null\n const members: number[] = []\n for (let i = 0; i < parsers.length; i++) {\n const term0 = leadingTermOfArm(parsers[i]!)\n if (term0 === null) return null\n const k = bareLeadingTermKey(term0)\n if (k === null) return null\n if (key === null) { key = k; prefix = term0 }\n else if (k !== key) return null\n members.push(i)\n }\n if (prefix === null || members.length < 2) return null\n return { tag: 'sharedPrefix', prefix, members }\n}\n\n/**\n * Peel wrappers that neither consume input nor skip trivia before their inner\n * sequence -- `node`, `parser`/`grammar`, `transform`, `label` -- down to the core\n * `sequence` and return its FIRST term (the candidate shared prefix), or null when\n * the arm is not a wrapped-or-bare sequence with >=2 terms. Because none of these\n * wrappers advance the position before the sequence's first term, the term is parsed\n * at the arm's entry position in every arm, so the once-recognized prefix can be\n * replayed there. `attempt`/`optional`/`many`/`choice`/etc. are NOT peeled, so such\n * arms are conservatively excluded.\n */\nexport function leadingTermOfArm(arm: Combinator<unknown>): Combinator<unknown> | null {\n let d = arm._def\n for (;;) {\n if (d.tag === 'node' || d.tag === 'grammar' || d.tag === 'transform' || d.tag === 'label') {\n d = (d as { parser: Combinator<unknown> }).parser._def\n continue\n }\n break\n }\n if (d.tag !== 'sequence' || d.parsers.length < 2) return null\n return d.parsers[0]!\n}\n\n// ---------------------------------------------------------------------------\n// Auto-not analysis (firstMatch fallback only)\n// ---------------------------------------------------------------------------\n\nfunction computeAutoNot(parsers: Combinator<unknown>[]): (AutoNotCheck[] | null)[] {\n return parsers.map((p, i) => {\n const litVal = getCoreLiteralValue(p)\n if (litVal === null) return null\n\n const checks: AutoNotCheck[] = []\n for (let j = i + 1; j < parsers.length; j++) {\n const other = parsers[j]!\n const otherLit = getCoreLiteralValue(other)\n if (otherLit !== null && otherLit.startsWith(litVal) && otherLit.length > litVal.length) {\n checks.push({ kind: 'startsWith', value: otherLit.slice(litVal.length) })\n continue\n }\n const regexDef = getCoreRegexDef(other)\n if (regexDef !== null) {\n const contSet = continuationFirstSet(litVal, regexDef.source, regexDef.flags)\n if (contSet !== null) checks.push({ kind: 'firstSet', set: contSet })\n }\n }\n return checks.length > 0 ? checks : null\n })\n}\n\nfunction autoNotFires(input: string, end: number, checks: AutoNotCheck[]): boolean {\n for (const check of checks) {\n if (check.kind === 'firstSet') {\n const code = end < input.length ? (input.codePointAt(end) ?? -1) : -1\n if (inFirstSet(code, check.set)) return true\n } else {\n if (input.startsWith(check.value, end)) return true\n }\n }\n return false\n}\n\n// ---------------------------------------------------------------------------\n// Helpers: unwrap transform/sequence wrappers\n// ---------------------------------------------------------------------------\n\n/** Walk transform wrappers to find an inner literal's string value. */\nexport function getCoreLiteralValue(p: Combinator<unknown>): string | null {\n const def = p._def\n if (def.tag === 'literal' && !def.caseInsensitive) return def.value\n if (def.tag === 'transform') return getCoreLiteralValue(def.parser)\n return null\n}\n\n/** Walk transform wrappers to find an inner regex's source/flags. */\nexport function getCoreRegexDef(p: Combinator<unknown>): { source: string; flags: string } | null {\n const def = p._def\n if (def.tag === 'regex') return { source: def.source, flags: def.flags }\n if (def.tag === 'transform') return getCoreRegexDef(def.parser)\n if (def.tag === 'label') return getCoreRegexDef(def.parser)\n return null\n}\n\n/**\n * Apply a parser's transform chain to an already-known value, without re-parsing.\n * Used by greedyClassify to avoid a second parse call for the winning literal arm.\n */\nfunction applyTransforms(p: Combinator<unknown>, value: unknown, span: { start: number; end: number }): unknown {\n const def = p._def\n if (def.tag === 'transform') {\n const inner = applyTransforms(def.parser, value, span)\n return def.fn(inner, span)\n }\n return value\n}\n\n// ---------------------------------------------------------------------------\n// Continuation first-set (for firstMatch auto-not analysis)\n// ---------------------------------------------------------------------------\n\nfunction continuationFirstSet(lit: string, source: string, flags: string): FirstSet | null {\n const re = new RegExp(source, 'y' + flags.replace(/[gy]/g, ''))\n re.lastIndex = 0\n const base = re.exec(lit)\n if (!base || base[0] !== lit) return null\n\n const contCodes: number[] = []\n for (let code = 1; code < 128; code++) {\n re.lastIndex = 0\n const m = re.exec(lit + String.fromCharCode(code))\n if (m && m[0].length > lit.length) contCodes.push(code)\n }\n if (contCodes.length === 0) return null\n return codesToFirstSet(contCodes)\n}\n\nfunction codesToFirstSet(codes: number[]): FirstSet {\n codes.sort((a, b) => a - b)\n const ranges: CharRange[] = []\n let lo = codes[0]!, hi = codes[0]!\n for (let i = 1; i < codes.length; i++) {\n if (codes[i] === hi + 1) { hi = codes[i]! }\n else { ranges.push({ lo, hi }); lo = hi = codes[i]! }\n }\n ranges.push({ lo, hi })\n return { kind: 'ranges', ranges }\n}\n\nfunction inFirstSet(code: number, fs: FirstSet): boolean {\n if (fs.kind === 'any') return true\n if (fs.kind === 'empty') return false\n for (const r of fs.ranges) if (code >= r.lo && code <= r.hi) return true\n return false\n}\n\nfunction areDisjoint(sets: FirstSet[]): boolean {\n if (sets.some(s => s.kind === 'any')) return false\n for (let i = 0; i < sets.length; i++)\n for (let j = i + 1; j < sets.length; j++)\n if (intersects(sets[i]!, sets[j]!)) return false\n return true\n}\n\n// ASCII first-char \u2192 arm INDEX (not the parser) so a gated arm's gate can be\n// looked up (gates[idx]) at dispatch time. -1 means \"no arm keys off this char\".\nfunction buildAsciiDispatch(parsers: Combinator<unknown>[]): number[] {\n const table = Array<number>(128).fill(-1)\n for (let i = 0; i < parsers.length; i++) {\n const fs = parsers[i]!._meta.firstSet\n if (fs.kind !== 'ranges') continue\n for (const { lo, hi } of fs.ranges) {\n for (let code = Math.max(0, lo); code <= Math.min(127, hi); code++) {\n table[code] = i\n }\n }\n }\n return table\n}\n", "/**\n * Static grammar-duplication / overlap / rewrite diagnostic.\n *\n * A parseman grammar is a COMBINATOR TREE, not source text \u2014 so the question\n * \"did I write this production twice?\" is a structural one a machine answers\n * exactly, and a reviewer answers badly. A few hundred productions is tens of\n * thousands of pairs; nobody reads that. This module walks the same tree\n * `analyzeGating` walks and reports nine families:\n *\n * 1. `duplicates` \u2014 subtrees that are structurally IDENTICAL, in \u22652 places.\n * 2. `nearDuplicates` \u2014 subtrees identical except at ONE slot. This is the\n * high-value case: a general rule cloned with one term\n * swapped, where the fix is one production whose varying\n * slot is a `choice`, not N copies of the scaffolding.\n * 3. `regexFragments` \u2014 alternation runs re-spelled across several `regex()`\n * terminals. Structural hashing cannot see inside a\n * regex, so this is its own pass.\n * 4. `regexClasses` \u2014 character classes re-spelled across terminals, and, more\n * usefully, NEAR-identical ones with the drift shown side\n * by side.\n * 5. `overlaps` \u2014 `choice` arms whose first-sets intersect, reported as\n * \"these two arms, on these chars, sharing these leading\n * terms\" rather than gating's \"dispatch failed\".\n * 6. `rewrites` \u2014 ALGEBRAIC simplifications: mechanically-derived exact\n * rewrites (`choice(sequence(A,B), B)` \u2192 `sequence(\n * optional(A), B)`), plus the dead-arm cases that are\n * outright bugs.\n * 7. `divergentNodes` \u2014 ONE `node()` type built by several structurally different\n * productions that are nonetheless variants of one shape.\n * 8. `structureLoss` \u2014 an earlier `choice` arm that FLATTENS what a later arm\n * would have structured: same `node()` type, overlapping\n * first-sets, and the earlier body contains no `node()`\n * at all. The parse succeeds either way, so nothing else\n * \u2014 not a test suite, not an output diff \u2014 reports it.\n * The ordered, consequential half of `divergentNodes`.\n * 9. `keywordRegexes` \u2014 hand-rolled keyword regexes (`regex(/not(?![-\\w])/i)`)\n * that should be `word()`/`keywords()`. Not a style note:\n * `/i` without `/u` gets non-ASCII case folding wrong,\n * and the fix that lives inside `keywords()` (see\n * `combinators/case-fold.ts`) never reached the copies.\n *\n * ## What this CANNOT see\n *\n * Structural hashing is exactly that: STRUCTURAL. Two productions that accept the\n * same language but are shaped differently \u2014 `many(x)` vs `optional(oneOrMore(x))`,\n * a `regex` spelling of what another rule builds from combinators, a rule inlined\n * once and referenced once \u2014 are invisible to `duplicates`/`nearDuplicates` unless\n * they happen to fall into the `rewrites` algebra below. Equally, two subtrees that\n * differ only in a `transform`/`node` CALLBACK are reported as distinct when the\n * callbacks' source text differs, even if the functions are equivalent. This finds\n * COPY-PASTE and mechanical redundancy. It does not find semantic redundancy, and a\n * clean report is not a proof that a grammar has none.\n *\n * `analyzeDuplication()` / `analyzeDuplicationRules()` are the programmatic\n * surface, mirroring `analyzeGating` / `analyzeGatingRules`. The compile-time\n * wiring is OPT-IN (`compile(g, { duplication: 'warn' })` /\n * `PARSEMAN_DUPLICATION=warn`) and runs on ALL THREE lowering paths \u2014 `compile`,\n * `compileRuleMap` and `compileLinkable` \u2014 because the macro build takes the\n * latter two and a diagnostic that only runs on the first is a diagnostic that\n * reports zero findings forever.\n */\nimport type { Combinator, FirstSet, ParserDef } from '../types.ts'\nimport { firstSetOf, type RefResolver } from '../combinators/first-set.ts'\nimport { firstSetToString } from './gating.ts'\n\n// \u2500\u2500 public shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Where a combinator sits: its owning rule, and the accessor path within it. */\nexport type Site = {\n /** Nearest enclosing `_ruleName`, or the seed name it was reached under. */\n rule: string\n /** Structural path inside that rule, e.g. `choice[0] \u203A node(Declaration) \u203A seq[4]`. */\n path: string\n}\n\nexport const siteToString = (s: Site): string => (s.path === '' ? s.rule : `${s.rule} \u203A ${s.path}`)\n\n/** N structurally identical copies of one subtree. */\nexport type DuplicateFinding = {\n kind: 'exact-duplicate'\n id: string\n /** Node count of the repeated subtree. */\n size: number\n /** How many DISTINCT combinator instances share the shape (shared-by-reference\n * reuse is not duplication and is never counted here). */\n count: number\n /** Nodes removed by hoisting the shape to one shared const: `(count - 1) * size`. */\n savings: number\n /** One-line rendering of the repeated shape. */\n shape: string\n sites: Site[]\n suggestion: string\n}\n\n/** N subtrees identical except at ONE slot. */\nexport type NearDuplicateFinding = {\n kind: 'near-duplicate'\n id: string\n /** Node count shared by every member (the scaffolding). */\n sharedSize: number\n count: number\n savings: number\n /** The scaffolding with the varying slot rendered as `\u2039slot\u203A`. */\n shape: string\n /** Path to the varying slot, relative to the members' root. */\n slotPath: string\n /** What each member puts in that slot, aligned with `sites`. */\n variants: string[]\n sites: Site[]\n suggestion: string\n}\n\n/** An alternation run re-spelled across several `regex()` terminals. */\nexport type RegexFragmentFinding = {\n kind: 'regex-fragment'\n id: string\n /** The shared run, as it appears in the sources (`>=|<=|=>|=<|=~|[<>=]`). */\n fragment: string\n /** Number of alternation branches in the run. */\n branches: number\n count: number\n /** Characters removed by hoisting: `(count - 1) * fragment.length`. */\n savings: number\n /** The full source of each regex that carries it, aligned with `sites`. */\n sources: string[]\n sites: Site[]\n suggestion: string\n}\n\n/** One spelling of a character class, and where it appears. */\nexport type RegexClassVariant = {\n /** The class as written, including any `^`: `-_a-zA-Z0-9\u0080-\uFFFF`. */\n source: string\n /** Members this spelling has that the cluster's most common spelling does not,\n * and vice versa \u2014 the DRIFT, rendered `+a-f / -0-9`. */\n delta: string\n count: number\n sites: Site[]\n}\n\n/**\n * A character class (or boundary lookahead class) re-spelled across several\n * `regex()` terminals \u2014 and, when the spellings are not identical, the drift\n * between them.\n */\nexport type RegexClassFinding = {\n kind: 'regex-class'\n id: string\n /** The cluster's most common spelling. */\n canonical: string\n /** Every spelling in the cluster, most common first. Two variants side by side\n * IS the finding: one of them is wrong and reading cannot tell you which. */\n variants: RegexClassVariant[]\n /** Distinct `regex()` terminals across the whole cluster. */\n count: number\n /** True when the cluster holds more than one spelling. */\n drifted: boolean\n /** The class's highest code point is U+FFFF and it was written as an explicit\n * range \u2014 astral-plane characters fall outside it. */\n bmpCeiling: boolean\n suggestion: string\n}\n\n/** Two arms of one `choice` whose first-sets intersect. */\nexport type ArmOverlapFinding = {\n kind: 'arm-overlap'\n id: string\n site: Site\n a: number\n b: number\n /** The SHARED first characters (not the union). */\n on: FirstSet\n /** How many leading terms the two arms spell identically. */\n sharedLeadingTerms: number\n /** Rendering of those shared leading terms, when there are any. */\n sharedPrefix: string | null\n /** True when parseman's `sharedPrefix` choice strategy already recognizes the\n * common prefix once at runtime \u2014 the finding is then about READABILITY, not\n * speed. */\n handledByStrategy: boolean\n /** Both arms lead with a `regex()` whose character classes intersect \u2014 usually\n * a sign the two arms want to be one terminal. */\n regexPair: boolean\n suggestion: string\n}\n\nexport type RewriteKind =\n | 'optional-prefix' // choice(sequence(A, R\u2026), sequence(R\u2026)) \u2192 sequence(optional(A), R\u2026)\n | 'optional-suffix' // choice(sequence(R\u2026, A), sequence(R\u2026)) \u2192 sequence(R\u2026, optional(A))\n | 'left-factor' // choice(sequence(A, B\u2026), sequence(A, C\u2026)) \u2192 sequence(A, choice(B\u2026, C\u2026))\n | 'hand-rolled-sepby' // sequence(X, many(sequence(S, X))) \u2192 sepBy(X, S)\n | 'idempotent-nesting' // optional(optional(X)), many(many(X)), \u2026\n | 'single-element' // choice(X) / sequence(X)\n | 'duplicate-arm' // choice(\u2026, X, \u2026, X, \u2026) \u2014 the later arm is dead\n | 'shadowed-arm' // choice(\u2026, X, \u2026, sequence(X, \u2026), \u2026) \u2014 the later arm is dead\n\n/** A mechanically-derived rewrite. */\nexport type RewriteFinding = {\n kind: 'rewrite'\n id: string\n rewrite: RewriteKind\n site: Site\n /** What is there now. */\n from: string\n /** What it is equal to. */\n to: string\n /**\n * `true` only when the rewrite provably cannot move the parse VALUE \u2014 which,\n * here, means it only deletes an arm that can never be selected. Every other\n * rewrite in this family changes the child arity or nesting of the value the\n * site produces, so a `node()` build / `transform` / downstream consumer that\n * reads positionally WILL see a different tree. Those are reported as\n * CANDIDATES to verify, never as \"fix this\".\n */\n astNeutral: boolean\n /** Non-empty when the rewrite removes speculative work at parse time. */\n perf: string\n /** Only on `hand-rolled-sepby`: whether this SITE can actually take `sepBy`. A\n * count of matches is not a worklist \u2014 in a real grammar most matches are\n * blocked, and reporting them all as convertible generates false work. */\n sepByVerdict?: SepByVerdict\n /** True when this is a latent BUG (an unreachable arm), not a verbosity smell. */\n bug: boolean\n suggestion: string\n}\n\n/**\n * One AST node type built by two or more STRUCTURALLY DIFFERENT productions that\n * are nonetheless variants of a single shape (they spell several of the same\n * terms). This is the clone family near-duplicate detection cannot see: the copies\n * diverge in more than one slot \u2014 extra scaffolding, a hand-rolled whitespace run,\n * a terminal guard \u2014 so no single hole explains them, yet every edit to \"the\n * declaration shape\" still has to land in all of them, and nothing checks that it did.\n */\nexport type DivergentNodeFinding = {\n kind: 'divergent-node'\n id: string\n /** The `node()` type every member produces. */\n nodeType: string\n /** Number of structurally distinct productions building it. */\n count: number\n /** Terms every member spells identically \u2014 the evidence they are one shape. */\n sharedTerms: string[]\n productions: {\n shape: string\n site: Site\n /** Terms this production has that at least one sibling does not. */\n distinctTerms: string[]\n }[]\n suggestion: string\n}\n\n/**\n * An earlier `choice` arm that FLATTENS what a later arm would have STRUCTURED.\n *\n * Both arms build the same `node()` type and can start on the same character, so\n * on the inputs both accept the earlier one wins \u2014 and its body contains no\n * `node()` at all, so the tree it produces is that node over bare leaves. The\n * later arm, on those same inputs, would have produced child nodes. Nothing about\n * this is visible in a parse that succeeds: `ok` is true, the span is right, the\n * text round-trips. Only the SHAPE moved, and only on the subset of inputs the\n * flattening arm happens to accept \u2014 which is why it survives a test suite that\n * checks \"does it parse\" and a corpus diff that checks emitted output. It shows\n * up in whatever consumes the tree: a language service that lints number tokens,\n * a formatter, a refactor.\n *\n * This is the ordered, consequential half of `divergent-node`. That finding says\n * two productions build one type and nothing keeps them in sync, and it expressly\n * allows \"the variants exist for a parse-order reason (a fast path tried first)\".\n * This one is the case where that excuse is the bug: the fast path is not\n * tree-neutral, and here is the list of node types it deletes.\n */\nexport type StructureLossFinding = {\n kind: 'structure-loss'\n id: string\n /** The `choice` that orders the two arms. */\n site: Site\n /** The `node()` type BOTH arms build. */\n nodeType: string\n /** Index of the flattening arm (the earlier one). */\n earlier: number\n /** Index of the structuring arm it shadows. */\n later: number\n /** The characters on which both arms can start \u2014 where the shadowing bites. */\n on: FirstSet\n /** Node types the later arm builds under `nodeType` and the earlier cannot. */\n lostNodeTypes: string[]\n earlierShape: string\n laterShape: string\n suggestion: string\n}\n\n/** A `regex()` that hand-rolls a keyword + word boundary. */\nexport type KeywordRegexFinding = {\n kind: 'keyword-regex'\n id: string\n site: Site\n source: string\n flags: string\n words: string[]\n /** The boundary character class, as a `word()`/`keywords()` `boundary` argument.\n * `null` when the regex enumerates a vocabulary with no guard at all. */\n boundary: string | null\n /** `/i` without `/u`: the fold class is NOT `{c, upper(c), lower(c)}`. */\n caseFoldRisk: boolean\n /** Sibling arm indices in the same `choice` that are also hand-rolled keywords. */\n siblingArms: number[]\n /**\n * >= 3 literal alternatives: a fixed VOCABULARY enumerated by hand rather than a\n * keyword with a guard. The interesting sub-case, because ordering starts to matter\n * and the list is usually long enough that nobody re-reads it.\n */\n vocabulary: boolean\n /**\n * Alternatives are in non-increasing length order. `keywords()` sorts longest-first\n * by construction; a hand-written alternation does not, and nothing checks it.\n */\n longestFirst: boolean\n /**\n * Earlier alternatives that are strict PREFIXES of later ones. Regex alternation is\n * first-match, so the longer branch is reachable only when a trailing boundary guard\n * rejects the following character and forces a backtrack (`rescuedByBoundary`).\n */\n hazards: { shorter: string; longer: string; at: string; rescuedByBoundary: boolean }[]\n /**\n * At least one hazard is NOT rescued by a boundary guard \u2014 a later alternative can\n * never match. That is a live bug, not a cleanup.\n */\n bug: boolean\n suggestion: string\n}\n\nexport type DuplicationReport = {\n duplicates: DuplicateFinding[]\n nearDuplicates: NearDuplicateFinding[]\n regexFragments: RegexFragmentFinding[]\n regexClasses: RegexClassFinding[]\n overlaps: ArmOverlapFinding[]\n rewrites: RewriteFinding[]\n divergentNodes: DivergentNodeFinding[]\n structureLoss: StructureLossFinding[]\n keywordRegexes: KeywordRegexFinding[]\n /** Ids listed in `accept` that matched no finding \u2014 stale entries to prune. */\n acceptedUnused: string[]\n stats: {\n rules: number\n /** Distinct combinator INSTANCES reached. */\n nodes: number\n /** Distinct structural shapes among them. */\n shapes: number\n }\n}\n\nexport type AnalyzeDuplicationOptions = {\n /** Smallest repeated subtree worth reporting, in nodes. Default 3 \u2014 which is\n * what keeps `optional(ws)` (2 nodes) out of the ranking. */\n minSize?: number\n /** Cap per category, applied AFTER ranking. Default 25. */\n maxFindings?: number\n /** Finding `id`s to suppress \u2014 the single per-finding acknowledgement channel,\n * mirroring the gating snapshot allowlist. */\n accept?: Iterable<string>\n /** Bind cross-artifact `g.Foo` holes when computing first-sets for `overlaps`. */\n resolveRef?: RefResolver\n /** Name to attribute an unnamed entry to, instead of `<entry>`. */\n entryName?: string\n}\n\n// \u2500\u2500 canonical structural hashing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Ordered structural children per def tag. Explicit rather than \"every key that\n * holds a Combinator\" because a SLOT's position is what near-duplicate detection\n * varies \u2014 a stable, meaningful order is load-bearing, not cosmetic.\n */\nfunction childrenOf(d: ParserDef): readonly Combinator<unknown>[] {\n switch (d.tag) {\n case 'sequence': case 'choice': return d.parsers\n case 'dispatch': return [\n d.selector,\n ...d.cases.map(c => c.parser),\n ...(d.otherwise === undefined ? [] : [d.otherwise]),\n ]\n case 'skip': return [d.main, d.skipped]\n case 'sepBy': return [d.parser, d.separator]\n case 'recover': return [d.parser, d.sentinel]\n case 'scanTo': return [d.sentinel, ...d.skip]\n case 'grammar': return d.triviaParser ? [d.parser, d.triviaParser] : [d.parser]\n // A `lazy` is a REFERENCE, not a subtree: hashing through it would make every\n // rule's shape include the whole reachable grammar. Treated as a leaf, keyed\n // by the rule name it refers to \u2014 which is also the right semantics, since two\n // productions referencing `g.Ident` really do fill that slot the same way.\n case 'lazy': case 'literal': case 'regex': case 'keywords': case 'guard': case 'unknown':\n return []\n default: {\n const rec = d as unknown as { parser?: Combinator<unknown> }\n return rec.parser ? [rec.parser] : []\n }\n }\n}\n\nconst ruleNameOf = (p: Combinator<unknown>): string | undefined =>\n (p as unknown as { _ruleName?: string })._ruleName\n\n/** Source text of a callback, so two COPY-PASTED lambdas hash alike (identity\n * would make every copy distinct and defeat the whole diagnostic). */\nconst fnKey = (src: string | undefined, fn: unknown): string =>\n src ?? (typeof fn === 'function' ? String(fn) : '')\n\n/** The discriminating payload of a node, excluding its children. */\nfunction payloadKey(p: Combinator<unknown>, d: ParserDef): string {\n switch (d.tag) {\n case 'literal': return `literal\\u0000${d.value}\\u0000${d.caseInsensitive}`\n case 'regex': return `regex\\u0000${d.source}\\u0000${d.flags}`\n case 'keywords': return `keywords\\u0000${[...d.words].join('\\u0001')}\\u0000${d.caseInsensitive}\\u0000${d.boundary ?? ''}`\n case 'lazy': {\n const n = ruleNameOf(p)\n return n === undefined ? `ref\\u0000#${anonId(p)}` : `ref\\u0000${n}`\n }\n case 'label': return `label\\u0000${d.label}`\n case 'field': return `field\\u0000${d.name}`\n case 'node': return `node\\u0000${d.type ?? ''}\\u0000${d.unwrap === true}\\u0000${d.collapse === true}\\u0000${fnKey(d.buildSrc, d.build)}`\n case 'transform': return `transform\\u0000${fnKey(d.fnSrc, d.fn)}\\u0000${d.recognitionOnly === true}`\n case 'leaf': return `leaf\\u0000${fnKey(d.fnSrc, d.fn)}`\n case 'many': case 'oneOrMore': return `${d.tag}\\u0000${d.min}\\u0000${d.max ?? ''}`\n case 'sepBy': return `sepBy\\u0000${d.min}\\u0000${d.max ?? ''}\\u0000${d.trailing ?? ''}`\n case 'dispatch': return `dispatch\\u0000${d.cases.map(c => JSON.stringify(c.keys)).join('\\u0002')}\\u0000${d.otherwise !== undefined}`\n case 'expect': return `expect\\u0000${d.label ?? ''}\\u0000${d.expected.join('\\u0001')}`\n case 'scanTo': return `scanTo\\u0000${d.raw}\\u0000${d.orEOF}`\n case 'guard': return `guard\\u0000${fnKey(d.predSrc, d.predicate)}`\n case 'withCtx': return `withCtx\\u0000${d.extraSrc ?? safeJson(d.extra)}`\n case 'grammar': return `grammar\\u0000${d.clearTrivia === true}\\u0000${d.captureTrivia === true}\\u0000${d.trackLines}`\n default: return d.tag\n }\n}\n\nfunction safeJson(v: unknown): string {\n try { return JSON.stringify(v) ?? String(v) } catch { return '?' }\n}\n\nlet anonCounter = 0\nconst anonIds = new WeakMap<object, number>()\n/** Identity key for an UNNAMED unresolvable ref: nothing can bind it by name, so\n * two of them are the same slot only when they are the same object. */\nfunction anonId(p: object): number {\n let id = anonIds.get(p)\n if (id === undefined) { id = ++anonCounter; anonIds.set(p, id) }\n return id\n}\n\n/**\n * Interning gives EXACT structural equality with short keys: a node's key is its\n * payload plus the interned ids of its children, so equal ids \u21D4 equal subtrees,\n * with no hash collisions to reason about.\n */\nclass Interner {\n private readonly ids = new Map<string, number>()\n readonly hole: number\n constructor() { this.hole = this.of('\\u0000HOLE\\u0000') }\n of(key: string): number {\n let id = this.ids.get(key)\n if (id === undefined) { id = this.ids.size; this.ids.set(key, id) }\n return id\n }\n}\n\n// \u2500\u2500 rendering \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst MAX_RENDER = 160\n\n/** A compact one-line rendering of a subtree, for the finding text. */\nfunction render(p: Combinator<unknown>, depth = 3): string {\n const d = p._def as ParserDef\n const name = ruleNameOf(p)\n switch (d.tag) {\n case 'literal': return `literal('${d.value}')`\n case 'regex': return `regex(/${d.source}/${d.flags})`\n case 'keywords': return `keywords([${[...d.words].slice(0, 4).map(w => `'${w}'`).join(', ')}${d.words.length > 4 ? ', \u2026' : ''}])`\n case 'lazy': return `g.${name ?? '?'}`\n case 'guard': return 'gate(\u2026)'\n default: break\n }\n if (depth <= 0) return `${d.tag}(\u2026)`\n const kids = childrenOf(d).map(k => render(k, depth - 1))\n switch (d.tag) {\n case 'sequence': return `sequence(${kids.join(', ')})`\n case 'choice': return `choice(${kids.join(', ')})`\n case 'dispatch': {\n const arms = d.cases.map((c, i) => `when([${c.keys.map(k => JSON.stringify(k)).join(', ')}], ${kids[i + 1] ?? ''})`)\n if (d.otherwise !== undefined) arms.push(`otherwise(${kids[kids.length - 1] ?? ''})`)\n return `dispatch(${kids[0] ?? ''}, ${arms.join(', ')})`\n }\n case 'node': return `node(${d.type ? `'${d.type}', ` : ''}${kids[0] ?? ''})`\n case 'label': return `label('${d.label}', ${kids[0] ?? ''})`\n case 'field': return `field('${d.name}', ${kids[0] ?? ''})`\n case 'many': return `many(${kids[0] ?? ''}${d.min === 0 && d.max === undefined ? '' : `, { min: ${d.min}${d.max === undefined ? '' : `, max: ${d.max}`} }`})`\n case 'oneOrMore': return `oneOrMore(${kids[0] ?? ''}${d.min === 1 && d.max === undefined ? '' : `, { min: ${d.min}${d.max === undefined ? '' : `, max: ${d.max}`} }`})`\n case 'sepBy': return `sepBy(${kids[0] ?? ''}, ${kids[1] ?? ''})`\n default: return `${d.tag}(${kids.join(', ')})`\n }\n}\n\nconst clamp = (s: string): string => (s.length <= MAX_RENDER ? s : `${s.slice(0, MAX_RENDER - 1)}\u2026`)\n\n/** Path segment for a child index, used to build `Site.path` and slot paths. */\nfunction segment(d: ParserDef, index: number): string {\n switch (d.tag) {\n case 'sequence': return `seq[${index}]`\n case 'choice': return `choice[${index}]`\n case 'dispatch':\n if (index === 0) return 'dispatch.selector'\n if (index <= d.cases.length) return `dispatch.when[${index - 1}]`\n return 'dispatch.otherwise'\n case 'node': return `node(${d.type ?? ''})`\n case 'label': return `label(${d.label})`\n case 'field': return `field(${d.name})`\n case 'sepBy': return index === 0 ? 'sepBy.item' : 'sepBy.sep'\n case 'skip': return index === 0 ? 'skip.main' : 'skip.skipped'\n case 'recover': return index === 0 ? 'recover.body' : 'recover.sentinel'\n case 'scanTo': return index === 0 ? 'scanTo.sentinel' : `scanTo.skip[${index - 1}]`\n default: return d.tag\n }\n}\n\n// \u2500\u2500 regex source: alternation runs + keyword shape \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Every alternation branch list in a regex source, at ANY nesting depth. Depth\n * matters: `/a|b/` and `/x(?:a|b)y/` re-spell the same run, and only one of them\n * has it at top level.\n */\nexport function alternationGroups(src: string): string[][] {\n const out: string[][] = []\n type Frame = { branches: string[]; last: number }\n const stack: Frame[] = [{ branches: [], last: 0 }]\n let i = 0\n while (i < src.length) {\n const c = src[i]!\n if (c === '\\\\') { i += 2; continue }\n if (c === '[') {\n let j = i + 1\n if (src[j] === '^') j++\n if (src[j] === ']') j++\n while (j < src.length && src[j] !== ']') { if (src[j] === '\\\\') j++; j++ }\n i = j + 1\n continue\n }\n if (c === '(') {\n let open = i + 1\n if (src[open] === '?') {\n const rest = src.slice(open)\n const m = /^\\?(?::|=|!|<=|<!|<[^>]*>)/.exec(rest)\n open += m ? m[0].length : 1\n }\n stack.push({ branches: [], last: open })\n i = open\n continue\n }\n if (c === ')') {\n const top = stack.pop()\n if (top !== undefined) {\n top.branches.push(src.slice(top.last, i))\n if (top.branches.length >= 2) out.push(top.branches)\n }\n i++\n continue\n }\n if (c === '|') {\n const top = stack[stack.length - 1]!\n top.branches.push(src.slice(top.last, i))\n top.last = i + 1\n i++\n continue\n }\n i++\n }\n const root = stack[0]!\n root.branches.push(src.slice(root.last))\n if (root.branches.length >= 2) out.push(root.branches)\n return out\n}\n\n/**\n * A LITERAL word: letters, digits, `_`, `-`, optionally vendor-prefixed. No\n * character class, no quantifier, no escape, no group \u2014 anything with regex\n * machinery in it is a pattern, not a vocabulary entry, and is left alone.\n */\nconst WORD_RE_SRC = '-?[A-Za-z][A-Za-z0-9_-]*'\nconst WORDS_RE = new RegExp(`^${WORD_RE_SRC}(?:\\\\|${WORD_RE_SRC})*$`)\n\n/**\n * How many literal alternatives make a regex a VOCABULARY rather than a pattern,\n * when there is no boundary guard to mark it as a keyword. With a guard, one word\n * is already enough (`regex(/not(?![-\\w])/)`); without one, two alternatives are\n * as likely to be an ordinary either/or as a keyword set, so the bar is three.\n */\nconst VOCABULARY_MIN_WORDS = 3\n\n/**\n * Recognize a `regex()` that hand-rolls what `word()`/`keywords()` owns.\n *\n * TWO shapes, because they fail differently:\n *\n * - a word (or word alternation) plus a trailing word-boundary guard \u2014\n * `regex(/not(?![-\\w])/i)`;\n * - a bare alternation of >= 3 literal words with NO guard \u2014 a fixed vocabulary\n * enumerated by hand. A regex enumerating a fixed vocabulary is a keyword set\n * written the hard way: it loses first-set gating, it hand-maintains an ordering\n * the combinator guarantees, and with `/i` and no `/u` it inherits the non-ASCII\n * case-folding bug `keywords()` fixes internally. The no-guard form is also where\n * ordering is load-bearing, since nothing backtracks past a shorter match.\n *\n * Returns the words and the boundary CLASS in the exact form `word(str, boundary)` /\n * `keywords(words, { boundary })` take, so the suggestion names a real call rather\n * than describing one.\n */\nexport function keywordRegexShape(source: string): { words: string[]; boundary: string | null } | null {\n let s = source\n if (s.startsWith('^')) s = s.slice(1)\n // A leading `(?<![-\\w])` is the same boundary on the other side \u2014 word()/keywords()\n // do not emit it, but its presence does not stop the body from being a keyword.\n s = s.replace(/^\\(\\?<!\\[[^\\]]+\\]\\)/, '')\n let boundary: string | null = null\n // Peel a trailing boundary guard.\n const tail = /(?:\\(\\?!\\[([^\\]]+)\\]\\)|\\\\b)$/.exec(s)\n if (tail !== null) {\n const cls = tail[1]\n // `(?![^-\\w])` is NOT a boundary guard \u2014 a negative lookahead of a NEGATED\n // class asserts the opposite, that the next char IS in the class. The capture\n // keeps the leading `^`, so passing it on would hand `word(str, boundary)` a\n // class meaning the reverse, and `boundaryMatches` would read `^` as a literal\n // member and return the inverted verdict. `bug` is derived from unrescued\n // hazards, so that inversion can invent or hide a BUG in error mode. The shape\n // is simply not expressible as a `boundary` argument: reject it.\n if (cls !== undefined && cls.startsWith('^')) return null\n boundary = cls ?? '_0-9A-Za-z'\n s = s.slice(0, tail.index)\n }\n // Unwrap one redundant non-capturing group around the word set.\n const grouped = /^\\(\\?:([^()]*)\\)$/.exec(s)\n if (grouped !== null) s = grouped[1]!\n if (s.endsWith('$')) s = s.slice(0, -1)\n if (!WORDS_RE.test(s)) return null\n const words = s.split('|')\n if (boundary === null && words.length < VOCABULARY_MIN_WORDS) return null\n return { words, boundary }\n}\n\n/** Does a boundary class (`-\\w`, `_0-9A-Za-z`, \u2026) match this character? */\nfunction boundaryMatches(boundary: string, ch: string): boolean {\n const cp = ch.codePointAt(0)!\n for (const m of charClassMembers(boundary)) {\n if (m === '\\\\w') { if (/[A-Za-z0-9_]/.test(ch)) return true; continue }\n if (m === '\\\\d') { if (/[0-9]/.test(ch)) return true; continue }\n if (m === '\\\\s') { if (/\\s/.test(ch)) return true; continue }\n const range = /^(.|\\\\u[0-9a-f]{4})-(.|\\\\u[0-9a-f]{4})$/.exec(m)\n if (range !== null) {\n const dec = (t: string): number => (t.startsWith('\\\\u') ? parseInt(t.slice(2), 16) : t.codePointAt(0)!)\n if (cp >= dec(range[1]!) && cp <= dec(range[2]!)) return true\n continue\n }\n if (m === ch) return true\n }\n return false\n}\n\n/**\n * Ordering hazards in a hand-written alternation: an EARLIER alternative that is a\n * strict prefix of a LATER one. Regex alternation is first-match, not longest-match,\n * so `red|redish` matches only `red` \u2014 unless a trailing boundary guard rejects the\n * character that follows, which makes the engine backtrack into the longer branch.\n *\n * That distinction is the whole point of reporting this: without a rescuing guard the\n * longer word is UNREACHABLE, which is a live bug, not a style finding. `keywords()`\n * sorts longest-first by construction and the hazard cannot exist there at all.\n */\nexport function keywordAlternationHazards(\n words: readonly string[],\n boundary: string | null,\n): { shorter: string; longer: string; at: string; rescuedByBoundary: boolean }[] {\n const out: { shorter: string; longer: string; at: string; rescuedByBoundary: boolean }[] = []\n for (let i = 0; i < words.length; i++) {\n for (let j = i + 1; j < words.length; j++) {\n const a = words[i]!, b = words[j]!\n if (a.length >= b.length || !b.startsWith(a)) continue\n const at = b[a.length]!\n out.push({ shorter: a, longer: b, at, rescuedByBoundary: boundary !== null && boundaryMatches(boundary, at) })\n }\n }\n return out\n}\n\n// \u2500\u2500 the walk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function analyzeDuplication(\n entry: Combinator<unknown>,\n opts?: AnalyzeDuplicationOptions,\n): DuplicationReport {\n return analyzeDuplicationRules([[ruleNameOf(entry) ?? opts?.entryName ?? '<entry>', entry]], opts)\n}\n\ntype Visited = {\n p: Combinator<unknown>\n d: ParserDef\n site: Site\n shape: number\n size: number\n /** Nearest enclosing `node()` type, if any. A rewrite under one changes the\n * children that node's build fn sees, which is the AST-neutrality question. */\n enclosingNode: string | null\n /** An enclosing `node()`/`transform()`/`leaf()` carries a REDUCER \u2014 a callback\n * that reads the children array. Any rewrite changing that array's length or\n * stride changes what the callback sees. */\n enclosingReducer: boolean\n}\n\n/**\n * The analysis input is the COMBINATOR TREE \u2014 a `rules()` map, or the map handed to\n * `compileRuleMap`/`compileLinkable`. It is NOT the value `compose()` returns: that\n * is a fused, already-compiled artifact whose entries are emitted parse FUNCTIONS\n * with no `_def` to walk.\n *\n * This is checked, loudly, because the alternative failure mode is the one that\n * matters. `analyzeGating()` handed a composed artifact throws deep inside its\n * walker on the first descriptor-less node \u2014 and a diagnostic that can throw or\n * silently report zero on exactly the grammars it exists to serve is worse than no\n * diagnostic, because a clean run reads as \"no findings\" instead of \"saw nothing\".\n * Silence is not a permitted outcome here.\n */\nfunction assertAnalyzable(ruleMap: ReadonlyArray<readonly [string, Combinator<unknown>]>): void {\n for (const [name, rule] of ruleMap) {\n const def = (rule as { _def?: unknown } | null | undefined)?._def\n if (def !== null && typeof def === 'object' && typeof (def as { tag?: unknown }).tag === 'string') continue\n throw new TypeError(\n `analyzeDuplicationRules: rule '${name}' is not a combinator (no _def). ` +\n `This analysis walks the COMBINATOR TREE; the value returned by compose()/composeLeaf() is a ` +\n `fused, already-compiled artifact whose entries are parse functions. Pass the rules() map itself ` +\n `(or the map given to compileRuleMap/compileLinkable) instead \u2014 for a composed grammar, analyze ` +\n `each piece's own rules() map.`,\n )\n }\n}\n\nexport function analyzeDuplicationRules(\n ruleMap: ReadonlyArray<readonly [string, Combinator<unknown>]>,\n opts?: AnalyzeDuplicationOptions,\n): DuplicationReport {\n assertAnalyzable(ruleMap)\n const minSize = opts?.minSize ?? 3\n const maxFindings = opts?.maxFindings ?? 25\n const interner = new Interner()\n\n const shapeCache = new Map<Combinator<unknown>, number>()\n const sizeCache = new Map<Combinator<unknown>, number>()\n\n const shapeOf = (p: Combinator<unknown>): number => {\n const hit = shapeCache.get(p)\n if (hit !== undefined) return hit\n const d = p._def as ParserDef\n // Seed against self-reference before recursing (a `lazy` is a leaf, so a true\n // cycle cannot form here \u2014 but a defensive seed keeps a malformed def finite).\n shapeCache.set(p, interner.hole)\n const kids = childrenOf(d)\n const id = interner.of(`${payloadKey(p, d)}|${kids.map(shapeOf).join(',')}`)\n shapeCache.set(p, id)\n return id\n }\n const sizeOf = (p: Combinator<unknown>): number => {\n const hit = sizeCache.get(p)\n if (hit !== undefined) return hit\n sizeCache.set(p, 1)\n let n = 1\n for (const k of childrenOf(p._def as ParserDef)) n += sizeOf(k)\n sizeCache.set(p, n)\n return n\n }\n\n // \u2500\u2500 traverse: one entry per distinct combinator INSTANCE \u2500\u2500\n const visited = new Map<Combinator<unknown>, Visited>()\n const visit = (p: Combinator<unknown>, rule: string, path: string, enclosingNode: string | null, enclosingReducer: boolean): void => {\n if (visited.has(p)) return\n const d = p._def as ParserDef\n const own = ruleNameOf(p)\n const here = own !== undefined && own !== rule ? { rule: own, path: '' } : { rule, path }\n visited.set(p, { p, d, site: here, shape: shapeOf(p), size: sizeOf(p), enclosingNode, enclosingReducer })\n const inner = d.tag === 'node' ? d.type ?? '(anonymous)' : enclosingNode\n const innerReducer = enclosingReducer\n || (d.tag === 'node' && (d.build !== undefined || d.buildSrc !== undefined))\n || d.tag === 'transform' || d.tag === 'leaf'\n const kids = childrenOf(d)\n kids.forEach((k, i) => {\n const seg = segment(d, i)\n visit(k, here.rule, here.path === '' ? seg : `${here.path} \u203A ${seg}`, inner, innerReducer)\n })\n // Follow refs so a rule reachable only through one is still attributed \u2014 under\n // its OWN name, because the ref carries `_ruleName`.\n if (d.tag === 'lazy') {\n try {\n const target = (d as { thunk(): Combinator<unknown> }).thunk()\n visit(target, ruleNameOf(target) ?? ruleNameOf(p) ?? here.rule, '', null, false)\n } catch { /* unresolved cross-artifact hole */ }\n }\n }\n for (const [name, root] of ruleMap) visit(root, ruleNameOf(root) ?? name, '', null, false)\n\n const accept = new Set(opts?.accept ?? [])\n const used = new Set<string>()\n const keep = <T extends { id: string }>(f: T): boolean => {\n if (!accept.has(f.id)) return true\n used.add(f.id)\n return false\n }\n\n const duplicates = findExactDuplicates(visited, minSize)\n const nearDuplicates = findNearDuplicates(visited, interner, shapeOf, minSize)\n const regexFragments = findRegexFragments(visited)\n const regexClasses = findRegexClasses(visited)\n const overlaps = findOverlaps(visited, shapeOf, opts?.resolveRef)\n const rewrites = findRewrites(visited, shapeOf)\n const divergentNodes = findDivergentNodes(visited, shapeOf)\n const structureLoss = findStructureLoss(visited, opts?.resolveRef)\n const keywordRegexes = findKeywordRegexes(visited)\n\n // Subsumption, WITHIN each category: a 40-node clone family otherwise reports\n // once at its root and again at every internal node, since each of those is\n // repeated exactly as often. Deliberately NOT applied across categories \u2014 a\n // near-duplicate family and an exact duplicate inside it are two different facts\n // about the same code, and suppressing the second because the first happens to\n // rank higher hides a real repetition behind a maybe-refactor.\n const subsume = <T extends { id: string; savings: number; _members: Combinator<unknown>[] }>(fs: T[]): Set<string> => {\n const covered = new Set<Combinator<unknown>>()\n const surviving = new Set<string>()\n for (const f of [...fs].sort((a, b) => b.savings - a.savings)) {\n if (f._members.every(m => covered.has(m))) continue\n surviving.add(f.id)\n for (const m of f._members) markSubtree(m, covered)\n }\n return surviving\n }\n const survivingExact = subsume(duplicates)\n const survivingNear = subsume(nearDuplicates)\n\n const report: DuplicationReport = {\n duplicates: duplicates.filter(f => survivingExact.has(f.id)).filter(keep).slice(0, maxFindings).map(stripMembers),\n nearDuplicates: nearDuplicates.filter(f => survivingNear.has(f.id)).filter(keep).slice(0, maxFindings).map(stripMembers),\n regexFragments: regexFragments.filter(keep).slice(0, maxFindings),\n regexClasses: regexClasses.filter(keep).slice(0, maxFindings),\n overlaps: overlaps.filter(keep).slice(0, maxFindings),\n rewrites: rewrites.filter(keep).slice(0, maxFindings),\n divergentNodes: divergentNodes.filter(keep).slice(0, maxFindings),\n structureLoss: structureLoss.filter(keep).slice(0, maxFindings),\n keywordRegexes: keywordRegexes.filter(keep).slice(0, maxFindings),\n acceptedUnused: [...accept].filter(id => !used.has(id)),\n stats: { rules: ruleMap.length, nodes: visited.size, shapes: new Set([...visited.values()].map(v => v.shape)).size },\n }\n return report\n}\n\nfunction markSubtree(p: Combinator<unknown>, into: Set<Combinator<unknown>>): void {\n if (into.has(p)) return\n into.add(p)\n for (const k of childrenOf(p._def as ParserDef)) markSubtree(k, into)\n}\n\ntype WithMembers<T> = T & { _members: Combinator<unknown>[] }\nconst stripMembers = <T extends object>(f: WithMembers<T>): T => {\n const { _members, ...rest } = f\n void _members\n return rest as T\n}\n\n// \u2500\u2500 1. exact duplicates \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction findExactDuplicates(\n visited: Map<Combinator<unknown>, Visited>,\n minSize: number,\n): WithMembers<DuplicateFinding>[] {\n const byShape = new Map<number, Visited[]>()\n for (const v of visited.values()) {\n if (v.size < minSize) continue\n const list = byShape.get(v.shape)\n if (list === undefined) byShape.set(v.shape, [v]); else list.push(v)\n }\n const out: WithMembers<DuplicateFinding>[] = []\n for (const group of byShape.values()) {\n if (group.length < 2) continue\n const size = group[0]!.size\n out.push({\n kind: 'exact-duplicate',\n id: `exact-duplicate:${siteToString(group[0]!.site)}`,\n size,\n count: group.length,\n savings: (group.length - 1) * size,\n shape: clamp(render(group[0]!.p)),\n sites: group.map(g => g.site),\n 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}.`,\n _members: group.map(g => g.p),\n })\n }\n return out.sort((a, b) => b.savings - a.savings)\n}\n\n// \u2500\u2500 2. near duplicates (identical but for one slot) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * \"Same shape, one differing slot\" is decided by HOLE KEYS: the key of a subtree\n * with one descendant position blanked. Two subtrees that differ at exactly one\n * position share exactly the hole key that blanks it, so grouping by hole key and\n * keeping the groups whose members' full shapes DIFFER is precisely the family.\n *\n * The root hole is excluded \u2014 blanking the root makes every subtree in the grammar\n * a \"near duplicate\" of every other.\n */\nfunction findNearDuplicates(\n visited: Map<Combinator<unknown>, Visited>,\n interner: Interner,\n shapeOf: (p: Combinator<unknown>) => number,\n minSize: number,\n): WithMembers<NearDuplicateFinding>[] {\n const holeCache = new Map<Combinator<unknown>, number[]>()\n const holesOf = (p: Combinator<unknown>): number[] => {\n const hit = holeCache.get(p)\n if (hit !== undefined) return hit\n holeCache.set(p, [])\n const d = p._def as ParserDef\n const kids = childrenOf(d)\n const kidShapes = kids.map(shapeOf)\n const payload = payloadKey(p, d)\n const out: number[] = []\n kids.forEach((k, i) => {\n for (const inner of [interner.hole, ...holesOf(k)]) {\n const arr = kidShapes.slice()\n arr[i] = inner\n out.push(interner.of(`${payload}|${arr.join(',')}`))\n }\n })\n holeCache.set(p, out)\n return out\n }\n\n const byHole = new Map<number, Visited[]>()\n for (const v of visited.values()) {\n if (v.size < minSize) continue\n for (const h of holesOf(v.p)) {\n const list = byHole.get(h)\n if (list === undefined) byHole.set(h, [v]); else list.push(v)\n }\n }\n\n const out: WithMembers<NearDuplicateFinding>[] = []\n const seenGroups = new Set<string>()\n for (const group of byHole.values()) {\n if (group.length < 2) continue\n // Exact duplicates share every hole key \u2014 they are the OTHER family.\n const shapes = new Set(group.map(g => g.shape))\n if (shapes.size < 2) continue\n // One representative per distinct shape: N copies of variant A and M of variant\n // B is one clone family with two variants, not N\u00D7M findings.\n const perShape = new Map<number, Visited>()\n for (const g of group) if (!perShape.has(g.shape)) perShape.set(g.shape, g)\n const members = [...perShape.values()]\n const key = members.map(m => m.shape).sort((a, b) => a - b).join(',')\n if (seenGroups.has(key)) continue\n seenGroups.add(key)\n const slot = findDivergentSlot(members.map(m => m.p), shapeOf)\n if (slot === null) continue\n const sharedSize = Math.min(...members.map(m => m.size)) - slot.slotSize\n if (sharedSize < minSize) continue\n out.push({\n kind: 'near-duplicate',\n id: `near-duplicate:${siteToString(members[0]!.site)}`,\n sharedSize,\n count: members.length,\n savings: (members.length - 1) * sharedSize,\n shape: clamp(renderWithHole(members[0]!.p, slot.path)),\n slotPath: slot.path.map((i, k) => segment(slot.defs[k]!, i)).join(' \u203A '),\n variants: slot.variants.map(v => clamp(render(v))),\n sites: members.map(m => m.site),\n 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(v => clamp(render(v, 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.`,\n _members: members.map(m => m.p),\n })\n }\n return out.sort((a, b) => b.savings - a.savings)\n}\n\n/** The single child position at which the given subtrees diverge, if there is one. */\nfunction findDivergentSlot(\n members: readonly Combinator<unknown>[],\n shapeOf: (p: Combinator<unknown>) => number,\n): { path: number[]; defs: ParserDef[]; variants: Combinator<unknown>[]; slotSize: number } | null {\n const path: number[] = []\n const defs: ParserDef[] = []\n let cur = [...members]\n for (let guard = 0; guard < 64; guard++) {\n const d0 = cur[0]!._def as ParserDef\n const kidLists = cur.map(c => childrenOf(c._def as ParserDef))\n const arity = kidLists[0]!.length\n if (kidLists.some(k => k.length !== arity) || arity === 0) break\n const diff: number[] = []\n for (let i = 0; i < arity; i++) {\n const s = shapeOf(kidLists[0]![i]!)\n if (kidLists.some(k => shapeOf(k[i]!) !== s)) diff.push(i)\n }\n if (diff.length !== 1) break\n const i = diff[0]!\n path.push(i)\n defs.push(d0)\n cur = kidLists.map(k => k[i]!)\n // Descend while the divergence is still a single slot; stop when the subtrees\n // are wholly different (that IS the varying slot).\n const nextArity = childrenOf(cur[0]!._def as ParserDef).length\n const samePayload = cur.every(c => payloadKey(c, c._def as ParserDef) === payloadKey(cur[0]!, cur[0]!._def as ParserDef))\n if (!samePayload || nextArity === 0) break\n }\n if (path.length === 0) return null\n let slotSize = 0\n const sizeOf = (p: Combinator<unknown>): number => {\n let n = 1\n for (const k of childrenOf(p._def as ParserDef)) n += sizeOf(k)\n return n\n }\n for (const c of cur) slotSize = Math.max(slotSize, sizeOf(c))\n return { path, defs, variants: cur, slotSize }\n}\n\nfunction renderWithHole(p: Combinator<unknown>, path: readonly number[], depth = 0): string {\n if (depth === path.length) return '\\u2039slot\\u203a'\n const d = p._def as ParserDef\n const kids = childrenOf(d)\n const idx = path[depth]!\n const parts = kids.map((k, i) => (i === idx ? renderWithHole(k, path, depth + 1) : render(k, 2)))\n switch (d.tag) {\n case 'sequence': return `sequence(${parts.join(', ')})`\n case 'choice': return `choice(${parts.join(', ')})`\n case 'node': return `node(${d.type ? `'${d.type}', ` : ''}${parts[0] ?? ''})`\n default: return `${d.tag}(${parts.join(', ')})`\n }\n}\n\n// \u2500\u2500 3. regex alternation fragments \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Longest contiguous branch window compared across regexes. Windows shorter than\n * the true maximal shared run are dropped by the containment pass below, so this\n * only has to be long enough to REACH the maximal run \u2014 a whole shared alternation\n * list is additionally offered as one candidate, however long it is. */\nconst MAX_RUN = 32\n\nfunction findRegexFragments(visited: Map<Combinator<unknown>, Visited>): RegexFragmentFinding[] {\n type Occurrence = { site: Site; source: string }\n const byRun = new Map<string, { occ: Occurrence[]; nodes: Set<Combinator<unknown>>; branches: number }>()\n for (const v of visited.values()) {\n const d = v.d\n if (d.tag !== 'regex') continue\n const runs = new Set<string>()\n for (const branches of alternationGroups(d.source)) {\n if (branches.length >= 2) runs.add(branches.join('|'))\n for (let i = 0; i < branches.length; i++) {\n for (let n = 2; n <= Math.min(MAX_RUN, branches.length - i); n++) {\n const run = branches.slice(i, i + n).join('|')\n if (run.length < 4) continue\n runs.add(run)\n }\n }\n }\n for (const run of runs) {\n let e = byRun.get(run)\n if (e === undefined) { e = { occ: [], nodes: new Set(), branches: run.split('|').length }; byRun.set(run, e) }\n if (e.nodes.has(v.p)) continue\n e.nodes.add(v.p)\n e.occ.push({ site: v.site, source: d.source })\n }\n }\n const candidates = [...byRun.entries()]\n .filter(([, e]) => e.occ.length >= 2)\n .map(([run, e]) => ({ run, e, savings: (e.occ.length - 1) * run.length }))\n // COUNT first: \"re-spelled in 7 terminals\" is the headline \u2014 it is the number\n // of places an edit has to land, and the number of chances for one of them to\n // drift. Length only breaks ties.\n .sort((a, b) => b.e.occ.length - a.e.occ.length || b.savings - a.savings || b.run.length - a.run.length)\n\n // Keep only MAXIMAL runs: a 6-branch run that occurs 7\u00D7 makes its own 5-branch\n // sub-runs (also 7\u00D7) noise.\n const kept: typeof candidates = []\n for (const c of candidates) {\n if (kept.some(k => k.e.occ.length >= c.e.occ.length && (`|${k.run}|`).includes(`|${c.run}|`))) continue\n kept.push(c)\n }\n return kept.map(({ run, e }) => ({\n kind: 'regex-fragment' as const,\n id: `regex-fragment:${run}`,\n fragment: run,\n branches: e.branches,\n count: e.occ.length,\n savings: (e.occ.length - 1) * run.length,\n sources: e.occ.map(o => `/${o.source}/`),\n sites: e.occ.map(o => o.site),\n 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.`,\n }))\n}\n\n// \u2500\u2500 3b. character classes across regexes (and their DRIFT) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Every `[...]` in a regex source, INCLUDING the ones inside boundary lookaheads\n * (`(?![-\\w])` yields `-\\w`) \u2014 those are the same duplication in a different\n * costume, and the same drift risk.\n */\nexport function extractCharClasses(src: string): string[] {\n const out: string[] = []\n let i = 0\n while (i < src.length) {\n const c = src[i]!\n if (c === '\\\\') { i += 2; continue }\n if (c !== '[') { i++; continue }\n let j = i + 1\n if (src[j] === '^') j++\n if (src[j] === ']') j++\n while (j < src.length && src[j] !== ']') { if (src[j] === '\\\\') j++; j++ }\n out.push(src.slice(i + 1, j))\n i = j + 1\n }\n return out\n}\n\n/**\n * Split a class body into normalized MEMBERS (`a-z`, `\\w`, `-`, `\u0080-\uFFFF`).\n * Non-ASCII literals are rewritten to `\\uXXXX` so a class typed with a raw `\uFFFF`\n * and one typed with `\uFFFF` compare equal \u2014 otherwise the diagnostic reports\n * drift that is only an editor's.\n */\nexport function charClassMembers(body: string): string[] {\n const esc = (ch: string): string => {\n const cp = ch.codePointAt(0)!\n return cp >= 0x80 ? `\\\\u${cp.toString(16).padStart(4, '0')}` : ch\n }\n const atoms: string[] = []\n let i = 0\n while (i < body.length) {\n if (body[i] === '\\\\') {\n // A code-point escape and the RAW character it denotes are the same member.\n // Missing this is not cosmetic: it splits one drifting family into two\n // clusters purely by which file's author typed the escape.\n const m = /^\\\\(?:u\\{([0-9a-fA-F]+)\\}|u([0-9a-fA-F]{4})|x([0-9a-fA-F]{2}))/.exec(body.slice(i))\n if (m !== null) {\n const cp = parseInt(m[1] ?? m[2] ?? m[3]!, 16)\n atoms.push(cp >= 0x80 ? `\\\\u${cp.toString(16).padStart(4, '0')}` : String.fromCodePoint(cp))\n i += m[0].length\n continue\n }\n atoms.push(body.slice(i, i + 2)); i += 2; continue\n }\n atoms.push(esc(body[i]!)); i++\n }\n const members: string[] = []\n for (let k = 0; k < atoms.length; k++) {\n if (k + 2 < atoms.length && atoms[k + 1] === '-' && atoms[k + 2] !== undefined) {\n members.push(`${atoms[k]}-${atoms[k + 2]}`)\n k += 2\n continue\n }\n members.push(atoms[k]!)\n }\n return members\n}\n\nconst CLASS_MIN_MEMBERS = 2\n\nfunction findRegexClasses(visited: Map<Combinator<unknown>, Visited>): RegexClassFinding[] {\n type Spelling = { source: string; members: string[]; key: string; nodes: Set<Combinator<unknown>>; sites: Site[] }\n const spellings = new Map<string, Spelling>()\n for (const v of visited.values()) {\n if (v.d.tag !== 'regex') continue\n for (const body of new Set(extractCharClasses(v.d.source))) {\n const members = charClassMembers(body)\n if (members.length < CLASS_MIN_MEMBERS) continue\n const key = [...new Set(members)].sort().join('\\u0001')\n let s = spellings.get(key)\n if (s === undefined) { s = { source: body, members, key, nodes: new Set(), sites: [] }; spellings.set(key, s) }\n if (s.nodes.has(v.p)) continue\n s.nodes.add(v.p)\n s.sites.push(v.site)\n }\n }\n\n // Cluster spellings that differ by at most `MAX_DELTA` members while sharing a\n // clear majority \u2014 that relation is what makes DRIFT visible: two classes nobody\n // can tell apart by reading, one of which is wrong.\n const MAX_DELTA = 3\n /** Members shared / members in either. Below this the two classes are simply\n * different classes that happen to share a couple of characters \u2014 clustering\n * them would bury the real drift under coincidence. */\n const MIN_JACCARD = 0.6\n const all = [...spellings.values()]\n const parent = all.map((_, i) => i)\n const find = (i: number): number => { while (parent[i] !== i) { parent[i] = parent[parent[i]!]!; i = parent[i]! } return i }\n const union = (a: number, b: number): void => { const ra = find(a), rb = find(b); if (ra !== rb) parent[ra] = rb }\n for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) {\n // A negated class and a positive one are opposites, never drift of each other.\n if (all[i]!.members.includes('^') !== all[j]!.members.includes('^')) continue\n const A = new Set(all[i]!.members), B = new Set(all[j]!.members)\n let shared = 0\n for (const m of A) if (B.has(m)) shared++\n const delta = (A.size - shared) + (B.size - shared)\n const jaccard = shared / (shared + delta)\n if (shared >= 2 && delta > 0 && delta <= MAX_DELTA && jaccard >= MIN_JACCARD) union(i, j)\n }\n const clusters = new Map<number, number[]>()\n all.forEach((_, i) => {\n const r = find(i)\n const list = clusters.get(r)\n if (list === undefined) clusters.set(r, [i]); else list.push(i)\n })\n\n const out: RegexClassFinding[] = []\n for (const idxs of clusters.values()) {\n const members = idxs.map(i => all[i]!).sort((a, b) => b.nodes.size - a.nodes.size)\n const total = members.reduce((n, m) => n + m.nodes.size, 0)\n const drifted = members.length > 1\n if (!drifted && total < 2) continue\n const base = new Set(members[0]!.members)\n const variants: RegexClassVariant[] = members.map(m => {\n const mine = new Set(m.members)\n const plus = [...mine].filter(x => !base.has(x))\n const minus = [...base].filter(x => !mine.has(x))\n return {\n source: m.source,\n delta: m === members[0]\n ? '(reference)'\n : `${plus.map(p => `+\\`${p}\\``).join(' ')}${plus.length > 0 && minus.length > 0 ? ' ' : ''}${minus.map(p => `-\\`${p}\\``).join(' ')}` || '(same members, different spelling)',\n count: m.nodes.size,\n sites: m.sites,\n }\n })\n const bmpCeiling = members.some(m => m.members.some(x => x.endsWith('-\\\\uffff')))\n out.push({\n kind: 'regex-class',\n id: `regex-class:${members[0]!.key}`,\n canonical: members[0]!.source,\n variants,\n count: total,\n drifted,\n bmpCeiling,\n suggestion: [\n drifted\n ? `${members.length} NEARLY-identical spellings of one class, across ${total} regex() terminals. They differ by ${variants.slice(1).map(v => v.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.`\n : `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.`,\n `Prefer the shared recognition surface where one already covers this class rather than a local extraction.`,\n bmpCeiling\n ? `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.`\n : '',\n `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.`,\n ].filter(s => s !== '').join(' '),\n })\n }\n // Drift first: an exact re-spelling is a tidy-up, a near-match is a latent bug.\n return out.sort((a, b) => Number(b.drifted) - Number(a.drifted) || b.count - a.count)\n}\n\n// \u2500\u2500 4. choice-arm overlap \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction intersects(a: FirstSet, b: FirstSet): boolean {\n if (a.kind === 'any' || b.kind === 'any') return true\n if (a.kind === 'empty' || b.kind === 'empty') return false\n for (const ra of a.ranges) for (const rb of b.ranges) if (ra.lo <= rb.hi && rb.lo <= ra.hi) return true\n return false\n}\n\nfunction intersection(a: FirstSet, b: FirstSet): FirstSet {\n if (a.kind === 'any') return b\n if (b.kind === 'any') return a\n if (a.kind === 'empty' || b.kind === 'empty') return { kind: 'empty' }\n const ranges: { lo: number; hi: number }[] = []\n for (const ra of a.ranges) for (const rb of b.ranges) {\n const lo = Math.max(ra.lo, rb.lo)\n const hi = Math.min(ra.hi, rb.hi)\n if (lo <= hi) ranges.push({ lo, hi })\n }\n return ranges.length === 0 ? { kind: 'empty' } : { kind: 'ranges', ranges }\n}\n\n/** The arm's term list, for shared-prefix comparison (a non-sequence arm is one term). */\nfunction termsOf(arm: Combinator<unknown>): readonly Combinator<unknown>[] {\n let cur = arm\n for (;;) {\n const d = cur._def as ParserDef\n if (d.tag === 'node' || d.tag === 'transform' || d.tag === 'label' || d.tag === 'attempt' || d.tag === 'leaf') {\n cur = (d as { parser: Combinator<unknown> }).parser\n continue\n }\n break\n }\n const d = cur._def as ParserDef\n return d.tag === 'sequence' ? d.parsers : [cur]\n}\n\nfunction leadingRegex(arm: Combinator<unknown>): boolean {\n const t = termsOf(arm)[0]\n return t !== undefined && (t._def as ParserDef).tag === 'regex'\n}\n\nfunction findOverlaps(\n visited: Map<Combinator<unknown>, Visited>,\n shapeOf: (p: Combinator<unknown>) => number,\n resolve?: RefResolver,\n): ArmOverlapFinding[] {\n const out: ArmOverlapFinding[] = []\n for (const v of visited.values()) {\n const d = v.d\n if (d.tag !== 'choice') continue\n const arms = d.parsers\n const fs = arms.map(a => firstSetOf(a, new Set(), resolve))\n const strategy = d.strategy as { tag: string; members?: number[] } | undefined\n for (let i = 0; i < arms.length; i++) {\n for (let j = i + 1; j < arms.length; j++) {\n const A = fs[i]!, B = fs[j]!\n if (A.kind === 'any' || B.kind === 'any') continue // gating's `anyArms` owns that\n if (!intersects(A, B)) continue\n const ta = termsOf(arms[i]!), tb = termsOf(arms[j]!)\n let shared = 0\n while (shared < ta.length && shared < tb.length && shapeOf(ta[shared]!) === shapeOf(tb[shared]!)) shared++\n const handled = strategy?.tag === 'sharedPrefix'\n && Array.isArray(strategy.members) && strategy.members.includes(i) && strategy.members.includes(j)\n const regexPair = leadingRegex(arms[i]!) && leadingRegex(arms[j]!)\n out.push({\n kind: 'arm-overlap',\n id: `arm-overlap:${siteToString(v.site)}:${i}-${j}`,\n site: v.site,\n a: i, b: j,\n on: intersection(A, B),\n sharedLeadingTerms: shared,\n sharedPrefix: shared > 0 ? clamp(ta.slice(0, shared).map(t => render(t, 2)).join(', ')) : null,\n handledByStrategy: handled,\n regexPair,\n suggestion: overlapSuggestion(shared, handled, regexPair),\n })\n }\n }\n }\n return out.sort((a, b) => b.sharedLeadingTerms - a.sharedLeadingTerms)\n}\n\nfunction overlapSuggestion(shared: number, handled: boolean, regexPair: boolean): string {\n if (shared > 0 && handled)\n 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.`\n if (shared > 0)\n 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.`\n if (regexPair)\n 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.`\n 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.`\n}\n\n// \u2500\u2500 5. algebraic rewrites \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst 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.'\nconst PERF_NONE = ''\n\nfunction findRewrites(\n visited: Map<Combinator<unknown>, Visited>,\n shapeOf: (p: Combinator<unknown>) => number,\n): RewriteFinding[] {\n const out: RewriteFinding[] = []\n // `at` discriminates findings that a single site can produce MORE than one of.\n // Without it every `duplicate-arm`/`shadowed-arm` pair at one choice shares an\n // id, so accepting one pair silently suppresses the rest \u2014 and these are\n // `bug: true` findings that error mode is supposed to hold.\n const push = (f: Omit<RewriteFinding, 'kind' | 'id'>, at?: string): void => {\n const site = siteToString(f.site)\n out.push({ kind: 'rewrite', id: `rewrite:${f.rewrite}:${site}${at === undefined ? '' : `:${at}`}`, ...f })\n }\n\n for (const v of visited.values()) {\n const d = v.d\n const site = v.site\n\n // (a) idempotent nesting.\n if (d.tag === 'optional' || d.tag === 'many' || d.tag === 'oneOrMore') {\n const inner = (d as { parser: Combinator<unknown> }).parser\n const id = inner._def as ParserDef\n const collapsed = collapseRepeat(d, id)\n if (collapsed !== null) {\n push({\n rewrite: 'idempotent-nesting', site,\n from: clamp(render(v.p, 2)), to: collapsed,\n astNeutral: false,\n 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.',\n bug: id.tag === 'optional' && d.tag === 'many',\n suggestion: `\\`${clamp(render(v.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.`,\n })\n }\n }\n\n // (b) single-element choice/sequence.\n if ((d.tag === 'choice' || d.tag === 'sequence') && d.parsers.length === 1) {\n push({\n rewrite: 'single-element', site,\n from: clamp(render(v.p, 2)),\n 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)`,\n astNeutral: d.tag === 'choice',\n perf: d.tag === 'choice' ? 'a one-arm choice still emits its dispatch scaffolding.' : PERF_NONE,\n bug: false,\n suggestion: d.tag === 'choice'\n ? 'a `choice` with one arm IS that arm \u2014 the wrapper only adds dispatch scaffolding. Safe to unwrap (choice forwards its arm value unchanged).'\n : '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.',\n })\n }\n\n if (d.tag !== 'choice') continue\n const arms = d.parsers\n const armShapes = arms.map(shapeOf)\n const strategy = d.strategy as { tag: string; members?: number[] } | undefined\n\n // (c) duplicate arms \u2014 the later one is dead.\n for (let i = 0; i < arms.length; i++) for (let j = i + 1; j < arms.length; j++) {\n if (armShapes[i] !== armShapes[j]) continue\n push({\n rewrite: 'duplicate-arm', site,\n from: `choice(\u2026 arm[${i}] \u2026, arm[${j}] \u2026)`,\n to: `delete arm[${j}]`,\n astNeutral: true,\n perf: PERF_ARM,\n bug: true,\n 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.`,\n }, `${i}-${j}`)\n }\n\n // (d) shadowed arm: an earlier arm is a strict TERM-PREFIX of a later one.\n for (let i = 0; i < arms.length; i++) for (let j = 0; j < arms.length; j++) {\n if (i >= j) continue\n if (armShapes[i] === armShapes[j]) continue\n const ta = termsOf(arms[i]!), tb = termsOf(arms[j]!)\n if (ta.length === 0 || ta.length >= tb.length) continue\n let k = 0\n while (k < ta.length && shapeOf(ta[k]!) === shapeOf(tb[k]!)) k++\n if (k !== ta.length) continue\n push({\n rewrite: 'shadowed-arm', site,\n from: `choice(\u2026 arm[${i}]=${clamp(render(arms[i]!, 2))}, \u2026 arm[${j}]=${clamp(render(arms[j]!, 2))} \u2026)`,\n to: `arm[${j}] is unreachable`,\n astNeutral: true,\n perf: PERF_ARM,\n bug: true,\n 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.`,\n }, `${i}-${j}`)\n }\n\n // (e) optional prefix / suffix \u2014 `choice(sequence(A, R\u2026), R\u2026)` is `sequence(optional(A), R\u2026)`.\n for (let i = 0; i + 1 < arms.length; i++) {\n const j = i + 1\n const longer = termsOf(arms[i]!), shorter = termsOf(arms[j]!)\n const ordered = detectOptionalTerm(longer, shorter, shapeOf)\n const reversed = ordered === null ? detectOptionalTerm(shorter, longer, shapeOf) : null\n const hit = ordered ?? reversed\n if (hit === null) continue\n const nodeWrapped = v.enclosingNode ?? wrappingNodeType(arms[i]!) ?? wrappingNodeType(arms[j]!)\n const rest = hit.rest.map(t => render(t, 2)).join(', ')\n const to = hit.where === 'prefix'\n ? `sequence(optional(${render(hit.term, 2)}), ${rest})`\n : `sequence(${rest}, optional(${render(hit.term, 2)}))`\n push({\n rewrite: hit.where === 'prefix' ? 'optional-prefix' : 'optional-suffix',\n site,\n from: clamp(render(v.p, 2)),\n to: clamp(to),\n astNeutral: false,\n perf: PERF_ARM,\n bug: false,\n 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.`,\n }, `${i}-${j}`)\n }\n\n // (f) left-factoring.\n for (let i = 0; i + 1 < arms.length; i++) {\n const j = i + 1\n const ta = termsOf(arms[i]!), tb = termsOf(arms[j]!)\n if (ta.length < 2 || tb.length < 2) continue\n let k = 0\n while (k < ta.length - 1 && k < tb.length - 1 && shapeOf(ta[k]!) === shapeOf(tb[k]!)) k++\n if (k === 0) continue\n const handled = strategy?.tag === 'sharedPrefix'\n && Array.isArray(strategy.members) && strategy.members.includes(i) && strategy.members.includes(j)\n push({\n rewrite: 'left-factor', site,\n from: `choice(sequence(${ta.map(t => render(t, 1)).join(', ')}), sequence(${tb.map(t => render(t, 1)).join(', ')}))`,\n 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(', ')})))`),\n astNeutral: false,\n perf: handled\n ? '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.'\n : PERF_ARM,\n bug: false,\n 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.`,\n }, `${i}-${j}`)\n }\n }\n\n // (g) hand-rolled sepBy \u2014 sequence(X, many(sequence(S, X))).\n for (const v of visited.values()) {\n if (v.d.tag !== 'sequence') continue\n const hit = detectHandRolledSepBy(v.d.parsers, shapeOf)\n if (hit === null) continue\n // Anywhere in the REPETITION, not just on the separator itself: a `field()`\n // wrapping the whole `sequence(sep, item)` is the same blocker.\n const captured = v.d.parsers.some(t => capturesPositionally(t))\n const verdict: SepByVerdict = captured ? 'blocked-by-capture' : v.enclosingReducer ? 'reducer-stride-review' : 'convertible'\n const to = `sepBy(${clamp(render(hit.item, 2))}, ${clamp(render(hit.sep, 2))}${hit.trailing ? `, { trailing: 'allow' }` : ''}, { min: ${hit.min} })`\n out.push({\n kind: 'rewrite',\n id: `rewrite:hand-rolled-sepby:${siteToString(v.site)}`,\n rewrite: 'hand-rolled-sepby',\n site: v.site,\n sepByVerdict: verdict,\n from: clamp(render(v.p, 3)),\n to: verdict === 'convertible' ? to : `${to} \u2014 NOT APPLICABLE HERE (${verdict})`,\n astNeutral: false,\n perf: verdict === 'convertible'\n ? 'the hand-rolled form allocates a tuple per repetition (`sequence(sep, item)`) and a wrapper array around them; `sepBy` builds the item list directly.'\n : PERF_NONE,\n bug: false,\n suggestion: `${SEPBY_SPELLED_OUT(hit.trailing)} ${SEPBY_VERDICT_TEXT[verdict](hit.trailing)}`,\n })\n }\n\n return out\n}\n\nfunction collapseRepeat(outer: ParserDef, inner: ParserDef): string | null {\n const o = outer.tag, i = inner.tag\n if (o === 'optional' && i === 'optional') return 'optional(X)'\n if (o === 'optional' && i === 'many') return 'many(X)'\n if (o === 'many' && i === 'many') return 'many(X)'\n if (o === 'many' && i === 'optional') return 'many(X)'\n if (o === 'optional' && i === 'oneOrMore' && inner.min === 1 && inner.max === undefined) return 'many(X)'\n if (o === 'many' && i === 'oneOrMore' && inner.min === 1 && inner.max === undefined) return 'many(X)'\n return null\n}\n\n/** `node()` type wrapping an arm, for the AST-neutrality caveat. */\nfunction wrappingNodeType(arm: Combinator<unknown>): string | null {\n const d = arm._def as ParserDef\n return d.tag === 'node' ? d.type ?? '(anonymous)' : null\n}\n\n/**\n * `longer` = `shorter` plus ONE extra term at the front or the back. That extra\n * term is exactly an `optional()`.\n */\nfunction detectOptionalTerm(\n longer: readonly Combinator<unknown>[],\n shorter: readonly Combinator<unknown>[],\n shapeOf: (p: Combinator<unknown>) => number,\n): { where: 'prefix' | 'suffix'; term: Combinator<unknown>; rest: readonly Combinator<unknown>[] } | null {\n if (longer.length !== shorter.length + 1 || shorter.length === 0) return null\n const same = (a: readonly Combinator<unknown>[], b: readonly Combinator<unknown>[]): boolean =>\n a.length === b.length && a.every((x, i) => shapeOf(x) === shapeOf(b[i]!))\n if (same(longer.slice(1), shorter)) return { where: 'prefix', term: longer[0]!, rest: shorter }\n if (same(longer.slice(0, -1), shorter)) return { where: 'suffix', term: longer[longer.length - 1]!, rest: shorter }\n return null\n}\n\nconst SEPBY_SPELLED_OUT = (trailing: boolean): string =>\n `this is \\`sepBy(item, sep${trailing ? \", { trailing: 'allow' }\" : ''})\\` spelled out.`\n\n/** The verdict text. Each says what to DO, and the blocked ones say why not. */\nconst SEPBY_VERDICT_TEXT: Record<SepByVerdict, (trailing: boolean) => string> = {\n 'blocked-by-capture': () =>\n '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.',\n 'reducer-stride-review': () =>\n '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.',\n convertible: (trailing: boolean) =>\n `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]]\\`.`,\n}\n\n/**\n * Whether a hand-rolled separated list can ACTUALLY become `sepBy` \u2014 a verdict per\n * site, not a count. Reporting every match as convertible generates false work: on\n * the reference Less grammar only a minority are, and the rest are blocked for two\n * concrete, detectable reasons.\n */\nexport type SepByVerdict = 'convertible' | 'blocked-by-capture' | 'reducer-stride-review'\n\n/** Does this subtree capture anything positionally (`field`/`label`)? */\nfunction capturesPositionally(p: Combinator<unknown>, seen = new Set<Combinator<unknown>>()): boolean {\n if (seen.has(p)) return false\n seen.add(p)\n const d = p._def as ParserDef\n if (d.tag === 'field' || d.tag === 'label') return true\n for (const k of childrenOf(d)) if (capturesPositionally(k, seen)) return true\n return false\n}\n\n/** `sequence(X, many(sequence(S, X)) [, optional(S)])` \u2014 a `sepBy` written out. */\nfunction detectHandRolledSepBy(\n terms: readonly Combinator<unknown>[],\n shapeOf: (p: Combinator<unknown>) => number,\n): { item: Combinator<unknown>; sep: Combinator<unknown>; trailing: boolean; min: number } | null {\n if (terms.length < 2 || terms.length > 3) return null\n const item = terms[0]!\n const rep = terms[1]!._def as ParserDef\n if (rep.tag !== 'many' && rep.tag !== 'oneOrMore') return null\n if (rep.max !== undefined) return null\n const innerDef = rep.parser._def as ParserDef\n if (innerDef.tag !== 'sequence' || innerDef.parsers.length !== 2) return null\n const [sep, repeated] = innerDef.parsers as [Combinator<unknown>, Combinator<unknown>]\n if (shapeOf(repeated) !== shapeOf(item)) return null\n let trailing = false\n if (terms.length === 3) {\n const t = terms[2]!._def as ParserDef\n if (t.tag !== 'optional' || shapeOf(t.parser) !== shapeOf(sep)) return null\n trailing = true\n }\n // The leading item plus whatever the repetition itself requires. `rep.min` is\n // already RESOLVED for both tags (`many` defaults it to 0, `oneOrMore` to 1), so\n // one expression covers both \u2014 special-casing the tag dropped an explicit\n // `many(\u2026, { min: n })` back to 1 and under-reported the rewrite's bound.\n return { item, sep, trailing, min: 1 + rep.min }\n}\n\n// \u2500\u2500 5b. one node type, several divergent productions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The term list of a `node()`'s BODY. Peels more wrappers than `termsOf` \u2014 a\n * clone typically differs from its original by exactly such a wrapper\n * (`noTrivia(\u2026)` around the sequence), and that difference is the thing to see\n * through, not the thing to report.\n */\nfunction bodyTermsOf(p: Combinator<unknown>): readonly Combinator<unknown>[] {\n let cur = p\n for (;;) {\n const d = cur._def as ParserDef\n if (d.tag === 'node' || d.tag === 'grammar' || d.tag === 'transform' || d.tag === 'label'\n || d.tag === 'attempt' || d.tag === 'leaf' || d.tag === 'token' || d.tag === 'expect' || d.tag === 'field') {\n cur = (d as { parser: Combinator<unknown> }).parser\n continue\n }\n break\n }\n const d = cur._def as ParserDef\n return d.tag === 'sequence' ? d.parsers : [cur]\n}\n\n/** Terms must overlap this much before two productions count as variants of one\n * shape rather than two genuinely different constructs that share a node type. */\nconst MIN_SHARED_TERMS = 2\n\nfunction findDivergentNodes(\n visited: Map<Combinator<unknown>, Visited>,\n shapeOf: (p: Combinator<unknown>) => number,\n): DivergentNodeFinding[] {\n const byType = new Map<string, Map<number, Visited>>()\n for (const v of visited.values()) {\n if (v.d.tag !== 'node' || v.d.type === undefined) continue\n let m = byType.get(v.d.type)\n if (m === undefined) { m = new Map(); byType.set(v.d.type, m) }\n if (!m.has(v.shape)) m.set(v.shape, v)\n }\n\n const out: DivergentNodeFinding[] = []\n for (const [type, m] of byType) {\n if (m.size < 2) continue\n const members = [...m.values()]\n const termSets = members.map(v => bodyTermsOf(v.p).map(t => ({ id: shapeOf(t), text: clamp(render(t, 2)) })))\n // Shared = spelled by EVERY production. That is what makes them one shape.\n const shared = termSets[0]!.filter(t => termSets.every(set => set.some(x => x.id === t.id)))\n const uniqueShared = [...new Map(shared.map(t => [t.id, t])).values()]\n if (uniqueShared.length < MIN_SHARED_TERMS) continue\n const sharedIds = new Set(uniqueShared.map(t => t.id))\n out.push({\n kind: 'divergent-node',\n id: `divergent-node:${type}`,\n nodeType: type,\n count: members.length,\n sharedTerms: uniqueShared.map(t => t.text),\n productions: members.map((v, i) => ({\n shape: clamp(render(v.p, 3)),\n site: v.site,\n distinctTerms: termSets[i]!.filter(t => !sharedIds.has(t.id)).map(t => t.text),\n })),\n 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.`,\n })\n }\n return out.sort((a, b) => b.sharedTerms.length * b.count - a.sharedTerms.length * a.count)\n}\n\n// \u2500\u2500 5c. an earlier arm that flattens what a later arm structures \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Peel the wrappers that are REFERENTIAL or purely annotative, so an arm written\n * `g.FlatDecl` is compared as the production it names. `transform`/`leaf`/`token`\n * are deliberately NOT peeled: each of them collapses its interior to one value\n * on purpose, and treating a `leaf(node('X', \u2026))` as if it still produced an `X`\n * would invert the very question this analysis asks.\n */\nfunction resolveArm(p: Combinator<unknown>): Combinator<unknown> {\n let cur = p\n const seen = new Set<Combinator<unknown>>()\n for (;;) {\n if (seen.has(cur)) return cur\n seen.add(cur)\n const d = cur._def as ParserDef\n if (d.tag === 'label' || d.tag === 'attempt') { cur = d.parser; continue }\n if (d.tag === 'lazy') {\n try { cur = (d as { thunk(): Combinator<unknown> }).thunk(); continue }\n catch { return cur } // unresolved cross-artifact hole\n }\n return cur\n }\n}\n\n/**\n * The `node()` types this subtree can put INSIDE the tree, excluding its own root\n * wrapper. Refs are followed (the structure a declaration's value builds usually\n * lives behind `g.valueList`, and an analysis that stopped at the ref would report\n * every grammar as flat). `leaf()`/`token()` are opaque: they reduce their\n * interior to a single value, so nothing under one reaches the tree.\n */\nfunction nestedNodeTypes(\n root: Combinator<unknown>,\n out: Set<string>,\n seen: Set<Combinator<unknown>>,\n isRoot: boolean,\n): void {\n if (seen.has(root)) return\n seen.add(root)\n const d = root._def as ParserDef\n if (d.tag === 'leaf' || d.tag === 'token') return\n if (d.tag === 'node' && !isRoot) out.add(d.type ?? '(anonymous)')\n if (d.tag === 'lazy') {\n try { nestedNodeTypes((d as { thunk(): Combinator<unknown> }).thunk(), out, seen, false) }\n catch { /* unresolved cross-artifact hole */ }\n return\n }\n for (const k of childrenOf(d)) nestedNodeTypes(k, out, seen, false)\n}\n\n/** Most node types worth naming in one finding before it stops being a list. */\nconst MAX_LOST_TYPES = 8\n\nfunction findStructureLoss(\n visited: Map<Combinator<unknown>, Visited>,\n resolve?: RefResolver,\n): StructureLossFinding[] {\n const nestedCache = new Map<Combinator<unknown>, Set<string>>()\n const nested = (p: Combinator<unknown>): Set<string> => {\n const hit = nestedCache.get(p)\n if (hit !== undefined) return hit\n const out = new Set<string>()\n nestedNodeTypes(p, out, new Set(), true)\n nestedCache.set(p, out)\n return out\n }\n\n const findings: StructureLossFinding[] = []\n for (const v of visited.values()) {\n const d = v.d\n if (d.tag !== 'choice') continue\n const arms = d.parsers\n const resolved = arms.map(resolveArm)\n const nodeTypes = resolved.map(wrappingNodeType)\n const fs = arms.map(a => firstSetOf(a, new Set(), resolve))\n\n for (let i = 0; i < arms.length; i++) {\n // A GATED arm is selected by a runtime predicate, not by order alone. The\n // author has said which branch applies when; that is a deliberate split,\n // not a shadow, so it is not reported as a bug.\n if (d.gates[i] != null) continue\n const type = nodeTypes[i] ?? null\n if (type === null) continue\n // Only the arm that produces NO nested node is reported. \"Earlier arm is\n // strictly poorer than later arm\" is the same family, but grading it means\n // comparing two ref-reachable type sets, and in a recursive grammar the\n // later set reaches most of the grammar \u2014 so the graded rule fires on\n // almost every pair and stops being a signal. Empty-vs-nonempty needs no\n // threshold and is exactly the reported defect: a node over bare leaves.\n if (nested(resolved[i]!).size !== 0) continue\n const A = fs[i]!\n if (A.kind === 'any') continue // gating's `anyArms` owns the any-first-set case\n\n for (let j = i + 1; j < arms.length; j++) {\n if (nodeTypes[j] !== type) continue\n const B = fs[j]!\n // OVER-APPROXIMATION, and the one place this finding can be wrong. A shared\n // first character is NECESSARY for the earlier arm to shadow the later one,\n // not sufficient: two arms can both start on `-` and still accept disjoint\n // languages (`-webkit-x` vs `-5px`), in which case no input reaches both and\n // nothing is shadowed. Deciding \"do these two arms share an input\" is\n // language intersection, which is undecidable for a general CFG, so a\n // first-set test is the strongest decidable proxy available. The finding is\n // therefore \"these arms overlap on these characters, and IF an input reaches\n // both then structure is lost\" \u2014 which is what the suggestion text says, and\n // why a reader is pointed at the two shapes rather than handed a verdict.\n if (B.kind === 'any' || !intersects(A, B)) continue\n const lost = nested(resolved[j]!)\n if (lost.size === 0) continue\n const lostNodeTypes = [...lost].sort()\n findings.push({\n kind: 'structure-loss',\n id: `structure-loss:${siteToString(v.site)}:${i}-${j}`,\n site: v.site,\n nodeType: type,\n earlier: i,\n later: j,\n on: intersection(A, B),\n lostNodeTypes: lostNodeTypes.slice(0, MAX_LOST_TYPES),\n earlierShape: clamp(render(resolved[i]!, 3)),\n laterShape: clamp(render(resolved[j]!, 3)),\n suggestion: structureLossSuggestion(type, i, j, lostNodeTypes),\n })\n }\n }\n }\n return findings.sort((a, b) => b.lostNodeTypes.length - a.lostNodeTypes.length)\n}\n\nfunction structureLossSuggestion(\n type: string,\n i: number,\n j: number,\n lost: readonly string[],\n): string {\n const names = lost.slice(0, MAX_LOST_TYPES).map(t => `\\`${t}\\``).join(', ')\n const more = lost.length > MAX_LOST_TYPES ? ` (and ${lost.length - MAX_LOST_TYPES} more)` : ''\n 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.`\n}\n\n// \u2500\u2500 6. hand-rolled keyword regexes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction findKeywordRegexes(visited: Map<Combinator<unknown>, Visited>): KeywordRegexFinding[] {\n // Sibling map: which choice arms are themselves hand-rolled keywords.\n const armIndexOf = new Map<Combinator<unknown>, { owner: Combinator<unknown>; index: number }>()\n for (const v of visited.values()) {\n if (v.d.tag !== 'choice') continue\n v.d.parsers.forEach((a, i) => {\n let cur = a\n for (;;) {\n const cd = cur._def as ParserDef\n if (cd.tag === 'node' || cd.tag === 'label' || cd.tag === 'transform' || cd.tag === 'leaf' || cd.tag === 'attempt') { cur = cd.parser; continue }\n break\n }\n armIndexOf.set(cur, { owner: v.p, index: i })\n })\n }\n const keywordArms = new Map<Combinator<unknown>, number[]>()\n for (const [arm, { owner }] of armIndexOf) {\n const d = arm._def as ParserDef\n if (d.tag !== 'regex' || keywordRegexShape(d.source) === null) continue\n const list = keywordArms.get(owner) ?? []\n list.push(armIndexOf.get(arm)!.index)\n keywordArms.set(owner, list)\n }\n\n const out: KeywordRegexFinding[] = []\n for (const v of visited.values()) {\n const d = v.d\n if (d.tag !== 'regex') continue\n const shape = keywordRegexShape(d.source)\n if (shape === null) continue\n const ci = d.flags.includes('i')\n const unicode = d.flags.includes('u') || d.flags.includes('v')\n const own = armIndexOf.get(v.p)\n const siblings = own === undefined ? [] : (keywordArms.get(own.owner) ?? []).filter(i => i !== own.index)\n const bq = (s: string): string => `'${s.replace(/\\\\/g, '\\\\\\\\')}'`\n const vocabulary = shape.words.length >= VOCABULARY_MIN_WORDS\n const hazards = keywordAlternationHazards(shape.words, shape.boundary)\n const unrescued = hazards.filter(h => !h.rescuedByBoundary)\n const longestFirst = shape.words.every((w, i) => i === 0 || shape.words[i - 1]!.length >= w.length)\n const shown = shape.words.length > 8 ? [...shape.words.slice(0, 6), '/* \u2026 */', shape.words[shape.words.length - 1]!] : shape.words\n const call = shape.words.length === 1\n ? `word(${bq(shape.words[0]!)}, ${bq(shape.boundary ?? '_0-9A-Za-z')}${ci ? ', { caseInsensitive: true }' : ''})`\n : `keywords([${shown.map(w => (w === '/* \u2026 */' ? w : bq(w))).join(', ')}], { boundary: ${bq(shape.boundary ?? '_0-9A-Za-z')}${ci ? ', caseInsensitive: true' : ''} })`\n out.push({\n kind: 'keyword-regex',\n id: `keyword-regex:${siteToString(v.site)}`,\n site: v.site,\n source: d.source,\n flags: d.flags,\n words: shape.words,\n boundary: shape.boundary,\n caseFoldRisk: ci && !unicode,\n siblingArms: siblings,\n vocabulary,\n longestFirst,\n hazards,\n bug: unrescued.length > 0,\n suggestion: [\n vocabulary\n ? `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.`\n : `\\`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.`,\n unrescued.length > 0\n ? `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.`\n : hazards.length > 0\n ? `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.`\n : !longestFirst && vocabulary\n ? `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.`\n : '',\n ci && !unicode\n ? `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, \u00B5/\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.`\n : '',\n siblings.length > 0\n ? `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.`\n : '',\n ].filter(s => s !== '').join(' '),\n })\n }\n // Bugs first, then the biggest vocabularies: a 150-word alternation is both the\n // most valuable conversion and the least likely to be spotted by reading.\n return out.sort((a, b) =>\n Number(b.bug) - Number(a.bug)\n || b.hazards.length - a.hazards.length\n || b.words.length - a.words.length\n || b.siblingArms.length - a.siblingArms.length)\n}\n\n// \u2500\u2500 formatting \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type DuplicationWarnLevel = 'off' | 'warn' | 'error'\n\nconst sitesLine = (sites: readonly Site[]): string =>\n sites.slice(0, 6).map(siteToString).join('\\n ') + (sites.length > 6 ? `\\n \u2026 and ${sites.length - 6} more` : '')\n\n/**\n * Ranked, actionable lines \u2014 same tone and shape as `formatGatingWarnings`: what\n * it is, where it is, and one concrete thing to do about it.\n */\nexport function formatDuplicationFindings(report: DuplicationReport): string[] {\n const lines: string[] = []\n // First: the only family here that is silently WRONG rather than redundant \u2014\n // the parse succeeds, so nothing else reports it.\n for (const f of report.structureLoss) {\n 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)}`)\n lines.push(` flat: ${f.earlierShape}`)\n lines.push(` rich: ${f.laterShape}`)\n lines.push(` lost: ${f.lostNodeTypes.map(t => `\\`${t}\\``).join(', ')}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n for (const f of report.rewrites) {\n lines.push(`parseman ${f.bug ? 'BUG' : 'rewrite'} [${f.rewrite}${f.sepByVerdict === undefined ? '' : `/${f.sepByVerdict}`}] @ ${siteToString(f.site)}${f.astNeutral ? '' : ' (candidate \u2014 verify AST identity)'}`)\n lines.push(` from: ${f.from}`)\n lines.push(` to: ${f.to}`)\n lines.push(` fix: ${f.suggestion}`)\n if (f.perf !== '') lines.push(` perf: ${f.perf}`)\n }\n for (const f of report.divergentNodes) {\n 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(', ')}`)\n for (const p of f.productions) lines.push(` ${siteToString(p.site)}\\n ${p.shape}\\n unique to it: ${p.distinctTerms.length === 0 ? '(none)' : p.distinctTerms.map(t => `\\`${t}\\``).join(', ')}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n for (const f of report.keywordRegexes) {\n const src = f.source.length > 90 ? `${f.source.slice(0, 88)}\u2026` : f.source\n 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]' : ''}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n for (const f of report.duplicates) {\n lines.push(`parseman duplication: ${f.count}\u00D7 identical ${f.size}-node shape (saves ${f.savings} nodes) \u2014 ${f.shape}`)\n lines.push(` at: ${sitesLine(f.sites)}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n for (const f of report.nearDuplicates) {\n 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}`)\n lines.push(` slot: ${f.slotPath} \u2208 { ${f.variants.join(' | ')} }`)\n lines.push(` at: ${sitesLine(f.sites)}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n for (const f of report.regexFragments) {\n lines.push(`parseman regex-fragment: \\`${f.fragment}\\` (${f.branches} branches) re-spelled in ${f.count} regex() terminals`)\n lines.push(` at: ${sitesLine(f.sites)}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n for (const f of report.regexClasses) {\n lines.push(`parseman regex-class${f.drifted ? ' DRIFT' : ''}: [${f.canonical}] across ${f.count} regex() terminals${f.bmpCeiling ? ' [BMP ceiling]' : ''}`)\n for (const v of f.variants) lines.push(` [${v.source}] \u00D7${v.count} ${v.delta}\\n ${sitesLine(v.sites)}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n for (const f of report.overlaps) {\n 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]' : ''}`)\n lines.push(` fix: ${f.suggestion}`)\n }\n return lines\n}\n\n/** Total findings across every category \u2014 the number the `'error'` gate keys on. */\nexport function duplicationFindingCount(report: DuplicationReport): number {\n return report.duplicates.length + report.nearDuplicates.length + report.regexFragments.length\n + report.regexClasses.length + report.overlaps.length + report.rewrites.length\n + report.divergentNodes.length + report.structureLoss.length + report.keywordRegexes.length\n}\n", "import type { ParseContext, ParseFail } from '../types.ts'\n\n/**\n * Creates a ParseFail and, if a completions probe is active, records it.\n *\n * Rules:\n * - Only failures at or before the probe's target offset are eligible.\n * - A deeper failure (higher pos) replaces the current best.\n * - A tie (same pos) merges expected arrays \u2014 this is what makes choice arms\n * aggregate their alternatives rather than each overwriting the last.\n * - Shallower failures are ignored.\n */\nexport function failAt(ctx: ParseContext, expected: string[], pos: number): ParseFail {\n const r: ParseFail = { ok: false, expected, span: { start: pos, end: pos } }\n const probe = ctx._probe\n if (probe !== undefined && pos <= probe.offset) {\n const best = probe.best\n if (best === null || pos > best.span.start) {\n probe.best = r\n } else if (pos === best.span.start) {\n probe.best = { ...best, expected: [...best.expected, ...expected] }\n }\n }\n return r\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { fromChar, empty } from './first-set.ts'\nimport { failAt } from './probe.ts'\nimport { pushCstLeaf, cstCaptureActive } from '../cst/capture-buffer.ts'\nimport { recordLineRangeFromContext } from '../line-index.ts'\n\n/**\n * ASCII case-fold equality \u2014 the interpreter twin of the compiler's `foldEq`\n * (and `/i`-flag regex lowering). Folds ASCII letters via bit 0x20, exact-matches\n * everything else. Deliberately NOT `Intl.Collator` (measured ~9\u00D7 slower, and its\n * Unicode accent-folding is the wrong semantic for a parser). Keeps interpreter /\n * compiled / macro output identical for case-insensitive `literal()`.\n */\nfunction asciiFoldEq(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n let ca = a.charCodeAt(i)\n let cb = b.charCodeAt(i)\n if (ca >= 65 && ca <= 90) ca += 32\n if (cb >= 65 && cb <= 90) cb += 32\n if (ca !== cb) return false\n }\n return true\n}\n\nexport type LiteralOptions = {\n caseInsensitive?: boolean\n}\n\nexport function literal(value: string, opts: LiteralOptions = {}): Combinator<string> {\n const caseInsensitive = opts.caseInsensitive ?? false\n\n const firstSet = value.length > 0\n ? fromChar(value.codePointAt(0)!)\n : empty()\n\n const meta: ParserMeta = {\n firstSet,\n canMatchNewline: value.includes('\\n'),\n isTrivia: false,\n }\n const canMatchNewline = meta.canMatchNewline\n\n if (caseInsensitive) {\n const upper = value.toUpperCase()\n const lower = value.toLowerCase()\n const firstUpper = upper.codePointAt(0)\n const firstLower = lower.codePointAt(0)\n // Two discrete points, not one spanning range \u2014 `asciiFoldEq` accepts only\n // the char and its fold twin, so `[min, max]` would over-approximate (e.g.\n // 'a'/'A' \u2192 the whole 65..97 span, pulling B\u2013Z/`[\\]^_\\`` into dispatch).\n meta.firstSet = firstLower !== undefined && firstUpper !== undefined\n ? firstLower === firstUpper\n ? { kind: 'ranges', ranges: [{ lo: firstLower, hi: firstLower }] }\n : { kind: 'ranges', ranges: [\n { lo: firstLower, hi: firstLower },\n { lo: firstUpper, hi: firstUpper },\n ]}\n : firstSet\n }\n\n const expected = [JSON.stringify(value)]\n\n // Single-char case-sensitive literals are the bulk of punctuation-heavy\n // grammars (GraphQL `{ } ( ) : $ @ [ ] ! =`, JSON, CSS). A bare `charCodeAt`\n // compare beats the generic `startsWith` builtin call, and an out-of-bounds\n // `charCodeAt` returns NaN \u2014 so the length check folds into the compare.\n const parse = !caseInsensitive && value.length === 1\n ? (() => {\n const code = value.charCodeAt(0)\n return function parse(input: string, pos: number, ctx: ParseContext): ParseResult<string> {\n if (input.charCodeAt(pos) === code) {\n const span = { start: pos, end: pos + 1 }\n if (canMatchNewline && ctx.trackLines) recordLineRangeFromContext(ctx, input, pos, span.end)\n if (cstCaptureActive(ctx)) pushCstLeaf(ctx, { _tag: 'leaf', value, span })\n return { ok: true, value, span }\n }\n return failAt(ctx, expected, pos)\n }\n })()\n : function parse(input: string, pos: number, ctx: ParseContext): ParseResult<string> {\n const end = pos + value.length\n if (end > input.length) {\n return failAt(ctx, expected, pos)\n }\n const matchedValue = caseInsensitive ? input.slice(pos, end) : value\n if (caseInsensitive ? asciiFoldEq(matchedValue, value) : input.startsWith(value, pos)) {\n const span = { start: pos, end }\n if (canMatchNewline && ctx.trackLines) recordLineRangeFromContext(ctx, input, pos, end)\n if (cstCaptureActive(ctx)) pushCstLeaf(ctx, { _tag: 'leaf', value: matchedValue, span })\n return { ok: true, value: matchedValue, span }\n }\n return failAt(ctx, expected, pos)\n }\n\n return {\n _tag: 'literal',\n _meta: meta,\n _def: { tag: 'literal', value, caseInsensitive },\n parse,\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta, FirstSet } from '../types.ts'\nimport { any } from './first-set.ts'\nimport { failAt } from './probe.ts'\nimport { pushCstLeaf, cstCaptureActive } from '../cst/capture-buffer.ts'\nimport { recordLineRangeFromContext } from '../line-index.ts'\nimport { shorthandRanges, parseClassRanges } from '../regex/classes.ts'\n\n/**\n * Computes a regex terminal's first-set (for choice-dispatch fast paths). The\n * implementation \u2014 `firstSetFromRegex` in `../regex/first-set.ts` \u2014 is a small,\n * dependency-free hand-rolled regex parser, registered by the interpreter/library\n * entry (`index.ts`) via `registerRegexAnalyzer`. It is injected rather than\n * imported so that consumers who import `regex` directly from this subpath (no\n * library entry) never pull the analyzer into their bundle at all. When no\n * analyzer is registered, `regex()` uses the permissive fallback below \u2014 this\n * only disables the dispatch fast paths, never changing matches.\n */\nexport type RegexFirstSetAnalyzer = (pattern: string) => { firstSet: FirstSet; canMatchNewline: boolean }\n\nlet firstSetAnalyzer: RegexFirstSetAnalyzer | null = null\n\nexport function registerRegexAnalyzer(analyzer: RegexFirstSetAnalyzer): void {\n firstSetAnalyzer = analyzer\n}\n\n/** Fallback when no analyzer is registered: \"could start with any char / could\n * match a newline\" \u2014 the same conservative value `firstSetFromRegex` returns on\n * an unparseable pattern, so a missing analyzer degrades to \"no fast path\", not\n * a wrong one. */\nconst permissiveFirstSet: RegexFirstSetAnalyzer = () => ({ firstSet: any(), canMatchNewline: true })\n\nconst SCAN_BAIL_AT = 64\ntype ShortScanner = (input: string, pos: number) => number | null | undefined\n\nfunction inRanges(cp: number, ranges: Array<[number, number]>): boolean {\n for (let i = 0; i < ranges.length; i++) {\n const [lo, hi] = ranges[i]!\n if (cp >= lo && cp <= hi) return true\n }\n return false\n}\n\n/**\n * The positive char-class body (chars between `[` and `]`) as ranges for the\n * short-scan fast path, or null if it can't be lowered \u2014 including a NEGATED\n * class (`[^\u2026]`), which the scan can't express. The class parsing itself is the\n * shared `parseClassRanges` (see `../regex/classes.ts`).\n */\nfunction readClassRanges(body: string): Array<[number, number]> | null {\n if (body.startsWith('^')) return null\n return parseClassRanges(body)\n}\n\nfunction shortScanner(source: string, flags: string): ShortScanner | null {\n if (/[imsuvy]/.test(flags)) return null\n let ranges: Array<[number, number]> | null = null\n let quant = ''\n if (source[0] === '[') {\n let end = 1\n while (end < source.length && source[end] !== ']') {\n if (source[end] === '\\\\') end += 2\n else end++\n }\n if (source[end] !== ']') return null\n ranges = readClassRanges(source.slice(1, end))\n quant = source.slice(end + 1)\n } else if (source[0] === '\\\\' && (source[1] === 'd' || source[1] === 'w' || source[1] === 's')) {\n ranges = shorthandRanges(source[1])\n quant = source.slice(2)\n }\n if (!ranges || (quant !== '+' && quant !== '*')) return null\n const minOne = quant === '+'\n return (input, pos) => {\n let end = pos\n while (end < input.length && inRanges(input.charCodeAt(end), ranges)) {\n end++\n if (end - pos >= SCAN_BAIL_AT) return undefined\n }\n return minOne && end === pos ? null : end\n }\n}\n\n/**\n * ASCII-case-fold a first-set: for every ASCII letter reachable as a leading char,\n * also admit its opposite-case twin (A\u2013Z \u2194 a\u2013z). Non-letter code points and `any`/\n * `empty` are unchanged. Only widens the set (sound superset) \u2014 used to correct a\n * case-insensitive regex's flag-agnostic first-set for first-char dispatch. Unicode\n * case-folding beyond ASCII is deliberately NOT applied (parseman first-sets are\n * ASCII-BMP for dispatch); a non-ASCII letter keeps its own code point only, which\n * stays sound (the interpreter's real `/i` match still runs).\n */\nfunction asciiCaseFold(fs: FirstSet): FirstSet {\n if (fs.kind !== 'ranges') return fs\n const ranges: { lo: number; hi: number }[] = fs.ranges.map(r => ({ lo: r.lo, hi: r.hi }))\n const add = (lo: number, hi: number): void => { if (lo <= hi) ranges.push({ lo, hi }) }\n for (const r of fs.ranges) {\n // Uppercase portion [A\u2013Z] \u2192 lowercase twin (+32).\n const uLo = Math.max(r.lo, 65), uHi = Math.min(r.hi, 90)\n add(uLo + 32, uHi + 32)\n // Lowercase portion [a\u2013z] \u2192 uppercase twin (\u221232).\n const lLo = Math.max(r.lo, 97), lHi = Math.min(r.hi, 122)\n add(lLo - 32, lHi - 32)\n }\n // Normalize: sort + coalesce overlapping/adjacent ranges.\n ranges.sort((a, b) => a.lo - b.lo)\n const merged: { lo: number; hi: number }[] = []\n for (const r of ranges) {\n const last = merged[merged.length - 1]\n if (last && r.lo <= last.hi + 1) last.hi = Math.max(last.hi, r.hi)\n else merged.push({ lo: r.lo, hi: r.hi })\n }\n return { kind: 'ranges', ranges: merged }\n}\n\nexport function regex(pattern: string | RegExp, flags = ''): Combinator<string> {\n const source = typeof pattern === 'string' ? pattern : pattern.source\n const resolvedFlags = typeof pattern === 'string' ? flags : pattern.flags\n\n const anchored = new RegExp(source, 'y' + resolvedFlags.replace(/[gy]/g, ''))\n const scan = shortScanner(source, resolvedFlags)\n\n const raw = (firstSetAnalyzer ?? permissiveFirstSet)(source)\n // The first-set analyzer is flag-agnostic, so for a CASE-INSENSITIVE pattern it\n // returns only the literal-case leading chars \u2014 e.g. `/red|blue/i` \u2192 `{r,b}`, NOT\n // `{r,R,b,B}`. Using that narrow set for first-char DISPATCH would false-EXCLUDE the\n // opposite-case input (`ReD` gated out of a `/(?:red|\u2026)/i` arm), so widen it under\n // `i`. The widening is FLAG-AWARE because `i` alone and `i`+`u` fold different sets:\n // - `/i` WITHOUT `u`: ECMAScript case-insensitive matching folds ONLY the ASCII\n // Basic-Latin case pairs (`a`\u2194`A` \u2026 `z`\u2194`Z`) \u2014 a plain `/[a-z]/i` does NOT match\n // `\u017F`(U+017F) or `K`(U+212A). So `asciiCaseFold` is a SOUND, tight superset, and\n // it preserves at-keyword dispatch (`/@media\u2026/i` still gates on `@`).\n // - `/ui` or `/iv` (Unicode mode \u2014 the `u` OR the ES2024 `v` Unicode-sets flag):\n // matching uses Unicode *simple case folding*, so `/[a-z]/ui` (and `/[a-z]/iv`)\n // ALSO match `\u017F`\u2192s and `K`\u2192k. ASCII-folding can't enumerate those astral/BMP case\n // pairs, so gating on the ASCII set would false-exclude them. Fall back to `any()`\n // (always-try) \u2014 sound, and only forfeits gating for the rare Unicode-mode `/i`\n // recognizer, never the ASCII-only `/i` at-keywords the fix targets.\n const firstSet = !resolvedFlags.includes('i')\n ? raw.firstSet\n : (resolvedFlags.includes('u') || resolvedFlags.includes('v'))\n ? any()\n : asciiCaseFold(raw.firstSet)\n const canMatchNewline = raw.canMatchNewline\n const meta: ParserMeta = { firstSet, canMatchNewline, isTrivia: false }\n\n return {\n _tag: 'regex',\n _meta: meta,\n _def: { tag: 'regex', source, flags: resolvedFlags },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<string> {\n const scanEnd = scan?.(input, pos)\n if (scanEnd !== undefined) {\n if (scanEnd === null) return failAt(ctx, [`/${source}/`], pos)\n const value = input.slice(pos, scanEnd)\n const span = { start: pos, end: scanEnd }\n if (canMatchNewline && ctx.trackLines) recordLineRangeFromContext(ctx, input, pos, scanEnd)\n if (cstCaptureActive(ctx)) pushCstLeaf(ctx, { _tag: 'leaf', value, span })\n return { ok: true, value, span }\n }\n anchored.lastIndex = pos\n const m = anchored.exec(input)\n if (m === null) {\n return failAt(ctx, [`/${source}/`], pos)\n }\n const span = { start: pos, end: pos + m[0]!.length }\n if (canMatchNewline && ctx.trackLines) recordLineRangeFromContext(ctx, input, pos, span.end)\n if (cstCaptureActive(ctx)) pushCstLeaf(ctx, { _tag: 'leaf', value: m[0]!, span })\n return { ok: true, value: m[0]!, span }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta, ParseFail } from '../types.ts'\nimport { sequenceFirstSet, firstSetOf, union } from './first-set.ts'\nimport { advanceTrivia, needsDeferredTriviaCommit, rollbackTrivia, saveTriviaMark, scanTrivia } from './trivia-skip.ts'\nimport { firstSetSentinel } from '../recovery/scan.ts'\n\ntype UnwrapParsers<T extends Combinator<unknown>[]> = {\n [K in keyof T]: T[K] extends Combinator<infer U> ? U : never\n}\n\nexport function sequence<T extends [Combinator<unknown>, ...Combinator<unknown>[]]>(\n ...parsers: T\n): Combinator<UnwrapParsers<T>> {\n const meta: ParserMeta = {\n // Union through the nullable prefix \u2014 a leading optional()/many() lets a later\n // term's first char start the sequence. Just `parsers[0]` under-approximates.\n firstSet: sequenceFirstSet(parsers),\n canMatchNewline: parsers.some(p => p._meta.canMatchNewline),\n isTrivia: false,\n }\n\n const def: { tag: 'sequence'; parsers: Combinator<unknown>[]; valueUnused?: boolean } =\n { tag: 'sequence', parsers: parsers as Combinator<unknown>[] }\n\n // Automatic recovery-sync inference, built lazily on the first tolerant parse and\n // never touched on the strict path: followSentinels[i] matches (zero-width) when\n // the input could start any term AFTER i, so a list nested in term i can resync\n // to this sequence's enclosing delimiter with NO grammar annotation. This is the\n // whole of \"recovery config\" \u2014 derived from structure, not authored.\n let followSentinels: (Combinator<null> | null)[] | undefined\n\n // Tolerant twin of the strict loop: identical term-parsing, but around each term\n // it publishes the inferred follow sentinel into ctx._sync so a nested list can\n // resync to this sequence's enclosing delimiter. Cold path (tolerant only).\n function parseTolerant(input: string, pos: number, ctx: ParseContext): ParseResult<UnwrapParsers<T>> {\n followSentinels ??= parsers.map((_, i) => {\n // A nested list can resync to the start of ANY term that follows it here, so\n // union every following term's first set (not just up to the first\n // non-nullable one \u2014 a mandatory middle term must not hide a later close).\n const fs = parsers.slice(i + 1).reduce<ReturnType<typeof firstSetOf>>(\n (acc, p) => union(acc, firstSetOf(p)),\n { kind: 'empty' },\n )\n return firstSetSentinel(fs)\n })\n const values: unknown[] | undefined = def.valueUnused ? undefined : []\n let cur = pos\n const inheritedSync = ctx._sync\n try {\n for (let i = 0; i < parsers.length; i++) {\n // Publish this term's follow set (or keep the inherited sync when the local\n // follow isn't usable, e.g. the last term or an `any` first set).\n ctx._sync = followSentinels[i] ?? inheritedSync\n if (ctx.trivia && i > 0) {\n const mark = saveTriviaMark(ctx)\n let scanEnd: number\n if (needsDeferredTriviaCommit(ctx)) {\n const scan = scanTrivia(input, cur, ctx)\n scan.commit()\n scanEnd = scan.end\n } else {\n scanEnd = advanceTrivia(input, cur, ctx)\n }\n const result = parsers[i]!.parse(input, scanEnd, ctx)\n if (!result.ok) return result as ParseFail\n if (result.span.end > scanEnd) cur = result.span.end\n else rollbackTrivia(ctx, mark)\n if (values !== undefined) values.push(result.value)\n continue\n }\n const result = parsers[i]!.parse(input, cur, ctx)\n if (!result.ok) return result as ParseFail\n if (values !== undefined) values.push(result.value)\n cur = result.span.end\n }\n } finally {\n ctx._sync = inheritedSync\n }\n return {\n ok: true,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion\n value: (values ?? undefined) as UnwrapParsers<T>,\n span: { start: pos, end: cur },\n }\n }\n\n return {\n _tag: 'sequence',\n _meta: meta,\n _def: def,\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<UnwrapParsers<T>> {\n // One cold branch: in tolerant mode publish each term's follow-set as ctx._sync\n // so a nested list resyncs to the enclosing delimiter (dynamic scoping through\n // refs carries this across rule boundaries automatically). The strict loop\n // below is byte-identical to a parser with no recovery.\n if (ctx._tolerant) return parseTolerant(input, pos, ctx)\n\n // Skip the tuple when it's never observed (markUnusedValues): terms still\n // parse (and self-capture) \u2014 only the array of their values is elided.\n const values: unknown[] | undefined = def.valueUnused ? undefined : []\n let cur = pos\n\n for (let i = 0; i < parsers.length; i++) {\n if (ctx.trivia && i > 0) {\n // Skip trivia between terms, but only *consume* it for span purposes if\n // this term actually matches content past the trivia. A term that matches\n // empty (optional/many/lookahead) leaves the trivia for the enclosing rule.\n let scanEnd: number\n let mark = saveTriviaMark(ctx)\n\n if (needsDeferredTriviaCommit(ctx)) {\n const scan = scanTrivia(input, cur, ctx)\n scan.commit()\n scanEnd = scan.end\n } else {\n scanEnd = advanceTrivia(input, cur, ctx)\n }\n\n const result = parsers[i]!.parse(input, scanEnd, ctx)\n if (!result.ok) return result as ParseFail\n if (result.span.end > scanEnd) {\n cur = result.span.end\n } else {\n rollbackTrivia(ctx, mark)\n }\n if (values !== undefined) values.push(result.value)\n continue\n }\n\n const result = parsers[i]!.parse(input, cur, ctx)\n if (!result.ok) return result as ParseFail\n if (values !== undefined) values.push(result.value)\n cur = result.span.end\n }\n\n return {\n ok: true,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion\n value: (values ?? undefined) as UnwrapParsers<T>,\n span: { start: pos, end: cur },\n }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { advanceTrivia, needsDeferredTriviaCommit, rollbackTrivia, saveTriviaMark, scanTrivia } from './trivia-skip.ts'\nimport { matchesEmpty, startsFirstSet } from './first-set.ts'\nimport { deriveExpected } from './expect.ts'\nimport { matchesAt, orSentinel, recoverScan, captureError } from '../recovery/scan.ts'\n\n/**\n * Parse one repetition item at `cur`, first skipping (and, in capture mode,\n * recording) any leading trivia \u2014 so a repeating combinator consumes the trivia\n * between items uniformly, the way advancing the index always should. Trivia is\n * committed *before* the item so rawChildren order stays [item, trivia, item];\n * if the item then fails or makes no progress the trivia is rolled back and the\n * loop stops (the trivia is trailing and belongs to the enclosing context).\n *\n * Returns the item value + end position, the underlying failure (so oneOrMore\n * can propagate a first-item failure), or 'stop'.\n */\nfunction repItem<T>(\n combinator: Combinator<T>,\n input: string,\n cur: number,\n ctx: ParseContext,\n guardable: boolean,\n): { value: T; end: number } | { fail: ParseResult<T>; failPos: number } | 'stop' {\n const mark = saveTriviaMark(ctx)\n let pos = cur\n if (ctx.trivia) {\n if (needsDeferredTriviaCommit(ctx)) {\n const scan = scanTrivia(input, cur, ctx)\n scan.commit()\n pos = scan.end\n } else {\n pos = advanceTrivia(input, cur, ctx)\n }\n }\n // Nothing but trivia left: don't speculatively parse an item at EOF (it would\n // fail and could trigger an item's expect()/error side-effects). The trivia\n // is trailing \u2014 roll it back for the enclosing context and stop.\n if (pos >= input.length) {\n rollbackTrivia(ctx, mark)\n return 'stop'\n }\n // First-set fast-path (mirrors emitMany's codegen guard): a body that can't match\n // empty and whose first set can't start at `pos` can ONLY fail this iteration, so\n // stop before the (composite) body's setup-then-fail. This is behaviour-identical\n // in strict mode \u2014 a swallowed body failure is discarded either way, and a\n // zero-width/leaf miss reaches the same loop stop. Skipped under a completions\n // probe or tolerant recovery, where a swallowed failure still feeds the probe /\n // triggers resync (matching the codegen guard's `!ctx.recovery` gate).\n if (guardable && ctx._probe === undefined && !ctx._tolerant && !startsFirstSet(combinator, input, pos)) {\n rollbackTrivia(ctx, mark)\n return 'stop'\n }\n const result = combinator.parse(input, pos, ctx)\n if (!result.ok) {\n rollbackTrivia(ctx, mark)\n if (result.committed) return { fail: result, failPos: pos }\n // Surface the POST-trivia position where the element actually failed. The\n // tolerant recovery guard must check the sync token there \u2014 not at `cur`,\n // which sits before any leading trivia \u2014 so trailing trivia before the sync\n // isn't mistaken for junk and swallowed into a spurious ParseError.\n return { fail: result, failPos: pos }\n }\n if (result.span.end === pos) {\n rollbackTrivia(ctx, mark)\n return 'stop'\n }\n return { value: result.value, end: result.span.end }\n}\n\nexport type RepeatOptions = {\n /**\n * Minimum number of ITEMS. Default `0`.\n *\n * `min >= 1` is not a validation nicety \u2014 it is what makes the combinator\n * NON-NULLABLE. A nullable arm matches at every position, which disables its\n * `choice`'s first-char dispatch by parseman's own first-set rule; a `min >= 1`\n * repeat keeps the item's first-set, so an arm led by it still gates.\n */\n min?: number\n /** Maximum number of ITEMS. Default: unbounded. Never affects nullability. */\n max?: number\n}\n\n/** Shared `min`/`max` validation \u2014 a bad bound is an authoring error, not a parse\n * outcome, so it throws at CONSTRUCTION where the stack points at the grammar. */\nfunction resolveBounds(what: string, opts: { min?: number; max?: number }): { min: number; max: number } {\n const min = opts.min ?? 0\n const max = opts.max ?? Infinity\n const bad = (msg: string): never => { throw new RangeError(`parseman: ${what} ${msg}`) }\n if (!Number.isInteger(min) || min < 0) bad(`min must be a non-negative integer (got ${String(opts.min)})`)\n if (max !== Infinity && (!Number.isInteger(max) || max < 1)) bad(`max must be a positive integer (got ${String(opts.max)})`)\n if (max < min) bad(`max (${max}) is less than min (${min}) \u2014 the combinator could never succeed`)\n return { min, max }\n}\n\n/**\n * Repetition: `item*` by default, bounded by `{ min, max }` (both count ITEMS).\n *\n * many(g.Decl) // zero or more \u2014 NULLABLE\n * many(g.Decl, { min: 1 }) // one or more \u2014 same as oneOrMore(g.Decl)\n * many(g.HexDigit, { min: 3, max: 8 })\n *\n * `oneOrMore(x)` is kept as the sugar for the common `{ min: 1 }` case.\n */\nexport function many<T>(combinator: Combinator<T>, opts: RepeatOptions = {}): Combinator<T[]> {\n const { min, max } = resolveBounds('many()', opts)\n // `min >= 1` routes to the SAME implementation `oneOrMore` has always used, so\n // `many(x, { min: 1 })` and `oneOrMore(x)` are the identical combinator \u2014 not\n // merely equivalent-looking. (They differ from the min-0 loop in one real way:\n // the mandatory items parse at `pos` with no leading-trivia skip, which is the\n // enclosing context's job.)\n if (min >= 1) return atLeast(combinator, min, max)\n const meta: ParserMeta = {\n firstSet: combinator._meta.firstSet,\n canMatchNewline: combinator._meta.canMatchNewline,\n isTrivia: false,\n }\n const def: { tag: 'many'; parser: Combinator<unknown>; min: 0; max?: number; valueUnused?: boolean } =\n { tag: 'many', parser: combinator as Combinator<unknown>, min: 0, ...(max === Infinity ? {} : { max }) }\n let expected: string[] | undefined\n // A non-nullable body can be first-set-gated per loop iteration (see repItem).\n const guardable = combinator._meta.firstSet.kind !== 'any' && !matchesEmpty(combinator)\n\n return {\n _tag: 'many',\n _meta: meta,\n _def: def,\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T[]> {\n // When the aggregate is never observed (markUnusedValues), skip the array:\n // items still parse and self-capture into the enclosing node's children.\n const values: T[] | undefined = def.valueUnused ? undefined : []\n let cur = pos\n let count = 0\n while (cur < input.length) {\n if (count >= max) break\n const item = repItem(combinator, input, cur, ctx, guardable)\n if (item === 'stop') break\n if ('fail' in item) {\n if (!item.fail.ok && item.fail.committed) return item.fail\n // Cold path: only reached on an element failure. Strict mode \u21D2 `break`.\n // Tolerant \u21D2 resync to the sync sentinel the enclosing sequence inferred\n // and published as ctx._sync (the grammar carries no recovery config). No\n // sync available \u21D2 nothing to skip to \u2192 break.\n const sync = ctx._tolerant ? ctx._sync : undefined\n if (sync === undefined) break\n // Sync token at the POST-trivia failure position \u21D2 clean list end (the\n // trailing trivia belongs to the enclosing context), not junk. Checking\n // `item.failPos` (past leading trivia), not `cur`, keeps trivia out of\n // both the break decision and the recovered error span.\n if (matchesAt(sync, input, item.failPos, ctx)) break\n expected ??= deriveExpected(combinator)\n const { error, end } = recoverScan(input, item.failPos, ctx, sync, expected)\n if (values !== undefined) values.push(error as unknown as T)\n captureError(ctx, error)\n count++\n cur = end\n continue\n }\n if (values !== undefined) values.push(item.value)\n count++\n cur = item.end\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion\n return { ok: true, value: (values ?? undefined) as T[], span: { start: pos, end: cur } }\n },\n }\n}\n\n/**\n * Sugar for the commonest bound: `many(combinator, { min: 1 })` \u2014 the identical\n * combinator, not merely an equivalent one.\n */\nexport function oneOrMore<T>(combinator: Combinator<T>, opts: RepeatOptions = {}): Combinator<T[]> {\n return many(combinator, { ...opts, min: opts.min ?? 1 })\n}\n\n/**\n * `min >= 1` repetition: `min` MANDATORY items (whose failure propagates) then a\n * greedy loop up to `max`. The tag stays `oneOrMore` \u2014 every downstream switch\n * keys on it for \"non-nullable repeat\" \u2014 and `min` carries the real count.\n */\nfunction atLeast<T>(combinator: Combinator<T>, min: number, max: number): Combinator<T[]> {\n const meta: ParserMeta = {\n firstSet: combinator._meta.firstSet,\n canMatchNewline: combinator._meta.canMatchNewline,\n isTrivia: false,\n }\n const def: { tag: 'oneOrMore'; parser: Combinator<unknown>; min: number; max?: number; valueUnused?: boolean } =\n { tag: 'oneOrMore', parser: combinator as Combinator<unknown>, min, ...(max === Infinity ? {} : { max }) }\n let expected: string[] | undefined\n // A non-nullable body can be first-set-gated per loop iteration (see repItem).\n const guardable = combinator._meta.firstSet.kind !== 'any' && !matchesEmpty(combinator)\n\n return {\n _tag: 'oneOrMore',\n _meta: meta,\n _def: def,\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T[]> {\n // First item is mandatory (parsed at pos directly \u2014 leading trivia is the\n // enclosing context's responsibility); subsequent items skip leading trivia.\n const first = combinator.parse(input, pos, ctx)\n if (!first.ok) return first\n // Aggregate skipped when never observed (see `many`).\n const values: T[] | undefined = def.valueUnused ? undefined : [first.value]\n let cur = first.span.end\n let count = 1\n // Mandatory items 2..min (only entered for min > 1) \u2014 each failure propagates,\n // exactly like the first. They go through repItem so the trivia BETWEEN items\n // is consumed the same way the loop consumes it.\n while (count < min) {\n const item = repItem(combinator, input, cur, ctx, guardable)\n if (item === 'stop' || 'fail' in item) {\n if (item !== 'stop' && !item.fail.ok && item.fail.committed) return item.fail\n // Anchored at `cur` \u2014 the furthest position the repeat reached \u2014 not at\n // its start. `many(regex(/x/), { min: 3 })` over \"xx\" consumed both x's\n // and got stuck at 2 wanting a third; reporting offset 0 points the\n // caret at input that matched. Same rule as `sepBy`'s `failAt`, and the\n // compiled emitter already anchored here \u2014 this side was the outlier.\n expected ??= deriveExpected(combinator)\n return { ok: false, expected: expected.length > 0 ? expected : [combinator._tag], span: { start: cur, end: cur } }\n }\n if (values !== undefined) values.push(item.value)\n cur = item.end\n count++\n }\n while (cur < input.length) {\n if (count >= max) break\n const item = repItem(combinator, input, cur, ctx, guardable)\n if (item === 'stop') break\n if ('fail' in item) {\n if (!item.fail.ok && item.fail.committed) return item.fail\n // Cold path (element failure). Strict: break. Tolerant: resync \u2014 see many().\n const sync = ctx._tolerant ? ctx._sync : undefined\n if (sync === undefined) break\n if (matchesAt(sync, input, item.failPos, ctx)) break\n expected ??= deriveExpected(combinator)\n const { error, end } = recoverScan(input, item.failPos, ctx, sync, expected)\n if (values !== undefined) values.push(error as unknown as T)\n captureError(ctx, error)\n count++\n cur = end\n continue\n }\n if (values !== undefined) values.push(item.value)\n count++\n cur = item.end\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion\n return { ok: true, value: (values ?? undefined) as T[], span: { start: pos, end: cur } }\n },\n }\n}\n\nexport function optional<T>(combinator: Combinator<T>): Combinator<T | null> {\n const meta: ParserMeta = {\n firstSet: combinator._meta.firstSet,\n canMatchNewline: combinator._meta.canMatchNewline,\n isTrivia: false,\n }\n const firstSetSkippable = !matchesEmpty(combinator)\n\n return {\n _tag: 'optional',\n _meta: meta,\n _def: { tag: 'optional', parser: combinator as Combinator<unknown> },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T | null> {\n if (firstSetSkippable && ctx._probe === undefined && !startsFirstSet(combinator, input, pos)) {\n return { ok: true, value: null, span: { start: pos, end: pos } }\n }\n const mark = saveTriviaMark(ctx)\n const result = combinator.parse(input, pos, ctx)\n if (result.ok) return result as ParseResult<T>\n // Inner failed \u2192 roll back any CST leaves/trivia it captured before giving up.\n rollbackTrivia(ctx, mark)\n if (result.committed) return result\n return { ok: true, value: null, span: { start: pos, end: pos } }\n },\n }\n}\n\n/**\n * Non-empty separated list \u2014 `oneOrMore`'s relationship to `many`, for separated\n * lists. `oneOrMoreSep(item, sep)` is exactly `sepBy(item, sep, { min: 1 })`.\n *\n * oneOrMoreSep(g.Selector, literal(',')) // a selector list is never empty\n *\n * REACH FOR THIS, NOT `sepBy`, for any list that cannot actually be empty \u2014\n * selector lists, value lists, media-query preludes, keyframe selectors. `sepBy`'s\n * min-0 default matches the EMPTY STRING, which makes it nullable, and a nullable\n * arm disables its `choice`'s first-char dispatch by parseman's own first-set\n * rule. This form is non-nullable and keeps the item's first-set, so an arm led by\n * it still gates.\n */\nexport function oneOrMoreSep<T, S>(combinator: Combinator<T>, separator: Combinator<S>, opts: SepByOptions = {}): Combinator<T[]> {\n return sepBy(combinator, separator, { ...opts, min: opts.min ?? 1 })\n}\n\n/** How a separator with NO item after it is treated. */\nexport type TrailingSeparator =\n /**\n * DEFAULT, and what `sepBy` has always done: the trailing separator is NOT\n * consumed \u2014 the list ends before it and the enclosing grammar sees it. (It is\n * not an error here; \"forbid\" means the list refuses to own it.)\n */\n | 'forbid'\n /** Consume a trailing separator when present (`a, b,` \u2192 2 items, comma eaten). */\n | 'allow'\n\nexport type SepByOptions = RepeatOptions & {\n /** What to do with a separator that has no item after it. Default `'forbid'`. */\n trailing?: TrailingSeparator\n}\n\n/**\n * Separated list: `(item (sep item)*)?` by default \u2014 note that it MATCHES THE\n * EMPTY STRING, which makes it nullable and therefore un-gateable as a choice arm.\n * For a list that cannot be empty reach for `oneOrMoreSep`, or pass `{ min: 1 }`.\n *\n * sepBy(g.Value, literal(',')) // may be empty \u2014 NULLABLE\n * oneOrMoreSep(g.Selector, literal(',')) // non-empty \u2014 gates as a choice arm\n * sepBy(g.Decl, literal(';'), { trailing: 'allow' })\n *\n * `min`/`max` count ITEMS, not separators.\n */\nexport function sepBy<T, S>(combinator: Combinator<T>, separator: Combinator<S>, opts: SepByOptions = {}): Combinator<T[]> {\n const { min, max } = resolveBounds('sepBy()', opts)\n const trailing = opts.trailing ?? 'forbid'\n const meta: ParserMeta = {\n firstSet: combinator._meta.firstSet,\n canMatchNewline: combinator._meta.canMatchNewline || separator._meta.canMatchNewline,\n isTrivia: false,\n }\n let expected: string[] | undefined\n /**\n * A list-level failure is anchored at the FURTHEST position the list reached,\n * and reports what would have allowed it to CONTINUE there \u2014 never at the\n * list's own start.\n *\n * Anchoring at the start throws away everything the parse learned: for\n * `sepBy(item, ',', { min: 3 })` over `\"a,b\"` the list consumed `a,b` perfectly\n * and got stuck at offset 3 wanting a third item, so a failure reported at 0\n * points the caret at a token that parsed fine. It also mislocates\n * `completionsAt`, which asks what may appear AT a cursor \u2014 the answer belongs\n * at the stuck position, not at the list's start.\n *\n * BOTH engines must follow this rule; it drifted three separate ways across\n * this option surface, and `test/parity/repeat-options-parity.test.ts` is what\n * now holds them together. The empty-set fallback mirrors codegen's\n * `deriveExpectedArr`, so the two payloads are identical.\n */\n const failAt = (at: number): ParseResult<T[]> => {\n expected ??= deriveExpected(combinator)\n return { ok: false, expected: expected.length > 0 ? expected : [combinator._tag], span: { start: at, end: at } }\n }\n\n return {\n _tag: 'sepBy',\n _meta: meta,\n _def: {\n tag: 'sepBy', parser: combinator as Combinator<unknown>, separator: separator as Combinator<unknown>, min,\n ...(max === Infinity ? {} : { max }),\n ...(trailing === 'forbid' ? {} : { trailing }),\n },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T[]> {\n const first = combinator.parse(input, pos, ctx)\n const values: T[] = []\n let cur: number\n if (first.ok) {\n values.push(first.value)\n cur = first.span.end\n } else {\n if (first.committed) return first\n // Cold path. Strict: an empty/absent first element is a legal empty list\n // for `sepBy`, and a FAILURE for `sepBy1` (min 1 \u2014 that is the whole point).\n // Tolerant: if the first element is JUNK (a terminator is inferable and we\n // are not already sitting on it) recover it and enter the loop; otherwise\n // it is a genuine empty list.\n const term = ctx._tolerant ? ctx._sync : undefined\n if (term === undefined || matchesAt(term, input, pos, ctx)) {\n // `min >= 1` \u2014 nothing was consumed, so the furthest position IS `pos`.\n // The compiled form swallows the first element's sub-parse (it is\n // discarded on the min-0 path), so it cannot reproduce the inner\n // failure's exact payload; both sides report this same derived set.\n if (min >= 1) return failAt(pos)\n return { ok: true, value: [], span: { start: pos, end: pos } }\n }\n expected ??= deriveExpected(combinator)\n const rec = recoverScan(input, pos, ctx, orSentinel(separator, term), expected)\n values.push(rec.error as unknown as T)\n captureError(ctx, rec.error)\n cur = rec.end\n }\n while (cur < input.length) {\n if (values.length >= max) break\n // One mark for the whole iteration (separator + following item): if the\n // item fails, the trailing separator must be rolled back with it, or its\n // captured leaves leak past the end of the list.\n const loopMark = saveTriviaMark(ctx)\n let sepPos = cur\n if (ctx.trivia) {\n if (needsDeferredTriviaCommit(ctx)) {\n const scan = scanTrivia(input, cur, ctx)\n scan.commit()\n sepPos = scan.end\n } else {\n sepPos = advanceTrivia(input, cur, ctx)\n }\n }\n const sep = separator.parse(input, sepPos, ctx)\n if (!sep.ok) {\n rollbackTrivia(ctx, loopMark)\n if (sep.committed) return sep\n break\n }\n // Mark taken AFTER the separator: `trailing` keeps the separator but must\n // still unwind the trivia + leaves captured past it.\n const sepMark = trailing === 'forbid' ? undefined : saveTriviaMark(ctx)\n let nextPos = sep.span.end\n if (ctx.trivia) {\n if (needsDeferredTriviaCommit(ctx)) {\n const scan = scanTrivia(input, sep.span.end, ctx)\n scan.commit()\n nextPos = scan.end\n } else {\n nextPos = advanceTrivia(input, sep.span.end, ctx)\n }\n }\n const next = combinator.parse(input, nextPos, ctx)\n if (!next.ok) {\n if (next.committed) return next\n // Cold path. Strict: roll back the trailing separator + break. Tolerant:\n // the separator we just consumed is real, so resync the bad element after\n // it. If a terminator is inferable and already present at nextPos, the\n // separator was a trailing one (e.g. `a;}`) \u2192 roll it back and stop.\n //\n // RECOVERY IS TESTED FIRST, and is ORTHOGONAL to `trailing`. This block\n // used to lead with the `sepMark !== undefined` branch \u2014 but sepMark is\n // non-undefined for EVERY 'allow' list, so that branch always won and the\n // resync below became unreachable the moment a grammar opted into a\n // trailing separator. `{a,,b}` recovered under the default 'forbid' and\n // hard-failed under 'allow', which is not a policy anyone would choose:\n // permitting a trailing comma has nothing to do with whether a tolerant\n // parse may resynchronize. (The compiled `failItem` already ordered it\n // this way \u2014 the engines disagreed because of this.)\n //\n // Junk after a REAL separator is recovered whatever `trailing` says, and\n // no rollback happens on that path: both the separator and the recovered\n // error element belong to the list.\n const term = ctx._tolerant ? ctx._sync : undefined\n if (term !== undefined && !matchesAt(term, input, nextPos, ctx)) {\n expected ??= deriveExpected(combinator)\n const rec = recoverScan(input, nextPos, ctx, orSentinel(separator, term), expected)\n values.push(rec.error as unknown as T)\n captureError(ctx, rec.error)\n cur = rec.end\n continue\n }\n if (sepMark !== undefined) {\n // 'allow': the separator we just consumed IS part of the list \u2014 a\n // genuine trailing one, since no resync applied above.\n rollbackTrivia(ctx, sepMark)\n cur = sep.span.end\n break\n }\n rollbackTrivia(ctx, loopMark)\n break\n }\n values.push(next.value)\n cur = next.span.end\n }\n // Too few items: the list is stuck at `cur` wanting another ITEM.\n if (values.length < min) return failAt(cur)\n return { ok: true, value: values, span: { start: pos, end: cur } }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult } from '../types.ts'\nimport { analyzeLabeledTrivia } from '../cst/trivia-kinds.ts'\nimport { choice } from './choice.ts'\nimport { matchesEmpty } from './first-set.ts'\nimport { oneOrMore } from './repeat.ts'\n\nexport function transform<T, U>(\n combinator: Combinator<T>,\n fn: (value: T, span: { start: number; end: number }) => U\n): Combinator<U> {\n return {\n _tag: 'transform',\n _meta: combinator._meta,\n _def: { tag: 'transform', parser: combinator as Combinator<unknown>, fn: fn as (v: unknown, span: { start: number; end: number }) => unknown },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<U> {\n const result = combinator.parse(input, pos, ctx)\n if (!result.ok) return result\n return { ok: true, value: fn(result.value, result.span), span: result.span }\n },\n }\n}\n\nexport function skip<T, S>(main: Combinator<T>, skipped: Combinator<S>): Combinator<T> {\n return {\n _tag: 'skip',\n _meta: main._meta,\n _def: { tag: 'skip', main: main as Combinator<unknown>, skipped: skipped as Combinator<unknown> },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T> {\n const result = main.parse(input, pos, ctx)\n if (!result.ok) return result\n const s = skipped.parse(input, result.span.end, ctx)\n if (!s.ok) return result\n return { ok: true, value: result.value, span: { start: result.span.start, end: s.span.end } }\n },\n }\n}\n\nexport function trivia<T>(combinator: Combinator<T>): Combinator<T> {\n const kindLabels = analyzeLabeledTrivia(combinator as Combinator<unknown>)?.labels\n return {\n _tag: combinator._tag,\n _meta: {\n ...combinator._meta,\n isTrivia: true,\n ...(kindLabels ? { triviaKindLabels: kindLabels } : {}),\n },\n _def: { tag: 'trivia', parser: combinator as Combinator<unknown> },\n parse: combinator.parse.bind(combinator),\n }\n}\n\n/**\n * Build trivia whose category labels are part of its recognition structure.\n *\n * Use this for a grammar that exposes selected root trivia. In contrast to\n * `trivia(label('categoryA', broadRegex))`, every category here owns one arm,\n * so one selected category cannot be silently consumed under another category's\n * broad matcher.\n * `rootTrivia: { select }` rejects ordinary scoped trivia\n * unless that scope explicitly declares itself opaque.\n */\nexport function classifiedTrivia(\n arms: Readonly<Record<string, Combinator<unknown>>>,\n): Combinator<unknown> {\n const entries = Object.entries(arms)\n if (entries.length === 0) {\n throw new TypeError('classifiedTrivia() requires at least one named trivia arm.')\n }\n for (let i = 0; i < entries.length; i++) {\n const [name, arm] = entries[i]!\n const first = arm._meta.firstSet\n if (matchesEmpty(arm) || first.kind !== 'ranges' || first.ranges.length === 0) {\n throw new TypeError(\n `classifiedTrivia(): ${JSON.stringify(name)} must be non-nullable with a concrete finite first set.`,\n )\n }\n }\n const labeledArms = entries.map(([name, arm]) => label(name, arm)) as [\n Combinator<unknown>,\n ...Combinator<unknown>[],\n ]\n const result = trivia(oneOrMore(choice(...labeledArms)))\n result._meta.rootTriviaClassified = true\n return result\n}\n\n/**\n * Attach a string label to a parser arm (e.g. trivia `choice` branches).\n * Parse behavior is unchanged; the label is metadata for tooling and future\n * trivia-kind capture (`'whitespace'`, `'blockComment'`, \u2026).\n */\nexport function label<T>(name: string, combinator: Combinator<T>): Combinator<T> {\n return {\n _tag: combinator._tag,\n _meta: combinator._meta,\n _def: { tag: 'label', label: name, parser: combinator as Combinator<unknown> },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T> {\n const result = combinator.parse(input, pos, ctx)\n if (!result.ok) return { ok: false, expected: [name], span: result.span }\n return result\n },\n }\n}\n\n/**\n * Capture a named parse result for the nearest enclosing node() builder.\n * Parse behavior and the normal returned value are unchanged.\n */\nexport function field<T>(name: string, combinator: Combinator<T>): Combinator<T> {\n return {\n _tag: combinator._tag,\n _meta: combinator._meta,\n _def: { tag: 'field', name, parser: combinator as Combinator<unknown> },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T> {\n const result = combinator.parse(input, pos, ctx)\n if (!result.ok) return result\n ctx._fields?.push({ name, value: result.value, span: result.span })\n return result\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { literal } from './literal.ts'\nimport { regex } from './regex.ts'\nimport { sequence } from './sequence.ts'\nimport { choice } from './choice.ts'\nimport { many } from './repeat.ts'\nimport { transform } from './map.ts'\nimport { expect } from './expect.ts'\nimport { any } from './first-set.ts'\nimport { ref } from './ref.ts'\nimport { pushCstLeaf, cstCaptureActive } from '../cst/capture-buffer.ts'\nimport { recordLineRangeFromContext } from '../line-index.ts'\n\nexport type ScanToOptions = {\n /**\n * Per-call opaque-unit skippers (balanced parens/brackets, dialect\n * interpolation, \u2026). These EXTEND the grammar-level ambient default: ambient\n * trivia (comments/ws) and ambient `scanSkip` (strings) are applied too, unless\n * `raw`. So a site only needs to list the extra units its scan requires.\n */\n skip?: Combinator<unknown>[]\n /**\n * Hard opt-out: skip NOTHING ambiently \u2014 no trivia, no scanSkip, and (with no\n * per-call `skip`) a pure raw byte-walk. For the rare site that intends to scan\n * literally through comments/strings.\n */\n raw?: boolean\n /**\n * If true, reaching EOF without finding the sentinel is a success \u2014 returns\n * everything consumed so far. Default false (fail at EOF).\n */\n orEOF?: boolean\n}\n\n/**\n * Resolve the effective ordered skipper list for a scan, folding grammar-level\n * ambient trivia + scanSkip in FRONT of the per-call `skip` (explicit skip\n * EXTENDS the ambient default). Shared by the interpreter `scanTo`/`balanced`;\n * the compiled path bakes the identical list in codegen.\n *\n * raw \u2192 [] (no trivia, no scanSkip, no skip)\n * else \u2192 [ ...trivia?, ...scanSkip?, ...skip ]\n *\n * The ambient trivia (comments/ws) leads so a sentinel hidden in a comment is\n * never matched, then ambient strings, then the site's extra units. The sentinel\n * itself is still checked before any skipper, so a sentinel that also starts a\n * skip region wins (unchanged priority).\n */\nexport function resolveScanSkip(\n explicitSkip: Combinator<unknown>[],\n raw: boolean,\n ctx: ParseContext,\n): Combinator<unknown>[] {\n if (raw) return []\n const trivia = ctx.trivia\n const ambient = ctx.scanSkip\n if (!trivia && !ambient) return explicitSkip\n const out: Combinator<unknown>[] = []\n if (trivia) out.push(trivia)\n if (ambient) out.push(...ambient)\n out.push(...explicitSkip)\n return out\n}\n\n/**\n * Consume input up to (but not including) the sentinel, skipping over any\n * \"hole\" patterns in order so their contents are never mistaken for the sentinel.\n *\n * Returns the consumed text as a string. The sentinel is NOT consumed.\n * Fails if the sentinel is never found (unless orEOF is true).\n *\n * const selector = scanTo(literal('{'), {\n * skip: [cssComment, stringLit, balanced('(', ')'), balanced('[', ']')],\n * })\n */\nexport function scanTo(\n sentinel: Combinator<unknown>,\n { skip, raw = false, orEOF = false }: ScanToOptions = {},\n): Combinator<string> {\n const meta: ParserMeta = {\n firstSet: any(),\n canMatchNewline: true,\n isTrivia: false,\n }\n const explicitSkip = skip ?? []\n\n return {\n _tag: 'scanTo',\n _meta: meta,\n _def: { tag: 'scanTo', sentinel, skip: explicitSkip, raw, orEOF },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<string> {\n let cur = pos\n // Fold grammar-level ambient trivia + scanSkip into the effective skippers.\n const skip = resolveScanSkip(explicitSkip, raw, ctx)\n\n // Sentinel checks and skip scans must not emit CST children of their own \u2014\n // scanTo represents the whole scanned span as one leaf. Probe them with a\n // collector-free context so their internal literal()/regex() don't push.\n // The error channel IS forwarded, so a committed skipper (e.g. balanced()\n // whose open delimiter was consumed) can still report an unmatched close.\n const probeCtx: ParseContext = {\n trackLines: false,\n state: ctx.state,\n ...(ctx._errors !== undefined ? { _errors: ctx._errors } : {}),\n }\n\n // Record the scanned text as a CSTLeaf so buildNode-driven grammars can\n // see it in children/rawChildren (it would otherwise be lost \u2014 only the\n // returned value carries it). Skipped when no collector is active.\n const emit = (end: number) => {\n if (end > pos && cstCaptureActive(ctx)) {\n const leaf = { _tag: 'leaf', value: input.slice(pos, end), span: { start: pos, end } }\n pushCstLeaf(ctx, leaf)\n }\n }\n\n while (cur < input.length) {\n // Check sentinel \u2014 if it matches here, stop and return consumed text.\n const s = sentinel.parse(input, cur, probeCtx)\n if (s.ok) {\n if (ctx.trackLines) recordLineRangeFromContext(ctx, input, pos, cur)\n emit(cur)\n return { ok: true, value: input.slice(pos, cur), span: { start: pos, end: cur } }\n }\n\n // Try each skipper in order; take first that advances.\n let advanced = false\n for (const skipper of skip) {\n const r = skipper.parse(input, cur, probeCtx)\n if (r.ok && r.span.end > cur) {\n cur = r.span.end\n advanced = true\n break\n }\n }\n\n // Nothing matched \u2014 consume one character and continue.\n if (!advanced) cur++\n }\n\n // Reached EOF without finding sentinel.\n if (orEOF) {\n if (ctx.trackLines) recordLineRangeFromContext(ctx, input, pos, cur)\n emit(cur)\n return { ok: true, value: input.slice(pos, cur), span: { start: pos, end: cur } }\n }\n const sentDef = sentinel._def\n const expected = sentDef.tag === 'literal' ? [JSON.stringify(sentDef.value)] : ['sentinel']\n return { ok: false, expected, span: { start: pos, end: cur } }\n },\n }\n}\n\n/** Codegen marker: a balanced combinator that must re-resolve ambient scanSkip\n * into its interior at emit time (the compiled mirror of the interpreter wrapper). */\nexport type BalancedAmbient = Combinator<string> & {\n _balancedAmbient?: { open: string; close: string; ownSkip: Combinator<unknown>[] }\n}\n\n/**\n * Match a balanced open/close pair, skipping over any holes inside.\n * Returns the full matched text including delimiters.\n *\n * const parenGroup = balanced('(', ')', { skip: [comment, stringLit] })\n *\n * With no per-call `skip`, a balanced under a grammar that declares\n * `rules({ scanSkip })` consults that ambient opaque-unit set in its INTERIOR too,\n * so a delimiter hidden inside a string/bracket run never closes the balance\n * early \u2014 the same footgun closure `scanTo` gets. `raw: true` opts out.\n */\nexport function balanced(\n open: string,\n close: string,\n options: ScanToOptions = {},\n): Combinator<string> {\n const ownSkip = options.skip ?? []\n const combi = buildBalancedInterior(open, close, ownSkip)\n // `raw` keeps the pre-ambient behavior: the eager interior (per-call skip only).\n if (options.raw) return combi\n\n // Ambient-aware in place \u2014 the returned combinator KEEPS its identity (its own\n // interior `self` ref points back to it, and ir-serialize / codegen dedup rely\n // on that), so we override `parse` rather than wrapping. `_def`/`_meta` are\n // unchanged, so every static analysis sees the eager interior; only PARSING and\n // codegen EMIT re-resolve `ctx.scanSkip`. Interiors are cached by the ambient\n // array's identity (stable per grammar). Balanced consults ambient `scanSkip`\n // (opaque units) but NOT trivia \u2014 its delimiters are structural and its content\n // regex already spans whitespace, so adding trivia would perturb every existing\n // balanced; the footgun is a delimiter hidden in opaque-unit content.\n const eagerParse = combi.parse.bind(combi)\n const cache = new Map<readonly Combinator<unknown>[], Combinator<string>>()\n ;(combi as BalancedAmbient)._balancedAmbient = { open, close, ownSkip }\n combi.parse = (input: string, pos: number, ctx: ParseContext): ParseResult<string> => {\n const amb = ctx.scanSkip\n if (!amb || amb.length === 0) return eagerParse(input, pos, ctx)\n let interior = cache.get(amb)\n if (!interior) {\n interior = buildBalancedInterior(open, close, [...amb, ...ownSkip])\n cache.set(amb, interior)\n }\n return interior.parse(input, pos, ctx)\n }\n return combi\n}\n\n/** Build a balanced open/close interior for a FIXED skip set (no ambient). */\nexport function buildBalancedInterior(\n open: string,\n close: string,\n skips: Combinator<unknown>[],\n): Combinator<string> {\n // The interior scan must skip NESTED same-delimiter pairs so depth is counted \u2014\n // otherwise `{{x}}` stops at the first `}`. `self` references this balanced\n // combinator; added to the interior scan's skip list, a nested `open` is\n // consumed intact (recursively) before the scan looks for the matching `close`.\n const self = ref<string>()\n // PREDICTIVE interior \u2014 no char-walk. The body is `many(choice(self, \u2026skips,\n // contentRun))`, where contentRun is a regex of chars that are NOT this pair's\n // delimiters and NOT the start of any skip (so a string/comment arm still wins\n // its position). At any other character \u2014 a stray close, or a *different* bracket\n // type \u2014 no arm matches, `many` stops, and the required close (expect()) reports\n // \"expected <close>\". So an unmatched open, a cross-type close `(a]`, and a stray\n // close all surface as errors; nothing is silently swallowed. Well-formed input\n // is consumed identically.\n const stop = new Set<string>([open, close])\n let bounded = true\n for (const sk of skips) {\n const cs = firstSetClassChars(sk)\n if (cs === null) { bounded = false; break }\n for (const ch of cs) stop.add(ch)\n }\n const cls = [...stop].map(escapeClassChar).join('')\n // A run when every skip's start is bounded (fast); else one char at a time so a\n // skip arm always gets the chance to match at its position.\n const content = bounded\n ? regex(new RegExp(`[^${cls}]+`))\n : regex(new RegExp(`[^${escapeClassChar(open)}${escapeClassChar(close)}]`))\n const inner = many(choice(self, ...skips, content))\n const combi = transform(\n sequence(literal(open), inner, expect(literal(close))),\n // parts: strings (content/self) or arrays (a sequence-shaped skip) or a\n // ParseError (recovered close). `c` is the close string or a ParseError.\n ([o, parts, c]) => o + (parts as unknown[]).map(p => typeof p === 'string' ? p : Array.isArray(p) ? p.join('') : '').join('') + (typeof c === 'string' ? c : ''),\n )\n // Provide the callback source so the macro can inline this library-internal\n // transform (codegen derives map-fn sources from def.fnSrc).\n if (combi._def.tag === 'transform') {\n combi._def.fnSrc = '([o, parts, c]) => o + parts.map(p => typeof p === \"string\" ? p : Array.isArray(p) ? p.join(\"\") : \"\").join(\"\") + (typeof c === \"string\" ? c : \"\")'\n // This is Parseman's structural delimiter reconstruction, not a grammar\n // semantic reduction. It must remain eligible for recognition-only\n // composeLeaf artifacts while user-authored transform() remains excluded.\n combi._def.recognitionOnly = true\n }\n self.define(combi as Combinator<string>)\n return combi\n}\n\n/**\n * The characters a combinator can START with, as char-class members \u2014 or null if\n * its first set is unbounded ('any') or too broad to be a delimiter. Used by\n * balanced() to keep a content run from eating the start of a skip.\n */\nfunction firstSetClassChars(c: Combinator<unknown>): string[] | null {\n const fs = c._meta.firstSet\n if (fs.kind === 'empty') return []\n if (fs.kind !== 'ranges') return null\n const out: string[] = []\n for (const { lo, hi } of fs.ranges) {\n if (hi - lo > 8) return null\n for (let cp = lo; cp <= hi; cp++) out.push(String.fromCodePoint(cp))\n }\n return out\n}\n\nfunction escapeClassChar(ch: string): string {\n return ch.replace(/[\\\\\\]^-]/g, '\\\\$&')\n}\n", "/**\n * Degradation diagnostics \u2014 \"parseman could not do the fast/complete thing here\".\n *\n * A fallback that is CORRECT but slower (or less complete) and announces nothing is\n * indistinguishable from working properly. Every such path in the compiler and the\n * analysis APIs reports through this one channel so a consumer's build gate can\n * assert ZERO degradations, exactly the way jess's `check:macro` already asserts zero\n * `\"falling back to runtime\"` lines.\n *\n * Machine-greppable contract (stable across minor versions):\n *\n * [parseman] degraded [<code>] <where>: <subject> \u2014 <fell back to>; otherwise <what>\n *\n * Grep token is the literal `[parseman] degraded`. The `<code>` is a stable kebab-case\n * identifier; new codes may be added, existing ones are not renamed without a note in\n * CHANGELOG.md.\n *\n * NOT for: user errors (those throw), un-taken optimizations that cost nothing, or\n * anything a grammar author cannot act on. A diagnostic that fires on every rule gets\n * filtered out and becomes the same silence we are trying to end \u2014 so a code that is\n * common and unavoidable AGGREGATES (see `DETAIL_CAP`) into one summary line with a\n * count instead of one line per rule.\n */\n\n/** Off / print / throw. */\nexport type DegradationLevel = 'off' | 'warn' | 'error'\n\n/** Stable, greppable code per degradation class. */\nexport type DegradationCode =\n /** A node build's formal parameter list could not be read \u2192 all capture tiers kept. */\n | 'build-arity-unconfirmed'\n /** A node build looks like an `mk(...)` wrapper but did not match \u2192 no inline-mk. */\n | 'mk-inline-missed'\n /** A composed/carried piece is an opaque artifact \u2192 its rules were not analysed. */\n | 'opaque-artifact'\n /** A coverage-definition request could not read the grammar \u2192 empty is NOT a zero. */\n | 'coverage-definitions-unavailable'\n\n/**\n * Severity. `warn` = a real, measurable cost the author can remove. `info` = the author\n * has nothing to act on (e.g. an imported reducer in someone else's package), but the\n * fact still has to be visible and countable.\n */\nexport type DegradationSeverity = 'warn' | 'info'\n\nexport type Degradation = {\n code: DegradationCode\n severity: DegradationSeverity\n /** Rule / node type / artifact the cost lands on. Never a bare \"<unknown>\" if avoidable. */\n where: string\n /** The reducer, identifier, or input that could not be analysed. */\n subject: string\n /** What parseman did instead. */\n fellBackTo: string\n /** What it would have done had the input been analysable. */\n otherwise: string\n}\n\n/** One line per finding, in the documented greppable shape. */\nexport function formatDegradation(d: Degradation): string {\n return `[parseman] degraded [${d.code}] ${d.where}: ${d.subject} \u2014 ${d.fellBackTo}; otherwise ${d.otherwise}`\n}\n\n/**\n * Per-code detail cap. Above it the remaining sites collapse to one counted summary\n * line. Chosen small on purpose: the point of a detail line is to give an author a\n * concrete place to start, and eight starting points is already more than anyone acts\n * on in one pass. The COUNT is what makes the rest visible.\n */\nconst DETAIL_CAP = 8\n\n/** Group by code, cap the detail lines, and append a counted summary for the rest. */\nexport function formatDegradations(list: readonly Degradation[]): string[] {\n const byCode = new Map<DegradationCode, Degradation[]>()\n for (const d of list) {\n const bucket = byCode.get(d.code)\n if (bucket) bucket.push(d)\n else byCode.set(d.code, [d])\n }\n const out: string[] = []\n for (const [code, items] of byCode) {\n for (const d of items.slice(0, DETAIL_CAP)) out.push(formatDegradation(d))\n if (items.length > DETAIL_CAP) {\n out.push(\n `[parseman] degraded [${code}] +${items.length - DETAIL_CAP} more site(s) not listed `\n + `(${items.length} total). Set PARSEMAN_DEGRADATION=error to fail the build on these.`,\n )\n }\n }\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Capture sink\n//\n// Compilation is single-module and synchronous, so a module-level sink (opened per\n// transform, drained after) records findings without threading a field through every\n// Ctx and every compile*() return \u2014 the same shape as the regex-lowering sink in\n// codegen.ts, for the same reason.\n// ---------------------------------------------------------------------------\n//\n// A STACK, not a single slot. `transformMacro` re-enters itself when it lowers a private\n// source module, so a single slot let the inner call's `endDegradationCapture()` close\n// the OUTER module's sink \u2014 every later finding in the outer pass then bypassed capture\n// and printed instead. A stack scopes each frame to its own module.\n// ---------------------------------------------------------------------------\nconst _sinks: Array<Map<string, Degradation>> = []\n\n/** Begin collecting degradations instead of printing them. */\nexport function beginDegradationCapture(): void {\n _sinks.push(new Map())\n}\n\n/** Stop collecting and return the findings (deduped, insertion-ordered). */\nexport function endDegradationCapture(): Degradation[] {\n const sink = _sinks.pop()\n return sink ? [...sink.values()] : []\n}\n\n/** Open-sink depth, for a caller that must unwind exactly its own frames. */\nexport function degradationCaptureDepth(): number {\n return _sinks.length\n}\n\n/**\n * Close every sink opened above `depth` and return their findings, outermost first.\n *\n * The safety net for an ABORTED capture. `beginDegradationCapture()` and its matching\n * `end` used to sit on the straight-line path of a function that throws between them, so\n * one failed macro transform left the sink open for the REST OF THE PROCESS: every later\n * `recordDegradation` \u2014 including from an unrelated runtime `compile()` \u2014 went into a\n * dead Map and printed nothing. Calling this from a `finally` bounds the damage to the\n * frame that failed, and returns what it had collected so it can still be reported\n * rather than silently dropped.\n */\nexport function unwindDegradationCapture(depth: number): Degradation[] {\n const found: Degradation[] = []\n while (_sinks.length > depth) {\n const sink = _sinks.pop()!\n found.unshift(...sink.values())\n }\n return found\n}\n\n/**\n * Resolve the level: explicit argument wins, else `PARSEMAN_DEGRADATION`, else\n * default-on `'warn'`. Default-on is the whole point \u2014 this exists because the\n * default was silence.\n */\nexport function resolveDegradationLevel(explicit?: DegradationLevel): DegradationLevel {\n if (explicit !== undefined) return explicit\n const env = typeof process !== 'undefined' ? (process.env?.PARSEMAN_DEGRADATION as DegradationLevel | undefined) : undefined\n if (env === 'off' || env === 'warn' || env === 'error') return env\n return 'warn'\n}\n\n/**\n * The dedup key for one finding.\n *\n * `JSON.stringify` of the tuple, NOT a delimiter-joined string. Two of the three\n * components are unbounded author text \u2014 `where` embeds a node type and `subject` is a\n * verbatim slice of reducer SOURCE \u2014 so no single delimiter character can be shown absent\n * from them, and picking a rarer one is the same bug one notch weaker. A JSON array is\n * injective by construction and needs no such argument.\n *\n * It is also PRINTABLE, which is the property this file lost twice. The key was built\n * with RAW 0x00 bytes in a template literal, which makes the whole source file BINARY:\n * `git diff --numstat` reported `- -` for it, GitHub refused to render it, and `grep -rn`\n * skipped it SILENTLY \u2014 no \"binary file matches\", no output, exit 0. The largest new file\n * in the release was invisible to ordinary review. Commit `ed81612` had already removed\n * exactly this pattern from `gating.ts` and `duplication.ts`; it came straight back here.\n * `scripts/check-control-bytes.mjs` now fails CI on it, because a fix without a gate got\n * us a second occurrence and would get us a third.\n *\n * This runs only when a degradation is actually recorded \u2014 never per match \u2014 so the\n * encoding cost is irrelevant.\n */\nfunction degradationKey(d: Degradation): string {\n return JSON.stringify([d.code, d.where, d.subject])\n}\n\n/**\n * Record one degradation. Deduped on `code + where + subject`, so the four capture-tier\n * probes that all consult the same unreadable parameter list produce ONE finding, not\n * four.\n *\n * With a sink open (a macro transform) the finding is collected and the drain site\n * decides what to do with it. With NO sink open \u2014 a runtime `compile()` \u2014 this is the\n * only place that ever sees the finding, so it is also the only place that can honour\n * `'error'`. It therefore throws here. `docs/guide/degradation-diagnostics.md` documents\n * `PARSEMAN_DEGRADATION=error` as \"fail the build\" without qualification, and until this\n * throw existed that was false in library mode: `error` silently behaved as `warn`,\n * because `endDegradationCapture()` had exactly one call site, in the macro plugin.\n */\nexport function recordDegradation(d: Degradation): void {\n const level = resolveDegradationLevel()\n if (level === 'off') return\n const key = degradationKey(d)\n const sink = _sinks[_sinks.length - 1]\n if (sink) {\n if (!sink.has(key)) sink.set(key, d)\n return\n }\n if (_immediate.has(key)) return\n _immediate.add(key)\n if (level === 'error') throw new Error(`parseman: degraded compilation path\\n${formatDegradation(d)}`)\n console.warn(formatDegradation(d))\n}\n\n/** Dedup memo for the sink-less (runtime `compile()`) path. */\nconst _immediate = new Set<string>()\n\n/**\n * Open a per-`compile()` drain and return the function that closes it.\n *\n * This channel stays LOUD. `compile()` no longer prints gating advice \u2014 that is a\n * deliberate diagnostic now (`diagnoseGrammar`) \u2014 but a degradation is not advice: it\n * is parseman reporting that it could not do the thing the caller asked for, and this\n * release exists to stop that happening silently. What changes here is only the SHAPE.\n *\n * Before, the sink-less path printed one ~500-character line per site as it went, with\n * no aggregation \u2014 31 of them for a single code in one `pnpm perf:workloads` run, each\n * repeating the same advice. The macro drain has always aggregated (`formatDegradations`,\n * `DETAIL_CAP`); the runtime path simply had no drain to aggregate at. It has one now,\n * so both paths report the same way and a real count survives instead of a wall.\n *\n * Nested inside a macro transform this is a NO-OP: that transform's sink owns the whole\n * module's findings and returns them on the bundler's warning channel. A per-compile\n * drain underneath it would steal them and print them instead.\n *\n * @returns `drain(report)` \u2014 always unwinds the sink (so a `compile()` that throws\n * cannot leave it open for the rest of the process), and reports only when\n * `report` is true, so a failed compile does not mask its own error with a second one.\n */\nexport function beginCompileDegradationDrain(): (report: boolean) => void {\n if (resolveDegradationLevel() === 'off' || _sinks.length > 0) return () => {}\n const depth = degradationCaptureDepth()\n beginDegradationCapture()\n return (report: boolean) => {\n const found = unwindDegradationCapture(depth)\n if (!report || found.length === 0) return\n // Process-level dedup, preserved from the immediate path: compiling the same grammar\n // twice must not re-print what the author has already been told once.\n const fresh = found.filter(d => {\n const k = degradationKey(d)\n if (_immediate.has(k)) return false\n _immediate.add(k)\n return true\n })\n if (fresh.length === 0) return\n const lines = formatDegradations(fresh)\n if (resolveDegradationLevel() === 'error') {\n throw new Error(`parseman: ${fresh.length} degraded compilation path(s)\\n${lines.join('\\n')}`)\n }\n for (const l of lines) console.warn(l)\n }\n}\n\n/** Test-only: forget the sink-less dedup memo. */\nexport function resetDegradationMemo(): void {\n _immediate.clear()\n}\n\n/** Test-only: is a sink open? Guards against a leaked capture between test files. */\nexport function hasOpenDegradationSink(): boolean {\n return _sinks.length > 0\n}\n\n", "/** View over a flat trivia log (`_triviaLog` or per-node `triviaLog`). */\nexport type TriviaEntriesView = {\n readonly length: number\n readonly labels: readonly string[] | undefined\n readonly stride: number\n start(i: number): number\n end(i: number): number\n /** Raw-child insertion boundary; defined only for a per-node trivia log. */\n insertIndex(i: number): number | undefined\n kindIndex(i: number): number | undefined\n kind(i: number): string | undefined\n text(i: number, input: string): string\n}\n\nexport type RootTriviaGap = {\n /** Start offset of the contiguous trivia gap. */\n readonly start: number\n /** End offset of the contiguous trivia gap. */\n readonly end: number\n /** Entry indices into `entries` that make up this gap. */\n readonly entryIndices: readonly number[]\n /** True when any entry in the gap has the requested labeled trivia kind. */\n hasKind(kind: string): boolean\n /** Slice the full contiguous gap text from the original input. */\n text(input: string): string\n}\n\nexport type RootTriviaIndex = {\n /** Lazy entry-level view over sparse selected-root rows. */\n readonly entries: TriviaEntriesView\n /** Selected-root label table; entry kind indices refer to this array. */\n readonly labels: readonly string[]\n /**\n * Contiguous trivia gaps keyed by the following content offset. Values are\n * entry indices into `entries`, not materialized `{ value, span }` objects.\n */\n readonly before: ReadonlyMap<number, readonly number[]>\n /**\n * Contiguous trivia gaps keyed by the preceding content offset. Values are\n * entry indices into `entries`, not materialized `{ value, span }` objects.\n */\n readonly after: ReadonlyMap<number, readonly number[]>\n entryIndicesBefore(offset: number): readonly number[]\n entryIndicesAfter(offset: number): readonly number[]\n /**\n * Contiguous trivia gap immediately before `offset`, keyed by the following\n * content offset. Returns undefined when no gap sits at that boundary.\n */\n gapBefore(offset: number): RootTriviaGap | undefined\n /**\n * Contiguous trivia gap immediately after `offset`, keyed by the preceding\n * content offset. Returns undefined when no gap sits at that boundary.\n */\n gapAfter(offset: number): RootTriviaGap | undefined\n /** All contiguous trivia gaps in source order. */\n gaps(): readonly RootTriviaGap[]\n /** Source-ordered gaps containing at least one entry with the given label. */\n gapsWithKind(kind: string | readonly string[]): readonly RootTriviaGap[]\n}\n\nconst EMPTY_INDICES: readonly number[] = Object.freeze([])\nconst EMPTY_GAPS: readonly RootTriviaGap[] = Object.freeze([])\n/** Number of packed fields in one selected-root trivia row. */\nexport const SELECTED_ROOT_STRIDE = 5\n\ntype RootTriviaMaps = {\n before: Map<number, number[]>\n after: Map<number, number[]>\n beforeGaps: Map<number, RootTriviaGap>\n afterGaps: Map<number, RootTriviaGap>\n gaps: RootTriviaGap[]\n}\n\nfunction entryOffset(i: number, stride: number): number {\n return i * stride\n}\n\n/**\n * Wrap a flat trivia log. Stride is inferred from `labels`:\n * - root `_triviaLog`: 2 (start, end) or 3 (+ kindIndex)\n * - node `triviaLog`: 3 (start, end, insertIdx) or 4 (+ kindIndex)\n */\nexport function triviaEntries(\n log: readonly number[],\n labels?: readonly string[],\n opts?: { nodeLog?: boolean },\n): TriviaEntriesView {\n const baseStride = opts?.nodeLog ? 3 : 2\n const stride = labels ? baseStride + 1 : baseStride\n const length = Math.floor(log.length / stride)\n\n return {\n length,\n labels,\n stride,\n start(i) {\n return log[entryOffset(i, stride)]!\n },\n end(i) {\n return log[entryOffset(i, stride) + 1]!\n },\n insertIndex(i) {\n return opts?.nodeLog ? log[entryOffset(i, stride) + 2] : undefined\n },\n kindIndex(i) {\n if (!labels) return undefined\n return log[entryOffset(i, stride) + baseStride]\n },\n kind(i) {\n const ki = labels ? log[entryOffset(i, stride) + baseStride] : undefined\n return ki !== undefined ? labels![ki] : undefined\n },\n text(i, input) {\n const s = log[entryOffset(i, stride)]!\n const e = log[entryOffset(i, stride) + 1]!\n return input.slice(s, e)\n },\n }\n}\n\n/**\n * Build a root view over the sparse selected-label rows captured as\n * `[ownedRangeStart, ownedRangeEnd, markerStart, markerEnd, kindIndex]`.\n *\n * This is intentionally a different input shape from `triviaLog`: each row is\n * one selected marker, while the first pair names the complete committed trivia\n * range around it. Thus a mixed trivia run costs one five-number row, not three\n * legacy trivia entries. Rows are source ordered and equal gap pairs are\n * contiguous, which lets singleton boundary lookups binary-search the sparse\n * rows without constructing document-wide maps.\n */\nexport function buildRootTriviaIndex(\n log: readonly number[],\n labels: readonly string[],\n): RootTriviaIndex {\n const length = Math.floor(log.length / SELECTED_ROOT_STRIDE)\n const markerOffset = (i: number) => i * SELECTED_ROOT_STRIDE\n const ownedRangeStart = (i: number) => log[markerOffset(i)]!\n const ownedRangeEnd = (i: number) => log[markerOffset(i) + 1]!\n const markerStart = (i: number) => log[markerOffset(i) + 2]!\n const markerEnd = (i: number) => log[markerOffset(i) + 3]!\n const markerKind = (i: number) => log[markerOffset(i) + 4]!\n\n const entries: TriviaEntriesView = {\n length,\n labels,\n stride: SELECTED_ROOT_STRIDE,\n start: markerStart,\n end: markerEnd,\n insertIndex: () => undefined,\n kindIndex: markerKind,\n kind(i) {\n return labels[markerKind(i)]\n },\n text(i, input) {\n return input.slice(markerStart(i), markerEnd(i))\n },\n }\n\n const lowerBound = (offset: number, by: (i: number) => number): number => {\n let lo = 0\n let hi = length\n while (lo < hi) {\n const mid = (lo + hi) >>> 1\n if (by(mid) < offset) lo = mid + 1\n else hi = mid\n }\n return lo\n }\n\n const gapRowsAt = (offset: number, direction: 'before' | 'after'): [number, number] | undefined => {\n const edge = direction === 'before' ? ownedRangeEnd : ownedRangeStart\n let first = lowerBound(offset, edge)\n if (first === length || edge(first) !== offset) return undefined\n const start = ownedRangeStart(first)\n const end = ownedRangeEnd(first)\n while (first > 0 && ownedRangeStart(first - 1) === start && ownedRangeEnd(first - 1) === end) first--\n let last = first + 1\n while (last < length && ownedRangeStart(last) === start && ownedRangeEnd(last) === end) last++\n return [first, last]\n }\n\n const indices = (first: number, last: number): readonly number[] => {\n const out: number[] = []\n for (let i = first; i < last; i++) out.push(i)\n return out\n }\n\n const makeGap = (first: number, last: number): RootTriviaGap => {\n const start = ownedRangeStart(first)\n const end = ownedRangeEnd(first)\n let entryIndices: readonly number[] | undefined\n return {\n start,\n end,\n get entryIndices() {\n return entryIndices ??= indices(first, last)\n },\n hasKind(kind) {\n for (let i = first; i < last; i++) {\n if (labels[markerKind(i)] === kind) return true\n }\n return false\n },\n text(input) {\n return input.slice(start, end)\n },\n }\n }\n\n let maps: RootTriviaMaps | undefined\n const getMaps = () => {\n if (maps !== undefined) return maps\n const before = new Map<number, number[]>()\n const after = new Map<number, number[]>()\n const beforeGaps = new Map<number, RootTriviaGap>()\n const afterGaps = new Map<number, RootTriviaGap>()\n const gaps: RootTriviaGap[] = []\n for (let first = 0; first < length;) {\n let last = first + 1\n while (last < length && ownedRangeStart(last) === ownedRangeStart(first) && ownedRangeEnd(last) === ownedRangeEnd(first)) last++\n const gap = makeGap(first, last)\n gaps.push(gap)\n afterGaps.set(gap.start, gap)\n beforeGaps.set(gap.end, gap)\n after.set(gap.start, [...gap.entryIndices])\n before.set(gap.end, [...gap.entryIndices])\n first = last\n }\n maps = { before, after, beforeGaps, afterGaps, gaps }\n return maps\n }\n\n return {\n entries,\n labels,\n get before() { return getMaps().before },\n get after() { return getMaps().after },\n entryIndicesBefore(offset) {\n const rows = gapRowsAt(offset, 'before')\n return rows ? indices(rows[0], rows[1]) : EMPTY_INDICES\n },\n entryIndicesAfter(offset) {\n const rows = gapRowsAt(offset, 'after')\n return rows ? indices(rows[0], rows[1]) : EMPTY_INDICES\n },\n gapBefore(offset) {\n const rows = gapRowsAt(offset, 'before')\n return rows ? makeGap(rows[0], rows[1]) : undefined\n },\n gapAfter(offset) {\n const rows = gapRowsAt(offset, 'after')\n return rows ? makeGap(rows[0], rows[1]) : undefined\n },\n gaps() {\n return getMaps().gaps\n },\n gapsWithKind(kind) {\n const kinds = typeof kind === 'string' ? [kind] : kind\n const matches: RootTriviaGap[] = []\n // Do not materialize the document-wide boundary maps for a sparse query.\n // The primary consumer selects comments: it needs only comment-bearing gaps,\n // not an object/Map for every whitespace-owned boundary in the document.\n for (let first = 0; first < length;) {\n let last = first + 1\n while (last < length\n && ownedRangeStart(last) === ownedRangeStart(first)\n && ownedRangeEnd(last) === ownedRangeEnd(first)) last++\n let matched = false\n for (let i = first; i < last && !matched; i++) {\n const label = labels[markerKind(i)]\n for (const kind of kinds) {\n if (label === kind) {\n matched = true\n break\n }\n }\n }\n if (matched) matches.push(makeGap(first, last))\n first = last\n }\n return matches.length === 0 ? EMPTY_GAPS : matches\n },\n }\n}\n", "/**\n * Structural recognition of \"scannable\" parser arms \u2014 regex shapes that lower to\n * a tight character-scan loop instead of `regex.exec` / combinator dispatch. Each\n * shape is derived from the regex STRUCTURE, not from any hardcoded knowledge\n * that a given regex \"is whitespace\" or \"is a comment\":\n *\n * [X]+ / [X]* \u2192 run while the char \u2208 X (chars)\n * <lit>[^X]* \u2192 consume <lit>, run until char \u2208 X (until)\n * <open>(?:\u2026)*<close> \u2192 consume <open>, run to <close> literal (delimited)\n * x?<lit><[X]*>\u2026 \u2192 a general linear chain of lit/run (seq)\n *\n * `seq` is the CATEGORY generalization: any chain of literal segments (required\n * or optional `x?`) and char-class runs (positive/negated, `?`/`*`/`+`). It\n * subsumes CSS/Less `-?ident`, `--custom`, `@-?keyword`, `[^\u2026]+`, `::?`, etc.\n * without hardcoding a single byte \u2014 lowered only when a greedy one-pass scan\n * provably equals the engine's backtracking (see `seqIsUnambiguous`).\n *\n * A `oneOrMore(choice(a, b, \u2026))` where every arm is one of these compiles to a\n * single char-dispatch loop with one branch per arm \u2014 any count/order, because\n * the shapes dispatch on their first 1\u20132 chars and are checked in turn. Trivia\n * (whitespace + comments) is just the value-discarded instance of this; nothing\n * here is trivia-specific.\n */\n\n/**\n * One segment of a `seq` shape. A `seq` is the general category \"a fixed linear\n * chain of literals and char-class runs\" \u2014 no alternation, no groups, no\n * backtracking. It subsumes every CSS/Less token that is \"(optional prefix)?\n * literal* char-run* \u2026\" without hardcoding any particular byte:\n *\n * lit \u2014 a run of fixed code points, optionally present (`x?`) or required.\n * run \u2014 a char-class run: positive/negated ranges, min 0/1, bounded to one\n * char (`[x]`, `[x]?`) or unbounded (`[x]*`, `[x]+`).\n * group \u2014 a non-capturing sub-pattern `(?:\u2026)` (\u00A78f), quantified the same way\n * as `run` (`min`/`unbounded`). `inner` is any already-recognized\n * `ScanShape` for the group's body (so a group can itself contain\n * `seq`/`chars`/`alt`/\u2026 \u2014 including a nested alternation via \u00A78e).\n * Only used when `groupInnerSafe(inner)` holds (see that function).\n *\n * We only lower a `seq` when greedy left-to-right scanning provably equals the\n * regex engine's backtracking match (see `seqIsUnambiguous`).\n */\nexport type SeqPart =\n | { part: 'lit'; cps: number[]; optional: boolean }\n // A char-class run with a general counted quantifier: `min`..`max` occurrences.\n // `max === Infinity` is unbounded (`+`/`*`/`{n,}`). The four legacy shapes map\n // as `+`\u2192{1,\u221E} `*`\u2192{0,\u221E} `?`\u2192{0,1} bare\u2192{1,1}; `{n,m}` (\u00A78c) fills the rest.\n // Greedy scanning has \"wiggle\" a backtracker could exploit iff `max > min`.\n | { part: 'run'; ranges: Array<[number, number]>; negated: boolean; min: number; max: number }\n | { part: 'group'; inner: ScanShape; min: 0 | 1; unbounded: boolean }\n\nexport type ScanShape =\n | { kind: 'chars'; ranges: Array<[number, number]>; minOne: boolean }\n | { kind: 'ident'; head: Array<[number, number]>; tail: Array<[number, number]> }\n | { kind: 'until'; open: number[]; stop: Array<[number, number]> }\n | { kind: 'delimited'; open: number[]; close: number[] }\n // <q>(?:[^<q>\\\\]|\\\\.)*<q> \u2014 a quote-delimited string with backslash escapes.\n // `excluded` = the body's negated class (always contains the quote + backslash,\n // maybe a newline); `escLineTerm` = whether `\\\\` may be followed by a line\n // terminator (`\\\\[\\s\\S]` \u2192 true, `\\\\.` \u2192 false, since `.` excludes them).\n | { kind: 'string'; quote: number; excluded: Array<[number, number]>; escLineTerm: boolean }\n // A linear chain of literal/char-run segments (optional prefixes, literal\n // openers, negated runs, \u2026) \u2014 the general CSS/Less token category.\n | { kind: 'seq'; parts: SeqPart[] }\n // A pure literal matched case-insensitively (`/i`): the general \"ASCII\n // case-fold literal\" category (CSS `url(`, `@media` keywords under `i`, \u2026).\n | { kind: 'litFold'; open: number[] }\n // `<inner>(?!class)` / `<inner>(?=class)` \u2014 a trailing lookahead boundary\n // check on an already-lowered shape. Zero-width: `end` is `inner`'s end, never\n // extended. `classNegated` is the bracket's OWN `[^\u2026]` negation (e.g.\n // `(?![0-9a-fA-F])` vs `(?=[^0-9])`), independent of `negative` (`!` vs `=`).\n | { kind: 'lookahead'; inner: ScanShape; ranges: Array<[number, number]>; classNegated: boolean; negative: boolean }\n // `A|B|C` \u2014 top-level alternation (\u00A78e), split outside any `[]`/`()`, each arm\n // independently lowered. `disjoint` is true iff every pair of arms has\n // provably non-overlapping first-char sets (`firsts[i]` holds that arm's set,\n // or `null` if it could start with any char \u2014 an unbounded-optional `chars`\n // arm, or a non-disjoint mix). When `disjoint`, codegen dispatches straight to\n // the one matching arm; otherwise it tries arms in order and takes the first\n // that succeeds \u2014 the same ordered-choice semantics as regex `|` itself (see\n // the ordered-vs-longest verification in PERF_IDEAS \u00A78e).\n | { kind: 'alt'; arms: ScanShape[]; disjoint: boolean; firsts: Array<CharSet | null> }\n\n/** Backslash (`\\`) code point \u2014 the escape lead char in string shapes. */\nexport const BACKSLASH = 92\n\nconst META = new Set('()[]{}*+?|^$.'.split(''))\n\n// Regex char-class primitives are shared with the interpreter's first-set\n// analyzer and `regex()`'s scanner \u2014 see `../regex/classes.ts`. `SPACE_RANGES`\n// and `parseClassRanges` are re-exported here because codegen's boundary-class\n// lowering imports them from this module.\nimport { CLASS_ESCAPES, SPACE_RANGES, shorthandRanges, readUnicodeEscape, parseClassRanges } from '../regex/classes.ts'\nimport { SELECTED_ROOT_STRIDE } from '../cst/trivia-entries.ts'\n\n/** Placeholder fields filled with the trivia span once the enclosing run ends. */\nconst SELECTED_ROOT_OWNED_RANGE_PLACEHOLDER = Array.from(\n { length: SELECTED_ROOT_STRIDE - 3 },\n () => '0',\n).join(', ')\nexport { SPACE_RANGES, parseClassRanges }\n\n/** A single class token (`[...]` or `\\d`/`\\w`) to ranges, or null. Rejects negation. */\nfunction classToRanges(cls: string): Array<[number, number]> | null {\n if (cls === '\\\\d') return shorthandRanges('d')\n if (cls === '\\\\w') return shorthandRanges('w')\n if (cls === '\\\\s') return shorthandRanges('s')\n const body = cls.slice(1, -1)\n if (body.startsWith('^')) return null\n return parseClassRanges(body)\n}\n\n/** ASCII case-insensitive letter check for `i`-flag literal lowering. */\n// ASCII case-insensitive char compare. For a letter, upper/lower differ only in\n// bit 0x20, and `(c | 32) === <lowercase>` is satisfied by EXACTLY that letter's\n// two cases (nothing else) \u2014 one OR + one compare, ~1.75\u00D7 faster than the\n// two-compare `(c===U || c===L)` form (measured). `(\u2026 | 32)` is parenthesized\n// because `===` binds tighter than `|`. Non-letters keep an exact compare.\n// Exported so the case-insensitive `literal()` emitter (codegen) shares the exact\n// same ASCII fold as `/i`-flag regex lowering \u2014 no `Intl.Collator` on any path.\nexport const foldEq = (cVar: string, cp: number): string => {\n if (cp >= 65 && cp <= 90) return `(${cVar} | 32) === ${cp + 32}`\n if (cp >= 97 && cp <= 122) return `(${cVar} | 32) === ${cp}`\n return `${cVar} === ${cp}`\n}\n\n/** All-literal regex fragment (`\\/\\*`, `\\/\\/`, \u2026) \u2192 its code points, or null on an unescaped metachar. */\nfunction literalCodePoints(frag: string): number[] | null {\n const out: number[] = []\n let i = 0\n while (i < frag.length) {\n const ch = frag[i]!\n if (ch === '\\\\') {\n const e = frag[i + 1]\n if (e === undefined) return null\n out.push(e in CLASS_ESCAPES ? CLASS_ESCAPES[e]! : e.codePointAt(0)!)\n i += 2\n continue\n }\n if (META.has(ch)) return null\n out.push(ch.codePointAt(0)!)\n i += 1\n }\n return out.length ? out : null\n}\n\n/**\n * Recognize a quote-delimited string with backslash escapes:\n * <q>(?:[^\u2026]|\\\\.)*<q> or <q>(?:\\\\.|[^\u2026])*<q> (`?:` optional)\n * where the negated body class contains the quote and the backslash, and the\n * escape body is `.` (no line terminators) or `[\\s\\S]` (any char). Returns null\n * for anything else so the caller falls back to `regex.exec`.\n */\nfunction parseStringShape(source: string): ScanShape | null {\n const q = source[0]\n if (q === undefined || q === '\\\\' || META.has(q)) return null\n if (source.length < 3 || source[source.length - 1] !== q) return null\n const inner = source.slice(1, -1)\n const CLS = String.raw`\\[\\^((?:\\\\.|[^\\]])+)\\]`\n const ESC = String.raw`\\\\\\\\(\\.|\\[\\\\s\\\\S\\]|\\[\\\\S\\\\s\\])`\n // Two arm orders; `?:` optional. Capture groups differ, so read both out.\n let body: string | undefined\n let esc: string | undefined\n let m = new RegExp(`^\\\\((?:\\\\?:)?${CLS}\\\\|${ESC}\\\\)\\\\*$`).exec(inner)\n if (m) { body = m[1]; esc = m[2] }\n else {\n m = new RegExp(`^\\\\((?:\\\\?:)?${ESC}\\\\|${CLS}\\\\)\\\\*$`).exec(inner)\n if (m) { esc = m[1]; body = m[2] }\n }\n if (body === undefined || esc === undefined) return null\n const excluded = parseClassRanges(body)\n if (!excluded) return null\n const qcp = q.codePointAt(0)!\n const inSet = (cp: number) => excluded.some(([lo, hi]) => cp >= lo && cp <= hi)\n if (!inSet(qcp) || !inSet(BACKSLASH)) return null\n return { kind: 'string', quote: qcp, excluded, escLineTerm: esc !== '.' }\n}\n\n/**\n * Parse a regex source into a linear chain of literal / char-run segments, or\n * null if it uses any construct outside that category (alternation, groups,\n * `.`, `{n,m}`, lookaround, unknown escapes). This is the STRUCTURAL recognizer\n * for the `seq` shape \u2014 it encodes categories (optional prefix, literal opener,\n * negated run, \u2026), never any specific byte value.\n */\nfunction parseSeqParts(source: string): SeqPart[] | null {\n const parts: SeqPart[] = []\n let lit: number[] = []\n const flush = () => {\n if (lit.length) { parts.push({ part: 'lit', cps: lit, optional: false }); lit = [] }\n }\n // Parse a `{n}` / `{n,}` / `{n,m}` counted quantifier at `source[at]` (`'{'`).\n // Returns the bounds and the token length, or null when it isn't a well-formed\n // brace quantifier (then the `{` is left for the caller's metachar decline).\n const braceQuant = (at: number): { min: number; max: number; len: number } | null => {\n const close = source.indexOf('}', at)\n if (close === -1) return null\n const body = source.slice(at + 1, close)\n const m = /^(\\d+)(,(\\d*)?)?$/.exec(body)\n if (!m) return null\n const min = Number(m[1])\n const max = m[2] === undefined ? min : m[3] ? Number(m[3]!) : Infinity\n // Decline degenerate/empty-capable or invalid bounds \u2014 RegExp handles them.\n if (max < 1 || min > max) return null\n return { min, max, len: close - at + 1 }\n }\n const runFrom = (ranges: Array<[number, number]>, negated: boolean, at: number) => {\n const q = source[at]\n if (q === '+') { parts.push({ part: 'run', ranges, negated, min: 1, max: Infinity }); return 1 }\n if (q === '*') { parts.push({ part: 'run', ranges, negated, min: 0, max: Infinity }); return 1 }\n if (q === '?') { parts.push({ part: 'run', ranges, negated, min: 0, max: 1 }); return 1 }\n if (q === '{') {\n const b = braceQuant(at)\n if (b) { parts.push({ part: 'run', ranges, negated, min: b.min, max: b.max }); return b.len }\n }\n parts.push({ part: 'run', ranges, negated, min: 1, max: 1 })\n return 0\n }\n let i = 0\n while (i < source.length) {\n const ch = source[i]!\n if (ch === '[') {\n // Read a char class, honoring `\\]`.\n let k = i + 1\n const neg = source[k] === '^'\n if (neg) k++\n let body = ''\n while (k < source.length && source[k] !== ']') {\n if (source[k] === '\\\\') { body += source[k]! + (source[k + 1] ?? ''); k += 2 }\n else { body += source[k]!; k++ }\n }\n if (source[k] !== ']') return null\n const ranges = parseClassRanges(body)\n if (!ranges) return null\n flush()\n i = k + 1\n i += runFrom(ranges, neg, i)\n continue\n }\n if (ch === '\\\\') {\n const e = source[i + 1]\n if (e === 'd' || e === 'w' || e === 's') {\n flush()\n i += 2\n i += runFrom(shorthandRanges(e), false, i)\n continue\n }\n // Escaped literal code point (incl. `\\uXXXX`, `\\t`, `\\(`, \u2026).\n const uni = readUnicodeEscape(source, i)\n let cp: number\n if (uni) { cp = uni.cp; i = uni.next }\n else if (e === undefined) return null\n else if (e in CLASS_ESCAPES) { cp = CLASS_ESCAPES[e]!; i += 2 }\n else if ((e >= 'a' && e <= 'z') || (e >= 'A' && e <= 'Z')) return null\n else { cp = e.codePointAt(0)!; i += 2 }\n if (source[i] === '?') { flush(); parts.push({ part: 'lit', cps: [cp], optional: true }); i++ }\n else lit.push(cp)\n continue\n }\n if (ch === '(') {\n // Only a non-capturing group `(?:\u2026)` is modeled (\u00A78f) \u2014 a bare capturing\n // group, or a lookaround appearing mid-pattern (a TRAILING one is peeled\n // off separately by `stripTrailingLookahead` before we ever get here), is\n // declined outright rather than risk misreading it.\n if (source[i + 1] !== '?' || source[i + 2] !== ':') return null\n let k = i + 3\n let depth = 1\n while (k < source.length && depth > 0) {\n const c2 = source[k]\n if (c2 === '\\\\') { k += 2; continue }\n if (c2 === '[') {\n let j = k + 1\n if (source[j] === '^') j++\n while (j < source.length && source[j] !== ']') {\n if (source[j] === '\\\\') j += 2\n else j++\n }\n if (source[j] !== ']') return null\n k = j + 1\n continue\n }\n if (c2 === '(') depth++\n else if (c2 === ')') depth--\n k++\n }\n if (depth !== 0) return null\n const body = source.slice(i + 3, k - 1)\n const inner = parseScanShape(body)\n if (!inner || !groupInnerSafe(inner)) return null\n const q = source[k]\n // `{n,m}` on a group is a \u00A78c/\u00A78f combination not modeled \u2014 decline.\n if (q === '{') return null\n flush()\n if (q === '+') {\n if (shapeCanBeEmpty(inner)) return null // would loop forever \u2014 decline\n parts.push({ part: 'group', inner, min: 1, unbounded: true })\n i = k + 1\n } else if (q === '*') {\n if (shapeCanBeEmpty(inner)) return null\n parts.push({ part: 'group', inner, min: 0, unbounded: true })\n i = k + 1\n } else if (q === '?') {\n parts.push({ part: 'group', inner, min: 0, unbounded: false })\n i = k + 1\n } else {\n parts.push({ part: 'group', inner, min: 1, unbounded: false })\n i = k\n }\n continue\n }\n // A bare metachar (`|`, `.`, `{`, stray `*`/`+`/`?`, \u2026) is outside the\n // linear-chain category \u2014 bail to the RegExp fallback.\n if (META.has(ch)) return null\n const cp = ch.codePointAt(0)!\n i += ch.length\n if (source[i] === '?') { flush(); parts.push({ part: 'lit', cps: [cp], optional: true }); i++ }\n else lit.push(cp)\n }\n flush()\n return parts.length ? parts : null\n}\n\n/**\n * Only lower a `seq` when greedy left-to-right scanning matches EXACTLY what the\n * backtracking regex engine would. The dangerous cases are (a) an optional part\n * that could also be consumed by what follows, and (b) an unbounded/repeated\n * part whose accepted class overlaps what follows \u2014 both let the engine\n * backtrack to a different boundary than a one-pass scan. We also require at\n * least one mandatory segment (so the token can't match zero-width).\n *\n * A skippable/repeatable part `p` at index `k` is checked against\n * `seqFirstAccept(parts.slice(k + 1))` \u2014 the accept-set of EVERYTHING that\n * could start at the very next position, unioned through any further chain of\n * optionals up to the next mandatory part (the exact same computation\n * `seqFirstAccept` already does for a seq's OWN leading accept-set). This\n * subsumes the simpler \"check only the immediate neighbor\" rule as the\n * one-part-following case, while also correctly handling a CHAIN of several\n * consecutive optional parts (e.g. two independent optional groups in a row,\n * `(?:\\.\\d+)?(?:[eE][+-]?\\d+)?` \u2014 JSON/GraphQL's number tail, \u00A78f): each is\n * safe precisely when disjoint from everything that could follow it, however\n * many further optionals that spans. An empty tail (`p` is the last part)\n * naturally resolves to a trivially-disjoint empty set \u2014 nothing to check.\n *\n * Uniform across `lit`/`run`/`group`: each part's own \"first char it could\n * start with\" (`partFirstAccept`) is compared via `firstSetsDisjoint` \u2014 the\n * same subset/disjoint math used everywhere else in this file (\u00A78b's\n * lookahead guard, \u00A78e's alt-dispatch guard).\n */\nfunction seqIsUnambiguous(parts: SeqPart[]): boolean {\n let hasMandatory = false\n for (let k = 0; k < parts.length; k++) {\n const p = parts[k]!\n const mandatory = p.part === 'lit' ? !p.optional : p.min >= 1\n if (mandatory) hasMandatory = true\n // A `group` part has a right-edge exposure (`groupPartExposure`): the chars a\n // backtracking engine could give back by shrinking the body's own trailing\n // quantifier, dropping the group (if optional/repeated), or \u2014 for a\n // non-disjoint alt body \u2014 switching arms. Ordered-choice greedy scanning\n // matches the engine only when NONE of those relinquished chars could also\n // start what follows the group (else the scan and the engine disagree on\n // where the group ends). Two outcomes:\n // - a concrete class \u2192 must be disjoint from `seqFirstAccept(rest)`. This\n // is the general fix for a group whose body ends in an unbounded run\n // (`(?:\\d+)\\d` must NOT lower), and it lets a mutually-exclusive fixed\n // alt (\u00A78i, exposure `null`) lower at ANY position, not just trailing.\n // - `'unsupported'` \u2192 the exposure can't be bounded (e.g. a non-disjoint\n // alt like `(?:a|ab)` that genuinely needs arm-switching). Sound only\n // when nothing follows to force reconsideration \u2014 the group must be the\n // trailing, matched-exactly-once part (\u00A78h); otherwise decline.\n if (p.part === 'group') {\n const exposure = groupPartExposure(p)\n if (exposure === 'unsupported') {\n const trailingOnce = k === parts.length - 1 && p.min === 1 && !p.unbounded\n if (!trailingOnce) return false\n } else if (exposure !== null) {\n if (!firstSetsDisjoint(exposure, seqFirstAccept(parts.slice(k + 1)))) return false\n }\n }\n // A part needs the disjoint-from-continuation check when a greedy one-pass\n // scan has freedom a backtracking engine could resolve differently: an\n // optional `lit`, a `run` with wiggle (`max > min` \u2014 covers `?`/`*`/`+` and\n // bounded `{n,m}` with `m > n`; a fixed `{n}` run has none), or an\n // optional/repeated `group`. A fixed-length run (`max === min`) consumes an\n // exact count with no boundary to shift, so it never needs the check.\n const needsDisjoint =\n p.part === 'lit' ? p.optional\n : p.part === 'run' ? p.max > p.min\n : (p.unbounded || p.min === 0)\n if (needsDisjoint) {\n const rest = seqFirstAccept(parts.slice(k + 1))\n if (!firstSetsDisjoint(partFirstAccept(p), rest)) return false\n }\n }\n return hasMandatory\n}\n\nfunction rangesOverlap(a: Array<[number, number]>, b: Array<[number, number]>): boolean {\n return a.some(([lo, hi]) => b.some(([lo2, hi2]) => lo <= hi2 && lo2 <= hi))\n}\n\n/** Is every range in `sub` fully contained in some range of `sup`? */\nfunction rangesSubset(sub: Array<[number, number]>, sup: Array<[number, number]>): boolean {\n return sub.every(([lo, hi]) => sup.some(([lo2, hi2]) => lo >= lo2 && hi <= hi2))\n}\n\n/**\n * A `(?!X)`/`(?=X)` operand: a char class (`[...]`, incl. `[^...]`), a\n * shorthand class (`\\d`/`\\w`/`\\s`), or a single literal/escaped char \u2014 never a\n * sub-pattern (no alternation, no nested groups). Returns the ranges to test\n * membership against, and whether the bracket itself was negated (`[^...]`) \u2014\n * independent of the lookahead's own `!`/`=` polarity.\n */\nfunction parseClassOperand(body: string): { ranges: Array<[number, number]>; negated: boolean } | null {\n if (body === '\\\\d' || body === '\\\\w' || body === '\\\\s') {\n return { ranges: shorthandRanges(body[1] as 'd' | 'w' | 's'), negated: false }\n }\n if (body.length >= 2 && body[0] === '[' && body[body.length - 1] === ']') {\n let inner = body.slice(1, -1)\n const negated = inner.startsWith('^')\n if (negated) inner = inner.slice(1)\n const ranges = parseClassRanges(inner)\n return ranges ? { ranges, negated } : null\n }\n const cps = literalCodePoints(body)\n if (cps && cps.length === 1) return { ranges: [[cps[0]!, cps[0]!]], negated: false }\n return null\n}\n\ntype TrailingLookahead = {\n base: string\n ranges: Array<[number, number]>\n classNegated: boolean\n negative: boolean\n}\n\ntype CharSet = { ranges: Array<[number, number]>; negated: boolean }\n\n/** Is char-set `t` fully contained in char-set `u`? Handles all 4 sign combos. */\nfunction classSubset(t: CharSet, u: CharSet): boolean {\n if (!t.negated && !u.negated) return rangesSubset(t.ranges, u.ranges)\n if (!t.negated && u.negated) return !rangesOverlap(t.ranges, u.ranges) // t \u2286 \u00ACu \u27FA t \u2229 u = \u2205\n if (t.negated && !u.negated) return false // \u00ACt \u2286 u is never true for finite ranges u\n return rangesSubset(u.ranges, t.ranges) // \u00ACt \u2286 \u00ACu \u27FA u \u2286 t\n}\n\n/** Are char-sets `t` and `u` disjoint (no overlap)? Handles all 4 sign combos. */\nfunction classDisjoint(t: CharSet, u: CharSet): boolean {\n if (!t.negated && !u.negated) return !rangesOverlap(t.ranges, u.ranges)\n if (!t.negated && u.negated) return rangesSubset(t.ranges, u.ranges) // t \u2229 \u00ACu = \u2205 \u27FA t \u2286 u\n if (t.negated && !u.negated) return rangesSubset(u.ranges, t.ranges) // symmetric\n return false // \u00ACt \u2229 \u00ACu = \u2205 would require t \u222A u = every code point \u2014 can't prove with finite ranges\n}\n\n/** `classDisjoint`, `'any'`-aware: an empty-capable part's first-set degrades\n * to `'any'` (see `shapeFirstAccept`), and `'any'` is never disjoint from\n * anything (it could start with literally any char, including whatever the\n * other side accepts). */\nfunction firstSetsDisjoint(a: CharSet | 'any', b: CharSet | 'any'): boolean {\n if (a === 'any' || b === 'any') return false\n return classDisjoint(a, b)\n}\n\n/**\n * A shape's match as a fixed-length list of per-position char-sets, or `null`\n * if its match length is NOT fixed. Only a `seq` of mandatory `lit`s (each code\n * point is one fixed position) and mandatory single-char runs (`[x]`, min 1,\n * bounded) qualifies \u2014 anything with an optional part, an unbounded/optional\n * run, or a nested group has a variable length and returns `null`. Used to\n * decide when a non-disjoint alternation's arms are mutually exclusive (\u00A78i).\n */\nfunction fixedClassSeq(shape: ScanShape): CharSet[] | null {\n // A case-fold literal is fixed-length: each code point becomes a single-char\n // class holding BOTH ASCII cases (so mutual-exclusivity is judged on what the\n // `/i` match actually accepts \u2014 `and` vs `or` are disjoint at position 0).\n if (shape.kind === 'litFold') {\n return shape.open.map(cp => {\n const other = cp >= 65 && cp <= 90 ? cp + 32 : cp >= 97 && cp <= 122 ? cp - 32 : cp\n return other === cp\n ? { ranges: [[cp, cp]] as Array<[number, number]>, negated: false }\n : { ranges: [[Math.min(cp, other), Math.min(cp, other)], [Math.max(cp, other), Math.max(cp, other)]] as Array<[number, number]>, negated: false }\n })\n }\n if (shape.kind !== 'seq') return null\n const out: CharSet[] = []\n for (const p of shape.parts) {\n if (p.part === 'lit') {\n if (p.optional) return null\n for (const cp of p.cps) out.push({ ranges: [[cp, cp]], negated: false })\n } else if (p.part === 'run' && p.max === p.min && Number.isFinite(p.max)) {\n // A fixed-count run `[x]{n}` (incl. the bare `[x]`, n=1) is n fixed\n // positions of the same class. Variable-length runs return null below.\n for (let c = 0; c < p.max; c++) out.push({ ranges: p.ranges, negated: p.negated })\n } else {\n return null // optional/variable/unbounded run, or a nested group \u2014 length not fixed\n }\n }\n return out.length ? out : null\n}\n\n/**\n * \u00A78i \u2014 is a NON-disjoint `alt` shape one whose arms are pairwise MUTUALLY\n * EXCLUSIVE fixed-length token sets? Every arm must be a `fixedClassSeq`, and no\n * arm's match may ever be a prefix (proper, or an equal-length overlap) of\n * another arm's \u2014 i.e. for every ordered pair (A, B) with `A.length <= B.length`\n * there is a position within A where their classes are DISJOINT. That property\n * guarantees at most one arm matches at any input position, so ordered-choice\n * commit lands on the SAME arm (and the SAME fixed end) the engine would, with\n * no arm to switch to under backtracking \u2014 sound in ANY position, not just\n * trailing (unlike the general non-disjoint alt, which needs the trailing-once\n * gate in `seqIsUnambiguous`). `(?:ab|ac)` and `(?:foo|barn)` qualify;\n * `(?:a|ab)` (arm `a` is a prefix of `ab`) does NOT.\n */\nfunction altFixedMutuallyExclusive(shape: ScanShape): boolean {\n if (shape.kind !== 'alt' || shape.disjoint) return false\n const lists: CharSet[][] = []\n for (const arm of shape.arms) {\n const f = fixedClassSeq(arm)\n if (!f) return false\n lists.push(f)\n }\n for (let i = 0; i < lists.length; i++) {\n for (let j = 0; j < lists.length; j++) {\n if (i === j) continue\n const a = lists[i]!\n const b = lists[j]!\n if (a.length > b.length) continue // only check the shorter (a) as a prefix of the longer (b)\n let disjointAt = false\n for (let p = 0; p < a.length; p++) {\n if (classDisjoint(a[p]!, b[p]!)) { disjointAt = true; break }\n }\n if (!disjointAt) return false // `a` could be a prefix of `b` \u2014 not mutually exclusive\n }\n }\n return true\n}\n\n/**\n * The char-set a backtracking engine could relinquish at a `group` PART's right\n * edge \u2014 its \"trailing exposure\". Combines two independent backtrack moves: the\n * group body's OWN trailing wiggle (`trailingBacktrackClass(inner)`, e.g. the\n * body ends in an unbounded run), and \u2014 if the group is optional (`min 0`) or\n * repeated (`unbounded`) \u2014 the \"drop the last occurrence\" move, which exposes\n * the body's own first-char set. A required-once group (`min 1`, bounded) has\n * only the first move. Returns `'unsupported'` if either component can't be\n * pinned to a concrete set. This is the single computation used everywhere a\n * group's right boundary matters: `trailingBacktrackClass` (a `seq` ending in a\n * group) and `seqIsUnambiguous` (a group at ANY position, followed by more).\n */\nfunction groupPartExposure(part: Extract<SeqPart, { part: 'group' }>): CharSet | null | 'unsupported' {\n const innerWiggle = trailingBacktrackClass(part.inner)\n if (innerWiggle === 'unsupported') return 'unsupported'\n const requiredOnce = !part.unbounded && part.min === 1\n if (requiredOnce) return innerWiggle // no \"drop it\" move possible \u2014 only inner's own wiggle matters\n const dropExposed = shapeFirstAccept(part.inner)\n if (dropExposed === 'any') return 'unsupported'\n if (innerWiggle === null) return dropExposed\n const unioned = unionCharSets([innerWiggle, dropExposed])\n return unioned === 'any' ? 'unsupported' : unioned\n}\n\n/**\n * The char-class a backtracking engine could expose by shrinking `shape`'s\n * OWN trailing quantifier by one position \u2014 i.e. the \"wiggle room\" a trailing\n * lookahead could interact with. Returns `null` when `shape`'s matched length\n * is fully fixed once it succeeds (no quantifier to shrink), which makes\n * wrapping it in a lookahead unconditionally safe. Returns `'unsupported'` for\n * shape kinds whose backtracking semantics aren't modeled here (declines the\n * lookahead lowering rather than risking an unproven guard).\n *\n * Only the LAST quantifier matters: `seqIsUnambiguous` already proves every\n * EARLIER part of a `seq` has exactly one valid parse (no alternate length),\n * so the sole remaining freedom a backtracking engine has \u2014 once we attach an\n * external trailing lookahead \u2014 is in whatever quantifier sits at the very end.\n */\nfunction trailingBacktrackClass(shape: ScanShape): CharSet | null | 'unsupported' {\n if (shape.kind === 'chars') return { ranges: shape.ranges, negated: false }\n if (shape.kind === 'ident') return { ranges: shape.tail, negated: false }\n if (shape.kind === 'litFold') return null // fixed-length literal \u2014 no quantifier at all\n if (shape.kind === 'seq') {\n const last = shape.parts[shape.parts.length - 1]!\n if (last.part === 'lit') return null // fixed literal tail \u2014 no wiggle room\n if (last.part === 'run') {\n // Wiggle iff `max > min`: unbounded (`+`/`*`/`{n,}`), optional (`[x]?`),\n // or bounded `{n,m}` with `m > n` all let a backtracker shrink the trailing\n // run by \u22651 position. A fixed run (`[x]`, `{n}`, `max === min`) has no\n // choice \u2014 no wiggle, hence no risk.\n if (last.max > last.min) return { ranges: last.ranges, negated: last.negated }\n return null\n }\n // A trailing `group` (\u00A78f): its trailing exposure combines its body's own\n // wiggle and (if optional/repeated) the \"drop it\" move \u2014 see\n // `groupPartExposure`, shared with `seqIsUnambiguous`.\n return groupPartExposure(last)\n }\n if (shape.kind === 'alt') {\n // Arm-switching hazard (see `groupInnerSafe`) applies here too: a\n // non-disjoint alt can't be trusted to expose the right wiggle class,\n // since which arm ultimately \"wins\" could itself change under backtrack.\n // A disjoint alt has no such hazard \u2014 exactly one arm is ever reachable\n // from a given starting char, so the union of every arm's OWN wiggle\n // covers whichever one is actually taken. A non-disjoint alt whose arms are\n // fixed-length and mutually exclusive (\u00A78i) also has no wiggle \u2014 exactly one\n // arm matches at any position and its length is fixed, so `null`.\n if (!shape.disjoint) return altFixedMutuallyExclusive(shape) ? null : 'unsupported'\n const classes = shape.arms.map(trailingBacktrackClass)\n if (classes.some(c => c === 'unsupported')) return 'unsupported'\n const concrete = classes.filter((c): c is CharSet => c !== null)\n if (concrete.length === 0) return null\n const unioned = unionCharSets(concrete)\n return unioned === 'any' ? 'unsupported' : unioned\n }\n // `until`/`delimited`/`string`/nested `lookahead` \u2014 not modeled; decline.\n return 'unsupported'\n}\n\n/**\n * Is it safe to lower `inner(?!ranges)` / `inner(?=ranges)` to a one-shot\n * post-match check (vs. requiring real backtracking)? See PERF_IDEAS \u00A78b.\n */\nfunction lookaheadUnambiguous(inner: ScanShape, operand: CharSet, negative: boolean): boolean {\n const tail = trailingBacktrackClass(inner)\n if (tail === 'unsupported') return false\n if (tail === null) return true // inner's length is fixed \u2014 no backtracking possible\n // Negative `(?!op)`: safe iff every char the tail could expose is ALSO\n // excluded by `op` (so shrinking never turns a failure into a pass).\n // Positive `(?=op)`: safe iff the tail is disjoint from `op` (so shrinking\n // could never expose a char that suddenly satisfies `op`).\n return negative ? classSubset(tail, operand) : classDisjoint(tail, operand)\n}\n\n/**\n * Strip a trailing `(?!class)` / `(?=class)` boundary assertion, if present.\n * Only a TRAILING lookahead with a char-class/single-char operand is\n * recognized \u2014 no sub-patterns, no nested groups. Anything else containing an\n * unescaped `(` is left to the other recognizers, which reject it as a\n * metachar (`META`) and fall back to `RegExp.exec`, so a false read here can\n * only fail to lower, never mis-lower.\n */\nfunction stripTrailingLookahead(source: string): TrailingLookahead | null {\n if (!source.endsWith(')')) return null\n for (const negative of [true, false] as const) {\n const lead = negative ? '(?!' : '(?='\n const idx = source.lastIndexOf(lead)\n if (idx === -1) continue\n const body = source.slice(idx + lead.length, -1)\n const operand = body.length ? parseClassOperand(body) : null\n if (!operand) continue\n return { base: source.slice(0, idx), ranges: operand.ranges, classNegated: operand.negated, negative }\n }\n return null\n}\n\n/**\n * Strip ONE redundant outer `(?:\u2026)` wrapper, if it spans the ENTIRE source\n * (nothing before it, nothing \u2014 not even a quantifier \u2014 after its matching\n * close). A non-capturing group with no trailing quantifier is semantically\n * identical to its bare contents, so this is always safe to unwrap; it's what\n * lets `(?:a|b|c)` (a whole-token alternation written as idiomatic regex\n * style, e.g. CSS `basicSel`) reach the top-level `|` split below. Bails\n * (leaves `source` untouched) on anything that isn't a clean whole-string\n * wrap: unbalanced parens, or a group that closes before the string ends\n * (which would mean a quantifier or trailing content follows it).\n */\nfunction unwrapOuterGroup(source: string): string {\n while (source.startsWith('(?:')) {\n let depth = 1\n let i = 3\n let ok = true\n while (i < source.length && depth > 0) {\n const ch = source[i]\n if (ch === '\\\\') { i += 2; continue }\n if (ch === '[') {\n let j = i + 1\n if (source[j] === '^') j++\n while (j < source.length && source[j] !== ']') {\n if (source[j] === '\\\\') j += 2\n else j++\n }\n if (source[j] !== ']') { ok = false; break }\n i = j + 1\n continue\n }\n if (ch === '(') depth++\n else if (ch === ')') depth--\n i++\n }\n if (!ok || depth !== 0 || i !== source.length) break\n source = source.slice(3, -1)\n }\n return source\n}\n\n/**\n * Split a regex source on top-level `|` \u2014 i.e. `|` outside any `[]` bracket\n * class and outside any `(...)` group (parens still count toward depth even\n * though we don't otherwise understand groups; a `|` nested in one is never a\n * split point). Returns null if there's no top-level `|` at all, if brackets/\n * parens are unbalanced, or if any resulting alternative is empty (a\n * zero-width arm \u2014 an unmodeled edge case, decline rather than mis-lower).\n * One redundant whole-string `(?:\u2026)` wrapper is stripped first (see\n * `unwrapOuterGroup`) so `(?:a|b)` splits the same as bare `a|b`.\n */\nfunction splitTopLevelAlternation(source: string): string[] | null {\n const body = unwrapOuterGroup(source)\n const parts: string[] = []\n let depth = 0\n let last = 0\n let i = 0\n while (i < body.length) {\n const ch = body[i]\n if (ch === '\\\\') { i += 2; continue }\n if (ch === '[') {\n let j = i + 1\n if (body[j] === '^') j++\n while (j < body.length && body[j] !== ']') {\n if (body[j] === '\\\\') j += 2\n else j++\n }\n if (body[j] !== ']') return null\n i = j + 1\n continue\n }\n if (ch === '(') { depth++; i++; continue }\n if (ch === ')') { depth--; if (depth < 0) return null; i++; continue }\n if (ch === '|' && depth === 0) {\n parts.push(body.slice(last, i))\n last = i + 1\n i++\n continue\n }\n i++\n }\n if (depth !== 0) return null\n parts.push(body.slice(last))\n if (parts.length < 2 || parts.some(p => p.length === 0)) return null\n return parts\n}\n\n/** Can `shape` match the empty string? Only an unbounded `chars` run with no\n * `+` (`[x]*`) can \u2014 every other shape requires at least one fixed/mandatory\n * char (`seq` always has \u22651 mandatory part per `seqIsUnambiguous`; `ident`/\n * `until`/`delimited`/`string`/`litFold` all require a fixed opening char). A\n * `lookahead`/`alt` defer to what they wrap. */\nfunction shapeCanBeEmpty(shape: ScanShape): boolean {\n if (shape.kind === 'chars') return !shape.minOne\n if (shape.kind === 'lookahead') return shapeCanBeEmpty(shape.inner)\n if (shape.kind === 'alt') return shape.arms.some(shapeCanBeEmpty)\n return false\n}\n\n/** Exact union of char-sets when it's computable, else `'any'` (conservative:\n * forces ordered dispatch rather than guessing at a mixed-polarity union, or\n * when any input is already `'any'`). A single concrete-set list is returned\n * as-is (including if negated) \u2014 the ambiguity is only in combining \u22652 sets\n * of differing polarity. */\nfunction unionCharSets(sets: Array<CharSet | 'any'>): CharSet | 'any' {\n if (sets.some(s => s === 'any')) return 'any'\n const concrete = sets as CharSet[]\n if (concrete.length === 1) return concrete[0]!\n if (concrete.some(s => s.negated)) return 'any'\n return { ranges: concrete.flatMap(s => s.ranges), negated: false }\n}\n\n/** A single seq part's own first-char set, ignoring whether it's skippable.\n * A `group` part delegates to its inner shape's own first-set (\u00A78f) \u2014\n * possibly `'any'` if the inner shape can match empty or is a non-disjoint\n * `alt` (see `shapeFirstAccept`). */\nfunction partFirstAccept(part: SeqPart): CharSet | 'any' {\n if (part.part === 'lit') return { ranges: [[part.cps[0]!, part.cps[0]!]], negated: false }\n if (part.part === 'run') return { ranges: part.ranges, negated: part.negated }\n return shapeFirstAccept(part.inner)\n}\n\n/** The char-set a `seq` can start with: union of each leading skippable part's\n * own set up to and including the first mandatory part (after which later\n * parts can no longer be what the very first input char matches). */\nfunction seqFirstAccept(parts: SeqPart[]): CharSet | 'any' {\n const sets: Array<CharSet | 'any'> = []\n for (const p of parts) {\n const mandatory = p.part === 'lit' ? !p.optional : p.min >= 1\n sets.push(partFirstAccept(p))\n if (mandatory) break\n }\n return unionCharSets(sets)\n}\n\n/**\n * Is `inner` safe to use as a group's body (\u00A78f)? `chars`/`ident`/`seq`/\n * `litFold` are always safe: each is only ever constructed after proving (via\n * `seqIsUnambiguous` or equivalent) that greedy resolution is the UNIQUE valid\n * match at a given position \u2014 there is no alternate length for a backtracker\n * to reconsider, so treating the group as an atomic, resolve-once unit is\n * sound regardless of what follows it. A `lookahead` defers to what it wraps\n * (zero-width, adds no new choice). An `alt` is safe ONLY when `disjoint`:\n * a NON-disjoint alt (`(?:a|ab)`) genuinely can need real backtracking into a\n * DIFFERENT arm if something after the group fails (verified: `/^(?:a|ab)c/`\n * matches \"abc\" via the SECOND arm, only because the first arm's match left\n * \"c\" unsatisfied) \u2014 our ordered-dispatch codegen resolves once and never\n * reconsiders, so that case must decline. `until`/`delimited`/`string` are\n * declined outright, same conservative call as `trailingBacktrackClass`.\n */\nfunction groupInnerSafe(shape: ScanShape): boolean {\n if (shape.kind === 'chars' || shape.kind === 'ident' || shape.kind === 'seq' || shape.kind === 'litFold') return true\n if (shape.kind === 'lookahead') return groupInnerSafe(shape.inner)\n // A disjoint alt is safe anywhere. A NON-disjoint alt is admitted here too,\n // but its ordered-choice-commit is only sound in the trailing-once position \u2014\n // `seqIsUnambiguous` (\u00A78h) enforces that positional constraint; a non-trailing\n // or optional/repeated non-disjoint-alt group is rejected there.\n if (shape.kind === 'alt') return true\n return false\n}\n\n/**\n * The set of first chars a NON-EMPTY match of `shape` could start with, or\n * `'any'` if that can't be pinned down to a single char-set (used to decide\n * whether `alt` arms have disjoint first-sets). A shape that can match empty\n * degrades to `'any'`: since it could succeed with zero chars regardless of\n * what follows, it would \"accept\" any first char by never actually needing one\n * \u2014 treating that as disjoint from anything else would be unsound.\n */\nfunction shapeFirstAccept(shape: ScanShape): CharSet | 'any' {\n if (shapeCanBeEmpty(shape)) return 'any'\n switch (shape.kind) {\n case 'chars': return { ranges: shape.ranges, negated: false }\n case 'ident': return { ranges: shape.head, negated: false }\n case 'until': return { ranges: [[shape.open[0]!, shape.open[0]!]], negated: false }\n case 'delimited': return { ranges: [[shape.open[0]!, shape.open[0]!]], negated: false }\n case 'string': return { ranges: [[shape.quote, shape.quote]], negated: false }\n case 'litFold': {\n const cp = shape.open[0]!\n if (cp >= 65 && cp <= 90) return { ranges: [[cp, cp], [cp + 32, cp + 32]], negated: false }\n if (cp >= 97 && cp <= 122) return { ranges: [[cp, cp], [cp - 32, cp - 32]], negated: false }\n return { ranges: [[cp, cp]], negated: false }\n }\n case 'seq': return seqFirstAccept(shape.parts)\n case 'lookahead': return shapeFirstAccept(shape.inner) // zero-width \u2014 doesn't change first-char acceptance\n case 'alt': {\n // The set of first chars is the union of every arm's own first-set,\n // independent of whether the arms are mutually disjoint (that flag only\n // governs dispatch, not what the shape can start with). Any arm whose\n // first-set is itself `'any'` (stored as `null`) makes the union `'any'`.\n const sets = shape.firsts.map((f): CharSet | 'any' => (f === null ? 'any' : f))\n return unionCharSets(sets)\n }\n }\n}\n\n/** True iff every pair of `sets` is provably disjoint; `'any'` is disjoint from nothing. */\nfunction allPairsDisjoint(sets: Array<CharSet | 'any'>): boolean {\n for (let i = 0; i < sets.length; i++) {\n const a = sets[i]!\n if (a === 'any') return false\n for (let j = i + 1; j < sets.length; j++) {\n const b = sets[j]!\n if (b === 'any' || !classDisjoint(a, b)) return false\n }\n }\n return true\n}\n\n/**\n * Recognize top-level alternation `A|B|C` (\u00A78e): split on `|` outside any\n * `[]`/`()`, lower each arm independently (an arm may itself be a `seq`,\n * `chars`, `lookahead`, \u2026, or even nested alternation via one redundant\n * `(?:\u2026)` wrapper \u2014 see `unwrapOuterGroup`). Declines (null) unless EVERY arm\n * independently lowers \u2014 a single unsupported arm (e.g. one with a nested\n * capturing/non-capturing group, \u00A78f) falls the whole alternation back to\n * `RegExp.exec` rather than partially lowering.\n */\nfunction parseAlternation(source: string): ScanShape | null {\n const parts = splitTopLevelAlternation(source)\n if (!parts) return null\n const arms: ScanShape[] = []\n for (const p of parts) {\n const arm = parseScanShape(p)\n if (!arm) return null\n arms.push(arm)\n }\n const firstSets = arms.map(shapeFirstAccept)\n const disjoint = allPairsDisjoint(firstSets)\n return { kind: 'alt', arms, disjoint, firsts: firstSets.map(f => (f === 'any' ? null : f)) }\n}\n\n/**\n * Recognize one scannable arm from its regex source, or null if it isn't one of\n * the structural shapes. Top-level alternation (\u00A78e) is tried FIRST \u2014 `|` has\n * the lowest precedence in regex, so splitting on it happens before anything\n * else, with each arm then recursively re-entering this same function (so an\n * arm's own trailing lookahead, or its own nested `(?:\u2026)`-wrapped alternation,\n * is still recognized). Failing that: char-class run, ident, string, then\n * open-until-terminator, delimited, and finally the general linear `seq` chain.\n * A trailing `(?!class)`/`(?=class)` is peeled off next (\u00A78b) and re-wraps\n * whatever shape the remaining base recognizes as.\n */\nexport function parseScanShape(source: string): ScanShape | null {\n const alt = parseAlternation(source)\n if (alt) return alt\n const la = stripTrailingLookahead(source)\n if (la) {\n const inner = parseScanShapeCore(la.base)\n if (!inner) return null\n const operand: CharSet = { ranges: la.ranges, negated: la.classNegated }\n if (!lookaheadUnambiguous(inner, operand, la.negative)) return null\n return { kind: 'lookahead', inner, ranges: la.ranges, classNegated: la.classNegated, negative: la.negative }\n }\n return parseScanShapeCore(source)\n}\n\n/**\n * Split a regex fragment on top-level `|` (outside `[]`/`()`), escape-aware.\n * Unlike `splitTopLevelAlternation` this allows a SINGLE arm (no `|` at all) and\n * does not unwrap an outer group \u2014 it's used to enumerate the arms of a\n * `delimited` body, which may legitimately be one bare arm (`[^x]`). Returns\n * null on unbalanced brackets/parens.\n */\nfunction splitDelimArms(body: string): string[] | null {\n const arms: string[] = []\n let depth = 0\n let last = 0\n let i = 0\n while (i < body.length) {\n const ch = body[i]\n if (ch === '\\\\') { i += 2; continue }\n if (ch === '[') {\n let j = i + 1\n if (body[j] === '^') j++\n while (j < body.length && body[j] !== ']') {\n if (body[j] === '\\\\') j += 2\n else j++\n }\n if (body[j] !== ']') return null\n i = j + 1\n continue\n }\n if (ch === '(') { depth++; i++; continue }\n if (ch === ')') { depth--; if (depth < 0) return null; i++; continue }\n if (ch === '|' && depth === 0) { arms.push(body.slice(last, i)); last = i + 1 }\n i++\n }\n if (depth !== 0) return null\n arms.push(body.slice(last))\n return arms\n}\n\n/**\n * Prove that the `delimited` lowering \u2014 \"scan the raw input to the first full\n * `close` literal, ignoring the body entirely\" \u2014 is EQUIVALENT to the real regex\n * `<open>(?:body)*<close>`. That equivalence holds iff `(?:body)*` can never\n * match a string that contains the `close` literal: then greedy repetition stops\n * exactly before the first `close`, which is where the scan lands too.\n *\n * We only prove this for the two-code-point delimiter-safe idiom (the sole shape that expresses\n * \"any char that doesn't form the close\"):\n *\n * n === 1 (`close` is one char l0): body must be exactly `[^l0]`.\n * n === 2 (`close` is `l0 l1`): body must be exactly `[^l0] | l0(?!l1)`.\n *\n * In both the bulk arm `[^l0]` consumes every char except l0, and the guard arm\n * (n === 2) consumes l0 only when it is NOT followed by l1 \u2014 so the body admits\n * l0 but never the full `l0 l1`, and rejects NOTHING else (a body that excluded\n * some non-close char would stop early while the raw scan skipped ahead to the\n * next close, diverging). Anything outside this template \u2014 an alternation whose\n * arms can consume the close (`z(?:a|[0-2]+)*a`), a bulk class narrower/wider\n * than `[^l0]`, a longer close, extra arms \u2014 is declined, falling through to\n * `RegExp.exec`. Sound-by-construction: we only ever return true for a body we\n * can prove never contains `close`.\n */\nfunction delimitedBodySound(body: string, close: number[]): boolean {\n const l0 = close[0]!\n if (close.length > 2) return false\n const arms = splitDelimArms(body)\n if (!arms) return false\n let bulkSeen = false\n let guardSeen = false\n for (const arm of arms) {\n // Bulk arm: a bare negated class `[^l0]` \u2014 excluded set is exactly {l0}.\n const bulk = /^\\[\\^((?:\\\\.|[^\\]])+)\\]$/.exec(arm)\n if (bulk) {\n if (bulkSeen) return false\n const ranges = parseClassRanges(bulk[1]!)\n if (!ranges || ranges.length !== 1 || ranges[0]![0] !== l0 || ranges[0]![1] !== l0) return false\n bulkSeen = true\n continue\n }\n // Guard arm (n === 2 only): `l0(?!l1)` \u2014 consume l0 unless it starts the close.\n if (close.length === 2 && arm.endsWith(')')) {\n const idx = arm.indexOf('(?!')\n if (idx === -1) return false\n const prefix = literalCodePoints(arm.slice(0, idx))\n const op = parseClassOperand(arm.slice(idx + 3, -1))\n const prefixIsL0 = prefix?.length === 1 && prefix[0] === l0\n const forbidsL1 = op && !op.negated && op.ranges.length === 1 &&\n op.ranges[0]![0] === close[1] && op.ranges[0]![1] === close[1]\n if (!prefixIsL0 || !forbidsL1 || guardSeen) return false\n guardSeen = true\n continue\n }\n return false\n }\n // Require the exact arm set: bulk always; guard iff the close is two chars.\n return bulkSeen && guardSeen === (close.length === 2)\n}\n\n/**\n * Structurally recognize `<openLit>(?:<body>)*<closeLit>` \u2014 literal opener, a\n * single non-capturing `*`-repeated group, literal closer \u2014 and lower it to a\n * `delimited` scan ONLY when `delimitedBodySound` proves the body can't contain\n * the close. Returns null (\u2192 fall through to `seq`/`RegExp.exec`) otherwise.\n */\nfunction parseDelimited(source: string): ScanShape | null {\n // An escape-aware body (a literal `\\\\` in the source \u21D2 string-like) is handled\n // by `parseStringShape`; here \"scan to first close\" would wrongly stop at an\n // escaped delimiter, so decline.\n if (source.includes('\\\\\\\\')) return null\n // Opener: literal chars up to the first unescaped `(`, which must open `(?:`.\n let i = 0\n while (i < source.length && source[i] !== '(') {\n i += source[i] === '\\\\' ? 2 : 1\n }\n if (source[i] !== '(' || source[i + 1] !== '?' || source[i + 2] !== ':') return null\n const openFrag = source.slice(0, i)\n // Balanced scan of the group body to its matching `)`.\n let k = i + 3\n let depth = 1\n while (k < source.length && depth > 0) {\n const ch = source[k]\n if (ch === '\\\\') { k += 2; continue }\n if (ch === '[') {\n let j = k + 1\n if (source[j] === '^') j++\n while (j < source.length && source[j] !== ']') {\n if (source[j] === '\\\\') j += 2\n else j++\n }\n if (source[j] !== ']') return null\n k = j + 1\n continue\n }\n if (ch === '(') depth++\n else if (ch === ')') depth--\n k++\n }\n if (depth !== 0) return null\n const body = source.slice(i + 3, k - 1)\n if (source[k] !== '*') return null\n const closeFrag = source.slice(k + 1)\n const open = literalCodePoints(openFrag)\n const close = literalCodePoints(closeFrag)\n if (!open || !close || !delimitedBodySound(body, close)) return null\n return { kind: 'delimited', open, close }\n}\n\nfunction parseScanShapeCore(source: string): ScanShape | null {\n // [X]+ / [X]* \u2014 a positive char-class run. A negated `[^X]+`/`[^X]*` is left to\n // the general `seq` path (which lowers `[^X]+` and declines zero-width `[^X]*`).\n let m = /^\\[((?:\\\\.|[^\\]])+)\\]([+*])$/.exec(source)\n if (m && !m[1]!.startsWith('^')) {\n const ranges = parseClassRanges(m[1]!)\n return ranges ? { kind: 'chars', ranges, minOne: m[2] === '+' } : null\n }\n // \\d+ / \\w+ / \\s+ / \\d* / \\w* / \\s* \u2014 a bare shorthand-class run.\n m = /^\\\\([dws])([+*])$/.exec(source)\n if (m) {\n return { kind: 'chars', ranges: shorthandRanges(m[1] as 'd' | 'w' | 's'), minOne: m[2] === '+' }\n }\n // <head><tail>* \u2014 identifier run: one head char, then a run of tail chars.\n m = /^(\\[(?:\\\\.|[^\\]])+\\]|\\\\[dws])(\\[(?:\\\\.|[^\\]])+\\]|\\\\[dws])\\*$/.exec(source)\n if (m) {\n const head = classToRanges(m[1]!)\n const tail = classToRanges(m[2]!)\n if (head && tail) return { kind: 'ident', head, tail }\n }\n // <q>(?:[^q\\\\]|\\\\.)*<q> \u2014 a quote-delimited string with escapes.\n const str = parseStringShape(source)\n if (str) return str\n // <lit>[^X]* \u2014 consume a literal opener, then run until a terminator char.\n m = /^(.*?)\\[\\^((?:\\\\.|[^\\]])+)\\]\\*$/.exec(source)\n if (m) {\n const open = literalCodePoints(m[1]!)\n const stop = parseClassRanges(m[2]!)\n if (open && stop) return { kind: 'until', open, stop }\n }\n // <open>(?:\u2026)*<close> \u2014 delimited token scanned to its first close literal.\n // Only lowered when the body provably can't contain the close (see\n // `parseDelimited` / `delimitedBodySound`); any other `X(?:\u2026)*Y` declines here\n // and falls through to the `seq` path / `RegExp.exec`.\n const delim = parseDelimited(source)\n if (delim) return delim\n // General category: a linear chain of literals + char runs (optional prefixes,\n // literal openers, negated runs), lowered only when unambiguously greedy.\n const parts = parseSeqParts(source)\n if (parts && seqIsUnambiguous(parts)) return { kind: 'seq', parts }\n return null\n}\n\n/**\n * Flag-aware wrapper around `parseScanShape`. Lowering to a raw code-point scan\n * assumes default regex semantics, so any flag that changes matching (`i` case\n * folding, `u` surrogate handling, `m`/`s` anchor/dot behavior) disables it.\n * `g`/`y` are stickiness-only and safe.\n */\nexport function scanShapeFromRegex(source: string, flags: string): ScanShape | null {\n if (/[msu]/.test(flags)) return null\n if (/i/.test(flags)) return caseFoldShape(source)\n return parseScanShape(source)\n}\n\n/**\n * Case-insensitive (`/i`) scannable shapes. Beyond a pure case-fold literal\n * (`litFold`), this recognizes a top-level alternation of literals (an ordered\n * `alt` of litFolds \u2014 CSS `(?:and|or)`, `(?:media|container|supports)`), each\n * optionally wrapped in a trailing lookahead boundary (`(?![-\\w])`, `(?=\\()`).\n * That last form is the regex spelling of `makeWord` \u2014 a keyword plus a word\n * boundary \u2014 the common CSS at-rule/keyword dispatcher. Anything else declines\n * (\u2192 `RegExp.exec`); a false read here can only fail to lower, never mis-lower.\n */\nfunction caseFoldShape(source: string): ScanShape | null {\n const la = stripTrailingLookahead(source)\n if (la) {\n const inner = caseFoldLiteralOrAlt(la.base)\n if (!inner) return null\n const operand: CharSet = { ranges: la.ranges, negated: la.classNegated }\n if (!lookaheadUnambiguous(inner, operand, la.negative)) return null\n return { kind: 'lookahead', inner, ranges: la.ranges, classNegated: la.classNegated, negative: la.negative }\n }\n return caseFoldLiteralOrAlt(source)\n}\n\n/** A case-fold literal, or a top-level `a|b|c` alternation of pure literals. */\nfunction caseFoldLiteralOrAlt(source: string): ScanShape | null {\n // `foldEq` only folds ASCII letters (65\u201390 / 97\u2013122). A non-ASCII code point\n // with a Unicode case pair (\u00E9/\u00C9, \u00E4/\u00C4, \u2026) would be emitted as an exact compare\n // and silently miss its alternate case \u2014 a mis-lower, not just a failed lower.\n // Decline those so they fall back to `RegExp.exec` (correct Unicode folding),\n // preserving this file's \"a false read can only fail to lower, never mis-lower\".\n const asciiOnly = (cps: number[]): boolean => cps.every(cp => cp <= 127)\n\n const open = literalCodePoints(source)\n if (open) return asciiOnly(open) ? { kind: 'litFold', open } : null\n // `splitTopLevelAlternation` unwraps the outer group itself, so no pre-strip.\n const arms = splitTopLevelAlternation(source)\n if (!arms || arms.length < 2) return null\n const litArms: ScanShape[] = []\n for (const arm of arms) {\n const cp = literalCodePoints(arm)\n if (!cp || !asciiOnly(cp)) return null\n litArms.push({ kind: 'litFold', open: cp })\n }\n // Ordered choice: each litFold arm case-folds on its own, so skipping the\n // first-char dispatch guard (disjoint:false, firsts:null) is always correct \u2014\n // it just tries arms in order, exactly like regex `|`.\n return { kind: 'alt', arms: litArms, disjoint: false, firsts: litArms.map(() => null) }\n}\n\nexport const classCond = (cVar: string, ranges: Array<[number, number]>): string =>\n ranges\n .map(([lo, hi]) => (lo === hi ? `${cVar} === ${lo}` : `(${cVar} >= ${lo} && ${cVar} <= ${hi})`))\n .join(' || ')\n\n/** Literal-match condition at `base + k` for each code point; uses `firstVar` at offset 0. */\nexport const litCond = (base: string, cps: number[], firstVar?: string): string =>\n cps\n .map((cp, k) =>\n k === 0 && firstVar\n ? `${firstVar} === ${cp}`\n : `input.charCodeAt(${base}${k ? ` + ${k}` : ''}) === ${cp}`,\n )\n .join(' && ')\n\n/** Line-terminator code points `.` does not match (`\\n \\r \\u2028 \\u2029`). */\nexport const LINE_TERMINATORS = [10, 13, 8232, 8233] as const\n\n/** The body-stop chars that abort a string match (excluded set minus quote/backslash). */\nexport function stringHardStop(\n shape: Extract<ScanShape, { kind: 'string' }>,\n): Array<[number, number]> {\n return shape.excluded.filter(\n ([lo, hi]) => !(lo === hi && (lo === shape.quote || lo === BACKSLASH)),\n )\n}\n\n/** Mints a fresh, unique local variable name (`prefix` + counter). */\nexport type Mint = (prefix?: string) => string\n\n/**\n * The SINGLE source of truth for how a scannable shape matches at `start`. Both\n * the terminal emitter and the trivia scan loop consume this, so no context can\n * silently reinterpret an incomplete match (e.g. an unterminated string):\n *\n * - `setup` statements (indented by `ind`) that compute the match.\n * - `ok` a boolean expr: did a token match at `start`? (zero-width for\n * `chars*` counts as a match \u2014 terminals allow it.)\n * - `end` the position AFTER the token. **Invariant:** `end === start`\n * whenever there is no progress (match failed or matched empty),\n * so the trivia loop can gate purely on `end > start`.\n *\n * `firstChar`, when supplied, is an expression already equal to\n * `charCodeAt(start)` (the trivia loop reads it once and shares it).\n */\nexport type ShapeMatch = { setup: string[]; ok: string; end: string }\n\nconst codeAt = (start: string, firstChar?: string): string =>\n firstChar ?? `input.charCodeAt(${start})`\n\n// Dispatch-planning thresholds for a disjoint alt's first-char `switch` \u2014 same\n// tuning as codegen's `planDisjointDispatch` (kept local to avoid a scannable-run\n// \u2192 codegen import cycle): only worth a jump table when every arm keys off a few\n// DISCRETE points; a wide range (`[a-z]+`) would explode into dozens of cases.\nconst ALT_SWITCH_RANGE_LIMIT = 4\nconst ALT_SWITCH_MAX_CASES = 48\nconst ALT_SWITCH_MIN_CASES = 3\n\n/**\n * A `switch` jump table for a *disjoint* alt when every arm's first-set is a few\n * discrete code points (operator/keyword first chars); else `{ kind: 'if' }` to\n * keep the range-comparison `if/else if` chain. Arms are pairwise-disjoint, so\n * each code point maps to exactly one arm.\n */\nfunction planAltSwitch(firsts: Array<CharSet | null>): { kind: 'switch'; cases: number[][] } | { kind: 'if' } {\n const cases: number[][] = []\n let total = 0\n for (const fs of firsts) {\n if (!fs || fs.negated) return { kind: 'if' } // any / negated \u2192 no discrete keys\n const pts: number[] = []\n for (const [lo, hi] of fs.ranges) {\n if (hi - lo + 1 > ALT_SWITCH_RANGE_LIMIT) return { kind: 'if' }\n for (let cp = lo; cp <= hi; cp++) pts.push(cp)\n }\n total += pts.length\n if (total > ALT_SWITCH_MAX_CASES) return { kind: 'if' }\n cases.push(pts)\n }\n return total >= ALT_SWITCH_MIN_CASES ? { kind: 'switch', cases } : { kind: 'if' }\n}\n\nexport function emitShapeMatch(\n shape: ScanShape,\n start: string,\n mint: Mint,\n ind: string,\n firstChar?: string,\n): ShapeMatch {\n if (shape.kind === 'lookahead') {\n const inner = emitShapeMatch(shape.inner, start, mint, ind, firstChar)\n const okV = mint('_ok')\n const endV = mint('_end')\n // `charInClass` folds the operand's OWN `[^\u2026]` negation in; `guardFails`\n // then applies the lookahead's `!`/`=` polarity on top. Zero-width: `end`\n // is always `inner.end` (on success) or `start` (on failure) \u2014 never past\n // where `inner` itself stopped.\n const rawIn = classCond(`input.charCodeAt(${inner.end})`, shape.ranges)\n const charInClass = shape.classNegated ? `!(${rawIn})` : `(${rawIn})`\n const hasMatchingChar = `${inner.end} < input.length && ${charInClass}`\n const guardFails = shape.negative ? hasMatchingChar : `!(${hasMatchingChar})`\n return {\n setup: [\n ...inner.setup,\n `${ind}let ${okV} = ${inner.ok}`,\n `${ind}let ${endV} = ${inner.end}`,\n `${ind}if (${okV} && (${guardFails})) { ${okV} = false; ${endV} = ${start} }`,\n ],\n ok: okV,\n end: endV,\n }\n }\n\n if (shape.kind === 'alt') {\n const okV = mint('_ok')\n const endV = mint('_end')\n const lines: string[] = [`${ind}let ${okV} = false`, `${ind}let ${endV} = ${start}`]\n // Fast path: an alternation of case-fold literals (CSS keyword lists like\n // `@media|@container|@supports`, `even|odd`) \u2192 a `switch` on the first char\n // that jumps straight to the matching group, tails compared with the bit-OR\n // fold. Measured ~2.4x over the ordered if-chain / ~1.4x over per-arm bit-OR.\n // Ordered-choice is preserved: arms are grouped by their FOLDED first code\n // point and, within a group, emitted in source order (first match wins);\n // arms in different groups can't both match a given first char.\n if (shape.arms.length >= 2 && shape.arms.every(a => a.kind === 'litFold' && a.open.length >= 1)) {\n const groups = new Map<number, number[][]>()\n for (const a of shape.arms) {\n const open = (a as Extract<ScanShape, { kind: 'litFold' }>).open\n const f = open[0]!\n const lower = f >= 65 && f <= 90 ? f + 32 : f\n ;(groups.get(lower) ?? groups.set(lower, []).get(lower)!).push(open)\n }\n lines.push(`${ind}if (${start} < input.length) switch (${codeAt(start, firstChar)}) {`)\n for (const [lower, arms] of groups) {\n const labels = lower >= 97 && lower <= 122 ? `case ${lower}: case ${lower - 32}:` : `case ${lower}:`\n lines.push(`${ind} ${labels} {`)\n for (const open of arms) {\n const tail = open.slice(1).map((cp, i) => foldEq(`input.charCodeAt(${start} + ${i + 1})`, cp))\n const cond = tail.length ? ` && ${tail.join(' && ')}` : ''\n lines.push(`${ind} if (${start} + ${open.length} <= input.length${cond}) { ${okV} = true; ${endV} = ${start} + ${open.length}; break }`)\n }\n lines.push(`${ind} break`)\n lines.push(`${ind} }`)\n }\n lines.push(`${ind}}`)\n return { setup: lines, ok: okV, end: endV }\n }\n if (shape.disjoint) {\n // Mutually exclusive first-sets: dispatch straight to the one matching\n // arm, no ordering/backtracking concerns (\u00A77b-style disjoint dispatch). A\n // `switch` jump table when arms key off discrete first chars, else the\n // range-comparison `if/else if` chain (same plan as codegen's choice()).\n const plan = planAltSwitch(shape.firsts)\n if (plan.kind === 'switch') {\n lines.push(`${ind}if (${start} < input.length) switch (${codeAt(start, firstChar)}) {`)\n shape.arms.forEach((arm, k) => {\n const labels = plan.cases[k]!.map(cp => `case ${cp}:`).join(' ')\n const m = emitShapeMatch(arm, start, mint, `${ind} `, firstChar)\n lines.push(`${ind} ${labels} {`)\n lines.push(...m.setup)\n lines.push(`${ind} ${okV} = ${m.ok}`)\n lines.push(`${ind} ${endV} = ${m.ok} ? ${m.end} : ${start}`)\n lines.push(`${ind} break`)\n lines.push(`${ind} }`)\n })\n lines.push(`${ind}}`)\n } else {\n const c0 = codeAt(start, firstChar)\n shape.arms.forEach((arm, k) => {\n const fs = shape.firsts[k]! // non-null whenever `disjoint` is true\n const cond = fs.negated ? `!(${classCond(c0, fs.ranges)})` : `(${classCond(c0, fs.ranges)})`\n const m = emitShapeMatch(arm, start, mint, `${ind} `, firstChar)\n lines.push(`${ind}${k === 0 ? 'if' : 'else if'} (${start} < input.length && ${cond}) {`)\n lines.push(...m.setup)\n lines.push(`${ind} ${okV} = ${m.ok}`)\n lines.push(`${ind} ${endV} = ${m.ok} ? ${m.end} : ${start}`)\n lines.push(`${ind}}`)\n })\n }\n } else {\n // Overlapping first-sets: ordered choice \u2014 try each arm in turn and take\n // the first that succeeds. This is exactly regex `|`'s own semantics:\n // first alternative to match AT ALL wins on ITS OWN greedy length, never\n // compared against a later alternative's (possibly longer) match.\n const lbl = mint('_alt')\n lines.push(`${ind}${lbl}: {`)\n for (const arm of shape.arms) {\n const m = emitShapeMatch(arm, start, mint, `${ind} `, firstChar)\n lines.push(...m.setup)\n lines.push(`${ind} if (${m.ok}) { ${okV} = true; ${endV} = ${m.end}; break ${lbl} }`)\n }\n lines.push(`${ind}}`)\n }\n return { setup: lines, ok: okV, end: endV }\n }\n\n if (shape.kind === 'chars') {\n const cur = mint('_e')\n return {\n setup: [\n `${ind}let ${cur} = ${start}`,\n `${ind}while (${cur} < input.length && (${classCond(`input.charCodeAt(${cur})`, shape.ranges)})) ${cur}++`,\n ],\n // `*` always matches (possibly empty); `+` needs at least one char.\n ok: shape.minOne ? `${cur} > ${start}` : 'true',\n end: cur,\n }\n }\n\n if (shape.kind === 'ident') {\n const cur = mint('_e')\n return {\n setup: [\n `${ind}let ${cur} = ${start}`,\n `${ind}if (${start} < input.length && (${classCond(codeAt(start, firstChar), shape.head)})) {`,\n `${ind} ${cur} = ${start} + 1`,\n `${ind} while (${cur} < input.length && (${classCond(`input.charCodeAt(${cur})`, shape.tail)})) ${cur}++`,\n `${ind}}`,\n ],\n ok: `${cur} > ${start}`,\n end: cur,\n }\n }\n\n if (shape.kind === 'seq') {\n const endV = mint('_e')\n const okV = mint('_ok')\n const runCond = (p: Extract<SeqPart, { part: 'run' }>, at: string) => {\n const c = classCond(`input.charCodeAt(${at})`, p.ranges)\n return p.negated ? `!(${c})` : `(${c})`\n }\n const lines = [`${ind}let ${endV} = ${start}`, `${ind}let ${okV} = false`, `${ind}do {`]\n let first = true\n for (const p of shape.parts) {\n if (p.part === 'lit') {\n const L = p.cps.length\n const cond = litCond(endV, p.cps, first ? firstChar : undefined)\n if (p.optional) {\n lines.push(`${ind} if (${endV} + ${L} <= input.length && (${cond})) ${endV} += ${L}`)\n } else {\n lines.push(`${ind} if (!(${endV} + ${L} <= input.length && (${cond}))) break`)\n lines.push(`${ind} ${endV} += ${L}`)\n }\n } else if (p.part === 'run' && p.max === Infinity) {\n // Unbounded run (`+`/`*`/`{n,}`): greedy scan, then enforce the minimum.\n const s = mint('_s')\n lines.push(`${ind} const ${s} = ${endV}`)\n lines.push(`${ind} while (${endV} < input.length && ${runCond(p, endV)}) ${endV}++`)\n if (p.min === 1) lines.push(`${ind} if (${endV} === ${s}) break`)\n else if (p.min > 1) lines.push(`${ind} if (${endV} - ${s} < ${p.min}) break`)\n } else if (p.part === 'run' && p.max === 1) {\n // Exactly one char: required (min 1) or optional (min 0).\n if (p.min === 1) {\n lines.push(`${ind} if (!(${endV} < input.length && ${runCond(p, endV)})) break`)\n lines.push(`${ind} ${endV}++`)\n } else {\n lines.push(`${ind} if (${endV} < input.length && ${runCond(p, endV)}) ${endV}++`)\n }\n } else if (p.part === 'run') {\n // Bounded counted run `[x]{min,max}` (\u00A78c), max \u2265 2: consume up to `max`\n // occurrences, then require at least `min` (greedy \u2014 sound because\n // `seqIsUnambiguous` proved any wiggle is disjoint from what follows).\n const s = mint('_s')\n lines.push(`${ind} const ${s} = ${endV}`)\n lines.push(`${ind} while (${endV} - ${s} < ${p.max} && ${endV} < input.length && ${runCond(p, endV)}) ${endV}++`)\n if (p.min > 0) lines.push(`${ind} if (${endV} - ${s} < ${p.min}) break`)\n } else {\n // `group` (\u00A78f): the group's own body is just another `ScanShape` \u2014\n // recurse via `emitShapeMatch`, then splice its setup in as the body\n // of a required-once check, an optional take, or a repeat loop.\n const inner = emitShapeMatch(p.inner, endV, mint, `${ind} `, first ? firstChar : undefined)\n if (!p.unbounded) {\n lines.push(...inner.setup)\n if (p.min === 1) {\n lines.push(`${ind} if (!(${inner.ok})) break`)\n lines.push(`${ind} ${endV} = ${inner.end}`)\n } else {\n lines.push(`${ind} if (${inner.ok}) ${endV} = ${inner.end}`)\n }\n } else {\n const progV = mint('_prog')\n lines.push(`${ind} let ${progV} = false`)\n lines.push(`${ind} while (true) {`)\n lines.push(...inner.setup)\n lines.push(`${ind} if (!(${inner.ok})) break`)\n lines.push(`${ind} ${endV} = ${inner.end}`)\n lines.push(`${ind} ${progV} = true`)\n lines.push(`${ind} }`)\n if (p.min === 1) lines.push(`${ind} if (!${progV}) break`)\n }\n }\n first = false\n }\n lines.push(`${ind} ${okV} = true`)\n lines.push(`${ind}} while (false)`)\n lines.push(`${ind}if (!${okV}) ${endV} = ${start}`)\n return { setup: lines, ok: okV, end: endV }\n }\n\n if (shape.kind === 'litFold') {\n const openLen = shape.open.length\n const endV = mint('_end')\n const checks = shape.open.map((cp, k) => {\n const cVar = k === 0 && firstChar ? firstChar : `input.charCodeAt(${start} + ${k})`\n return foldEq(cVar, cp)\n })\n return {\n setup: [\n `${ind}let ${endV} = ${start}`,\n `${ind}if (${start} + ${openLen} <= input.length && (${checks.join(' && ')})) ${endV} = ${start} + ${openLen}`,\n ],\n ok: `${endV} > ${start}`,\n end: endV,\n }\n }\n\n if (shape.kind === 'until') {\n const j = mint('_j')\n const openLen = shape.open.length\n const openChk = openLen === 1\n ? `${codeAt(start, firstChar)} === ${shape.open[0]}`\n : litCond(start, shape.open, firstChar)\n return {\n setup: [\n `${ind}let ${j} = ${start}`,\n `${ind}if (${start} + ${openLen} <= input.length && (${openChk})) {`,\n `${ind} ${j} = ${start} + ${openLen}`,\n `${ind} while (${j} < input.length && !(${classCond(`input.charCodeAt(${j})`, shape.stop)})) ${j}++`,\n `${ind}}`,\n ],\n // An open-until-terminator always completes (stop char or EOF), so a matched\n // open literal is a full match; `end === start` iff the open didn't match.\n ok: `${j} > ${start}`,\n end: j,\n }\n }\n\n if (shape.kind === 'string') {\n const okV = mint('_ok')\n const endV = mint('_end')\n const i = mint('_i')\n const c2 = mint('_c')\n const hard = stringHardStop(shape)\n const ltLines = shape.escLineTerm\n ? []\n : (() => {\n const c3 = mint('_c')\n return [\n `${ind} const ${c3} = input.charCodeAt(${i} + 1)`,\n `${ind} if (${LINE_TERMINATORS.map(t => `${c3} === ${t}`).join(' || ')}) break`,\n ]\n })()\n return {\n setup: [\n `${ind}let ${okV} = false`,\n `${ind}let ${endV} = ${start}`,\n `${ind}if (${start} < input.length && (${codeAt(start, firstChar)}) === ${shape.quote}) {`,\n `${ind} let ${i} = ${start} + 1`,\n `${ind} while (${i} < input.length) {`,\n `${ind} const ${c2} = input.charCodeAt(${i})`,\n `${ind} if (${c2} === ${shape.quote}) { ${okV} = true; ${endV} = ${i} + 1; break }`,\n `${ind} if (${c2} === ${BACKSLASH}) {`,\n `${ind} if (${i} + 1 >= input.length) break`,\n ...ltLines,\n `${ind} ${i} += 2`,\n `${ind} continue`,\n `${ind} }`,\n ...(hard.length ? [`${ind} if (${classCond(c2, hard)}) break`] : []),\n `${ind} ${i}++`,\n `${ind} }`,\n `${ind}}`,\n ],\n ok: okV,\n end: endV,\n }\n }\n\n // delimited: <open>\u2026<close>, requires the close literal (unclosed \u21D2 no match).\n const j = mint('_j')\n const endV = mint('_end')\n const openLen = shape.open.length\n const closeLen = shape.close.length\n const openChk = openLen === 1\n ? `${codeAt(start, firstChar)} === ${shape.open[0]}`\n : litCond(start, shape.open, firstChar)\n const closeChk = litCond(j, shape.close)\n return {\n setup: [\n `${ind}let ${j} = ${start}`,\n `${ind}let ${endV} = ${start}`,\n `${ind}if (${start} + ${openLen} <= input.length && (${openChk})) {`,\n `${ind} ${j} = ${start} + ${openLen}`,\n `${ind} while (${j} + ${closeLen - 1} < input.length && !(${closeChk})) ${j}++`,\n `${ind} if (${j} + ${closeLen} <= input.length && (${closeChk})) ${endV} = ${j} + ${closeLen}`,\n `${ind}}`,\n ],\n ok: `${endV} > ${start}`,\n end: endV,\n }\n}\n\n/**\n * One trivia-loop branch for a shape, dispatched on the current char `c`\n * (= charCodeAt(_e)). Advances `_e` and `continue`s ONLY on real progress\n * (`end > _e`) \u2014 an unterminated delimited/string token leaves `end === _e`, so\n * the loop stops there exactly as the interpreter's `oneOrMore(choice(\u2026))` would.\n */\nexport function scanBranch(shape: ScanShape, mint: Mint): string {\n const m = emitShapeMatch(shape, '_e', mint, ' ', 'c')\n return [...m.setup, ` if (${m.end} > _e) { _e = ${m.end}; continue }`].join('\\n')\n}\n\n/**\n * A labeled branch: match one token and, on progress, log its [start, end,\n * kindIndex] trivia chunk. Same completion semantics as scanBranch.\n */\nexport function scanBranchLabeled(shape: ScanShape, kindIndex: number, label: string, mint: Mint): string {\n const m = emitShapeMatch(shape, '_e', mint, ' ', 'c')\n return [\n ...m.setup,\n ` if (${m.end} > _e) {`,\n ` if (_cap) {`,\n ` if (_ctx._triviaLog !== undefined) _ctx._triviaLog.push(_e, ${m.end}, ${kindIndex})`,\n ` const _rk = _ctx._rootTriviaCapture === false || _ctx._rootTriviaLog === undefined ? -1 : (_ctx._rootTriviaKindIndex?.[${JSON.stringify(label)}] ?? -1)`,\n ` if (_rk >= 0) _ctx._rootTriviaLog.push(${SELECTED_ROOT_OWNED_RANGE_PLACEHOLDER}, _e, ${m.end}, _rk)`,\n ` if (_cap === 1 && _ctx._cstTriviaLog !== undefined && _ctx.captureTrivia && (_ctx._triviaCaptureMask === undefined || (_ctx._triviaCaptureMask & ${1 << kindIndex}))) _ctx._cstTriviaLog.push(_e, ${m.end}, _ctx._cstRawChildren ? _ctx._cstRawChildren.length : 0, ${kindIndex})`,\n ` }`,\n ` _e = ${m.end}`,\n ` continue`,\n ` }`,\n ].join('\\n')\n}\n", "import type { Combinator } from '../types.ts'\nimport { getCoreRegexDef } from '../combinators/choice.ts'\nimport type { LabeledTriviaSpec } from '../cst/trivia-kinds.ts'\nimport { SELECTED_ROOT_STRIDE } from '../cst/trivia-entries.ts'\nimport { analyzeLabeledTrivia } from '../cst/trivia-kinds.ts'\nimport { type ScanShape, type Mint, scanShapeFromRegex, scanBranch, scanBranchLabeled } from './scannable-run.ts'\n\n/** Fresh, collision-free local names for one generated scan function. */\nfunction makeMint(): Mint {\n let n = 0\n return (prefix = '_v') => `${prefix}${n++}`\n}\n\nfunction unwrapTrivia(p: Combinator<unknown>): Combinator<unknown> {\n let cur = p\n while (cur._def.tag === 'trivia') cur = cur._def.parser\n return cur\n}\n\nfunction oneOrMoreInner(p: Combinator<unknown>): Combinator<unknown> | null {\n const d = p._def\n if (d.tag === 'oneOrMore') return d.parser\n if (d.tag === 'many' && d.min >= 1) return d.parser\n return null\n}\n\nfunction choiceArms(p: Combinator<unknown>): Combinator<unknown>[] | null {\n if (p._def.tag === 'choice') return p._def.parsers\n return null\n}\n\n/** The scannable shape of one arm (a regex), or null if it isn't scannable. */\nfunction armShape(arm: Combinator<unknown>): ScanShape | null {\n const d = getCoreRegexDef(arm)\n return d ? scanShapeFromRegex(d.source, d.flags) : null\n}\n\n/**\n * A trivia parser that lowers to a hand-rolled char-scan loop: `oneOrMore(choice(\n * \u2026))` (or `many`, min\u22651) where EVERY arm is a scannable shape (a `[X]+` run, a\n * `<lit>[^X]*` open-until-terminator, or a `<open>(?:\u2026)*<close>` delimited token\n * \u2014 see scannable-run.ts). Returns the per-arm shapes, or a single-element list\n * for a bare scannable regex, or null (\u2192 caller falls back to the regex/generic\n * trivia path). A single alternation regex is NOT scannable (one exec matches one\n * arm per call, defeating the loop).\n */\nexport function analyzeTriviaFastPath(trivia: Combinator<unknown>): ScanShape[] | null {\n const core = unwrapTrivia(trivia)\n\n const directDef = getCoreRegexDef(core)\n if (directDef) {\n const shape = scanShapeFromRegex(directDef.source, directDef.flags)\n return shape && shape.kind === 'chars' ? [shape] : null\n }\n\n const inner = oneOrMoreInner(core)\n if (!inner) return null\n\n const innerShape = armShape(inner)\n if (innerShape) return innerShape.kind === 'chars' ? [innerShape] : null\n\n const arms = choiceArms(inner)\n if (!arms || arms.length < 2) return null\n\n const shapes: ScanShape[] = []\n for (const arm of arms) {\n const shape = armShape(arm)\n if (!shape) return null\n shapes.push(shape)\n }\n return shapes\n}\n\nconst CAP_RECORD = [\n ` if (_cap && _e > _pos) {`,\n ` if (_ctx._triviaLog !== undefined) _ctx._triviaLog.push(_pos, _e)`,\n ` if (_cap === 1 && _ctx._cstTriviaLog !== undefined && _ctx.captureTrivia) _ctx._cstTriviaLog.push(_pos, _e, _ctx._cstRawChildren ? _ctx._cstRawChildren.length : 0)`,\n ` }`,\n].join('\\n')\n\nconst SELECTED_ROOT_FINISH = [\n ` if (_cap && _ctx._rootTriviaCapture !== false && _ctx._rootTriviaLog !== undefined && _ctx._rootTriviaLog.length !== _rootMark) {`,\n ` for (let _ri = _rootMark; _ri < _ctx._rootTriviaLog.length; _ri += ${SELECTED_ROOT_STRIDE}) { _ctx._rootTriviaLog[_ri] = _pos; _ctx._rootTriviaLog[_ri + 1] = _e }`,\n ` }`,\n].join('\\n')\n\n/** One char-scan loop carrying a branch per scannable shape, dispatched on `c`. */\nfunction composeFastLoop(shapes: ScanShape[]): string {\n const mint = makeMint()\n return [\n ` while (_e < input.length) {`,\n ` const c = input.charCodeAt(_e)`,\n ...shapes.map(s => scanBranch(s, mint)),\n ` break`,\n ` }`,\n ].join('\\n')\n}\n\n/** Emit a specialized `_tfN` that skips (unlabeled) trivia via a char-scan loop. */\nexport function buildFastTriviaFnDecl(fnName: string, shapes: ScanShape[]): string {\n return [\n `function ${fnName}(input, _pos, _ctx, _cap) {`,\n ` let _e = _pos`,\n composeFastLoop(shapes),\n CAP_RECORD,\n ` return _e`,\n `}`,\n ].join('\\n')\n}\n\n/**\n * A LABELED trivia parser whose every arm is scannable \u2192 per-arm shape + kind\n * index, or null. Same recognition as analyzeTriviaFastPath, but keyed by the\n * label table so the fast loop can log each chunk's category. It accepts any\n * structurally scannable arm set / arm count; labels do not affect recognition.\n */\nexport function analyzeLabeledScannableRun(\n trivia: Combinator<unknown>,\n): Array<{ shape: ScanShape; kindIndex: number; label: string }> | null {\n const spec = analyzeLabeledTrivia(trivia)\n if (!spec) return null\n const out: Array<{ shape: ScanShape; kindIndex: number; label: string }> = []\n for (const arm of spec.arms) {\n const d = getCoreRegexDef(arm.parser)\n const shape = d ? scanShapeFromRegex(d.source, d.flags) : null\n if (!shape) return null\n out.push({ shape, kindIndex: arm.kindIndex, label: arm.label })\n }\n return out\n}\n\n/** Emit a labeled scannable trivia `_tfN`: char-scan loop with per-chunk kind capture. */\nexport function buildLabeledScannableTriviaFnDecl(\n fnName: string,\n arms: ReadonlyArray<{ shape: ScanShape; kindIndex: number; label: string }>,\n): string {\n const mint = makeMint()\n return [\n `function ${fnName}(input, _pos, _ctx, _cap) {`,\n ` let _e = _pos`,\n ` const _rootMark = _cap && _ctx._rootTriviaLog !== undefined ? _ctx._rootTriviaLog.length : 0`,\n ` while (_e < input.length) {`,\n ` const c = input.charCodeAt(_e)`,\n ...arms.map(a => scanBranchLabeled(a.shape, a.kindIndex, a.label, mint)),\n ` break`,\n ` }`,\n SELECTED_ROOT_FINISH,\n ` return _e`,\n `}`,\n ].join('\\n')\n}\n\n/** Labeled trivia with regex arms \u2014 per-chunk kind capture in compiled output. */\nexport function buildLabeledRegexTriviaFnDecl(\n fnName: string,\n spec: LabeledTriviaSpec,\n reNames: string[],\n): string {\n const tryArms = spec.arms.map((arm, i) => {\n const re = reNames[i]!\n const k = arm.kindIndex\n return [\n ` ${re}.lastIndex = _e`,\n ` const _m${i} = ${re}.exec(input)`,\n ` if (_m${i} && _m${i}.index === _e) {`,\n ` const _ce = _e + _m${i}[0].length`,\n ` if (_cap) {`,\n ` if (_ctx._triviaLog !== undefined) _ctx._triviaLog.push(_e, _ce, ${k})`,\n ` const _rk${i} = _ctx._rootTriviaCapture === false || _ctx._rootTriviaLog === undefined ? -1 : (_ctx._rootTriviaKindIndex?.[${JSON.stringify(arm.label)}] ?? -1)`,\n ` if (_rk${i} >= 0) _ctx._rootTriviaLog.push(0, 0, _e, _ce, _rk${i})`,\n ` if (_cap === 1 && _ctx._cstTriviaLog !== undefined && _ctx.captureTrivia && (_ctx._triviaCaptureMask === undefined || (_ctx._triviaCaptureMask & ${1 << k}))) _ctx._cstTriviaLog.push(_e, _ce, _ctx._cstRawChildren ? _ctx._cstRawChildren.length : 0, ${k})`,\n ` }`,\n ` _e = _ce`,\n ` _matched = true`,\n ` continue`,\n ` }`,\n ].join('\\n')\n }).join('\\n')\n\n return [\n `function ${fnName}(input, _pos, _ctx, _cap) {`,\n ` let _e = _pos`,\n ` const _rootMark = _cap && _ctx._rootTriviaLog !== undefined ? _ctx._rootTriviaLog.length : 0`,\n ` while (_e < input.length) {`,\n ` let _matched = false`,\n tryArms,\n ` if (!_matched) break`,\n ` }`,\n SELECTED_ROOT_FINISH,\n ` return _e`,\n `}`,\n ].join('\\n')\n}\n\nexport function labeledTriviaRegexArms(trivia: Combinator<unknown>): LabeledTriviaSpec | null {\n const spec = analyzeLabeledTrivia(trivia)\n if (!spec) return null\n for (const arm of spec.arms) {\n if (!getCoreRegexDef(arm.parser)) return null\n }\n return spec\n}\n\n/** Labeled trivia via per-arm runtime parsers (non-regex or mixed arms). */\nexport function buildLabeledRuntimeTriviaFnDecl(\n fnName: string,\n spec: LabeledTriviaSpec,\n rpStartIndex: number,\n): string {\n const tryArms = spec.arms.map((arm, i) => {\n const k = arm.kindIndex\n const ri = rpStartIndex + i\n return [\n ` const _r${i} = _rp[${ri}].parse(input, _e, _ctx)`,\n ` if (_r${i}.ok && _r${i}.span.end > _e) {`,\n ` const _ce = _r${i}.span.end`,\n ` if (_cap) {`,\n ` if (_ctx._triviaLog !== undefined) _ctx._triviaLog.push(_e, _ce, ${k})`,\n ` const _rk${i} = _ctx._rootTriviaCapture === false || _ctx._rootTriviaLog === undefined ? -1 : (_ctx._rootTriviaKindIndex?.[${JSON.stringify(arm.label)}] ?? -1)`,\n ` if (_rk${i} >= 0) _ctx._rootTriviaLog.push(0, 0, _e, _ce, _rk${i})`,\n ` if (_cap === 1 && _ctx._cstTriviaLog !== undefined && _ctx.captureTrivia && (_ctx._triviaCaptureMask === undefined || (_ctx._triviaCaptureMask & ${1 << k}))) _ctx._cstTriviaLog.push(_e, _ce, _ctx._cstRawChildren ? _ctx._cstRawChildren.length : 0, ${k})`,\n ` }`,\n ` _e = _ce`,\n ` _matched = true`,\n ` continue`,\n ` }`,\n ].join('\\n')\n }).join('\\n')\n\n return [\n `function ${fnName}(input, _pos, _ctx, _cap) {`,\n ` let _e = _pos`,\n ` const _rootMark = _cap && _ctx._rootTriviaLog !== undefined ? _ctx._rootTriviaLog.length : 0`,\n ` while (_e < input.length) {`,\n ` let _matched = false`,\n tryArms,\n ` if (!_matched) break`,\n ` }`,\n SELECTED_ROOT_FINISH,\n ` return _e`,\n `}`,\n ].join('\\n')\n}\n", "import type { ParserDef } from '../types.ts'\nimport { recordDegradation } from './degradation.ts'\n\n/**\n * Per-node children/fields/raw/trivia/state capture is dead work when the build\n * never declares the corresponding formal param. This module derives a build's\n * *confirmed* formal-parameter arity so the compiler and macro can elide their\n * direct-AST-only CST collectors without changing structural/CST output.\n *\n * Conservative by construction: any source we can't confidently parse \u2014 rest params,\n * destructuring, `arguments`, an unrecognized shape \u2014 yields `null` (arity unknown),\n * and callers KEEP full capture. We only ever return a number when the parameter list\n * is a plain comma-separated list of simple identifiers.\n */\n\ntype NodeDef = Extract<ParserDef, { tag: 'node' }>\n\n/**\n * Is a positioned-CST host installed for this parse?\n *\n * `cstBuildHost` (and the language-service hosts) mark themselves with\n * `_parsemanCstOutput`. That flag is what re-routes a node with its OWN direct builder\n * through the host \u2014 and therefore what makes the direct builder's formal arity the\n * WRONG basis for eliding capture, since the consumer is no longer that builder.\n *\n * The COMPILED engine answers this at compile time (`hostMode`, 0.37.0). The interpreter\n * has no compile step, so it asks per parse.\n */\nexport function cstOutputHost(build: unknown): boolean {\n return (build as { _parsemanCstOutput?: true } | undefined)?._parsemanCstOutput === true\n}\n\n/**\n * \u2500\u2500 THE ONE RULE IN THIS FILE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * A WRONG NUMBER IS THE BUG. `null` (unknown) IS ALWAYS ACCEPTABLE.\n *\n * `null` fails open: the caller keeps every capture tier and records a degradation, so\n * the output is correct and the cost is visible. A wrong NUMBER silently drops capture\n * tiers \u2014 fields vanish from the AST with no diagnostic, because a confident answer\n * never reaches `recordDegradation`. Every branch below that cannot decide with\n * certainty must therefore return `null`, never a guess.\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n */\n\n/** `x => ...` \u2014 a single unparenthesised identifier parameter. */\nconst SINGLE_IDENT_ARROW_RE = /^[A-Za-z_$][\\w$]*\\s*=>/\n\n/** Start of a formal-parameter list: `(`, or `function name?(`. */\nconst PARAM_LIST_OPEN_RE = /^(?:function\\b[^(]*)?\\(/\n\n/**\n * A host builtin, a `Function.prototype.bind` result and a `Proxy` all stringify to\n * `function () { [native code] }`. That has an EMPTY parameter list which says nothing\n * whatever about the underlying function's arity \u2014 reading it as arity 0 is a confident\n * lie that silently drops every capture tier. None of those are documented reducer\n * shapes and parseman does not owe them support; it owes them an honest `null`.\n */\nconst NATIVE_CODE_RE = /\\{\\s*\\[native code\\]\\s*\\}/\n\n/** Identifier head of a formal param, with its optional `?`. */\nconst PARAM_HEAD_RE = /^[A-Za-z_$][\\w$]*\\s*\\??\\s*/\n\n/**\n * Confirmed count of simple formal parameters the build declares, or `null` when the\n * source can't be parsed into a plain identifier list (\u2192 caller keeps full capture).\n */\nexport function confirmedBuildArity(src: string): number | null {\n const s = src.trim()\n\n // Unreadable source \u2192 unknown. Checked FIRST: its parameter list is empty, and the\n // empty-list answer below would otherwise report a confident 0.\n if (NATIVE_CODE_RE.test(s)) return null\n\n // A stray `arguments` reference defeats formal-arity reasoning entirely; only a\n // full-source scan can rule it out. Cheap guard against the obvious cases.\n //\n // Checked BEFORE the empty-parameter-list answer below. It used to sit after it, which\n // made it unreachable for exactly the shape it matters most for: `function () { return\n // arguments[0] }` has an empty formal list and real arity \u2265 1, and was reported 0.\n if (/\\barguments\\b/.test(s)) return null\n\n // Single-ident arrow: `x => ...` \u2192 exactly one param.\n if (SINGLE_IDENT_ARROW_RE.test(s)) return 1\n\n const inner = paramListText(s)\n if (inner === null) return null\n if (inner.trim() === '') return 0\n\n const parts = splitTopLevel(inner)\n if (parts === null) return null\n\n // Reject anything that isn't a flat list of simple identifiers. A rest param\n // (`...args`), destructuring (`{a}`, `[a]`), or default (`a = 1`) all appear here.\n for (const part of parts) {\n if (!isConfirmableParam(part.trim())) return null\n }\n\n return parts.length\n}\n\n/**\n * The text between a build's parameter parentheses, or `null` when it cannot be located\n * with certainty.\n *\n * Found by a BALANCED scan rather than a character class. The previous `[^)]*` stopped at\n * the first `)`, which in ordinary TypeScript is the one inside a function-typed\n * annotation: `(children: (n: N) => N, fields) => \u2026` yielded `children: (n: N` and\n * reported arity 1 instead of 2 \u2014 a silent under-capture on precisely the typed shape the\n * docs tell authors to write.\n */\nfunction paramListText(s: string): string | null {\n const open = PARAM_LIST_OPEN_RE.exec(s)\n if (!open) return null\n const start = open[0].length\n const end = matchingParen(s, start)\n if (end === null) return null\n // An arrow's list must be followed by `=>`; a `function`'s is followed by its body.\n // Without this a parenthesised expression could be read as a parameter list.\n if (!s.startsWith('function') && !/^\\s*=>/.test(s.slice(end + 1))) return null\n return s.slice(start, end)\n}\n\n/** Index of the `)` closing the list opened just before `start`, else `null`. */\nfunction matchingParen(s: string, start: number): number | null {\n let depth = 0\n for (let i = start; i < s.length; i++) {\n const c = s[i]!\n if (c === '\"' || c === \"'\" || c === '`') {\n const close = skipString(s, i)\n if (close === null) return null\n i = close\n continue\n }\n if (c === '(' || c === '[' || c === '{') depth++\n else if (c === ']' || c === '}') { if (--depth < 0) return null }\n else if (c === ')') { if (depth === 0) return i; depth-- }\n }\n return null\n}\n\n/** Index of the closing quote of the literal opened at `open`, else `null`. */\nfunction skipString(s: string, open: number): number | null {\n const quote = s[open]!\n for (let i = open + 1; i < s.length; i++) {\n if (s[i] === '\\\\') { i++; continue }\n if (s[i] === quote) return i\n }\n return null\n}\n\n/**\n * Split a parameter list on TOP-LEVEL commas, or `null` if it cannot be split with\n * certainty.\n *\n * Tracks `()`/`[]`/`{}` AND `<>`, because a comma inside type arguments belongs to the\n * annotation, not the list: a plain `,`-split turned `(a: Map<K, V>, b) => \u2026` into three\n * fragments. `=>` is consumed as a unit so the `>` of an arrow type is not mistaken for\n * the close of a type-argument list.\n */\nfunction splitTopLevel(inner: string): string[] | null {\n const parts: string[] = []\n let depth = 0\n let angle = 0\n let last = 0\n for (let i = 0; i < inner.length; i++) {\n const c = inner[i]!\n if (c === '=' && inner[i + 1] === '>') { i++; continue }\n if (c === '\"' || c === \"'\" || c === '`') {\n const close = skipString(inner, i)\n if (close === null) return null\n i = close\n continue\n }\n if (c === '(' || c === '[' || c === '{') depth++\n else if (c === ')' || c === ']' || c === '}') { if (--depth < 0) return null }\n else if (c === '<') angle++\n else if (c === '>') { if (--angle < 0) return null }\n else if (c === ',' && depth === 0 && angle === 0) { parts.push(inner.slice(last, i)); last = i + 1 }\n }\n if (depth !== 0 || angle !== 0) return null\n parts.push(inner.slice(last))\n return parts\n}\n\n/**\n * A confirmable formal param: a plain identifier, optionally `?`-optional and optionally\n * carrying a TypeScript type annotation (`c`, `c?`, `c: any`, `c?: Map<K, V>`, `c: (n: N)\n * => N`). The build source is sliced verbatim from the (possibly TS) grammar source, so\n * typed params must be recognized or every typed grammar keeps full capture.\n *\n * A DEFAULT (`a = 1`, `a: number = 1`) stays unconfirmed: the parameter is optional, so\n * the formal count overstates what the reducer is guaranteed to receive.\n */\nfunction isConfirmableParam(part: string): boolean {\n const head = PARAM_HEAD_RE.exec(part)\n if (!head) return false // rest `...a`, destructuring `{a}` / `[a]`\n const rest = part.slice(head[0].length)\n if (rest === '') return true\n if (rest[0] !== ':') return false // `a = 1`, or anything else we cannot read\n return !hasDefaultAssign(rest.slice(1))\n}\n\n/** An `=` that is not part of `=>`, `>=`, `<=`, `==` or `!=` \u2014 i.e. a default value. */\nfunction hasDefaultAssign(annotation: string): boolean {\n for (let i = 0; i < annotation.length; i++) {\n if (annotation[i] !== '=') continue\n if (annotation[i + 1] === '>' || annotation[i + 1] === '=') { i++; continue }\n const prev = annotation[i - 1]\n if (prev === '<' || prev === '>' || prev === '!' || prev === '=') continue\n return true\n }\n return false\n}\n\n/**\n * The source a def's arity/shape analysis must read.\n *\n * `buildSrc` is the source text of the EXPRESSION written at the `node(...)` call\n * site. When the reducer is passed as a bare identifier \u2014 `node('Foo', p, { build:\n * foldOperation })` \u2014 that text is just `\"foldOperation\"`, which matches no parameter\n * list and used to fail open into all five capture tiers, silently. The macro plugin\n * already holds the whole module's AST, so it resolves such an identifier to its\n * module-scope declaration and parks that declaration's source here. `buildSigSrc` is\n * ANALYSIS-ONLY: it is never emitted, so the generated builder reference is unchanged.\n */\nexport function buildAnalysisSrc(def: NodeDef): string {\n return def.buildSigSrc ?? def.buildSrc ?? def.build!.toString()\n}\n\n/**\n * Why a parameter list could not be read \u2014 the actionable half of the diagnostic.\n *\n * Only genuinely undecidable shapes reach here. The resolver (`plugin/reducer-resolver.\n * ts`) handles named reducers, cross-module imports, namespace members, aliases,\n * non-reassigned `let`/`var`, defaults and destructuring; a decline from it carries a\n * machine-readable reason, which is what the author needs in order to fix or declare it.\n */\nconst RESOLVER_REASONS: Record<string, string> = {\n 'rest-parameter': 'its parameter list uses a rest parameter, so the declared arity is unbounded',\n 'arguments': 'its body references `arguments`',\n 'reassigned': 'the binding it names is reassigned, so the function read here is not decidable',\n 'not-a-function': 'the binding it names is not a function declaration',\n 'unresolved-import': 'its module could not be resolved or parsed',\n 'not-found': 'the name did not resolve to any binding',\n 'computed': 'it is a computed expression',\n 'foreign-source': 'it is named in a module the resolver was never told about, so its '\n + 'offsets index no scope tree the resolver holds',\n 'ambiguous-source': 'two distinct registered modules hold byte-identical text, so that '\n + 'text no longer names the module its offsets index',\n}\n\nfunction unconfirmableReason(def: NodeDef, src: string): string {\n const declared = def.buildArityUnresolved\n if (declared !== undefined && RESOLVER_REASONS[declared]) return RESOLVER_REASONS[declared]!\n const s = src.trim()\n const params = s.slice(0, s.indexOf(')') + 1)\n if (params.includes('...')) return RESOLVER_REASONS['rest-parameter']!\n if (/\\barguments\\b/.test(s)) return RESOLVER_REASONS['arguments']!\n if (/^[A-Za-z_$][\\w$]*(\\s*\\.\\s*[A-Za-z_$][\\w$]*)?$/.test(s)) {\n return 'it names a binding this build could not resolve to a function declaration'\n }\n return 'its parameter list could not be parsed'\n}\n\n/**\n * Confirmed formal arity for a node def, reporting once when it cannot be confirmed.\n *\n * Order of authority:\n * 1. `node(..., { buildArity })` \u2014 the author DECLARED it. Nothing overrides that.\n * 2. `def.buildArity` as resolved by the macro's reducer resolver (real scope analysis\n * and cross-module import following).\n * 3. Reading the parameter list out of whatever source we have.\n *\n * Fail-open is the correct BEHAVIOR \u2014 capturing too much is safe, capturing too little\n * is a correctness bug. Fail-open with no diagnostic was the defect. But a diagnostic is\n * the right answer only for the genuinely undecidable; for everything a static analysis\n * can decide, the right answer is to decide it, which is why (2) exists and why (1) gives\n * the author a way out of (3) entirely.\n */\nexport function confirmedArityForDef(def: NodeDef): number | null {\n if (def.buildArity !== undefined) return def.buildArity\n const src = buildAnalysisSrc(def)\n const arity = confirmedBuildArity(src)\n if (arity !== null) return arity\n const subject = `build reducer \\`${(def.buildSrc ?? '<runtime fn>').trim().split('\\n')[0]!.slice(0, 60)}\\``\n recordDegradation({\n code: 'build-arity-unconfirmed',\n severity: 'warn',\n where: `node(\"${def.type ?? '<inferred>'}\")`,\n subject,\n fellBackTo: `could not confirm its declared arity \u2014 ${unconfirmableReason(def, src)} \u2014 `\n + 'so this node captures children, fields and raw children, logs trivia, and clones `_ctx.state` on every match',\n otherwise: 'only the tiers the reducer actually declares would be captured '\n + '(arity >= 1 children, >= 2 fields, >= 4 raw, >= 5 trivia, >= 6 state). '\n + 'Declare it with `node(..., { buildArity: n })` if it cannot be derived',\n })\n return null\n}\n\n/** Build reads its 1st (`children`) arg? Unknown/unparseable \u2192 true (keep capture). */\nexport function buildReadsChildren(def: NodeDef): boolean {\n if (!def.build) return true // structural node: CST output always owns children\n const arity = confirmedArityForDef(def)\n if (arity === null) return true\n return arity >= 1\n}\n\n/** Build reads its 4th (`rawChildren`) arg? Unknown/unparseable \u2192 true (keep capture). */\nexport function buildReadsRaw(def: NodeDef): boolean {\n if (!def.build) return true // structural node: host/default CST may read raw children\n const arity = confirmedArityForDef(def)\n if (arity === null) return true\n return arity >= 4\n}\n\n/** Build reads the 5th (triviaLog) arg? Unknown/unparseable \u2192 true (keep capture). */\nexport function buildReadsTrivia(def: NodeDef): boolean {\n if (!def.build) return true // structural node: host may read trivia \u2014 keep capture\n const arity = confirmedArityForDef(def)\n if (arity === null) return true\n return arity >= 5\n}\n\n/** Build reads the 6th (state) arg? Unknown/unparseable \u2192 true (keep state clone). */\nexport function buildReadsState(def: NodeDef): boolean {\n if (!def.build) return true // structural node: host may read state \u2014 keep clone\n const arity = confirmedArityForDef(def)\n if (arity === null) return true\n return arity >= 6\n}\n", "import type { ParserDef } from '../types.ts'\nimport { buildAnalysisSrc } from './build-arity.ts'\nimport { recordDegradation } from './degradation.ts'\n\n/**\n * A formal param, optionally carrying a TypeScript annotation.\n *\n * The macro path TS-strips `buildSrc` before it reaches here, so a bare `\\w+` was\n * *usually* enough \u2014 but \"usually\" is exactly the failure class this module is being\n * audited for: a `mk` reducer spelled with a type annotation that survives (a runtime\n * `compile()` over untranspiled source, a hand-written IR string) silently loses the\n * inline-`mk` fast path and pays a `_build[n](...)` call on every match, with nothing\n * said. Admitting the annotation removes the class rather than relying on an upstream\n * pass to have removed it. No `=` (default) \u2014 a default is not a plain positional param.\n */\n/** Optional `?` and/or `: T` suffix on a formal param. */\nconst ANN = String.raw`\\s*\\??\\s*(?::[^,)=]+)?`\n/** A whole ignorable param (the `fields` slot, whose name the shape never re-reads). */\nconst ANY_P = String.raw`\\w+${ANN}`\n\n/** `(c, f, s, r, tl) => mk('Type', c, r, s, tl)` \u2014 CSS perf regression builder shape. */\nconst MK_BUILD_RE = new RegExp(\n String.raw`^\\(\\s*(\\w+)${ANN}\\s*,\\s*${ANY_P}\\s*,\\s*(\\w+)${ANN}\\s*,\\s*(\\w+)${ANN}\\s*,\\s*(\\w+)${ANN}\\s*\\)\\s*=>\\s*mk\\s*\\(\\s*(['\"])([^'\"]+)\\5\\s*,\\s*\\1\\s*,\\s*\\3\\s*,\\s*\\2\\s*,\\s*\\4\\s*\\)\\s*$`,\n)\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Same shape, but the type is named by an IDENTIFIER in BOTH positions rather than by a\n * string literal.\n *\n * `node(type, body, (c, f, s, r, tl) => mk(type, c, r, s, tl))` inside a factory is the\n * ordinary way to write a family of nodes \u2014 jess's `less` grammar does it at 31 sites \u2014\n * and it missed the inline path purely because the matcher demanded a quoted literal.\n * Requiring the SAME identifier in both positions is what makes this sound rather than a\n * loosening: the arrow's own parameters are `(c, f, s, r, tl)`, so nothing between the\n * two occurrences can rebind the name, and the evaluator has already resolved that\n * binding to `def.type`. Two spellings of one value, not two values.\n */\nfunction identMkBuildRe(typeIdent: string): RegExp {\n return new RegExp(\n String.raw`^\\(\\s*(\\w+)${ANN}\\s*,\\s*${ANY_P}\\s*,\\s*(\\w+)${ANN}\\s*,\\s*(\\w+)${ANN}\\s*,\\s*(\\w+)${ANN}\\s*\\)\\s*=>\\s*(?:[\\w$.]*\\.)?mk\\s*\\(\\s*${escapeRegExp(typeIdent)}\\s*,\\s*\\1\\s*,\\s*\\3\\s*,\\s*\\2\\s*,\\s*\\4\\s*\\)\\s*$`,\n )\n}\n\n/** Any callee \u2014 covers `mk`, `import_x.mk`, `__vite_ssr_import_0__.mk`, etc. */\nfunction looseMkBuildRe(type: string): RegExp {\n return new RegExp(\n String.raw`^\\(\\s*(\\w+)${ANN}\\s*,\\s*${ANY_P}\\s*,\\s*(\\w+)${ANN}\\s*,\\s*(\\w+)${ANN}\\s*,\\s*(\\w+)${ANN}\\s*\\)\\s*=>\\s*.+\\(\\s*(['\"])${escapeRegExp(type)}\\5\\s*,\\s*\\1\\s*,\\s*\\3\\s*,\\s*\\2\\s*,\\s*\\4\\s*\\)\\s*$`,\n )\n}\n\n/**\n * Does this source LOOK like it wants the inline-`mk` path? Used only to decide whether\n * a miss is worth reporting: a reducer that never mentions `mk(` was never a candidate,\n * and warning about it would be per-rule noise on every grammar that does not use the\n * pattern at all \u2014 the flood that turns a diagnostic back into silence.\n */\nconst LOOKS_LIKE_MK_RE = /=>\\s*(?:[\\w$.]*\\.)?mk\\s*\\(/\n\n\n/**\n * When a node() build is a thin `mk(type, \u2026)` wrapper, emit the object literal\n * at the call site instead of `_build[n](\u2026)`.\n */\nexport function analyzeMkInlineBuild(def: Extract<ParserDef, { tag: 'node' }>): string | null {\n if (!def.build) return null // structural node \u2014 no own build to inline\n if (def.type === undefined) return null\n const src = buildAnalysisSrc(def).trim()\n const strict = src.match(MK_BUILD_RE)\n if (strict) {\n const mkType = strict[6]!\n if (mkType === def.type) return def.type\n reportMkMiss(def.type, src, `it builds a \"${mkType}\" node, not \"${def.type}\"`)\n return null\n }\n if (looseMkBuildRe(def.type).test(src)) return def.type\n // Factory-authored: `node(t, \u2026, (\u2026) => mk(t, \u2026))`. See `identMkBuildRe`.\n if (def.typeSrc !== undefined && identMkBuildRe(def.typeSrc).test(src)) return def.type\n if (LOOKS_LIKE_MK_RE.test(src)) {\n reportMkMiss(def.type, src, 'its parameter list or argument order does not match '\n + '`(children, fields, span, rawChildren, triviaLog) => mk(type, children, rawChildren, span, triviaLog)`')\n }\n return null\n}\n\n/** A near-miss on the inline-`mk` shape costs a real call per match \u2014 say so. */\nfunction reportMkMiss(type: string, src: string, why: string): void {\n recordDegradation({\n code: 'mk-inline-missed',\n severity: 'warn',\n where: `node(\"${type}\")`,\n subject: `build reducer \\`${src.split('\\n')[0]!.slice(0, 80)}\\``,\n fellBackTo: `looks like an inline-\\`mk\\` builder but ${why}, so every match pays a `\n + '`_build[n](...)` call instead of an inlined object literal',\n otherwise: 'the node object would be constructed at the call site with no call frame',\n })\n}\n\n/** Object literal matching `stub-build.ts` `mk()` without the function call. */\nexport function emitInlineMkNodeExpr(\n type: string,\n chV: string,\n rawV: string,\n spanExpr: string,\n tlV: string,\n): string {\n return `{ _tag: 'node', type: ${JSON.stringify(type)}, span: ${spanExpr}, children: ${chV}, rawCount: ${rawV}.length, localTriviaLen: ${tlV}.length }`\n}\n", "import type { Combinator, FieldMap, ParserDef } from '../types.ts'\nimport { confirmedArityForDef } from './build-arity.ts'\n\ntype NodeDef = Extract<ParserDef, { tag: 'node' }>\n\nexport function buildReadsFields(def: NodeDef): boolean {\n if (!def.build) return true\n const arity = confirmedArityForDef(def)\n if (arity === null) return true\n return arity >= 2\n}\n\nexport function parserHasOwnFields(p: Combinator<unknown>, seen: Set<Combinator<unknown>> = new Set()): boolean {\n if (seen.has(p)) return false\n seen.add(p)\n const d = p._def\n switch (d.tag) {\n case 'field': return true\n case 'node': return false\n case 'lazy': {\n try { return parserHasOwnFields(d.thunk(), seen) } catch { return false }\n }\n case 'sequence':\n case 'choice': return d.parsers.some(x => parserHasOwnFields(x, seen))\n case 'dispatch': return parserHasOwnFields(d.selector, seen) || d.cases.some(x => parserHasOwnFields(x.parser, seen)) || (d.matchers ? d.matchers.some(entry => parserHasOwnFields(entry.parser, seen)) : false) || (d.otherwise ? parserHasOwnFields(d.otherwise, seen) : false)\n case 'sepBy': return parserHasOwnFields(d.parser, seen) || parserHasOwnFields(d.separator, seen)\n case 'skip': return parserHasOwnFields(d.main, seen) || parserHasOwnFields(d.skipped, seen)\n case 'grammar': return parserHasOwnFields(d.parser, seen) || (d.triviaParser ? parserHasOwnFields(d.triviaParser, seen) : false)\n case 'scanTo': return parserHasOwnFields(d.sentinel, seen) || d.skip.some(x => parserHasOwnFields(x, seen))\n case 'recover': return parserHasOwnFields(d.parser, seen) || parserHasOwnFields(d.sentinel, seen)\n case 'many':\n case 'oneOrMore':\n case 'optional':\n case 'attempt':\n case 'transform':\n case 'trivia':\n case 'token':\n case 'leaf':\n case 'label':\n case 'expect':\n case 'withCtx':\n case 'not':\n case 'peek':\n return parserHasOwnFields(d.parser, seen)\n default:\n return false\n }\n}\n\n/**\n * Does the node's OWN parse frame ever have a trivia run logged into it?\n * Trivia is logged only by the trivia-skip fn, which runs at `sequence`/`many`/\n * repeat boundaries. A bare terminal (regex/literal/keywords/\u2026) has NO trivia\n * site, so its `_cstTriviaLog` stays empty and its `captureTrivia`/`_cstTriviaLog`/\n * `_triviaCaptureMask` save+install+restore is dead work \u2014 the per-node scope\n * trivia frame can be elided for it (see emitNode `needsTriviaFrame`).\n *\n * Stops at a nested `node()` (it manages its OWN trivia frame; trivia inside it\n * never logs to THIS node's frame). CONSERVATIVE: any unknown / trivia-bearing\n * shape returns `true` (keep the frame) \u2014 we only elide when provably safe.\n */\nexport function parserHasTriviaSite(p: Combinator<unknown>, seen: Set<Combinator<unknown>> = new Set()): boolean {\n if (seen.has(p)) return true // cycle \u2192 conservative (keep the frame)\n seen.add(p)\n const d = p._def\n switch (d.tag) {\n // Trivia is skipped between/around elements or iterations \u2192 a site.\n case 'sequence':\n case 'many':\n case 'oneOrMore':\n case 'sepBy':\n case 'scanTo':\n case 'recover':\n case 'skip':\n return true\n // Nested node manages its own trivia frame; none logs here.\n case 'node': return false\n // Pure terminals + trivia-suppressing token: no site.\n case 'regex':\n case 'literal':\n case 'keywords':\n case 'guard':\n case 'token':\n case 'leaf':\n return false\n // Transparent single-child wrappers: recurse.\n case 'optional':\n case 'attempt':\n case 'transform':\n case 'trivia':\n case 'label':\n case 'expect':\n case 'withCtx':\n case 'not':\n case 'peek':\n case 'field':\n return parserHasTriviaSite(d.parser, seen)\n case 'choice': return d.parsers.some(x => parserHasTriviaSite(x, seen))\n case 'dispatch': return parserHasTriviaSite(d.selector, seen) || d.cases.some(x => parserHasTriviaSite(x.parser, seen)) || (d.matchers ? d.matchers.some(entry => parserHasTriviaSite(entry.parser, seen)) : false) || (d.otherwise ? parserHasTriviaSite(d.otherwise, seen) : false)\n case 'grammar': return parserHasTriviaSite(d.parser, seen)\n case 'lazy': {\n try { return parserHasTriviaSite(d.thunk(), seen) } catch { return true }\n }\n default: return true // unknown shape \u2192 conservative\n }\n}\n\n/**\n * Can this node's inner grammar explicitly enable trivia capture? A surrounding\n * node owns the collector, so a nested `parser({ captureTrivia: true })` must\n * allocate that collector before it enters the grammar scope. Nested node()\n * rules own their separate collector and therefore do not contribute here.\n */\nexport function parserEnablesTriviaCapture(p: Combinator<unknown>, seen: Set<Combinator<unknown>> = new Set()): boolean {\n if (seen.has(p)) return false\n seen.add(p)\n const d = p._def\n switch (d.tag) {\n case 'grammar': return d.captureTrivia === true || parserEnablesTriviaCapture(d.parser, seen)\n case 'node': return false\n case 'sequence':\n case 'choice': return d.parsers.some(x => parserEnablesTriviaCapture(x, seen))\n case 'dispatch': return parserEnablesTriviaCapture(d.selector, seen) || d.cases.some(x => parserEnablesTriviaCapture(x.parser, seen)) || (d.matchers ? d.matchers.some(entry => parserEnablesTriviaCapture(entry.parser, seen)) : false) || (d.otherwise ? parserEnablesTriviaCapture(d.otherwise, seen) : false)\n case 'sepBy': return parserEnablesTriviaCapture(d.parser, seen) || parserEnablesTriviaCapture(d.separator, seen)\n case 'skip': return parserEnablesTriviaCapture(d.main, seen) || parserEnablesTriviaCapture(d.skipped, seen)\n case 'scanTo': return parserEnablesTriviaCapture(d.sentinel, seen) || d.skip.some(x => parserEnablesTriviaCapture(x, seen))\n case 'recover': return parserEnablesTriviaCapture(d.parser, seen) || parserEnablesTriviaCapture(d.sentinel, seen)\n case 'many':\n case 'oneOrMore':\n case 'optional':\n case 'attempt':\n case 'transform':\n case 'trivia':\n case 'token':\n case 'label':\n case 'field':\n case 'expect':\n case 'withCtx':\n case 'not':\n case 'peek': return parserEnablesTriviaCapture(d.parser, seen)\n // leaf() clears the inner CST/trivia collector and publishes only its own\n // terminal result. An inner parser() capture cannot reach this node.\n case 'leaf': return false\n case 'lazy': {\n try { return parserEnablesTriviaCapture(d.thunk(), seen) } catch { return false }\n }\n default: return false\n }\n}\n\nexport function buildFieldMap(captures: ReadonlyArray<{ name: string; value: unknown; span: { start: number; end: number } }> | undefined): FieldMap | undefined {\n if (!captures?.length) return undefined\n const out: FieldMap = {}\n for (const cap of captures) {\n const entry = { value: cap.value, span: cap.span }\n const current = out[cap.name]\n if (current === undefined) out[cap.name] = entry\n else if (Array.isArray(current)) current.push(entry)\n else out[cap.name] = [current, entry]\n }\n return out\n}\n", "/**\n * The case-fold CLASS of a code point under ECMAScript's NON-Unicode `/i`\n * matching \u2014 the exact relation `keywords({ caseInsensitive: true })` compiles to.\n *\n * A first-set drives O(1) `choice` dispatch, so it MUST be a superset of every\n * character the combinator can really start with. For a case-insensitive matcher\n * that means: for every input char X that the matcher would accept as the first\n * char, X is in the set. Under `/i` WITHOUT `u`, two chars match iff they share a\n * canonical form, and that relation is NOT simply `{c, toUpperCase(c),\n * toLowerCase(c)}` \u2014 67 BMP code points sit in classes those three miss:\n *\n * \u03C3 (U+03C3) \u2194 \u03A3 (U+03A3) \u2194 \u03C2 (U+03C2) final sigma is in the class but is\n * neither the upper- nor lowercase of \u03C3\n * \u00B5 (U+00B5) \u2194 \u03BC (U+03BC) \u2194 \u039C (U+039C) micro sign folds into Greek mu\n * \u01C4 (U+01C4) \u2194 \u01C5 (U+01C5) \u2194 \u01C6 (U+01C6) titlecase digraphs (also \u01C7\u01C8\u01C9\u01CA\u01CB\u01CC\u01F1\u01F2\u01F3)\n * \u0345 (U+0345) \u2194 \u03B9 (U+03B9) \u2194 \u03B9 (U+1FBE) combining iota subscript\n *\n * so widening a first-set by upper/lower alone is UNSOUND for them.\n *\n * The canonical form below is ECMAScript's `Canonicalize` for non-Unicode mode:\n * uppercase the char; if that is not exactly one char, or if it would cross the\n * ASCII boundary INTO Basic Latin, keep the original. That last clause is why\n * `/s/i` does not match `\u017F` (U+017F) and `/k/i` does not match `K` (U+212A) \u2014\n * cross-boundary folds are refused in BOTH directions, which is what keeps an\n * ASCII first-set tight and sound for the common all-ASCII keyword set.\n *\n * The classes are derived from the RUNNING engine's own `toUpperCase`, not a\n * frozen table, so they cannot drift from the regex engine that will do the\n * matching. Verified exhaustively against real `/i` behaviour across the BMP:\n * 1141 multi-member classes, 2307 members, zero disagreements in either\n * direction (see `test/unit/case-fold.test.ts`).\n */\n\n/** ECMAScript `Canonicalize` for non-Unicode `/i`. */\nfunction canonical(ch: string): string {\n const u = ch.toUpperCase()\n // A fold that expands (`\u00DF` \u2192 `SS`) is not a single-char fold: no canonicalization.\n if (u.length !== 1) return ch\n // Refuse a fold that would move a non-ASCII char INTO Basic Latin (`\u017F` \u2192 `S`).\n if (ch.codePointAt(0)! >= 128 && u.codePointAt(0)! < 128) return ch\n return u\n}\n\n/**\n * Lazily-built reverse index over the non-ASCII BMP, keyed by canonical form.\n * Only classes with more than one member are kept (a singleton class needs no\n * widening), which is ~2.3k entries rather than 65k. The ~12ms scan is paid ONCE\n * per process and only when a non-ASCII case-insensitive first char actually\n * appears \u2014 the all-ASCII path below never touches it.\n */\nlet foldIndex: Map<number, readonly number[]> | null = null\n\nfunction buildFoldIndex(): Map<number, readonly number[]> {\n const byCanonical = new Map<string, number[]>()\n for (let cp = 0; cp < 0x10000; cp++) {\n // Lone surrogates have no case and never canonicalize with anything.\n if (cp >= 0xd800 && cp <= 0xdfff) continue\n const key = canonical(String.fromCharCode(cp))\n const bucket = byCanonical.get(key)\n if (bucket) bucket.push(cp)\n else byCanonical.set(key, [cp])\n }\n const index = new Map<number, readonly number[]>()\n for (const members of byCanonical.values()) {\n if (members.length < 2) continue\n for (const cp of members) index.set(cp, members)\n }\n return index\n}\n\n/**\n * Every code point that a non-Unicode `/i` matcher treats as equal to `cp`,\n * INCLUDING `cp` itself. Union these into a first-set to keep case-insensitive\n * dispatch sound.\n */\nexport function caseFoldVariants(cp: number): readonly number[] {\n // Basic Latin: the fold class is exactly the a\u2194A twin, no index needed. (The\n // cross-boundary refusal above is what guarantees nothing outside ASCII joins\n // an ASCII char's class, so this fast path is exact, not an approximation.)\n if (cp < 128) {\n if (cp >= 0x41 && cp <= 0x5a) return [cp, cp + 32]\n if (cp >= 0x61 && cp <= 0x7a) return [cp, cp - 32]\n return [cp]\n }\n // Above the BMP there is nothing to fold: in non-Unicode mode the pattern is\n // matched as UTF-16 code units, and no surrogate has a case mapping.\n if (cp > 0xffff) return [cp]\n foldIndex ??= buildFoldIndex()\n return foldIndex.get(cp) ?? [cp]\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta, FirstSet } from '../types.ts'\nimport { fromChar, union, empty } from './first-set.ts'\nimport { caseFoldVariants } from './case-fold.ts'\nimport { failAt } from './probe.ts'\nimport { pushCstLeaf, cstCaptureActive } from '../cst/capture-buffer.ts'\n\nexport type KeywordsOptions = {\n /** Match case-insensitively. */\n caseInsensitive?: boolean\n /**\n * Character class (regex source, e.g. `'A-Za-z0-9_-'`) that must NOT follow a\n * match \u2014 a word boundary. Prevents matching `red` inside `redish`.\n */\n boundary?: string\n}\n\nexport type WordOptions = Omit<KeywordsOptions, 'boundary'>\n\n/**\n * Match a single keyword with an automatic word-boundary guard. Prevents\n * matching `true` inside `trueish`. The boundary defaults to `_0-9A-Za-z`,\n * which covers most programming-language identifiers.\n *\n * word('true') // matches \"true\" but not \"trueish\"\n * word('color', 'A-Za-z-') // CSS-style identifier boundary\n * word('media', 'A-Za-z0-9_-', { caseInsensitive: true })\n * word('media', { caseInsensitive: true }) // default boundary + options\n *\n * `caseInsensitive` matches `keywords()` and exists because it is REQUIRED, not a\n * nicety: CSS at-keywords, function names and units are ASCII case-insensitive per\n * spec (CSS Syntax \u00A73). Without it the only conforming spellings were\n * `regex(/media/i)` \u2014 which `analyzeGating` correctly flags as the `keyword-regex`\n * anti-pattern \u2014 or `keywords(['media'], \u2026)` for a single word.\n */\nexport function word(str: string, boundary?: string, opts?: WordOptions): Combinator<string>\nexport function word(str: string, opts: WordOptions): Combinator<string>\nexport function word(\n str: string,\n boundaryOrOpts?: string | WordOptions,\n opts?: WordOptions,\n): Combinator<string> {\n const boundary = typeof boundaryOrOpts === 'string' ? boundaryOrOpts : '_0-9A-Za-z'\n const rest = typeof boundaryOrOpts === 'object' && boundaryOrOpts !== null ? boundaryOrOpts : opts\n return keywords([str], { ...rest, boundary })\n}\n\n/**\n * Create a keyword factory with a fixed word-boundary class. Use when many\n * keywords share the same boundary (e.g. CSS identifiers). For a single keyword,\n * `word(str, boundary?)` is enough.\n *\n * const kw = makeWord() // default boundary\n * const cssKw = makeWord('A-Za-z0-9_-', { caseInsensitive: true })\n *\n * const query = kw('query')\n * const color = cssKw('color') // matches \"COLOR\" but not \"color-scheme\"\n */\nexport function makeWord(boundary?: string, opts?: WordOptions): (str: string) => Combinator<string>\nexport function makeWord(opts: WordOptions): (str: string) => Combinator<string>\nexport function makeWord(\n boundaryOrOpts: string | WordOptions = '_0-9A-Za-z',\n opts?: WordOptions,\n): (str: string) => Combinator<string> {\n const boundary = typeof boundaryOrOpts === 'string' ? boundaryOrOpts : '_0-9A-Za-z'\n const rest = typeof boundaryOrOpts === 'object' && boundaryOrOpts !== null ? boundaryOrOpts : opts\n return (str: string) => keywords([str], { ...rest, boundary })\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Match any one of a set of fixed keywords, longest-first (so `border` wins over\n * `bord`), with an optional trailing word-boundary guard. Compiles to a single\n * sticky regex \u2014 far less error-prone than a hand-maintained alternation, and\n * the common case (keyword sets: CSS colors, units, at-rule names, HTML tags).\n *\n * keywords(CSS_COLOR_NAMES, { caseInsensitive: true, boundary: 'A-Za-z0-9_-' })\n *\n * On success the matched text is recorded as a CSTLeaf (like literal()/regex()).\n */\nexport function keywords(words: readonly string[], opts: KeywordsOptions = {}): Combinator<string> {\n // Longest-first keeps the alternation greedy-correct (regex alternation is\n // first-match, not longest-match).\n const sorted = [...new Set(words)].sort((a, b) => b.length - a.length)\n const alt = sorted.map(escapeRe).join('|')\n const boundary = opts.boundary ? `(?![${opts.boundary}])` : ''\n // Case-INSENSITIVE drops `u` deliberately, so that MATCHING and the first-set\n // below fold the SAME set of characters \u2014 the invariant `regex()` established in\n // 0.32.0 (see the flag-aware widening in `src/combinators/regex.ts`):\n // - `/i` WITHOUT `u` folds only pairs that stay on the SAME side of the ASCII\n // boundary \u2014 every Basic-Latin pair (a\u2194A \u2026 z\u2194Z), and also the non-ASCII ones\n // (\u00E4\u2194\u00C4, \u03C3\u2194\u03A3\u2194\u03C2), but never a pair that crosses it. `caseFoldVariants` below\n // enumerates exactly that relation \u2192 the first-set is a tight, SOUND superset\n // and dispatch stays exact. (Widening by toUpperCase/toLowerCase alone would\n // NOT be: 67 BMP code points sit in fold classes those two miss.)\n // - `/iu` folds by Unicode *simple case folding*, so `/(?:stroke)/iu` also\n // matches `\u017Ftroke` (U+017F \u2192 s). An ASCII-only first-set would then dispatch\n // that input AWAY from this arm \u2014 an unsound gate. `regex()` answers that by\n // falling back to `any()` (forfeiting the gate); `keywords()` answers it by\n // not entering Unicode mode at all, which keeps the gate.\n // Every keyword is fully escaped by `escapeRe`, so `u` mode changes nothing about\n // what a case-SENSITIVE set matches; that path keeps `u` unchanged.\n const flags = opts.caseInsensitive ? 'iy' : 'uy'\n const re = new RegExp(`(?:${alt})${boundary}`, flags)\n\n // First-set: the set of first code points across all keywords (and their\n // case-folded variants when case-insensitive), for choice() dispatch.\n //\n // The fold must cover the SAME pairs the `iy` matcher above accepts, or the gate\n // dispatches valid input away from this arm. `/i` folds non-ASCII pairs too\n // (`/\u00E4rger/i` matches `\u00C4rger`, `/\u03C3/i` matches both `\u03A3` and `\u03C2`) \u2014 it only refuses\n // folds that would CROSS the ASCII boundary. `caseFoldVariants` is that exact\n // relation, so the widening stays a tight, sound superset for every first char,\n // not just the Basic-Latin ones.\n let firstSet: FirstSet = empty()\n for (const w of sorted) {\n if (w.length === 0) continue\n const cp = w.codePointAt(0)!\n firstSet = union(firstSet, fromChar(cp))\n if (opts.caseInsensitive) {\n for (const v of caseFoldVariants(cp)) firstSet = union(firstSet, fromChar(v))\n }\n }\n\n const meta: ParserMeta = { firstSet, canMatchNewline: false, isTrivia: false }\n\n return {\n _tag: 'keywords',\n _meta: meta,\n _def: { tag: 'keywords', words: sorted, caseInsensitive: opts.caseInsensitive ?? false, boundary: opts.boundary },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<string> {\n re.lastIndex = pos\n const m = re.exec(input)\n if (m === null || m.index !== pos) {\n return failAt(ctx, ['keyword'], pos)\n }\n const value = m[0]!\n const span = { start: pos, end: pos + value.length }\n if (cstCaptureActive(ctx)) pushCstLeaf(ctx, { _tag: 'leaf', value, span })\n return { ok: true, value, span }\n },\n }\n}\n", "import type { Combinator, DispatchCase, DispatchMatcherCase, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { cstCaptureActive, pushCstLeaf } from '../cst/capture-buffer.ts'\nimport { rollbackTrivia, saveTriviaMark } from './trivia-skip.ts'\n\nexport type DispatchWhen<T> = {\n readonly kind: 'when'\n readonly keys: readonly string[]\n readonly parser: Combinator<T>\n readonly caseInsensitive: boolean\n readonly usesRouted?: boolean\n}\n\nexport type DispatchWhenMatcher<T> = {\n readonly kind: 'whenMatcher'\n readonly matcher: DispatchStringMatcher\n readonly parser: Combinator<T>\n readonly caseInsensitive: boolean\n readonly usesRouted?: boolean\n}\n\nexport type DispatchStringMatcher =\n | { readonly kind: 'startsWith'; readonly value: string }\n | { readonly kind: 'endsWith'; readonly value: string }\n | { readonly kind: 'matches'; readonly value: string; readonly flags: string }\n\nexport type DispatchOtherwise<T> = {\n readonly kind: 'otherwise'\n readonly parser: Combinator<T>\n readonly usesRouted?: boolean\n}\n\nexport type DispatchArm<T = unknown> = DispatchWhen<T> | DispatchWhenMatcher<T> | DispatchOtherwise<T>\nexport type DispatchWhenOptions = {\n caseInsensitive?: boolean\n}\nexport type DispatchWhenFactory = <T>(\n key: string | readonly string[],\n parser: Combinator<T>,\n) => DispatchWhen<T>\nexport type DispatchWhenKey = string | readonly string[]\nexport type DispatchWhenSelector = DispatchWhenKey | DispatchStringMatcher\n\ntype ArmValue<T> = T extends DispatchWhen<infer U>\n ? U\n : T extends DispatchWhenMatcher<infer U>\n ? U\n : T extends DispatchOtherwise<infer U>\n ? U\n : never\ntype UnionArms<T extends readonly DispatchArm<unknown>[]> = {\n [K in keyof T]: ArmValue<T[K]>\n}[number]\n\nfunction parserUsesRouted(parser: Combinator<unknown>, seen: Set<Combinator<unknown>> = new Set()): boolean {\n if (seen.has(parser)) return false\n seen.add(parser)\n const def = parser._def\n switch (def.tag) {\n case 'routed':\n return true\n case 'sequence':\n case 'choice':\n return def.parsers.some(entry => parserUsesRouted(entry, seen))\n case 'dispatch':\n return false\n case 'sepBy':\n return parserUsesRouted(def.parser, seen) || parserUsesRouted(def.separator, seen)\n case 'skip':\n return parserUsesRouted(def.main, seen) || parserUsesRouted(def.skipped, seen)\n case 'grammar':\n return parserUsesRouted(def.parser, seen) || (def.triviaParser ? parserUsesRouted(def.triviaParser, seen) : false)\n case 'scanTo':\n return parserUsesRouted(def.sentinel, seen) || def.skip.some(entry => parserUsesRouted(entry, seen))\n case 'recover':\n return parserUsesRouted(def.parser, seen) || parserUsesRouted(def.sentinel, seen)\n case 'lazy':\n try { return parserUsesRouted(def.thunk(), seen) } catch { return false }\n case 'many':\n case 'oneOrMore':\n case 'optional':\n case 'attempt':\n case 'transform':\n case 'trivia':\n case 'token':\n case 'leaf':\n case 'label':\n case 'field':\n case 'not':\n case 'peek':\n case 'node':\n case 'withCtx':\n case 'expect':\n return parserUsesRouted(def.parser, seen)\n default:\n return false\n }\n}\n\nfunction branchUsesRouted(branch: { parser: Combinator<unknown>; usesRouted?: boolean | undefined }): boolean {\n return branch.usesRouted === true || parserUsesRouted(branch.parser)\n}\n\nfunction asciiFoldKey(key: string): string {\n let out = ''\n for (let i = 0; i < key.length; i++) {\n const c = key.charCodeAt(i)\n out += String.fromCharCode(c >= 65 && c <= 90 ? c + 32 : c)\n }\n return out\n}\n\nfunction matchesDispatchMatcher(value: string, matcher: DispatchMatcherCase): boolean {\n const candidate = matcher.caseInsensitive ? asciiFoldKey(value) : value\n const expected = matcher.caseInsensitive ? asciiFoldKey(matcher.value) : matcher.value\n switch (matcher.kind) {\n case 'startsWith':\n return candidate.startsWith(expected)\n case 'endsWith':\n return candidate.endsWith(expected)\n case 'matches': {\n const flags = matcher.caseInsensitive && !matcher.flags?.includes('i')\n ? `${matcher.flags ?? ''}i`\n : matcher.flags ?? ''\n return new RegExp(matcher.value, flags).test(value)\n }\n }\n}\n\nfunction isStringMatcher(value: unknown): value is DispatchStringMatcher {\n if (typeof value !== 'object' || value === null) return false\n const kind = (value as { kind?: unknown }).kind\n return kind === 'startsWith' || kind === 'endsWith' || kind === 'matches'\n}\n\nfunction fixedMatcher(kind: 'startsWith' | 'endsWith', value: string): DispatchStringMatcher {\n if (typeof value !== 'string') throw new TypeError(`parseman: ${kind}() value must be a string`)\n if (value.length === 0) throw new RangeError(`parseman: ${kind}() requires a non-empty value`)\n return { kind, value }\n}\n\nexport function startsWith(prefix: string): DispatchStringMatcher {\n return fixedMatcher('startsWith', prefix)\n}\n\nexport function endsWith(suffix: string): DispatchStringMatcher {\n return fixedMatcher('endsWith', suffix)\n}\n\nexport function matches(pattern: RegExp): DispatchStringMatcher {\n if (!(pattern instanceof RegExp)) throw new TypeError('parseman: matches() requires a RegExp')\n if (pattern.flags.includes('g') || pattern.flags.includes('y')) {\n throw new TypeError('parseman: matches() does not accept global or sticky regex flags')\n }\n return { kind: 'matches', value: pattern.source, flags: pattern.flags }\n}\n\nexport function when<T>(\n key: DispatchWhenKey,\n parser: Combinator<T>,\n opts?: DispatchWhenOptions,\n): DispatchWhen<T>\nexport function when<T>(\n matcher: DispatchStringMatcher,\n parser: Combinator<T>,\n opts?: DispatchWhenOptions,\n): DispatchWhenMatcher<T>\nexport function when<T>(\n key: DispatchWhenSelector,\n parser: Combinator<T>,\n opts: DispatchWhenOptions = {},\n): DispatchWhen<T> | DispatchWhenMatcher<T> {\n const usesRouted = parserUsesRouted(parser as Combinator<unknown>)\n if (isStringMatcher(key)) {\n return { kind: 'whenMatcher', matcher: key, parser, caseInsensitive: opts.caseInsensitive ?? false, usesRouted }\n }\n const keys = Array.isArray(key) ? [...key] : [key]\n if (keys.length === 0) throw new RangeError('parseman: when() requires at least one key')\n for (const item of keys) {\n if (typeof item !== 'string') throw new TypeError('parseman: when() keys must be strings')\n }\n return { kind: 'when', keys, parser, caseInsensitive: opts.caseInsensitive ?? false, usesRouted }\n}\n\nexport function makeWhen(opts: DispatchWhenOptions = {}): DispatchWhenFactory {\n return (key, parser) => when(key, parser, opts)\n}\n\nexport function otherwise<T>(parser: Combinator<T>): DispatchOtherwise<T> {\n return { kind: 'otherwise', parser, usesRouted: parserUsesRouted(parser as Combinator<unknown>) }\n}\n\n/**\n * Reuse the token the enclosing `dispatch()` already consumed to select this branch,\n * instead of re-recognizing it.\n *\n * With no argument this is dispatch-only: outside a dispatch branch (or at a position\n * other than the selector's) it fails with `expected: ['routed()']`.\n *\n * `routed(fallback)` makes the SAME production usable in both contexts: inside a\n * dispatch branch it reuses the routed token; anywhere else it parses `fallback` in\n * place. That is what collapses a `Routed<X>` twin production into its original \u2014\n * `sequence(routed(Name), Prelude, ';')` replaces the pair\n * `sequence(Name, Prelude, ';')` / `sequence(routed(), Prelude, ';')`, which\n * otherwise differ by exactly one element and duplicate a whole production (and a\n * whole compiled emission) for a one-token difference.\n *\n * A `routed()` in a dispatch SELECTOR is still an error with or without a fallback:\n * the selector is what produces the routed token, so reading it there is misuse.\n */\nexport function routed<T = string>(fallback?: Combinator<T>): Combinator<T> {\n return {\n _tag: 'routed',\n _meta: {\n // The routed token is whatever the selector matched, so the first set stays\n // `any` even with a fallback \u2014 `any` already subsumes the fallback's.\n firstSet: { kind: 'any' },\n canMatchNewline: fallback?._meta.canMatchNewline ?? false,\n isTrivia: false,\n },\n _def: fallback === undefined\n ? { tag: 'routed' }\n : { tag: 'routed', fallback: fallback as Combinator<unknown> },\n parse(_input: string, pos: number, ctx: ParseContext): ParseResult<T> {\n const item = ctx._routed\n if (item === undefined || pos !== item.span.start) {\n if (fallback !== undefined) return fallback.parse(_input, pos, ctx)\n return { ok: false, expected: ['routed()'], span: { start: pos, end: pos } }\n }\n if (cstCaptureActive(ctx)) {\n pushCstLeaf(ctx, { _tag: 'leaf', value: item.value, span: item.span })\n }\n return { ok: true, value: item.value as T, span: item.span }\n },\n }\n}\n\nexport function dispatch<S extends string, T extends readonly DispatchArm<unknown>[]>(\n selector: Combinator<S>,\n ...arms: T\n): Combinator<[S, UnionArms<T>]> {\n if (parserUsesRouted(selector as Combinator<unknown>)) {\n throw new Error('parseman: routed() can only appear inside a dispatch() branch')\n }\n let fallback: Combinator<unknown> | undefined\n let fallbackUsesRouted = false\n const matchers: DispatchMatcherCase[] = []\n const cases: DispatchCase[] = []\n const seen: Array<{ raw: string; folded: string; caseInsensitive: boolean }> = []\n\n for (let i = 0; i < arms.length; i++) {\n const arm = arms[i]!\n if (arm.kind === 'otherwise') {\n if (fallback !== undefined) throw new Error('parseman: dispatch() accepts at most one otherwise() arm')\n if (i !== arms.length - 1) throw new Error('parseman: otherwise() must be the last dispatch() arm')\n fallback = arm.parser\n fallbackUsesRouted = arm.usesRouted === true\n continue\n }\n if (arm.kind === 'whenMatcher') {\n const matcher = arm.matcher\n matchers.push({\n kind: matcher.kind,\n value: matcher.value,\n ...(matcher.kind === 'matches' ? { flags: matcher.flags } : {}),\n parser: arm.parser as Combinator<unknown>,\n caseInsensitive: arm.caseInsensitive,\n ...(arm.usesRouted === true ? { usesRouted: true } : {}),\n })\n continue\n }\n for (const key of arm.keys) {\n const folded = asciiFoldKey(key)\n for (const prior of seen) {\n const overlaps = arm.caseInsensitive || prior.caseInsensitive\n ? folded === prior.folded\n : key === prior.raw\n if (overlaps) throw new Error(`parseman: duplicate dispatch key ${JSON.stringify(key)}`)\n }\n seen.push({ raw: key, folded, caseInsensitive: arm.caseInsensitive })\n }\n cases.push({\n keys: arm.keys,\n parser: arm.parser as Combinator<unknown>,\n caseInsensitive: arm.caseInsensitive,\n ...(arm.usesRouted === true ? { usesRouted: true } : {}),\n })\n }\n\n const meta: ParserMeta = {\n firstSet: selector._meta.firstSet,\n canMatchNewline: selector._meta.canMatchNewline ||\n cases.some(entry => entry.parser._meta.canMatchNewline) ||\n matchers.some(entry => entry.parser._meta.canMatchNewline) ||\n (fallback?._meta.canMatchNewline ?? false),\n isTrivia: false,\n }\n\n const byKey = new Map<string, DispatchCase>()\n const byFoldedKey = new Map<string, DispatchCase>()\n for (const entry of cases) {\n for (const key of entry.keys) {\n if (entry.caseInsensitive) byFoldedKey.set(asciiFoldKey(key), entry)\n else byKey.set(key, entry)\n }\n }\n\n return {\n _tag: 'dispatch',\n _meta: meta,\n _def: {\n tag: 'dispatch',\n selector: selector as Combinator<string>,\n cases,\n ...(matchers.length === 0 ? {} : { matchers }),\n ...(fallback === undefined ? {} : { otherwise: fallback, ...(fallbackUsesRouted ? { otherwiseUsesRouted: true } : {}) }),\n },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<[S, UnionArms<T>]> {\n if (parserUsesRouted(selector as Combinator<unknown>)) {\n throw new Error('parseman: routed() can only appear inside a dispatch() branch')\n }\n const selectorMark = saveTriviaMark(ctx)\n const selected = selector.parse(input, pos, ctx)\n if (!selected.ok) return selected\n\n const branch = byKey.get(selected.value) ??\n (byFoldedKey.size === 0 ? undefined : byFoldedKey.get(asciiFoldKey(selected.value))) ??\n matchers.find(matcher => matchesDispatchMatcher(selected.value, matcher)) ??\n (fallback === undefined ? undefined : { keys: [], parser: fallback, caseInsensitive: false, usesRouted: fallbackUsesRouted })\n if (branch === undefined) {\n const expected = cases.flatMap(entry => entry.keys.map(key => JSON.stringify(key)))\n return { ok: false, expected, span: { start: selected.span.end, end: selected.span.end } }\n }\n\n const savedRouted = ctx._routed\n const usesRouted = branchUsesRouted(branch)\n let mark = saveTriviaMark(ctx)\n if (usesRouted) {\n rollbackTrivia(ctx, selectorMark)\n mark = saveTriviaMark(ctx)\n ctx._routed = { value: selected.value, span: selected.span }\n }\n let result: ParseResult<unknown>\n try {\n result = branch.parser.parse(input, usesRouted ? pos : selected.span.end, ctx)\n } finally {\n if (usesRouted) ctx._routed = savedRouted\n }\n if (!result.ok) {\n rollbackTrivia(ctx, mark)\n return { ...result, committed: true }\n }\n\n return {\n ok: true,\n value: [selected.value, result.value as UnionArms<T>],\n span: { start: pos, end: result.span.end },\n }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult } from '../types.ts'\nimport { rollbackCstCapture, saveCstMark } from '../cst/capture-buffer.ts'\nimport { matchesEmpty, startsFirstSet } from './first-set.ts'\nimport { deriveExpected } from './expect.ts'\n\n/**\n * Transactional ordered-choice arm. On failure it restores Parseman's\n * structural capture/trivia/error sinks and reports failure at its entry point;\n * user-owned `ctx.state` is intentionally not cloned or mutated by Parseman.\n */\nexport function attempt<T>(parser: Combinator<T>): Combinator<T> {\n // First-set fail-fast (mirrors emitAttempt's codegen guard): a non-nullable inner\n // whose first set can't start here can only fail, so reject BEFORE taking the six\n // transaction rollback marks, re-anchoring at `pos` and reporting the same static\n // `expected` the inner start-fail would. Skipped under a completions probe /\n // tolerant recovery, where the swallowed failure still feeds the probe.\n const guardable = parser._meta.firstSet.kind !== 'any' && !matchesEmpty(parser)\n let failExpected: string[] | undefined\n return {\n _tag: 'attempt', _meta: parser._meta, _def: { tag: 'attempt', parser },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T> {\n if (guardable && ctx._probe === undefined && !ctx._tolerant && !startsFirstSet(parser, input, pos)) {\n if (failExpected === undefined) {\n const e = deriveExpected(parser)\n failExpected = e.length > 0 ? e : [parser._tag]\n }\n return { ok: false, expected: failExpected, span: { start: pos, end: pos } }\n }\n const mark = saveCstMark(ctx)\n const log = ctx._triviaLog?.length\n const rootLog = ctx._rootTriviaLog?.length\n const result = parser.parse(input, pos, ctx)\n if (result.ok) return result\n rollbackCstCapture(ctx, mark)\n if (log !== undefined && ctx._triviaLog && ctx._triviaLog.length !== log) ctx._triviaLog.length = log\n if (rootLog !== undefined && ctx._rootTriviaLog && ctx._rootTriviaLog.length !== rootLog) ctx._rootTriviaLog.length = rootLog\n if (result.committed) return result\n return { ok: false, expected: result.expected, span: { start: pos, end: pos } }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { any } from './first-set.ts'\nimport { saveLookaheadMark, rollbackLookahead } from './trivia-skip.ts'\n\n/**\n * Negative lookahead. Succeeds (consuming nothing) when `combinator` fails;\n * fails when `combinator` succeeds.\n *\n * The standard way to match a keyword without also matching the prefix\n * of a longer identifier:\n *\n * const kwTrue = sequence(literal('true'), not(regex(/\\w/)))\n * // matches \"true\" in \"true && x\" but NOT in \"trueish\" or \"trueness\"\n */\nexport function not(combinator: Combinator<unknown>): Combinator<null> {\n const meta: ParserMeta = {\n firstSet: any(), // we don't know what NOT matches\n canMatchNewline: false,\n isTrivia: false,\n }\n\n return {\n _tag: 'not',\n _meta: meta,\n _def: { tag: 'not', parser: combinator },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<null> {\n // Negative lookahead is a pure predicate: whatever the inner attempt\n // captured (CST leaves/rawChildren/per-node trivia/fields), recovered (a\n // ParseError pushed to ctx._errors + embedded via captureError), or committed\n // to the GLOBAL `_triviaLog` must be rolled back on BOTH outcomes \u2014 not()\n // consumes nothing and so may leave no side effect.\n //\n // `rollbackLookahead`, not `rollbackCstCapture`: the latter's mark omits two\n // further sinks a probe can write.\n // - `_triviaLog`, which `scanTrivia().commit()` writes when the probed body\n // skips ambient trivia between terms. Missing it duplicates every probed\n // span once the region is parsed for real \u2014 `_triviaLog` has no dedup\n // anywhere (`triviaEntries()` is a positional view over the flat array),\n // so the duplicate reaches output.\n // - `_probe.best`, the completions tracker, for the same reason `peek()`\n // restores it: expectations raised INSIDE a zero-width probe are not\n // reachable from the enclosing grammar at the cursor, so leaving them\n // offers unreachable tokens as completions.\n // Using the shared lookahead helper means neither can silently regress the\n // next time a sink is added.\n const mark = saveLookaheadMark(ctx)\n const result = combinator.parse(input, pos, ctx)\n rollbackLookahead(ctx, mark)\n if (result.ok) {\n return { ok: false, expected: [`not(${combinator._tag})`], span: { start: pos, end: pos } }\n }\n return { ok: true, value: null, span: { start: pos, end: pos } }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { any, matchesEmpty } from './first-set.ts'\nimport { saveLookaheadMark, rollbackLookahead } from './trivia-skip.ts'\n\n/**\n * Positive lookahead. Succeeds (consuming nothing) when `combinator` matches at\n * this position; fails when it doesn't. The mirror of `not()`.\n *\n * // \"a mixin reference, not a class selector\": require the punctuation ahead,\n * // then let the real production consume it.\n * const mixinRef = sequence(peek(regex(/[.#]/)), mixinCall)\n *\n * WHY THIS EXISTS AS A PRIMITIVE (not `not(not(X))`):\n *\n * `not(not(X))` is behaviourally a positive lookahead, but `not()` reports\n * `firstSet: any()` \u2014 it cannot know what it forbids \u2014 so `not(not(X))` reports\n * `any()` too. An arm leading with it therefore POISONS its choice's first-char\n * dispatch (`analyzeGating` flags it as the `double-not` anti-pattern), and among\n * sibling arms that share a first char the hand-rolled gate miscompiles.\n *\n * `peek(X)` carries X's first-set instead, so a leading `peek()` GATES its arm:\n * `choice(sequence(peek(regex(/[.#]/)), \u2026), \u2026)` still emits O(1) dispatch.\n *\n * The first-set is exact only when X is NON-NULLABLE. A nullable `peek(X)`\n * succeeds on the empty string, so it constrains no first character at all \u2014 it\n * reports `any()`, the sound over-approximation. (Same rule the sequence\n * first-set uses; see `isPositiveLookahead` in `first-set.ts`.)\n */\nexport function peek(combinator: Combinator<unknown>): Combinator<null> {\n const meta: ParserMeta = {\n // A nullable body imposes no first-char constraint \u2014 `any()`, not its set.\n firstSet: matchesEmpty(combinator) ? any() : combinator._meta.firstSet,\n canMatchNewline: false,\n isTrivia: false,\n }\n\n return {\n _tag: 'peek',\n _meta: meta,\n _def: { tag: 'peek', parser: combinator },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<null> {\n // Zero-width on BOTH outcomes, so the probe must leave NO observable trace:\n // whatever the inner attempt captured (CST leaves/rawChildren/per-node\n // trivia/fields), recovered (`_errors`), or committed to the GLOBAL\n // `_triviaLog` is rolled back either way.\n //\n // `rollbackTrivia`, not `rollbackCstCapture`: the latter's mark omits\n // `_triviaLog`, which is a SEPARATE sink `scanTrivia().commit()` writes when\n // the body skips ambient trivia between terms. Missing it duplicates every\n // probed trivia span once the region is parsed for real \u2014 `_triviaLog` has no\n // dedup anywhere (`triviaEntries()` is a positional view over the flat array),\n // so the duplicate reaches output. Same failure mode as the one recorded in\n // `test/parity/trivia-log-regression.test.ts`. The compiled `peek` emits its\n // body under a non-capturing ctx and so never writes these sinks at all; this\n // is what keeps the two engines at parity.\n const mark = saveLookaheadMark(ctx)\n const result = combinator.parse(input, pos, ctx)\n rollbackLookahead(ctx, mark)\n if (result.ok) return { ok: true, value: null, span: { start: pos, end: pos } }\n return { ok: false, expected: [`peek(${combinator._tag})`], span: { start: pos, end: pos } }\n },\n }\n}\n", "import type { Combinator, FieldMap, ParseContext, ParseResult, ParserMeta, ParserDef } from '../types.ts'\nimport { beginCstNodeCapture, endCstNodeCapture, pushCstChild } from '../cst/capture-buffer.ts'\nimport { buildReadsTrivia, buildReadsState, cstOutputHost } from '../compiler/build-arity.ts'\nimport { buildFieldMap, buildReadsFields, parserHasOwnFields } from '../compiler/fields.ts'\nimport { consumeTrivia } from './trivia-skip.ts'\nimport { matchesEmpty, startsFirstSet } from './first-set.ts'\nimport { deriveExpected } from './expect.ts'\nimport { annotateSpanFromLineContext } from '../line-index.ts'\nimport { NODE_TAG, NODE_TYPE } from '../cst/reflection.ts'\n\n/**\n * A CST/AST node rule. Runs `combinator` while collecting its terminals into\n * `children` / `rawChildren` arrays and trivia spans into `triviaLog`, then\n * calls `build(children, fields, span, rawChildren, triviaLog, state)` to produce the node.\n *\n * - `children` \u2014 structural items in source order: spanned CSTLeaf terminals\n * and sub-nodes (whatever `build` returned for inner nodes).\n * - `rawChildren` \u2014 structural children only (same items as `children`).\n * - `triviaLog` \u2014 flat log of trivia entries: each entry is `[start, end, insertIdx]`\n * consumed between terms. `insertIdx` is the rawChildren index\n * before which the trivia was consumed. Use `buildTriviaIndex`\n * to turn this into a before/after lookup table.\n *\n * If `build` returns a non-node value (e.g. a bare string for an unwrapped rule),\n * the parent records it as a spanned leaf so its source span is still recoverable.\n */\nexport type BuildNode<N> = (\n children: ReadonlyArray<unknown>,\n fields: FieldMap | undefined,\n span: { start: number; end: number },\n rawChildren: ReadonlyArray<unknown>,\n triviaLog: readonly number[],\n state: unknown,\n) => N\n\n/**\n * Options for `node()`.\n * - `unwrap` \u2014 an AST/value wrapper rule that IS its single child when it\n * captured exactly one. A leaf unwraps to its string value; a sub-node is\n * returned as-is.\n * - `collapse` \u2014 a structural wrapper rule that returns its single child exactly\n * as captured. A leaf stays a CSTLeaf; a node stays a node.\n * - `project` \u2014 return one captured semantic child by index while retaining the\n * complete node frame for CST hosts. Leaves unwrap to their string value.\n * - `captureTrivia` \u2014 capture trivia consumed inside this node even when its\n * enclosing `parser()` did not opt into document-wide trivia capture. This is\n * scoped to the node; sibling and parent nodes retain their own setting.\n * - `trailingTrivia` \u2014 after a successful node body, consume the active grammar\n * trivia once into THIS node's log. Intended for a document root whose body is\n * a repetition; do not set it on a block that already has a closing delimiter.\n * - `tags` \u2014 grammar-level CST categories for visitor dispatch. Stored once in\n * grammar reflection; not copied onto every CST node.\n * Both skip `build` only for a one-child match; zero or two-plus children go\n * through `build` normally.\n */\ntype ParserValue<P> = P extends Combinator<infer T> ? T : never\ntype ProjectValue<P extends Combinator<unknown>, I extends number> =\n ParserValue<P> extends readonly unknown[]\n ? I extends keyof ParserValue<P> ? ParserValue<P>[I] : unknown\n : I extends 0 ? ParserValue<P> : unknown\n\nexport type NodeCombinator<T, NodeType extends string = never, NodeTag extends string = never> =\n Combinator<T> & {\n /** Type-only CST node identity carried for grammar-aware visitors. */\n readonly [NODE_TYPE]?: NodeType\n /** Type-only CST tags carried for grammar-aware visitors. */\n readonly [NODE_TAG]?: NodeTag\n }\n\nexport type NodeOptions<Tags extends readonly string[] = readonly never[]> = {\n unwrap?: boolean\n collapse?: boolean\n project?: number\n captureTrivia?: boolean\n trailingTrivia?: boolean\n tags?: Tags\n /**\n * Declared positional arity of `build` \u2014 the ESCAPE HATCH for a reducer parseman\n * cannot read.\n *\n * Arity gates five capture tiers (`>= 1` children, `>= 2` fields, `>= 4` rawChildren,\n * `>= 5` triviaLog, `>= 6` a clone of `_ctx.state`), and parseman normally derives it\n * from the reducer's declaration \u2014 including across module boundaries. A few shapes\n * are genuinely undecidable: a rest parameter (`...args`), a body that reads\n * `arguments`, a reassigned or dynamically constructed reducer. Those fail OPEN, which\n * is safe but pays for every tier on every match, forever.\n *\n * Declaring the arity here turns \"undecidable\" into \"declared\". You are asserting the\n * highest positional argument the reducer reads; parseman then elides everything above\n * it exactly as if it had read the parameter list.\n *\n * DECLARING TOO LOW UNDER-CAPTURES: the reducer will receive an empty `rawChildren` /\n * `triviaLog` or an absent `state` rather than a wrong value. Count the parameters.\n */\n buildArity?: number\n}\nexport type NodeProjectOptions<I extends number = number> =\n Omit<NodeOptions, 'project' | 'unwrap' | 'collapse'> & { project: I; unwrap?: never; collapse?: never }\n\n/** A captured child's value form: a leaf unwraps to its string value, else as-is. */\nfunction unwrapChild(child: unknown): unknown {\n return child !== null && typeof child === 'object' && (child as { _tag?: string })._tag === 'leaf'\n ? (child as { value: unknown }).value\n : child\n}\n\nfunction isCstChild(value: unknown): boolean {\n return typeof value === 'object'\n && value !== null\n && ((value as { _tag?: string })._tag === 'node'\n || (value as { _tag?: string })._tag === 'leaf'\n || (value as { _tag?: string })._tag === 'parseError')\n}\n\nfunction missingInferredType(): never {\n throw new Error('node(): inferred node type requires a rules() key; pass node(\"Type\", parser) outside rules()')\n}\n\nfunction normalizeBuildArity(arity: number | undefined): number | undefined {\n if (arity === undefined) return undefined\n if (!Number.isInteger(arity) || arity < 0 || arity > 6) {\n throw new Error('node() buildArity must be an integer 0..6 (children, fields, span, rawChildren, triviaLog, state)')\n }\n return arity\n}\n\nfunction normalizeProject(project: number | undefined): number | undefined {\n if (project === undefined) return undefined\n if (!Number.isInteger(project) || project < 0) {\n throw new Error('node() project child must be a non-negative integer')\n }\n return project\n}\n\nfunction projectChild(children: ReadonlyArray<unknown>, project: number, type: string): unknown {\n if (!(project in children)) {\n throw new Error(`node(${JSON.stringify(type)}) project child ${project} was not captured`)\n }\n return unwrapChild(children[project])\n}\n\nexport function node<P extends Combinator<unknown>, const I extends number, const Tags extends readonly string[] = readonly never[]>(combinator: P, opts: NodeProjectOptions<I> & { tags?: Tags }): NodeCombinator<ProjectValue<P, I>, never, Tags[number]>\nexport function node<N, const Tags extends readonly string[] = readonly never[]>(combinator: Combinator<unknown>, build?: BuildNode<N>, opts?: NodeOptions<Tags>): NodeCombinator<N, never, Tags[number]>\nexport function node<N, const Tags extends readonly string[] = readonly never[]>(combinator: Combinator<unknown>, opts?: NodeOptions<Tags>): NodeCombinator<N, never, Tags[number]>\nexport function node<const Type extends string, P extends Combinator<unknown>, const I extends number, const Tags extends readonly string[] = readonly never[]>(type: Type, combinator: P, opts: NodeProjectOptions<I> & { tags?: Tags }): NodeCombinator<ProjectValue<P, I>, Type, Tags[number]>\nexport function node<N, const Type extends string, const Tags extends readonly string[] = readonly never[]>(type: Type, combinator: Combinator<unknown>, build?: BuildNode<N>, opts?: NodeOptions<Tags>): NodeCombinator<N, Type, Tags[number]>\nexport function node<N, const Type extends string, const Tags extends readonly string[] = readonly never[]>(type: Type, combinator: Combinator<unknown>, opts?: NodeOptions<Tags>): NodeCombinator<N, Type, Tags[number]>\nexport function node<N>(\n typeOrCombinator: string | Combinator<unknown>,\n combinatorOrBuild?: Combinator<unknown> | BuildNode<N> | NodeOptions,\n buildOrOpts?: BuildNode<N> | NodeOptions,\n maybeOpts?: NodeOptions,\n): Combinator<N> {\n const hasExplicitType = typeof typeOrCombinator === 'string'\n const type = hasExplicitType ? typeOrCombinator : undefined\n const combinator = (hasExplicitType ? combinatorOrBuild : typeOrCombinator) as Combinator<unknown>\n const buildArg = hasExplicitType ? buildOrOpts : combinatorOrBuild\n const build = typeof buildArg === 'function' ? buildArg as BuildNode<N> : undefined\n const opts = (typeof buildArg === 'function' ? maybeOpts : buildArg ?? maybeOpts) as NodeOptions | undefined\n const project = normalizeProject(opts?.project)\n if (project !== undefined && build !== undefined) {\n throw new Error('node() options cannot combine project with a build callback')\n }\n const baseDef = { tag: 'node' as const, parser: combinator, ...(type === undefined ? {} : { type }), ...(build === undefined ? {} : { build }) }\n const meta: ParserMeta = {\n firstSet: combinator._meta.firstSet,\n canMatchNewline: combinator._meta.canMatchNewline,\n isTrivia: false,\n }\n const unwrap = opts?.unwrap === true\n const collapse = opts?.collapse === true\n const captureTrivia = opts?.captureTrivia === true\n const trailingTrivia = opts?.trailingTrivia === true\n const tags = opts?.tags\n const buildArity = normalizeBuildArity(opts?.buildArity)\n if (unwrap && collapse) {\n throw new Error('node() options cannot set both unwrap and collapse')\n }\n if (project !== undefined && (unwrap || collapse)) {\n throw new Error('node() options cannot combine project with unwrap or collapse')\n }\n const def: Extract<ParserDef, { tag: 'node' }> = unwrap || collapse || project !== undefined || captureTrivia || trailingTrivia || buildArity !== undefined || (tags !== undefined && tags.length > 0)\n ? { ...baseDef, ...(unwrap ? { unwrap: true } : {}), ...(collapse ? { collapse: true } : {}), ...(project !== undefined ? { project } : {}), ...(captureTrivia ? { captureTrivia: true } : {}), ...(trailingTrivia ? { trailingTrivia: true } : {}), ...(buildArity !== undefined ? { buildArity } : {}), ...(tags !== undefined && tags.length > 0 ? { tags } : {}) }\n : baseDef\n // Arity-gated elision \u2014 decided once, identically to the compiler (build-arity.ts).\n // When the build never reads the trivia (4th) arg, disable per-node CST-trivia\n // capture for the inner scope; when it never reads state (5th), skip the state clone.\n // A STRUCTURAL node (no own build) defers to `ctx.build` / a default CST, which\n // may read either, so capture both.\n // These are the DIRECT builder's own needs, and they are not the whole story. A node\n // with its own build is re-routed through `ctx.build` when that host marks itself\n // `_parsemanCstOutput` (see the dispatch below) \u2014 and then the HOST, not the builder,\n // is the consumer. Nearly every AST builder is `children => \u2026`, arity 1, so under a CST\n // host these nodes handed the host an EMPTY triviaLog and absent fields and state, and\n // an empty trivia log is indistinguishable from a node that genuinely had none.\n //\n // The COMPILED engine settles this at build time (`compile(g, { hostMode: 'cst' })`,\n // added in 0.37.0), where it costs nothing. The interpreter has no compile step and\n // stays dynamic, so it re-decides per parse \u2014 which is the same answer, reached the\n // only way this engine can reach it.\n const capturesTrivia = captureTrivia || trailingTrivia || (build ? buildReadsTrivia(def) : project === undefined)\n const clonesState = build ? buildReadsState(def) : project === undefined\n const hasOwnFields = parserHasOwnFields(combinator)\n const capturesFields = hasOwnFields && (build ? buildReadsFields(def) : project === undefined)\n // First-set fail-fast (mirrors emitNode's codegen guard): a node whose body can't\n // match empty and whose first set can't start here can only fail, so reject BEFORE\n // allocating the CST capture frame. Sound and output-neutral \u2014 the failing body\n // would capture nothing and beginCstNodeCapture saves/restores every buffer, so\n // skipping returns the same failure the body's start-fail produces. Skipped under a\n // completions probe / tolerant recovery, where the swallowed failure still feeds the\n // probe (matching the codegen guard's `!ctx.recovery` gate).\n const guardable = combinator._meta.firstSet.kind !== 'any' && !matchesEmpty(combinator)\n let failExpected: string[] | undefined\n return {\n _tag: 'node',\n _meta: meta,\n _def: def,\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<N> {\n if (guardable && ctx._probe === undefined && !ctx._tolerant && !startsFirstSet(combinator, input, pos)) {\n if (failExpected === undefined) {\n const e = deriveExpected(combinator)\n failExpected = e.length > 0 ? e : [combinator._tag]\n }\n return { ok: false, expected: failExpected, span: { start: pos, end: pos } }\n }\n // Under a positioned-CST host a direct builder is bypassed, so capture must follow\n // what the HOST reads. Mirrors `hostMode: 'cst'` in the compiled engine, which\n // captures unconditionally there because it knows the mode at compile time.\n const hasDirectValue = build !== undefined || project !== undefined\n const hostCst = hasDirectValue && cstOutputHost(ctx.build)\n const effTrivia = capturesTrivia || hostCst\n const effFields = capturesFields || (hostCst && hasOwnFields)\n const saved = beginCstNodeCapture(ctx)\n const savedFields = ctx._fields\n ctx._fields = effFields ? [] : undefined\n // Per-node-type trivia-kind mask: a structural (host-built) node may want\n // only certain kinds captured (comments for Ruleset, whitespace for\n // CompoundSelector). Scoped here, restored below \u2014 matches the compiled path.\n const savedMask = ctx._triviaCaptureMask\n if (build === undefined && project === undefined && ctx.build?._parsemanTriviaKinds !== undefined && def.type !== undefined) {\n ctx._triviaCaptureMask = ctx.build._parsemanTriviaKinds(def.type)\n }\n // Short-circuit the per-node trivia push (scanTrivia gates on captureTrivia)\n // without touching the global _triviaLog, which is committed independently.\n if (!effTrivia) ctx.captureTrivia = false\n let r = combinator.parse(input, pos, ctx)\n if (r.ok && trailingTrivia && ctx.trivia) {\n const end = consumeTrivia(input, r.span.end, ctx)\n r = { ...r, span: { start: r.span.start, end } }\n }\n const fields = effFields ? buildFieldMap(ctx._fields) : undefined\n ctx._fields = savedFields\n ctx._triviaCaptureMask = savedMask\n const { children, rawChildren, triviaLog } = endCstNodeCapture(ctx, saved)\n\n if (!r.ok) return r\n\n // unwrap/collapse: a single captured child IS the value \u2014 skip build.\n const st = clonesState && ctx.state !== undefined ? Object.assign({}, ctx.state as Record<string, unknown>) : undefined\n const nodeType = def.type ?? missingInferredType()\n const cstOutput = cstOutputHost(ctx.build)\n const span = ctx.trackLines ? annotateSpanFromLineContext(r.span, ctx) : r.span\n // A direct builder that never declared `state` still owes the host its snapshot.\n // The clone happens AFTER the body, so unlike trivia it needs no gate up front \u2014\n // build it here, on a branch the eval-AST path never takes. Matches what\n // `hostMode: 'cst'` does in the compiled engine.\n const hostState = clonesState\n ? st\n : ctx.state !== undefined ? Object.assign({}, ctx.state as Record<string, unknown>) : undefined\n const built: unknown = unwrap && children.length === 1\n ? unwrapChild(children[0])\n : collapse && children.length === 1\n ? children[0]\n // Collapse applies wherever the node's VALUE comes from the host: a structural\n // node, or ANY node under a positioned-CST host, where the direct builder is\n // bypassed and the produced thing is a host-owned CST node either way. Gating on\n // `!build` alone made `cstBuildHost({ collapse })` a documented no-op for every\n // grammar whose rules carry reducers \u2014 silently, in both engines.\n : (cstOutput || (!build && project === undefined))\n && ctx.build?._parsemanCstCollapse\n && children.length === 1\n && rawChildren.length === 1\n && ctx.build._parsemanCstCollapse(nodeType, children[0], children, rawChildren)\n ? children[0]\n : project !== undefined\n ? cstOutput && ctx.build\n ? ctx.build(nodeType, children, fields, span, rawChildren, triviaLog, hostState, tags)\n : projectChild(children, project, nodeType)\n : build\n // A direct builder normally owns its result. The positioned-CST host is\n // the one exception: it must never receive an arbitrary AST object as a\n // child of a CST node, so build this grammar node through that host.\n ? cstOutput && ctx.build\n ? ctx.build(nodeType, children, fields, span, rawChildren, triviaLog, hostState, tags)\n : build(children, fields, span, rawChildren, triviaLog, st)\n // Structural node: a `ctx.build` host if present, else a default CST.\n : ctx.build\n ? ctx.build(nodeType, children, fields, span, rawChildren, triviaLog, st, tags)\n : { _tag: 'node', type: nodeType, span: ctx.trackLines ? { ...span } : { start: r.span.start, end: r.span.end }, state: st ?? null, children }\n const rawEntry = isCstChild(built)\n ? built\n // A direct semantic object is opaque to the raw CST, but its source is\n // not. Preserve the exact matched span so legacy/structural parents can\n // retain text and trivia without fabricating an empty token.\n : { _tag: 'leaf', value: typeof built === 'string' ? built : typeof built === 'object' && built !== null ? input.slice(r.span.start, r.span.end) : '', span }\n if (saved.buf !== undefined || saved.ch !== undefined) {\n pushCstChild(ctx, built, rawEntry)\n }\n return { ok: true, value: built as N, span }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\nimport { pushCstLeaf, cstCaptureActive } from '../cst/capture-buffer.ts'\n\n/**\n * Treat a parser as one source token.\n *\n * The wrapped parser runs with trivia cleared, so its parts must be contiguous.\n * On success the token returns the matched source text and captures one CST leaf\n * for the full span, suppressing any internal terminal leaves.\n */\nexport function token(root: Combinator<unknown>): Combinator<string> {\n const meta: ParserMeta = {\n firstSet: root._meta.firstSet,\n canMatchNewline: root._meta.canMatchNewline,\n isTrivia: false,\n }\n return {\n _tag: 'token',\n _meta: meta,\n _def: { tag: 'token', parser: root },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<string> {\n const savedTrivia = ctx.trivia\n const savedKinds = ctx.triviaKindLabels\n const savedBuf = ctx._cstBuf\n const savedChildren = ctx._cstChildren\n const savedLeaves = ctx._cstLeaves\n const savedRaw = ctx._cstRawChildren\n const savedTriviaLog = ctx._cstTriviaLog\n const savedOuterTriviaLog = ctx._triviaLog\n const savedRootTriviaLog = ctx._rootTriviaLog\n const wasCapturing = cstCaptureActive(ctx)\n\n ctx.trivia = undefined\n ctx.triviaKindLabels = undefined\n ctx._cstBuf = undefined\n ctx._cstChildren = undefined\n ctx._cstLeaves = undefined\n ctx._cstRawChildren = undefined\n ctx._cstTriviaLog = undefined\n delete ctx._triviaLog\n delete ctx._rootTriviaLog\n\n let result: ParseResult<unknown>\n try {\n result = root.parse(input, pos, ctx)\n } finally {\n ctx.trivia = savedTrivia\n ctx.triviaKindLabels = savedKinds\n ctx._cstBuf = savedBuf\n ctx._cstChildren = savedChildren\n ctx._cstLeaves = savedLeaves\n ctx._cstRawChildren = savedRaw\n ctx._cstTriviaLog = savedTriviaLog\n if (savedOuterTriviaLog === undefined) delete ctx._triviaLog\n else ctx._triviaLog = savedOuterTriviaLog\n if (savedRootTriviaLog === undefined) delete ctx._rootTriviaLog\n else ctx._rootTriviaLog = savedRootTriviaLog\n }\n\n if (!result.ok) return result\n\n const span = result.span\n const value = input.slice(pos, span.end)\n if (wasCapturing) pushCstLeaf(ctx, { _tag: 'leaf', value, span })\n return { ok: true, value, span }\n },\n }\n}\n\n/**\n * Reduce a structural parser to one semantic leaf.\n *\n * Unlike `token()`, `leaf()` does not change trivia policy: put `noTrivia()` or\n * a scoped `parser({ trivia })` inside the supplied grammar when that region has\n * a local spacing rule. Internal CST captures are suppressed, while selected\n * root-source trivia remains visible, and one leaf with the reducer's value and\n * the complete consumed span is exposed to the parent.\n */\nexport function leaf<T, U>(\n root: Combinator<T>,\n fn: (value: T, span: { start: number; end: number }) => U,\n): Combinator<U> {\n const meta: ParserMeta = {\n firstSet: root._meta.firstSet,\n canMatchNewline: root._meta.canMatchNewline,\n isTrivia: false,\n }\n return {\n _tag: 'leaf',\n _meta: meta,\n _def: { tag: 'leaf', parser: root as Combinator<unknown>, fn: fn as (v: unknown, span: { start: number; end: number }) => unknown },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<U> {\n const savedBuf = ctx._cstBuf\n const savedChildren = ctx._cstChildren\n const savedLeaves = ctx._cstLeaves\n const savedRaw = ctx._cstRawChildren\n const savedTriviaLog = ctx._cstTriviaLog\n const savedOuterTriviaLog = ctx._triviaLog\n const wasCapturing = cstCaptureActive(ctx)\n ctx._cstBuf = undefined\n ctx._cstChildren = undefined\n ctx._cstLeaves = undefined\n ctx._cstRawChildren = undefined\n ctx._cstTriviaLog = undefined\n delete ctx._triviaLog\n let result: ParseResult<T>\n try { result = root.parse(input, pos, ctx) }\n finally {\n ctx._cstBuf = savedBuf\n ctx._cstChildren = savedChildren\n ctx._cstLeaves = savedLeaves\n ctx._cstRawChildren = savedRaw\n ctx._cstTriviaLog = savedTriviaLog\n if (savedOuterTriviaLog === undefined) delete ctx._triviaLog\n else ctx._triviaLog = savedOuterTriviaLog\n }\n if (!result.ok) return result\n const value = fn(result.value, result.span)\n if (wasCapturing) pushCstLeaf(ctx, { _tag: 'leaf', value, span: result.span })\n return { ok: true, value, span: result.span }\n },\n }\n}\n", "import type { Combinator, ParseContext, ParseResult, ParserMeta } from '../types.ts'\n\n/**\n * Runs `combinator` with `ctx.state` set to `extra` for the duration of the parse.\n * The outer user context is restored on exit (lexical scoping).\n *\n * const functionBody = withCtx({ inFn: true },\n * sequence(literal('{'), many(statement), literal('}'))\n * )\n *\n * Read back with guard() or from within a transform's span argument.\n */\nexport function withCtx<U, T>(extra: U, combinator: Combinator<T>): Combinator<T> {\n const meta: ParserMeta = {\n firstSet: combinator._meta.firstSet,\n canMatchNewline: combinator._meta.canMatchNewline,\n isTrivia: false,\n }\n return {\n _tag: 'withCtx',\n _meta: meta,\n _def: { tag: 'withCtx', extra, parser: combinator as Combinator<unknown> },\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<T> {\n return combinator.parse(input, pos, { ...ctx, state: extra })\n },\n }\n}\n", "/**\n * Serialize a compiled rule map BACK to a compact combinator-construction source\n * expression \u2014 the \"IR\" a composed grammar carries instead of ~1MB of fully\n * lowered `_r_<Name>` function source. At fuse time the expression is evaluated\n * (with the combinator constructors in scope) to reconstruct the rule map, then\n * re-lowered via `compileLinkable` \u2014 identical behaviour, a fraction of the bytes.\n *\n * The output mirrors how a grammar is WRITTEN, not how it lowers:\n * - a rule reference (`g.Foo`, a `lazy` carrying `_ruleName`) \u2192 `g[\"Foo\"]`\n * - a sub-combinator shared by identity (referenced \u22652\u00D7, e.g. a `balanced` const\n * reused across rules) \u2192 a hoisted `const _s<N> = \u2026`, referenced by name, so it\n * stays shared through the round trip (and `compileLinkable` re-hoists it)\n * - a self-referential combinator (`balanced`'s internal `self = ref()`) \u2192 a\n * `ref()` + `.define()` closure, the same shape the library combinator emits\n * - `transform`/`node` callbacks \u2192 their captured source (`fnSrc`/`buildSrc`)\n *\n * Returns null if the map can't be faithfully serialized (a callback without\n * source, or an unsupported construct) \u2014 the caller then keeps the lowered source.\n */\nimport type { Combinator, DispatchMatcherCase, ParserDef } from '../types.ts'\nimport { rules } from '../combinators/parser.ts'\nimport { ref } from '../combinators/ref.ts'\nimport { regex } from '../combinators/regex.ts'\nimport { literal } from '../combinators/literal.ts'\nimport { keywords } from '../combinators/keywords.ts'\nimport { sequence } from '../combinators/sequence.ts'\nimport { choice } from '../combinators/choice.ts'\nimport { dispatch, endsWith, matches, otherwise, routed, startsWith, when } from '../combinators/dispatch.ts'\nimport { attempt } from '../combinators/attempt.ts'\nimport { many, oneOrMore, optional, sepBy } from '../combinators/repeat.ts'\nimport { not } from '../combinators/not.ts'\nimport { peek } from '../combinators/peek.ts'\nimport { node } from '../combinators/node.ts'\nimport { parser } from '../combinators/grammar.ts'\nimport { scanTo } from '../combinators/scanTo.ts'\nimport { token, leaf } from '../combinators/token.ts'\nimport { classifiedTrivia, transform, skip, trivia, label, field } from '../combinators/map.ts'\nimport { analyzeLabeledTrivia } from '../cst/trivia-kinds.ts'\nimport { expect as expectC } from '../combinators/expect.ts'\nimport { withCtx } from '../combinators/withCtx.ts'\n\ntype Comb = Combinator<unknown>\n\n/** Child combinators of a def, in construction order (mirrors codegen's childrenOf). */\nfunction childrenOf(def: ParserDef): Comb[] {\n switch (def.tag) {\n case 'sequence':\n case 'choice': return def.parsers\n case 'dispatch': return [def.selector, ...def.cases.map(entry => entry.parser), ...(def.matchers ? def.matchers.map(entry => entry.parser) : []), ...(def.otherwise ? [def.otherwise] : [])]\n case 'many':\n case 'oneOrMore':\n case 'optional':\n case 'attempt':\n case 'transform':\n case 'trivia':\n case 'token':\n case 'leaf':\n case 'label':\n case 'field':\n case 'not':\n case 'peek':\n case 'node':\n case 'withCtx':\n case 'expect': return [def.parser]\n case 'grammar': return def.triviaParser ? [def.parser, def.triviaParser] : [def.parser]\n case 'sepBy': return [def.parser, def.separator]\n case 'skip': return [def.main, def.skipped]\n case 'scanTo': return [def.sentinel, ...def.skip]\n case 'routed': return def.fallback ? [def.fallback] : []\n case 'lazy':\n case 'literal':\n case 'regex':\n case 'keywords':\n case 'guard':\n case 'recover':\n case 'unknown': return []\n }\n}\n\nconst ruleNameOf = (c: Comb): string | undefined =>\n (c as unknown as { _ruleName?: string })._ruleName\n\n/** Resolve a lazy's target, or null if it isn't defined yet (external ref). */\nfunction lazyTarget(c: Comb): Comb | null {\n if (c._def.tag !== 'lazy') return null\n try { return c._def.thunk() } catch { return null }\n}\n\nclass Unserializable extends Error {}\n\n/** `, { min, max, trailing }` \u2014 omitted entirely when everything is at its default. */\nfunction repeatOpts(min: number, max: number | undefined, trailing?: string): string {\n const parts: string[] = []\n if (min !== 0) parts.push(`min: ${min}`)\n if (max !== undefined) parts.push(`max: ${max}`)\n if (trailing !== undefined) parts.push(`trailing: ${JSON.stringify(trailing)}`)\n return parts.length === 0 ? '' : `, { ${parts.join(', ')} }`\n}\n\nfunction projectOpt(project: Extract<ParserDef, { tag: 'node' }>['project']): string | undefined {\n if (project === undefined) return undefined\n return `project: ${project}`\n}\n\nfunction tagsOpt(tags: Extract<ParserDef, { tag: 'node' }>['tags']): string | undefined {\n if (tags === undefined || tags.length === 0) return undefined\n return `tags: ${JSON.stringify(tags)}`\n}\n\nfunction matcherExpr(entry: DispatchMatcherCase): string {\n switch (entry.kind) {\n case 'startsWith':\n return `startsWith(${JSON.stringify(entry.value)})`\n case 'endsWith':\n return `endsWith(${JSON.stringify(entry.value)})`\n case 'matches':\n return `matches(${new RegExp(entry.value, entry.flags ?? '').toString()})`\n }\n}\n\nexport function serializeRuleMap(\n ruleMap: ReadonlyArray<readonly [string, Comb]>,\n scanSkip?: readonly Comb[] | null,\n): string | null {\n try {\n return new Serializer(ruleMap, scanSkip ?? []).run()\n } catch (e) {\n if (e instanceof Unserializable) {\n if (process.env.PARSEMAN_IR_DEBUG) console.error(`[ir] fallback: ${(e as Error).message}`)\n return null\n }\n throw e\n }\n}\n\n/** Reconstruct a rule map from serialized IR (the inverse of `serializeRuleMap`) \u2014\n * evaluate the combinator-construction expression with every constructor in scope.\n * Used at fuse time (runtime linker + build-time plugin) to re-lower carried IR. */\nexport function evalRuleMapIR(ir: string): Array<[string, Comb]> {\n // `_tf`/`_nd` reconstruct a transform/node AND restore its captured callback\n // source (`_def.fnSrc`/`buildSrc`) so re-lowering inlines it statically. The live\n // fn is only needed for interpreted mode; a self-contained transform source is\n // eval'd, a node build (which may reference imported AST classes) is left to its\n // source only. Macro-only validation metadata is carried as plain data: this\n // runtime module never parses callback source or imports a compiler frontend.\n const _tf = (child: Comb, src: string, recognitionOnly = false): Comb => {\n let fn: (...a: unknown[]) => unknown\n // eslint-disable-next-line no-eval\n try { fn = (0, eval)(`(${src})`) } catch { fn = () => { throw new Error('IR transform fn not materialized') } }\n const t = transform(child as never, fn as never)\n ;(t._def as { fnSrc?: string }).fnSrc = src\n if (recognitionOnly) (t._def as { recognitionOnly?: boolean }).recognitionOnly = true\n return t as Comb\n }\n const _lf = (child: Comb, src: string): Comb => {\n let fn: (...a: unknown[]) => unknown\n // eslint-disable-next-line no-eval\n try { fn = (0, eval)(`(${src})`) } catch { fn = () => { throw new Error('IR leaf fn not materialized') } }\n const l = leaf(child as never, fn as never)\n ;(l._def as { fnSrc?: string }).fnSrc = src\n return l as Comb\n }\n const _nd = (type: string, child: Comb, src: string, opts?: unknown, staticError?: readonly string[], sigSrc?: string): Comb => {\n if (staticError !== undefined && staticError.length > 0) {\n throw new Error(`IR direct node builder for ${type} must be macro-static and self-contained; unsupported binding(s): ${staticError.join(', ')}`)\n }\n // A serialized direct builder needs an inert sentinel as well as buildSrc.\n // `node(..., undefined)` is structural, so re-lowering a composed artifact\n // silently routes it through ctx.build/default CST even though the IR still\n // carries the callback source. The compiler is the only consumer that may\n // materialize `buildSrc`; raw IR interpretation deliberately rejects direct\n // builders rather than evaluating arbitrary captured source at runtime.\n const n = node(type, child as never, (() => { throw new Error('IR node build requires static re-lowering') }) as never, opts as never)\n ;(n._def as { buildSrc?: string; buildStaticError?: readonly string[] }).buildSrc = src\n if (staticError !== undefined) (n._def as { buildStaticError?: readonly string[] }).buildStaticError = staticError\n // Analysis-only resolved reducer signature (see `buildAnalysisSrc`). Without it a\n // re-lowered composed artifact silently re-acquires the fail-open capture cost the\n // authoring module had already resolved away.\n if (sigSrc !== undefined) (n._def as { buildSigSrc?: string }).buildSigSrc = sigSrc\n return n as Comb\n }\n // `_gch` rebuilds a GATED choice AND restores its `_def.gateSrcs` (parallel to the\n // arms) \u2014 the gate mirror of `_tf`/`_nd`. Each item is either a plain arm or a\n // `[gateSource, arm]` tuple: the source is eval'd to the live predicate (interpreted\n // mode) and recorded as the arm's gateSrcs entry so re-lowering INLINES the gate\n // statically (keeping the artifact fusible via `emitFusedSource`). A missing/failed\n // source falls back to a throwing predicate \u2014 the same contract as `_tf`.\n const _gch = (items: Array<Comb | [string, Comb]>): Comb => {\n const gateSrcs: (string | null)[] = []\n const arms = items.map(it => {\n if (Array.isArray(it)) {\n const [src, comb] = it\n gateSrcs.push(src)\n let gate: (s: unknown) => boolean\n // eslint-disable-next-line no-eval\n try { gate = (0, eval)(`(${src})`) } catch { gate = () => { throw new Error('IR gate fn not materialized') } }\n return { gate, combinator: comb }\n }\n gateSrcs.push(null)\n return it\n })\n const c = (choice as (...a: unknown[]) => Comb)(...arms)\n // `choice` is the authority on gate alignment; `gateSrcs` must line up 1:1 with\n // the constructed `_def.gates`. They always do on the normal path (both from the\n // same `items.map`), but assert it so a future change in `choice` that coalesces\n // or drops arms can't silently ship a mis-aligned gate-source array.\n const gates = (c._def as { gates?: unknown[] }).gates\n if (gates && gates.length !== gateSrcs.length) {\n throw new Error(`_gch: gateSrcs length ${gateSrcs.length} != choice gates length ${gates.length}`)\n }\n ;(c._def as { gateSrcs?: (string | null)[] }).gateSrcs = gateSrcs\n return c\n }\n // `_wc` rebuilds a `withCtx` AND restores its `_def.extraSrc` (the source of the\n // `extra`/state value) \u2014 the withCtx mirror of `_tf`/`_nd`/`_gch`. The source is\n // eval'd to the live `extra` value (interpreted mode) and recorded on the def so\n // re-lowering INLINES the state getter statically (`() => (extraSrc)`), keeping the\n // artifact fusible via `emitFusedSource`. A plain `withCtx(value, inner)` would\n // leave `extraSrc` unset \u2192 codegen emits a source-less runtime closure (a non-static\n // callback) \u2192 `emitFusedSource` fails and a downstream `compose()` silently falls\n // back to a runtime fuse. A missing/failed source falls back to `undefined` state \u2014\n // the same best-effort contract as `_tf`.\n const _wc = (src: string, inner: Comb): Comb => {\n let extra: unknown\n // eslint-disable-next-line no-eval\n try { extra = (0, eval)(`(${src})`) } catch { extra = undefined }\n const w = (withCtx as (e: unknown, c: Comb) => Comb)(extra, inner)\n ;(w._def as { extraSrc?: string }).extraSrc = src\n return w\n }\n // eslint-disable-next-line no-new-func\n const fn = new Function(\n 'rules', 'ref', 'regex', 'literal', 'keywords', 'sequence', 'choice', 'dispatch', 'when', 'startsWith', 'endsWith', 'matches', 'otherwise', 'routed', 'attempt',\n 'many', 'oneOrMore', 'optional', 'sepBy', 'not', 'peek', 'node', 'parser',\n 'scanTo', 'token', 'leaf', 'transform', 'skip', 'trivia', 'classifiedTrivia', 'label', 'field', 'expect', '_tf', '_lf', '_nd', '_gch', '_wc',\n `return (${ir})`,\n )\n const map = fn(\n rules, ref, regex, literal, keywords, sequence, choice, dispatch, when, startsWith, endsWith, matches, otherwise, routed, attempt,\n many, oneOrMore, optional, sepBy, not, peek, node, parser,\n scanTo, token, leaf, transform, skip, trivia, classifiedTrivia, label, field, expectC, _tf, _lf, _nd, _gch, _wc,\n ) as Record<string, Comb>\n return Object.entries(map)\n}\n\nclass Serializer {\n private counts = new Map<Comb, number>()\n private selfRef = new Set<Comb>() // combinators reached by an unnamed lazy pointing back into their own subtree\n private constName = new Map<Comb, string>()\n private emitted = new Set<string>()\n private decls: string[] = []\n private ruleValues = new Set<Comb>()\n private localRuleNames = new Map<Comb, string>()\n private ruleMap: ReadonlyArray<readonly [string, Comb]>\n private scanSkip: readonly Comb[]\n\n constructor(ruleMap: ReadonlyArray<readonly [string, Comb]>, scanSkip: readonly Comb[] = []) {\n this.ruleMap = ruleMap\n this.scanSkip = scanSkip\n for (const [name, c] of ruleMap) {\n this.localRuleNames.set(c, name)\n this.ruleValues.add(this.body(c))\n }\n }\n\n /** A grammar-level `scanSkip` unit is an opaque TERMINAL (a string, a balanced\n * bracket) \u2014 it must not reach a grammar-rule ref (`g[name]`), because the\n * serialized `scanSkip` array sits in the `rules({ scanSkip })` OPTIONS position,\n * outside the `(g) => \u2026` factory where `g` is bound. A unit that does reference a\n * rule can't be carried in options; bail to the full-pieces fallback. */\n private assertNoRuleRef(c: Comb, seen: Set<Comb>): void {\n if (seen.has(c)) return\n seen.add(c)\n if (c._def.tag === 'lazy') {\n if (ruleNameOf(c) !== undefined) throw new Unserializable('scanSkip unit references a grammar rule')\n const target = lazyTarget(c)\n if (target) this.assertNoRuleRef(target, seen)\n return\n }\n for (const child of childrenOf(c._def)) this.assertNoRuleRef(child, seen)\n }\n\n /** A `rules()` map wraps each rule value in a named `lazy` proxy; the real body is\n * its target (compileLinkable unwraps the same way). A ref INSIDE a body stays a\n * `g[name]` ref \u2014 only the top-level entry is unwrapped. */\n private body(c: Comb): Comb {\n return c._def.tag === 'lazy' && ruleNameOf(c) !== undefined ? (lazyTarget(c) ?? c) : c\n }\n\n run(): string {\n for (const [, c] of this.ruleMap) this.analyze(this.body(c), new Set())\n for (const c of this.scanSkip) { this.assertNoRuleRef(c, new Set()); this.analyze(c, new Set()) }\n // A shared sub-combinator (count \u2265 2) or a self-ref target gets a const, EXCEPT\n // a top-level rule value (it already lives under its rule name).\n let n = 0\n for (const [c, count] of this.counts) {\n if (this.ruleValues.has(c)) continue\n if (count >= 2 || this.selfRef.has(c)) this.constName.set(c, `_s${n++}`)\n }\n // Two decl scopes. `scanSkip` is emitted FIRST into `outerDecls` (an IIFE that\n // wraps the whole rules() call) because the `{ scanSkip }` options object\n // precedes the `(g) => \u2026` factory and so cannot see consts declared inside it.\n // A scanSkip unit is grammar-rule free (asserted above), so every const it\n // reaches is g-free and safe in the outer scope; the `emitted` guard then keeps\n // each remaining (factory-only, possibly `g[name]`-referencing) const inside the\n // factory. With no scanSkip, `outerDecls` stays empty and the output is\n // byte-identical to the pre-scanSkip form.\n const outerDecls: string[] = []\n const innerDecls: string[] = []\n let optionsArg = ''\n if (this.scanSkip.length > 0) {\n this.decls = outerDecls\n const units = this.scanSkip.map(c => this.ref(c, null))\n optionsArg = `{ scanSkip: [${units.join(', ')}] }, `\n }\n this.decls = innerDecls\n const body = this.ruleMap\n .map(([name, c]) => ` ${JSON.stringify(name)}: ${this.wrap(this.body(c))}`)\n .join(',\\n')\n // Shared consts go INSIDE the factory: they can reference `g[name]` rule refs,\n // and `g` only exists in the factory scope.\n const factory = innerDecls.length === 0\n ? `(g) => ({\\n${body}\\n})`\n : `(g) => {\\n${innerDecls.map(d => ' ' + d).join('\\n')}\\n return ({\\n${body}\\n})\\n}`\n const call = `rules(${optionsArg}${factory})`\n return outerDecls.length === 0\n ? call\n : `(() => {\\n${outerDecls.map(d => ' ' + d).join('\\n')}\\n return ${call}\\n})()`\n }\n\n /** Count identity references and flag self-referential subtrees. `active` is the\n * set of combinators on the current DFS path (to detect a lazy pointing back). */\n private analyze(c: Comb, active: Set<Comb>): void {\n const def = c._def\n if (def.tag === 'lazy') {\n if (ruleNameOf(c) !== undefined) return // named rule ref \u2014 resolved by g[name]\n const target = lazyTarget(c)\n if (!target) throw new Unserializable('unresolved unnamed ref')\n if (active.has(target)) { this.selfRef.add(target); return } // recursion into an ancestor\n this.analyze(target, active) // inline (unnamed, non-recursive) \u2014 rare\n return\n }\n if (def.tag === 'guard' || def.tag === 'recover' || def.tag === 'unknown') {\n throw new Unserializable(`unsupported tag ${def.tag}`)\n }\n this.counts.set(c, (this.counts.get(c) ?? 0) + 1)\n if ((this.counts.get(c) ?? 0) > 1) return // already descended\n active.add(c)\n for (const child of childrenOf(def)) this.analyze(child, active)\n active.delete(c)\n }\n\n /** Reference `c`: a const var if it has one (emitting its decl first), else inline.\n * `selfOf` is the const currently being wrapped in a ref()/define closure \u2014 an\n * unnamed lazy back into it emits the local ref var instead of recursing. */\n private ref(c: Comb, selfOf: { comb: Comb; var: string } | null): string {\n const cn = this.constName.get(c)\n if (cn) { this.emitDecl(c); return cn }\n return this.expr(c, selfOf)\n }\n\n private emitDecl(c: Comb): void {\n const name = this.constName.get(c)!\n if (this.emitted.has(name)) return\n this.emitted.add(name) // mark first (cycle-safe)\n this.decls.push(`const ${name} = ${this.wrap(c)}`)\n }\n\n private selfN = 0\n\n /** Emit `c`'s own constructor call, wrapping it in a `ref()`+`.define()` closure\n * if it is self-referential (an unnamed lazy in its subtree points back to it) \u2014\n * the shape `balanced()` and other recursive library combinators build. */\n private wrap(c: Comb): string {\n if (!this.selfRef.has(c)) return this.expr(c, null)\n const rv = `_rr${this.selfN++}`\n const bodyExpr = this.expr(c, { comb: c, var: rv })\n return `(() => { const ${rv} = ref(); const _b = ${bodyExpr}; ${rv}.define(_b); return _b })()`\n }\n\n /** Emit the constructor-call source for `c` (never a const shortcut for `c` itself). */\n private expr(c: Comb, selfOf: { comb: Comb; var: string } | null): string {\n const def = c._def\n const kid = (x: Comb) => this.ref(x, selfOf)\n switch (def.tag) {\n case 'lazy': {\n const name = this.localRuleNames.get(c) ?? ruleNameOf(c)\n if (name !== undefined) return `g[${JSON.stringify(name)}]`\n const target = lazyTarget(c)!\n if (selfOf && target === selfOf.comb) return selfOf.var\n return this.ref(target, selfOf)\n }\n case 'literal':\n return `literal(${JSON.stringify(def.value)}${def.caseInsensitive ? ', { caseInsensitive: true }' : ''})`\n case 'regex':\n return `regex(${JSON.stringify(def.source)}, ${JSON.stringify(def.flags)})`\n case 'keywords':\n return `keywords(${JSON.stringify(def.words)}, { caseInsensitive: ${def.caseInsensitive}${def.boundary !== undefined ? `, boundary: ${JSON.stringify(def.boundary)}` : ''} })`\n case 'sequence':\n return `sequence(${def.parsers.map(kid).join(', ')})`\n case 'choice': {\n // Ungated choices stay `choice(a, b, \u2026)` byte-for-byte as before.\n const gates = def.gates\n if (gates.every(g => g === null)) return `choice(${def.parsers.map(kid).join(', ')})`\n // A gated choice round-trips through `_gch`, which rebuilds the choice AND\n // re-attaches `_def.gateSrcs` from each arm's captured gate SOURCE. Preserving\n // gateSrcs is load-bearing: on re-lowering, codegen inlines the gate from its\n // source (a static callback), so the re-lowered artifact stays STATICALLY\n // FUSIBLE. A plain `choice({ gate: fn, \u2026 })` would rebuild the predicate as a\n // source-less runtime closure \u2192 a non-static callback \u2192 `emitFusedSource`\n // (macro static fusion) fails and `compose()` silently falls back to a runtime\n // fuse. Without a captured source we cannot re-emit the gate \u2192 keep full pieces.\n const gateSrcs = def.gateSrcs\n const items = def.parsers.map((p, i) => {\n if (gates[i] === null) return kid(p)\n const src = gateSrcs?.[i]\n if (src == null) throw new Unserializable('choice gate() has no captured source')\n // `[gateSource, arm]` \u2014 `_gch` evals the source to the live predicate and\n // records it as the arm's `gateSrcs` entry.\n return `[${JSON.stringify(src)}, ${kid(p)}]`\n })\n return `_gch([${items.join(', ')}])`\n }\n case 'dispatch': {\n const arms = def.cases.map(entry =>\n `when(${entry.keys.length === 1 ? JSON.stringify(entry.keys[0]) : JSON.stringify(entry.keys)}, ${kid(entry.parser)}${entry.caseInsensitive ? ', { caseInsensitive: true }' : ''})`\n )\n if (def.matchers) {\n for (const entry of def.matchers) {\n arms.push(`when(${matcherExpr(entry)}, ${kid(entry.parser)}${entry.caseInsensitive ? ', { caseInsensitive: true }' : ''})`)\n }\n }\n if (def.otherwise) arms.push(`otherwise(${kid(def.otherwise)})`)\n return `dispatch(${kid(def.selector)}${arms.length === 0 ? '' : `, ${arms.join(', ')}`})`\n }\n case 'many': return `many(${kid(def.parser)}${repeatOpts(def.min, def.max)})`\n // A `oneOrMore` def with min > 1 came from `many(x, { min: n })`; round-trip\n // it through `many` so the bounds survive (oneOrMore defaults min to 1).\n case 'oneOrMore': return def.min === 1 && def.max === undefined\n ? `oneOrMore(${kid(def.parser)})`\n : `many(${kid(def.parser)}${repeatOpts(def.min, def.max)})`\n case 'optional': return `optional(${kid(def.parser)})`\n case 'attempt': return `attempt(${kid(def.parser)})`\n case 'sepBy': return `sepBy(${kid(def.parser)}, ${kid(def.separator)}${repeatOpts(def.min, def.max, def.trailing)})`\n case 'not': return `not(${kid(def.parser)})`\n case 'peek': return `peek(${kid(def.parser)})`\n case 'routed': return def.fallback === undefined ? 'routed()' : `routed(${kid(def.fallback)})`\n case 'trivia': return `trivia(${kid(def.parser)})`\n case 'token': return `token(${kid(def.parser)})`\n case 'leaf': {\n if (def.fnSrc === undefined) throw new Unserializable('leaf without fnSrc')\n return `_lf(${kid(def.parser)}, ${JSON.stringify(def.fnSrc)})`\n }\n case 'label': return `label(${JSON.stringify(def.label)}, ${kid(def.parser)})`\n case 'field': return `field(${JSON.stringify(def.name)}, ${kid(def.parser)})`\n case 'expect': return `expect(${kid(def.parser)}${def.label !== undefined ? `, ${JSON.stringify(def.label)}` : ''})`\n case 'skip': return `skip(${kid(def.main)}, ${kid(def.skipped)})`\n case 'scanTo':\n return `scanTo(${kid(def.sentinel)}, { skip: [${def.skip.map(kid).join(', ')}]${def.raw ? ', raw: true' : ''}, orEOF: ${def.orEOF} })`\n case 'transform': {\n if (def.fnSrc === undefined) throw new Unserializable('transform without fnSrc')\n // `_tf` sets `_def.fnSrc` so re-lowering INLINES the callback (a plain\n // `transform(child, fn)` would leave fnSrc unset \u2192 a non-static runtime\n // callback that emitFusedSource can't inline).\n return `_tf(${kid(def.parser)}, ${JSON.stringify(def.fnSrc)}${def.recognitionOnly ? ', true' : ''})`\n }\n case 'node': {\n if (def.build !== undefined && def.buildSrc === undefined) throw new Unserializable('node build without buildSrc')\n const projectEntry = projectOpt(def.project)\n const tagEntry = tagsOpt(def.tags)\n const optEntries = [\n ...(def.unwrap ? ['unwrap: true'] : []),\n ...(def.collapse ? ['collapse: true'] : []),\n ...(projectEntry === undefined ? [] : [projectEntry]),\n ...(def.captureTrivia ? ['captureTrivia: true'] : []),\n ...(def.trailingTrivia ? ['trailingTrivia: true'] : []),\n // Declared or resolved arity. Carried so a re-lowered composed artifact does\n // not silently re-acquire the fail-open capture cost this module resolved away.\n ...(def.buildArity === undefined ? [] : [`buildArity: ${def.buildArity}`]),\n ...(tagEntry === undefined ? [] : [tagEntry]),\n ]\n const opts = optEntries.length > 0 ? `, { ${optEntries.join(', ')} }` : ''\n // `_nd` sets `_def.buildSrc` (same reason as `_tf`). No build \u2192 plain node.\n if (def.type === undefined) {\n if (def.buildSrc !== undefined) throw new Unserializable('inferred node build without inferred type')\n return opts ? `node(${kid(def.parser)}, undefined${opts})` : `node(${kid(def.parser)})`\n }\n if (def.buildSrc !== undefined) {\n // Trailing optionals, emitted only when present so an artifact that carries\n // neither is byte-identical to what previous versions produced.\n const tail: string[] = []\n if (def.buildStaticError !== undefined || def.buildSigSrc !== undefined) {\n if (!opts) tail.push('undefined')\n tail.push(def.buildStaticError === undefined ? 'undefined' : JSON.stringify(def.buildStaticError))\n }\n if (def.buildSigSrc !== undefined) tail.push(JSON.stringify(def.buildSigSrc))\n const trailing = tail.length > 0 ? `, ${tail.join(', ')}` : ''\n return `_nd(${JSON.stringify(def.type)}, ${kid(def.parser)}, ${JSON.stringify(def.buildSrc)}${opts}${trailing})`\n }\n return opts ? `node(${JSON.stringify(def.type)}, ${kid(def.parser)}, undefined${opts})` : `node(${JSON.stringify(def.type)}, ${kid(def.parser)})`\n }\n case 'grammar': {\n const classified = def.triviaParser?._meta.rootTriviaClassified === true\n const spec = classified && def.triviaParser ? analyzeLabeledTrivia(def.triviaParser) : null\n if (classified && !spec) throw new Unserializable('classified trivia without labeled arms')\n const trivia = def.clearTrivia\n ? 'null'\n : spec\n ? `classifiedTrivia({ ${spec.arms.map(arm => `${JSON.stringify(arm.label)}: ${kid(arm.parser)}`).join(', ')} })`\n : def.triviaParser ? kid(def.triviaParser) : 'undefined'\n return `parser({ trivia: ${trivia}${def.captureTrivia ? ', captureTrivia: true' : ''}${def.rootCapture ? `, rootCapture: ${JSON.stringify(def.rootCapture)}` : ''}${def.trackLines ? ', trackLines: true' : ''} }, ${kid(def.parser)})`\n }\n case 'withCtx': {\n // A `withCtx` round-trips through `_wc`, which rebuilds it AND re-attaches\n // `_def.extraSrc` from the captured `extra` SOURCE. Preserving extraSrc is\n // load-bearing for the same reason as `_tf`/`_gch`: on re-lowering, codegen\n // inlines the state getter from source (a static callback), so the re-lowered\n // artifact stays STATICALLY FUSIBLE. Without a captured source we cannot\n // re-emit the state statically \u2192 keep full pieces (interpreter fallback).\n if (def.extraSrc === undefined) throw new Unserializable('withCtx without extraSrc')\n return `_wc(${JSON.stringify(def.extraSrc)}, ${kid(def.parser)})`\n }\n case 'guard':\n case 'recover':\n case 'unknown':\n throw new Unserializable(`unsupported tag ${def.tag}`)\n }\n }\n}\n", "/**\n * The linker (RULE_ABI_PLAN \u00A74): fuse independently-compiled linkable artifacts\n * (`compileLinkable`) into ONE closure of parse functions.\n *\n * Every rule is a canonical `_r_<Name>` function and every sibling reference is a\n * call to that name; because fusion drops them all into one scope, those calls\n * are **direct local calls** (0% dispatch). Composition is by name:\n * - **override** \u2014 later artifact wins per rule name; because references resolve\n * by name in the shared scope, overriding a rule reroutes EVERY call to it,\n * including calls inside a base artifact's own rules (open recursion).\n * - **\u00E0 la carte** \u2014 `pick(artifact, names)` keeps only those rules + their\n * transitive dependency closure.\n * Private per-artifact state (`_ns_re`, `_ns_pf`, \u2026) is namespaced so it can't\n * collide; the sentinel protocol / `_EMPTY_TL` are shared and\n * emitted once.\n *\n * Uses `new Function` (like `compile()`), so it needs `'unsafe-eval'` under a\n * strict CSP; a build-time variant that emits fused source instead is a later\n * addition. Fusion runs ONCE at parser construction \u2014 parsing is then full speed.\n */\nimport { compileLinkable, firstSetCond, ruleDependencies, HOST_READS_DECL, RAW_ENTRY_DECL } from './codegen.ts'\nimport { FUSED_HOST_MODE, FUSED_HOST_ELIDED } from '../cst/host-mode.ts'\nimport { evalRuleMapIR, serializeRuleMap } from './ir-serialize.ts'\nimport type { LinkablePieces, FirstSetRecipe, HostMode } from './codegen.ts'\nimport { union } from '../combinators/first-set.ts'\nimport { PARSEMAN_VERSION } from '../version.ts'\nimport type { BuildHost, Combinator, CstCollapsePredicate, FirstSet, ParseContext, ParseResult } from '../types.ts'\nimport { grammarReflectionSource, mergeGrammarReflections } from '../cst/reflection.ts'\nimport type { ModuleHoist } from './module-hoist.ts'\n\n/**\n * Compile a `rules()` map to a **linkable artifact** \u2014 the composable, shippable\n * form (RULE_ABI_PLAN \u00A74). A package exports `linkable(rules(g => \u2026))`; consumers\n * import that artifact and `fuse([...])` it \u2014 **no source of the base grammar is\n * ever read**. Under the macro this is precompiled to static pieces; in the\n * interpreter it compiles here at load (like `compile()`).\n *\n * `ns` is a per-artifact namespace; omit it to auto-assign a process-unique one\n * (fine at runtime \u2014 the macro supplies a stable module-derived ns instead).\n */\nlet _nsCounter = 0\nexport function linkable(\n rulesMap: Record<string, Combinator<unknown>>,\n ns?: string,\n trivia?: Combinator<unknown>,\n // Compile-time host mode, same meaning as `compile(g, { hostMode })`: 'ast' (default)\n // emits the grammar's own builders and NO positioned-CST branch; 'cst' builds every\n // node through the host. A linked/fused artifact is version- and mode-locked, so a\n // language service links its own 'cst' artifact rather than switching at parse time.\n hostMode?: HostMode,\n): LinkablePieces {\n const pieces = compileLinkable(\n Object.entries(rulesMap),\n ns ?? `_lk${_nsCounter++}_`,\n { ...(trivia ? { trivia } : {}), ...(hostMode ? { hostMode } : {}) },\n )\n if (!pieces) throw new Error('linkable(): this grammar cannot be compiled to a linkable artifact (contains a runtime-only parser fallback)')\n return pieces\n}\n\nexport type CstBuildHostOptions = {\n /**\n * Collapse transparent one-child CST wrapper nodes at build time.\n * - `true`: collapse any one-child node whose rawChildren also has exactly one\n * entry, so trivia/error boundaries are not silently dropped.\n * - `string[]`: collapse only these grammar node types.\n * - predicate: final policy hook for language-specific public CSTs.\n */\n collapse?: boolean | readonly string[] | CstCollapsePredicate\n /**\n * Materialize `node(..., { tags })` grammar metadata onto produced CST nodes.\n * When omitted, tags stay in grammar reflection for zero per-node tree cost.\n */\n tags?: boolean\n}\n\nfunction normalizeCstCollapse(collapse: CstBuildHostOptions['collapse']): CstCollapsePredicate | undefined {\n if (collapse === true) return () => true\n if (Array.isArray(collapse)) {\n const types = new Set(collapse)\n return type => types.has(type)\n }\n return typeof collapse === 'function' ? collapse : undefined\n}\n\nfunction buildCstNode(\n type: string,\n children: ReadonlyArray<unknown>,\n _fields: unknown,\n span: { start: number; end: number },\n _rawChildren?: ReadonlyArray<unknown>,\n _triviaLog?: readonly number[],\n state?: unknown,\n tags?: readonly string[] | undefined,\n): unknown {\n // Carry the grammar's `ctx.state` snapshot onto the node (null when unset) \u2014 the\n // CST contract includes `state` and incremental re-parse replays it on edit.\n return tags !== undefined && tags.length > 0\n ? { _tag: 'node', type, tags, span: { ...span }, state: state ?? null, children: [...children] }\n : { _tag: 'node', type, span: { ...span }, state: state ?? null, children: [...children] }\n}\n\n/**\n * A generic positioned-CST build host (RULE_ABI_PLAN \u00A77). Pass as `ctx.build`\n * (or `parseDoc(..., { build: cstBuildHost })`) to make ANY linkable/fused\n * grammar produce a uniform CST \u2014 `{ _tag:'node', type, span, state, children }`\n * \u2014 instead of its own eval-AST builders. This is the host the linter and IDE\n * drivers use; the eval driver leaves `ctx.build` unset (grammar's own builders).\n *\n * For public syntax trees, call `cstBuildHost({ collapse })`: Parseman will skip\n * allocating wrapper CST nodes whose single child should stand in for the rule.\n */\nexport function cstBuildHost(options?: CstBuildHostOptions): BuildHost\nexport function cstBuildHost(\n type: string,\n children: ReadonlyArray<unknown>,\n fields: unknown,\n span: { start: number; end: number },\n rawChildren?: ReadonlyArray<unknown>,\n triviaLog?: readonly number[],\n state?: unknown,\n tags?: readonly string[] | undefined,\n): unknown\nexport function cstBuildHost(\n typeOrOptions?: string | CstBuildHostOptions,\n children?: ReadonlyArray<unknown>,\n _fields?: unknown,\n span?: { start: number; end: number },\n rawChildren?: ReadonlyArray<unknown>,\n triviaLog?: readonly number[],\n state?: unknown,\n _tags?: readonly string[] | undefined,\n): unknown {\n if (typeof typeOrOptions === 'string') {\n return buildCstNode(typeOrOptions, children ?? [], _fields, span ?? { start: 0, end: 0 }, rawChildren, triviaLog, state)\n }\n const collapse = normalizeCstCollapse(typeOrOptions?.collapse)\n const materializeTags = typeOrOptions?.tags === true\n const host: BuildHost = (\n type: string,\n children: ReadonlyArray<unknown> | undefined,\n fields: unknown,\n span: { start: number; end: number },\n rawChildren: ReadonlyArray<unknown>,\n triviaLog: readonly number[],\n state: unknown,\n tags?: readonly string[] | undefined,\n // A CST/collapse host always keeps `children` (chV) \u2014 the opt-out never\n // applies \u2014 so `?? []` is unreachable defensive modeling for the widened type.\n ) => buildCstNode(type, children ?? [], fields, span, rawChildren, triviaLog, state, materializeTags ? tags : undefined)\n ;(host as typeof host & { _parsemanCstOutput?: true })._parsemanCstOutput = true\n if (collapse) host._parsemanCstCollapse = collapse\n return host\n}\n\n// `cstBuildHost` itself is also accepted as a BuildHost (without options).\n;(cstBuildHost as unknown as { _parsemanCstOutput?: true })._parsemanCstOutput = true\n\n/**\n * A fused function receives the full ParseContext through `run()`. Direct\n * callers historically supplied a plain context object, so keep that usage\n * valid while making the function assignable to the public `Runnable` type.\n * Generated code treats optional framework fields as absent when they are not\n * provided, matching the interpreter's normal defaults.\n */\nexport type FusedRule = (\n input: string,\n pos: number,\n ctx: ParseContext | Record<string, unknown>,\n) => ParseResult<unknown> & { readonly value?: unknown }\n\n/**\n * Restrict a grammar/artifact to `names` plus their transitive rule-dependency\n * closure (\u00E0 la carte selection) \u2014 e.g. Jess taking parts of Less and parts of\n * Sass: `compose([pick(less, ['MixinCall']), pick(sass, ['EachFor']), css])`. A\n * picked rule pulls in every rule name it references, so the result is always\n * self-consistent within the artifact. Accepts a grammar (`rules()` result) or a\n * compiled artifact; returns an artifact for `compose()`.\n */\nexport function pick(\n grammar: LinkablePieces | Record<string, Combinator<unknown>>,\n names: string[],\n): LinkablePieces {\n // A COMPOSED grammar (`compose([...])` result): it has no single rule map \u2014 its rules\n // live across several carried pieces. Materialize them under the composing trivia it\n // was built with (so the selection keeps composing-wins trivia), then filter across\n // pieces to `names` + their transitive dep closure, keeping each rule in the piece\n // that WINS it (compose override order = last wins). Return a composed-like value so a\n // downstream `compose([pick(composed, \u2026)])` flattens it the same way.\n const carried = (grammar as Record<symbol, unknown>)[COMPOSED_PIECES]\n if (Array.isArray(carried)) {\n const trivia = (grammar as Record<symbol, unknown>)[COMPOSED_TRIVIA] as Combinator<unknown> | undefined\n const pieces = (carried as Array<LinkablePieces | IRPiece>).map(pc => materializePiece(pc, trivia))\n const filtered = pickPieces(pieces, names)\n // A composed-like value (carries COMPOSED_PIECES, no single rule map). It is only\n // ever consumed through compose()'s COMPOSED_PIECES branch \u2014 which is checked before\n // any LinkablePieces field \u2014 so this masquerades as LinkablePieces for the signature.\n const out: Record<string, unknown> = {}\n Object.defineProperty(out, COMPOSED_PIECES, { value: filtered, enumerable: false })\n if (trivia) Object.defineProperty(out, COMPOSED_TRIVIA, { value: trivia, enumerable: false })\n return out as unknown as LinkablePieces\n }\n\n const p = (grammar as LinkablePieces).ruleFns instanceof Map\n ? (grammar as LinkablePieces)\n : linkable(grammar as Record<string, Combinator<unknown>>)\n return pickPieces([p], names)[0] ?? { ...p, keys: [], ruleFns: new Map(), wrappers: new Map(), deps: new Map() }\n}\n\n/** Restrict a set of linkable pieces to `names` + their transitive dep closure,\n * keeping each surviving rule in the piece that WINS it (later piece wins, matching\n * compose override order). Shared by `pick()` (runtime) and the macro's build-time\n * `pick(...)` handling, so \u00E0-la-carte selection is identical on both paths. */\nexport function pickPieces(pieces: LinkablePieces[], names: string[]): LinkablePieces[] {\n const winner = new Map<string, LinkablePieces>()\n for (const pc of pieces) for (const k of pc.keys) winner.set(k, pc)\n // A requested name that isn't in the grammar is a typo \u2014 fail here, not later with a\n // confusing name-closure error at compose() time.\n for (const n of names) {\n if (!winner.has(n)) throw new Error(`pick: rule \"${n}\" is not in this grammar (available: ${[...winner.keys()].join(', ')})`)\n }\n const keep = new Set<string>()\n const visit = (n: string): void => {\n // A missing winner is an EXTERNAL dep (a base-grammar rule) \u2014 it resolves at\n // compose() time, not here. Top-level `names` were already validated above.\n const w = winner.get(n)\n if (keep.has(n) || !w) return\n keep.add(n)\n for (const d of w.deps.get(n) ?? []) visit(d)\n }\n for (const n of names) visit(n)\n const filt = <V>(m: Map<string, V>, pc: LinkablePieces): Map<string, V> =>\n new Map([...m].filter(([k]) => keep.has(k) && winner.get(k) === pc))\n return pieces\n .map(pc => ({ ...pc, keys: pc.keys.filter(k => keep.has(k) && winner.get(k) === pc), ruleFns: filt(pc.ruleFns, pc), wrappers: filt(pc.wrappers, pc), deps: filt(pc.deps, pc), nodeMeta: filt(pc.nodeMeta, pc) }))\n .filter(pc => pc.keys.length > 0)\n}\n\n/**\n * Build the fused-closure body (shared by the runtime `fuseRules` and the\n * build-time `emitFusedSource`). Returns the closure body (which reads `_env`\n * for any non-inlined callbacks) and the `_env` to bind. In macro mode callbacks\n * are inlined from source, so `_env` is empty and the body is fully static.\n */\nexport function fusedBody(pieces: LinkablePieces[], hoist?: ModuleHoist): { body: string; env: Record<string, unknown> } {\n // ARTIFACT VERSION LOCK (see src/version.ts): a compiled artifact is fused by the\n // SAME parseman version that produced it \u2014 the artifact format carries no\n // cross-version back-compat. Reject BOTH a version MISMATCH and an UNSTAMPED piece\n // (a pre-0.32 artifact predates the invariant \u2192 its recipe/pieces shape is\n // unsupported): fail LOUDLY rather than silently mis-reading a stale shape. Every\n // artifact `compileLinkable` produces is stamped, so an absent stamp means a stale\n // serialized artifact, not a current one.\n for (const p of pieces) {\n if (p.v === undefined) {\n throw new Error(\n `parseman: artifact \"${p.ns}\" is UNSTAMPED (compiled before the version-lock invariant). ` +\n `Recompile the grammar with parseman ${PARSEMAN_VERSION}; parseman does not fuse unversioned or cross-version artifacts.`,\n )\n }\n if (p.v !== PARSEMAN_VERSION) {\n throw new Error(\n `parseman: artifact \"${p.ns}\" was compiled with parseman ${p.v}, but is being fused with parseman ${PARSEMAN_VERSION}. ` +\n `Compiled grammar artifacts are version-locked \u2014 recompile the grammar with parseman ${PARSEMAN_VERSION}; parseman does not fuse across versions.`,\n )\n }\n }\n // Winner per rule name \u2014 later pieces override earlier ones.\n const winner = new Map<string, LinkablePieces>()\n for (const p of pieces) for (const k of p.keys) winner.set(k, p)\n\n // Name-closure check: every referenced rule must resolve in the fused set.\n for (const [k, p] of winner) {\n for (const d of p.deps.get(k) ?? []) {\n if (!winner.has(d)) throw new Error(`compose: rule \"${k}\" references missing rule \"${d}\"`)\n }\n }\n\n const contributing = new Set(winner.values())\n const contributingPieces = [...contributing]\n const needsEmptyTl = contributingPieces.some(p => p.needsEmptyTl)\n const needsHostReads = contributingPieces.some(p => p.needsHostReads)\n const needsRawEntry = contributingPieces.some(p => p.needsRawEntry)\n\n const lines: string[] = [\n // Shared sentinel protocol (must match NAMED_FN_FAIL / NAMED_FN_END in codegen).\n 'const _pfFail = {}',\n 'let _pfEnd',\n ...(needsEmptyTl ? ['const _EMPTY_TL = Object.freeze([])'] : []),\n ...(needsHostReads ? [HOST_READS_DECL] : []),\n ...(needsRawEntry ? [RAW_ENTRY_DECL] : []),\n // Each contributing artifact's namespaced private prelude (regexes, _pf, \u2026).\n ...new Set(contributingPieces.flatMap(p => p.prelude)),\n // The winning `_r_<Name>` function for each rule (one per name \u2192 no redeclare).\n ...[...winner].map(([k, p]) => p.ruleFns.get(k)!),\n ]\n const wrapperEntries = [...winner].map(([k, p]) => `${JSON.stringify(k)}: ${p.wrappers.get(k)!}`)\n const reflection = mergeGrammarReflections([...winner].map(([k, p]) => p.nodeMeta.get(k) ?? { nodes: [] }))\n // The host-mode stamp is emitted INTO the body rather than applied afterwards by the\n // caller, so the runtime fuse (`fuseRules`) and the build-time fuse\n // (`emitFusedSource`) cannot disagree about it. They have drifted on exactly this\n // kind of change before, and an unstamped macro artifact is invisible to\n // `assertHostModeCompatible` \u2014 it reads `elided: false` and passes, which is the\n // silent wrong output the whole mechanism exists to prevent.\n const { mode, elided } = hostModeOfPieces(pieces)\n const tailSrc = [\n 'const _map = {',\n wrapperEntries.join(',\\n'),\n '}',\n `Object.defineProperty(_map, Symbol.for(${JSON.stringify(FUSED_HOST_MODE.description!)}), { value: ${JSON.stringify(mode)}, enumerable: false })`,\n `Object.defineProperty(_map, Symbol.for(${JSON.stringify(FUSED_HOST_ELIDED.description!)}), { value: ${JSON.stringify(elided)}, enumerable: false })`,\n `Object.defineProperty(_map, Symbol.for('parseman.grammarReflection'), { value: ${grammarReflectionSource(reflection)}, enumerable: false })`,\n // \u2026and on each rule FUNCTION, because `run(map.Rule, \u2026)` is handed the rule, not the\n // map, and would otherwise have nothing to check against. Done once at fuse time,\n // before any rule has been called, so it costs nothing per parse.\n 'for (const _k of Object.keys(_map)) {',\n ` Object.defineProperty(_map[_k], Symbol.for(${JSON.stringify(FUSED_HOST_MODE.description!)}), { value: ${JSON.stringify(mode)}, enumerable: false })`,\n ` Object.defineProperty(_map[_k], Symbol.for(${JSON.stringify(FUSED_HOST_ELIDED.description!)}), { value: ${JSON.stringify(elided)}, enumerable: false })`,\n '}',\n 'return _map',\n ].join('\\n')\n const rawBody = [...lines, tailSrc].join('\\n')\n\n // Fuse-time first-set dispatch: a rule-ref choice arm was emitted (in linkable\n // mode) as `/*@FS:rule:codevar@*\u200B/true`. Resolve it now against the WINNING rule's\n // LEADING first-set recipe \u2014 sound under override, since we use the final rule, not\n // the one visible when the referencing rule was compiled. Each rule's recipe is a\n // union of ordered leading-term chains; resolving them over the WINNING rules to a\n // fixpoint makes a `sequence(ref, \u2026)`-led arm/node dispatch on the ref's real first\n // char (parity with a monolithic compile) instead of degrading to always-try\n // because the ref baked `any`. A genuinely unknown ref \u2192 `any` (always try).\n const ANY: FirstSet = { kind: 'any' }\n const EMPTY: FirstSet = { kind: 'empty' }\n const recipes = new Map<string, FirstSetRecipe>()\n const shallow = new Map<string, FirstSet>()\n const nullable = new Map<string, boolean>()\n for (const [k, p] of winner) {\n const r = p.firstSetRecipes?.get(k); if (r) recipes.set(k, r)\n const fs = p.firstSets?.get(k); if (fs) shallow.set(k, fs)\n const nu = p.nullable?.get(k); if (nu !== undefined) nullable.set(k, nu)\n }\n const knownRef = (ref: string): boolean => recipes.has(ref) || shallow.has(ref)\n // A referenced rule's resolved first-set (or `any` for a genuinely unknown ref \u2014\n // always try). A ref whose nullability is unknown defaults to nullable (keep\n // unioning the chain tail \u2014 never drops a valid first char).\n const refFS = (ref: string): FirstSet => (knownRef(ref) ? (finalFS.get(ref) ?? ANY) : ANY)\n const refNullable = (ref: string): boolean => (knownRef(ref) ? (nullable.get(ref) ?? true) : true)\n // Resolve a recipe: union each ordered chain, and within a chain union each\n // segment's first-set left-to-right STOPPING after the first non-nullable segment\n // (its tail can't start the rule). A ref segment is skippable if it was forced so\n // at build (a wrapping optional/many \u2192 `seg.nullable`) OR the resolved rule is\n // itself nullable; only a definitely-consuming ref stops the chain.\n const resolveRecipe = (r: FirstSetRecipe): FirstSet => {\n let out: FirstSet = EMPTY\n for (const chain of r.alts) {\n for (const seg of chain) {\n out = union(out, seg.ref !== undefined ? refFS(seg.ref) : seg.set)\n const skippable = seg.ref !== undefined ? (seg.nullable || refNullable(seg.ref)) : seg.nullable\n if (!skippable) break\n }\n }\n return out\n }\n // Least-fixpoint: recipe-bearing rules start EMPTY and grow monotonically via\n // `resolveRecipe` (union of refs is monotone; the chain stop is static), so a\n // recursive rule converges to its tightest sound first-set. Rules with no recipe\n // keep their static shallow set.\n const finalFS = new Map<string, FirstSet>()\n for (const [k] of winner) finalFS.set(k, recipes.has(k) ? EMPTY : (shallow.get(k) ?? ANY))\n for (let iter = 0; iter <= recipes.size; iter++) {\n let changed = false\n for (const [k, r] of recipes) {\n const fs = resolveRecipe(r)\n if (JSON.stringify(finalFS.get(k)) !== JSON.stringify(fs)) { finalFS.set(k, fs); changed = true }\n }\n if (!changed) break\n }\n const resolveFS = (src: string): string => src.replace(\n // Rule name + code-point var are both JS identifiers (rule names are validated\n // at compile time \u2014 see assertRuleName in codegen), so an identifier class\n // matches every well-formed placeholder.\n /\\/\\*@FS:([A-Za-z0-9_$]+):([A-Za-z0-9_$]+)@\\*\\/true/g,\n (_m, name: string, codevar: string) => {\n const fs = finalFS.get(name)\n if (!fs || fs.kind === 'any' || fs.kind === 'empty') return 'true'\n return `(${firstSetCond(codevar, fs)})`\n },\n )\n // Placeholders never span a line, so resolving the declarations one at a time is\n // identical to resolving the joined body \u2014 and it has to happen BEFORE the hoist\n // claims them, or two variants whose dispatch conditions resolve the same way\n // would still be compared as different text.\n const body = hoist === undefined\n ? resolveFS(rawBody)\n : [...hoist.claim(lines.map(resolveFS)), resolveFS(tailSrc)].join('\\n')\n\n // Non-inlined callbacks (runtime compile() mode), keyed `<ns>mf` / `<ns>build`.\n const env: Record<string, unknown> = {}\n for (const p of contributingPieces) {\n if (p.mfFns.length) env[`${p.ns}mf`] = p.mfFns\n if (p.buildFns.length) env[`${p.ns}build`] = p.buildFns\n }\n return { body, env }\n}\n\n/**\n * The host mode a fusion of these pieces lowers to, and whether any of them dropped a\n * direct builder's positioned-CST branch. Shared by BOTH fuses via `fusedBody`, so the\n * runtime and build-time engines cannot label the same artifact differently.\n *\n * A MIXED fusion is the one way the per-parse host check could be defeated. Carried IR\n * re-lowers under this compose's mode, but a piece that arrived ALREADY COMPILED\n * (`linkable()` / `pick()` / a macro artifact) keeps the mode it was built with \u2014 so a\n * 'cst' fusion can contain an 'ast' piece whose direct builders dropped their host\n * branch. The map would be labeled 'cst', `assertHostModeCompatible` would pass, and\n * that piece would hand AST-shaped objects into a positioned CST: precisely the silent\n * wrong output this whole mechanism exists to prevent. Reject it here, where both facts\n * are still in hand.\n */\nfunction hostModeOfPieces(pieces: LinkablePieces[]): { mode: HostMode; elided: boolean } {\n const mode = pieces.find(p => p.hostMode !== undefined && p.hostMode !== 'ast')?.hostMode ?? 'ast'\n const elided = pieces.filter(p => p.hostBranchElided === true)\n if (mode === 'cst' && elided.length > 0) {\n throw new Error(\n `compose: cannot build a positioned-CST artifact from pieces that were `\n + `compiled for host mode \"ast\" \u2014 ${elided.map(p => `\"${p.ns}\"`).join(', ')} `\n + `${elided.length === 1 ? 'dropped its' : 'dropped their'} direct builders' CST branch, `\n + `so ${elided.length === 1 ? 'it' : 'they'} would return AST objects inside the CST. `\n + `An already-compiled piece keeps the mode it was built with; only pieces carried as `\n + `IR are re-lowered by this compose. Re-compile ${elided.length === 1 ? 'it' : 'them'} `\n + `with hostMode: 'cst', or pass the source grammar so it can be re-lowered.`,\n )\n }\n return { mode, elided: elided.length > 0 }\n}\n\n/** Fuse at RUNTIME (via `new Function`) \u2014 used by `compose()` when not compiled\n * by the macro (like `compile()`). The macro path uses `emitFusedSource` instead.\n * Both stamp the host mode from inside `fusedBody`; see `hostModeOfPieces`. */\nexport function fuseRules(pieces: LinkablePieces[]): Record<string, FusedRule> {\n const { body, env } = fusedBody(pieces)\n // eslint-disable-next-line no-new-func\n return new Function('_env', body)(env) as Record<string, FusedRule>\n}\n\nexport { FUSED_HOST_MODE, FUSED_HOST_ELIDED } from '../cst/host-mode.ts'\n\n/** The host mode a fused/composed rule map was built for. Defaults to 'ast'. */\nexport function fusedHostModeOf(registry: object): HostMode {\n const m = (registry as Record<symbol, unknown>)[FUSED_HOST_MODE]\n return m === 'cst' ? 'cst' : 'ast'\n}\n\n/** Whether a fused/composed rule map dropped any direct builder's CST branch. */\nexport function fusedHostElidedOf(registry: object): boolean {\n return (registry as Record<symbol, unknown>)[FUSED_HOST_ELIDED] === true\n}\n\n/**\n * Fuse at BUILD time \u2014 emit the fused closure as a self-contained SOURCE\n * expression (`(() => { \u2026 })()`), with **no `new Function`**. This is what the\n * macro splices in for a `compose([...])` call, so macro output stays eval-free.\n * Requires every callback to be inlined from source (macro mode); throws if any\n * artifact carries runtime-only callback functions.\n */\nexport function emitFusedSource(pieces: LinkablePieces[], hoist?: ModuleHoist): string {\n const { body, env } = fusedBody(pieces, hoist)\n if (Object.keys(env).length > 0) {\n throw new Error('emitFusedSource: artifact carries non-static callbacks (runtime-only); cannot emit static source')\n }\n return `/* @__PURE__ */ (() => {\\n${body}\\n})()`\n}\n\n/**\n * Compose grammars/artifacts into a runnable parser map \u2014 the ONLY public\n * composition entry point. `compose([base, ext, \u2026])`: later entries override\n * earlier ones by rule name, and because fusion re-binds every reference in one\n * shared scope, an override reroutes the base's OWN calls too (open recursion).\n *\n * Each entry may be a **grammar** (a `rules()` result \u2014 a map of combinators,\n * linkable-ified here) OR an already-compiled **linkable artifact** (what the\n * macro emits and a package ships). So a package needs no opt-in wrapper to be\n * composable \u2014 `compose([importedGrammar, myRules])` just works.\n *\n * The macro compiles `compose([...])` to STATIC fused source (no `new Function`).\n * Called at runtime (no macro, like `compile()`) it fuses via `new Function`.\n */\n/** A composed parser carries its flattened source pieces (non-enumerable) so it\n * can be composed AGAIN \u2014 `compose([lessGrammar, delta])` where `lessGrammar` is\n * itself a `compose([...])` result. */\nconst COMPOSED_PIECES = Symbol.for('parseman.composedPieces')\n\n/** The carried pieces a `compose()`/`composeLeaf()` result holds, or `undefined` when\n * the value is not a composed grammar. This is what makes a fused grammar analysable:\n * the pieces are re-lowerable IR even though the fused map itself is only functions. */\nexport function composedPiecesOf(\n grammar: Record<string, unknown>,\n): ReadonlyArray<LinkablePieces | IRPiece> | undefined {\n const pieces = (grammar as unknown as Record<symbol, unknown>)[COMPOSED_PIECES]\n return Array.isArray(pieces) ? pieces as ReadonlyArray<LinkablePieces | IRPiece> : undefined\n}\n\n/**\n * A terminal fused grammar may be used to run a parser, but not as an input to\n * another composition. Macro `composeLeaf()` uses this for a local semantic\n * reduction over imported recognition-only IR: the local reductions stay in\n * their lexical module and therefore never become carried IR.\n */\nconst LEAF_COMPOSED = Symbol.for('parseman.leafComposed')\n\n/** The composing (outermost) trivia a runtime `compose()` applied \u2014 stored so a\n * later `pick(composedGrammar, \u2026)` can re-lower the selected rules under the SAME\n * trivia (composing-wins survives \u00E0-la-carte selection). The carried IR pieces hold\n * no trivia of their own, so it must be remembered separately. Not serialized by the\n * macro (which delegates pick to the runtime linker). */\nconst COMPOSED_TRIVIA = Symbol.for('parseman.composedTrivia')\n\n/** Final winner map for semantic-coverage tooling. It exists only when every\n * carried compose piece is re-lowerable IR; opaque precompiled artifacts have no\n * combinator graph to inspect and therefore deliberately expose no fake map. */\nconst COMPOSED_COVERAGE_RULES = Symbol.for('parseman.composedCoverageRules')\n\n/** The compact IR form a grammar carries instead of its lowered rule source: the\n * combinator-construction expression, re-lowered here at fuse time. */\nexport type IRPiece = { ns: string; ir: string; trackLines?: true }\n\nfunction isIRPiece(p: unknown): p is IRPiece {\n return !!p && typeof p === 'object'\n && typeof (p as IRPiece).ir === 'string' && typeof (p as IRPiece).ns === 'string'\n && !('ruleFns' in (p as object))\n}\n\n/** Memoize a zero-arg thunk, keeping it LAZY. Used where two diagnostic thunks want\n * the same carried-IR hydration: the work must not happen when the diagnostic is off,\n * and must not happen twice when it is on. */\nexport function once<T>(fn: () => T): () => T {\n let done = false\n let value: T\n return () => {\n if (!done) { value = fn(); done = true }\n return value\n }\n}\n\n/** The re-lowerable carried pieces' rule maps, in compose order \u2014 the input to the\n * gating analysis (`diagnoseGrammar`). An opaque precompiled artifact contributes no\n * combinator graph, so it is skipped: a hole it would have bound stays unresolved\n * and its choice stays deferred, never falsely warned.\n *\n * Skipping is not the same as having nothing to say. Use `carriedRuleMapsDetailed`\n * where the skip must be REPORTED \u2014 a diagnostic that drops part of the grammar and\n * then returns a clean result is indistinguishable from one that verified it. */\nexport function carriedRuleMaps(carried: ReadonlyArray<LinkablePieces | IRPiece>): Array<Array<[string, Combinator<unknown>]>> {\n return carriedRuleMapsDetailed(carried).maps\n}\n\n/** `carriedRuleMaps` plus the pieces it could NOT re-lower, named by namespace and\n * rule count, so a caller can report exactly how much of the grammar went unseen. */\nexport function carriedRuleMapsDetailed(\n carried: ReadonlyArray<LinkablePieces | IRPiece>,\n): { maps: Array<Array<[string, Combinator<unknown>]>>; opaque: Array<{ ns: string; ruleNames: string[] }> } {\n const maps: Array<Array<[string, Combinator<unknown>]>> = []\n const opaque: Array<{ ns: string; ruleNames: string[] }> = []\n for (const p of carried) {\n if (isIRPiece(p)) { maps.push(evalRuleMapIR(p.ir)); continue }\n // `ruleFns` is a Map, not a plain object \u2014 `Object.keys` on it silently yields []\n // and every opaque piece would degrade to an anonymous `<artifact _lkN_>`, which is\n // exactly the \"reported, but uselessly\" failure this whole change is against.\n const ruleFns = (p as { ruleFns?: Map<string, string> }).ruleFns\n opaque.push({ ns: p.ns, ruleNames: ruleFns instanceof Map ? [...ruleFns.keys()] : [] })\n }\n return { maps, opaque }\n}\n\n/**\n * Recover the override-winner COMBINATOR map behind a `compose()` result, plus the\n * pieces that could not be recovered.\n *\n * A fused map holds rule functions, so any consumer that walks a combinator graph\n * (gating analysis, the spec/EBNF/railroad model) cannot read it directly. The graph\n * is not lost, though \u2014 `compose()` retains re-lowerable IR \u2014 so this is the single\n * shared recovery both consumers use. Sharing it is the point: two copies of this\n * logic is how one walker gets fixed and the other silently keeps failing.\n *\n * Returns `undefined` when `grammar` is not a composed result.\n */\nexport function recoverComposedRules(\n grammar: Record<string, unknown>,\n): { rules: Map<string, Combinator<unknown>>; opaque: Array<{ ns: string; ruleNames: string[] }> } | undefined {\n const carried = composedPiecesOf(grammar)\n if (carried === undefined) return undefined\n const { maps, opaque } = carriedRuleMapsDetailed(carried)\n const rules = new Map<string, Combinator<unknown>>()\n // Later wins, matching the linker's own fuse semantics. An accessed-but-undefined\n // `g.X` leaks in as an unresolved lazy \u2014 a REFERENCE, not a definition \u2014 and must\n // never shadow the artifact that really defines X.\n for (const map of maps) for (const [name, rule] of map) {\n if (rule._def.tag === 'lazy') { try { rule._def.thunk() } catch { continue } }\n rules.set(name, rule)\n }\n return { rules, opaque }\n}\n\nfunction coverageRulesOf(carried: Array<LinkablePieces | IRPiece>): Record<string, Combinator<unknown>> | undefined {\n const winners: Record<string, Combinator<unknown>> = {}\n for (const piece of carried) {\n if (!isIRPiece(piece)) return undefined\n const map = evalRuleMapIR(piece.ir)\n for (const [name, rule] of map) {\n // An accessed-but-undefined `g.Name` is an external reference, never a\n // rule definition. Match compose's IR filtering rule exactly.\n if (rule._def.tag === 'lazy') {\n try { rule._def.thunk() } catch { continue }\n }\n winners[name] = rule\n }\n }\n return winners\n}\n\n/** Return the final override-winner combinator map carried by runtime\n * `compose()`, or `undefined` when a precompiled opaque artifact participated.\n * This is intentionally internal: callers must not treat it as a parser API. */\nexport function composedCoverageRules(grammar: Record<string, unknown>): Record<string, Combinator<unknown>> | undefined {\n return (grammar as Record<symbol, unknown>)[COMPOSED_COVERAGE_RULES] as Record<string, Combinator<unknown>> | undefined\n}\n\n/** Materialize a carried item to full `LinkablePieces`: an IR piece is evaluated\n * back to a rule map and re-lowered; a full piece passes through. */\nexport function materializePiece(\n p: LinkablePieces | IRPiece,\n trivia?: Combinator<unknown>,\n captureTerminals = false,\n hostMode?: HostMode,\n): LinkablePieces {\n // A piece carried as IR is RE-LOWERED here, which is what lets `compose()` choose the\n // host mode: the same carried grammar can be fused into an eval-AST artifact and into\n // a positioned-CST one. An already-lowered piece keeps whatever mode it was built\n // with \u2014 that is why `compose({ hostMode: 'cst' })` only works on carried IR.\n if (!isIRPiece(p)) return p\n const pieces = compileLinkable(evalRuleMapIR(p.ir), p.ns, {\n ...(trivia ? { trivia } : {}),\n ...(captureTerminals ? { captureTerminals: true } : {}),\n ...(hostMode ? { hostMode } : {}),\n ...(p.trackLines ? { trackLines: true } : {}),\n })\n if (!pieces) throw new Error(`compose: carried IR for ns \"${p.ns}\" could not be re-lowered`)\n return pieces\n}\n\n/** Flatten one `compose()` item to its pieces: a prior composed result \u2192 its\n * carried list; an artifact \u2192 itself; a grammar (`rules()` map) \u2192 linkable-ified. */\nfunction nextComposeNs(used: Set<string>): string {\n let ns: string\n do { ns = `_lk${_nsCounter++}_` } while (used.has(ns))\n used.add(ns)\n return ns\n}\n\n/** Flatten one `compose()` item to its RE-LOWERABLE carried items \u2014 the form stored\n * on the composed result so it can be composed AGAIN under a NEW composing trivia.\n * A grammar (`rules()` map) is carried as compact IR (`{ns, ir}`), NOT baked source,\n * so a later `compose([thisResult, delta])` re-lowers it with the delta's trivia\n * (multi-level composing-wins). A prior composed result contributes its OWN carried\n * items (already IR); a pre-compiled artifact has no source, so it stays baked. */\nfunction itemCarried(\n item: LinkablePieces | Record<string, unknown>,\n used: Set<string>,\n trivia?: Combinator<unknown>,\n // Only reaches the non-serializable fallback below, where the grammar is baked\n // immediately instead of carried as re-lowerable IR. The IR path gets the mode later,\n // in `materializePiece`.\n hostMode?: HostMode,\n): Array<LinkablePieces | IRPiece> {\n const carried = (item as Record<symbol, unknown>)[COMPOSED_PIECES]\n // A prior composed result (runtime or macro-compiled): its carried list is already\n // re-lowerable (IR pieces, plus any pre-compiled artifacts). Pass it through so THIS\n // compose re-lowers it under its own composing trivia. Reserve its namespaces so a\n // sibling grammar map can't collide with them.\n if (Array.isArray(carried)) {\n const items = carried as Array<LinkablePieces | IRPiece>\n for (const p of items) used.add(p.ns)\n return items\n }\n // A pre-compiled artifact (`linkable()`/`pick()`): no source to re-lower \u2014 its trivia\n // was baked when it was compiled. Keep it as-is.\n if ((item as LinkablePieces).ruleFns instanceof Map) {\n const p = item as LinkablePieces\n used.add(p.ns)\n return [p]\n }\n // A grammar (`rules()` map): carry it as compact IR so a later compose re-lowers it\n // under ITS trivia. Unserializable \u2192 bake now with this compose's trivia (can't\n // re-lower later; acceptable fallback, mirrors the macro's full-pieces fallback).\n const map = item as Record<string, Combinator<unknown>>\n const ns = nextComposeNs(used)\n // Drop EXTERNAL entries first (same filter as compileLinkable): a `rules()` cache\n // also holds every ACCESSED-but-undefined `g.X` as an unresolved-lazy entry. Left in,\n // serializeRuleMap would emit `X: g[\"X\"]` \u2014 a self-referential rule that shadows the\n // sibling artifact defining X and recurses forever. They resolve by name at fuse time.\n const entries = Object.entries(map).filter(([, val]) => {\n const d = val._def\n if (d.tag !== 'lazy') return true\n try { d.thunk(); return true } catch { return false }\n })\n // Carry this grammar's ambient `scanSkip` (per-piece \u2014 opaque units are\n // dialect-specific, NOT composing-wins) into the IR so a re-lower stamps\n // `grammarScanSkip` back on. `linkable()`'s fallback reads it off `_meta` directly.\n const scanSkip = entries\n .map(([, val]) => (val._meta as { grammarScanSkip?: Combinator<unknown>[] }).grammarScanSkip)\n .find(Boolean)\n const ir = serializeRuleMap(entries, scanSkip)\n return ir ? [{ ns, ir }] : [linkable(map, ns, trivia, hostMode)]\n}\n\n/** The composed grammar's ambient trivia = the LAST composed item that declares a\n * grammar-level trivia (via `rules({ trivia }, \u2026)`, which tags `grammarTrivia` on its\n * rules). Outermost wins: the composing grammar's trivia applies to every fused rule,\n * including those inherited from a base \u2014 so e.g. an SCSS `rw` (which extends Less's)\n * governs the inherited Less/CSS rules too. `parser`/`noTrivia` still override locally. */\nfunction composingTriviaOf(items: Array<LinkablePieces | Record<string, unknown>>): Combinator<unknown> | undefined {\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i] as Record<string, unknown> | undefined\n if (!item || (item as LinkablePieces).ruleFns instanceof Map || (item as Record<symbol, unknown>)[COMPOSED_PIECES]) continue\n for (const v of Object.values(item)) {\n const t = (v as Combinator<unknown> | undefined)?._meta?.grammarTrivia\n if (t) return t\n }\n }\n return undefined\n}\n\nexport function compose(\n items: Array<LinkablePieces | Record<string, unknown>>,\n /**\n * Compile-time host mode for the fused artifact, same meaning as\n * `compile(g, { hostMode })`. Omit (or `'ast'`) for the eval driver \u2014 the fused rules\n * build through the grammar's own `build` callbacks and carry no positioned-CST\n * branch. Pass `'cst'` to fuse a SECOND artifact from the same pieces for the linter /\n * IDE / language-service driver. Two compilations of one grammar, decided here, rather\n * than one artifact deciding per node on every parse.\n */\n opts?: { hostMode?: HostMode },\n): Record<string, FusedRule> {\n if (items.some(item => (item as Record<symbol, unknown>)[LEAF_COMPOSED] === true)) {\n throw new Error('compose: a composeLeaf() result is terminal and cannot be composed again')\n }\n const used = new Set<string>()\n // The composed grammar's ambient trivia comes from the composing grammar itself \u2014\n // whatever the last piece declared via rules({ trivia }, \u2026). No separate option:\n // the trivia rides with the grammar that declared it.\n const trivia = composingTriviaOf(items)\n // Carried items are RE-LOWERABLE (IR); materialize them ONCE with this compose's\n // trivia for the now-fuse, but STORE the un-materialized carried list so a later\n // compose can re-lower it under a different trivia (multi-level composing-wins).\n const carried = items.flatMap(item => itemCarried(item, used, trivia, opts?.hostMode))\n const pieces = carried.map(p => materializePiece(p, trivia, false, opts?.hostMode))\n const map = fuseRules(pieces)\n Object.defineProperty(map, COMPOSED_PIECES, { value: carried, enumerable: false })\n if (trivia) Object.defineProperty(map, COMPOSED_TRIVIA, { value: trivia, enumerable: false })\n const coverageRules = coverageRulesOf(carried)\n if (coverageRules) Object.defineProperty(map, COMPOSED_COVERAGE_RULES, { value: coverageRules, enumerable: false })\n return map\n}\n\n/**\n * Compose a terminal grammar. This is for a leaf parser that overlays local\n * semantic reductions on reusable recognition rules.\n *\n * Under the macro this lowers to STATIC fused source (functions), exactly like\n * `compose()`. It is still macro-only as a *compiled* artifact: without macro\n * lowering there is no safe way to keep lexical builders out of carried IR, so it\n * never falls back to runtime CODEGEN composition.\n *\n * Called at runtime (no macro) it returns the INTERPRETED fuse of the same items\n * \u2014 a combinator map, not a map of compiled functions (`fuseInterpreted`). That is\n * the supported way to run/inspect a leaf grammar without a build step: drive it\n * with `run()` / `parseDoc()`, which accept either shape. The declared return type\n * is the MACRO-path type (a leaf grammar is shipped compiled); use\n * `isInterpretedFuse(map)` when a caller must tell the two apart.\n */\nexport function composeLeaf(\n items: Array<LinkablePieces | Record<string, unknown>>,\n): Record<string, FusedRule> {\n const pieces = items.flatMap(interpretedPieces)\n let fused: Record<string, Combinator<unknown>> | undefined\n const map: Record<string, unknown> = {}\n // LAZY on purpose. A grammar module typically builds SEVERAL leaf grammars over\n // one shared recognition piece (`cssGrammar`, `cssLineGrammar`, `cssCstGrammar`,\n // \u2026). An interpreted fuse binds that shared piece IN PLACE, so only one of them\n // can exist at a time \u2014 fusing all of them at import would make merely importing\n // the module throw. Fusing on first ACCESS means the grammar you actually use\n // works, and reaching for a second, conflicting one fails loudly at that point.\n // (`trackLines`/`hostMode` are compile-time distinctions; the interpreter decides\n // both per parse, so those variants are the same interpreted grammar anyway.)\n for (const name of ruleNamesOf(pieces)) {\n Object.defineProperty(map, name, {\n enumerable: true,\n configurable: true,\n get: () => (fused ??= fusePieces(pieces))[name],\n })\n }\n Object.defineProperty(map, LEAF_COMPOSED, { value: true, enumerable: false })\n Object.defineProperty(map, INTERPRETED_PIECES, {\n value: pieces.filter(p => p.plain).map(p => p.entries),\n enumerable: false,\n })\n return map as unknown as Record<string, FusedRule>\n}\n\n/* \u2500\u2500 Interpreted fuse \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * `compose()` fuses by CODEGEN: every piece is compiled to `_r_<Name>` functions\n * dropped into one scope, so a reference resolves by NAME and an override reroutes\n * the base piece's own calls (open recursion). None of that exists interpreted \u2014\n * the interpreter runs the combinator graph, and a cross-piece reference is an\n * ordinary `ref()` placeholder that nobody ever `.define()`d. That is why a\n * composed grammar could not be run interpreted at all, and why every diagnostic\n * that must NOT reach codegen (profiling, gating analysis, coverage) had to be\n * hand-fused in throwaway scripts.\n *\n * The interpreted fuse binds those placeholders directly, with the SAME semantics\n * the compiled fuse gets from name resolution:\n * - later piece wins per rule name (matching `fuseRules`/`pickPieces`);\n * - an override REPOINTS the slot every call site already holds, so a base\n * piece's internal calls reroute too (open recursion);\n * - the composing grammar's trivia governs every fused rule (`composingTriviaOf`);\n * - a referenced-but-undefined rule is a fuse-time error, not a parse-time one.\n *\n * It is MUTATING by construction: a hole is a shared object, and binding it is the\n * only way its call sites can see the answer. `repointRef` therefore records what\n * it changed and refuses a CONFLICTING second bind, so two different fusions over\n * one shared piece fail loudly instead of silently rewriting each other's parser.\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * A rule slot produced by `ref()` \u2014 what `rules()` stores for every rule that is\n * referenced by name, and for every `g.X` hole a piece leaves for another piece to\n * fill. `parse`/`_def.thunk` are OWN properties of that object, which is what lets\n * the interpreted fuse repoint it in place.\n */\ntype RefSlot = Combinator<unknown> & {\n _def: { tag: 'lazy'; thunk: () => Combinator<unknown> }\n define(p: Combinator<unknown>): void\n parse(input: string, pos: number, ctx: ParseContext): ParseResult<unknown>\n}\n\nfunction isRefSlot(c: Combinator<unknown>): c is RefSlot {\n return c._def.tag === 'lazy' && typeof (c as unknown as { define?: unknown }).define === 'function'\n}\n\n/** What a slot resolved to BEFORE any interpreted fuse touched it (`null` = it was\n * an unbound cross-piece hole). Recorded on first repoint so a LATER fuse computes\n * its winner from the grammar as authored, never from another fusion's binding. */\nconst FUSE_ORIGINAL = Symbol.for('parseman.interpretedFuseOriginal')\n/** What an interpreted fuse repointed this slot at. */\nconst FUSE_TARGET = Symbol.for('parseman.interpretedFuseTarget')\n/** The source rule maps behind a `fuseInterpreted()` result, so it can be fused\n * again \u2014 the interpreted mirror of `COMPOSED_PIECES`. */\nconst INTERPRETED_PIECES = Symbol.for('parseman.interpretedPieces')\n\n/** Whether `map` is an interpreted fuse (a combinator map) rather than a compiled\n * `compose()` result (a map of fused functions). */\nexport function isInterpretedFuse(map: object): boolean {\n return Array.isArray((map as Record<symbol, unknown>)[INTERPRETED_PIECES])\n}\n\ntype NamedEntries = ReadonlyArray<[string, Combinator<unknown>]>\n/** `plain` = the item was an authored `rules()` map. Only plain maps declare the\n * composing trivia, mirroring `composingTriviaOf`, which skips artifacts and prior\n * composed results for exactly the same reason: their trivia was already applied. */\ntype FusePiece = { entries: NamedEntries; plain: boolean }\n\n/** The rule a map entry DEFINES, or `undefined` when it is an external reference\n * (an accessed-but-undefined `g.X`). Same local-vs-external test `compileLinkable`\n * and `itemCarried` apply, so the two fuses agree on what a piece contributes. */\nfunction definitionOf(entry: Combinator<unknown>): Combinator<unknown> | undefined {\n if (isRefSlot(entry)) {\n const original = (entry as unknown as Record<symbol, unknown>)[FUSE_ORIGINAL]\n if (original !== undefined) return (original as Combinator<unknown> | null) ?? undefined\n try { return entry._def.thunk() } catch { return undefined }\n }\n if (entry._def.tag === 'lazy') {\n try { (entry._def as { thunk: () => Combinator<unknown> }).thunk() } catch { return undefined }\n }\n return entry\n}\n\n/** Point `slot` at `target`, updating every call site that holds it. Mirrors\n * `ref().define()`'s metadata propagation; refuses to overwrite a binding a\n * DIFFERENT fusion already made (see the mutation note above). */\nfunction repointRef(slot: RefSlot, target: Combinator<unknown>, name: string): void {\n const tagged = slot as unknown as Record<symbol, unknown>\n const bound = tagged[FUSE_TARGET] as Combinator<unknown> | undefined\n const original = FUSE_ORIGINAL in tagged\n ? tagged[FUSE_ORIGINAL] as Combinator<unknown> | null\n : (() => { try { return slot._def.thunk() } catch { return null } })()\n if ((bound ?? original) === target) return\n if (bound !== undefined) {\n throw new Error(\n `fuseInterpreted: rule \"${name}\" is already bound by a DIFFERENT interpreted fusion of the same grammar piece. `\n + `An interpreted fuse binds the shared placeholder objects in place, so two fusions cannot share a piece \u2014 `\n + `build a fresh instance of the piece (call its rules() factory again, or import the module under a distinct specifier) for the second fusion.`,\n )\n }\n if (!(FUSE_ORIGINAL in tagged)) Object.defineProperty(slot, FUSE_ORIGINAL, { value: original, enumerable: false })\n Object.defineProperty(slot, FUSE_TARGET, { value: target, enumerable: false })\n slot._def.thunk = () => target\n slot.parse = (input, pos, ctx) => target.parse(input, pos, ctx)\n const meta = slot._meta\n meta.firstSet = target._meta.firstSet\n meta.canMatchNewline = target._meta.canMatchNewline\n meta.isTrivia = target._meta.isTrivia\n if (target._meta.triviaKindLabels !== undefined) meta.triviaKindLabels = target._meta.triviaKindLabels\n else delete meta.triviaKindLabels\n if (target._meta.disjoint !== undefined) meta.disjoint = target._meta.disjoint\n else delete meta.disjoint\n}\n\n/** Flatten one `fuseInterpreted()` item to the rule maps it contributes, in order. */\nfunction interpretedPieces(item: LinkablePieces | Record<string, unknown>): FusePiece[] {\n const fused = (item as Record<symbol, unknown>)[INTERPRETED_PIECES]\n if (Array.isArray(fused)) return (fused as NamedEntries[]).map(entries => ({ entries, plain: false }))\n const carried = composedPiecesOf(item as Record<string, unknown>)\n if (carried !== undefined) {\n // A compiled `compose()` result. Its carried IR re-lowers to combinators, but a\n // piece that arrived already COMPILED has no combinator graph at all \u2014 fusing\n // around it would silently drop its rules, which is the one failure mode a\n // diagnostic must never have.\n const { maps, opaque } = carriedRuleMapsDetailed(carried)\n if (opaque.length > 0) {\n throw new Error(\n `fuseInterpreted: cannot interpret a composed grammar containing precompiled artifact(s) `\n + `${opaque.map(o => `\"${o.ns}\" (${o.ruleNames.length} rules)`).join(', ')} \u2014 they carry compiled functions, not a combinator graph. `\n + `Pass the source grammars (the same items you passed to compose()) instead.`,\n )\n }\n return maps.map(entries => ({ entries, plain: false }))\n }\n if ((item as LinkablePieces).ruleFns instanceof Map) {\n throw new Error('fuseInterpreted: a precompiled linkable artifact has no combinator graph to interpret; pass the source grammar (a rules() map) instead')\n }\n return [{ entries: Object.entries(item as Record<string, Combinator<unknown>>), plain: true }]\n}\n\n/**\n * Materialize a composition as a RUNNABLE INTERPRETED rule map \u2014 the interpreted\n * counterpart of `compose()`, with identical fuse semantics (later piece wins,\n * override reroutes the base's own calls, composing trivia governs every rule).\n * No codegen, no `new Function`, no macro build step: the result is a plain map of\n * combinators that `run()` / `parseDoc()` accept exactly like a fused map.\n *\n * This is what diagnostics and profiling run against \u2014 they must stay in\n * interpreted mode, and before this they could not see a composed grammar at all.\n *\n * Items are the SAME items `compose()`/`composeLeaf()` take: `rules()` maps\n * (the intended input), a prior `fuseInterpreted()` result, or a runtime\n * `compose()` result (re-lowered from its carried IR \u2014 note that carried IR cannot\n * materialize direct `node()` builders, so prefer the source maps). A precompiled\n * `linkable()` artifact is rejected: it has no combinator graph.\n *\n * MUTATION: binding a cross-piece hole rewrites the shared placeholder object every\n * call site already holds \u2014 that IS how an override reaches a base piece's own\n * calls. A second, DIFFERENT fusion over the same piece objects therefore throws\n * rather than silently rewriting the first one's parser.\n */\nexport function fuseInterpreted(\n items: Array<LinkablePieces | Record<string, unknown>>,\n opts?: { hostMode?: HostMode },\n): Record<string, Combinator<unknown>> {\n return fusePieces(items.flatMap(interpretedPieces), opts)\n}\n\n/** The rule names a fusion of these pieces defines, in winner order \u2014 computable\n * WITHOUT binding anything, which is what lets `composeLeaf()` expose its key set\n * before it fuses. */\nfunction ruleNamesOf(pieces: FusePiece[]): string[] {\n const names = new Set<string>()\n for (const piece of pieces) {\n for (const [name, value] of piece.entries) if (definitionOf(value) !== undefined) names.add(name)\n }\n return [...names]\n}\n\nfunction fusePieces(\n pieces: FusePiece[],\n opts?: { hostMode?: HostMode },\n): Record<string, Combinator<unknown>> {\n // Composing-wins trivia, read exactly as `composingTriviaOf` reads it for compose():\n // the LAST authored grammar that declared `rules({ trivia }, \u2026)`.\n let trivia: Combinator<unknown> | undefined\n for (let i = pieces.length - 1; i >= 0 && trivia === undefined; i--) {\n if (!pieces[i]!.plain) continue\n for (const [, rule] of pieces[i]!.entries) {\n const t = rule._meta.grammarTrivia\n if (t) { trivia = t; break }\n }\n }\n\n // Winner per rule name \u2014 later piece wins, matching `fuseRules`. The winner is the\n // DEFINITION, never the slot holding it: a slot can be repointed, and a chain\n // through one would make an override of X reroute into itself.\n const winner = new Map<string, Combinator<unknown>>()\n const entry = new Map<string, Combinator<unknown>>()\n for (const piece of pieces) {\n for (const [name, value] of piece.entries) {\n const def = definitionOf(value)\n if (def === undefined) continue\n winner.set(name, def)\n entry.set(name, value)\n }\n }\n\n // Bind every hole (and repoint every overridden slot) before anything runs.\n const missing = new Set<string>()\n for (const piece of pieces) {\n for (const [name, value] of piece.entries) {\n if (!isRefSlot(value)) continue\n const target = winner.get(name)\n if (target === undefined) { missing.add(name); continue }\n repointRef(value, target, name)\n }\n }\n if (missing.size > 0) throw new Error(missingRuleMessage(pieces, missing))\n\n const out: Record<string, Combinator<unknown>> = {}\n for (const [name, value] of entry) {\n out[name] = value\n const meta = value._meta as {\n isTrivia: boolean\n grammarTrivia?: Combinator<unknown>\n grammarHostMode?: HostMode\n }\n // A trivia rule must never carry the ambient trivia (it would recursively skip\n // trivia within itself) \u2014 the same guard `compileLinkable` applies per rule.\n if (trivia !== undefined && !meta.isTrivia) meta.grammarTrivia = trivia\n // Host mode is PER PIECE, exactly as `compileLinkable` resolves it: an explicit\n // option wins, otherwise the owning piece's own `rules({ hostMode })` stamp.\n if (opts?.hostMode !== undefined && !meta.isTrivia) {\n if (opts.hostMode === 'cst') meta.grammarHostMode = 'cst'\n else delete meta.grammarHostMode\n }\n }\n Object.defineProperty(out, INTERPRETED_PIECES, {\n value: pieces.filter(p => p.plain).map(p => p.entries),\n enumerable: false,\n })\n return out\n}\n\n/** Name-closure failure, reported the way the compiled fuse reports it: which rule\n * referenced the missing name. Computed only on the error path. */\nfunction missingRuleMessage(pieces: FusePiece[], missing: Set<string>): string {\n for (const piece of pieces) {\n const deps = ruleDependencies(piece.entries.filter(([, v]) => definitionOf(v) !== undefined))\n for (const [name, ds] of deps) {\n for (const d of ds) if (missing.has(d)) return `fuseInterpreted: rule \"${name}\" references missing rule \"${d}\"`\n }\n }\n return `fuseInterpreted: missing rule(s) ${[...missing].map(n => `\"${n}\"`).join(', ')}`\n}\n", "/**\n * Grammar spec model \u2014 a small, notation-agnostic tree that both the EBNF\n * emitter and the railroad-diagram emitter consume.\n *\n * The model is produced by walking the SAME `_def` structure the interpreter\n * and macro compiler consume, so a generated spec cannot drift from what\n * actually parses. See `docs/proposals/grammar-spec-generation.md`.\n */\nimport type { Combinator, ParserDef } from '../types.ts'\nimport { RULE_ORDER } from '../combinators/parser.ts'\nimport { recoverComposedRules } from '../compiler/linker.ts'\n\n// ---------------------------------------------------------------------------\n// Spec node tree\n// ---------------------------------------------------------------------------\n\n/** A node in the grammar spec tree \u2014 one per syntactic construct. */\nexport type SpecNode =\n | { kind: 'seq'; items: SpecNode[] }\n | { kind: 'choice'; items: SpecNode[] }\n /** `item*`, or `item{0,max}` when `many(\u2026, { max })` bounded it. */\n | { kind: 'star'; item: SpecNode; max?: number }\n /** `item+`, or `item{min,max}` when `many(\u2026, { min, max })` bounded it. `min`\n * defaults to 1 and is always >= 1 (a min-0 repeat is a `star`). */\n | { kind: 'plus'; item: SpecNode; min?: number; max?: number }\n | { kind: 'opt'; item: SpecNode }\n /**\n * Separated repetition. `min`/`max` count ITEMS, not separators: `min: 0` is\n * `(item (sep item)*)?` \u2014 NULLABLE \u2014 and any `min >= 1` requires that many\n * items, so it is not. `trailing` mirrors `sepBy`'s option of the same name.\n */\n | { kind: 'sepBy'; item: SpecNode; sep: SpecNode; min: number; max?: number; trailing?: 'allow' }\n /** Reference to a named production (non-terminal). */\n | { kind: 'ref'; name: string }\n /**\n * A terminal. `literal` terminals are exact strings (rendered quoted);\n * non-literal terminals are patterns/prose (rendered as-is, e.g. a regex\n * or a caller-supplied display name).\n */\n | { kind: 'terminal'; text: string; literal: boolean }\n /** Negative lookahead (`not`). Rendered as an annotation, not consumed input. */\n | { kind: 'not'; item: SpecNode }\n /** Positive lookahead (`ahead`). Zero-width, like `not`. */\n | { kind: 'peek'; item: SpecNode }\n /** An out-of-band annotation (guards, error-recovery, unknowns). */\n | { kind: 'annotation'; text: string }\n /** Matches nothing (elided trivia / semantic-only wrappers). */\n | { kind: 'empty' }\n\n/** One named production: `name ::= expr`. */\nexport type Production = {\n name: string\n expr: SpecNode\n /** True when the rule is trivia (whitespace/comment). Elided by default. */\n trivia: boolean\n}\n\nexport type SpecModel = {\n productions: Production[]\n}\n\nexport type SpecOptions = {\n /**\n * How to order the emitted productions when neither `order` nor `root` is given:\n * - `'source'` (default) \u2014 the order the rules were **declared** in the\n * `rules()` factory. Predictable, includes every rule, and leads with the\n * entry rule (authors write it first). Internal-but-referenced helper rules\n * follow, in first-reference order.\n * - `'reachable'` \u2014 BFS from the entry rule: the first-declared rule leads,\n * then each rule appears the first time it is referenced; any rules not\n * reachable from the entry are appended in declaration order.\n * Ignored when `order` or `root` is set.\n */\n sort?: 'source' | 'reachable'\n /**\n * Explicit rule order (and subset). When given, only these rules are emitted,\n * in this order, plus any rules they reach. Overrides `sort`.\n */\n order?: string[]\n /**\n * Start rule(s). When given, only these and the rules they reach are emitted\n * (a pruned, reachability-ordered spec). Overrides `sort`.\n */\n root?: string | string[]\n /** Include trivia rules (whitespace/comment) in the output. Default: false. */\n includeTrivia?: boolean\n /**\n * Display names for terminals, keyed by rule name. When a rule whose body is a\n * single terminal (regex/literal/keywords) has an entry here, that whole rule\n * renders as the given terminal name instead of expanding \u2014 e.g.\n * `{ Ident: 'identifier' }`.\n */\n terminals?: Record<string, string>\n /**\n * Best-effort rendering of a regex terminal to a readable form. Return\n * `undefined` to fall back to the default `/source/` rendering.\n */\n regexDisplay?: (source: string, flags: string) => string | undefined\n}\n\nexport type GrammarInput =\n | Record<string, Combinator<unknown>>\n | Combinator<unknown>\n\n// ---------------------------------------------------------------------------\n// Walk\n// ---------------------------------------------------------------------------\n\ntype Tagged = Combinator<unknown> & { _ruleName?: string }\n\nfunction ruleNameOf(c: Combinator<unknown>): string | undefined {\n return (c as Tagged)._ruleName\n}\n\n/** Resolve a `lazy`/`ref` combinator one hop to its defined body, if resolvable. */\nfunction resolveLazy(c: Combinator<unknown>): Combinator<unknown> | undefined {\n const def = c._def\n if (def.tag !== 'lazy') return undefined\n try {\n return def.thunk() as Combinator<unknown>\n } catch {\n return undefined\n }\n}\n\nfunction defaultRegexDisplay(source: string): string {\n return `/${source}/`\n}\n\nclass Builder {\n private seen = new Set<string>()\n private pending: Array<{ name: string; comb: Combinator<unknown> }> = []\n private pendingNames = new Set<string>()\n private record: Record<string, Combinator<unknown>>\n private opts: SpecOptions\n productions: Production[] = []\n\n constructor(record: Record<string, Combinator<unknown>>, opts: SpecOptions) {\n this.record = record\n this.opts = opts\n }\n\n enqueue(name: string, comb: Combinator<unknown>): void {\n if (this.seen.has(name)) return\n if (this.pendingNames.has(name)) return\n this.pendingNames.add(name)\n this.pending.push({ name, comb })\n }\n\n /**\n * Seed and drain in phases. Each phase seeds its names, then BFS-drains the\n * queue (following references) before the next phase seeds. This lets callers\n * express \"entry first, then its reachable closure, then any leftovers\" by\n * splitting the seed across phases; a single phase with every rule yields plain\n * declaration order (references, already queued, keep their declared slot).\n */\n run(phases: string[][]): SpecModel {\n for (const phase of phases) {\n for (const name of phase) {\n const comb = this.record[name]\n if (comb) this.enqueue(name, comb)\n }\n this.drain()\n }\n return { productions: this.productions }\n }\n\n private drain(): void {\n while (this.pending.length > 0) {\n const { name, comb } = this.pending.shift()!\n this.pendingNames.delete(name)\n if (this.seen.has(name)) continue\n this.seen.add(name)\n const expr = this.ruleBody(comb, name)\n this.productions.push({ name, expr, trivia: comb._meta.isTrivia === true })\n }\n }\n\n /** Walk a rule's top-level combinator, transparently unwrapping its own self-ref. */\n private ruleBody(comb: Combinator<unknown>, name: string): SpecNode {\n // A rule that IS a single terminal can be pinned to a caller display name.\n const pinned = this.opts.terminals?.[name]\n if (pinned !== undefined) return { kind: 'terminal', text: pinned, literal: false }\n\n let c = comb\n // Unwrap the rule's own placeholder ref(s) so we expand its body, not a\n // self-reference. Both the placeholder and the resolved body carry the same\n // `_ruleName`, so guard against cycles.\n const guard = new Set<Combinator<unknown>>()\n while (c._def.tag === 'lazy' && ruleNameOf(c) === name && !guard.has(c)) {\n guard.add(c)\n const next = resolveLazy(c)\n if (!next) break\n c = next\n }\n return this.walk(c, true)\n }\n\n /** Walk any combinator. `isRuleRoot` suppresses treating it as a self-reference. */\n private walk(c: Combinator<unknown>, isRuleRoot = false): SpecNode {\n // A reference to a named rule \u2192 non-terminal (unless this IS that rule's root).\n const rn = ruleNameOf(c)\n if (rn !== undefined && !isRuleRoot) {\n // Register the target so it gets its own production, even if it wasn't in\n // the returned record (internal-but-referenced helper rules).\n if (!this.record[rn]) this.record[rn] = c\n this.enqueue(rn, c)\n return { kind: 'ref', name: rn }\n }\n return this.walkDef(c._def, c)\n }\n\n private walkDef(def: ParserDef, self: Combinator<unknown>): SpecNode {\n switch (def.tag) {\n case 'literal':\n return { kind: 'terminal', text: def.value, literal: true }\n\n case 'regex': {\n const shown =\n this.opts.regexDisplay?.(def.source, def.flags) ??\n defaultRegexDisplay(def.source)\n return { kind: 'terminal', text: shown, literal: false }\n }\n\n case 'keywords':\n return {\n kind: 'choice',\n items: def.words.map(w => ({ kind: 'terminal', text: w, literal: true }) as SpecNode),\n }\n\n case 'sequence': {\n const items = def.parsers.map(p => this.walk(p)).filter(nonEmpty)\n return flattenSeq(items)\n }\n\n case 'choice': {\n const items = def.parsers.map(p => this.walk(p)).filter(nonEmpty)\n return flattenChoice(items)\n }\n\n case 'dispatch': {\n const selector = this.walk(def.selector)\n const tails = [\n ...def.cases.map(entry => this.walk(entry.parser)),\n ...(def.matchers ? def.matchers.map(entry => this.walk(entry.parser)) : []),\n ...(def.otherwise ? [this.walk(def.otherwise)] : []),\n ]\n return flattenSeq([selector, flattenChoice(tails)])\n }\n\n // `max`/`min` are carried through so a BOUNDED repeat does not render as an\n // unbounded one \u2014 the spec is generated to be read as the truth about what\n // parses, and `many(x, { min: 3, max: 8 })` is not `x+`.\n case 'many':\n return { kind: 'star', item: this.walk(def.parser), ...(def.max === undefined ? {} : { max: def.max }) }\n case 'oneOrMore':\n return {\n kind: 'plus', item: this.walk(def.parser),\n ...(def.min === 1 ? {} : { min: def.min }),\n ...(def.max === undefined ? {} : { max: def.max }),\n }\n case 'optional':\n return { kind: 'opt', item: this.walk(def.parser) }\n case 'attempt':\n return this.walk(def.parser)\n case 'sepBy':\n return {\n kind: 'sepBy', item: this.walk(def.parser), sep: this.walk(def.separator), min: def.min,\n ...(def.max === undefined ? {} : { max: def.max }),\n ...(def.trailing === undefined ? {} : { trailing: def.trailing }),\n }\n\n case 'not':\n return { kind: 'not', item: this.walk(def.parser) }\n case 'peek':\n return { kind: 'peek', item: this.walk(def.parser) }\n case 'routed':\n // The routed token is spelled by the dispatch selector, so it contributes\n // nothing here; a fallback IS spelled in place, so render it.\n return def.fallback === undefined ? { kind: 'empty' } : this.walk(def.fallback)\n\n // Transparent semantic wrappers \u2014 render the inner syntax.\n case 'transform':\n case 'token':\n case 'leaf':\n case 'label':\n case 'field':\n case 'expect':\n case 'withCtx':\n case 'node':\n return this.walk((def as { parser: Combinator<unknown> }).parser)\n\n case 'skip':\n return this.walk(def.main)\n case 'grammar':\n return this.walk(def.parser)\n\n // Error recovery \u2014 render the intended sub-parser, drop the sentinel.\n case 'recover':\n return this.walk(def.parser)\n case 'scanTo':\n return { kind: 'annotation', text: '\u2026' }\n\n // Trivia \u2014 elided by default; included as an annotation when asked.\n case 'trivia':\n return this.opts.includeTrivia ? this.walk(def.parser) : { kind: 'empty' }\n\n case 'guard':\n return { kind: 'empty' }\n\n case 'lazy': {\n const inner = resolveLazy(self)\n return inner ? this.walk(inner) : { kind: 'annotation', text: '?' }\n }\n\n case 'unknown':\n default:\n return { kind: 'annotation', text: '?' }\n }\n }\n}\n\nfunction nonEmpty(n: SpecNode): boolean {\n return n.kind !== 'empty'\n}\n\nfunction flattenSeq(items: SpecNode[]): SpecNode {\n const flat: SpecNode[] = []\n for (const it of items) {\n if (it.kind === 'seq') flat.push(...it.items)\n else flat.push(it)\n }\n if (flat.length === 0) return { kind: 'empty' }\n if (flat.length === 1) return flat[0]!\n return { kind: 'seq', items: flat }\n}\n\nfunction flattenChoice(items: SpecNode[]): SpecNode {\n const flat: SpecNode[] = []\n for (const it of items) {\n if (it.kind === 'choice') flat.push(...it.items)\n else flat.push(it)\n }\n if (flat.length === 0) return { kind: 'empty' }\n if (flat.length === 1) return flat[0]!\n return { kind: 'choice', items: flat }\n}\n\nfunction toRecord(grammar: GrammarInput): Record<string, Combinator<unknown>> {\n // A single combinator \u2192 a one-rule grammar keyed by its rule name or \"start\".\n if (isCombinator(grammar)) {\n const name = ruleNameOf(grammar) ?? 'start'\n return { [name]: grammar }\n }\n // A `compose()` result is a map of FUSED rule FUNCTIONS, not combinators \u2014 walking\n // it read `_def` off a function and threw a bare `TypeError: Cannot read properties\n // of undefined (reading 'tag')`. The combinator graph is recoverable from the\n // carried IR, so recover it rather than fail. (Same recovery the gating analysis\n // uses \u2014 see `recoverComposedRules`.)\n const recovered = recoverComposedRules(grammar as Record<string, unknown>)\n if (recovered !== undefined) {\n if (recovered.opaque.length > 0) {\n // Fail LOUDLY and specifically. A partial spec is worse than none: it renders a\n // grammar that looks complete while silently omitting whole artifacts.\n const named = recovered.opaque.map(o => `\"${o.ns}\"${o.ruleNames.length > 0 ? ` (${o.ruleNames.length} rule(s))` : ''}`).join(', ')\n throw new TypeError(\n `parseman spec: this composed grammar includes opaque precompiled artifact(s) ${named} that carry compiled rule `\n + 'functions rather than re-lowerable IR. Their rules cannot be rendered, and emitting a spec without them would '\n + 'silently understate the grammar. Recompile the contributing grammar(s) so they carry IR.',\n )\n }\n return Object.fromEntries(recovered.rules)\n }\n return grammar\n}\n\nfunction isCombinator(x: unknown): x is Combinator<unknown> {\n return (\n typeof x === 'object' &&\n x !== null &&\n typeof (x as { parse?: unknown }).parse === 'function' &&\n '_def' in (x as object)\n )\n}\n\n/** Declaration order recorded by `rules()`; falls back to the record's key order. */\nfunction declarationOrder(record: Record<string, Combinator<unknown>>): string[] {\n const declared = (record as Record<string, unknown>)[RULE_ORDER]\n if (Array.isArray(declared)) return declared.filter(k => k in record)\n return Object.keys(record)\n}\n\n/**\n * Build the notation-agnostic spec model from a `rules()` grammar (or a single\n * combinator). Following every referenced named rule keeps the closure complete;\n * ordering is controlled by `order` / `root` / `sort` (see {@link SpecOptions}).\n */\nexport function buildSpecModel(grammar: GrammarInput, options: SpecOptions = {}): SpecModel {\n const record = toRecord(grammar)\n const decl = declarationOrder(record)\n\n // Validate rule names in `order` / `root` up front. Left unchecked, an unknown\n // name (or a stray string like `order: 'source'` where a `string[]` is meant)\n // seeds a phase that reaches nothing and silently yields an EMPTY model \u2014 a\n // confusing footgun. Fail loudly with the offending names and the known rules.\n const known = new Set(decl)\n const asList = (v: string | string[]): string[] => (Array.isArray(v) ? v : [v])\n const requireKnown = (names: string[], opt: string): void => {\n const bad = names.filter(n => !known.has(n))\n if (bad.length > 0) {\n throw new Error(\n `buildSpecModel: unknown rule name(s) in \\`${opt}\\`: ${bad.map(n => JSON.stringify(n)).join(', ')}. ` +\n `Known rules: ${decl.map(n => JSON.stringify(n)).join(', ')}.`,\n )\n }\n }\n\n // Seed phases (see Builder.run). Priority: explicit `order` > `root` (pruned) >\n // `sort`. Default `sort` = 'source' (declaration order, every rule).\n let phases: string[][]\n if (options.order !== undefined) {\n const order = asList(options.order as string | string[])\n requireKnown(order, 'order')\n phases = [order]\n } else if (options.root !== undefined) {\n const root = asList(options.root)\n requireKnown(root, 'root')\n phases = [root]\n } else if (options.sort === 'reachable') {\n // Entry (first-declared) leads; BFS discovers the rest in first-reference\n // order; unreachable rules trail in declaration order.\n phases = decl.length > 0 ? [[decl[0]!], decl.slice(1)] : [decl]\n } else {\n phases = [decl]\n }\n\n const model = new Builder({ ...record }, options).run(phases)\n if (!options.includeTrivia) {\n model.productions = model.productions.filter(p => !p.trivia)\n }\n return model\n}\n", "/**\n * EBNF (W3C-style) text emitter for the grammar spec model.\n *\n * Precedence, lowest \u2192 highest: alternation (`|`) < concatenation (space) <\n * postfix (`* + ?`) < atom. The renderer parenthesizes only where a lower-\n * precedence construct sits inside a higher-precedence one.\n */\nimport type { Production, SpecModel, SpecNode } from './model.ts'\n\nconst ALT = 1 // choice\nconst CAT = 2 // sequence\nconst ATOM = 3 // terminal, ref, postfix, parenthesized\n\nfunction quote(s: string): string {\n // W3C EBNF uses quoted string terminals; prefer double quotes, fall back to\n // single quotes when the literal itself contains a double quote.\n if (s.includes('\"') && !s.includes(\"'\")) return `'${s}'`\n return `\"${s.replace(/\"/g, '\\\\\"')}\"`\n}\n\nfunction wrap(inner: string, innerLevel: number, minLevel: number): string {\n return innerLevel < minLevel ? `(${inner})` : inner\n}\n\n/**\n * Postfix repetition operator for an item count of `min..max`. The unbounded\n * counts keep their familiar `* + ?` spelling; a genuinely bounded repeat gets\n * the regex-style `{n,m}` form, since plain W3C EBNF has no way to say it and\n * silently rendering `x{3,8}` as `x+` understates the grammar.\n */\nfunction repeatOp(min: number, max: number | undefined): string {\n if (max === undefined) {\n if (min === 0) return '*'\n if (min === 1) return '+'\n return `{${min},}`\n }\n if (max === min) return min === 1 ? '' : `{${min}}`\n if (min === 0 && max === 1) return '?'\n return `{${min},${max}}`\n}\n\n/** Render a node, returning its text and precedence level. */\nfunction render(node: SpecNode): { text: string; level: number } {\n switch (node.kind) {\n case 'terminal':\n return { text: node.literal ? quote(node.text) : node.text, level: ATOM }\n case 'ref':\n return { text: node.name, level: ATOM }\n case 'empty':\n return { text: '', level: ATOM }\n case 'annotation':\n return { text: `/* ${node.text} */`, level: ATOM }\n\n case 'seq': {\n const text = node.items\n .map(it => {\n const r = render(it)\n return wrap(r.text, r.level, CAT)\n })\n .filter(t => t.length > 0)\n .join(' ')\n return { text, level: CAT }\n }\n\n case 'choice': {\n const text = node.items\n .map(it => {\n const r = render(it)\n return r.text.length === 0 ? '/* empty */' : wrap(r.text, r.level, ALT)\n })\n .join(' | ')\n return { text, level: ALT }\n }\n\n case 'star':\n case 'plus':\n case 'opt': {\n const r = render(node.item)\n const op = node.kind === 'opt'\n ? '?'\n : node.kind === 'star'\n ? repeatOp(0, node.max)\n : repeatOp(node.min ?? 1, node.max)\n return { text: `${wrap(r.text, r.level, ATOM)}${op}`, level: ATOM }\n }\n\n case 'sepBy': {\n const item = render(node.item)\n const sep = render(node.sep)\n const itemA = wrap(item.text, item.level, ATOM)\n const sepA = wrap(sep.text, sep.level, CAT)\n // The tail repeats `(sep item)` ONE FEWER time than there are items, so the\n // item bounds shift down by one to become the tail's bounds.\n const tail = `(${sepA} ${itemA})${repeatOp(Math.max(node.min - 1, 0), node.max === undefined ? undefined : node.max - 1)}`\n const trail = node.trailing === 'allow' ? ` ${sepA}?` : ''\n const body = `${itemA} ${tail}${trail}`\n // Only a min-0 list is OPTIONAL. Any `min >= 1` requires that many items and\n // can never match empty \u2014 rendering it `( \u2026 )?` claimed the opposite.\n return node.min === 0 ? { text: `(${body})?`, level: ATOM } : { text: body, level: CAT }\n }\n\n case 'not': {\n const r = render(node.item)\n return { text: `!${wrap(r.text, r.level, ATOM)}`, level: ATOM }\n }\n\n // PEG notation: `&` positive lookahead, `!` negative.\n case 'peek': {\n const r = render(node.item)\n return { text: `&${wrap(r.text, r.level, ATOM)}`, level: ATOM }\n }\n }\n}\n\nfunction renderProduction(p: Production): string {\n const { text } = render(p.expr)\n return `${p.name} ::= ${text || '/* empty */'}`\n}\n\n/** Render the whole spec model as EBNF text (one production per line). */\nexport function renderEBNF(model: SpecModel): string {\n return model.productions.map(renderProduction).join('\\n') + '\\n'\n}\n\n/** Render a single production's right-hand side (no `name ::=`). */\nexport function renderExpr(node: SpecNode): string {\n return render(node).text\n}\n", "/**\n * Vendored copy of tabatkins railroad-diagrams (v1.0.0), license CC0-1.0.\n * https://github.com/tabatkins/railroad-diagrams\n *\n * Public domain (CC0) \u2014 embedded verbatim as strings so the generated\n * railroad-diagram HTML page is fully self-contained (no CDN, no runtime dep).\n * Do not edit by hand; regenerate from the npm package if bumping versions.\n */\n/* eslint-disable */\nexport const RAILROAD_JS: string = `/*\nRailroad Diagrams\nby Tab Atkins Jr. (and others)\nhttp://xanthir.com\nhttp://twitter.com/tabatkins\nhttp://github.com/tabatkins/railroad-diagrams\n\nThis document and all associated files in the github project are licensed under CC0: http://creativecommons.org/publicdomain/zero/1.0/\nThis means you can reuse, remix, or otherwise appropriate this project for your own use WITHOUT RESTRICTION.\n(The actual legal meaning can be found at the above link.)\nDon't ask me for permission to use any part of this project, JUST USE IT.\nI would appreciate attribution, but that is not required by the license.\n*/\n\n/*\nThis file uses a module pattern to avoid leaking names into the global scope.\nThe only accidental leakage is the name \"temp\".\nThe exported names can be found at the bottom of this file;\nsimply change the names in the array of strings to change what they are called in your application.\n\nAs well, several configuration constants are passed into the module function at the bottom of this file.\nAt runtime, these constants can be found on the Diagram class.\n*/\n\n(function(options) {\n\tfunction subclassOf(baseClass, superClass) {\n\t\tbaseClass.prototype = Object.create(superClass.prototype);\n\t\tbaseClass.prototype.$super = superClass.prototype;\n\t}\n\n\tfunction unnull(/* children */) {\n\t\treturn [].slice.call(arguments).reduce(function(sofar, x) { return sofar !== undefined ? sofar : x; });\n\t}\n\n\tfunction determineGaps(outer, inner) {\n\t\tvar diff = outer - inner;\n\t\tswitch(Diagram.INTERNAL_ALIGNMENT) {\n\t\t\tcase 'left': return [0, diff]; break;\n\t\t\tcase 'right': return [diff, 0]; break;\n\t\t\tcase 'center':\n\t\t\tdefault: return [diff/2, diff/2]; break;\n\t\t}\n\t}\n\n\tfunction wrapString(value) {\n\t\treturn ((typeof value) == 'string') ? new Terminal(value) : value;\n\t}\n\n\n\tfunction SVG(name, attrs, text) {\n\t\tattrs = attrs || {};\n\t\ttext = text || '';\n\t\tvar el = document.createElementNS(\"http://www.w3.org/2000/svg\",name);\n\t\tfor(var attr in attrs) {\n\t\t\tel.setAttribute(attr, attrs[attr]);\n\t\t}\n\t\tel.textContent = text;\n\t\treturn el;\n\t}\n\n\tfunction FakeSVG(tagName, attrs, text){\n\t\tif(!(this instanceof FakeSVG)) return new FakeSVG(tagName, attrs, text);\n\t\tif(text) this.children = text;\n\t\telse this.children = [];\n\t\tthis.tagName = tagName;\n\t\tthis.attrs = unnull(attrs, {});\n\t\treturn this;\n\t};\n\tFakeSVG.prototype.format = function(x, y, width) {\n\t\t// Virtual\n\t};\n\tFakeSVG.prototype.addTo = function(parent) {\n\t\tif(parent instanceof FakeSVG) {\n\t\t\tparent.children.push(this);\n\t\t\treturn this;\n\t\t} else {\n\t\t\tvar svg = this.toSVG();\n\t\t\tparent.appendChild(svg);\n\t\t\treturn svg;\n\t\t}\n\t};\n\tFakeSVG.prototype.escapeString = function(string) {\n // Escape markdown and HTML special characters\n\t\treturn string.replace(/[*_\\\\\\`\\\\[\\\\]<&]/g, function(charString) {\n\t\t\treturn '&#' + charString.charCodeAt(0) + ';';\n\t\t});\n\t};\n\tFakeSVG.prototype.toSVG = function() {\n\t\tvar el = SVG(this.tagName, this.attrs);\n\t\tif(typeof this.children == 'string') {\n\t\t\tel.innerHTML = FakeSVG.prototype.escapeString(this.children);\n\t\t} else {\n\t\t\tthis.children.forEach(function(e) {\n\t\t\t\tel.appendChild(e.toSVG());\n\t\t\t});\n\t\t}\n\t\treturn el;\n\t};\n\tFakeSVG.prototype.toString = function() {\n\t\tvar str = '<' + this.tagName;\n\t\tvar group = this.tagName == \"g\" || this.tagName == \"svg\";\n\t\tfor(var attr in this.attrs) {\n\t\t\tstr += ' ' + attr + '=\"' + (this.attrs[attr]+'').replace(/&/g, '&amp;').replace(/\"/g, '&quot;') + '\"';\n\t\t}\n\t\tstr += '>';\n\t\tif(group) str += \"\\\\n\";\n\t\tif(typeof this.children == 'string') {\n\t\t\tstr += FakeSVG.prototype.escapeString(this.children);\n\t\t} else {\n\t\t\tthis.children.forEach(function(e) {\n\t\t\t\tstr += e;\n\t\t\t});\n\t\t}\n\t\tstr += '</' + this.tagName + '>\\\\n';\n\t\treturn str;\n\t}\n\n\tfunction Path(x,y) {\n\t\tif(!(this instanceof Path)) return new Path(x,y);\n\t\tFakeSVG.call(this, 'path');\n\t\tthis.attrs.d = \"M\"+x+' '+y;\n\t}\n\tsubclassOf(Path, FakeSVG);\n\tPath.prototype.m = function(x,y) {\n\t\tthis.attrs.d += 'm'+x+' '+y;\n\t\treturn this;\n\t}\n\tPath.prototype.h = function(val) {\n\t\tthis.attrs.d += 'h'+val;\n\t\treturn this;\n\t}\n\tPath.prototype.right = Path.prototype.h;\n\tPath.prototype.left = function(val) { return this.h(-val); }\n\tPath.prototype.v = function(val) {\n\t\tthis.attrs.d += 'v'+val;\n\t\treturn this;\n\t}\n\tPath.prototype.down = Path.prototype.v;\n\tPath.prototype.up = function(val) { return this.v(-val); }\n\tPath.prototype.arc = function(sweep){\n\t\tvar x = Diagram.ARC_RADIUS;\n\t\tvar y = Diagram.ARC_RADIUS;\n\t\tif(sweep[0] == 'e' || sweep[1] == 'w') {\n\t\t\tx *= -1;\n\t\t}\n\t\tif(sweep[0] == 's' || sweep[1] == 'n') {\n\t\t\ty *= -1;\n\t\t}\n\t\tif(sweep == 'ne' || sweep == 'es' || sweep == 'sw' || sweep == 'wn') {\n\t\t\tvar cw = 1;\n\t\t} else {\n\t\t\tvar cw = 0;\n\t\t}\n\t\tthis.attrs.d += \"a\"+Diagram.ARC_RADIUS+\" \"+Diagram.ARC_RADIUS+\" 0 0 \"+cw+' '+x+' '+y;\n\t\treturn this;\n\t}\n\tPath.prototype.format = function() {\n\t\t// All paths in this library start/end horizontally.\n\t\t// The extra .5 ensures a minor overlap, so there's no seams in bad rasterizers.\n\t\tthis.attrs.d += 'h.5';\n\t\treturn this;\n\t}\n\n\tfunction Diagram(items) {\n\t\tif(!(this instanceof Diagram)) return new Diagram([].slice.call(arguments));\n\t\tFakeSVG.call(this, 'svg', {class: Diagram.DIAGRAM_CLASS});\n\t\tthis.items = items.map(wrapString);\n\t\tthis.items.unshift(new Start);\n\t\tthis.items.push(new End);\n\t\tthis.width = this.items.reduce(function(sofar, el) { return sofar + el.width + (el.needsSpace?20:0)}, 0)+1;\n\t\tthis.up = Math.max.apply(null, this.items.map(function (x) { return x.up; }));\n\t\tthis.down = Math.max.apply(null, this.items.map(function (x) { return x.down; }));\n\t\tthis.formatted = false;\n\t}\n\tsubclassOf(Diagram, FakeSVG);\n\tfor(var option in options) {\n\t\tDiagram[option] = options[option];\n\t}\n\tDiagram.prototype.format = function(paddingt, paddingr, paddingb, paddingl) {\n\t\tpaddingt = unnull(paddingt, 20);\n\t\tpaddingr = unnull(paddingr, paddingt, 20);\n\t\tpaddingb = unnull(paddingb, paddingt, 20);\n\t\tpaddingl = unnull(paddingl, paddingr, 20);\n\t\tvar x = paddingl;\n\t\tvar y = paddingt;\n\t\ty += this.up;\n\t\tvar g = FakeSVG('g', Diagram.STROKE_ODD_PIXEL_LENGTH ? {transform:'translate(.5 .5)'} : {});\n\t\tfor(var i = 0; i < this.items.length; i++) {\n\t\t\tvar item = this.items[i];\n\t\t\tif(item.needsSpace) {\n\t\t\t\tPath(x,y).h(10).addTo(g);\n\t\t\t\tx += 10;\n\t\t\t}\n\t\t\titem.format(x, y, item.width).addTo(g);\n\t\t\tx += item.width;\n\t\t\tif(item.needsSpace) {\n\t\t\t\tPath(x,y).h(10).addTo(g);\n\t\t\t\tx += 10;\n\t\t\t}\n\t\t}\n\t\tthis.attrs.width = this.width + paddingl + paddingr;\n\t\tthis.attrs.height = this.up + this.down + paddingt + paddingb;\n\t\tthis.attrs.viewBox = \"0 0 \" + this.attrs.width + \" \" + this.attrs.height;\n\t\tg.addTo(this);\n\t\tthis.formatted = true;\n\t\treturn this;\n\t}\n\tDiagram.prototype.addTo = function(parent) {\n\t\tvar scriptTag = document.getElementsByTagName('script');\n\t\tscriptTag = scriptTag[scriptTag.length - 1];\n\t\tvar parentTag = scriptTag.parentNode;\n\t\tparent = parent || parentTag;\n\t\treturn this.$super.addTo.call(this, parent);\n\t}\n\tDiagram.prototype.toSVG = function() {\n\t\tif (!this.formatted) {\n\t\t\tthis.format();\n\t\t}\n\t\treturn this.$super.toSVG.call(this);\n\t}\n\tDiagram.prototype.toString = function() {\n\t\tif (!this.formatted) {\n\t\t\tthis.format();\n\t\t}\n\t\treturn this.$super.toString.call(this);\n\t}\n\n\tfunction ComplexDiagram() {\n\t\tvar diagram = new Diagram([].slice.call(arguments));\n var items = diagram.items;\n\t\titems.shift();\n\t\titems.pop();\n\t\titems.unshift(new Start(false));\n\t\titems.push(new End(false));\n\t\tdiagram.items = items;\n\t\treturn diagram;\n }\n\n\tfunction Sequence(items) {\n\t\tif(!(this instanceof Sequence)) return new Sequence([].slice.call(arguments));\n\t\tFakeSVG.call(this, 'g');\n\t\tthis.items = items.map(wrapString);\n\t\tthis.width = this.items.reduce(function(sofar, el) { return sofar + el.width + (el.needsSpace?20:0)}, 0);\n\t\tthis.up = this.items.reduce(function(sofar,el) { return Math.max(sofar, el.up)}, 0);\n\t\tthis.down = this.items.reduce(function(sofar,el) { return Math.max(sofar, el.down)}, 0);\n\t}\n\tsubclassOf(Sequence, FakeSVG);\n\tSequence.prototype.format = function(x,y,width) {\n\t\t// Hook up the two sides if this is narrower than its stated width.\n\t\tvar gaps = determineGaps(width, this.width);\n\t\tPath(x,y).h(gaps[0]).addTo(this);\n\t\tPath(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);\n\t\tx += gaps[0];\n\n\t\tfor(var i = 0; i < this.items.length; i++) {\n\t\t\tvar item = this.items[i];\n\t\t\tif(item.needsSpace) {\n\t\t\t\tPath(x,y).h(10).addTo(this);\n\t\t\t\tx += 10;\n\t\t\t}\n\t\t\titem.format(x, y, item.width).addTo(this);\n\t\t\tx += item.width;\n\t\t\tif(item.needsSpace) {\n\t\t\t\tPath(x,y).h(10).addTo(this);\n\t\t\t\tx += 10;\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\tfunction Choice(normal, items) {\n\t\tif(!(this instanceof Choice)) return new Choice(normal, [].slice.call(arguments,1));\n\t\tFakeSVG.call(this, 'g');\n\t\tif( typeof normal !== \"number\" || normal !== Math.floor(normal) ) {\n\t\t\tthrow new TypeError(\"The first argument of Choice() must be an integer.\");\n\t\t} else if(normal < 0 || normal >= items.length) {\n\t\t\tthrow new RangeError(\"The first argument of Choice() must be an index for one of the items.\");\n\t\t} else {\n\t\t\tthis.normal = normal;\n\t\t}\n\t\tthis.items = items.map(wrapString);\n\t\tthis.width = this.items.reduce(function(sofar, el){return Math.max(sofar, el.width)},0) + Diagram.ARC_RADIUS*4;\n\t\tthis.up = this.down = 0;\n\t\tfor(var i = 0; i < this.items.length; i++) {\n\t\t\tvar item = this.items[i];\n\t\t\tif(i < normal) { this.up += Math.max(Diagram.ARC_RADIUS,item.up + item.down + Diagram.VERTICAL_SEPARATION); }\n\t\t\tif(i == normal) { this.up += Math.max(Diagram.ARC_RADIUS, item.up); this.down += Math.max(Diagram.ARC_RADIUS, item.down); }\n\t\t\tif(i > normal) { this.down += Math.max(Diagram.ARC_RADIUS,Diagram.VERTICAL_SEPARATION + item.up + item.down); }\n\t\t}\n\t}\n\tsubclassOf(Choice, FakeSVG);\n\tChoice.prototype.format = function(x,y,width) {\n\t\t// Hook up the two sides if this is narrower than its stated width.\n\t\tvar gaps = determineGaps(width, this.width);\n\t\tPath(x,y).h(gaps[0]).addTo(this);\n\t\tPath(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);\n\t\tx += gaps[0];\n\n\t\tvar last = this.items.length -1;\n\t\tvar innerWidth = this.width - Diagram.ARC_RADIUS*4;\n\n\t\t// Do the elements that curve above\n\t\tfor(var i = this.normal - 1; i >= 0; i--) {\n\t\t\tvar item = this.items[i];\n\t\t\tif( i == this.normal - 1 ) {\n\t\t\t\tvar distanceFromY = Math.max(Diagram.ARC_RADIUS*2, this.items[i+1].up + Diagram.VERTICAL_SEPARATION + item.down);\n\t\t\t}\n\t\t\tPath(x,y).arc('se').up(distanceFromY - Diagram.ARC_RADIUS*2).arc('wn').addTo(this);\n\t\t\titem.format(x+Diagram.ARC_RADIUS*2,y - distanceFromY,innerWidth).addTo(this);\n\t\t\tPath(x+Diagram.ARC_RADIUS*2+innerWidth, y-distanceFromY).arc('ne').down(distanceFromY - Diagram.ARC_RADIUS*2).arc('ws').addTo(this);\n\t\t\tdistanceFromY += Math.max(Diagram.ARC_RADIUS, item.up + Diagram.VERTICAL_SEPARATION + (i == 0 ? 0 : this.items[i-1].down));\n\t\t}\n\n\t\t// Do the straight-line path.\n\t\tPath(x,y).right(Diagram.ARC_RADIUS*2).addTo(this);\n\t\tthis.items[this.normal].format(x+Diagram.ARC_RADIUS*2, y, innerWidth).addTo(this);\n\t\tPath(x+Diagram.ARC_RADIUS*2+innerWidth, y).right(Diagram.ARC_RADIUS*2).addTo(this);\n\n\t\t// Do the elements that curve below\n\t\tfor(var i = this.normal+1; i <= last; i++) {\n\t\t\tvar item = this.items[i];\n\t\t\tif( i == this.normal + 1 ) {\n\t\t\t\tvar distanceFromY = Math.max(Diagram.ARC_RADIUS*2, this.items[i-1].down + Diagram.VERTICAL_SEPARATION + item.up);\n\t\t\t}\n\t\t\tPath(x,y).arc('ne').down(distanceFromY - Diagram.ARC_RADIUS*2).arc('ws').addTo(this);\n\t\t\titem.format(x+Diagram.ARC_RADIUS*2, y+distanceFromY, innerWidth).addTo(this);\n\t\t\tPath(x+Diagram.ARC_RADIUS*2+innerWidth, y+distanceFromY).arc('se').up(distanceFromY - Diagram.ARC_RADIUS*2).arc('wn').addTo(this);\n\t\t\tdistanceFromY += Math.max(Diagram.ARC_RADIUS, item.down + Diagram.VERTICAL_SEPARATION + (i == last ? 0 : this.items[i+1].up));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tfunction Optional(item, skip) {\n\t\tif( skip === undefined )\n\t\t\treturn Choice(1, Skip(), item);\n\t\telse if ( skip === \"skip\" )\n\t\t\treturn Choice(0, Skip(), item);\n\t\telse\n\t\t\tthrow \"Unknown value for Optional()'s 'skip' argument.\";\n\t}\n\n\tfunction OneOrMore(item, rep) {\n\t\tif(!(this instanceof OneOrMore)) return new OneOrMore(item, rep);\n\t\tFakeSVG.call(this, 'g');\n\t\trep = rep || (new Skip);\n\t\tthis.item = wrapString(item);\n\t\tthis.rep = wrapString(rep);\n\t\tthis.width = Math.max(this.item.width, this.rep.width) + Diagram.ARC_RADIUS*2;\n\t\tthis.up = this.item.up;\n\t\tthis.down = Math.max(Diagram.ARC_RADIUS*2, this.item.down + Diagram.VERTICAL_SEPARATION + this.rep.up + this.rep.down);\n\t}\n\tsubclassOf(OneOrMore, FakeSVG);\n\tOneOrMore.prototype.needsSpace = true;\n\tOneOrMore.prototype.format = function(x,y,width) {\n\t\t// Hook up the two sides if this is narrower than its stated width.\n\t\tvar gaps = determineGaps(width, this.width);\n\t\tPath(x,y).h(gaps[0]).addTo(this);\n\t\tPath(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);\n\t\tx += gaps[0];\n\n\t\t// Draw item\n\t\tPath(x,y).right(Diagram.ARC_RADIUS).addTo(this);\n\t\tthis.item.format(x+Diagram.ARC_RADIUS,y,this.width-Diagram.ARC_RADIUS*2).addTo(this);\n\t\tPath(x+this.width-Diagram.ARC_RADIUS,y).right(Diagram.ARC_RADIUS).addTo(this);\n\n\t\t// Draw repeat arc\n\t\tvar distanceFromY = Math.max(Diagram.ARC_RADIUS*2, this.item.down+Diagram.VERTICAL_SEPARATION+this.rep.up);\n\t\tPath(x+Diagram.ARC_RADIUS,y).arc('nw').down(distanceFromY-Diagram.ARC_RADIUS*2).arc('ws').addTo(this);\n\t\tthis.rep.format(x+Diagram.ARC_RADIUS, y+distanceFromY, this.width - Diagram.ARC_RADIUS*2).addTo(this);\n\t\tPath(x+this.width-Diagram.ARC_RADIUS, y+distanceFromY).arc('se').up(distanceFromY-Diagram.ARC_RADIUS*2).arc('en').addTo(this);\n\n\t\treturn this;\n\t}\n\n\tfunction ZeroOrMore(item, rep, skip) {\n\t\treturn Optional(OneOrMore(item, rep), skip);\n\t}\n\n\tfunction Start(simpleType) {\n\t\tif(!(this instanceof Start)) return new Start();\n\t\tFakeSVG.call(this, 'path');\n\t\tthis.width = 20;\n\t\tthis.up = 10;\n\t\tthis.down = 10;\n\t\tthis.simpleType = simpleType;\n\t}\n\tsubclassOf(Start, FakeSVG);\n\tStart.prototype.format = function(x,y) {\n\t\tif (this.simpleType === false) {\n\t\t\tthis.attrs.d = 'M '+x+' '+(y-10)+' v 20 m 0 -10 h 20.5';\n\t\t} else {\n\t\t\tthis.attrs.d = 'M '+x+' '+(y-10)+' v 20 m 10 -20 v 20 m -10 -10 h 20.5';\n\t\t}\n\t\treturn this;\n\t}\n\n\tfunction End(simpleType) {\n\t\tif(!(this instanceof End)) return new End();\n\t\tFakeSVG.call(this, 'path');\n\t\tthis.width = 20;\n\t\tthis.up = 10;\n\t\tthis.down = 10;\n\t\tthis.simpleType = simpleType;\n\t}\n\tsubclassOf(End, FakeSVG);\n\tEnd.prototype.format = function(x,y) {\n\t\tif (this.simpleType === false) {\n\t\t\tthis.attrs.d = 'M '+x+' '+y+' h 20 m 0 -10 v 20';\n\t\t} else {\n\t\t\tthis.attrs.d = 'M '+x+' '+y+' h 20 m -10 -10 v 20 m 10 -20 v 20';\n\t\t}\n\t\treturn this;\n\t}\n\n\tfunction Terminal(text) {\n\t\tif(!(this instanceof Terminal)) return new Terminal(text);\n\t\tFakeSVG.call(this, 'g');\n\t\tthis.text = text;\n\t\tthis.width = text.length * 8 + 20; /* Assume that each char is .5em, and that the em is 16px */\n\t\tthis.up = 11;\n\t\tthis.down = 11;\n\t}\n\tsubclassOf(Terminal, FakeSVG);\n\tTerminal.prototype.needsSpace = true;\n\tTerminal.prototype.format = function(x, y, width) {\n\t\t// Hook up the two sides if this is narrower than its stated width.\n\t\tvar gaps = determineGaps(width, this.width);\n\t\tPath(x,y).h(gaps[0]).addTo(this);\n\t\tPath(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);\n\t\tx += gaps[0];\n\n\t\tFakeSVG('rect', {x:x, y:y-11, width:this.width, height:this.up+this.down, rx:10, ry:10}).addTo(this);\n\t\tFakeSVG('text', {x:x+this.width/2, y:y+4}, this.text).addTo(this);\n\t\treturn this;\n\t}\n\n\tfunction NonTerminal(text) {\n\t\tif(!(this instanceof NonTerminal)) return new NonTerminal(text);\n\t\tFakeSVG.call(this, 'g');\n\t\tthis.text = text;\n\t\tthis.width = text.length * 8 + 20;\n\t\tthis.up = 11;\n\t\tthis.down = 11;\n\t}\n\tsubclassOf(NonTerminal, FakeSVG);\n\tNonTerminal.prototype.needsSpace = true;\n\tNonTerminal.prototype.format = function(x, y, width) {\n\t\t// Hook up the two sides if this is narrower than its stated width.\n\t\tvar gaps = determineGaps(width, this.width);\n\t\tPath(x,y).h(gaps[0]).addTo(this);\n\t\tPath(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);\n\t\tx += gaps[0];\n\n\t\tFakeSVG('rect', {x:x, y:y-11, width:this.width, height:this.up+this.down}).addTo(this);\n\t\tFakeSVG('text', {x:x+this.width/2, y:y+4}, this.text).addTo(this);\n\t\treturn this;\n\t}\n\n\tfunction Comment(text) {\n\t\tif(!(this instanceof Comment)) return new Comment(text);\n\t\tFakeSVG.call(this, 'g');\n\t\tthis.text = text;\n\t\tthis.width = text.length * 7 + 10;\n\t\tthis.up = 11;\n\t\tthis.down = 11;\n\t}\n\tsubclassOf(Comment, FakeSVG);\n\tComment.prototype.needsSpace = true;\n\tComment.prototype.format = function(x, y, width) {\n\t\t// Hook up the two sides if this is narrower than its stated width.\n\t\tvar gaps = determineGaps(width, this.width);\n\t\tPath(x,y).h(gaps[0]).addTo(this);\n\t\tPath(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);\n\t\tx += gaps[0];\n\n\t\tFakeSVG('text', {x:x+this.width/2, y:y+5, class:'comment'}, this.text).addTo(this);\n\t\treturn this;\n\t}\n\n\tfunction Skip() {\n\t\tif(!(this instanceof Skip)) return new Skip();\n\t\tFakeSVG.call(this, 'g');\n\t\tthis.width = 0;\n\t\tthis.up = 0;\n\t\tthis.down = 0;\n\t}\n\tsubclassOf(Skip, FakeSVG);\n\tSkip.prototype.format = function(x, y, width) {\n\t\tPath(x,y).right(width).addTo(this);\n\t\treturn this;\n\t}\n\t\n\tvar root;\n\tif (typeof define === 'function' && define.amd) {\n\t\t// AMD. Register as an anonymous module.\n\t\troot = {};\n\t\tdefine([], function() {\n\t\t\treturn root;\n\t\t});\n\t} else if (typeof exports === 'object') {\n\t\t// CommonJS for node\n\t\troot = exports;\n\t} else {\n\t\t// Browser globals (root is window)\n\t\troot = this;\n\t}\n\n\tvar temp = [Diagram, ComplexDiagram, Sequence, Choice, Optional, OneOrMore, ZeroOrMore, Terminal, NonTerminal, Comment, Skip];\n\t/*\n\tThese are the names that the internal classes are exported as.\n\tIf you would like different names, adjust them here.\n\t*/\n\t['Diagram', 'ComplexDiagram', 'Sequence', 'Choice', 'Optional', 'OneOrMore', 'ZeroOrMore', 'Terminal', 'NonTerminal', 'Comment', 'Skip']\n\t\t.forEach(function(e,i) { root[e] = temp[i]; });\n}).call(this,\n\t{\n\tVERTICAL_SEPARATION: 8,\n\tARC_RADIUS: 10,\n\tDIAGRAM_CLASS: 'railroad-diagram',\n\tSTROKE_ODD_PIXEL_LENGTH: true,\n\tINTERNAL_ALIGNMENT: 'center',\n\t}\n);\n`\n\nexport const RAILROAD_CSS: string = `svg.railroad-diagram {\n background-color: hsl(30,20%,95%);\n}\nsvg.railroad-diagram path {\n stroke-width: 3;\n stroke: black;\n fill: rgba(0,0,0,0);\n}\nsvg.railroad-diagram text {\n font: bold 14px monospace;\n text-anchor: middle;\n}\nsvg.railroad-diagram text.label {\n text-anchor: start;\n}\nsvg.railroad-diagram text.comment {\n font: italic 12px monospace;\n}\nsvg.railroad-diagram rect {\n stroke-width: 3;\n stroke: black;\n fill: hsl(120,100%,90%);\n}\n`\n", "/**\n * Railroad-diagram (syntax-diagram) emitter. Converts the spec model to a\n * self-contained HTML page that renders SVG railroad diagrams \u2014 one per\n * production \u2014 using a vendored copy of tabatkins/railroad-diagrams (CC0).\n *\n * The page has no external dependencies: the diagram library and its CSS are\n * inlined, so it renders offline and drops straight into a docs site.\n */\nimport type { Production, SpecModel, SpecNode } from './model.ts'\nimport { renderExpr } from './ebnf.ts'\nimport { RAILROAD_CSS, RAILROAD_JS } from './railroad-lib.ts'\n\nconst j = (s: string): string => JSON.stringify(s)\n\n/**\n * Human label for a bounded repeat, or `null` when the bounds are the default\n * ones the diagram shape already conveys (`ZeroOrMore` = 0+, `OneOrMore` = 1+).\n * Railroad diagrams have no repetition-count primitive, so a genuine bound rides\n * the repeat's loop-back path as a Comment rather than going unrendered.\n */\nfunction boundLabel(min: number, max: number | undefined): string | null {\n if (max === undefined) return min <= 1 ? null : `${min}+ times`\n if (max === min) return `${min}\u00D7`\n return `${min}\u2013${max} times`\n}\n\n/** Convert a spec node to a railroad-diagrams DSL expression string. */\nfunction toDsl(node: SpecNode): string {\n switch (node.kind) {\n case 'terminal':\n return `Terminal(${j(node.text)})`\n case 'ref':\n return `NonTerminal(${j(node.name)})`\n case 'empty':\n return `Skip()`\n case 'annotation':\n return `Comment(${j(node.text)})`\n case 'seq':\n return `Sequence(${node.items.map(toDsl).join(', ')})`\n case 'choice':\n return `Choice(0, ${node.items.map(toDsl).join(', ')})`\n case 'star': {\n const b = boundLabel(0, node.max)\n return b ? `ZeroOrMore(${toDsl(node.item)}, Comment(${j(b)}))` : `ZeroOrMore(${toDsl(node.item)})`\n }\n case 'plus': {\n const b = boundLabel(node.min ?? 1, node.max)\n return b ? `OneOrMore(${toDsl(node.item)}, Comment(${j(b)}))` : `OneOrMore(${toDsl(node.item)})`\n }\n case 'opt':\n return `Optional(${toDsl(node.item)})`\n case 'sepBy': {\n // OneOrMore(item, separator): the separator rides the repeat loop, carrying\n // the item-count label with it when the list is bounded.\n const b = boundLabel(node.min, node.max)\n const loop = b ? `Sequence(${toDsl(node.sep)}, Comment(${j(b)}))` : toDsl(node.sep)\n const rep = `OneOrMore(${toDsl(node.item)}, ${loop})`\n const withTrail = node.trailing === undefined\n ? rep\n : `Sequence(${rep}, Optional(${toDsl(node.sep)}))`\n // ONLY a min-0 list can match nothing. Collapsing every `min > 1` into\n // Optional too rendered a list that requires N items as nullable.\n return node.min === 0 ? `Optional(${withTrail})` : withTrail\n }\n case 'not':\n return `Sequence(Comment(\"not\"), ${toDsl(node.item)})`\n case 'peek':\n return `Sequence(Comment(\"peek\"), ${toDsl(node.item)})`\n }\n}\n\n// Vendored railroad-diagrams builders, evaluated once. `.toString()` on the\n// result walks an in-memory FakeSVG tree and emits SVG markup with no DOM \u2014 so a\n// diagram can be rendered to a static SVG string at build time (Node), not just\n// in the browser. The library exports onto `exports` when it's an object.\ntype RailroadBuilders = {\n Diagram: (item: unknown) => { toString(): string }\n Sequence: (...xs: unknown[]) => unknown\n Choice: (normal: number, ...xs: unknown[]) => unknown\n Optional: (x: unknown) => unknown\n OneOrMore: (x: unknown, sep?: unknown) => unknown\n ZeroOrMore: (x: unknown, rep?: unknown) => unknown\n Terminal: (t: string) => unknown\n NonTerminal: (t: string) => unknown\n Comment: (t: string) => unknown\n Skip: () => unknown\n}\nlet _builders: RailroadBuilders | null = null\nfunction builders(): RailroadBuilders {\n if (_builders) return _builders\n const mod = {} as Record<string, unknown>\n // eslint-disable-next-line no-new-func\n new Function('exports', RAILROAD_JS)(mod)\n _builders = mod as unknown as RailroadBuilders\n return _builders\n}\n\n/** Build a railroad-diagrams object from a spec node (mirrors `toDsl`, but live). */\nfunction toDiagramNode(b: RailroadBuilders, node: SpecNode): unknown {\n switch (node.kind) {\n case 'terminal': return b.Terminal(node.text)\n case 'ref': return b.NonTerminal(node.name)\n case 'empty': return b.Skip()\n case 'annotation': return b.Comment(node.text)\n case 'seq': return b.Sequence(...node.items.map((n) => toDiagramNode(b, n)))\n case 'choice': return b.Choice(0, ...node.items.map((n) => toDiagramNode(b, n)))\n case 'star': {\n const lbl = boundLabel(0, node.max)\n return lbl ? b.ZeroOrMore(toDiagramNode(b, node.item), b.Comment(lbl)) : b.ZeroOrMore(toDiagramNode(b, node.item))\n }\n case 'plus': {\n const lbl = boundLabel(node.min ?? 1, node.max)\n return lbl ? b.OneOrMore(toDiagramNode(b, node.item), b.Comment(lbl)) : b.OneOrMore(toDiagramNode(b, node.item))\n }\n case 'opt': return b.Optional(toDiagramNode(b, node.item))\n case 'sepBy': {\n const lbl = boundLabel(node.min, node.max)\n const sep = toDiagramNode(b, node.sep)\n const rep = b.OneOrMore(toDiagramNode(b, node.item), lbl ? b.Sequence(sep, b.Comment(lbl)) : sep)\n const withTrail = node.trailing === undefined\n ? rep\n : b.Sequence(rep, b.Optional(toDiagramNode(b, node.sep)))\n return node.min === 0 ? b.Optional(withTrail) : withTrail\n }\n case 'not': return b.Sequence(b.Comment('not'), toDiagramNode(b, node.item))\n case 'peek': return b.Sequence(b.Comment('peek'), toDiagramNode(b, node.item))\n }\n}\n\n/** One production rendered to a static SVG string. */\nexport type RailroadSvg = { name: string; svg: string }\n\n/**\n * Render each production to a self-contained **static SVG** string \u2014 no DOM and\n * no client-side script, so a diagram can be inlined straight into a docs page,\n * README, or any HTML. Pair each SVG with [`RAILROAD_CSS`](./railroad-lib) (scope\n * it to a container) to style the strokes and boxes.\n */\nexport function renderRailroadSvg(model: SpecModel): RailroadSvg[] {\n const b = builders()\n return model.productions.map((p) => ({\n name: p.name,\n svg: b.Diagram(toDiagramNode(b, p.expr)).toString(),\n }))\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\nfunction slug(name: string): string {\n return 'rule-' + name.replace(/[^\\w-]/g, '_')\n}\n\nexport type RailroadHtmlOptions = {\n /** Page `<title>` and top heading. Default: \"Grammar\". */\n title?: string\n /** Show the EBNF production text under each diagram. Default: true. */\n showEbnf?: boolean\n}\n\nconst PAGE_CSS = `\n /* The railroad SVGs ship a fixed light background, so the page commits to a\n light theme for a consistent look regardless of the viewer's OS setting. */\n body { font: 14px/1.5 system-ui, sans-serif; margin: 0; padding: 2rem 2.5rem;\n color: #1a1a1a; background: #fff; }\n h1 { font-size: 1.6rem; margin: 0 0 0.25rem; }\n .subtitle { color: #666; margin: 0 0 2rem; }\n .toc { columns: 3 12rem; margin: 0 0 2.5rem; padding: 1rem 1.25rem; background: #f6f4f1; border-radius: 8px; }\n .toc a { display: block; color: #0b6; text-decoration: none; font-family: monospace; padding: 1px 0; }\n .toc a:hover { text-decoration: underline; }\n .rule { margin: 0 0 2.75rem; padding-top: 0.5rem; border-top: 1px solid #eee; }\n .rule h2 { font-size: 1.1rem; font-family: monospace; margin: 0 0 0.75rem; }\n .rule h2 a { color: #bbb; text-decoration: none; font-weight: normal; }\n .rule h2 a:hover { color: #0b6; }\n .ebnf { margin: 0.5rem 0 0; padding: 0.5rem 0.75rem; background: #f6f4f1; border-radius: 6px;\n font-family: monospace; font-size: 12px; white-space: pre-wrap; overflow-x: auto; }\n .diagram { overflow-x: auto; }\n /* The vendored library sizes each shape as (chars * 8 + padding), which assumes\n an 8px glyph advance (0.5em at 16px). Its own 14px-bold CSS actually advances\n ~8.4px/char, so long terminals crowd the box edges. Drop the text to 13px\n (advance ~7.8px) to restore comfortable side padding, and nudge the baked\n baseline (y+4) down slightly so glyphs sit vertically centered in the shapes. */\n svg.railroad-diagram text { font-size: 13px; }\n svg.railroad-diagram text:not(.comment) { transform: translateY(0.75px); }\n`\n\n/** Render the spec model as a self-contained HTML page of railroad diagrams. */\nexport function renderRailroadHtml(model: SpecModel, options: RailroadHtmlOptions = {}): string {\n const title = options.title ?? 'Grammar'\n const showEbnf = options.showEbnf ?? true\n\n const toc = model.productions\n .map(p => `<a href=\"#${slug(p.name)}\">${escapeHtml(p.name)}</a>`)\n .join('\\n ')\n\n const sections = model.productions\n .map((p: Production) => {\n const ebnf = showEbnf\n ? `<div class=\"ebnf\">${escapeHtml(`${p.name} ::= ${renderExpr(p.expr) || '/* empty */'}`)}</div>`\n : ''\n return ` <section class=\"rule\" id=\"${slug(p.name)}\">\n <h2><a href=\"#${slug(p.name)}\">\u00A7</a> ${escapeHtml(p.name)}</h2>\n <div class=\"diagram\" data-rule=\"${escapeHtml(p.name)}\"></div>\n ${ebnf}\n </section>`\n })\n .join('\\n')\n\n // One DSL expression per rule, built into its container at load time.\n const builders = model.productions\n .map(p => ` { name: ${j(p.name)}, dsl: function(){ return Diagram(${toDsl(p.expr)}); } }`)\n .join(',\\n')\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(title)}</title>\n<style>\n${RAILROAD_CSS}\n${PAGE_CSS}\n</style>\n</head>\n<body>\n<h1>${escapeHtml(title)}</h1>\n<p class=\"subtitle\">Syntax diagrams generated from the parser grammar.</p>\n<nav class=\"toc\">\n ${toc}\n</nav>\n${sections}\n<script>\n${RAILROAD_JS}\n</script>\n<script>\n(function () {\n var rules = [\n${builders}\n ];\n rules.forEach(function (r) {\n var host = document.querySelector('.diagram[data-rule=' + CSS.escape(r.name) + ']');\n if (!host) return;\n try { r.dsl().addTo(host); }\n catch (e) { host.textContent = 'diagram error: ' + e.message; }\n });\n})();\n</script>\n</body>\n</html>\n`\n}\n", "/**\n * `parseman/spec` \u2014 generate a formal grammar specification directly from a\n * Pars\u00E9man `rules()` grammar.\n *\n * Because the emitter walks the SAME `_def` combinator tree the interpreter and\n * macro compiler consume, a generated spec is a single source of truth: it\n * cannot disagree with what actually parses.\n *\n * import { toEBNF, toRailroadHtml } from 'parseman/spec'\n *\n * const grammar = rules(g => ({ ... })) // your grammar\n * const ebnf = toEBNF(grammar) // EBNF text\n * const html = toRailroadHtml(grammar) // self-contained syntax diagrams\n *\n * Scope: syntax only, not semantics. See docs/proposals/grammar-spec-generation.md.\n */\nimport { buildSpecModel } from './model.ts'\nimport type { GrammarInput, SpecModel, SpecOptions } from './model.ts'\nimport { renderEBNF } from './ebnf.ts'\nimport { renderRailroadHtml, renderRailroadSvg } from './railroad.ts'\nimport type { RailroadHtmlOptions } from './railroad.ts'\n\nexport { buildSpecModel } from './model.ts'\nexport type { GrammarInput, SpecModel, SpecOptions, SpecNode, Production } from './model.ts'\nexport { renderEBNF, renderExpr } from './ebnf.ts'\nexport { renderRailroadHtml, renderRailroadSvg } from './railroad.ts'\nexport type { RailroadHtmlOptions, RailroadSvg } from './railroad.ts'\nexport { RAILROAD_CSS } from './railroad-lib.ts'\n\n/** Generate W3C-style EBNF text (one production per named rule). */\nexport function toEBNF(grammar: GrammarInput, options?: SpecOptions): string {\n return renderEBNF(buildSpecModel(grammar, options))\n}\n\n/**\n * Generate a self-contained HTML page of SVG railroad (syntax) diagrams \u2014 one\n * per production \u2014 with an EBNF caption under each. No external dependencies.\n */\nexport function toRailroadHtml(\n grammar: GrammarInput,\n options?: SpecOptions & RailroadHtmlOptions,\n): string {\n const model: SpecModel = buildSpecModel(grammar, options)\n return renderRailroadHtml(model, options)\n}\n\n/**\n * Render each production to a static, self-contained SVG string \u2014 one per named\n * rule \u2014 ready to inline in a docs page, README, or any HTML (no client script).\n * Style with the exported `RAILROAD_CSS`, scoped to whatever wraps the SVGs.\n */\nexport function toRailroadSvg(grammar: GrammarInput, options?: SpecOptions): ReturnType<typeof renderRailroadSvg> {\n return renderRailroadSvg(buildSpecModel(grammar, options))\n}\n"],
5
- "mappings": ";AAiBA,SAAS,gBAAgB,GAAwB,SAAmE;AAClH,MAAI,YAAY,OAAW,QAAO;AAClC,QAAM,OAAQ,EAAwC;AACtD,SAAO,SAAS,SAAY,SAAY,QAAQ,IAAI;AACtD;AAEO,SAAS,MAAM,GAAa,GAAuB;AACxD,MAAI,EAAE,SAAS,SAAS,EAAE,SAAS,MAAO,QAAO,EAAE,MAAM,MAAM;AAC/D,MAAI,EAAE,SAAS,QAAS,QAAO;AAC/B,MAAI,EAAE,SAAS,QAAS,QAAO;AAC/B,SAAO,EAAE,MAAM,UAAU,QAAQ,YAAY,CAAC,GAAG,EAAE,QAAQ,GAAG,EAAE,MAAM,CAAC,EAAE;AAC3E;AAEO,SAAS,WAAW,GAAa,GAAsB;AAC5D,MAAI,EAAE,SAAS,SAAS,EAAE,SAAS,MAAO,QAAO;AACjD,MAAI,EAAE,SAAS,WAAW,EAAE,SAAS,QAAS,QAAO;AACrD,aAAW,MAAM,EAAE,QAAQ;AACzB,eAAW,MAAM,EAAE,QAAQ;AACzB,UAAI,GAAG,MAAM,GAAG,MAAM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AQ,EACzF,KAAK,KAAK;AAEb,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,SAKA,WAAW,KAAK,CAAC;AAAA;AAAA,EAExB,YAAY;AAAA,EACZ,QAAQ;AAAA;AAAA;AAAA;AAAA,MAIJ,WAAW,KAAK,CAAC;AAAA;AAAA;AAAA,MAGjB,GAAG;AAAA;AAAA,EAEP,QAAQ;AAAA;AAAA,EAER,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA,EAKXA,SAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaV;;;ACjOO,SAAS,OAAO,SAAuB,SAA+B;AAC3E,SAAO,WAAW,eAAe,SAAS,OAAO,CAAC;AACpD;AAMO,SAAS,eACd,SACA,SACQ;AACR,QAAM,QAAmB,eAAe,SAAS,OAAO;AACxD,SAAO,mBAAmB,OAAO,OAAO;AAC1C;AAOO,SAAS,cAAc,SAAuB,SAA6D;AAChH,SAAO,kBAAkB,eAAe,SAAS,OAAO,CAAC;AAC3D;",
6
- "names": ["leaf", "trivia", "parser", "parser", "deriveExpected", "label", "fast", "tr", "trivia", "parser", "j", "parse", "inRanges", "span", "result", "failAt", "trivia", "skip", "leaf", "quote", "parser", "parser", "parser", "fn", "children", "span", "rawChildren", "triviaLog", "state", "rules", "ruleNameOf", "node", "node", "builders"]
3
+ "sources": ["../../src/combinators/first-set.ts", "../../src/combinators/trivia-boundary.ts", "../../src/combinators/ref.ts", "../../src/compiler/value-usage.ts", "../../src/line-index.ts", "../../src/cst/capture-buffer.ts", "../../src/parse-context.ts", "../../src/regex/classes.ts", "../../src/cst/trivia-charscan.ts", "../../src/cst/trivia-kinds.ts", "../../src/cst/root-trivia-scope.ts", "../../src/combinators/grammar.ts", "../../src/cst/reflection-symbols.ts", "../../src/cst/reflection.ts", "../../src/cst/reflection-attach.ts", "../../src/combinators/parser.ts", "../../src/combinators/probe.ts", "../../src/regex/first-set.ts", "../../src/combinators/regex.ts", "../../src/combinators/literal.ts", "../../src/combinators/case-fold.ts", "../../src/combinators/keywords.ts", "../../src/combinators/trivia-skip.ts", "../../src/recovery/scan.ts", "../../src/combinators/adjacency.ts", "../../src/combinators/sequence.ts", "../../src/combinators/expect.ts", "../../src/combinators/choice.ts", "../../src/combinators/dispatch.ts", "../../src/combinators/attempt.ts", "../../src/combinators/repeat.ts", "../../src/combinators/not.ts", "../../src/combinators/peek.ts", "../../src/compiler/degradation.ts", "../../src/compiler/build-arity.ts", "../../src/compiler/fields.ts", "../../src/combinators/node.ts", "../../src/combinators/map.ts", "../../src/combinators/token.ts", "../../src/combinators/scanTo.ts", "../../src/combinators/withCtx.ts", "../../src/compiler/ir-serialize.ts", "../../src/table/ops.ts", "../../src/table/scan-shapes.ts", "../../src/table/assemble.ts", "../../src/analysis/duplication.ts", "../../src/compiler/linker.ts", "../../src/spec/model.ts", "../../src/spec/ebnf.ts", "../../src/spec/railroad-lib.ts", "../../src/spec/railroad.ts", "../../src/spec/index.ts"],
4
+ "mappings": ";AAiBA,SAAS,gBAAgB,GAAwB,SAAmE;AAClH,MAAI,YAAY,OAAW,QAAO;AAClC,QAAM,OAAQ,EAAwC;AACtD,SAAO,SAAS,SAAY,SAAY,QAAQ,IAAI;AACtD;AAEO,SAAS,MAAM,GAAa,GAAuB;AACxD,MAAI,EAAE,SAAS,SAAS,EAAE,SAAS,MAAO,QAAO,EAAE,MAAM,MAAM;AAC/D,MAAI,EAAE,SAAS,QAAS,QAAO;AAC/B,MAAI,EAAE,SAAS,QAAS,QAAO;AAC/B,SAAO,EAAE,MAAM,UAAU,QAAQ,YAAY,CAAC,GAAG,EAAE,QAAQ,GAAG,EAAE,MAAM,CAAC,EAAE;AAC3E;AAEO,SAAS,WAAW,GAAa,GAAsB;AAC5D,MAAI,EAAE,SAAS,SAAS,EAAE,SAAS,MAAO,QAAO;AACjD,MAAI,EAAE,SAAS,WAAW,EAAE,SAAS,QAAS,QAAO;AACrD,aAAW,MAAM,EAAE,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AAQ,WAAW,EAAE,IAAI,KAAK,aAAa,EAAE,CAAC,WACvF;AACJ,WAAO,+BAA+B,KAAK,EAAE,IAAI,CAAC;AAAA,oBACpC,KAAK,EAAE,IAAI,CAAC,cAAW,WAAW,EAAE,IAAI,CAAC;AAAA,sCACvB,WAAW,EAAE,IAAI,CAAC;AAAA,MAClD,IAAI;AAAA;AAAA,EAEN,CAAC,EACA,KAAK,IAAI;AAGZ,QAAMC,YAAW,MAAM,YACpB,IAAI,OAAK,aAAa,EAAE,EAAE,IAAI,CAAC,qCAAqC,MAAM,EAAE,IAAI,CAAC,QAAQ,EACzF,KAAK,KAAK;AAEb,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,SAKA,WAAW,KAAK,CAAC;AAAA;AAAA,EAExB,YAAY;AAAA,EACZ,QAAQ;AAAA;AAAA;AAAA;AAAA,MAIJ,WAAW,KAAK,CAAC;AAAA;AAAA;AAAA,MAGjB,GAAG;AAAA;AAAA,EAEP,QAAQ;AAAA;AAAA,EAER,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA,EAKXA,SAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaV;;;ACjOO,SAAS,OAAO,SAAuB,SAA+B;AAC3E,SAAO,WAAW,eAAe,SAAS,OAAO,CAAC;AACpD;AAMO,SAAS,eACd,SACA,SACQ;AACR,QAAM,QAAmB,eAAe,SAAS,OAAO;AACxD,SAAO,mBAAmB,OAAO,OAAO;AAC1C;AAOO,SAAS,cAAc,SAAuB,SAA6D;AAChH,SAAO,kBAAkB,eAAe,SAAS,OAAO,CAAC;AAC3D;",
5
+ "names": ["leaf", "rawEntry", "trivia", "trivia", "parser", "parser", "EMPTY", "node", "inRanges", "firstSet", "span", "firstSet", "parse", "firstSet", "fast", "tr", "trivia", "parser", "inRanges", "j", "result", "deriveExpected", "label", "j", "parser", "parser", "parser", "failAt", "quote", "rawEntry", "trivia", "skip", "leaf", "fn", "META", "EMPTY_TL", "children", "span", "rawChildren", "triviaLog", "state", "rules", "ruleNameOf", "node", "node", "builders"]
7
6
  }