solve-engine 2.23.0 → 2.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +82 -32
  2. package/dist/{Configuration-BGQn-cJ8.d.cts → Configuration-DnzYPmoK.d.cts} +33 -0
  3. package/dist/{Configuration-BGQn-cJ8.d.ts → Configuration-DnzYPmoK.d.ts} +33 -0
  4. package/dist/{EngineError-DTk7I7hZ.d.cts → EngineError-D1kXsjIj.d.cts} +4 -0
  5. package/dist/{EngineError-DTk7I7hZ.d.ts → EngineError-D1kXsjIj.d.ts} +4 -0
  6. package/dist/{PackageCompatibility-BGXSFuL9.d.ts → PackageCompatibility-Bq82y0ZN.d.ts} +1 -1
  7. package/dist/{PackageCompatibility-BZCqaTOO.d.cts → PackageCompatibility-CeAPVHZr.d.cts} +1 -1
  8. package/dist/{PackageRegistry-rMGnTh7W.d.cts → PackageRegistry-B9-7fJGH.d.cts} +16 -11
  9. package/dist/{PackageRegistry-BRoVOYzg.d.ts → PackageRegistry-CDEgfhT_.d.ts} +16 -11
  10. package/dist/{Parselet-Bkbp9CKD.d.cts → Parselet-4oH5OuRt.d.cts} +1 -1
  11. package/dist/{Parselet-B-WyUtX4.d.ts → Parselet-BwDqKFfK.d.ts} +1 -1
  12. package/dist/{ScopeManager-gB9UengK.d.ts → ScopeManager-BQBhlDAu.d.ts} +38 -7
  13. package/dist/{ScopeManager-bCYewWVt.d.cts → ScopeManager-DrXB3Nvm.d.cts} +38 -7
  14. package/dist/{VMCheckpoints-DGar9Yg8.d.cts → VMCheckpoints-BK32PTl2.d.cts} +2 -2
  15. package/dist/{VMCheckpoints-BDRY1Kx8.d.ts → VMCheckpoints-C5jC92o3.d.ts} +2 -2
  16. package/dist/{Value-DCTqTSeP.d.cts → Value-Ds3Gy07C.d.cts} +1 -1
  17. package/dist/{Value-DCTqTSeP.d.ts → Value-Ds3Gy07C.d.ts} +1 -1
  18. package/dist/{WorkerError-DpZgKRks.d.ts → WorkerError-CVQbs6_D.d.ts} +1 -1
  19. package/dist/{WorkerError-DGBNM3gA.d.cts → WorkerError-DaNWQFp1.d.cts} +1 -1
  20. package/dist/chunk-2BXNZM3G.js +2 -0
  21. package/dist/chunk-2BXNZM3G.js.map +1 -0
  22. package/dist/chunk-2JSNWYYA.cjs +3 -0
  23. package/dist/chunk-2JSNWYYA.cjs.map +1 -0
  24. package/dist/{chunk-J7ABVGZH.cjs → chunk-2VE4OW4A.cjs} +2 -2
  25. package/dist/{chunk-J7ABVGZH.cjs.map → chunk-2VE4OW4A.cjs.map} +1 -1
  26. package/dist/{chunk-HMC7FJO7.js → chunk-3SHWTGTP.js} +2 -2
  27. package/dist/{chunk-HMC7FJO7.js.map → chunk-3SHWTGTP.js.map} +1 -1
  28. package/dist/{chunk-EN3CDYOS.cjs → chunk-5GL4SAVH.cjs} +2 -2
  29. package/dist/{chunk-EN3CDYOS.cjs.map → chunk-5GL4SAVH.cjs.map} +1 -1
  30. package/dist/{chunk-SGIDBZ4T.cjs → chunk-72N3ZRVE.cjs} +2 -2
  31. package/dist/chunk-72N3ZRVE.cjs.map +1 -0
  32. package/dist/{chunk-CHSO3DCS.js → chunk-7EP36NXE.js} +3 -3
  33. package/dist/{chunk-CHSO3DCS.js.map → chunk-7EP36NXE.js.map} +1 -1
  34. package/dist/chunk-A4JV7HRB.js +3 -0
  35. package/dist/chunk-A4JV7HRB.js.map +1 -0
  36. package/dist/chunk-AUOE7MFI.cjs +2 -0
  37. package/dist/chunk-AUOE7MFI.cjs.map +1 -0
  38. package/dist/chunk-BDF4VCQX.js +3 -0
  39. package/dist/chunk-BDF4VCQX.js.map +1 -0
  40. package/dist/{chunk-3SSMOVWB.cjs → chunk-CDNJZBM3.cjs} +2 -2
  41. package/dist/{chunk-3SSMOVWB.cjs.map → chunk-CDNJZBM3.cjs.map} +1 -1
  42. package/dist/{chunk-YAONCEAW.cjs → chunk-CMZSK6FY.cjs} +3 -3
  43. package/dist/{chunk-YAONCEAW.cjs.map → chunk-CMZSK6FY.cjs.map} +1 -1
  44. package/dist/chunk-D2Q2VFJ6.js +2 -0
  45. package/dist/chunk-D2Q2VFJ6.js.map +1 -0
  46. package/dist/{chunk-75JLWK4L.cjs → chunk-DA7M6H63.cjs} +2 -2
  47. package/dist/{chunk-75JLWK4L.cjs.map → chunk-DA7M6H63.cjs.map} +1 -1
  48. package/dist/chunk-ELQQKZN3.cjs +3 -0
  49. package/dist/{chunk-PIZQIQVM.js.map → chunk-ELQQKZN3.cjs.map} +1 -1
  50. package/dist/chunk-F7QIBC4B.cjs +3 -0
  51. package/dist/chunk-F7QIBC4B.cjs.map +1 -0
  52. package/dist/chunk-GP4H5OIT.js +3 -0
  53. package/dist/chunk-GP4H5OIT.js.map +1 -0
  54. package/dist/chunk-HQ7BKXG7.js +2 -0
  55. package/dist/chunk-HQ7BKXG7.js.map +1 -0
  56. package/dist/{chunk-KRXO3MOW.cjs → chunk-IHAZL4EF.cjs} +2 -2
  57. package/dist/chunk-IHAZL4EF.cjs.map +1 -0
  58. package/dist/{chunk-7E7NXKQ5.js → chunk-IJHL3LMH.js} +2 -2
  59. package/dist/chunk-IJHL3LMH.js.map +1 -0
  60. package/dist/{chunk-3GR46UOX.js → chunk-IPSOWFCA.js} +2 -2
  61. package/dist/{chunk-3GR46UOX.js.map → chunk-IPSOWFCA.js.map} +1 -1
  62. package/dist/chunk-LM6ZQUEU.js +2 -0
  63. package/dist/chunk-LM6ZQUEU.js.map +1 -0
  64. package/dist/{chunk-N37PUZJR.cjs → chunk-LTJV3VJE.cjs} +2 -2
  65. package/dist/{chunk-N37PUZJR.cjs.map → chunk-LTJV3VJE.cjs.map} +1 -1
  66. package/dist/chunk-MWWAKZOD.cjs +3 -0
  67. package/dist/chunk-MWWAKZOD.cjs.map +1 -0
  68. package/dist/chunk-NUF66H57.js +5 -0
  69. package/dist/chunk-NUF66H57.js.map +1 -0
  70. package/dist/{chunk-MRRMIBHE.js → chunk-OMHRBKAT.js} +2 -2
  71. package/dist/{chunk-MRRMIBHE.js.map → chunk-OMHRBKAT.js.map} +1 -1
  72. package/dist/{chunk-4ETS224G.js → chunk-PTQCHMYA.js} +2 -2
  73. package/dist/{chunk-4ETS224G.js.map → chunk-PTQCHMYA.js.map} +1 -1
  74. package/dist/{chunk-4DJJIUQF.js → chunk-PWWQZFAE.js} +2 -2
  75. package/dist/chunk-PWWQZFAE.js.map +1 -0
  76. package/dist/chunk-RE6AIU6Y.js +3 -0
  77. package/dist/chunk-RE6AIU6Y.js.map +1 -0
  78. package/dist/chunk-RECRD45C.cjs +5 -0
  79. package/dist/chunk-RECRD45C.cjs.map +1 -0
  80. package/dist/{chunk-O3BDXOQJ.js → chunk-RENO2AWO.js} +2 -2
  81. package/dist/{chunk-O3BDXOQJ.js.map → chunk-RENO2AWO.js.map} +1 -1
  82. package/dist/chunk-RMCN5WFO.cjs +2 -0
  83. package/dist/chunk-RMCN5WFO.cjs.map +1 -0
  84. package/dist/{chunk-TL545PXW.cjs → chunk-RN3ISTM3.cjs} +2 -2
  85. package/dist/{chunk-TL545PXW.cjs.map → chunk-RN3ISTM3.cjs.map} +1 -1
  86. package/dist/{chunk-JYLNQOPU.cjs → chunk-S46R5QZP.cjs} +2 -2
  87. package/dist/{chunk-JYLNQOPU.cjs.map → chunk-S46R5QZP.cjs.map} +1 -1
  88. package/dist/{chunk-USQ4KL6S.cjs → chunk-UPH22K2T.cjs} +2 -2
  89. package/dist/chunk-UPH22K2T.cjs.map +1 -0
  90. package/dist/{chunk-KEA5HRL3.js → chunk-UXR7JIPX.js} +2 -2
  91. package/dist/{chunk-KEA5HRL3.js.map → chunk-UXR7JIPX.js.map} +1 -1
  92. package/dist/chunk-UY3ID6JF.cjs +2 -0
  93. package/dist/chunk-UY3ID6JF.cjs.map +1 -0
  94. package/dist/{chunk-JVMINMAB.js → chunk-WFOQRPA6.js} +2 -2
  95. package/dist/{chunk-JVMINMAB.js.map → chunk-WFOQRPA6.js.map} +1 -1
  96. package/dist/{chunk-AF7HQN6I.js → chunk-XFJABR3B.js} +2 -2
  97. package/dist/chunk-XFJABR3B.js.map +1 -0
  98. package/dist/{chunk-LNZNJSRW.cjs → chunk-ZVPZQ66D.cjs} +2 -2
  99. package/dist/chunk-ZVPZQ66D.cjs.map +1 -0
  100. package/dist/constants.cjs +1 -1
  101. package/dist/constants.d.cts +1 -1
  102. package/dist/constants.d.ts +1 -1
  103. package/dist/constants.js +1 -1
  104. package/dist/engine.cjs +1 -1
  105. package/dist/engine.d.cts +9 -9
  106. package/dist/engine.d.ts +9 -9
  107. package/dist/engine.js +1 -1
  108. package/dist/errors.cjs +1 -1
  109. package/dist/errors.d.cts +3 -3
  110. package/dist/errors.d.ts +3 -3
  111. package/dist/errors.js +1 -1
  112. package/dist/format.cjs +1 -1
  113. package/dist/format.d.cts +1 -1
  114. package/dist/format.d.ts +1 -1
  115. package/dist/format.js +1 -1
  116. package/dist/index.cjs +1 -1
  117. package/dist/index.cjs.map +1 -1
  118. package/dist/index.d.cts +11 -9
  119. package/dist/index.d.ts +11 -9
  120. package/dist/index.js +1 -1
  121. package/dist/index.js.map +1 -1
  122. package/dist/language.d.cts +8 -8
  123. package/dist/language.d.ts +8 -8
  124. package/dist/lexer.cjs +1 -1
  125. package/dist/lexer.js +1 -1
  126. package/dist/normalizer.cjs +1 -1
  127. package/dist/normalizer.d.cts +14 -8
  128. package/dist/normalizer.d.ts +14 -8
  129. package/dist/normalizer.js +1 -1
  130. package/dist/packages.cjs +1 -1
  131. package/dist/packages.d.cts +7 -7
  132. package/dist/packages.d.ts +7 -7
  133. package/dist/packages.js +1 -1
  134. package/dist/parser.cjs +1 -1
  135. package/dist/parser.d.cts +3 -3
  136. package/dist/parser.d.ts +3 -3
  137. package/dist/parser.js +1 -1
  138. package/dist/{pipeline-B4wf3M1h.d.cts → pipeline-69q2tsLE.d.cts} +1 -1
  139. package/dist/{pipeline-QIT4iD8f.d.ts → pipeline-DTqGLPsV.d.ts} +1 -1
  140. package/dist/resolvers.cjs +1 -1
  141. package/dist/resolvers.d.cts +18 -2
  142. package/dist/resolvers.d.ts +18 -2
  143. package/dist/resolvers.js +1 -1
  144. package/dist/testing.cjs +2 -2
  145. package/dist/testing.d.cts +8 -8
  146. package/dist/testing.d.ts +8 -8
  147. package/dist/testing.js +1 -1
  148. package/dist/uom.cjs +1 -1
  149. package/dist/uom.d.cts +1 -1
  150. package/dist/uom.d.ts +1 -1
  151. package/dist/uom.js +1 -1
  152. package/dist/vm.cjs +1 -1
  153. package/dist/vm.d.cts +7 -7
  154. package/dist/vm.d.ts +7 -7
  155. package/dist/vm.js +1 -1
  156. package/dist/worker.cjs +2 -2
  157. package/dist/worker.cjs.map +1 -1
  158. package/dist/worker.d.cts +31 -22
  159. package/dist/worker.d.ts +31 -22
  160. package/dist/worker.js +1 -1
  161. package/dist/worker.js.map +1 -1
  162. package/package.json +1 -1
  163. package/dist/chunk-42JXN3BH.js +0 -5
  164. package/dist/chunk-42JXN3BH.js.map +0 -1
  165. package/dist/chunk-4DJJIUQF.js.map +0 -1
  166. package/dist/chunk-6YM67DWH.cjs +0 -3
  167. package/dist/chunk-6YM67DWH.cjs.map +0 -1
  168. package/dist/chunk-7E7NXKQ5.js.map +0 -1
  169. package/dist/chunk-7SZBEE5R.cjs +0 -2
  170. package/dist/chunk-7SZBEE5R.cjs.map +0 -1
  171. package/dist/chunk-A5M4QZIK.js +0 -2
  172. package/dist/chunk-A5M4QZIK.js.map +0 -1
  173. package/dist/chunk-AF7HQN6I.js.map +0 -1
  174. package/dist/chunk-ALY4ZMYO.js +0 -2
  175. package/dist/chunk-ALY4ZMYO.js.map +0 -1
  176. package/dist/chunk-BRJ4RT5U.js +0 -2
  177. package/dist/chunk-BRJ4RT5U.js.map +0 -1
  178. package/dist/chunk-CO2BI6WL.cjs +0 -3
  179. package/dist/chunk-CO2BI6WL.cjs.map +0 -1
  180. package/dist/chunk-EQDT42JG.js +0 -3
  181. package/dist/chunk-EQDT42JG.js.map +0 -1
  182. package/dist/chunk-FMMT5C5H.cjs +0 -3
  183. package/dist/chunk-FMMT5C5H.cjs.map +0 -1
  184. package/dist/chunk-FP6Z6PYR.js +0 -2
  185. package/dist/chunk-FP6Z6PYR.js.map +0 -1
  186. package/dist/chunk-H3JXNH7X.cjs +0 -3
  187. package/dist/chunk-H3JXNH7X.cjs.map +0 -1
  188. package/dist/chunk-HZOLIL5T.js +0 -3
  189. package/dist/chunk-HZOLIL5T.js.map +0 -1
  190. package/dist/chunk-KRXO3MOW.cjs.map +0 -1
  191. package/dist/chunk-KVLJDOZ7.cjs +0 -5
  192. package/dist/chunk-KVLJDOZ7.cjs.map +0 -1
  193. package/dist/chunk-LNZNJSRW.cjs.map +0 -1
  194. package/dist/chunk-PIZQIQVM.js +0 -3
  195. package/dist/chunk-QTSDIDAS.js +0 -3
  196. package/dist/chunk-QTSDIDAS.js.map +0 -1
  197. package/dist/chunk-SGIDBZ4T.cjs.map +0 -1
  198. package/dist/chunk-UNKSCVIL.cjs +0 -2
  199. package/dist/chunk-UNKSCVIL.cjs.map +0 -1
  200. package/dist/chunk-USQ4KL6S.cjs.map +0 -1
  201. package/dist/chunk-XDXIPVZB.cjs +0 -2
  202. package/dist/chunk-XDXIPVZB.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","ErrorFactory","op","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","localeCode","withoutSuffix","digits","stripLocaleGrouping","separator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AAoBF,EAAeD,CAAU,CAAA,CAEhD,GAAI,CAACH,CAAAA,CAAY,IAAA,CAAKK,CAAM,CAAA,CAAG,CAC9B,IAAME,CAAAA,CAAYH,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,GAAA,CAAMA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,IAAMA,CAAAA,CAC1F,MAAMtB,mBAAAA,CAAa,OAAA,CAClB,wBAAA,CACA,CAAA,CAAA,EAAIoB,CAAG,CAAA,0BAAA,EAA6BK,CAAS,CAAA,4BAAA,EAA+BJ,CAAU,CAAA,0DAAA,CAAA,CACtF,CAAE,IAAAD,CAAAA,CAAK,UAAA,CAAAC,CAAAA,CAAY,SAAA,CAAAI,CAAU,CAC9B,CACD,CACA,OAAOF,CACR,CASA,SAASC,CAAAA,CAAoBE,EAAcL,CAAAA,CAA4B,CACtE,IAAMM,CAAAA,CAAqBC,mBAAAA,CAAUP,CAAU,EAAE,OAAA,CAAQ,kBAAA,CACzD,OAAOM,CAAAA,CAAqBD,CAAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-EN3CDYOS.cjs","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when declaring an infix parselet in a\n * package's `infixParselets`. See the built-in packages for examples of\n * picking an appropriate level (e.g. arithmetic `+`/`-` use `Sum`, `*`/`/`\n * use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nconst BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/**\n\t * The per-engine `plugin function name -> registry index` map, wired in by\n\t * the engine so {@link emitPluginCall} can resolve a name at emit time. The\n\t * same object reference is shared with every builder in an engine (the pool\n\t * and each ad-hoc nested-body builder), and the engine populates it as\n\t * packages register, so a parselet never sees the numeric index.\n\t */\n\tconstructor(private readonly pluginFunctionIndex?: ReadonlyMap<string, number>) {}\n\n\t/** The name->index map, so a nested-body builder inherits the same resolution. */\n\tget pluginIndexMap(): ReadonlyMap<string, number> | undefined {\n\t\treturn this.pluginFunctionIndex;\n\t}\n\n\t/**\n\t * Emit a plugin-function call by NAME. The engine assigns each registered\n\t * `pluginFunctions` entry an index at registration; this resolves the name to\n\t * that index and emits `CALL_PLUGIN` + index + argCount. Package authors emit\n\t * through this rather than a hand-allocated index.\n\t */\n\temitPluginCall(name: string, argCount: number): void {\n\t\tconst index = this.pluginFunctionIndex?.get(name);\n\t\tif (index === undefined) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"UNKNOWN_PLUGIN_FUNCTION\",\n\t\t\t\t`No registered plugin function named \"${name}\". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,\n\t\t\t\t{ functionName: name },\n\t\t\t);\n\t\t}\n\t\t// One byte covers the first 256 plugin functions; beyond that, the\n\t\t// wide opcode carries a two-byte little-endian index. Emitting the\n\t\t// narrow form whenever it fits keeps existing bytecode and snapshots\n\t\t// byte-for-byte unchanged. The index cannot exceed 65535 because the\n\t\t// allocator (allocatePluginFunctionIndex) caps it, but guard anyway so\n\t\t// a stray index is a clear error rather than a silently truncated byte.\n\t\tif (index > 0xffff) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\t\t\t\t`Plugin-function index ${index} exceeds the two-byte bytecode limit (65535).`,\n\t\t\t\t{ index },\n\t\t\t);\n\t\t}\n\t\tif (index <= 0xff) {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN);\n\t\t\tthis.emitIndex(index);\n\t\t} else {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN_WIDE);\n\t\t\tthis.emitIndex(index & 0xff); // low byte\n\t\t\tthis.emitIndex((index >> 8) & 0xff); // high byte\n\t\t}\n\t\tthis.emitIndex(argCount);\n\t}\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN || op === OpCode.CALL_PLUGIN_WIDE) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: appends `n` to the program's constant pool and\n\t * writes its index into the opcode stream (read back by the VM as e.g.\n\t * `PUSH_NUMBER <idx>`).\n\t *\n\t * Numeric constants are NOT deduplicated (unlike {@link emitString})\n\t * every call appends a new entry, so an expression with more than\n\t * {@link MAX_CONSTANT_POOL_INDEX}+1 distinct numeric-literal occurrences\n\t * throws rather than silently wrapping the index (see\n\t * `MAX_CONSTANT_POOL_INDEX`'s doc for what that would otherwise do).\n\t *\n\t * @throws If the constant pool would exceed 256 entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst idx = this.numbers.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.numbers.push(n);\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(b);\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tthis.opcodes[position] = target;\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tthis.numbers.length = 0;\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
1
+ {"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","ErrorFactory","op","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","localeCode","withoutSuffix","digits","stripLocaleGrouping","separator","text","thousandsSeparator","getLocale"],"mappings":"uKAWO,IAAMA,CAAAA,CAAe,CAC1B,MAAA,CAAQ,CAAA,CACR,WAAY,EAAA,CACZ,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CAaZ,WAAA,CAAa,GAab,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CACZ,UAAA,CAAY,EAAA,CACZ,YAAa,EAAA,CACb,KAAA,CAAO,EAAA,CACP,GAAA,CAAK,EAAA,CACL,OAAA,CAAS,GAMT,WAAA,CAAa,EAAA,CAIb,QAAA,CAAU,EAAA,CACV,MAAA,CAAQ,EAAA,CACR,QAAS,EAAA,CACT,IAAA,CAAM,EACR,EAiDA,IAAMC,CAAAA,CAA2C,CAE/C,CAACC,mBAAAA,CAAW,IAAI,EAAOF,CAAAA,CAAa,GAAA,CACpC,CAACE,mBAAAA,CAAW,KAAK,EAAMF,CAAAA,CAAa,GAAA,CACpC,CAACE,oBAAW,IAAI,EAAOF,CAAAA,CAAa,OAAA,CACpC,CAACE,mBAAAA,CAAW,KAAK,EAAMF,CAAAA,CAAa,OAAA,CACpC,CAACE,mBAAAA,CAAW,GAAG,EAAQF,CAAAA,CAAa,OAAA,CAGpC,CAACE,mBAAAA,CAAW,KAAK,EAAMF,EAAa,QAAA,CAOpC,CAACE,mBAAAA,CAAW,MAAM,EAAKF,CAAAA,CAAa,UACpC,CAACE,mBAAAA,CAAW,OAAO,EAAIF,CAAAA,CAAa,UAAA,CACpC,CAACE,mBAAAA,CAAW,OAAO,EAAIF,CAAAA,CAAa,UAAA,CACpC,CAACE,oBAAW,MAAM,EAAKF,CAAAA,CAAa,KAAA,CACpC,CAACE,mBAAAA,CAAW,MAAM,EAAKF,CAAAA,CAAa,KAAA,CACpC,CAACE,mBAAAA,CAAW,OAAO,EAAIF,CAAAA,CAAa,KAAA,CAGpC,CAACE,mBAAAA,CAAW,O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MAAM,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAChCE,CAAAA,CAAoBF,EAAeD,CAAU,CAAA,CAEhD,GAAI,CAACH,CAAAA,CAAY,IAAA,CAAKK,CAAM,CAAA,CAAG,CAC9B,IAAME,CAAAA,CAAYH,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,GAAA,CAAMA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,IAAMA,CAAAA,CAC1F,MAAMtB,mBAAAA,CAAa,OAAA,CAClB,wBAAA,CACA,CAAA,CAAA,EAAIoB,CAAG,CAAA,0BAAA,EAA6BK,CAAS,CAAA,4BAAA,EAA+BJ,CAAU,CAAA,0DAAA,CAAA,CACtF,CAAE,IAAAD,CAAAA,CAAK,UAAA,CAAAC,CAAAA,CAAY,SAAA,CAAAI,CAAU,CAC9B,CACD,CACA,OAAOF,CACR,CASA,SAASC,CAAAA,CAAoBE,EAAcL,CAAAA,CAA4B,CACtE,IAAMM,CAAAA,CAAqBC,mBAAAA,CAAUP,CAAU,EAAE,OAAA,CAAQ,kBAAA,CACzD,OAAOM,CAAAA,CAAqBD,CAAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-5GL4SAVH.cjs","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when declaring an infix parselet in a\n * package's `infixParselets`. See the built-in packages for examples of\n * picking an appropriate level (e.g. arithmetic `+`/`-` use `Sum`, `*`/`/`\n * use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nconst BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/**\n\t * The per-engine `plugin function name -> registry index` map, wired in by\n\t * the engine so {@link emitPluginCall} can resolve a name at emit time. The\n\t * same object reference is shared with every builder in an engine (the pool\n\t * and each ad-hoc nested-body builder), and the engine populates it as\n\t * packages register, so a parselet never sees the numeric index.\n\t */\n\tconstructor(private readonly pluginFunctionIndex?: ReadonlyMap<string, number>) {}\n\n\t/** The name->index map, so a nested-body builder inherits the same resolution. */\n\tget pluginIndexMap(): ReadonlyMap<string, number> | undefined {\n\t\treturn this.pluginFunctionIndex;\n\t}\n\n\t/**\n\t * Emit a plugin-function call by NAME. The engine assigns each registered\n\t * `pluginFunctions` entry an index at registration; this resolves the name to\n\t * that index and emits `CALL_PLUGIN` + index + argCount. Package authors emit\n\t * through this rather than a hand-allocated index.\n\t */\n\temitPluginCall(name: string, argCount: number): void {\n\t\tconst index = this.pluginFunctionIndex?.get(name);\n\t\tif (index === undefined) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"UNKNOWN_PLUGIN_FUNCTION\",\n\t\t\t\t`No registered plugin function named \"${name}\". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,\n\t\t\t\t{ functionName: name },\n\t\t\t);\n\t\t}\n\t\t// One byte covers the first 256 plugin functions; beyond that, the\n\t\t// wide opcode carries a two-byte little-endian index. Emitting the\n\t\t// narrow form whenever it fits keeps existing bytecode and snapshots\n\t\t// byte-for-byte unchanged. The index cannot exceed 65535 because the\n\t\t// allocator (allocatePluginFunctionIndex) caps it, but guard anyway so\n\t\t// a stray index is a clear error rather than a silently truncated byte.\n\t\tif (index > 0xffff) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\t\t\t\t`Plugin-function index ${index} exceeds the two-byte bytecode limit (65535).`,\n\t\t\t\t{ index },\n\t\t\t);\n\t\t}\n\t\tif (index <= 0xff) {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN);\n\t\t\tthis.emitIndex(index);\n\t\t} else {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN_WIDE);\n\t\t\tthis.emitIndex(index & 0xff); // low byte\n\t\t\tthis.emitIndex((index >> 8) & 0xff); // high byte\n\t\t}\n\t\tthis.emitIndex(argCount);\n\t}\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN || op === OpCode.CALL_PLUGIN_WIDE) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: appends `n` to the program's constant pool and\n\t * writes its index into the opcode stream (read back by the VM as e.g.\n\t * `PUSH_NUMBER <idx>`).\n\t *\n\t * Numeric constants are NOT deduplicated (unlike {@link emitString})\n\t * every call appends a new entry, so an expression with more than\n\t * {@link MAX_CONSTANT_POOL_INDEX}+1 distinct numeric-literal occurrences\n\t * throws rather than silently wrapping the index (see\n\t * `MAX_CONSTANT_POOL_INDEX`'s doc for what that would otherwise do).\n\t *\n\t * @throws If the constant pool would exceed 256 entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst idx = this.numbers.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.numbers.push(n);\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(b);\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tthis.opcodes[position] = target;\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tthis.numbers.length = 0;\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkUSQ4KL6S_cjs=require('./chunk-USQ4KL6S.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');var N=32,U=2;function x(a){return a.shape!==void 0?a.shape:a.startTokenTypes!==void 0?[{types:a.startTokenTypes}]:[]}var I=class{constructor(e){this.rules=e;let r=e.length,t=Math.max(1,Math.ceil(r/N));this.words=t,this.scratch=new Uint32Array(t);let s=e.map(x),n=0;for(let l of s)for(let c of l)for(let f of c.types??[])n=Math.max(n,chunk5IJD5L3O_cjs.c(f));this.typeRows=n+1;let i=0;for(let l of s)i=Math.max(i,l.length);i=Math.min(i,U),this.allRules=new Uint32Array(t);for(let l=0;l<r;l++)this.allRules[l/N|0]|=1<<l%N;let u=[];for(let l=0;l<i;l++)u.push(this.buildPlane(s,l,t));this.planes=u;}buildPlane(e,r,t){let s={byType:new Uint32Array(this.typeRows*t),typeAny:new Uint32Array(t),atEnd:new Uint32Array(t),typeHasValues:new Uint8Array(this.typeRows),byValue:new Map,valueAny:new Uint32Array(t)};for(let n=0;n<e.length;n++){let i=e[n][r],u=n/N|0,l=1<<n%N,c=i?.types;if(c===void 0)s.typeAny[u]|=l,s.atEnd[u]|=l;else for(let p of c)s.byType[chunk5IJD5L3O_cjs.c(p)*t+u]|=l;let f=i?.values;if(f===void 0)s.valueAny[u]|=l;else {for(let p of f){let h=p.toLowerCase(),o=s.byValue.get(h);o===void 0&&(o=new Uint32Array(t),s.byValue.set(h,o)),o[u]|=l;}if(c===void 0)s.typeHasValues.fill(1);else for(let p of c){let h=chunk5IJD5L3O_cjs.c(p);h<this.typeRows&&(s.typeHasValues[h]=1);}}}return s}get size(){return this.rules.length}get depth(){return this.planes.length}candidates(e,r){let t=this.words,s=this.scratch,n=this.planes,i=e.length;if(n.length===0)return s.set(this.allRules),s;for(let u=0;u<n.length;u++){let l=n[u],c=r+u;if(c>=i){if(u===0)s.set(l.atEnd);else for(let o=0;o<t;o++)s[o]&=l.atEnd[o];continue}let f=e[c],p=f.typeId,h=p>=0&&p<this.typeRows?p*t:-1;if(u===0)if(h>=0)for(let o=0;o<t;o++)s[o]=l.byType[h+o]|l.typeAny[o];else s.set(l.typeAny);else if(h>=0)for(let o=0;o<t;o++)s[o]&=l.byType[h+o]|l.typeAny[o];else for(let o=0;o<t;o++)s[o]&=l.typeAny[o];if(h>=0&&l.typeHasValues[p]===1){let o=f.value,R=B(o)?o.toLowerCase():o,g=l.byValue.get(R);for(let T=0;T<t;T++)s[T]&=(g===void 0?0:g[T])|l.valueAny[T];}if(C(s))return s}return s}};function C(a){for(let e=0;e<a.length;e++)if(a[e]!==0)return false;return true}function B(a){for(let e=0;e<a.length;e++){let r=a.charCodeAt(e);if(r>=65&&r<=90)return true}return false}var O={maxPasses:100,maxTokens:1e4,onFusion:()=>{},ignoreRuleIndex:false};function S(a,e,r){let t=r[0],s=r[r.length-1],n=new chunkUSQ4KL6S_cjs.a(a,chunk5IJD5L3O_cjs.c(a),e,e,t.offset,t.lineBreaks??0,t.line,t.col);return n.sourceEnd=s.sourceEnd??s.offset+s.text.length,n}function M(a,e){let r=e[e.length-1];r&&(a.sourceEnd=r.sourceEnd??r.offset+r.text.length);}var _=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],P=(()=>{let a=_.map(t=>chunk5IJD5L3O_cjs.c(t)),e=Math.max(...a)+1,r=new Uint8Array(e);for(let t of a)r[t]=1;return r})(),z=new Set;function D(a){a.shape!==void 0&&a.shape.length>0||a.startTokenTypes===void 0&&a.unshapedReason===void 0&&(z.has(a.name)||(z.add(a.name),console.warn(`[TokenNormalizer] Rule "${a.name}" declares no \`shape\`, so it is tried at every token of every line and slows down documents that never use it. Declare the tokens it can start at, e.g. shape: [{ types: ["IDENT"], values: ["myword"] }, { types: ["LPAREN"] }]. If it genuinely cannot be described that way, set \`unshapedReason\` to say why and this warning will stop.`)));}var L=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.ruleIndexCache=null;this.candidateBuffer=[];this.normalizeCalls=0;this.phraseTrie=new E;this.ruleShapesCache=null;this.options={...O,...e};}register(e){D(e),this.rules.push(e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}unregister(e){this.rules=this.rules.filter(r=>r.name!==e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}clear(){this.rules=[],this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null,this.phraseTrie=new E;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,r)=>r.priority-e.priority)),this.sortedRulesCache}getRuleIndex(){return this.ruleIndexCache===null&&(this.ruleIndexCache=new I(this.getSortedRules())),this.ruleIndexCache}rulesAt(e,r){let t=this.candidateBuffer;if(t.length=0,e===null){let n=this.rulesForTokenType(r);for(let i=0;i<n.length;i++)t.push(n[i]);return t}let s=this.getRuleIndex().rules;for(let n=0;n<e.length;n++){let i=e[n]>>>0,u=n*32;for(;i!==0;)(i&1)!==0&&t.push(s[u]),i>>>=1,u++;}return t}rulesForTokenType(e){let r=this.rulesByTokenType.get(e);return r===void 0&&(r=this.getSortedRules().filter(t=>t.startTokenTypes===void 0||t.startTokenTypes.includes(e)),this.rulesByTokenType.set(e,r)),r}get ruleCount(){return this.rules.length}getRuleShapes(){if(this.ruleShapesCache!==null)return this.ruleShapesCache;let e=this.getRuleIndex();return this.ruleShapesCache=this.getSortedRules().map(r=>{let t=x(r);return {name:r.name,priority:r.priority,shape:t,unshapedReason:r.unshapedReason,indexedSlots:Math.min(t.length,e.depth)}}),this.ruleShapesCache}getCandidateCounts(e){let r=this.getRuleIndex(),t=[];for(let s=0;s<e.length;s++){let n=r.candidates(e,s),i=0;for(let u=0;u<n.length;u++){let l=n[u]>>>0;for(;l!==0;)i+=l&1,l>>>=1;}t.push(i);}return t}addPhrase(e,r){this.phraseTrie.addPhrase(e,r);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,r){if(e.length===0)return e;let t=r??this.options.onFusion,s=this.options.maxPasses,n=this.options.maxTokens,i=this.normalizeCalls>0;i||(this.normalizeCalls=1);let u=i&&!this.options.ignoreRuleIndex,l=u?this.getRuleIndex():null,c=e,f=true,p=0;for(;f&&p<s;){f=false,p++;let h=null,o=0;for(;o<c.length;){let g=false,T=c[o].typeId;if(T>=P.length||P[T]===0){let m=this.phraseTrie.matchAt(c,o);if(m){let d=c.slice(o,o+m.consumed);h===null&&(h=c.slice(0,o));for(let A of m.replacement)h.push(A);m.consumed>1&&m.replacement.length===1&&(M(m.replacement[0],d),t({rule:m.ruleName??"phrase-trie",sourceTokens:d,fusedToken:m.replacement[0]})),o+=m.consumed,f=true;continue}}let b=u?l.candidates(c,o):null;if(b!==null&&C(b)){h!==null&&h.push(c[o]),o++;continue}for(let m of this.rulesAt(b,c[o].type)){let d=m.match(c,o);if(d){let A=c.slice(o,o+d.consumed);h===null&&(h=c.slice(0,o));for(let v of d.replacement)h.push(v);if(d.consumed>1&&d.replacement.length===1)M(d.replacement[0],A),t({rule:m.name,sourceTokens:A,fusedToken:d.replacement[0]});else if(d.consumed>1&&d.replacement.length<d.consumed)for(let v of d.replacement)t({rule:m.name,sourceTokens:A,fusedToken:v});o+=d.consumed,f=true,g=true;break}}g||(h!==null&&h.push(c[o]),o++);}if(h===null)break;let R=h;if(R.length>n)throw chunkCO2BI6WL_cjs.c.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${R.length}) exceeds safety limit (${n})`,{tokenCount:R.length,maxTokens:n});c=R;}return c}};var E=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,r){let t=e.toLowerCase().trim().split(/\s+/);if(t.length===0||t[0]==="")return;this.startWords.add(t[0]);let s=t[0],n;if(this.root.has(s)?n=this.root.get(s):(n={children:new Map,terminal:null},this.root.set(s,n)),t.length===1){n.terminal={tokenType:r,phrase:e,consumed:1};return}for(let i=1;i<t.length;i++){let u=t[i];n.children.has(u)||n.children.set(u,{children:new Map,terminal:null}),n=n.children.get(u);}n.terminal={tokenType:r,phrase:e,consumed:t.length};}matchAt(e,r){if(r>=e.length)return null;let t=e[r].type;if(t==="TAG"||t.startsWith("TAG_"))return null;let s=e[r].value.toLowerCase();if(!this.startWords.has(s))return null;let n=this.root.get(s);if(!n)return null;let i=null,u=1;if(n.terminal){let l=e.slice(r,r+1);i={consumed:1,replacement:[S(n.terminal.tokenType,n.terminal.phrase,l)],ruleName:n.terminal.phrase};}for(let l=r+1;l<e.length&&n?.children;l++){let c=e[l].type;if(c==="TAG"||c.startsWith("TAG_"))break;let f=e[l].value.toLowerCase();if(n=n.children.get(f),!n)break;if(u++,n.terminal){let p=e.slice(r,r+u);i={consumed:u,replacement:[S(n.terminal.tokenType,n.terminal.phrase,p)],ruleName:n.terminal.phrase};}}return i}get size(){return this.root.size}getAllPhrases(){let e={},r=(t,s)=>{t.terminal&&(e[s.join(" ")]=t.terminal.tokenType);for(let[n,i]of t.children)r(i,[...s,n]);};for(let[t,s]of this.root)r(s,[t]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var F=new Set(["per","a","an","each","every"]),W=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function V(a=50,e){let r=e??(t=>W.has(t.toLowerCase()));return {name:"implicit:multiply",priority:a,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT","LPAREN","PI","E"]}],match(t,s){if(s+1>=t.length)return null;let n=t[s],i=t[s+1];if(!((n.type==="NUMBER"||n.type==="RPAREN")&&(i.type==="IDENT"||i.type==="LPAREN"||i.type==="PI"||i.type==="E")))return null;let l=i.value.toLowerCase();if(r(l)||F.has(l)&&t[s+2]?.type==="UNIT")return null;let c=new chunkUSQ4KL6S_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col);return {consumed:1,replacement:[n,c]}}}}function te(a,e){let r=[];for(let t=0;t<e;t++){let s=a[t];if(s.type==="LBRACKET")r.push(true);else if(s.type==="LPAREN"){let n=a[t-1],i=!!n&&(n.type==="MAP"||n.type==="REDUCE"||n.type==="SUM_FN"||n.type==="PROD_FN"||n.type==="IDENT"&&(n.value.toLowerCase()==="map"||n.value.toLowerCase()==="reduce"||n.value.toLowerCase()==="sum"||n.value.toLowerCase()==="prod"));r.push(i);}else (s.type==="RBRACKET"||s.type==="RPAREN")&&r.pop();}return r.length>0&&r[r.length-1]}function ne(){return [V()]}var re={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","divide by":"DIVIDE_BY","multiplied by":"MULTIPLY_BY","divided by":"DIVIDE_BY"};exports.a=E;exports.b=S;exports.c=L;exports.d=V;exports.e=te;exports.f=ne;exports.g=re;//# sourceMappingURL=chunk-SGIDBZ4T.cjs.map
2
- //# sourceMappingURL=chunk-SGIDBZ4T.cjs.map
1
+ 'use strict';var chunkUPH22K2T_cjs=require('./chunk-UPH22K2T.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkELQQKZN3_cjs=require('./chunk-ELQQKZN3.cjs');var N=32,L=2;function I(a){return a.shape!==void 0?a.shape:a.startTokenTypes!==void 0?[{types:a.startTokenTypes}]:[]}var x=class{constructor(e){this.rules=e;let r=e.length,t=Math.max(1,Math.ceil(r/N));this.words=t,this.scratch=new Uint32Array(t);let s=e.map(I),n=0;for(let l of s)for(let c of l)for(let f of c.types??[])n=Math.max(n,chunk5IJD5L3O_cjs.c(f));this.typeRows=n+1;let i=0;for(let l of s)i=Math.max(i,l.length);i=Math.min(i,L),this.allRules=new Uint32Array(t);for(let l=0;l<r;l++)this.allRules[l/N|0]|=1<<l%N;let u=[];for(let l=0;l<i;l++)u.push(this.buildPlane(s,l,t));this.planes=u;}buildPlane(e,r,t){let s={byType:new Uint32Array(this.typeRows*t),typeAny:new Uint32Array(t),atEnd:new Uint32Array(t),typeHasValues:new Uint8Array(this.typeRows),byValue:new Map,valueAny:new Uint32Array(t)};for(let n=0;n<e.length;n++){let i=e[n][r],u=n/N|0,l=1<<n%N,c=i?.types;if(c===void 0)s.typeAny[u]|=l,s.atEnd[u]|=l;else for(let p of c)s.byType[chunk5IJD5L3O_cjs.c(p)*t+u]|=l;let f=i?.values;if(f===void 0)s.valueAny[u]|=l;else {for(let p of f){let h=p.toLowerCase(),o=s.byValue.get(h);o===void 0&&(o=new Uint32Array(t),s.byValue.set(h,o)),o[u]|=l;}if(c===void 0)s.typeHasValues.fill(1);else for(let p of c){let h=chunk5IJD5L3O_cjs.c(p);h<this.typeRows&&(s.typeHasValues[h]=1);}}}return s}get size(){return this.rules.length}get depth(){return this.planes.length}candidates(e,r){let t=this.words,s=this.scratch,n=this.planes,i=e.length;if(n.length===0)return s.set(this.allRules),s;for(let u=0;u<n.length;u++){let l=n[u],c=r+u;if(c>=i){if(u===0)s.set(l.atEnd);else for(let o=0;o<t;o++)s[o]&=l.atEnd[o];continue}let f=e[c],p=f.typeId,h=p>=0&&p<this.typeRows?p*t:-1;if(u===0)if(h>=0)for(let o=0;o<t;o++)s[o]=l.byType[h+o]|l.typeAny[o];else s.set(l.typeAny);else if(h>=0)for(let o=0;o<t;o++)s[o]&=l.byType[h+o]|l.typeAny[o];else for(let o=0;o<t;o++)s[o]&=l.typeAny[o];if(h>=0&&l.typeHasValues[p]===1){let o=f.value,R=O(o)?o.toLowerCase():o,g=l.byValue.get(R);for(let T=0;T<t;T++)s[T]&=(g===void 0?0:g[T])|l.valueAny[T];}if(C(s))return s}return s}};function C(a){for(let e=0;e<a.length;e++)if(a[e]!==0)return false;return true}function O(a){for(let e=0;e<a.length;e++){let r=a.charCodeAt(e);if(r>=65&&r<=90)return true}return false}var B={maxPasses:100,maxTokens:1e4,onFusion:()=>{},ignoreRuleIndex:false};function S(a,e,r){let t=r[0],s=r[r.length-1],n=new chunkUPH22K2T_cjs.a(a,chunk5IJD5L3O_cjs.c(a),e,e,t.offset,t.lineBreaks??0,t.line,t.col);return n.sourceEnd=s.sourceEnd??s.offset+s.text.length,n}function z(a,e){let r=e[e.length-1];r&&(a.sourceEnd=r.sourceEnd??r.offset+r.text.length);}var _=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],M=(()=>{let a=_.map(t=>chunk5IJD5L3O_cjs.c(t)),e=Math.max(...a)+1,r=new Uint8Array(e);for(let t of a)r[t]=1;return r})(),P=new Set;function D(a){a.shape!==void 0&&a.shape.length>0||a.startTokenTypes===void 0&&a.unshapedReason===void 0&&(P.has(a.name)||(P.add(a.name),console.warn(`[TokenNormalizer] Rule "${a.name}" declares no \`shape\`, so it is tried at every token of every line and slows down documents that never use it. Declare the tokens it can start at, e.g. shape: [{ types: ["IDENT"], values: ["myword"] }, { types: ["LPAREN"] }]. If it genuinely cannot be described that way, set \`unshapedReason\` to say why and this warning will stop.`)));}var U=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.ruleIndexCache=null;this.candidateBuffer=[];this.normalizeCalls=0;this.phraseTrie=new w;this.ruleShapesCache=null;this.options={...B,...e};}register(e){D(e),this.rules.push(e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}unregister(e){this.rules=this.rules.filter(r=>r.name!==e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}clear(){this.rules=[],this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null,this.phraseTrie=new w;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,r)=>r.priority-e.priority)),this.sortedRulesCache}getRuleIndex(){return this.ruleIndexCache===null&&(this.ruleIndexCache=new x(this.getSortedRules())),this.ruleIndexCache}rulesAt(e,r){let t=this.candidateBuffer;if(t.length=0,e===null){let n=this.rulesForTokenType(r);for(let i=0;i<n.length;i++)t.push(n[i]);return t}let s=this.getRuleIndex().rules;for(let n=0;n<e.length;n++){let i=e[n]>>>0,u=n*32;for(;i!==0;)(i&1)!==0&&t.push(s[u]),i>>>=1,u++;}return t}rulesForTokenType(e){let r=this.rulesByTokenType.get(e);return r===void 0&&(r=this.getSortedRules().filter(t=>t.startTokenTypes===void 0||t.startTokenTypes.includes(e)),this.rulesByTokenType.set(e,r)),r}get ruleCount(){return this.rules.length}getRuleShapes(){if(this.ruleShapesCache!==null)return this.ruleShapesCache;let e=this.getRuleIndex();return this.ruleShapesCache=this.getSortedRules().map(r=>{let t=I(r);return {name:r.name,priority:r.priority,shape:t,unshapedReason:r.unshapedReason,indexedSlots:Math.min(t.length,e.depth)}}),this.ruleShapesCache}getCandidateCounts(e){let r=this.getRuleIndex(),t=[];for(let s=0;s<e.length;s++){let n=r.candidates(e,s),i=0;for(let u=0;u<n.length;u++){let l=n[u]>>>0;for(;l!==0;)i+=l&1,l>>>=1;}t.push(i);}return t}addPhrase(e,r){this.phraseTrie.addPhrase(e,r);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,r){if(e.length===0)return e;let t=r??this.options.onFusion,s=this.options.maxPasses,n=this.options.maxTokens,i=this.normalizeCalls>0;i||(this.normalizeCalls=1);let u=i&&!this.options.ignoreRuleIndex,l=u?this.getRuleIndex():null,c=e,f=true,p=0;for(;f&&p<s;){f=false,p++;let h=null,o=0;for(;o<c.length;){let g=false,T=c[o].typeId;if(T>=M.length||M[T]===0){let m=this.phraseTrie.matchAt(c,o);if(m){let d=c.slice(o,o+m.consumed);h===null&&(h=c.slice(0,o));for(let A of m.replacement)h.push(A);m.consumed>1&&m.replacement.length===1&&(z(m.replacement[0],d),t({rule:m.ruleName??"phrase-trie",sourceTokens:d,fusedToken:m.replacement[0]})),o+=m.consumed,f=true;continue}}let v=u?l.candidates(c,o):null;if(v!==null&&C(v)){h!==null&&h.push(c[o]),o++;continue}for(let m of this.rulesAt(v,c[o].type)){let d=m.match(c,o);if(d){let A=c.slice(o,o+d.consumed);h===null&&(h=c.slice(0,o));for(let b of d.replacement)h.push(b);if(d.consumed>1&&d.replacement.length===1)z(d.replacement[0],A),t({rule:m.name,sourceTokens:A,fusedToken:d.replacement[0]});else if(d.consumed>1&&d.replacement.length<d.consumed)for(let b of d.replacement)t({rule:m.name,sourceTokens:A,fusedToken:b});o+=d.consumed,f=true,g=true;break}}g||(h!==null&&h.push(c[o]),o++);}if(h===null)break;let R=h;if(R.length>n)throw chunkELQQKZN3_cjs.c.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${R.length}) exceeds safety limit (${n})`,{tokenCount:R.length,maxTokens:n});c=R;}return c}};var w=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,r){let t=e.toLowerCase().trim().split(/\s+/);if(t.length===0||t[0]==="")return;this.startWords.add(t[0]);let s=t[0],n;if(this.root.has(s)?n=this.root.get(s):(n={children:new Map,terminal:null},this.root.set(s,n)),t.length===1){n.terminal={tokenType:r,phrase:e,consumed:1};return}for(let i=1;i<t.length;i++){let u=t[i];n.children.has(u)||n.children.set(u,{children:new Map,terminal:null}),n=n.children.get(u);}n.terminal={tokenType:r,phrase:e,consumed:t.length};}matchAt(e,r){if(r>=e.length)return null;let t=e[r].type;if(t==="TAG"||t.startsWith("TAG_"))return null;let s=e[r].value.toLowerCase();if(!this.startWords.has(s))return null;let n=this.root.get(s);if(!n)return null;let i=null,u=1;if(n.terminal){let l=e.slice(r,r+1);i={consumed:1,replacement:[S(n.terminal.tokenType,n.terminal.phrase,l)],ruleName:n.terminal.phrase};}for(let l=r+1;l<e.length&&n?.children;l++){let c=e[l].type;if(c==="TAG"||c.startsWith("TAG_"))break;let f=e[l].value.toLowerCase();if(n=n.children.get(f),!n)break;if(u++,n.terminal){let p=e.slice(r,r+u);i={consumed:u,replacement:[S(n.terminal.tokenType,n.terminal.phrase,p)],ruleName:n.terminal.phrase};}}return i}get size(){return this.root.size}getAllPhrases(){let e={},r=(t,s)=>{t.terminal&&(e[s.join(" ")]=t.terminal.tokenType);for(let[n,i]of t.children)r(i,[...s,n]);};for(let[t,s]of this.root)r(s,[t]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var F=new Set(["per","a","an","each","every"]),W=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function H(a=50,e){let r=e??(t=>W.has(t.toLowerCase()));return {name:"implicit:multiply",priority:a,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT","LPAREN","PI","E"]}],match(t,s){if(s+1>=t.length)return null;let n=t[s],i=t[s+1];if(!((n.type==="NUMBER"||n.type==="RPAREN")&&(i.type==="IDENT"||i.type==="LPAREN"||i.type==="PI"||i.type==="E")))return null;let l=i.value.toLowerCase();if(r(l)||F.has(l)&&t[s+2]?.type==="UNIT")return null;let c=new chunkUPH22K2T_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col);return {consumed:1,replacement:[n,c]}}}}function ne(a,e){let r=[];for(let t=0;t<e;t++){let s=a[t];if(s.type==="LBRACKET")r.push(true);else if(s.type==="LPAREN"){let n=a[t-1],i=!!n&&(n.type==="MAP"||n.type==="REDUCE"||n.type==="SUM_FN"||n.type==="PROD_FN"||n.type==="IDENT"&&(n.value.toLowerCase()==="map"||n.value.toLowerCase()==="reduce"||n.value.toLowerCase()==="sum"||n.value.toLowerCase()==="prod"));r.push(i);}else (s.type==="RBRACKET"||s.type==="RPAREN")&&r.pop();}return r.length>0&&r[r.length-1]}function re(){return [H()]}exports.a=w;exports.b=S;exports.c=U;exports.d=H;exports.e=ne;exports.f=re;//# sourceMappingURL=chunk-72N3ZRVE.cjs.map
2
+ //# sourceMappingURL=chunk-72N3ZRVE.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/normalizer/RuleIndex.ts","../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":["WORD_BITS","MAX_PLANES","effectiveShape","rule","RuleIndex","sortedRules","n","w","shapes","maxTypeId","shape","slot","t","tokenTypeId","depth","i","planes","k","plane","word","bit","types","values","raw","value","mask","id","tokens","pos","scratch","len","at","token","typeId","base","lowered","hasUpper","named","isEmptyMask","c","DEFAULT_OPTIONS","createFusedToken","type","text","sourceTokens","first","last","LexerToken","recordSourceSpan","fused","NON_WORD_NAMES","NON_WORD_TABLE","ids","table","warnedUnshapedRules","warnIfUnshaped","TokenNormalizer","options","PhraseTrie","ruleName","a","b","buffer","list","rules","bits","index","counts","phrase","tokenType","onFusion","fusionHandler","maxPasses","maxTokens","warmedUp","useIndex","ruleIndex","current","changed","passCount","result","matched","tid","trieMatch","rt","candidates","match","passResult","ErrorFactory","words","firstWord","node","startType","best","contType","collect","path","child","RATE_DENOMINATOR_WORDS","PHRASE_START_WORDS","implicitMultiplyRule","priority","canStart","phraseGuard","next","nextValue","starToken","isInsideRangeContext","safeStack","prev","opensMapReduceCall","createBuiltinNormalizerRules"],"mappings":"uKAiEA,IAAMA,CAAAA,CAAY,EAAA,CAeZC,CAAAA,CAAa,CAAA,CASZ,SAASC,CAAAA,CAAeC,CAAAA,CAA2C,CACzE,OAAIA,CAAAA,CAAK,KAAA,GAAU,MAAA,CAAkBA,EAAK,KAAA,CACtCA,CAAAA,CAAK,eAAA,GAAoB,MAAA,CAAkB,CAAC,CAAE,KAAA,CAAOA,CAAAA,CAAK,eAAgB,CAAC,CAAA,CACxE,EACR,CA8BO,IAAMC,CAAAA,CAAN,KAAgB,CA2BtB,WAAA,CAAYC,CAAAA,CAAwC,CACnD,IAAA,CAAK,KAAA,CAAQA,CAAAA,CACb,IAAMC,CAAAA,CAAID,CAAAA,CAAY,MAAA,CAChBE,CAAAA,CAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAG,IAAA,CAA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,CAAK,OAAS,OAAA,GAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,KAAA,CAAM,aAAY,GAAM,QAAA,EAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,MAAM,WAAA,EAAY,GAAM,MAAA,CAAA,CAAA,CAE/KD,CAAAA,CAAU,IAAA,CAAKE,CAAkB,EACnC,CAAA,KAAA,CAAWlG,CAAAA,CAAE,IAAA,GAAS,UAAA,EAAcA,CAAAA,CAAE,IAAA,GAAS,QAAA,GAC7CgG,CAAAA,CAAU,GAAA,GAEd,CACA,OAAOA,CAAAA,CAAU,MAAA,CAAS,CAAA,EAAKA,CAAAA,CAAUA,CAAAA,CAAU,MAAA,CAAS,CAAC,CAC/D,CAoBO,SAASG,EAAAA,EAAiD,CAC/D,OAAO,CAELX,CAAAA,EACF,CACF","file":"chunk-72N3ZRVE.cjs","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * RuleIndex, a conjunctive bitmask prefilter over the normalizer's rules.\n *\n * ## Problem\n * The normalizer tries every rule eligible at a position, at every position.\n * The `startTokenTypes` hint buckets rules by the type of the token they start\n * at, which helps only where that type is selective. It is not: the thirteen\n * call-fusion rules all declare `[\"IDENT\"]`, the commonest token in prose, and\n * the rules firing on a bare `NUMBER` all share that one type too. Measured\n * against the built-in package set, the `IDENT` bucket held 53 of 57 rules and\n * the `NUMBER` bucket 45, because a rule declaring no hint has to be tried\n * everywhere.\n *\n * ## Solution\n * Rules discriminate on different things, so no single axis separates them.\n * A rule declares its leading {@link RuleSlot} shape, and this builds one\n * lookup plane per slot: a flat `Uint32Array` of rule bitmasks indexed by token\n * type id, so a lookup is an array load rather than a hash. A position ANDs the\n * planes together and iterates only the surviving bits, which for most\n * positions is none at all.\n *\n * Rejecting a position therefore costs a few loads and ANDs instead of\n * forty-odd closure calls, and one AND tests 32 rules at once. That the common\n * answer is \"no rule can fire here\" is the point.\n *\n * ## Why planes rather than a fingerprint\n * A superimposed code (OR the hashed types of a window into one word, AND\n * against a per-rule required fingerprint) looks like the cheaper way to reach\n * depth, but it is a per-RULE test with no way to invert it into a lookup, so\n * it stays O(rules) per position. These planes are the same conjunctive test\n * done exactly, at O(rules / 32) and with no false positives. Token types\n * number a couple of hundred, small enough to table, so there is nothing to\n * gain by approximating.\n *\n * ## Ordering\n * Bit `i` is the rule at index `i` of the priority-sorted rule list, so\n * iterating bits from low to high visits rules in exactly the order the\n * unindexed scan did. Ties keep registration order, because the sort is stable.\n * This is what makes the index a pure filter rather than a behaviour change,\n * and `NormalizerIndexFidelity.spec` pins it.\n *\n * ## Safety\n * The contract runs one way: a slot admitting MORE than the rule can match\n * costs a `match()` that returns null, which is what happens today; a slot\n * admitting LESS makes the rule unreachable, a silent bug. So indexing fewer\n * planes than were declared is always safe, which is why {@link MAX_PLANES}\n * can be tuned on evidence rather than being a correctness decision. Only\n * over-narrow declarations are dangerous, and those are what the fidelity spec\n * hunts for.\n *\n * @module RuleIndex\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { NormalizerRule, RuleSlot } from \"./NormalizerRule\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n//#endregion\n//#region ─── Constants ────────────────────────────────────────────────────────\n\n/** Bits per word in the masks below. */\nconst WORD_BITS = 32;\n\n/**\n * How many leading slots are indexed, however many a rule declares.\n *\n * Each plane costs a load and an AND at every position, unconditionally, while\n * only positions surviving the earlier planes can benefit from a later one.\n * After two planes most positions have no candidates left, so a third would tax\n * every token to save a couple of `match()` calls on the few that reach it.\n *\n * Two is a measured default, not a limit of the design: raising it is a\n * one-line change, and lowering it can never break a rule (see this module's\n * Safety note). Rules may declare deeper shapes freely; the extra slots simply\n * go unindexed and are checked by `match()` as before.\n */\nconst MAX_PLANES = 2;\n\n//#endregion\n//#region ─── Shape normalisation ──────────────────────────────────────────────\n\n/**\n * A rule's effective shape, folding the older {@link NormalizerRule.startTokenTypes}\n * into the general form. `shape` wins when both are present.\n */\nexport function effectiveShape(rule: NormalizerRule): readonly RuleSlot[] {\n\tif (rule.shape !== undefined) return rule.shape;\n\tif (rule.startTokenTypes !== undefined) return [{ types: rule.startTokenTypes }];\n\treturn [];\n}\n\n//#endregion\n//#region ─── RuleIndex ────────────────────────────────────────────────────────\n\n/** One indexed slot position: the type plane, plus the value axis for it. */\ninterface Plane {\n\t/** `[typeId * words + w]`, rules whose slot admits `typeId`. */\n\treadonly byType: Uint32Array;\n\t/** Rules constraining no type here, admitted at a type with no row. */\n\treadonly typeAny: Uint32Array;\n\t/**\n\t * Rules constraining no type here, and so the only ones still admissible\n\t * when the stream ends before this slot.\n\t */\n\treadonly atEnd: Uint32Array;\n\t/** `[typeId]`, 1 when a value-constraining rule admits this type here. */\n\treadonly typeHasValues: Uint8Array;\n\t/** Lower-cased word to the rules naming it at this slot. */\n\treadonly byValue: Map<string, Uint32Array>;\n\t/** Rules constraining no value here. */\n\treadonly valueAny: Uint32Array;\n}\n\n/**\n * A conjunctive bitmask prefilter over a priority-sorted rule list.\n *\n * Built once per rule-set mutation (registration time), then read only. See\n * this module's overview for the shape and the ordering guarantee.\n */\nexport class RuleIndex {\n\t/** The priority-sorted rules. Bit `i` of every mask refers to `rules[i]`. */\n\treadonly rules: readonly NormalizerRule[];\n\n\t/** Words per mask, `ceil(rules.length / 32)`. */\n\treadonly words: number;\n\n\t/** Number of token type ids with their own row, exclusive upper bound. */\n\tprivate readonly typeRows: number;\n\n\t/** One per indexed slot, at most {@link MAX_PLANES}. */\n\tprivate readonly planes: readonly Plane[];\n\n\t/** Reused across positions so the hot path allocates nothing. */\n\tprivate readonly scratch: Uint32Array;\n\n\t/**\n\t * Every rule's bit set.\n\t *\n\t * Returned when there are no planes at all, which happens when no rule\n\t * declares a shape. Without it {@link candidates} would hand back an\n\t * unwritten scratch buffer, i.e. \"no rule can fire anywhere\", and every\n\t * rule would silently stop running. The all-admitted answer is the correct\n\t * one: a rule that constrains nothing can match anywhere.\n\t */\n\tprivate readonly allRules: Uint32Array;\n\n\tconstructor(sortedRules: readonly NormalizerRule[]) {\n\t\tthis.rules = sortedRules;\n\t\tconst n = sortedRules.length;\n\t\tconst w = Math.max(1, Math.ceil(n / WORD_BITS));\n\t\tthis.words = w;\n\t\tthis.scratch = new Uint32Array(w);\n\n\t\tconst shapes = sortedRules.map(effectiveShape);\n\n\t\t// Size the type-indexed rows to cover every type any rule names. A token\n\t\t// whose id lands past this (a plugin type minted after the index was\n\t\t// built, say) falls back to the \"constrains nothing\" masks, which is\n\t\t// correct rather than merely safe: a rule naming types cannot match a\n\t\t// type it did not name, and a rule naming none can match anywhere.\n\t\tlet maxTypeId = 0;\n\t\tfor (const shape of shapes) {\n\t\t\tfor (const slot of shape) {\n\t\t\t\tfor (const t of slot.types ?? []) maxTypeId = Math.max(maxTypeId, tokenTypeId(t));\n\t\t\t}\n\t\t}\n\t\tthis.typeRows = maxTypeId + 1;\n\n\t\tlet depth = 0;\n\t\tfor (const shape of shapes) depth = Math.max(depth, shape.length);\n\t\tdepth = Math.min(depth, MAX_PLANES);\n\n\t\tthis.allRules = new Uint32Array(w);\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tthis.allRules[(i / WORD_BITS) | 0] |= 1 << (i % WORD_BITS);\n\t\t}\n\n\t\tconst planes: Plane[] = [];\n\t\tfor (let k = 0; k < depth; k++) {\n\t\t\tplanes.push(this.buildPlane(shapes, k, w));\n\t\t}\n\t\tthis.planes = planes;\n\t}\n\n\t/** Build the lookup plane for slot `k`. */\n\tprivate buildPlane(shapes: readonly (readonly RuleSlot[])[], k: number, w: number): Plane {\n\t\tconst plane: Plane = {\n\t\t\tbyType: new Uint32Array(this.typeRows * w),\n\t\t\ttypeAny: new Uint32Array(w),\n\t\t\tatEnd: new Uint32Array(w),\n\t\t\ttypeHasValues: new Uint8Array(this.typeRows),\n\t\t\tbyValue: new Map<string, Uint32Array>(),\n\t\t\tvalueAny: new Uint32Array(w),\n\t\t};\n\n\t\tfor (let i = 0; i < shapes.length; i++) {\n\t\t\tconst slot: RuleSlot | undefined = shapes[i][k];\n\t\t\tconst word = (i / WORD_BITS) | 0;\n\t\t\tconst bit = 1 << (i % WORD_BITS);\n\n\t\t\t// ── Types ──\n\t\t\tconst types = slot?.types;\n\t\t\tif (types === undefined) {\n\t\t\t\t// Constrains nothing here, so admitted at every type, at a type\n\t\t\t\t// with no row, and past the end of the stream.\n\t\t\t\t//\n\t\t\t\t// Deliberately NOT written into every row of `byType`. Doing that\n\t\t\t\t// made construction O(rules x tokenTypes), tens of thousands of\n\t\t\t\t// writes for a table most of which is the same bit, and the\n\t\t\t\t// engine builds an index per instance: a cold parse of a short\n\t\t\t\t// document paid for it without ever amortising it. The lookup\n\t\t\t\t// ORs `typeAny` in instead, which is one extra operation per word\n\t\t\t\t// on a path that already does several.\n\t\t\t\tplane.typeAny[word] |= bit;\n\t\t\t\tplane.atEnd[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const t of types) plane.byType[tokenTypeId(t) * w + word] |= bit;\n\t\t\t}\n\n\t\t\t// ── Values ──\n\t\t\tconst values = slot?.values;\n\t\t\tif (values === undefined) {\n\t\t\t\tplane.valueAny[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const raw of values) {\n\t\t\t\t\tconst value = raw.toLowerCase();\n\t\t\t\t\tlet mask = plane.byValue.get(value);\n\t\t\t\t\tif (mask === undefined) {\n\t\t\t\t\t\tmask = new Uint32Array(w);\n\t\t\t\t\t\tplane.byValue.set(value, mask);\n\t\t\t\t\t}\n\t\t\t\t\tmask[word] |= bit;\n\t\t\t\t}\n\t\t\t\t// The value axis is only worth a map lookup at a type some\n\t\t\t\t// value-constraining rule admits here.\n\t\t\t\tif (types === undefined) {\n\t\t\t\t\tplane.typeHasValues.fill(1);\n\t\t\t\t} else {\n\t\t\t\t\tfor (const t of types) {\n\t\t\t\t\t\tconst id = tokenTypeId(t);\n\t\t\t\t\t\tif (id < this.typeRows) plane.typeHasValues[id] = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn plane;\n\t}\n\n\t/** Number of indexed rules. */\n\tget size(): number { return this.rules.length; }\n\n\t/** How many slot positions are indexed. */\n\tget depth(): number { return this.planes.length; }\n\n\t/**\n\t * The candidate mask for a position, written into a reused scratch buffer\n\t * and returned. Bits are rule indices, ascending bit order being descending\n\t * priority. The buffer is overwritten by the next call, so read it before\n\t * calling again.\n\t *\n\t * @param tokens - The stream being walked\n\t * @param pos - The position to test\n\t */\n\tcandidates(tokens: readonly { typeId: number; value: string }[], pos: number): Uint32Array {\n\t\tconst w = this.words;\n\t\tconst scratch = this.scratch;\n\t\tconst planes = this.planes;\n\t\tconst len = tokens.length;\n\n\t\tif (planes.length === 0) {\n\t\t\tscratch.set(this.allRules);\n\t\t\treturn scratch;\n\t\t}\n\n\t\tfor (let k = 0; k < planes.length; k++) {\n\t\t\tconst plane = planes[k];\n\t\t\tconst at = pos + k;\n\n\t\t\tif (at >= len) {\n\t\t\t\t// The stream ends before this slot, so only rules that constrain\n\t\t\t\t// nothing here remain admissible.\n\t\t\t\tif (k === 0) { scratch.set(plane.atEnd); }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.atEnd[i]; }\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst token = tokens[at];\n\t\t\tconst typeId = token.typeId;\n\t\t\tconst base = typeId >= 0 && typeId < this.typeRows ? typeId * w : -1;\n\n\t\t\t// `typeAny` holds the rules that constrain no type at this slot, so\n\t\t\t// they are admitted whatever the token is; see the construction note.\n\t\t\tif (k === 0) {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] = plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { scratch.set(plane.typeAny); }\n\t\t\t} else {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] &= plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.typeAny[i]; }\n\t\t\t}\n\n\t\t\t// The value axis costs a map lookup and possibly a lower-casing, so\n\t\t\t// it is consulted only at a type some value-constraining rule names.\n\t\t\tif (base >= 0 && plane.typeHasValues[typeId] === 1) {\n\t\t\t\tconst value = token.value;\n\t\t\t\tconst lowered = hasUpper(value) ? value.toLowerCase() : value;\n\t\t\t\tconst named = plane.byValue.get(lowered);\n\t\t\t\tfor (let i = 0; i < w; i++) {\n\t\t\t\t\tscratch[i] &= (named === undefined ? 0 : named[i]) | plane.valueAny[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isEmptyMask(scratch)) return scratch;\n\t\t}\n\n\t\treturn scratch;\n\t}\n}\n\n/** Whether every bit of a mask returned by {@link RuleIndex.candidates} is clear. */\nexport function isEmptyMask(mask: Uint32Array): boolean {\n\tfor (let i = 0; i < mask.length; i++) if (mask[i] !== 0) return false;\n\treturn true;\n}\n\n/**\n * Whether a string contains an ASCII upper-case letter.\n *\n * `toLowerCase()` allocates even when it changes nothing, and identifiers in\n * running prose are overwhelmingly already lower case, so this scan pays for\n * itself by skipping the allocation in the common case.\n */\nfunction hasUpper(value: string): boolean {\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst c = value.charCodeAt(i);\n\t\tif (c >= 65 && c <= 90) return true;\n\t}\n\treturn false;\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, RuleSlot, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { RuleIndex, isEmptyMask, effectiveShape } from \"./RuleIndex\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n\n /**\n * Try every registered rule at every position, ignoring the shape index.\n *\n * Diagnostic only, and much slower. It exists so the indexed walk can be\n * compared against the unindexed one over a corpus: the index is a pure\n * filter, so the two must agree token for token, and a rule whose declared\n * {@link NormalizerRule.shape} is too narrow shows up as a difference rather\n * than as a feature that quietly stopped working.\n * `NormalizerIndexFidelity.spec` is the consumer.\n *\n * @default false\n */\n ignoreRuleIndex?: boolean;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n ignoreRuleIndex: false,\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Rule names already warned about, so a rule registered into many engines\n * says it once rather than once per engine.\n */\nconst warnedUnshapedRules = new Set<string>();\n\n/**\n * Warn when a rule declares neither a shape nor a reason for not having one.\n *\n * An unshaped rule is tried at every position of every line, so its cost is\n * paid by every document rather than only by the feature it implements. The\n * warning names the rule and points at the two ways out, and it fires once per\n * rule name per process: a warning a package author sees on every engine they\n * construct is one they learn to filter out, which would make it worse than\n * useless.\n *\n * Deliberately not an error. A rule without a shape is correct, only slower,\n * and refusing to register it would break every package written before the\n * field existed.\n */\nfunction warnIfUnshaped(rule: NormalizerRule): void {\n if (rule.shape !== undefined && rule.shape.length > 0) return;\n if (rule.startTokenTypes !== undefined) return;\n if (rule.unshapedReason !== undefined) return;\n if (warnedUnshapedRules.has(rule.name)) return;\n warnedUnshapedRules.add(rule.name);\n console.warn(\n `[TokenNormalizer] Rule \"${rule.name}\" declares no \\`shape\\`, so it is tried at every ` +\n `token of every line and slows down documents that never use it. Declare the tokens it ` +\n `can start at, e.g. shape: [{ types: [\"IDENT\"], values: [\"myword\"] }, { types: [\"LPAREN\"] }]. ` +\n `If it genuinely cannot be described that way, set \\`unshapedReason\\` to say why and this ` +\n `warning will stop.`,\n );\n}\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Per-token-type view of the priority-sorted rules: for a token type, the\n * rules that could match a token of that type (those with no\n * {@link NormalizerRule.startTokenTypes} hint, plus those that list the type),\n * in the same priority order {@link getSortedRules} produces. Built lazily on\n * the first token of each type and cached, so a document of many number and\n * operator tokens never re-tries the many rules that only fire on an\n * identifier. Invalidated alongside {@link sortedRulesCache}.\n */\n private rulesByTokenType = new Map<string, NormalizerRule[]>();\n\n /**\n * Shape index over the priority-sorted rules, rebuilt alongside\n * {@link sortedRulesCache}. `null` means \"stale, rebuild on next use\".\n *\n * This is what turns the per-position scan from \"try every rule that could\n * fire on this token type\" into \"AND a few lookup planes and try what\n * survives\", which is usually nothing. See {@link RuleIndex}.\n */\n private ruleIndexCache: RuleIndex | null = null;\n\n /** Reused by {@link rulesAt} so a position's candidate list costs no allocation. */\n private candidateBuffer: NormalizerRule[] = [];\n\n /**\n * How many times {@link normalize} has run, capped once the index is in use.\n *\n * The index costs a few tens of microseconds to build and pays that back\n * within a line or two, but an engine that normalises exactly once, which is\n * what evaluating a single expression on a fresh engine does, would never\n * reach the payback. Skipping the build on the first call keeps that case at\n * the cost it had before the index existed, and a document reaches line two\n * immediately.\n */\n private normalizeCalls = 0;\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n warnIfUnshaped(rule);\n this.rules.push(rule);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * The priority-sorted rules to try at a token of `type`: every rule with no\n * {@link NormalizerRule.startTokenTypes} hint, plus those that list this type.\n * A rule that declares a different trigger would have returned null here\n * anyway, so omitting it is behaviour-preserving. Built once per distinct type\n * and cached, which is what turns the per-position rule scan from \"try all R\n * rules\" into \"try only the ones that could fire on this token\".\n */\n private getRuleIndex(): RuleIndex {\n if (this.ruleIndexCache === null) {\n this.ruleIndexCache = new RuleIndex(this.getSortedRules());\n }\n return this.ruleIndexCache;\n }\n\n /**\n * The rules to try at a position, in priority order.\n *\n * With a candidate mask, walks its set bits low to high, which is descending\n * priority because bit `i` is the rule at index `i` of the priority-sorted\n * list.\n *\n * The walk shifts a bit at a time rather than jumping to the next set bit\n * with `Math.clz32(bits & -bits)`, which is the idiomatic form and was 36x\n * SLOWER here: 45us per line against 1.2us, measured over the built-in rule\n * set. `clz32` is specified on uint32 and the masks come out of a\n * `Uint32Array` as doubles above 2^31, so every call pays a conversion that\n * swamps the handful of iterations it saves. A de Bruijn table matched the\n * shift scan to within noise and needs a magic constant, so the plain shift\n * wins on both counts. Worst case is 32 iterations per word of pure integer\n * work.\n *\n * With `null` (the {@link NormalizerOptions.ignoreRuleIndex} path) it falls\n * back to the type-bucketed list, which is the behaviour this replaced.\n *\n * Returns a buffer reused across positions, so the caller must finish with it\n * before calling again. Copying the surviving rules out here rather than\n * yielding them lazily is deliberate twice over: it keeps the mask's own\n * scratch buffer from being read after the next position overwrites it, and\n * it avoids a generator on the hottest loop in the pass.\n */\n private rulesAt(mask: Uint32Array | null, type: string): NormalizerRule[] {\n const buffer = this.candidateBuffer;\n buffer.length = 0;\n\n if (mask === null) {\n const list = this.rulesForTokenType(type);\n for (let i = 0; i < list.length; i++) buffer.push(list[i]);\n return buffer;\n }\n\n const rules = this.getRuleIndex().rules;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n let index = w * 32;\n while (bits !== 0) {\n if ((bits & 1) !== 0) buffer.push(rules[index]);\n bits >>>= 1;\n index++;\n }\n }\n return buffer;\n }\n\n private rulesForTokenType(type: string): NormalizerRule[] {\n let list = this.rulesByTokenType.get(type);\n if (list === undefined) {\n list = this.getSortedRules().filter(\n (rule) => rule.startTokenTypes === undefined || rule.startTokenTypes.includes(type),\n );\n this.rulesByTokenType.set(type, list);\n }\n return list;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n /**\n * Every registered rule with the shape it declared, for diagnostic display.\n *\n * Exposes what the index is actually working with: a rule that declares a\n * shape is only tried where that shape can match, and one that declares none\n * is tried at every position of every line. Which is which is invisible from\n * the outside otherwise, and it is the difference between a package that\n * costs the documents that use it and one that costs all of them, so the\n * playground draws it.\n *\n * Returned in priority order, highest first, which is the order the\n * normalizer tries them in.\n */\n private ruleShapesCache: Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> | null = null;\n\n getRuleShapes(): Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> {\n // Memoised: the answer depends only on the rule set, but the diagnostic\n // pipeline builds a stage per LINE, so recomputing it there made a\n // 25-line document walk every rule 25 times to produce 25 identical lists.\n if (this.ruleShapesCache !== null) return this.ruleShapesCache;\n const index = this.getRuleIndex();\n this.ruleShapesCache = this.getSortedRules().map((rule) => {\n const shape = effectiveShape(rule);\n return {\n name: rule.name,\n priority: rule.priority,\n shape,\n unshapedReason: rule.unshapedReason,\n indexedSlots: Math.min(shape.length, index.depth),\n };\n });\n return this.ruleShapesCache;\n }\n\n /**\n * How many rules could fire at each position of `tokens`, against the total.\n *\n * The point of the index is that most positions admit no rule at all, and\n * this is what makes that visible rather than asserted.\n */\n getCandidateCounts(tokens: Token[]): number[] {\n const index = this.getRuleIndex();\n const counts: number[] = [];\n for (let pos = 0; pos < tokens.length; pos++) {\n const mask = index.candidates(tokens, pos);\n let n = 0;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n while (bits !== 0) { n += bits & 1; bits >>>= 1; }\n }\n counts.push(n);\n }\n return counts;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // Rules are consulted per token type via rulesForTokenType(), which builds\n // on the priority-sorted cache in getSortedRules().\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n // Hoisted out of the pass loop: the rule set cannot change mid-normalize,\n // so the index is resolved once rather than per position.\n const warmedUp = this.normalizeCalls > 0;\n if (!warmedUp) this.normalizeCalls = 1;\n const useIndex = warmedUp && !this.options.ignoreRuleIndex;\n const ruleIndex = useIndex ? this.getRuleIndex() : null;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n // Built lazily: a pass that changes nothing must not allocate an array\n // and copy every token into it only to throw the copy away. `null` means\n // \"nothing has changed yet, `current` is still the answer\"; the first\n // rule to fire calls ensureResult() to materialise it. A document whose\n // lines mostly normalise to themselves is the common case, and it now\n // costs no allocation at all.\n let result: Token[] | null = null;\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n if (result === null) result = current.slice(0, pos);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try, in priority order, only the rules whose declared shape admits\n // this position. The index is a pure filter: bit order is priority\n // order, and a rule it excludes would have returned null here anyway\n // (see RuleIndex). `ignoreRuleIndex` restores the exhaustive scan so\n // the two can be compared.\n const candidates = useIndex\n ? ruleIndex!.candidates(current, pos)\n : null;\n if (candidates !== null && isEmptyMask(candidates)) {\n // Nothing can fire here. This is the common case in running prose,\n // and reaching it costs a few array loads rather than one call per\n // registered rule.\n if (result !== null) result.push(current[pos]);\n pos++;\n continue;\n }\n for (const rule of this.rulesAt(candidates, current[pos].type)) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n if (result === null) result = current.slice(0, pos);\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged.\n // Only copied when an earlier position already forced the array.\n if (result !== null) result.push(current[pos]);\n pos++;\n }\n }\n\n // Nothing fired anywhere in this pass, so the stream is already its own\n // normal form and `changed` is false; the loop is about to end.\n if (result === null) break;\n const passResult: Token[] = result;\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (passResult.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${passResult.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: passResult.length, maxTokens }\n );\n }\n\n current = passResult;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── A tag token never takes part in phrase fusion (#197, #213) ──\n\t\t// A `#tag` is a typed token, not a bare word, so it must not start or\n\t\t// complete a phrase. The trie matches on written value alone, so without\n\t\t// this guard a tag whose name equals a phrase or a phrase-continuation\n\t\t// word (`1200 #assuming`, `total of #column`) is fused into that grammar\n\t\t// before the category-tag rules ever run, and the tag is lost.\n\t\t//\n\t\t// The guard also covers the fused aggregate tokens the tags package emits\n\t\t// (`TAG_SUM` / `TAG_COUNT` / `TAG_AVERAGE`), whose value is the tag NAME:\n\t\t// otherwise `total of #assuming` fuses correctly to TAG_SUM(\"assuming\"),\n\t\t// then the trie re-reads that value on the next pass and turns it back\n\t\t// into the finance ASSUMING keyword (#213). The whole `TAG` / `TAG_*`\n\t\t// namespace belongs to the tags package.\n\t\tconst startType = tokens[pos].type;\n\t\tif (startType === \"TAG\" || startType.startsWith(\"TAG_\")) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst contType = tokens[i].type;\n\t\t\tif (contType === \"TAG\" || contType.startsWith(\"TAG_\")) break; // a tag token can't continue a phrase (#197, #213)\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n // Both slots are exactly the `triggers` test below, which is the whole\n // condition: a value or closing bracket, then something a multiplication\n // could apply to.\n shape: [\n { types: [\"NUMBER\", \"RPAREN\"] },\n { types: [\"IDENT\", \"LPAREN\", \"PI\", \"E\"] },\n ],\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Check trigger conditions ──\n // Ordered FIRST deliberately. The two guards below only ever suppress a\n // match, so testing them after the trigger cannot change any result, and\n // the first of them allocates a lower-cased copy of the next token's\n // value. Running that ahead of a pair of type comparisons meant every\n // position in the document paid a string allocation and a set lookup to\n // reach a test that rejects nearly all of them.\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}. The table\n * itself lives in `lexer/BuiltinPhrases.ts`, shared with the lexer's token\n * lookup, and is re-exported here so existing imports keep working.\n */\nexport { BUILTIN_PHRASES } from \"@solve-js/lexer/BuiltinPhrases\";\n\n//#endregion\n"]}
@@ -1,3 +1,3 @@
1
- import {a}from'./chunk-RAF57WYO.js';import {l,m,g}from'./chunk-42JXN3BH.js';import {b as b$1}from'./chunk-76F3LCIL.js';import {J,K}from'./chunk-A5M4QZIK.js';import {h,i,P as P$1}from'./chunk-3GR46UOX.js';import {b}from'./chunk-BRJ4RT5U.js';import {c as c$1}from'./chunk-FP6Z6PYR.js';import {c,b as b$2}from'./chunk-PIZQIQVM.js';var P=class{constructor(){this.root=null;}get length(){return this.root?this.root.size:0}get isEmpty(){return this.root===null}getAt(e){if(!(e<0||e>=(this.root?.size??0)))return this.nodeAt(this.root,e).lineId}insertAt(e,t){let[n,r]=I(this.root,e);this.root=C(C(n,te(t)),r);}deleteAt(e){if(e<0||e>=(this.root?.size??0))return;let[t,n]=I(this.root,e),[r,s]=I(n,1),i=r?r.lineId:void 0;return this.root=C(t,s),i}spliceAt(e,t,n){let r=Math.max(0,e),s=Math.min(Math.max(0,t),(this.root?.size??0)-r),[i,a]=I(this.root,r),[l,o]=I(a,s),c=ne(l),d=B(n,0,n.length);return this.root=C(C(i,d),o),c}replaceAll(e){this.root=B(e,0,e.length);}getRange(e,t){let n=Math.max(0,e),r=Math.min((this.root?.size??0)-1,t);if(n>r)return [];let s=[];return this.collectRange(this.root,n,r,0,s),s}clear(){this.root=null;}*[Symbol.iterator](){yield*this.inOrder(this.root);}*inOrder(e){e&&(yield*this.inOrder(e.left),yield e.lineId,yield*this.inOrder(e.right));}nodeAt(e,t){let n=e.left?e.left.size:0;return t<n?this.nodeAt(e.left,t):t===n?e:this.nodeAt(e.right,t-n-1)}collectRange(e,t,n,r,s){if(!e)return;let i=e.left?e.left.size:0,a=r+i;a>t&&e.left&&this.collectRange(e.left,t,n,r,s),a>=t&&a<=n&&s.push(e.lineId),a<n&&e.right&&this.collectRange(e.right,t,n,a+1,s);}};function te(u){return {lineId:u,size:1,priority:Math.random(),left:null,right:null}}function T(u){u.size=1+(u.left?u.left.size:0)+(u.right?u.right.size:0);}function C(u,e){return u?e?u.priority>e.priority?(u.right=C(u.right,e),T(u),u):(e.left=C(u,e.left),T(e),e):u:e}function I(u,e){if(!u)return [null,null];let t=u.left?u.left.size:0;if(e<=t){let[n,r]=I(u.left,e);return u.left=r,T(u),[n,u]}else {let[n,r]=I(u.right,e-t-1);return u.right=n,T(u),[u,r]}}function ne(u){let e=[];return F(u,e),e}function F(u,e){u&&(F(u.left,e),e.push(u.lineId),F(u.right,e));}function B(u,e,t){if(e>=t)return null;let n=Math.floor((e+t)/2),r=re(n);return {lineId:u[n],size:t-e,priority:r,left:B(u,e,n),right:B(u,n+1,t)}}function re(u){let e=u;return e=(e>>16^e)*73244475,e=(e>>16^e)*73244475,e=e>>16^e,e/4294967295}var R=class{constructor(e=b.performance.maxDocumentLines){this.lines=new Map;this.orderTree=new P;this.nextLineId=1;this._positionCache=null;this.dirtyLineIds=new Set;this.maxLines=e;}setDocument(e){if(b$1(e,this.maxLines)>this.maxLines)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${this.maxLines.toLocaleString("en-US")} lines, which is the most the engine will hold at once`,{maxLines:this.maxLines});this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.dirtyLineIds.clear(),this.nextLineId=1;let n=e.split(`
2
- `),r=new Array(n.length);for(let s=0;s<n.length;s++){let i=this.nextLineId++;r[s]=i,this.lines.set(i,{lineId:i,textHash:a(n[s]),text:n[s],expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:n[s].trim().length===0,inlineSolveCount:0});}this.orderTree.replaceAll(r);for(let s of r)this.dirtyLineIds.add(s);}applyChanges(e){let t=[],n=[],r=[...e].sort((s,i)=>i.startLine-s.startLine);for(let s of r){let i=s.startLine-1,a$1=[];for(let o of s.insertLines){let c=this.nextLineId++;a$1.push(c),t.push(c),this.lines.set(c,{lineId:c,textHash:a(o),text:o,expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:o.trim().length===0,inlineSolveCount:0});}for(let o of a$1)this.dirtyLineIds.add(o);let l=this.orderTree.spliceAt(i,s.deleteCount,a$1);for(let o of l)n.push(o),this.lines.delete(o),this.dirtyLineIds.delete(o);}return this._positionCache=null,{inserted:t,removed:n}}insertLines(e,t){let n={startLine:e,deleteCount:0,insertLines:t};return this.applyChanges([n]).inserted}deleteLines(e,t){let n={startLine:e,deleteCount:t-e+1,insertLines:[]};return this.applyChanges([n]).removed}editLine(e,t){let n=this.getLineAt(e);if(!n)return false;let r=a(t);return r===n.textHash?false:(n.text=t,n.textHash=r,n.expressions=[],n.bytecodes=[],n.results=[],n.result=null,n.inlineSolveCount=0,n.dirty=true,this.dirtyLineIds.add(n.lineId),n.isEmpty=t.trim().length===0,true)}getLineAt(e){let t=e-1,n=this.orderTree.getAt(t);if(n!==void 0)return this.lines.get(n)}getLinePosition(e){if(this._positionCache)return this._positionCache.get(e)??-1;this._positionCache=new Map;let t=1;for(let n of this.orderTree)this._positionCache.set(n,t++);return this._positionCache.get(e)??-1}getVisibleLines(e,t){let n=this.orderTree.getRange(e-1,t-1),r=[];for(let s of n){let i=this.lines.get(s);i&&r.push(i);}return r}getAllLines(){return this.getVisibleLines(1,this.lineCount)}getLineById(e){return this.lines.get(e)}getDirtyLines(){let e=[];for(let t of this.lines.values())t.dirty&&e.push(t);return e}hasAnyDirtyLineBefore(e){for(let t of this.dirtyLineIds){let n=this.getLinePosition(t);if(n>=1&&n<e)return true}return false}hasAnyDirtyVariableDefLineBefore(e){for(let t of this.dirtyLineIds){let n=this.lines.get(t);if(!n||!n.isVariableDef)continue;let r=this.getLinePosition(t);if(r>=1&&r<e)return true}return false}get dirtyCount(){return this.dirtyLineIds.size}isBytecodeValid(e,t){let n=this.lines.get(e);return n!==void 0&&n.textHash===t}markClean(e){let t=this.lines.get(e);t&&(t.dirty=false,this.dirtyLineIds.delete(e));}markDirtyByLineNumber(e){let t=this.getLineAt(e);t&&(t.dirty=true,this.dirtyLineIds.add(t.lineId));}markDirty(e){let t=this.lines.get(e);t&&(t.dirty=true,this.dirtyLineIds.add(e));}invalidateAll(){for(let e of this.lines.values())e.dirty=true;this.dirtyLineIds=new Set(this.lines.keys());}updateLineResult(e,t,n,r,s,i,a,l=0){let o=this.lines.get(e);o&&(o.results=t,o.result=t[0]?.[0]??null,o.bytecodes=n,o.expressions=r,o.reads=s,o.writes=i,o.isVariableDef=a,o.inlineSolveCount=l,o.dirty=false,this.dirtyLineIds.delete(e));}updateLineCompiled(e,t,n,r,s,i,a=0){let l=this.lines.get(e);l&&(l.expressions=t,l.bytecodes=n,l.reads=r,l.writes=s,l.isVariableDef=i,l.inlineSolveCount=a);}get lineCount(){return this.orderTree.length}get isEmpty(){return this.orderTree.isEmpty}*[Symbol.iterator](){for(let e of this.orderTree){let t=this.lines.get(e);t&&(yield t);}}clear(){this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.nextLineId=1;}toJSON(){return {lineCount:this.lineCount,lines:this.getAllLines().map(e=>({lineId:e.lineId,text:e.text.substring(0,80),textHash:e.textHash,dirty:e.dirty,isVariableDef:e.isVariableDef,isEmpty:e.isEmpty,hasBytecode:e.bytecodes.length>0,hasResult:e.results.length>0,inlineSolveCount:e.inlineSolveCount,reads:e.reads,writes:e.writes}))}}};var A=class{constructor(){this.worker=null;this.nextId=1;this.pending=new Map;}ensureWorker(){return this.worker?this.worker:(this.worker=g(),this.worker.onmessage=e=>{let t=e.data;if(!t||t.type!=="COMPILE_RESULT")return;let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id);let r=[];for(let s of t.results)r.push(this.reconstructResult(s));n.resolve(r);},this.worker.onerror=e=>{for(let[t,n]of this.pending)n.reject(new Error(`Compilation worker error: ${e.message}`)),this.pending.delete(t);},this.worker)}async compileBatch(e){if(e.length===0)return [];let t=this.ensureWorker(),n=this.nextId++;return new Promise((r,s)=>{this.pending.set(n,{resolve:r,reject:s}),t.postMessage({type:"COMPILE_BATCH",id:n,items:e});})}storeResults(e,t){let n=new Map;for(let i of e){if(i.error)continue;let a=t.getLineById(i.lineId);if(!a||a.textHash!==i.compiledAgainstHash)continue;let l=n.get(i.lineId);l||(l={bytecodes:[],reads:new Set,writes:new Set,isVariableDef:false,expressions:a.expressions.length>0?[...a.expressions]:[],textHash:i.compiledAgainstHash},n.set(i.lineId,l)),l.bytecodes.push(i.program);for(let o of i.reads)l.reads.add(o);for(let o of i.writes)l.writes.add(o);i.isVariableDef&&(l.isVariableDef=true);}let s=0;for(let[i,a]of n){if(a.bytecodes.length===0)continue;let o=t.getLineById(i)?.inlineSolveCount??0;t.updateLineCompiled(i,a.expressions,a.bytecodes,[...a.reads],[...a.writes],a.isVariableDef,o),s+=a.bytecodes.length;}return s}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.pending.clear());}get isActive(){return this.worker!==null}reconstructResult(e){if(e.error)return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},reads:[],writes:[],isVariableDef:false,error:e.error};let t=e.opcodesLength>0?new Uint8Array(e.opcodesBuffer,0,e.opcodesLength):new Uint8Array(0),n=e.numbersLength>0?new Float64Array(e.numbersBuffer,0,e.numbersLength):new Float64Array(0),r={opcodes:t,numbers:n,strings:e.strings,hasAsync:false};return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:r,reads:e.reads,writes:e.writes,isVariableDef:e.isVariableDef,error:null}}};var U=128,k=3,Z=6,Q=2,X=k,H=class u{constructor(){this.lastViewportStart=null;this.savedDirection=null;this.pageAccess=new Map;this.accessSeq=0;}static pageForLine(e){return Math.floor((e-1)/U)}static pageRange(e,t){return {startLine:e*U+1,endLine:Math.min((e+1)*U,t)}}detectDirection(e){return this.lastViewportStart===null?null:e.startLine>this.lastViewportStart?"down":e.startLine<this.lastViewportStart?"up":null}maintainAfterEval(e,t){this.savedDirection=this.detectDirection(e),this.lastViewportStart=e.startLine;let n=t.lineCount,r=u.pageForLine(e.startLine),s=u.pageForLine(e.endLine),i=u.pageForLine(n),a=Math.max(0,r-k),l=Math.min(i,s+k),o=Math.max(0,r-Z),c=Math.min(i,s+Z);for(let h=a;h<=l;h++)this.touchPage(h);for(let h=o;h<=c;h++)h>=a&&h<=l||this.evictPageResults(h,t,n);let d=o-1,p=Math.max(0,d-X+1);for(let h=p;h<=d;h++)this.evictPageBytecode(h,t,n);let f=c+1,g=Math.min(i,f+X-1);for(let h=f;h<=g;h++)this.evictPageBytecode(h,t,n);}getPreloadTargets(e,t){let n=this.savedDirection;if(!n)return [];let r=[],s=u.pageForLine(e.endLine),i=u.pageForLine(e.startLine),a=u.pageForLine(t.lineCount),l=[];if(n==="down"){let o=s+k+1,c=Math.min(o+Q-1,a);for(let d=o;d<=c&&d<=a;d++)l.push(d);}else {let o=i-k-1;for(let c=o;c>o-Q&&c>=0;c--)l.push(c);}for(let o of l){let c=u.pageRange(o,t.lineCount);for(let d=c.startLine;d<=c.endLine;d++){let p=t.getLineAt(d);if(p&&p.dirty&&!(p.bytecodes.length>0&&!p.isVariableDef)&&!p.isEmpty)if(p.expressions.length>0)for(let f of p.expressions)f.trim()&&r.push({lineId:p.lineId,expression:f,textHash:p.textHash});else {let f=c$1.findInlineSolves(p.text);if(f.length>0)for(let g of f)g.expression.trim()&&r.push({lineId:p.lineId,expression:g.expression,textHash:p.textHash});else {let g=p.text.trim();g&&r.push({lineId:p.lineId,expression:g,textHash:p.textHash});}}}}return r}clear(){this.pageAccess.clear(),this.accessSeq=0,this.lastViewportStart=null,this.savedDirection=null;}touchPage(e){this.pageAccess.set(e,++this.accessSeq);}evictPageResults(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);i&&!i.isVariableDef&&i.results.length>0&&(i.results=[],i.result=null);}}evictPageBytecode(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);!i||i.isVariableDef||(i.bytecodes.length>0||i.results.length>0)&&(i.bytecodes=[],i.results=[],i.result=null,t.markDirty(i.lineId));}}};var Y=(r=>(r[r.Tier1=1]="Tier1",r[r.Tier2=2]="Tier2",r[r.Tier3=3]="Tier3",r[r.Skipped=0]="Skipped",r))(Y||{}),w=class{constructor(e,t,n){this.compilationWorker=null;this.globalUnsubscribe=null;this.doc=e,this.engine=t,this.dag=t.getDag(),this.checkpointer=n??null,this.pageManager=new H,this.engine.setDocumentModel(this.doc),this.globalUnsubscribe=J.subscribe(r=>{for(let s of this.dag.getAffectedLines(K(r)))this.doc.markDirtyByLineNumber(s);});}evaluate(e,t){this.engine.setKeystrokeSignal(t??null),h();try{this.reseedAccumulators();let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(e.endLine,i);for(let l=1;l<=a;l++){let o=this.doc.getLineAt(l);if(!o){s.skipped++;continue}let c=l>=e.startLine&&l<=e.endLine,d=this.evaluateSingleLine(o,l,c);n.push(d),d.tier===1?s.tier1++:d.tier===2?s.tier2++:d.tier===3?s.tier3++:s.skipped++,d.results&&c&&r.set(l,d.results.flat());}return this.pageManager.maintainAfterEval(e,this.doc),{lines:n,resultMap:r,tierCounts:s}}finally{this.engine.setKeystrokeSignal(null),i();}}backgroundCompile(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef)continue;let a=this.evaluateSingleLine(i,s,false);t.push(a);}return t}dispatchBackgroundCompiles(e){let t=this.collectInvisibleCompileTargets(e);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}terminateWorker(){this.compilationWorker&&(this.compilationWorker.terminate(),this.compilationWorker=null),this.globalUnsubscribe&&(this.globalUnsubscribe(),this.globalUnsubscribe=null);}getDoc(){return this.doc}evaluateAll(e){let t={startLine:1,endLine:this.doc.lineCount};return this.evaluate(t,e)}setViewport(e,t){if(this.engine.setKeystrokeSignal(t??null),e.startLine>1&&this.hasDirtyLinesBefore(e.startLine))return this.checkpointer?.clear(),this.evaluate(e,t);this.pageManager.maintainAfterEval(e,this.doc),this.preloadNextPages(e),this.restoreTo(e.startLine-1),h();try{return this.collectEvalResults(e.startLine,e.endLine)}finally{this.engine.setKeystrokeSignal(null),i();}}applyTransaction(e){let t=new Set;for(let s of e)for(let i=0;i<s.deleteCount;i++){let a=s.startLine+i,l=this.dag.getWrites(a);for(let o of l)t.add(o);this.dag.removeLine(a),this.engine.getLineCache().removeAllForLine(a);}let n=new Set;for(let s of t){let i=this.dag.getAffectedLines(s);for(let a of i){let l=this.doc.getLineAt(a);l&&n.add(l.lineId);}}let r=this.doc.applyChanges(e);this.checkpointer?.clear();for(let s of n)this.doc.markDirty(s);return this.dag.clear(),{inserted:r.inserted,removed:r.removed}}reseedAccumulators(){let e=this.engine.resetAccumulators();if(e.size===0)return;let t=this.doc.lineCount;for(let n=1;n<=t;n++){let r=this.dag.getWrites(n);if(r.size!==0){for(let s of r)if(e.has(s)){this.doc.markDirtyByLineNumber(n);break}}}}collectEvalResults(e,t){let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(t,i);for(let l=e;l<=a;l++){let o=this.doc.getLineAt(l);if(!o)continue;let c=this.evaluateSingleLine(o,l,true);n.push(c),c.tier===1?s.tier1++:c.tier===2?s.tier2++:c.tier===3?s.tier3++:s.skipped++,c.results&&r.set(l,c.results.flat());}return {lines:n,resultMap:r,tierCounts:s}}hasDirtyLinesBefore(e){return this.doc.hasAnyDirtyVariableDefLineBefore(e)}evaluateSingleLine(e,t,n){let r={lineId:e.lineId,lineNumber:t};if(e.isEmpty||l(e.text))return e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null};let{expressions:s,inlineSolveCount:i}=this.extractExpressions(e);return s.length===0?(e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null}):e.dirty?n?this.evaluateTier1(e,t,s,i,r):e.bytecodes.length>0&&e.bytecodes.length===s.length&&!e.isVariableDef?{...r,tier:0,result:null,error:null}:this.evaluateTier3(e,t,s,i,r):n&&e.bytecodes.length>0?this.evaluateTier2(e,t,r):{...r,tier:0,result:null,error:null}}evaluateTier1(e,t,n,r,s){let i=[],a=[],l=new Set,o=new Set,c=false,d=null,p=null,f=false,g=false;for(let y of n){if(!y.trim())continue;let b=null,L;try{let m=this.engine.evaluateLine(t,y);b=[m],d=m,L=this.engine.getLineCache().get(t,y);}catch(m){let x=m instanceof Error?m.message:String(m);p||(p=x),f=true,b=null;}if(b&&b.some(m=>m.type===12)&&(g=true),b?i.push(b):i.push([P$1("eval_failed",p??"unknown error")]),L){a.push(L.bytecode);for(let m of L.readVariables)l.add(m);L.writeVariable&&(o.add(L.writeVariable),c=true);}else try{let{program:m,reads:x,writes:E}=this.engine.compileExpression(y);a.push(m);for(let S of x)l.add(S);for(let S of E)o.add(S);E.length>0&&(c=!0);}catch(m){if(a.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),m instanceof b$2&&m.context){let x=m.context.reads,E=m.context.writes;if(Array.isArray(x))for(let S of x)l.add(S);if(Array.isArray(E))for(let S of E)o.add(S);}}}let h=[...l],v=[...o];return f||g?(this.doc.updateLineCompiled(e.lineId,n,a,h,v,c,r),e.results=i,e.result=i[0]?.[0]??null,e.inlineSolveCount=r,e.expressions=n):this.doc.updateLineResult(e.lineId,i,a,n,h,v,c,r),this.dag.registerLine(t,h,v),this.checkpointer&&v.length>0&&!f&&!g&&this.checkpointer.snapshot(t,e.lineId,v),{...s,tier:1,result:d,results:i,error:p}}evaluateTier2(e,t,n){if(e.bytecodes.length===0)return {...n,tier:0,result:null,error:null};let r=[],s=null,i=null,a=false;for(let l of e.bytecodes)if(l.opcodes.length!==0)try{let o=this.engine.executeCached(l,t);s=o,r.push([o]);}catch(o){let c=o instanceof Error?o.message:String(o);i||(i=c),a=true,r.push([P$1("exec_failed",c)]);}return this.dag.registerLine(t,e.reads,e.writes),e.results=r,e.result=r[0]?.[0]??null,a&&this.doc.markDirty(e.lineId),{...n,tier:2,result:s,results:r,error:i}}evaluateTier3(e,t,n,r,s){let i=[],a=new Set,l=new Set,o=false,c=null,d=null,p=false,f=false;for(let v of n)if(v.trim())try{let{program:y,reads:b,writes:L}=this.engine.compileExpression(v);i.push(y);for(let m of b)a.add(m);for(let m of L)l.add(m);L.length>0&&(o=!0),L.length>0&&y.opcodes.length>0&&(c=this.engine.executeCached(y,t),c&&c.type===12&&(f=!0));}catch(y){let b=y instanceof Error?y.message:String(y);d||(d=b),p=true,i.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false});}let g=[...a],h=[...l];return this.doc.updateLineCompiled(e.lineId,n,i,g,h,o,r),this.dag.registerLine(t,g,h),o&&c&&!p&&!f&&(e.results=[[c]],e.result=c,this.doc.markClean(e.lineId),this.checkpointer&&this.checkpointer.snapshot(t,e.lineId,h)),{...s,tier:3,result:c,results:o&&c&&!p&&!f?[[c]]:void 0,error:d}}restoreTo(e){this.checkpointer&&this.checkpointer.restoreTo(e);}getCheckpointer(){return this.checkpointer}getPageManager(){return this.pageManager}preloadNextPages(e){let t=this.pageManager.getPreloadTargets(e,this.doc);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}collectInvisibleCompileTargets(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef||i.isEmpty||l(i.text))continue;let{expressions:a}=this.extractExpressions(i);if(a.length!==0)for(let l of a)l.trim()&&t.push({lineId:i.lineId,expression:l,textHash:i.textHash});}return t}extractExpressions(e){if(e.expressions.length>0)return {expressions:e.expressions,inlineSolveCount:e.inlineSolveCount};let t=e.text.trim();if(t.length===0)return {expressions:[],inlineSolveCount:0};let n=c$1.findInlineSolves(e.text);return n.length>0?{expressions:n.map(r=>r.expression),inlineSolveCount:n.length}:{expressions:[t],inlineSolveCount:0}}};function ee(u){return typeof u.unit=="string"?u.unit:String(u.value)}function ie(u,e,t={inputType:"markdown"}){let n=u.getDocumentModel(),r=new R;r.setDocument(e);let s=new w(r,u);try{let i=r.lineCount;s.evaluate({startLine:1,endLine:i});let a=[],l=[],o=0;for(let c=1;c<=i;c++){let d=r.getLineAt(c),p=d.text,f=o,g=o+p.length;o=g+1;let h=d.inlineSolveCount>0,v=[],y=null,b=null;d.isEmpty||(h?v=m(p,c).map((L,m)=>{let x=d.results[m]?.[0]??null;if(x&&x.type===13){let E=ee(x);return l.push(`Line ${c}: ${E}`),{...L,result:null,error:E}}return {...L,result:x,error:null}}):(y=d.expressions[0]??null,b=d.result??null,b&&b.type===13&&l.push(`Line ${c}: ${ee(b)}`))),a.push({lineNumber:c,text:p,startPosition:f,endPosition:g,isEmpty:d.isEmpty,hasInlineSolves:h,inlineSolves:v,expression:y,error:null,result:b});}return {lines:a,totalLines:i,errors:l}}finally{s.terminateWorker(),u.setDocumentModel(n);}}export{R as a,Y as b,w as c,ie as d};//# sourceMappingURL=chunk-CHSO3DCS.js.map
3
- //# sourceMappingURL=chunk-CHSO3DCS.js.map
1
+ import {a}from'./chunk-RAF57WYO.js';import {l,m,g}from'./chunk-NUF66H57.js';import {b as b$1}from'./chunk-76F3LCIL.js';import {J,K}from'./chunk-2BXNZM3G.js';import {h,i,P as P$1}from'./chunk-IPSOWFCA.js';import {b}from'./chunk-HQ7BKXG7.js';import {c as c$1}from'./chunk-LM6ZQUEU.js';import {c,b as b$2}from'./chunk-BDF4VCQX.js';var P=class{constructor(){this.root=null;}get length(){return this.root?this.root.size:0}get isEmpty(){return this.root===null}getAt(e){if(!(e<0||e>=(this.root?.size??0)))return this.nodeAt(this.root,e).lineId}insertAt(e,t){let[n,r]=I(this.root,e);this.root=C(C(n,te(t)),r);}deleteAt(e){if(e<0||e>=(this.root?.size??0))return;let[t,n]=I(this.root,e),[r,s]=I(n,1),i=r?r.lineId:void 0;return this.root=C(t,s),i}spliceAt(e,t,n){let r=Math.max(0,e),s=Math.min(Math.max(0,t),(this.root?.size??0)-r),[i,a]=I(this.root,r),[l,o]=I(a,s),c=ne(l),d=B(n,0,n.length);return this.root=C(C(i,d),o),c}replaceAll(e){this.root=B(e,0,e.length);}getRange(e,t){let n=Math.max(0,e),r=Math.min((this.root?.size??0)-1,t);if(n>r)return [];let s=[];return this.collectRange(this.root,n,r,0,s),s}clear(){this.root=null;}*[Symbol.iterator](){yield*this.inOrder(this.root);}*inOrder(e){e&&(yield*this.inOrder(e.left),yield e.lineId,yield*this.inOrder(e.right));}nodeAt(e,t){let n=e.left?e.left.size:0;return t<n?this.nodeAt(e.left,t):t===n?e:this.nodeAt(e.right,t-n-1)}collectRange(e,t,n,r,s){if(!e)return;let i=e.left?e.left.size:0,a=r+i;a>t&&e.left&&this.collectRange(e.left,t,n,r,s),a>=t&&a<=n&&s.push(e.lineId),a<n&&e.right&&this.collectRange(e.right,t,n,a+1,s);}};function te(u){return {lineId:u,size:1,priority:Math.random(),left:null,right:null}}function T(u){u.size=1+(u.left?u.left.size:0)+(u.right?u.right.size:0);}function C(u,e){return u?e?u.priority>e.priority?(u.right=C(u.right,e),T(u),u):(e.left=C(u,e.left),T(e),e):u:e}function I(u,e){if(!u)return [null,null];let t=u.left?u.left.size:0;if(e<=t){let[n,r]=I(u.left,e);return u.left=r,T(u),[n,u]}else {let[n,r]=I(u.right,e-t-1);return u.right=n,T(u),[u,r]}}function ne(u){let e=[];return F(u,e),e}function F(u,e){u&&(F(u.left,e),e.push(u.lineId),F(u.right,e));}function B(u,e,t){if(e>=t)return null;let n=Math.floor((e+t)/2),r=re(n);return {lineId:u[n],size:t-e,priority:r,left:B(u,e,n),right:B(u,n+1,t)}}function re(u){let e=u;return e=(e>>16^e)*73244475,e=(e>>16^e)*73244475,e=e>>16^e,e/4294967295}var R=class{constructor(e=b.performance.maxDocumentLines){this.lines=new Map;this.orderTree=new P;this.nextLineId=1;this._positionCache=null;this.dirtyLineIds=new Set;this.maxLines=e;}setDocument(e){if(b$1(e,this.maxLines)>this.maxLines)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${this.maxLines.toLocaleString("en-US")} lines, which is the most the engine will hold at once`,{maxLines:this.maxLines});this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.dirtyLineIds.clear(),this.nextLineId=1;let n=e.split(`
2
+ `),r=new Array(n.length);for(let s=0;s<n.length;s++){let i=this.nextLineId++;r[s]=i,this.lines.set(i,{lineId:i,textHash:a(n[s]),text:n[s],expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:n[s].trim().length===0,inlineSolveCount:0});}this.orderTree.replaceAll(r);for(let s of r)this.dirtyLineIds.add(s);}applyChanges(e){let t=[],n=[],r=[...e].sort((s,i)=>i.startLine-s.startLine);for(let s of r){let i=s.startLine-1,a$1=[];for(let o of s.insertLines){let c=this.nextLineId++;a$1.push(c),t.push(c),this.lines.set(c,{lineId:c,textHash:a(o),text:o,expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:o.trim().length===0,inlineSolveCount:0});}for(let o of a$1)this.dirtyLineIds.add(o);let l=this.orderTree.spliceAt(i,s.deleteCount,a$1);for(let o of l)n.push(o),this.lines.delete(o),this.dirtyLineIds.delete(o);}return this._positionCache=null,{inserted:t,removed:n}}insertLines(e,t){let n={startLine:e,deleteCount:0,insertLines:t};return this.applyChanges([n]).inserted}deleteLines(e,t){let n={startLine:e,deleteCount:t-e+1,insertLines:[]};return this.applyChanges([n]).removed}editLine(e,t){let n=this.getLineAt(e);if(!n)return false;let r=a(t);return r===n.textHash?false:(n.text=t,n.textHash=r,n.expressions=[],n.bytecodes=[],n.results=[],n.result=null,n.inlineSolveCount=0,n.dirty=true,this.dirtyLineIds.add(n.lineId),n.isEmpty=t.trim().length===0,true)}getLineAt(e){let t=e-1,n=this.orderTree.getAt(t);if(n!==void 0)return this.lines.get(n)}getLinePosition(e){if(this._positionCache)return this._positionCache.get(e)??-1;this._positionCache=new Map;let t=1;for(let n of this.orderTree)this._positionCache.set(n,t++);return this._positionCache.get(e)??-1}getVisibleLines(e,t){let n=this.orderTree.getRange(e-1,t-1),r=[];for(let s of n){let i=this.lines.get(s);i&&r.push(i);}return r}getAllLines(){return this.getVisibleLines(1,this.lineCount)}getLineById(e){return this.lines.get(e)}getDirtyLines(){let e=[];for(let t of this.lines.values())t.dirty&&e.push(t);return e}hasAnyDirtyLineBefore(e){for(let t of this.dirtyLineIds){let n=this.getLinePosition(t);if(n>=1&&n<e)return true}return false}hasAnyDirtyVariableDefLineBefore(e){for(let t of this.dirtyLineIds){let n=this.lines.get(t);if(!n||!n.isVariableDef)continue;let r=this.getLinePosition(t);if(r>=1&&r<e)return true}return false}get dirtyCount(){return this.dirtyLineIds.size}isBytecodeValid(e,t){let n=this.lines.get(e);return n!==void 0&&n.textHash===t}markClean(e){let t=this.lines.get(e);t&&(t.dirty=false,this.dirtyLineIds.delete(e));}markDirtyByLineNumber(e){let t=this.getLineAt(e);t&&(t.dirty=true,this.dirtyLineIds.add(t.lineId));}markDirty(e){let t=this.lines.get(e);t&&(t.dirty=true,this.dirtyLineIds.add(e));}invalidateAll(){for(let e of this.lines.values())e.dirty=true;this.dirtyLineIds=new Set(this.lines.keys());}updateLineResult(e,t,n,r,s,i,a,l=0){let o=this.lines.get(e);o&&(o.results=t,o.result=t[0]?.[0]??null,o.bytecodes=n,o.expressions=r,o.reads=s,o.writes=i,o.isVariableDef=a,o.inlineSolveCount=l,o.dirty=false,this.dirtyLineIds.delete(e));}updateLineCompiled(e,t,n,r,s,i,a=0){let l=this.lines.get(e);l&&(l.expressions=t,l.bytecodes=n,l.reads=r,l.writes=s,l.isVariableDef=i,l.inlineSolveCount=a);}get lineCount(){return this.orderTree.length}get isEmpty(){return this.orderTree.isEmpty}*[Symbol.iterator](){for(let e of this.orderTree){let t=this.lines.get(e);t&&(yield t);}}clear(){this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.nextLineId=1;}toJSON(){return {lineCount:this.lineCount,lines:this.getAllLines().map(e=>({lineId:e.lineId,text:e.text.substring(0,80),textHash:e.textHash,dirty:e.dirty,isVariableDef:e.isVariableDef,isEmpty:e.isEmpty,hasBytecode:e.bytecodes.length>0,hasResult:e.results.length>0,inlineSolveCount:e.inlineSolveCount,reads:e.reads,writes:e.writes}))}}};var A=class{constructor(){this.worker=null;this.nextId=1;this.pending=new Map;}ensureWorker(){return this.worker?this.worker:(this.worker=g(),this.worker.onmessage=e=>{let t=e.data;if(!t||t.type!=="COMPILE_RESULT")return;let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id);let r=[];for(let s of t.results)r.push(this.reconstructResult(s));n.resolve(r);},this.worker.onerror=e=>{for(let[t,n]of this.pending)n.reject(new Error(`Compilation worker error: ${e.message}`)),this.pending.delete(t);},this.worker)}async compileBatch(e){if(e.length===0)return [];let t=this.ensureWorker(),n=this.nextId++;return new Promise((r,s)=>{this.pending.set(n,{resolve:r,reject:s}),t.postMessage({type:"COMPILE_BATCH",id:n,items:e});})}storeResults(e,t){let n=new Map;for(let i of e){if(i.error)continue;let a=t.getLineById(i.lineId);if(!a||a.textHash!==i.compiledAgainstHash)continue;let l=n.get(i.lineId);l||(l={bytecodes:[],reads:new Set,writes:new Set,isVariableDef:false,expressions:a.expressions.length>0?[...a.expressions]:[],textHash:i.compiledAgainstHash},n.set(i.lineId,l)),l.bytecodes.push(i.program);for(let o of i.reads)l.reads.add(o);for(let o of i.writes)l.writes.add(o);i.isVariableDef&&(l.isVariableDef=true);}let s=0;for(let[i,a]of n){if(a.bytecodes.length===0)continue;let o=t.getLineById(i)?.inlineSolveCount??0;t.updateLineCompiled(i,a.expressions,a.bytecodes,[...a.reads],[...a.writes],a.isVariableDef,o),s+=a.bytecodes.length;}return s}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.pending.clear());}get isActive(){return this.worker!==null}reconstructResult(e){if(e.error)return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},reads:[],writes:[],isVariableDef:false,error:e.error};let t=e.opcodesLength>0?new Uint8Array(e.opcodesBuffer,0,e.opcodesLength):new Uint8Array(0),n=e.numbersLength>0?new Float64Array(e.numbersBuffer,0,e.numbersLength):new Float64Array(0),r={opcodes:t,numbers:n,strings:e.strings,hasAsync:false};return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:r,reads:e.reads,writes:e.writes,isVariableDef:e.isVariableDef,error:null}}};var U=128,k=3,Z=6,Q=2,X=k,H=class u{constructor(){this.lastViewportStart=null;this.savedDirection=null;this.pageAccess=new Map;this.accessSeq=0;}static pageForLine(e){return Math.floor((e-1)/U)}static pageRange(e,t){return {startLine:e*U+1,endLine:Math.min((e+1)*U,t)}}detectDirection(e){return this.lastViewportStart===null?null:e.startLine>this.lastViewportStart?"down":e.startLine<this.lastViewportStart?"up":null}maintainAfterEval(e,t){this.savedDirection=this.detectDirection(e),this.lastViewportStart=e.startLine;let n=t.lineCount,r=u.pageForLine(e.startLine),s=u.pageForLine(e.endLine),i=u.pageForLine(n),a=Math.max(0,r-k),l=Math.min(i,s+k),o=Math.max(0,r-Z),c=Math.min(i,s+Z);for(let h=a;h<=l;h++)this.touchPage(h);for(let h=o;h<=c;h++)h>=a&&h<=l||this.evictPageResults(h,t,n);let d=o-1,p=Math.max(0,d-X+1);for(let h=p;h<=d;h++)this.evictPageBytecode(h,t,n);let f=c+1,g=Math.min(i,f+X-1);for(let h=f;h<=g;h++)this.evictPageBytecode(h,t,n);}getPreloadTargets(e,t){let n=this.savedDirection;if(!n)return [];let r=[],s=u.pageForLine(e.endLine),i=u.pageForLine(e.startLine),a=u.pageForLine(t.lineCount),l=[];if(n==="down"){let o=s+k+1,c=Math.min(o+Q-1,a);for(let d=o;d<=c&&d<=a;d++)l.push(d);}else {let o=i-k-1;for(let c=o;c>o-Q&&c>=0;c--)l.push(c);}for(let o of l){let c=u.pageRange(o,t.lineCount);for(let d=c.startLine;d<=c.endLine;d++){let p=t.getLineAt(d);if(p&&p.dirty&&!(p.bytecodes.length>0&&!p.isVariableDef)&&!p.isEmpty)if(p.expressions.length>0)for(let f of p.expressions)f.trim()&&r.push({lineId:p.lineId,expression:f,textHash:p.textHash});else {let f=c$1.findInlineSolves(p.text);if(f.length>0)for(let g of f)g.expression.trim()&&r.push({lineId:p.lineId,expression:g.expression,textHash:p.textHash});else {let g=p.text.trim();g&&r.push({lineId:p.lineId,expression:g,textHash:p.textHash});}}}}return r}clear(){this.pageAccess.clear(),this.accessSeq=0,this.lastViewportStart=null,this.savedDirection=null;}touchPage(e){this.pageAccess.set(e,++this.accessSeq);}evictPageResults(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);i&&!i.isVariableDef&&i.results.length>0&&(i.results=[],i.result=null);}}evictPageBytecode(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);!i||i.isVariableDef||(i.bytecodes.length>0||i.results.length>0)&&(i.bytecodes=[],i.results=[],i.result=null,t.markDirty(i.lineId));}}};var Y=(r=>(r[r.Tier1=1]="Tier1",r[r.Tier2=2]="Tier2",r[r.Tier3=3]="Tier3",r[r.Skipped=0]="Skipped",r))(Y||{}),w=class{constructor(e,t,n){this.compilationWorker=null;this.globalUnsubscribe=null;this.doc=e,this.engine=t,this.dag=t.getDag(),this.checkpointer=n??null,this.pageManager=new H,this.engine.setDocumentModel(this.doc),this.globalUnsubscribe=J.subscribe(r=>{for(let s of this.dag.getAffectedLines(K(r)))this.doc.markDirtyByLineNumber(s);});}evaluate(e,t){this.engine.setKeystrokeSignal(t??null),h();try{this.reseedAccumulators();let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(e.endLine,i);for(let l=1;l<=a;l++){let o=this.doc.getLineAt(l);if(!o){s.skipped++;continue}let c=l>=e.startLine&&l<=e.endLine,d=this.evaluateSingleLine(o,l,c);n.push(d),d.tier===1?s.tier1++:d.tier===2?s.tier2++:d.tier===3?s.tier3++:s.skipped++,d.results&&c&&r.set(l,d.results.flat());}return this.pageManager.maintainAfterEval(e,this.doc),{lines:n,resultMap:r,tierCounts:s}}finally{this.engine.setKeystrokeSignal(null),i();}}backgroundCompile(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef)continue;let a=this.evaluateSingleLine(i,s,false);t.push(a);}return t}dispatchBackgroundCompiles(e){let t=this.collectInvisibleCompileTargets(e);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}terminateWorker(){this.compilationWorker&&(this.compilationWorker.terminate(),this.compilationWorker=null),this.globalUnsubscribe&&(this.globalUnsubscribe(),this.globalUnsubscribe=null);}getDoc(){return this.doc}evaluateAll(e){let t={startLine:1,endLine:this.doc.lineCount};return this.evaluate(t,e)}setViewport(e,t){if(this.engine.setKeystrokeSignal(t??null),e.startLine>1&&this.hasDirtyLinesBefore(e.startLine))return this.checkpointer?.clear(),this.evaluate(e,t);this.pageManager.maintainAfterEval(e,this.doc),this.preloadNextPages(e),this.restoreTo(e.startLine-1),h();try{return this.collectEvalResults(e.startLine,e.endLine)}finally{this.engine.setKeystrokeSignal(null),i();}}applyTransaction(e){let t=new Set;for(let s of e)for(let i=0;i<s.deleteCount;i++){let a=s.startLine+i,l=this.dag.getWrites(a);for(let o of l)t.add(o);this.dag.removeLine(a),this.engine.getLineCache().removeAllForLine(a);}let n=new Set;for(let s of t){let i=this.dag.getAffectedLines(s);for(let a of i){let l=this.doc.getLineAt(a);l&&n.add(l.lineId);}}let r=this.doc.applyChanges(e);this.checkpointer?.clear();for(let s of n)this.doc.markDirty(s);return this.dag.clear(),{inserted:r.inserted,removed:r.removed}}reseedAccumulators(){let e=this.engine.resetAccumulators();if(e.size===0)return;let t=this.doc.lineCount;for(let n=1;n<=t;n++){let r=this.dag.getWrites(n);if(r.size!==0){for(let s of r)if(e.has(s)){this.doc.markDirtyByLineNumber(n);break}}}}collectEvalResults(e,t){let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(t,i);for(let l=e;l<=a;l++){let o=this.doc.getLineAt(l);if(!o)continue;let c=this.evaluateSingleLine(o,l,true);n.push(c),c.tier===1?s.tier1++:c.tier===2?s.tier2++:c.tier===3?s.tier3++:s.skipped++,c.results&&r.set(l,c.results.flat());}return {lines:n,resultMap:r,tierCounts:s}}hasDirtyLinesBefore(e){return this.doc.hasAnyDirtyVariableDefLineBefore(e)}evaluateSingleLine(e,t,n){let r={lineId:e.lineId,lineNumber:t};if(e.isEmpty||l(e.text))return e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null};let{expressions:s,inlineSolveCount:i}=this.extractExpressions(e);return s.length===0?(e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null}):e.dirty?n?this.evaluateTier1(e,t,s,i,r):e.bytecodes.length>0&&e.bytecodes.length===s.length&&!e.isVariableDef?{...r,tier:0,result:null,error:null}:this.evaluateTier3(e,t,s,i,r):n&&e.bytecodes.length>0?this.evaluateTier2(e,t,r):{...r,tier:0,result:null,error:null}}evaluateTier1(e,t,n,r,s){let i=[],a=[],l=new Set,o=new Set,c=false,d=null,p=null,f=false,g=false;for(let y of n){if(!y.trim())continue;let b=null,L;try{let m=this.engine.evaluateLine(t,y);b=[m],d=m,L=this.engine.getLineCache().get(t,y);}catch(m){let x=m instanceof Error?m.message:String(m);p||(p=x),f=true,b=null;}if(b&&b.some(m=>m.type===12)&&(g=true),b?i.push(b):i.push([P$1("eval_failed",p??"unknown error")]),L){a.push(L.bytecode);for(let m of L.readVariables)l.add(m);L.writeVariable&&(o.add(L.writeVariable),c=true);}else try{let{program:m,reads:x,writes:E}=this.engine.compileExpression(y);a.push(m);for(let S of x)l.add(S);for(let S of E)o.add(S);E.length>0&&(c=!0);}catch(m){if(a.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),m instanceof b$2&&m.context){let x=m.context.reads,E=m.context.writes;if(Array.isArray(x))for(let S of x)l.add(S);if(Array.isArray(E))for(let S of E)o.add(S);}}}let h=[...l],v=[...o];return f||g?(this.doc.updateLineCompiled(e.lineId,n,a,h,v,c,r),e.results=i,e.result=i[0]?.[0]??null,e.inlineSolveCount=r,e.expressions=n):this.doc.updateLineResult(e.lineId,i,a,n,h,v,c,r),this.dag.registerLine(t,h,v),this.checkpointer&&v.length>0&&!f&&!g&&this.checkpointer.snapshot(t,e.lineId,v),{...s,tier:1,result:d,results:i,error:p}}evaluateTier2(e,t,n){if(e.bytecodes.length===0)return {...n,tier:0,result:null,error:null};let r=[],s=null,i=null,a=false;for(let l of e.bytecodes)if(l.opcodes.length!==0)try{let o=this.engine.executeCached(l,t);s=o,r.push([o]);}catch(o){let c=o instanceof Error?o.message:String(o);i||(i=c),a=true,r.push([P$1("exec_failed",c)]);}return this.dag.registerLine(t,e.reads,e.writes),e.results=r,e.result=r[0]?.[0]??null,a&&this.doc.markDirty(e.lineId),{...n,tier:2,result:s,results:r,error:i}}evaluateTier3(e,t,n,r,s){let i=[],a=new Set,l=new Set,o=false,c=null,d=null,p=false,f=false;for(let v of n)if(v.trim())try{let{program:y,reads:b,writes:L}=this.engine.compileExpression(v);i.push(y);for(let m of b)a.add(m);for(let m of L)l.add(m);L.length>0&&(o=!0),L.length>0&&y.opcodes.length>0&&(c=this.engine.executeCached(y,t),c&&c.type===12&&(f=!0));}catch(y){let b=y instanceof Error?y.message:String(y);d||(d=b),p=true,i.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false});}let g=[...a],h=[...l];return this.doc.updateLineCompiled(e.lineId,n,i,g,h,o,r),this.dag.registerLine(t,g,h),o&&c&&!p&&!f&&(e.results=[[c]],e.result=c,this.doc.markClean(e.lineId),this.checkpointer&&this.checkpointer.snapshot(t,e.lineId,h)),{...s,tier:3,result:c,results:o&&c&&!p&&!f?[[c]]:void 0,error:d}}restoreTo(e){this.checkpointer&&this.checkpointer.restoreTo(e);}getCheckpointer(){return this.checkpointer}getPageManager(){return this.pageManager}preloadNextPages(e){let t=this.pageManager.getPreloadTargets(e,this.doc);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}collectInvisibleCompileTargets(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef||i.isEmpty||l(i.text))continue;let{expressions:a}=this.extractExpressions(i);if(a.length!==0)for(let l of a)l.trim()&&t.push({lineId:i.lineId,expression:l,textHash:i.textHash});}return t}extractExpressions(e){if(e.expressions.length>0)return {expressions:e.expressions,inlineSolveCount:e.inlineSolveCount};let t=e.text.trim();if(t.length===0)return {expressions:[],inlineSolveCount:0};let n=c$1.findInlineSolves(e.text);return n.length>0?{expressions:n.map(r=>r.expression),inlineSolveCount:n.length}:{expressions:[t],inlineSolveCount:0}}};function ee(u){return typeof u.unit=="string"?u.unit:String(u.value)}function ie(u,e,t={inputType:"markdown"}){let n=u.getDocumentModel(),r=new R;r.setDocument(e);let s=new w(r,u);try{let i=r.lineCount;s.evaluate({startLine:1,endLine:i});let a=[],l=[],o=0;for(let c=1;c<=i;c++){let d=r.getLineAt(c),p=d.text,f=o,g=o+p.length;o=g+1;let h=d.inlineSolveCount>0,v=[],y=null,b=null;d.isEmpty||(h?v=m(p,c).map((L,m)=>{let x=d.results[m]?.[0]??null;if(x&&x.type===13){let E=ee(x);return l.push(`Line ${c}: ${E}`),{...L,result:null,error:E}}return {...L,result:x,error:null}}):(y=d.expressions[0]??null,b=d.result??null,b&&b.type===13&&l.push(`Line ${c}: ${ee(b)}`))),a.push({lineNumber:c,text:p,startPosition:f,endPosition:g,isEmpty:d.isEmpty,hasInlineSolves:h,inlineSolves:v,expression:y,error:null,result:b});}return {lines:a,totalLines:i,errors:l}}finally{s.terminateWorker(),u.setDocumentModel(n);}}export{R as a,Y as b,w as c,ie as d};//# sourceMappingURL=chunk-7EP36NXE.js.map
3
+ //# sourceMappingURL=chunk-7EP36NXE.js.map