solve-engine 1.0.0-beta.7 → 1.0.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 (205) hide show
  1. package/dist/{BytecodeBuilder-3egMyuDi.d.cts → BytecodeBuilder-B0xskcv5.d.cts} +2 -1
  2. package/dist/{BytecodeBuilder-3egMyuDi.d.ts → BytecodeBuilder-B0xskcv5.d.ts} +2 -1
  3. package/dist/{Configuration-fVpd-HC-.d.cts → Configuration-B-G5gTRn.d.cts} +107 -29
  4. package/dist/{Configuration-fVpd-HC-.d.ts → Configuration-B-G5gTRn.d.ts} +107 -29
  5. package/dist/{EngineError-DvPSnhZi.d.cts → EngineError-LU7W7AgI.d.cts} +96 -16
  6. package/dist/{EngineError-DvPSnhZi.d.ts → EngineError-LU7W7AgI.d.ts} +96 -16
  7. package/dist/{Lexer-W9MBOP0V.d.ts → Lexer-BN5mt30n.d.ts} +16 -0
  8. package/dist/{Lexer-Cfm79Dak.d.cts → Lexer-D78E2yDW.d.cts} +16 -0
  9. package/dist/{PackageRegistry-CjDt-Jy_.d.ts → PackageRegistry-DFeINv2O.d.ts} +54 -13
  10. package/dist/{PackageRegistry-pHtKythi.d.cts → PackageRegistry-u2zdfFaj.d.cts} +54 -13
  11. package/dist/{Parselet-DEdF9I7n.d.ts → Parselet-BaySkMV3.d.ts} +37 -5
  12. package/dist/{Parselet-Cu0bLSis.d.cts → Parselet-DuI1Pjiq.d.cts} +37 -5
  13. package/dist/{ScopeManager-CKfQtl7l.d.cts → ScopeManager-B6GzdhVG.d.cts} +75 -6
  14. package/dist/{ScopeManager-B5k0nk05.d.ts → ScopeManager-udv4Twwq.d.ts} +75 -6
  15. package/dist/{VMCheckpoints-BmDwIXgK.d.ts → VMCheckpoints-BiaIlOOY.d.ts} +4 -4
  16. package/dist/{VMCheckpoints-CqFuLwrT.d.cts → VMCheckpoints-DwLjivM7.d.cts} +4 -4
  17. package/dist/{Value-KtAQNHur.d.cts → Value-CXJqDH9J.d.cts} +5 -2
  18. package/dist/{Value-KtAQNHur.d.ts → Value-CXJqDH9J.d.ts} +5 -2
  19. package/dist/{chunk-CSG5XVNJ.cjs → chunk-3AFRJYP4.cjs} +556 -414
  20. package/dist/chunk-3AFRJYP4.cjs.map +1 -0
  21. package/dist/chunk-3BOK2LDK.js +17 -0
  22. package/dist/chunk-3BOK2LDK.js.map +1 -0
  23. package/dist/{chunk-6RDSQURE.js → chunk-3D7V24DG.js} +57 -6
  24. package/dist/chunk-3D7V24DG.js.map +1 -0
  25. package/dist/{chunk-MEOHSQEH.js → chunk-3LAEG75D.js} +47 -15
  26. package/dist/chunk-3LAEG75D.js.map +1 -0
  27. package/dist/{chunk-P75775WC.js → chunk-3VNGREMU.js} +118 -41
  28. package/dist/chunk-3VNGREMU.js.map +1 -0
  29. package/dist/{chunk-4AVD7NZW.cjs → chunk-4B2CNWQU.cjs} +13 -7
  30. package/dist/chunk-4B2CNWQU.cjs.map +1 -0
  31. package/dist/{chunk-6GCKCWLB.js → chunk-526PMQOA.js} +126 -69
  32. package/dist/chunk-526PMQOA.js.map +1 -0
  33. package/dist/{chunk-2CS6OMZK.js → chunk-5F4C26RU.js} +8 -5
  34. package/dist/chunk-5F4C26RU.js.map +1 -0
  35. package/dist/{chunk-M4N5GA5Z.cjs → chunk-5KMIY374.cjs} +57 -6
  36. package/dist/chunk-5KMIY374.cjs.map +1 -0
  37. package/dist/{chunk-R24DI24X.cjs → chunk-5LI5EPGJ.cjs} +6 -5
  38. package/dist/chunk-5LI5EPGJ.cjs.map +1 -0
  39. package/dist/{chunk-BAMZT3GL.js → chunk-5WVP4YHP.js} +939 -134
  40. package/dist/chunk-5WVP4YHP.js.map +1 -0
  41. package/dist/{chunk-MZOVP3WI.cjs → chunk-6KFYJ6TD.cjs} +3 -2
  42. package/dist/chunk-6KFYJ6TD.cjs.map +1 -0
  43. package/dist/{chunk-BXKJLM5R.cjs → chunk-6WFMPTGB.cjs} +972 -636
  44. package/dist/chunk-6WFMPTGB.cjs.map +1 -0
  45. package/dist/{chunk-2MV4HBKC.cjs → chunk-A2N2GFCG.cjs} +10 -10
  46. package/dist/{chunk-2MV4HBKC.cjs.map → chunk-A2N2GFCG.cjs.map} +1 -1
  47. package/dist/chunk-ADBA3XBE.cjs +20 -0
  48. package/dist/chunk-ADBA3XBE.cjs.map +1 -0
  49. package/dist/{chunk-MBNQVDVC.cjs → chunk-AMOJYLG2.cjs} +16 -10
  50. package/dist/chunk-AMOJYLG2.cjs.map +1 -0
  51. package/dist/{chunk-CLVQBF5C.cjs → chunk-AQNHHJMJ.cjs} +5 -5
  52. package/dist/{chunk-CLVQBF5C.cjs.map → chunk-AQNHHJMJ.cjs.map} +1 -1
  53. package/dist/{chunk-AHCLWAM5.cjs → chunk-BHTNFEGZ.cjs} +13 -13
  54. package/dist/chunk-BHTNFEGZ.cjs.map +1 -0
  55. package/dist/{chunk-35IWNZPJ.cjs → chunk-E4NUZXVK.cjs} +58 -27
  56. package/dist/chunk-E4NUZXVK.cjs.map +1 -0
  57. package/dist/{chunk-P33SBYGG.js → chunk-GLG5ZMX7.js} +54 -23
  58. package/dist/chunk-GLG5ZMX7.js.map +1 -0
  59. package/dist/{chunk-BVAR5J2F.js → chunk-GQCOSXMG.js} +117 -6
  60. package/dist/chunk-GQCOSXMG.js.map +1 -0
  61. package/dist/{chunk-QDMPOAI7.cjs → chunk-HDP7VK3C.cjs} +1118 -313
  62. package/dist/chunk-HDP7VK3C.cjs.map +1 -0
  63. package/dist/{chunk-GVWHCL2N.js → chunk-HMOISHXR.js} +217 -75
  64. package/dist/chunk-HMOISHXR.js.map +1 -0
  65. package/dist/{chunk-MTX2KVU7.cjs → chunk-HVQFNJKE.cjs} +122 -90
  66. package/dist/chunk-HVQFNJKE.cjs.map +1 -0
  67. package/dist/{chunk-OC6LTXYS.cjs → chunk-JMXUNXQS.cjs} +126 -7
  68. package/dist/chunk-JMXUNXQS.cjs.map +1 -0
  69. package/dist/{chunk-WWOLFXTX.cjs → chunk-KBSXGXPM.cjs} +10 -7
  70. package/dist/chunk-KBSXGXPM.cjs.map +1 -0
  71. package/dist/{chunk-YU2CUNFO.js → chunk-KV7UW6T6.js} +11 -5
  72. package/dist/chunk-KV7UW6T6.js.map +1 -0
  73. package/dist/{chunk-CCJPSHGI.cjs → chunk-N7FNVFXW.cjs} +4 -12
  74. package/dist/chunk-N7FNVFXW.cjs.map +1 -0
  75. package/dist/{chunk-CYFK5SY2.js → chunk-O3ANBHSA.js} +169 -39
  76. package/dist/chunk-O3ANBHSA.js.map +1 -0
  77. package/dist/{chunk-NZFKROS7.cjs → chunk-PA4VC73I.cjs} +130 -72
  78. package/dist/chunk-PA4VC73I.cjs.map +1 -0
  79. package/dist/{chunk-NJTXJ5AG.cjs → chunk-PFUESQTW.cjs} +18 -18
  80. package/dist/{chunk-NJTXJ5AG.cjs.map → chunk-PFUESQTW.cjs.map} +1 -1
  81. package/dist/{chunk-SFQWJMKT.js → chunk-QY25VWBF.js} +51 -12
  82. package/dist/chunk-QY25VWBF.js.map +1 -0
  83. package/dist/{chunk-WC5FFSHB.js → chunk-R3PY4G7J.js} +3 -3
  84. package/dist/{chunk-WC5FFSHB.js.map → chunk-R3PY4G7J.js.map} +1 -1
  85. package/dist/{chunk-M5E34VG5.js → chunk-SBUFNJVE.js} +3 -3
  86. package/dist/{chunk-M5E34VG5.js.map → chunk-SBUFNJVE.js.map} +1 -1
  87. package/dist/{chunk-UKPGSAZW.js → chunk-TMA4RCEN.js} +3 -3
  88. package/dist/{chunk-UKPGSAZW.js.map → chunk-TMA4RCEN.js.map} +1 -1
  89. package/dist/{chunk-V6HA6JJZ.cjs → chunk-U5VAY32K.cjs} +215 -138
  90. package/dist/chunk-U5VAY32K.cjs.map +1 -0
  91. package/dist/{chunk-DUEZFTK2.js → chunk-UKQHXPGW.js} +4 -12
  92. package/dist/chunk-UKQHXPGW.js.map +1 -0
  93. package/dist/{chunk-4CVLFLOB.cjs → chunk-UM6BVY2S.cjs} +201 -69
  94. package/dist/chunk-UM6BVY2S.cjs.map +1 -0
  95. package/dist/{chunk-75JP4BZX.js → chunk-UQ3UIZJC.js} +3 -2
  96. package/dist/chunk-UQ3UIZJC.js.map +1 -0
  97. package/dist/{chunk-PCPX42KL.js → chunk-V4XG5QF6.js} +16 -10
  98. package/dist/chunk-V4XG5QF6.js.map +1 -0
  99. package/dist/{chunk-GPPLSM2Z.js → chunk-VB37OC6I.js} +6 -5
  100. package/dist/chunk-VB37OC6I.js.map +1 -0
  101. package/dist/{chunk-MVBEL57Q.js → chunk-Y7FT4IQT.js} +500 -170
  102. package/dist/chunk-Y7FT4IQT.js.map +1 -0
  103. package/dist/{chunk-OFXOTECC.js → chunk-YPPPYLSR.js} +7 -7
  104. package/dist/chunk-YPPPYLSR.js.map +1 -0
  105. package/dist/{chunk-M4F66R4O.cjs → chunk-YWQ6V4ZN.cjs} +121 -82
  106. package/dist/chunk-YWQ6V4ZN.cjs.map +1 -0
  107. package/dist/constants.cjs +5 -5
  108. package/dist/constants.d.cts +1 -1
  109. package/dist/constants.d.ts +1 -1
  110. package/dist/constants.js +2 -2
  111. package/dist/engine.cjs +31 -31
  112. package/dist/engine.d.cts +11 -11
  113. package/dist/engine.d.ts +11 -11
  114. package/dist/engine.js +21 -21
  115. package/dist/errors.cjs +19 -19
  116. package/dist/errors.d.cts +2 -2
  117. package/dist/errors.d.ts +2 -2
  118. package/dist/errors.js +1 -1
  119. package/dist/format.cjs +29 -22
  120. package/dist/format.cjs.map +1 -1
  121. package/dist/format.d.cts +1 -2
  122. package/dist/format.d.ts +1 -2
  123. package/dist/format.js +23 -16
  124. package/dist/format.js.map +1 -1
  125. package/dist/index.cjs +31 -31
  126. package/dist/index.d.cts +10 -10
  127. package/dist/index.d.ts +10 -10
  128. package/dist/index.js +22 -22
  129. package/dist/language.cjs +8 -8
  130. package/dist/language.cjs.map +1 -1
  131. package/dist/language.d.cts +10 -10
  132. package/dist/language.d.ts +10 -10
  133. package/dist/language.js +6 -6
  134. package/dist/language.js.map +1 -1
  135. package/dist/lexer.cjs +18 -18
  136. package/dist/lexer.d.cts +2 -2
  137. package/dist/lexer.d.ts +2 -2
  138. package/dist/lexer.js +6 -6
  139. package/dist/normalizer.cjs +12 -12
  140. package/dist/normalizer.js +6 -6
  141. package/dist/packages.cjs +39 -39
  142. package/dist/packages.d.cts +9 -9
  143. package/dist/packages.d.ts +9 -9
  144. package/dist/packages.js +16 -16
  145. package/dist/parser.cjs +15 -15
  146. package/dist/parser.d.cts +23 -9
  147. package/dist/parser.d.ts +23 -9
  148. package/dist/parser.js +5 -5
  149. package/dist/{pipeline-CrsRPmsv.d.ts → pipeline-B6k5lCB7.d.ts} +1 -1
  150. package/dist/{pipeline-DPUQt7yL.d.cts → pipeline-BEb3hujr.d.cts} +1 -1
  151. package/dist/resolvers.d.cts +2 -2
  152. package/dist/resolvers.d.ts +2 -2
  153. package/dist/uom.cjs +17 -17
  154. package/dist/uom.d.cts +2 -2
  155. package/dist/uom.d.ts +2 -2
  156. package/dist/uom.js +7 -7
  157. package/dist/utilities.cjs +8 -4
  158. package/dist/utilities.d.cts +19 -3
  159. package/dist/utilities.d.ts +19 -3
  160. package/dist/utilities.js +2 -2
  161. package/dist/vm.cjs +43 -31
  162. package/dist/vm.d.cts +105 -9
  163. package/dist/vm.d.ts +105 -9
  164. package/dist/vm.js +9 -9
  165. package/package.json +1 -1
  166. package/dist/chunk-2CS6OMZK.js.map +0 -1
  167. package/dist/chunk-35IWNZPJ.cjs.map +0 -1
  168. package/dist/chunk-4AVD7NZW.cjs.map +0 -1
  169. package/dist/chunk-4CVLFLOB.cjs.map +0 -1
  170. package/dist/chunk-6GCKCWLB.js.map +0 -1
  171. package/dist/chunk-6RDSQURE.js.map +0 -1
  172. package/dist/chunk-75JP4BZX.js.map +0 -1
  173. package/dist/chunk-AHCLWAM5.cjs.map +0 -1
  174. package/dist/chunk-BAMZT3GL.js.map +0 -1
  175. package/dist/chunk-BVAR5J2F.js.map +0 -1
  176. package/dist/chunk-BXKJLM5R.cjs.map +0 -1
  177. package/dist/chunk-CCJPSHGI.cjs.map +0 -1
  178. package/dist/chunk-CSG5XVNJ.cjs.map +0 -1
  179. package/dist/chunk-CYFK5SY2.js.map +0 -1
  180. package/dist/chunk-DUEZFTK2.js.map +0 -1
  181. package/dist/chunk-GPPLSM2Z.js.map +0 -1
  182. package/dist/chunk-GVWHCL2N.js.map +0 -1
  183. package/dist/chunk-M4F66R4O.cjs.map +0 -1
  184. package/dist/chunk-M4N5GA5Z.cjs.map +0 -1
  185. package/dist/chunk-MBNQVDVC.cjs.map +0 -1
  186. package/dist/chunk-MEOHSQEH.js.map +0 -1
  187. package/dist/chunk-MTX2KVU7.cjs.map +0 -1
  188. package/dist/chunk-MVBEL57Q.js.map +0 -1
  189. package/dist/chunk-MZOVP3WI.cjs.map +0 -1
  190. package/dist/chunk-N5YFR4UP.cjs +0 -10
  191. package/dist/chunk-N5YFR4UP.cjs.map +0 -1
  192. package/dist/chunk-NZFKROS7.cjs.map +0 -1
  193. package/dist/chunk-OC6LTXYS.cjs.map +0 -1
  194. package/dist/chunk-OFXOTECC.js.map +0 -1
  195. package/dist/chunk-P33SBYGG.js.map +0 -1
  196. package/dist/chunk-P75775WC.js.map +0 -1
  197. package/dist/chunk-PCPX42KL.js.map +0 -1
  198. package/dist/chunk-PFSDGGYL.js +0 -8
  199. package/dist/chunk-PFSDGGYL.js.map +0 -1
  200. package/dist/chunk-QDMPOAI7.cjs.map +0 -1
  201. package/dist/chunk-R24DI24X.cjs.map +0 -1
  202. package/dist/chunk-SFQWJMKT.js.map +0 -1
  203. package/dist/chunk-V6HA6JJZ.cjs.map +0 -1
  204. package/dist/chunk-WWOLFXTX.cjs.map +0 -1
  205. package/dist/chunk-YU2CUNFO.js.map +0 -1
@@ -0,0 +1,17 @@
1
+ // src/utilities/Strings.ts
2
+ function stripQuotes(value) {
3
+ return value.startsWith('"') && value.endsWith('"') && value.length >= 2 ? value.slice(1, -1) : value;
4
+ }
5
+ function countLines(text, stopAfter = Number.MAX_SAFE_INTEGER) {
6
+ let count = 1;
7
+ let index = text.indexOf("\n");
8
+ while (index !== -1) {
9
+ if (++count > stopAfter) return count;
10
+ index = text.indexOf("\n", index + 1);
11
+ }
12
+ return count;
13
+ }
14
+
15
+ export { countLines, stripQuotes };
16
+ //# sourceMappingURL=chunk-3BOK2LDK.js.map
17
+ //# sourceMappingURL=chunk-3BOK2LDK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utilities/Strings.ts"],"names":[],"mappings":";AASO,SAAS,YAAY,KAAA,EAAuB;AAClD,EAAA,OAAO,KAAA,CAAM,UAAA,CAAW,GAAG,CAAA,IAAK,MAAM,QAAA,CAAS,GAAG,CAAA,IAAK,KAAA,CAAM,UAAU,CAAA,GACpE,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,GACjB,KAAA;AACJ;AAeO,SAAS,UAAA,CAAW,IAAA,EAAc,SAAA,GAAoB,MAAA,CAAO,gBAAA,EAA0B;AAC7F,EAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,EAAA,IAAI,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,IAAI,CAAA;AAC7B,EAAA,OAAO,UAAU,EAAA,EAAI;AACpB,IAAA,IAAI,EAAE,KAAA,GAAQ,SAAA,EAAW,OAAO,KAAA;AAChC,IAAA,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,KAAA,GAAQ,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,KAAA;AACR","file":"chunk-3BOK2LDK.js","sourcesContent":["/**\n * Strips a single layer of matching double quotes from a string, if present.\n * Returns the input unchanged if it isn't fully wrapped in quotes.\n *\n * Was needed for STRING token values, which the lexer used to emit with their\n * surrounding `\"...\"` quotes still attached. `tokenizeString()` now strips them\n * when it builds the token, so on that path this is a no-op kept as a defence\n * against text arriving from somewhere else already quoted.\n */\nexport function stripQuotes(value: string): string {\n\treturn value.startsWith('\"') && value.endsWith('\"') && value.length >= 2\n\t\t? value.slice(1, -1)\n\t\t: value;\n}\n\n/**\n * How many lines `text` has, without splitting it into an array.\n *\n * `split(\"\\n\").length` answers the same question and allocates the whole\n * document to do it, which is the wrong shape for a caller whose next move may\n * be to refuse the document for being too large. Counting stops as soon as the\n * answer is \"more than the caller cares about\".\n *\n * @param text - The document.\n * @param stopAfter - Stop counting once past this many lines.\n * @returns The line count, or `stopAfter + 1` for anything longer. A document\n * with no newline in it is one line, matching `split`.\n */\nexport function countLines(text: string, stopAfter: number = Number.MAX_SAFE_INTEGER): number {\n\tlet count = 1;\n\tlet index = text.indexOf(\"\\n\");\n\twhile (index !== -1) {\n\t\tif (++count > stopAfter) return count;\n\t\tindex = text.indexOf(\"\\n\", index + 1);\n\t}\n\treturn count;\n}\n"]}
@@ -93,7 +93,7 @@ var ErrorFactory = class _ErrorFactory {
93
93
  return _ErrorFactory.build("EXTERNAL" /* EXTERNAL */, true, codeOrInit, message, context);
94
94
  }
95
95
  static internal(codeOrInit, message, context) {
96
- return _ErrorFactory.build("INTERNAL" /* INTERNAL */, false, codeOrInit, message, context);
96
+ return _ErrorFactory.build("INTERNAL" /* INTERNAL */, true, codeOrInit, message, context);
97
97
  }
98
98
  static config(codeOrInit, message, context) {
99
99
  return _ErrorFactory.build("CONFIG" /* CONFIG */, false, codeOrInit, message, context);
@@ -106,13 +106,15 @@ function normalizeUnknownError(error) {
106
106
  code: "UNEXPECTED_ERROR",
107
107
  message: error.message,
108
108
  context: { originalErrorName: error.name },
109
- cause: error
109
+ cause: error,
110
+ recoverable: true
110
111
  });
111
112
  }
112
113
  return ErrorFactory.internal({
113
114
  code: "UNKNOWN_ERROR",
114
115
  message: "An unknown error occurred",
115
- context: { error: String(error) }
116
+ context: { error: String(error) },
117
+ recoverable: true
116
118
  });
117
119
  }
118
120
 
@@ -175,6 +177,8 @@ async function tryCatchAsync(fn, normalize = normalizeUnknownError) {
175
177
  var CoreErrorCodes = {
176
178
  // ── Parser (parser/PrecedenceParser.ts, parser/BytecodeBuilder.ts, parser/PhrasePattern.ts) ──
177
179
  INVALID_NUMBER_LITERAL: "INVALID_NUMBER_LITERAL",
180
+ /** A `"` that never meets its closing partner (`lexer/ExpressionLexer.ts`'s `tokenizeString()`). Previously the tokenizer ran off the end of the input and returned what it had, so `"abc` lexed to an ordinary String and an unterminated literal was indistinguishable from a terminated one. */
181
+ UNTERMINATED_STRING: "UNTERMINATED_STRING",
178
182
  NO_PREFIX_PARSELET: "NO_PREFIX_PARSELET",
179
183
  UNEXPECTED_END_OF_INPUT: "UNEXPECTED_END_OF_INPUT",
180
184
  UNEXPECTED_TOKEN_TYPE: "UNEXPECTED_TOKEN_TYPE",
@@ -201,7 +205,9 @@ var CoreErrorCodes = {
201
205
  EVALUATION_ERROR: "EVALUATION_ERROR",
202
206
  INSTRUCTION_LIMIT_EXCEEDED: "INSTRUCTION_LIMIT_EXCEEDED",
203
207
  STACK_LIMIT_EXCEEDED: "STACK_LIMIT_EXCEEDED",
204
- /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Always `recoverable: false` (internal invariant violation). */
208
+ /** One evaluation asking for more elements (collection Values, matrix cells) than `vm.maxAllocatedElements` allows. The counter the two limits above cannot be: both are checked between opcodes, so neither can see what a single opcode allocates inside a loop of its own. See `vm/AllocationBudget.ts`. Recoverable, since it describes this expression rather than the engine. */
209
+ ALLOCATION_LIMIT_EXCEEDED: "ALLOCATION_LIMIT_EXCEEDED",
210
+ /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Category INTERNAL, since it is an engine or plugin fault rather than a typed line, but recoverable: it happened on one line and the engine is still usable. */
205
211
  STACK_UNDERFLOW: "STACK_UNDERFLOW",
206
212
  UNDEFINED_VARIABLE: "UNDEFINED_VARIABLE",
207
213
  /** New this phase, the Tier-2/`LOAD_GLOBAL_VAR` hardening: a global variable read before its async preflight resolved, surfaced as a controlled error instead of pushing `undefined`. */
@@ -212,15 +218,54 @@ var CoreErrorCodes = {
212
218
  /** User-defined-function call/definition errors (`CALL_USER_FUNCTION`/`DEFINE_USER_FUNCTION` opcodes), calling a name with no matching definition, calling with the wrong argument count, and the deliberate v1 restriction that a function body can't itself contain async work. */
213
219
  UNDEFINED_FUNCTION: "UNDEFINED_FUNCTION",
214
220
  FUNCTION_ARITY_MISMATCH: "FUNCTION_ARITY_MISMATCH",
221
+ /** The same mistake against a BUILT-IN rather than a user-defined function (`sqrt()`, `atan2(1)`, `sqrt(1,2,3)`). Separate from `FUNCTION_ARITY_MISMATCH` above because the two are raised by different opcodes and a host may want to word them differently. Checked at the `CALL_BUILTIN` dispatch against `vm/VMBuiltinArity.ts`; recoverable, since it is a typo in the line, not an engine fault. */
222
+ BUILTIN_ARITY_MISMATCH: "BUILTIN_ARITY_MISMATCH",
215
223
  USER_FUNCTION_ASYNC_UNSUPPORTED: "USER_FUNCTION_ASYNC_UNSUPPORTED",
216
224
  /** A map/reduce transform body (inline expression or user-defined function) calling an async plugin. Same v1 scope restriction as `USER_FUNCTION_ASYNC_UNSUPPORTED` above, enforced both at parse time (`MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS`, packages/mapreduce/) and as a defense-in-depth runtime backstop here. */
217
225
  MAP_REDUCE_ASYNC_UNSUPPORTED: "MAP_REDUCE_ASYNC_UNSUPPORTED",
226
+ /** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */
227
+ SYMBOLIC_ASYNC_UNSUPPORTED: "SYMBOLIC_ASYNC_UNSUPPORTED",
218
228
  /** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */
219
229
  FUNCTION_RECURSION_LIMIT_EXCEEDED: "FUNCTION_RECURSION_LIMIT_EXCEEDED",
230
+ /** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */
231
+ FUNCTION_CALL_LIMIT_EXCEEDED: "FUNCTION_CALL_LIMIT_EXCEEDED",
232
+ /** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */
233
+ DATE_OFFSET_LIMIT_EXCEEDED: "DATE_OFFSET_LIMIT_EXCEEDED",
234
+ /** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */
235
+ BIGINT_SHIFT_LIMIT_EXCEEDED: "BIGINT_SHIFT_LIMIT_EXCEEDED",
236
+ /** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */
237
+ BIGINT_POW_LIMIT_EXCEEDED: "BIGINT_POW_LIMIT_EXCEEDED",
238
+ /** An operand with no whole-number form (a fraction, an infinity, a NaN) meeting a bigint: `1n + 0.5`, `1n & 1.5`, `5n/pi`. `BigInt()` answers those with a raw RangeError, which the VM relabelled UNEXPECTED_ERROR, so a typo in the line was reported as an engine fault. Recoverable; see `vm/VMConversion.ts`'s `toBigIntOperand()`. */
239
+ BIGINT_INEXACT_OPERAND: "BIGINT_INEXACT_OPERAND",
240
+ /** `10n / 0n` and `10n mod 0n`. Deliberately NOT what `1 / 0` does, which is Infinity: a bigint division is exact integer division (`7n / 2n` is 3n), and integer division by zero has no answer, exactly as it has none in C, Java, Python or JavaScript's own BigInt. Previously V8's own RangeError, relabelled UNEXPECTED_ERROR. Recoverable; see `vm/VMConversion.ts`'s `bigIntDivisionByZero()`. */
241
+ BIGINT_DIVISION_BY_ZERO: "BIGINT_DIVISION_BY_ZERO",
220
242
  /** `DEFINE_USER_FUNCTION`'s body-index lookup failing, a compiler/VM invariant violation (the opcode stream referenced a `userFunctionBodies` slot that doesn't exist), never a user-input error. */
221
243
  INTERNAL_MISSING_FUNCTION_BODY: "INTERNAL_MISSING_FUNCTION_BODY",
222
244
  /** `MAP_INVOKE`/`REDUCE_INVOKE`'s anonymous-body-index lookup failing. Same class as `INTERNAL_MISSING_FUNCTION_BODY` above, for the `anonymousBodies` side-table instead of `userFunctionBodies`. */
223
245
  INTERNAL_MISSING_ANONYMOUS_BODY: "INTERNAL_MISSING_ANONYMOUS_BODY",
246
+ // ── Malformed bytecode on the public `./vm` surface (vm/VM.ts) ──
247
+ //
248
+ // `executeBytecode` is exported, so a bytecode program is caller input in
249
+ // the same sense an expression string is, and these five say so. They are
250
+ // VALIDATION rather than INTERNAL for exactly that reason: before they
251
+ // existed, every one of these cases reached a raw TypeError (`BigInt(undefined)`,
252
+ // `code.toUpperCase()` on a boolean, destructuring a program that was not
253
+ // there), which normalised to UNEXPECTED_ERROR and told the caller the
254
+ // engine was broken when their eleven bytes were. Reachable from ordinary
255
+ // source only through a compiler bug, which is why the messages name the
256
+ // opcode and the operand rather than the user's line.
257
+ /** An operand byte read past the end of the stream: the program ends in the middle of an instruction. */
258
+ MALFORMED_BYTECODE_TRUNCATED: "MALFORMED_BYTECODE_TRUNCATED",
259
+ /** A constant-pool operand indexing a `numbers`/`strings` entry that does not exist, or that is not of the pool's type. */
260
+ MALFORMED_BYTECODE_CONSTANT_INDEX: "MALFORMED_BYTECODE_CONSTANT_INDEX",
261
+ /** A unit or converter name read off the value stack that is not a string. Distinct from the pool case above: the operand is a Value another opcode pushed, not a pool entry. */
262
+ MALFORMED_BYTECODE_OPERAND_TYPE: "MALFORMED_BYTECODE_OPERAND_TYPE",
263
+ /** `MAP_INVOKE`/`REDUCE_INVOKE` carrying a body kind other than 0/1/2. Used to fall through every arm with no body and recurse into `executeBytecode(undefined)`. */
264
+ MALFORMED_BYTECODE_BODY_KIND: "MALFORMED_BYTECODE_BODY_KIND",
265
+ /** A `PUSH_BIGINT` pool entry that is not a whole number, e.g. `"1.000"`. `BigInt()` answers that with a raw SyntaxError. */
266
+ MALFORMED_BYTECODE_BIGINT_LITERAL: "MALFORMED_BYTECODE_BIGINT_LITERAL",
267
+ /** `executeBytecode()` called with something that is not a runnable program at all. Checked before the destructure that used to throw outside the function's own try/catch. */
268
+ MALFORMED_BYTECODE_PROGRAM: "MALFORMED_BYTECODE_PROGRAM",
224
269
  // ── Symbolic algebra (symbolic/, vm/SymbolicOps.ts) ──
225
270
  /** A coefficient grew past `RATIONAL_MAX_BITS`, e.g. repeated exact elimination multiplying denominators together. */
226
271
  SYMBOLIC_RATIONAL_OVERFLOW: "SYMBOLIC_RATIONAL_OVERFLOW",
@@ -236,6 +281,8 @@ var CoreErrorCodes = {
236
281
  SYMBOLIC_FACTOR_LIMIT_EXCEEDED: "SYMBOLIC_FACTOR_LIMIT_EXCEEDED",
237
282
  /** An equation outside what the solver attempts: not a polynomial, above the degree ceiling, or non-linear in the unknown while another unknown is present. */
238
283
  SYMBOLIC_SOLVE_UNSUPPORTED: "SYMBOLIC_SOLVE_UNSUPPORTED",
284
+ /** Some but not all of an equation's roots were found. Reported rather than returned, because a partial list of roots looks exactly like a complete one. */
285
+ SYMBOLIC_SOLVE_INCOMPLETE: "SYMBOLIC_SOLVE_INCOMPLETE",
239
286
  /** `solve`'s second argument not being a bare name. */
240
287
  SOLVE_REQUIRES_VARIABLE_NAME: "SOLVE_REQUIRES_VARIABLE_NAME",
241
288
  /** A derivative order outside 0..`DERIVATIVE_MAX_ORDER`. */
@@ -255,11 +302,15 @@ var CoreErrorCodes = {
255
302
  // ── Engine (engine/ExpressionEngine.ts, engine/ExpressionEngineSafety.ts, engine/AsyncResolutionBatcher.ts) ──
256
303
  EXPRESSION_TOO_LONG: "EXPRESSION_TOO_LONG",
257
304
  EXPRESSION_TOO_COMPLEX: "EXPRESSION_TOO_COMPLEX",
305
+ /** A document with more lines than `performance.maxDocumentLines`. The per-line limits above bound what one line may ask for and say nothing about how many lines there are; two hundred thousand of `1 + 1` exhausted the heap on the line records alone. Recoverable. */
306
+ DOCUMENT_TOO_LARGE: "DOCUMENT_TOO_LARGE",
258
307
  NORMALIZED_TOKEN_LIMIT_EXCEEDED: "NORMALIZED_TOKEN_LIMIT_EXCEEDED",
259
308
  /** `"=>"` with nothing before it, needs an expression or variable name to solve/simplify. */
260
309
  THEREFORE_REQUIRES_EXPRESSION: "THEREFORE_REQUIRES_EXPRESSION",
261
310
  /** A `"=>"`-triggered expression called an async plugin (weather/stocks/currency). Same v1 scope restriction as user-function/map-reduce bodies. */
262
311
  THEREFORE_ASYNC_UNSUPPORTED: "THEREFORE_ASYNC_UNSUPPORTED",
312
+ /** Colon-separated numbers that are not a time any clock can show ("24:00", "9:60", "100:5"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */
313
+ INVALID_TIME_LITERAL: "INVALID_TIME_LITERAL",
263
314
  // ── Config (constants/Configuration.ts) ──
264
315
  CONFIG_PATH_NOT_FOUND: "CONFIG_PATH_NOT_FOUND",
265
316
  INVALID_CONFIG_PATH: "INVALID_CONFIG_PATH",
@@ -286,5 +337,5 @@ var CoreErrorCodes = {
286
337
  };
287
338
 
288
339
  export { CoreErrorCodes, EngineError, ErrorCategory, ErrorFactory, andThen, combine, err, isErr, isOk, map, mapErr, match, normalizeUnknownError, ok, throwIfErr, tryCatch, tryCatchAsync, unwrapOr };
289
- //# sourceMappingURL=chunk-6RDSQURE.js.map
290
- //# sourceMappingURL=chunk-6RDSQURE.js.map
340
+ //# sourceMappingURL=chunk-3D7V24DG.js.map
341
+ //# sourceMappingURL=chunk-3D7V24DG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/EngineError.ts","../src/errors/Result.ts","../src/errors/ErrorCode.ts"],"names":["ErrorCategory"],"mappings":";AA6BO,IAAK,aAAA,qBAAAA,cAAAA,KAAL;AAEL,EAAAA,eAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,eAAA,WAAA,CAAA,GAAY,WAAA;AAEZ,EAAAA,eAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,eAAA,UAAA,CAAA,GAAW,UAAA;AAEX,EAAAA,eAAA,UAAA,CAAA,GAAW,UAAA;AAEX,EAAAA,eAAA,QAAA,CAAA,GAAS,QAAA;AAZC,EAAA,OAAAA,cAAAA;AAAA,CAAA,EAAA,aAAA,IAAA,EAAA;AAmEL,IAAM,WAAA,GAAN,MAAM,YAAA,SAAoB,KAAA,CAAM;AAAA,EAsBrC,WAAA,CAAY,UAAyB,IAAA,EAAuB;AAC1D,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AACvB,IAAA,IAAA,CAAK,WAAA,GAAc,KAAK,WAAA,IAAe,IA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A,EAA+B,+BAAA;AAAA;AAAA,EAE/B,2BAAA,EAA6B,6BAAA;AAAA;AAAA,EAE7B,oBAAA,EAAsB,sBAAA;AAAA;AAAA,EAGtB,qBAAA,EAAuB,uBAAA;AAAA,EACvB,mBAAA,EAAqB,qBAAA;AAAA,EACrB,wBAAA,EAA0B,0BAAA;AAAA,EAC1B,yBAAA,EAA2B,2BAAA;AAAA;AAAA,EAG3B,yBAAA,EAA2B,2BAAA;AAAA,EAC3B,wBAAA,EAA0B,0BAAA;AAAA,EAC1B,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAEvB,+BAAA,EAAiC,iCAAA;AAAA;AAAA,EAEjC,oCAAA,EAAsC,sCAAA;AAAA;AAAA,EAEtC,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAEvB,oCAAA,EAAsC,sCAAA;AAAA;AAAA,EAGtC,iBAAA,EAAmB,mBAAA;AAAA,EACnB,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAGvB,gBAAA,EAAkB,kBAAA;AAAA,EAClB,aAAA,EAAe;AACjB","file":"chunk-3D7V24DG.js","sourcesContent":["/**\n * The engine's structured error type, the \"Rust/Go-style, verbose, easy to\n * tell the issue\" half of the error-handling redesign (the other half is\n * `Result.ts`).\n *\n * Historical note: an earlier version of this class (`UnifiedErrorFramework.ts`,\n * still the import path most of the codebase uses. See that file, now a\n * pure re-export barrel) had a much larger field set (`severity`,\n * `recovery`, a 5-value enum, `ErrorRecoveryManager`) that was almost\n * entirely dead: nothing downstream ever read `.severity`/`.recovery`,\n * only `.message` reliably survived to a caller. This version is smaller\n * and deliberately keeps only fields something actually consumes.\n */\n\nimport type { ErrorCode } from \"@solve-js/errors/ErrorCode\";\n\n/** A character-offset (and optional line/col) span into the original expression text, for a future \"underline the offending token\" UI, not yet wired to one. */\nexport interface SourceSpan {\n start: number;\n end: number;\n line?: number;\n col?: number;\n}\n\n/**\n * Error classification, kept from the original framework, now actually\n * consulted: it's the `format()` header and lets host code group errors\n * by pipeline stage without string-matching `.code`.\n */\nexport enum ErrorCategory {\n /** Errors during expression parsing. */\n PARSING = \"PARSING\",\n /** Errors during bytecode execution. */\n EXECUTION = \"EXECUTION\",\n /** Errors from input validation (safety limits, config). */\n VALIDATION = \"VALIDATION\",\n /** Errors from external services/APIs (currency rates, weather, stocks). */\n EXTERNAL = \"EXTERNAL\",\n /** Internal engine invariant violations. See `recoverable`'s doc comment. */\n INTERNAL = \"INTERNAL\",\n /** Configuration errors. */\n CONFIG = \"CONFIG\",\n}\n\n/** Fields accepted when constructing an {@link EngineError}. */\nexport interface EngineErrorInit {\n /** Catalog code. See `errors/ErrorCode.ts`. Not a free string: every code used by a BUILT-IN package should be registered there so `ErrorCodeCatalog.spec.ts` can catch collisions/typos. Third-party packages may still use any string here, `EngineError.code`'s runtime type is `string`. */\n code: ErrorCode | (string & {});\n /** Short, single-line, `Error.message`-compatible. Existing `.toThrow(/pattern/)`/`.message` assertions keep working against this field, richer detail goes in `expected`/`found`/`suggestion`, not crammed into this string. */\n message: string;\n /** What the parser/validator/VM expected to see, in plain words, e.g. \"a city name\", \"a 4-digit year\", \"end of expression\". */\n expected?: string;\n /** What was actually found instead, e.g. \"end of expression\", `NUMBER \"5\"`, the offending token's literal text. */\n found?: string;\n /** An actionable, worked-example fix, e.g. `e.g. \"weather in London\"`. Mirrors this codebase's best existing messages (`WEATHER_EXPECTED_CITY`, `AS_CONVERTER_EXPECTED_NAME`). */\n suggestion?: string;\n /**\n * Whether this engine instance is still usable. `true` for everything that\n * went wrong on ONE line, whether the line's fault (bad syntax, an unknown\n * variable, a safety limit exceeded), the environment's (an external API\n * down), or the engine's own (corrupted bytecode, a stack underflow from a\n * buggy plugin). `false` is for the far rarer case where there is no working\n * engine to go on with: a configuration or package-registration failure,\n * which is what `ErrorFactory.config()` is for and the only factory method\n * that still defaults to it.\n *\n * The category answers a different question, and the two used to be answered\n * as one. Category INTERNAL says whose fault this is, the engine's, worth\n * reporting as a bug. `recoverable` says whether the host may carry on, and\n * after an internal slip on one line it may:\n * `__tests__/hardening/RobustnessEngineLifecycle.spec.ts` alternates a\n * throwing line with a good one five hundred times and every answer stays\n * correct. Reporting that as `isFatal()` told a host the opposite, and a host\n * that honours the name would tear a document down over one bad line.\n *\n * This has never gated \"does evaluation of the rest of the document\n * continue\"; with this engine's per-line containment it always does, even for\n * a `recoverable: false` error (see `ARCHITECTURE.md`'s async-batcher/Tier-2\n * hardening notes). It gates what a host is TOLD. See\n * {@link EngineError.isFatal}.\n */\n recoverable?: boolean;\n /** Character-offset span into the source expression, when available. Not yet threaded through every call site, populate opportunistically, don't block on retrofitting every existing throw site. */\n span?: SourceSpan;\n /** Free-form structured context. The one field the pre-existing framework's real consumer (`ThreeTierEvaluator.ts`'s DAG-preservation-on-compile-error path) actually reads, kept name- and shape-compatible on purpose. */\n context?: Record<string, unknown>;\n /** The underlying error this one wraps, if any, passed straight through to native `Error.cause` (ES2022), so Node's default printer, most loggers, and `instanceof Error` tooling understand the chain for free. */\n cause?: unknown;\n}\n\n/**\n * The engine's structured error type. Still a real `Error` subclass (so\n * `throw`/`catch`/`instanceof Error` all keep working exactly as before),\n * but now every field except the removed `severity`/`recovery` pair is\n * something real code reads.\n */\nexport class EngineError extends Error {\n readonly category: ErrorCategory;\n readonly code: string;\n readonly expected?: string;\n readonly found?: string;\n readonly suggestion?: string;\n readonly recoverable: boolean;\n readonly span?: SourceSpan;\n readonly context?: Record<string, unknown>;\n readonly timestamp: Date;\n /**\n * Set explicitly (not via `super(message, {cause})`). This repo's\n * `tsconfig.json` targets ES6/ES5-ES7 lib, which predates TypeScript's\n * ES2022 `Error` constructor `cause`-option overload. `Error.prototype.cause`\n * is still a real runtime feature in every target this engine actually\n * runs in (Node 16.9+, all evergreen browsers, Electron/Obsidian's\n * bundled Chromium) regardless of the TS lib target used to type-check\n * against it, assigning it directly gets the same Node-printer/logger\n * interop with no build-config change needed.\n */\n readonly cause?: unknown;\n\n constructor(category: ErrorCategory, init: EngineErrorInit) {\n super(init.message);\n this.name = \"EngineError\";\n this.category = category;\n this.code = init.code;\n this.expected = init.expected;\n this.found = init.found;\n this.suggestion = init.suggestion;\n this.recoverable = init.recoverable ?? true;\n this.span = init.span;\n this.context = init.context;\n this.cause = init.cause;\n this.timestamp = new Date();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, EngineError);\n }\n }\n\n /** `!recoverable`. See `EngineErrorInit.recoverable`'s doc comment for what this actually gates (message framing/telemetry, not whether evaluation continues). */\n isFatal(): boolean {\n return !this.recoverable;\n }\n\n /** Walk `.cause` repeatedly, collecting the full chain (this error first). */\n causeChain(): unknown[] {\n const chain: unknown[] = [this];\n let current: unknown = this.cause;\n while (current !== undefined && current !== null) {\n chain.push(current);\n current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined;\n }\n return chain;\n }\n\n /**\n * Rust/Go-style multi-line renderer, the NEW thing a host/CLI/test\n * reaches for when it wants the full, verbose picture, as distinct from\n * `.message` (kept short and stable for existing assertions). Example:\n *\n * ```\n * error[WEATHER_EXPECTED_CITY]: Expected a city name after \"weather in\"\n * expected: a city name\n * found: end of expression\n * suggestion: e.g. \"weather in London\"\n * ```\n */\n format(): string {\n const lines = [`error[${this.code}]: ${this.message}`];\n if (this.expected) lines.push(` expected: ${this.expected}`);\n if (this.found) lines.push(` found: ${this.found}`);\n if (this.suggestion) lines.push(` suggestion: ${this.suggestion}`);\n return lines.join(\"\\n\");\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n category: this.category,\n code: this.code,\n message: this.message,\n expected: this.expected,\n found: this.found,\n suggestion: this.suggestion,\n recoverable: this.recoverable,\n span: this.span,\n context: this.context,\n timestamp: this.timestamp.toISOString(),\n };\n }\n}\n\n/**\n * Factory for creating classified `EngineError`s. Every method accepts\n * EITHER the original, minimal 3-arg shape (`code, message, context?`\n * every existing call site across the codebase keeps compiling unchanged)\n * OR the richer `EngineErrorInit` object (for `expected`/`found`/\n * `suggestion`/`recoverable`/`span`/`cause`), upgrade a call site to the\n * richer form only when you're already touching it, no separate churn\n * pass required.\n */\nexport class ErrorFactory {\n private static build(\n category: ErrorCategory,\n defaultRecoverable: boolean,\n codeOrInit: string | EngineErrorInit,\n message?: string,\n context?: Record<string, unknown>,\n ): EngineError {\n const init: EngineErrorInit =\n typeof codeOrInit === \"string\"\n ? { code: codeOrInit, message: message!, context }\n : codeOrInit;\n return new EngineError(category, { recoverable: defaultRecoverable, ...init });\n }\n\n static validation(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static validation(init: EngineErrorInit): EngineError;\n static validation(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.VALIDATION, true, codeOrInit, message, context);\n }\n\n static parsing(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static parsing(init: EngineErrorInit): EngineError;\n static parsing(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.PARSING, true, codeOrInit, message, context);\n }\n\n static execution(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static execution(init: EngineErrorInit): EngineError;\n static execution(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXECUTION, true, codeOrInit, message, context);\n }\n\n static external(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static external(init: EngineErrorInit): EngineError;\n static external(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXTERNAL, true, codeOrInit, message, context);\n }\n\n /**\n * Reserve for genuine engine-internal invariant violations (corrupted\n * bytecode, a stack underflow from a buggy plugin, an \"impossible\" state),\n * not for user-input errors: the category is a bug report.\n *\n * Defaults `recoverable: true` all the same, because every one of these sites\n * is an invariant that failed on ONE line and none of them leaves the engine\n * unusable. This used to default to `false`, which conflated \"the engine's\n * fault\" with \"the engine is finished\" and told a host to tear a document\n * down over a line it could simply have shown an error against. A site that\n * has looked at its own case and concluded the instance really is gone can\n * still pass `recoverable: false` explicitly. See {@link\n * EngineErrorInit.recoverable}.\n */\n static internal(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static internal(init: EngineErrorInit): EngineError;\n static internal(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.INTERNAL, true, codeOrInit, message, context);\n }\n\n /** Defaults `recoverable: false`, and is now the only method that does: a configuration or package-registration failure is the one class that leaves no working engine to carry on with, rather than one bad line in a document. */\n static config(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static config(init: EngineErrorInit): EngineError;\n static config(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.CONFIG, false, codeOrInit, message, context);\n }\n}\n\n/**\n * Normalize any thrown value into an `EngineError`, an `EngineError`\n * passes through as-is; a plain `Error` gets wrapped (message preserved,\n * original attached via `cause`); anything else becomes a generic\n * \"unknown error\" wrapping the stringified value. Used at every\n * throw-space/Result-space boundary (`Result.tryCatch`'s default\n * `normalize`, the VM's outer execution try/catch, `AsyncResolutionBatcher`'s\n * per-line containment) so a raw `TypeError` from a genuine engine bug\n * still surfaces as a structured, catalogued error instead of an opaque\n * uncaught exception.\n *\n * Both branches state RECOVERABLE explicitly, while keeping the INTERNAL\n * category. The two fields answer different questions and were previously\n * answering the same one:\n *\n * category INTERNAL whose fault is this? The engine's. Worth reporting.\n * recoverable is this engine instance still usable? Yes.\n *\n * Everything reaching here is by definition something the engine did not\n * anticipate on ONE line, and per-line containment means the next line\n * evaluates normally, which `__tests__/hardening/RobustnessEngineLifecycle`\n * demonstrates over hundreds of alternating failure/success pairs. Reporting\n * that as `isFatal()` told a host the opposite, and a host that honours the\n * name would tear a document down over a single bad line. The \"this is an\n * engine bug rather than your syntax\" signal a caller wants for telemetry is\n * the CATEGORY, which is unchanged.\n *\n * The flag is written out here rather than inherited from\n * `ErrorFactory.internal()`, which now defaults the same way, so that this\n * function's contract survives a future change to that default.\n */\nexport function normalizeUnknownError(error: unknown): EngineError {\n if (error instanceof EngineError) return error;\n if (error instanceof Error) {\n return ErrorFactory.internal({\n code: \"UNEXPECTED_ERROR\",\n message: error.message,\n context: { originalErrorName: error.name },\n cause: error,\n recoverable: true,\n });\n }\n return ErrorFactory.internal({\n code: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred\",\n context: { error: String(error) },\n recoverable: true,\n });\n}\n","import { type EngineError, normalizeUnknownError } from \"@solve-js/errors/EngineError\";\n\n/**\n * A Rust-style `Result<T, E>`, the value half of this engine's error-handling\n * redesign. `E` defaults to `EngineError` (this engine's structured error\n * type) but every combinator here is generic over `E`, so `Result` works\n * equally well for a domain that isn't `EngineError`-shaped.\n *\n * This exact shape used to live in `errors/UnifiedErrorFramework.ts` (kept\n * there as a barrel re-export for backward compatibility), moved here as\n * its own module because it's genuinely generic (no dependency on\n * `EngineError` beyond the default type parameter) and because the engine\n * is migrating callers to it incrementally: parsing/VM/package code that\n * expects \"a failure is a possibility, not an exception\" returns\n * `Result<T, EngineError>` instead of throwing; two explicit adapters\n * {@link throwIfErr} and {@link tryCatch}, are the sanctioned way to cross\n * the boundary between Result-based code and still-throw-based code during\n * the migration (and permanently, at the public API boundary. See\n * `ExpressionEngine.evaluateExpression()`'s documented throw contract).\n */\nexport type Result<T, E = EngineError> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\n/** Wrap a successful value. */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/** Wrap a failure. */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Narrow a {@link Result} to its success arm.\n *\n * @param r - The result to test.\n * @returns True when it succeeded, narrowing `r` so `r.value` is reachable.\n */\nexport function isOk<T, E>(r: Result<T, E>): r is { ok: true; value: T } {\n return r.ok;\n}\n\n/**\n * Narrow a {@link Result} to its failure arm.\n *\n * @param r - The result to test.\n * @returns True when it failed, narrowing `r` so `r.error` is reachable.\n */\nexport function isErr<T, E>(r: Result<T, E>): r is { ok: false; error: E } {\n return !r.ok;\n}\n\n/** Transform the success value; a failure passes through untouched. */\nexport function map<T, U, E>(r: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return r.ok ? ok(fn(r.value)) : r;\n}\n\n/** Transform the error; a success passes through untouched. */\nexport function mapErr<T, E, F>(r: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return r.ok ? r : err(fn(r.error));\n}\n\n/** Chain a Result-returning operation onto a success (a.k.a. flatMap/bind). */\nexport function andThen<T, U, E>(r: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return r.ok ? fn(r.value) : r;\n}\n\n/** Unwrap a success, or return `fallback` for a failure. Never throws. */\nexport function unwrapOr<T, E>(r: Result<T, E>, fallback: T): T {\n return r.ok ? r.value : fallback;\n}\n\n/** Exhaustive pattern-match, the `match`/`switch` a Rust enum gets for free. */\nexport function match<T, E, R>(r: Result<T, E>, arms: { ok: (value: T) => R; err: (error: E) => R }): R {\n return r.ok ? arms.ok(r.value) : arms.err(r.error);\n}\n\n/**\n * Combine several Results into one, succeeds with a tuple of all values\n * iff every input succeeded; otherwise fails with the FIRST error\n * encountered (left-to-right), matching this codebase's existing\n * fail-fast convention elsewhere (e.g. `BytecodeBuilder`'s constant-pool\n * limit checks).\n */\nexport function combine<T extends readonly unknown[], E>(\n results: { [K in keyof T]: Result<T[K], E> },\n): Result<T, E> {\n const values: unknown[] = [];\n for (const r of results as readonly Result<unknown, E>[]) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values as unknown as T);\n}\n\n/**\n * Cross from Result-space back to throw-space, the sanctioned boundary\n * adapter for callers (public API surface, older not-yet-migrated code,\n * tests) that still want exception-based control flow. Throws `r.error`\n * as-is (an `EngineError` is already a real `Error` subclass, so this\n * needs no wrapping).\n */\nexport function throwIfErr<T, E>(r: Result<T, E>): T {\n if (r.ok) return r.value;\n throw r.error;\n}\n\n/**\n * Cross from throw-space into Result-space, runs `fn`, converting any\n * thrown value into a Result via `normalize` (defaults to\n * {@link normalizeUnknownError}). The inverse of {@link throwIfErr}; the\n * pairing that lets Result-based and throw-based code interoperate during\n * an incremental migration instead of requiring a single flag-day rewrite.\n */\nexport function tryCatch<T>(\n fn: () => T,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Result<T, EngineError> {\n try {\n return ok(fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n\n/** Async sibling of {@link tryCatch}. */\nexport async function tryCatchAsync<T>(\n fn: () => Promise<T>,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Promise<Result<T, EngineError>> {\n try {\n return ok(await fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n","/**\n * The built-in error-code catalog, one typed const object per domain\n * unioned together here for autocomplete/exhaustiveness in core engine\n * code. Deliberately NOT one central enum: `IEnginePackage` is documented\n * public SDK surface for third-party packages (see `api/PackageRegistry.ts`),\n * and a closed enum would block an external package author from defining\n * their own codes without editing this file. `EngineError.code`'s runtime\n * type stays `string` for exactly that reason. This catalog is for the\n * codes THIS repo owns and wants collision/typo checking on (see\n * `__tests__/errors/ErrorCodeCatalog.spec.ts`), not a hard runtime\n * whitelist.\n *\n * As each package migrates to `Result<void, EngineError>` (see this\n * session's error-handling-refactor plan, Phase 5), it should export its\n * own small `XxxErrorCodes` const object co-located with its parselets\n * exactly like `CoreErrorCodes` below, just scoped to one domain, and get\n * unioned into `ErrorCode` here. Until a package migrates, its existing\n * free-string codes keep working (ErrorFactory accepts any string); they\n * just aren't caught by the catalog's uniqueness/orphan checks yet.\n */\n\n/**\n * Codes used directly by the parser/VM/engine/errors layers themselves\n * confirmed against the current source, not aspirational. Grouped by\n * pipeline stage via the comments, not a naming prefix (these predate any\n * naming convention and renaming them is out of scope for introducing the\n * catalog, only NEW codes need to follow a scoped/prefixed style, see\n * `STACK_UNDERFLOW` etc. below).\n */\nexport const CoreErrorCodes = {\n // ── Parser (parser/PrecedenceParser.ts, parser/BytecodeBuilder.ts, parser/PhrasePattern.ts) ──\n INVALID_NUMBER_LITERAL: \"INVALID_NUMBER_LITERAL\",\n /** A `\"` that never meets its closing partner (`lexer/ExpressionLexer.ts`'s `tokenizeString()`). Previously the tokenizer ran off the end of the input and returned what it had, so `\"abc` lexed to an ordinary String and an unterminated literal was indistinguishable from a terminated one. */\n UNTERMINATED_STRING: \"UNTERMINATED_STRING\",\n NO_PREFIX_PARSELET: \"NO_PREFIX_PARSELET\",\n UNEXPECTED_END_OF_INPUT: \"UNEXPECTED_END_OF_INPUT\",\n UNEXPECTED_TOKEN_TYPE: \"UNEXPECTED_TOKEN_TYPE\",\n NESTING_DEPTH_EXCEEDED: \"NESTING_DEPTH_EXCEEDED\",\n UNEXPECTED_END: \"UNEXPECTED_END\",\n UNEXPECTED_TRAILING_TOKEN: \"UNEXPECTED_TRAILING_TOKEN\",\n PARSE_ERROR: \"PARSE_ERROR\",\n TOO_MANY_NUMERIC_CONSTANTS: \"TOO_MANY_NUMERIC_CONSTANTS\",\n TOO_MANY_STRING_CONSTANTS: \"TOO_MANY_STRING_CONSTANTS\",\n NO_MATCHING_PHRASE_ALTERNATIVE: \"NO_MATCHING_PHRASE_ALTERNATIVE\",\n INVALID_PHRASE_PATTERN: \"INVALID_PHRASE_PATTERN\",\n PHRASE_KEYWORD_MISMATCH: \"PHRASE_KEYWORD_MISMATCH\",\n /** User-defined-function definition parsing (`f(x, y) = ...`), an invalid token where a parameter name was expected. */\n USER_FUNCTION_INVALID_PARAM_NAME: \"USER_FUNCTION_INVALID_PARAM_NAME\",\n /** `f() = ...` with zero parameters, indistinguishable from a plain no-arg function call, so rejected at definition time. */\n USER_FUNCTION_NO_PARAMS: \"USER_FUNCTION_NO_PARAMS\",\n /** A user-defined function body calling an async plugin (weather/stocks/currency/...), rejected at definition time; v1 scope excludes async function bodies. */\n FUNCTION_BODY_MUST_BE_SYNCHRONOUS: \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n /** `BytecodeBuilder`'s `userFunctionBodies` side-table exceeding its capacity. Same class as `TOO_MANY_NUMERIC_CONSTANTS`/`TOO_MANY_STRING_CONSTANTS` below. */\n TOO_MANY_FUNCTION_DEFINITIONS: \"TOO_MANY_FUNCTION_DEFINITIONS\",\n /** `BytecodeBuilder`'s `anonymousBodies` side-table (map/reduce inline transform bodies) exceeding its capacity. Same class as `TOO_MANY_FUNCTION_DEFINITIONS` above. */\n TOO_MANY_ANONYMOUS_BODIES: \"TOO_MANY_ANONYMOUS_BODIES\",\n\n // ── VM (vm/VM.ts, vm/OpRegistry.ts, vm/VMBuiltins.ts) ──\n EVALUATION_ERROR: \"EVALUATION_ERROR\",\n INSTRUCTION_LIMIT_EXCEEDED: \"INSTRUCTION_LIMIT_EXCEEDED\",\n STACK_LIMIT_EXCEEDED: \"STACK_LIMIT_EXCEEDED\",\n /** One evaluation asking for more elements (collection Values, matrix cells) than `vm.maxAllocatedElements` allows. The counter the two limits above cannot be: both are checked between opcodes, so neither can see what a single opcode allocates inside a loop of its own. See `vm/AllocationBudget.ts`. Recoverable, since it describes this expression rather than the engine. */\n ALLOCATION_LIMIT_EXCEEDED: \"ALLOCATION_LIMIT_EXCEEDED\",\n /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Category INTERNAL, since it is an engine or plugin fault rather than a typed line, but recoverable: it happened on one line and the engine is still usable. */\n STACK_UNDERFLOW: \"STACK_UNDERFLOW\",\n UNDEFINED_VARIABLE: \"UNDEFINED_VARIABLE\",\n /** New this phase, the Tier-2/`LOAD_GLOBAL_VAR` hardening: a global variable read before its async preflight resolved, surfaced as a controlled error instead of pushing `undefined`. */\n GLOBAL_VARIABLE_NOT_RESOLVED: \"GLOBAL_VARIABLE_NOT_RESOLVED\",\n UNKNOWN_FUNCTION: \"UNKNOWN_FUNCTION\",\n /** `unwrapEvalResult()`'s pending-when-expecting-value case, a caller-contract violation, not user-input. */\n UNEXPECTED_PENDING_RESULT: \"UNEXPECTED_PENDING_RESULT\",\n /** User-defined-function call/definition errors (`CALL_USER_FUNCTION`/`DEFINE_USER_FUNCTION` opcodes), calling a name with no matching definition, calling with the wrong argument count, and the deliberate v1 restriction that a function body can't itself contain async work. */\n UNDEFINED_FUNCTION: \"UNDEFINED_FUNCTION\",\n FUNCTION_ARITY_MISMATCH: \"FUNCTION_ARITY_MISMATCH\",\n /** The same mistake against a BUILT-IN rather than a user-defined function (`sqrt()`, `atan2(1)`, `sqrt(1,2,3)`). Separate from `FUNCTION_ARITY_MISMATCH` above because the two are raised by different opcodes and a host may want to word them differently. Checked at the `CALL_BUILTIN` dispatch against `vm/VMBuiltinArity.ts`; recoverable, since it is a typo in the line, not an engine fault. */\n BUILTIN_ARITY_MISMATCH: \"BUILTIN_ARITY_MISMATCH\",\n USER_FUNCTION_ASYNC_UNSUPPORTED: \"USER_FUNCTION_ASYNC_UNSUPPORTED\",\n /** A map/reduce transform body (inline expression or user-defined function) calling an async plugin. Same v1 scope restriction as `USER_FUNCTION_ASYNC_UNSUPPORTED` above, enforced both at parse time (`MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS`, packages/mapreduce/) and as a defense-in-depth runtime backstop here. */\n MAP_REDUCE_ASYNC_UNSUPPORTED: \"MAP_REDUCE_ASYNC_UNSUPPORTED\",\n /** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */\n SYMBOLIC_ASYNC_UNSUPPORTED: \"SYMBOLIC_ASYNC_UNSUPPORTED\",\n /** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */\n FUNCTION_RECURSION_LIMIT_EXCEEDED: \"FUNCTION_RECURSION_LIMIT_EXCEEDED\",\n /** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */\n FUNCTION_CALL_LIMIT_EXCEEDED: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n /** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */\n DATE_OFFSET_LIMIT_EXCEEDED: \"DATE_OFFSET_LIMIT_EXCEEDED\",\n /** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */\n BIGINT_SHIFT_LIMIT_EXCEEDED: \"BIGINT_SHIFT_LIMIT_EXCEEDED\",\n /** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */\n BIGINT_POW_LIMIT_EXCEEDED: \"BIGINT_POW_LIMIT_EXCEEDED\",\n /** An operand with no whole-number form (a fraction, an infinity, a NaN) meeting a bigint: `1n + 0.5`, `1n & 1.5`, `5n/pi`. `BigInt()` answers those with a raw RangeError, which the VM relabelled UNEXPECTED_ERROR, so a typo in the line was reported as an engine fault. Recoverable; see `vm/VMConversion.ts`'s `toBigIntOperand()`. */\n BIGINT_INEXACT_OPERAND: \"BIGINT_INEXACT_OPERAND\",\n /** `10n / 0n` and `10n mod 0n`. Deliberately NOT what `1 / 0` does, which is Infinity: a bigint division is exact integer division (`7n / 2n` is 3n), and integer division by zero has no answer, exactly as it has none in C, Java, Python or JavaScript's own BigInt. Previously V8's own RangeError, relabelled UNEXPECTED_ERROR. Recoverable; see `vm/VMConversion.ts`'s `bigIntDivisionByZero()`. */\n BIGINT_DIVISION_BY_ZERO: \"BIGINT_DIVISION_BY_ZERO\",\n /** `DEFINE_USER_FUNCTION`'s body-index lookup failing, a compiler/VM invariant violation (the opcode stream referenced a `userFunctionBodies` slot that doesn't exist), never a user-input error. */\n INTERNAL_MISSING_FUNCTION_BODY: \"INTERNAL_MISSING_FUNCTION_BODY\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE`'s anonymous-body-index lookup failing. Same class as `INTERNAL_MISSING_FUNCTION_BODY` above, for the `anonymousBodies` side-table instead of `userFunctionBodies`. */\n INTERNAL_MISSING_ANONYMOUS_BODY: \"INTERNAL_MISSING_ANONYMOUS_BODY\",\n\n // ── Malformed bytecode on the public `./vm` surface (vm/VM.ts) ──\n //\n // `executeBytecode` is exported, so a bytecode program is caller input in\n // the same sense an expression string is, and these five say so. They are\n // VALIDATION rather than INTERNAL for exactly that reason: before they\n // existed, every one of these cases reached a raw TypeError (`BigInt(undefined)`,\n // `code.toUpperCase()` on a boolean, destructuring a program that was not\n // there), which normalised to UNEXPECTED_ERROR and told the caller the\n // engine was broken when their eleven bytes were. Reachable from ordinary\n // source only through a compiler bug, which is why the messages name the\n // opcode and the operand rather than the user's line.\n /** An operand byte read past the end of the stream: the program ends in the middle of an instruction. */\n MALFORMED_BYTECODE_TRUNCATED: \"MALFORMED_BYTECODE_TRUNCATED\",\n /** A constant-pool operand indexing a `numbers`/`strings` entry that does not exist, or that is not of the pool's type. */\n MALFORMED_BYTECODE_CONSTANT_INDEX: \"MALFORMED_BYTECODE_CONSTANT_INDEX\",\n /** A unit or converter name read off the value stack that is not a string. Distinct from the pool case above: the operand is a Value another opcode pushed, not a pool entry. */\n MALFORMED_BYTECODE_OPERAND_TYPE: \"MALFORMED_BYTECODE_OPERAND_TYPE\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE` carrying a body kind other than 0/1/2. Used to fall through every arm with no body and recurse into `executeBytecode(undefined)`. */\n MALFORMED_BYTECODE_BODY_KIND: \"MALFORMED_BYTECODE_BODY_KIND\",\n /** A `PUSH_BIGINT` pool entry that is not a whole number, e.g. `\"1.000\"`. `BigInt()` answers that with a raw SyntaxError. */\n MALFORMED_BYTECODE_BIGINT_LITERAL: \"MALFORMED_BYTECODE_BIGINT_LITERAL\",\n /** `executeBytecode()` called with something that is not a runnable program at all. Checked before the destructure that used to throw outside the function's own try/catch. */\n MALFORMED_BYTECODE_PROGRAM: \"MALFORMED_BYTECODE_PROGRAM\",\n\n // ── Symbolic algebra (symbolic/, vm/SymbolicOps.ts) ──\n /** A coefficient grew past `RATIONAL_MAX_BITS`, e.g. repeated exact elimination multiplying denominators together. */\n SYMBOLIC_RATIONAL_OVERFLOW: \"SYMBOLIC_RATIONAL_OVERFLOW\",\n /** `NaN` or `±Infinity` reaching a symbolic expression, neither of which has an exact rational value. */\n SYMBOLIC_NONFINITE_OPERAND: \"SYMBOLIC_NONFINITE_OPERAND\",\n /** Division by an exactly-zero rational. Exact, unlike the double comparison it replaced, which could not distinguish a true zero from `5.551e-17`. */\n SYMBOLIC_DIVISION_BY_ZERO: \"SYMBOLIC_DIVISION_BY_ZERO\",\n /** A tree exceeding `SYMBOLIC_MAX_NODES` entering the simplifier. */\n SYMBOLIC_NODE_LIMIT_EXCEEDED: \"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n /** A builtin with no symbolic reading (`min`, `random`, the finance block, ...) applied to an expression still containing an unknown. Returned rather than computing against `toNumber()`'s placeholder zero. */\n SYMBOLIC_UNSUPPORTED_FUNCTION: \"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n /** The rational-root search exceeding `FACTOR_MAX_ROOT_CANDIDATES`. The candidate set is the product of two divisor sets, so a highly-composite coefficient escapes quickly. */\n SYMBOLIC_FACTOR_LIMIT_EXCEEDED: \"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n /** An equation outside what the solver attempts: not a polynomial, above the degree ceiling, or non-linear in the unknown while another unknown is present. */\n SYMBOLIC_SOLVE_UNSUPPORTED: \"SYMBOLIC_SOLVE_UNSUPPORTED\",\n /** Some but not all of an equation's roots were found. Reported rather than returned, because a partial list of roots looks exactly like a complete one. */\n SYMBOLIC_SOLVE_INCOMPLETE: \"SYMBOLIC_SOLVE_INCOMPLETE\",\n /** `solve`'s second argument not being a bare name. */\n SOLVE_REQUIRES_VARIABLE_NAME: \"SOLVE_REQUIRES_VARIABLE_NAME\",\n /** A derivative order outside 0..`DERIVATIVE_MAX_ORDER`. */\n SYMBOLIC_DERIVATIVE_ORDER_LIMIT: \"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n /** An expression with no known elementary antiderivative. Reported rather than approximated, since a wrong integral is indistinguishable from a right one at the point of use. */\n SYMBOLIC_INTEGRAL_UNSUPPORTED: \"SYMBOLIC_INTEGRAL_UNSUPPORTED\",\n /** A Taylor degree outside 0..`TAYLOR_MAX_DEGREE`. */\n SYMBOLIC_TAYLOR_DEGREE_LIMIT: \"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n /** A Taylor coefficient that does not reduce to an exact number at the expansion point. */\n SYMBOLIC_TAYLOR_INEXACT: \"SYMBOLIC_TAYLOR_INEXACT\",\n /** An algebra verb's variable-name argument not being a bare name. */\n SYMBOLIC_REQUIRES_VARIABLE_NAME: \"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n /** `jacobian` called with expressions containing no unknown to differentiate against. */\n SYMBOLIC_JACOBIAN_NO_VARIABLES: \"SYMBOLIC_JACOBIAN_NO_VARIABLES\",\n /** A finite number whose decimal form could not be read back, which the regex covering every `Number.prototype.toString` output should make unreachable. */\n INTERNAL_RATIONAL_PARSE: \"INTERNAL_RATIONAL_PARSE\",\n\n // ── Engine (engine/ExpressionEngine.ts, engine/ExpressionEngineSafety.ts, engine/AsyncResolutionBatcher.ts) ──\n EXPRESSION_TOO_LONG: \"EXPRESSION_TOO_LONG\",\n EXPRESSION_TOO_COMPLEX: \"EXPRESSION_TOO_COMPLEX\",\n /** A document with more lines than `performance.maxDocumentLines`. The per-line limits above bound what one line may ask for and say nothing about how many lines there are; two hundred thousand of `1 + 1` exhausted the heap on the line records alone. Recoverable. */\n DOCUMENT_TOO_LARGE: \"DOCUMENT_TOO_LARGE\",\n NORMALIZED_TOKEN_LIMIT_EXCEEDED: \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n /** `\"=>\"` with nothing before it, needs an expression or variable name to solve/simplify. */\n THEREFORE_REQUIRES_EXPRESSION: \"THEREFORE_REQUIRES_EXPRESSION\",\n /** A `\"=>\"`-triggered expression called an async plugin (weather/stocks/currency). Same v1 scope restriction as user-function/map-reduce bodies. */\n THEREFORE_ASYNC_UNSUPPORTED: \"THEREFORE_ASYNC_UNSUPPORTED\",\n /** Colon-separated numbers that are not a time any clock can show (\"24:00\", \"9:60\", \"100:5\"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */\n INVALID_TIME_LITERAL: \"INVALID_TIME_LITERAL\",\n\n // ── Config (constants/Configuration.ts) ──\n CONFIG_PATH_NOT_FOUND: \"CONFIG_PATH_NOT_FOUND\",\n INVALID_CONFIG_PATH: \"INVALID_CONFIG_PATH\",\n CONFIG_SECTION_NOT_FOUND: \"CONFIG_SECTION_NOT_FOUND\",\n CONFIG_PROPERTY_NOT_FOUND: \"CONFIG_PROPERTY_NOT_FOUND\",\n\n // ── Package/lexer registration-time collisions (lexer/ExpressionLexer.ts) ──\n PLUGIN_OPERATOR_COLLISION: \"PLUGIN_OPERATOR_COLLISION\",\n PLUGIN_KEYWORD_COLLISION: \"PLUGIN_KEYWORD_COLLISION\",\n PLUGIN_UNIT_COLLISION: \"PLUGIN_UNIT_COLLISION\",\n /** A package's declared `IEnginePackage.engineVersion` semver range doesn't satisfy the running engine's ENGINE_VERSION. See api/EngineVersionCompatibility.ts. */\n PACKAGE_ENGINE_VERSION_MISMATCH: \"PACKAGE_ENGINE_VERSION_MISMATCH\",\n /** A package's declared `IEnginePackage.engineVersion` isn't a parseable semver range at all (a typo in the package's own descriptor). */\n PACKAGE_ENGINE_VERSION_INVALID_RANGE: \"PACKAGE_ENGINE_VERSION_INVALID_RANGE\",\n /** `OpRegistry.allocateOpcode()`'s dynamic opcode pool (started at 201) exhausted, too many packages calling it. */\n OPCODE_POOL_EXHAUSTED: \"OPCODE_POOL_EXHAUSTED\",\n /** `VMBuiltins.allocatePluginFunctionIndex()`'s 0-255 index pool (a single opcode-stream byte) exhausted. */\n PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED: \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n\n // ── vm/Value.ts caller-contract violations (check isRateUnit()/isTimecodeUnit() first) ──\n INVALID_RATE_UNIT: \"INVALID_RATE_UNIT\",\n INVALID_TIMECODE_UNIT: \"INVALID_TIMECODE_UNIT\",\n\n // ── errors/EngineError.ts's own fallback normalization ──\n UNEXPECTED_ERROR: \"UNEXPECTED_ERROR\",\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\n/** Every error code the engine's own layers can produce, from {@link CoreErrorCodes}. */\nexport type CoreErrorCode = (typeof CoreErrorCodes)[keyof typeof CoreErrorCodes];\n\n/**\n * The aggregated catalog type. Currently just `CoreErrorCode`, union in\n * each package's own code-object type here as Phase 5 converts it, e.g.\n * `CoreErrorCode | WeatherErrorCode | StocksErrorCode | ...`.\n */\nexport type ErrorCode = CoreErrorCode;\n"]}
@@ -1,8 +1,8 @@
1
1
  import { DiagnosticEventType } from './chunk-G535KJEG.js';
2
- import { buildBindingPowerTable, BindingPower, BytecodeBuilder } from './chunk-6GCKCWLB.js';
3
- import { tokenTypeId, TokenTypes } from './chunk-GPPLSM2Z.js';
2
+ import { buildBindingPowerTable, BindingPower, bigIntLiteralDigits, BytecodeBuilder } from './chunk-526PMQOA.js';
3
+ import { tokenTypeId, TokenTypes } from './chunk-VB37OC6I.js';
4
4
  import { getLocale } from './chunk-XBTEO4OB.js';
5
- import { ErrorFactory } from './chunk-6RDSQURE.js';
5
+ import { ErrorFactory } from './chunk-3D7V24DG.js';
6
6
 
7
7
  // src/parser/registry/ParseletRegistry.ts
8
8
  function bindingPowersOf(parselet) {
@@ -60,26 +60,58 @@ var ParseletRegistry = class {
60
60
  this.infixParselets.set(tokenType, parselet);
61
61
  this.infixById.set(tokenTypeId(tokenType), parselet);
62
62
  }
63
- /** Iterate all registered prefix parselets for diagnostic display. */
63
+ /**
64
+ * Iterate all registered prefix parselets for diagnostic display.
65
+ *
66
+ * `PrefixParselet` declares no binding power, and this used to read a field
67
+ * of that name and report 0 for every one of them. 0 is not a neutral
68
+ * wrong answer: it is the value that means "not an operator, stop the
69
+ * expression", so a host drawing a table from this was told none of them
70
+ * bind at all. A prefix parselet in this parser has no per-parselet power
71
+ * to report, they all bind at the prefix level and each chooses for itself
72
+ * at what power to parse its own operand, so that level is what is
73
+ * reported. A parselet that does carry its own `bindingPower` still wins.
74
+ */
64
75
  getAllPrefix() {
65
76
  const result = [];
66
77
  for (const [tokenType, parselet] of this.prefixParselets) {
67
78
  result.push({
68
79
  tokenType,
69
- bindingPower: bindingPowersOf(parselet).bindingPower ?? 0,
80
+ bindingPower: bindingPowersOf(parselet).bindingPower ?? BindingPower.Prefix,
70
81
  category: parselet.category
71
82
  });
72
83
  }
73
84
  return result;
74
85
  }
75
- /** Iterate all registered infix parselets for diagnostic display. */
86
+ /**
87
+ * Iterate all registered infix parselets for diagnostic display.
88
+ *
89
+ * The field an `InfixParselet` actually declares is `bindingPower`. This
90
+ * used to read `leftBindingPower` and `rightBindingPower`, which no
91
+ * parselet in this codebase declares, so both reads were `undefined`, both
92
+ * fell to the `?? 0` default, and the public `getParseletRegistry()`
93
+ * reported a binding power of 0 for every one of the ~60 infix operators.
94
+ * A host building a precedence table from it was told `*` and `+` bind
95
+ * equally, and that neither binds at all.
96
+ *
97
+ * The left/right split: `bindingPower` is the LEFT power, and the right is
98
+ * one higher. That is the standard encoding for a left-associative
99
+ * operator, and it is what the parser itself does, see
100
+ * `PrecedenceParser.parseExpression()`'s `bp + 1` for the right operand.
101
+ * Every operator is reported that way, `^` included. Associativity is not
102
+ * something a parselet declares, it is a property of how each one calls
103
+ * `parseExpression`, so this API cannot report it without a new field on
104
+ * the interface. See {@link ParseletBindingPowers} for why scraping a
105
+ * plausible-looking one off the parselet is worse than not reporting it.
106
+ */
76
107
  getAllInfix() {
77
108
  const result = [];
78
109
  for (const [tokenType, parselet] of this.infixParselets) {
110
+ const left = bindingPowersOf(parselet).bindingPower ?? 0;
79
111
  result.push({
80
112
  tokenType,
81
- leftBindingPower: bindingPowersOf(parselet).leftBindingPower ?? 0,
82
- rightBindingPower: bindingPowersOf(parselet).rightBindingPower ?? 0,
113
+ leftBindingPower: left,
114
+ rightBindingPower: left + 1,
83
115
  category: parselet.category
84
116
  });
85
117
  }
@@ -217,7 +249,7 @@ var _PrecedenceParser = class _PrecedenceParser {
217
249
  *
218
250
  * @param minBp - minimum binding power (precedence climbing threshold).
219
251
  * For left-associative operators, the recursive call uses `bp + 1`.
220
- * For right-associative operators (^), it uses `bp`.
252
+ * For right-associative operators (^), it uses `bp - 1`.
221
253
  * @param _builder - accepted for parselet API compatibility; always uses `this.builder`.
222
254
  */
223
255
  parseExpression(minBp = 0, _builder) {
@@ -265,7 +297,7 @@ var _PrecedenceParser = class _PrecedenceParser {
265
297
  builder.emitOpcode(23 /* DIV */);
266
298
  builder.emitOpcode(74 /* TO_PERCENTAGE */);
267
299
  } else if (typeId === _PrecedenceParser.CARET_ID && this.tryEmitMatrixCaretOp(builder)) ; else {
268
- const rightBp = typeId === _PrecedenceParser.CARET_ID ? bp : bp + 1;
300
+ const rightBp = typeId === _PrecedenceParser.CARET_ID ? bp - 1 : bp + 1;
269
301
  this.parseExpression(rightBp, builder);
270
302
  builder.emitOpcode(_PrecedenceParser.INFIX_OPCODE[typeId]);
271
303
  }
@@ -341,10 +373,8 @@ var _PrecedenceParser = class _PrecedenceParser {
341
373
  return;
342
374
  }
343
375
  case _PrecedenceParser.BIGINT_ID: {
344
- let raw = token.value;
345
- if (raw.endsWith("n")) raw = raw.slice(0, -1);
346
376
  builder.emitOpcode(11 /* PUSH_BIGINT */);
347
- builder.emitString(raw);
377
+ builder.emitString(bigIntLiteralDigits(token.value, this.localeCode));
348
378
  return;
349
379
  }
350
380
  case _PrecedenceParser.STRING_ID: {
@@ -669,6 +699,7 @@ _PrecedenceParser.MOD_ID = tokenTypeId(TokenTypes.MOD);
669
699
  _PrecedenceParser.CARET_ID = tokenTypeId(TokenTypes.CARET);
670
700
  _PrecedenceParser.LSHIFT_ID = tokenTypeId(TokenTypes.LSHIFT);
671
701
  _PrecedenceParser.RSHIFT_ID = tokenTypeId(TokenTypes.RSHIFT);
702
+ _PrecedenceParser.URSHIFT_ID = tokenTypeId(TokenTypes.URSHIFT);
672
703
  _PrecedenceParser.BIT_AND_ID = tokenTypeId(TokenTypes.BIT_AND);
673
704
  _PrecedenceParser.BIT_OR_ID = tokenTypeId(TokenTypes.BIT_OR);
674
705
  _PrecedenceParser.BIT_XOR_ID = tokenTypeId(TokenTypes.BIT_XOR);
@@ -687,6 +718,7 @@ _PrecedenceParser.INFIX_OPCODE = {
687
718
  [tokenTypeId(TokenTypes.CARET)]: 25 /* EXP */,
688
719
  [tokenTypeId(TokenTypes.LSHIFT)]: 30 /* LSHIFT */,
689
720
  [tokenTypeId(TokenTypes.RSHIFT)]: 31 /* RSHIFT */,
721
+ [tokenTypeId(TokenTypes.URSHIFT)]: 32 /* URSHIFT */,
690
722
  [tokenTypeId(TokenTypes.BIT_AND)]: 33 /* BIT_AND */,
691
723
  [tokenTypeId(TokenTypes.BIT_OR)]: 34 /* BIT_OR */,
692
724
  [tokenTypeId(TokenTypes.BIT_XOR)]: 35 /* BIT_XOR */,
@@ -771,5 +803,5 @@ _PrecedenceParser.CARET_SUFFIX_RULES = [
771
803
  var PrecedenceParser = _PrecedenceParser;
772
804
 
773
805
  export { ParseletRegistry, PrecedenceParser, sharedParseletRegistry };
774
- //# sourceMappingURL=chunk-MEOHSQEH.js.map
775
- //# sourceMappingURL=chunk-MEOHSQEH.js.map
806
+ //# sourceMappingURL=chunk-3LAEG75D.js.map
807
+ //# sourceMappingURL=chunk-3LAEG75D.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parser/registry/ParseletRegistry.ts","../src/parser/PrecedenceParser.ts"],"names":[],"mappings":";;;;;;;AAyBA,SAAS,gBAAgB,QAAA,EAAiE;AACzF,EAAA,OAAO,QAAA;AACR;AAcO,IAAM,mBAAN,MAAuB;AAAA,EAAvB,WAAA,GAAA;AAEN;AAAA,IAAA,IAAA,CAAQ,eAAA,uBAAmD,GAAA,EAAI;AAC/D,IAAA,IAAA,CAAQ,cAAA,uBAAiD,GAAA,EAAI;AAG7D;AAAA,IAAA,IAAA,CAAQ,UAAA,uBAA8C,GAAA,EAAI;AAC1D,IAAA,IAAA,CAAQ,SAAA,uBAA4C,GAAA,EAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBxD,cAAA,CAAe,WAAmB,QAAA,EAAgC;AACjE,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,eAAA,CAAgB,GAAA,CAAI,SAAS,CAAA;AACnD,IAAA,IAAI,QAAA,IAAY,aAAa,QAAA,EAAU;AACtC,MAAA,OAAA,CAAQ,IAAA;AAAA,QACP,CAAA,8CAAA,EAAiD,SAAS,CAAA,oCAAA,EAC3C,QAAA,CAAS,YAA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parselet\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\n\n/**\n * The one binding-power field a parselet may expose beyond what its interface\n * requires, read only for diagnostic display.\n *\n * `InfixParselet` requires `bindingPower`; `PrefixParselet` declares none, and\n * some prefix parselets carry one anyway. That single field is the whole\n * optional surface deliberately. A `leftBindingPower`/`rightBindingPower` pair\n * used to be read here as well, and reading a name off an object this way finds\n * PRIVATE fields too, since TypeScript's `private` exists only at compile time:\n * `BinaryOpParselet` holds a private `rightBindingPower` meaning \"the minimum\n * power to parse my right operand at\", which is a different quantity from \"the\n * power at which I bind to my right\" and differs from it by one. Reading it\n * silently reported that other number. So neither is read.\n *\n * `category` is not here: both interfaces already declare it.\n */\ninterface ParseletBindingPowers {\n\treadonly bindingPower?: number;\n}\n\n/** Reads the optional binding-power field off a parselet for diagnostics. */\nfunction bindingPowersOf(parselet: PrefixParselet | InfixParselet): ParseletBindingPowers {\n\treturn parselet as ParseletBindingPowers;\n}\n\n/**\n * Dual-keyed ParseletRegistry, accepts both string token types and\n * integer token type IDs for fast dispatch in the Parser hot path.\n *\n * Providers call registerPrefix(\"NUMBER\", ...) with string token types.\n * Internally, we populate both string-keyed and integer-keyed maps so\n * Parser.parseExpression() can use token.typeId (integer) for lookup\n * while diagnostics and error messages use token.type (string).\n *\n * Performance: Integer Map.get() avoids string hashing, saving ~2-5ns\n * per dispatch. With ~10-15 dispatches per expression, that's ~20-75ns.\n */\nexport class ParseletRegistry {\n\t// String-keyed maps (kept for diagnostics + backwards compat)\n\tprivate prefixParselets: Map<string, PrefixParselet> = new Map();\n\tprivate infixParselets: Map<string, InfixParselet> = new Map();\n\n\t// Integer-keyed maps for parser hot path\n\tprivate prefixById: Map<number, PrefixParselet> = new Map();\n\tprivate infixById: Map<number, InfixParselet> = new Map();\n\n\t/**\n\t * Register a prefix parselet for `tokenType`.\n\t *\n\t * If another parselet is already registered for this token type, it is\n\t * silently overwritten by default (`Map.set()` semantics), the old\n\t * parselet is simply unreachable from then on, with no error. This is\n\t * a real footgun for third-party packages: two packages independently\n\t * choosing the same custom token type will collide with zero signal\n\t * about which one \"won\". Mirrors ResolverRegistry.register()'s and\n\t * ExpressionEngine.registerPackage()'s existing \"warn and replace\"\n\t * pattern for the same class of problem at the resolver-namespace and\n\t * package-name levels.\n\t *\n\t * Note: this warns about registry-level collisions only. It does NOT\n\t * detect the separate case where `tokenType` is one of PrecedenceParser's\n\t * Tier-1 fast-path token types (NUMBER, STRING, IDENT, LPAREN, MINUS,\n\t * PLUS, and the Tier-1 infix operators), those are deliberately kept\n\t * registered here for introspection/diagnostics even though Tier-1\n\t * always intercepts them before this registry is consulted (see\n\t * PrecedenceParser.parsePrefix()'s docs), so warning there would\n\t * misfire on that intentional, already-documented pattern.\n\t */\n\tregisterPrefix(tokenType: string, parselet: PrefixParselet): void {\n\t\tconst existing = this.prefixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Prefix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.prefixParselets.set(tokenType, parselet);\n\t\tthis.prefixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/** Register an infix parselet for `tokenType`. See {@link registerPrefix} for the collision-warning behavior this mirrors. */\n\tregisterInfix(tokenType: string, parselet: InfixParselet): void {\n\t\tconst existing = this.infixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Infix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.infixParselets.set(tokenType, parselet);\n\t\tthis.infixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/**\n\t * Iterate all registered prefix parselets for diagnostic display.\n\t *\n\t * `PrefixParselet` declares no binding power, and this used to read a field\n\t * of that name and report 0 for every one of them. 0 is not a neutral\n\t * wrong answer: it is the value that means \"not an operator, stop the\n\t * expression\", so a host drawing a table from this was told none of them\n\t * bind at all. A prefix parselet in this parser has no per-parselet power\n\t * to report, they all bind at the prefix level and each chooses for itself\n\t * at what power to parse its own operand, so that level is what is\n\t * reported. A parselet that does carry its own `bindingPower` still wins.\n\t */\n\tgetAllPrefix(): Array<{ tokenType: string; bindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; bindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.prefixParselets) {\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tbindingPower: bindingPowersOf(parselet).bindingPower ?? BindingPower.Prefix,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterate all registered infix parselets for diagnostic display.\n\t *\n\t * The field an `InfixParselet` actually declares is `bindingPower`. This\n\t * used to read `leftBindingPower` and `rightBindingPower`, which no\n\t * parselet in this codebase declares, so both reads were `undefined`, both\n\t * fell to the `?? 0` default, and the public `getParseletRegistry()`\n\t * reported a binding power of 0 for every one of the ~60 infix operators.\n\t * A host building a precedence table from it was told `*` and `+` bind\n\t * equally, and that neither binds at all.\n\t *\n\t * The left/right split: `bindingPower` is the LEFT power, and the right is\n\t * one higher. That is the standard encoding for a left-associative\n\t * operator, and it is what the parser itself does, see\n\t * `PrecedenceParser.parseExpression()`'s `bp + 1` for the right operand.\n\t * Every operator is reported that way, `^` included. Associativity is not\n\t * something a parselet declares, it is a property of how each one calls\n\t * `parseExpression`, so this API cannot report it without a new field on\n\t * the interface. See {@link ParseletBindingPowers} for why scraping a\n\t * plausible-looking one off the parselet is worse than not reporting it.\n\t */\n\tgetAllInfix(): Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.infixParselets) {\n\t\t\tconst left = bindingPowersOf(parselet).bindingPower ?? 0;\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tleftBindingPower: left,\n\t\t\t\trightBindingPower: left + 1,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Number of registered prefix parselets. */\n\tget prefixCount(): number { return this.prefixParselets.size; }\n\n\t/** Number of registered infix parselets. */\n\tget infixCount(): number { return this.infixParselets.size; }\n\n\t/**\n\t * Get prefix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings\n\t * (diagnostics, error messages, backwards compatibility).\n\t */\n\tgetPrefix(tokenType: string | number): PrefixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.prefixById.get(tokenType);\n\t\treturn this.prefixParselets.get(tokenType);\n\t}\n\n\t/**\n\t * Get infix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings.\n\t */\n\tgetInfix(tokenType: string | number): InfixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.infixById.get(tokenType);\n\t\treturn this.infixParselets.get(tokenType);\n\t}\n\n\thasPrefix(tokenType: string): boolean {\n\t\treturn this.prefixParselets.has(tokenType);\n\t}\n\n\thasInfix(tokenType: string): boolean {\n\t\treturn this.infixParselets.has(tokenType);\n\t}\n\n\tclear(): void {\n\t\tthis.prefixParselets.clear();\n\t\tthis.infixParselets.clear();\n\t\tthis.prefixById.clear();\n\t\tthis.infixById.clear();\n\t}\n}\n\n/**\n * A process-wide parselet registry.\n *\n * @deprecated An engine builds its own registry and does not read this one, so\n * registering here reaches nothing that evaluates. It survives for the\n * deprecated {@link PackageRegistry} path only.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n","import { ParseletRegistry } from \"@solve-js/parser/registry/ParseletRegistry\";\nimport { Token, tokenTypeId, TokenTypes } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DiagnosticPipeline, DiagnosticEventType, type DiagnosticEvent } from \"@solve-js/diagnostics\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower, buildBindingPowerTable } from \"@solve-js/parser/BindingPower\";\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { bigIntLiteralDigits } from \"@solve-js/parser/BigIntLiteral\";\n\n/**\n * Matches a CHAINED thousands-grouped integer using \".\" as the group\n * separator (e.g. \"1.234.567\"), independent of locale. Kept in sync with\n * the identical constant in NumberParselet.ts (not imported from there\n * that file transitively re-imports PrecedenceParser via Parser.ts's\n * `export { PrecedenceParser as Parser }`, so importing the other\n * direction would create a circular dependency for the sake of one\n * regex literal). See NumberParselet.ts's copy for the full explanation.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/**\n * ── Hybrid Precedence Climbing Parser ─────────────────────────────────────────\n *\n * Two-tier dispatch strategy:\n *\n * Tier 1 (Fast Path): Inline switch on token.typeId for built-in operators.\n * - Prefix: NUMBER, IDENT, LPAREN, MINUS, PLUS, STRING\n * - Infix: checked via static BP_TABLE (Uint8Array indexed by typeId)\n * - No Map.get(), no parselet function call overhead for ~95% of tokens\n *\n * Tier 2 (Plugin Path): ParseletRegistry fallback for custom/plugin tokens.\n * - Prefix: Map.get(tokenTypeId) for PrefixParselet\n * - Infix: Map.get(tokenTypeId) for InfixParselet\n * - Full flexibility for custom syntax\n *\n * The parser emits directly to a BytecodeBuilder, no AST intermediate.\n * Implements the same public API as the legacy Parser class so existing\n * parselets continue to work without modification.\n */\nexport class PrecedenceParser {\n private tokens: Token[] = [];\n private current = 0;\n private depth = 0;\n private maxDepth: number;\n\n /** Cached registry reference, avoids property chain in hot loop */\n private registry: ParseletRegistry;\n\n /** BytecodeBuilder, set before each parseExpression call */\n private builder!: BytecodeBuilder;\n\n /** Diagnostic pipeline for parselet-matched events */\n private diagnosticPipeline: DiagnosticPipeline | undefined;\n private currentExpression: string = \"\";\n private localeCode: string;\n\n /**\n * Static binding power table, built once at module load, shared across all instances.\n * Index = tokenTypeId, value = binding power (0 = not a built-in infix).\n */\n static readonly BP_TABLE: Uint8Array = buildBindingPowerTable();\n\n // ── Pre-computed token type IDs for inline dispatch ────────────────────────\n // Prefix built-ins\n private static readonly NUMBER_ID = tokenTypeId(TokenTypes.NUMBER);\n private static readonly BIGINT_ID = tokenTypeId(TokenTypes.BIGINT);\n private static readonly STRING_ID = tokenTypeId(TokenTypes.STRING);\n private static readonly IDENT_ID = tokenTypeId(TokenTypes.IDENT);\n private static readonly LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n private static readonly RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n private static readonly MINUS_ID = tokenTypeId(TokenTypes.MINUS);\n private static readonly PLUS_ID = tokenTypeId(TokenTypes.PLUS);\n private static readonly KEYWORD_ID = tokenTypeId(TokenTypes.KEYWORD);\n\n // Infix built-ins (Tier 1, full inline emission)\n private static readonly STAR_ID = tokenTypeId(TokenTypes.STAR);\n private static readonly SLASH_ID = tokenTypeId(TokenTypes.SLASH);\n private static readonly MOD_ID = tokenTypeId(TokenTypes.MOD);\n private static readonly CARET_ID = tokenTypeId(TokenTypes.CARET);\n private static readonly LSHIFT_ID = tokenTypeId(TokenTypes.LSHIFT);\n private static readonly RSHIFT_ID = tokenTypeId(TokenTypes.RSHIFT);\n private static readonly URSHIFT_ID = tokenTypeId(TokenTypes.URSHIFT);\n private static readonly BIT_AND_ID = tokenTypeId(TokenTypes.BIT_AND);\n private static readonly BIT_OR_ID = tokenTypeId(TokenTypes.BIT_OR);\n private static readonly BIT_XOR_ID = tokenTypeId(TokenTypes.BIT_XOR);\n private static readonly PERCENT_ID = tokenTypeId(TokenTypes.PERCENT);\n private static readonly OF_ID = tokenTypeId(TokenTypes.OF);\n\n /**\n * Inline opcode map for Tier 1 infix operators.\n * tokenTypeId → OpCode. PERCENT and CARET are handled specially (not in this map).\n */\n private static readonly INFIX_OPCODE: Record<number, OpCode> = {\n [tokenTypeId(TokenTypes.PLUS)]: OpCode.ADD,\n [tokenTypeId(TokenTypes.MINUS)]: OpCode.SUB,\n [tokenTypeId(TokenTypes.STAR)]: OpCode.MUL,\n [tokenTypeId(TokenTypes.SLASH)]: OpCode.DIV,\n [tokenTypeId(TokenTypes.MOD)]: OpCode.MOD,\n [tokenTypeId(TokenTypes.CARET)]: OpCode.EXP,\n [tokenTypeId(TokenTypes.LSHIFT)]: OpCode.LSHIFT,\n [tokenTypeId(TokenTypes.RSHIFT)]: OpCode.RSHIFT,\n [tokenTypeId(TokenTypes.URSHIFT)]: OpCode.URSHIFT,\n [tokenTypeId(TokenTypes.BIT_AND)]: OpCode.BIT_AND,\n [tokenTypeId(TokenTypes.BIT_OR)]: OpCode.BIT_OR,\n [tokenTypeId(TokenTypes.BIT_XOR)]: OpCode.BIT_XOR,\n [tokenTypeId(TokenTypes.OF)]: OpCode.MUL,\n };\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\") {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n }\n\n /** Get locale code for NumberParselet to normalize separators */\n getLocaleCode(): string {\n return this.localeCode;\n }\n\n /**\n * Set the diagnostic pipeline for parselet matching events.\n * Cleared after each non-cached parse to avoid holding refs.\n */\n setDiagnosticPipeline(pipeline: DiagnosticPipeline | undefined, expression: string): void {\n this.diagnosticPipeline = pipeline;\n this.currentExpression = expression ?? \"\";\n }\n\n /**\n * Load tokens for parsing. Identical to Parser.load().\n *\n * @param hasParens - if false, skips the O(n) paren balance scan (~90% of expressions)\n */\n load(tokens: Token[], hasParens?: boolean): void {\n if (hasParens === false) {\n this.tokens = tokens;\n this.current = 0;\n this.depth = 0;\n return;\n }\n // Paren scan: count balance to skip array copy for balanced expressions.\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n let openCount = 0;\n for (let i = 0; i < tokens.length; i++) {\n if (tokens[i].typeId === LPAREN_ID) openCount++;\n else if (tokens[i].typeId === RPAREN_ID) openCount--;\n }\n this.tokens = openCount === 0 ? tokens : this.balanceParens(tokens, openCount);\n this.current = 0;\n this.depth = 0;\n }\n\n /**\n * Auto-balance unmatched parentheses.\n */\n private balanceParens(tokens: Token[], openCount: number): Token[] {\n const result = tokens.slice();\n if (openCount > 0) {\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n for (let i = 0; i < openCount; i++) {\n const lastToken = tokens[tokens.length - 1];\n result.push({\n type: TokenTypes.RPAREN,\n typeId: RPAREN_ID,\n value: \")\",\n text: \")\",\n offset: lastToken ? lastToken.offset + lastToken.text.length : 0,\n lineBreaks: 0,\n line: lastToken ? lastToken.line : 1,\n col: lastToken ? lastToken.col + lastToken.text.length : 1,\n } as Token);\n }\n } else if (openCount < 0) {\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n for (let i = 0; i < -openCount; i++) {\n result.unshift({\n type: TokenTypes.LPAREN,\n typeId: LPAREN_ID,\n value: \"(\",\n text: \"(\",\n offset: 0,\n lineBreaks: 0,\n line: 1,\n col: 1,\n } as Token);\n }\n }\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Main entry point: precedence climbing parse expression\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a full expression starting at the current token position.\n *\n * @param minBp - minimum binding power (precedence climbing threshold).\n * For left-associative operators, the recursive call uses `bp + 1`.\n * For right-associative operators (^), it uses `bp - 1`.\n * @param _builder - accepted for parselet API compatibility; always uses `this.builder`.\n */\n parseExpression(minBp: number = 0, _builder?: BytecodeBuilder): void {\n // Accept builder via parameter for backward compatibility with the old Parser API.\n // The ExpressionEngine always calls setBuilder() before parseExpression(),\n // but tests and parselets pass builder as a parameter.\n if (_builder) {\n this.builder = _builder;\n }\n this.depth++;\n if (this.depth > this.maxDepth) {\n this.depth--;\n throw ErrorFactory.parsing(\n \"NESTING_DEPTH_EXCEEDED\",\n `Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,\n { maxDepth: this.maxDepth, currentDepth: this.depth }\n );\n }\n\n const token = this.consume();\n if (!token) {\n this.depth--;\n throw ErrorFactory.parsing(\"UNEXPECTED_END\", \"Unexpected end of expression\");\n }\n\n // ── Prefix ──────────────────────────────────────────────────────────────\n this.parsePrefix(token);\n\n // ── Infix loop (precedence climbing with inline Tier 1 dispatch) ──────────\n const tokens = this.tokens;\n const len = tokens.length;\n const bpTable = PrecedenceParser.BP_TABLE;\n const registry = this.registry;\n const builder = this.builder;\n let idx = this.current;\n\n while (idx < len) {\n const lookahead = tokens[idx];\n if (!lookahead) break;\n\n const bp = bpTable[lookahead.typeId];\n if (bp > 0) {\n // Tier 1: Built-in infix, full inline emission, zero parselet delegation\n if (bp <= minBp) break;\n\n if (this.diagnosticPipeline) {\n // Fast path skips the registry, but built-ins are still registered\n // there (for introspection/tests), look them up only in this\n // diagnostics-only branch so the playground's \"matched parselets\"\n // view isn't permanently blind to every arithmetic operator.\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (infixParselet) {\n this.fireParseletMatched(infixParselet, lookahead, false, bp);\n }\n }\n\n this.current = ++idx;\n const typeId = lookahead.typeId;\n\n if (typeId === PrecedenceParser.PERCENT_ID) {\n // Postfix: no right operand. \"50%\" → Percentage holding 0.5.\n //\n // Must stay byte-for-byte equivalent to PercentParselet, which is\n // the Tier-2 registration of the same operator. This path is the one\n // that actually runs for ordinary expressions, so a change made only\n // in the parselet does nothing at all: that is exactly how the\n // divide-by-100 here outlived its replacement and kept `200 + 10%`\n // answering 200.10.\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(100);\n builder.emitOpcode(OpCode.DIV);\n builder.emitOpcode(OpCode.TO_PERCENTAGE);\n } else if (typeId === PrecedenceParser.CARET_ID && this.tryEmitMatrixCaretOp(builder)) {\n // `^T` (transpose) or `^-1` (inverse), already fully handled\n // including consuming their own trailing tokens.\n } else {\n // Infix: parse right operand, then emit opcode.\n // Right-associative for CARET (^), left-associative for all others.\n //\n // The threshold has to be bp - 1, not bp. The loop above breaks on\n // `bp <= minBp`, so a right operand parsed at `bp` stops at the next\n // `^` exactly as one parsed at `bp + 1` does: the old special case\n // was dead code and \"2 ^ 3 ^ 2\" grouped left, answering 64. One\n // below lets the recursive call keep consuming `^`, which is what\n // makes it 2^(3^2) = 512, as in mathematics, Python, Ruby and\n // JavaScript's `**`.\n //\n // Nothing else sits between Exponent (50) and Product (40), so\n // 49 cannot collide with another operator's level. Unary minus is\n // unaffected: it parses its operand at Prefix (60), above `^`\n // either way, so \"-2 ^ 2\" is still (-2)^2 = 4.\n const rightBp = (typeId === PrecedenceParser.CARET_ID) ? bp - 1 : bp + 1;\n this.parseExpression(rightBp, builder);\n builder.emitOpcode(PrecedenceParser.INFIX_OPCODE[typeId]);\n }\n } else {\n // Tier 2: Plugin parselet fallback, full flexibility for custom syntax\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (!infixParselet) break;\n if (infixParselet.bindingPower <= minBp) break;\n\n this.current = ++idx;\n\n if (this.diagnosticPipeline) {\n this.fireParseletMatched(infixParselet, lookahead, false, infixParselet.bindingPower);\n }\n // Parselet handles its own recursion for right operand internally\n infixParselet.parse(this, token, lookahead, builder);\n }\n\n idx = this.current;\n }\n\n this.current = idx;\n this.depth--;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Prefix dispatch: inline switch for built-ins, parselet registry for plugins\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a prefix token. Built-in tokens (NUMBER, IDENT, LPAREN, etc.) are\n * handled inline with zero registry lookup. Everything else falls through\n * to the parselet registry (Tier 2).\n */\n private parsePrefix(token: Token): void {\n const builder = this.builder;\n const typeId = token.typeId;\n\n if (this.diagnosticPipeline) {\n // Fast path below skips the registry for built-ins, but they're still\n // registered there (for introspection/tests), look up here so the\n // playground's \"matched parselets\" view isn't permanently blind to\n // every number, identifier, paren, and unary operator.\n const parselet = this.registry.getPrefix(typeId);\n if (parselet) {\n this.fireParseletMatched(parselet, token, true);\n }\n }\n\n switch (typeId) {\n // ── Numeric literals ──────────────────────────────────────────────────\n case PrecedenceParser.NUMBER_ID: {\n // Parse number with locale-aware separator normalization\n let v: number;\n const raw = token.value;\n if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n v = parseInt(raw, 16);\n // A prefix with no digits after it (\"0x\" alone) makes parseInt\n // return NaN. This used to push straight through as a silent\n // NaN Number value instead of a visible error.\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid hex literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0b\") || raw.startsWith(\"0B\")) {\n v = parseInt(raw.slice(2), 2);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid binary literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0o\") || raw.startsWith(\"0O\")) {\n v = parseInt(raw.slice(2), 8);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid octal literal: \"${raw}\"`, { raw });\n }\n } else if (CHAINED_DOT_THOUSANDS_GROUPS.test(raw)) {\n // The lexer accepts \".\" as a thousands-group separator\n // independent of locale (ExpressionLexer's number-scanning\n // \"Thousands separators\" block), but the locale-based\n // normalization below only strips the ACTIVE locale's own\n // configured thousandsSeparator character, for \"en\" that's\n // \",\", not \".\", so a chained dot-grouped literal like\n // \"1.234.567\" fell through to parseFloat() untouched, which\n // stops at the second \".\" and silently truncated it to 1.234\n // (over 99% of the digits dropped, with no error). This is the\n // REAL number-parsing path for actual evaluation, Tier 1 of\n // the two-tier dispatch above always returns for NUMBER_ID, so\n // NumberParselet.parse() (which has the identical fix) never\n // actually runs except via direct unit tests / the \"matched\n // parselets\" diagnostic display.\n v = parseFloat(raw.split(\".\").join(\"\"));\n } else {\n const locale = getLocale(this.localeCode);\n const decimalSep = locale.display.decimalSeparator;\n const thousandsSep = locale.display.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation)\n if (thousandsSep) {\n normalized = normalized.split(thousandsSep).join(\"\");\n }\n // Replace locale decimal separator with \".\" for JavaScript parsing\n if (decimalSep && decimalSep !== \".\") {\n normalized = normalized.replace(decimalSep, \".\");\n }\n v = parseFloat(normalized);\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(v);\n return;\n }\n\n case PrecedenceParser.BIGINT_ID: {\n // Strips the `n` and any thousands grouping the lexer coalesced in.\n // This used to be `raw.slice(0, -1)` and nothing else, so `1.000n`\n // reached BigInt(\"1.000\") and threw a raw SyntaxError. See\n // parser/BigIntLiteral.ts, which the parselet tier shares.\n builder.emitOpcode(OpCode.PUSH_BIGINT);\n builder.emitString(bigIntLiteralDigits(token.value, this.localeCode));\n return;\n }\n\n case PrecedenceParser.STRING_ID: {\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(token.value);\n return;\n }\n\n // ── Identifiers (variables) ────────────────────────────────────────────\n case PrecedenceParser.IDENT_ID: {\n // An identifier immediately followed by \"(\" may be a user-defined\n // function DEFINITION (`f(x) = ...`) or CALL (`f(5)`). See\n // parseUserFunctionDefOrCall's doc comment for the full\n // disambiguation. Only the (cheap) LPAREN check runs for the\n // overwhelmingly common case of a bare identifier with nothing\n // following it.\n if (this.peek()?.typeId === PrecedenceParser.LPAREN_ID) {\n this.parseUserFunctionDefOrCall(token, builder);\n return;\n }\n // IDENT tokens map to LOAD_VAR by default. The IdentifierParselet\n // and VariableParselet add STORE_VAR for assignments, those are\n // handled via the parselet registry below. Note this is also how a\n // user-defined function's own PARAMETER references compile. See\n // UserFunctionDef's doc comment in BytecodeBuilder.ts for why there\n // is no separate parameter-load opcode: `LOAD_VAR` resolution\n // dynamically checks the VM's innermost call frame first.\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(token.value);\n return;\n }\n\n // ── Grouping / bare-tuple vector literal ─────────────────────────────────\n // `(expr)` groups for precedence; `(x, y[, z[, w]])` is the bare-tuple\n // vector literal documented as an alternative to vec2/vec3/vec4(...)\n // (wiki: Arithmetic/Vector). This Tier-1 case is what actually runs for\n // every LPAREN in production parsing, GroupParselet.ts mirrors this\n // logic for registry-introspection/diagnostic-listing purposes, but a\n // package can never override LPAREN's dispatch here (Tier 1 always\n // wins over the ParseletRegistry fallback below), so both must be kept\n // in sync by hand.\n case PrecedenceParser.LPAREN_ID: {\n this.parseExpression(0, builder);\n let count = 1;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(0, builder);\n count++;\n }\n this.consume(TokenTypes.RPAREN);\n if (count > 1) {\n // Legacy bare-tuple vector sugar, a 1xN row-vector Matrix (see\n // packages/vector/parselets/VectorParselet.ts's comment).\n builder.emitOpcode(OpCode.MAT_NEW);\n builder.emitIndex(1);\n builder.emitIndex(count);\n }\n return;\n }\n\n // ── Unary operators ───────────────────────────────────────────────────\n case PrecedenceParser.MINUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.NEG);\n return;\n }\n\n case PrecedenceParser.PLUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.POS);\n return;\n }\n\n // ── Keyword constants ─────────────────────────────────────────────────\n case PrecedenceParser.KEYWORD_ID: {\n // Keywords are handled by parselets (pi→PI, e→E, etc.)\n // Fall through to registry below.\n }\n }\n\n // ── Tier 2: Plugin/parselet prefix path ──────────────────────────────────\n const prefixParselet = this.registry.getPrefix(typeId);\n if (!prefixParselet) {\n throw ErrorFactory.parsing(\n \"NO_PREFIX_PARSELET\",\n `No prefix parselet found for token: ${token.type} (\"${token.value}\")`,\n { tokenType: token.type, tokenValue: token.value }\n );\n }\n\n prefixParselet.parse(this, token, builder);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // The \"Tier-1 shape-exception\" pattern\n // ═══════════════════════════════════════════════════════════════════════════════\n //\n // Tier 1 exists purely for performance, avoid a Map lookup + parselet call\n // on ~95% of tokens (see this file's own module doc comment above). A\n // recurring consequence: any grammar shape tied to a Tier-1 token type can\n // ONLY be implemented by hand-editing this switch, since a package-\n // registered ParseletRegistry parselet for that same token type would\n // simply never run in production (Tier 1 always wins over the registry\n // fallback). Five confirmed instances of this tension exist in this file\n // (plus one that had to move OUTSIDE it entirely):\n // 1. NUMBER_ID, the full locale-aware number-literal parsing (hex/\n // binary/octal, chained-dot thousands grouping, decimal-separator\n // normalization) is inlined in parsePrefix() above; NumberParselet.ts's\n // own copy is dead code for real evaluation, kept registered only for\n // the \"matched parselets\" diagnostic view.\n // 2. IDENT_ID, parseUserFunctionDefOrCall's lookahead (below) disambig-\n // uates a function DEFINITION from a CALL from a plain variable load.\n // 3. LPAREN_ID, the bare-tuple vector-literal sugar (\"(x,y[,z[,w]])\" ->\n // MAT_NEW) is inlined in parsePrefix() above; GroupParselet.ts mirrors\n // it for introspection only and must be kept in sync by hand.\n // 4. CARET_ID, the transpose/inverse suffix table just below.\n // 5. PLUS_ID, the locale word \"and\" lexes as PLUS (Tier-1, fixed Sum\n // binding power), so a registry parselet can never intercept it the\n // way LogicalParselet.ts intercepts \"or\"/&&/||; unlike the other four,\n // there's no SHAPE to special-case on here (the token itself IS the\n // operator), so the workaround lives entirely outside this file, as a\n // runtime Boolean/Boolean type-check inside vm/VM.ts's OpCode.ADD\n // handler instead.\n //\n // Deliberate non-goal: none of this is exposed as an IEnginePackage\n // extension point (unlike prefixParselets/infixParselets). Letting\n // third-party packages register their own Tier-1 shape-matchers would put\n // per-package matcher iteration on a genuinely hot path (every CARET/\n // NUMBER/IDENT/LPAREN/PLUS token, matched or not), a materially bigger\n // separate product decision than \"make this one table more concise,\" and\n // not one this pattern write-up makes.\n\n /**\n * A single `^`-suffix shape: `matches` peeks ahead (consuming nothing) to\n * check whether this shape starts at the current position; `emit` is only\n * called immediately after `matches` returned true for that SAME position,\n * and is responsible for consuming that shape's own trailing tokens and\n * emitting its bytecode.\n */\n private static readonly CARET_SUFFIX_RULES: ReadonlyArray<{\n name: string;\n matches(parser: PrecedenceParser): boolean;\n emit(parser: PrecedenceParser, builder: BytecodeBuilder): void;\n }> = [\n {\n name: \"transpose (^T)\",\n matches: (p) => {\n const next = p.peek();\n return next?.type === TokenTypes.IDENT && next.value === \"T\";\n },\n emit: (p, builder) => {\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(63); // transpose — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n {\n name: \"inverse (^-1)\",\n matches: (p) => {\n const next = p.peek();\n if (next?.typeId !== PrecedenceParser.MINUS_ID) return false;\n const afterMinus = p.peekAt(1);\n return afterMinus?.type === TokenTypes.NUMBER && afterMinus.value === \"1\";\n },\n emit: (p, builder) => {\n p.advance();\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(65); // inv — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n ];\n\n /**\n * After a `^` token (already consumed by the Tier-1 infix loop above),\n * checks {@link CARET_SUFFIX_RULES} in order for a shape that means\n * something other than ordinary exponentiation: `^T` (transpose) and `^-1`\n * (matrix inverse, LITERALLY the integer exponent `-1`; `^-2`, `^-1.5`\n * etc. still mean ordinary exponentiation). On a match, the rule's `emit`\n * consumes that shape's own tokens and this returns `true`. On no match,\n * consumes NOTHING, returning `false` so the caller falls through to\n * ordinary `EXP` parsing.\n *\n * Every rule dispatches purely on SHAPE, never on operand type (unknowable\n * at parse time): `inv()`'s own handler (`VMBuiltins.ts` index 65) returns\n * `1/x` for a plain Number, byte-identical to what `Math.pow(x, -1)`\n * already computed for `x^-1` before this feature existed, and a real\n * matrix inverse for a Matrix, so `5^-1` still means exactly what it always\n * has; only a Matrix operand actually inverts.\n *\n * Adding a future `^`-suffix shape is a new table entry here, not a new\n * if-block. See the \"Tier-1 shape-exception\" pattern write-up above for\n * why this table can't instead be a package-registered parselet.\n */\n private tryEmitMatrixCaretOp(builder: BytecodeBuilder): boolean {\n for (const rule of PrecedenceParser.CARET_SUFFIX_RULES) {\n if (rule.matches(this)) {\n rule.emit(this, builder);\n return true;\n }\n }\n return false;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // User-defined, parameterized, reusable functions (f(x) = 2*x + 1, then f(5))\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * From an LPAREN token index, scan forward tracking paren depth and\n * return the index of the matching RPAREN, or `null` if the parens never\n * balance before the token stream ends. No emission, no position\n * advance. Same class of technique as {@link balanceParens}'s own\n * pre-scan, just exposed mid-parse instead of only at `load()` time.\n * `openIdx` must point AT the LPAREN itself.\n */\n private findMatchingRParen(openIdx: number): number | null {\n let depth = 0;\n for (let i = openIdx; i < this.tokens.length; i++) {\n const t = this.tokens[i];\n if (t.typeId === PrecedenceParser.LPAREN_ID) depth++;\n else if (t.typeId === PrecedenceParser.RPAREN_ID) {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n }\n\n /**\n * Disambiguates a bare `IDENT` immediately followed by `(` between three\n * things, using ONLY a bracket-depth scan (no backtracking, nothing is\n * consumed until the shape is known):\n * - `f(x) = expr`, a DEFINITION: the matching `)` is followed by `=`.\n * - `f(5)`, a CALL to a (possibly not-yet-defined) function: anything\n * else. This was never valid syntax before this feature (a bare\n * `IDENT` immediately before `(` has no pre-existing \"plain variable\n * read + separately grouped `(...)`\" meaning to preserve, confirmed\n * via `BuiltinNormalizerRules.ts`'s `implicitMultiplyRule()`, which\n * only inserts an implicit `*` for `NUMBER/RPAREN` immediately before\n * `IDENT/LPAREN`, never for a bare `IDENT` immediately before\n * `LPAREN`). Always commits to a CALL; an unregistered name produces a\n * clear `UNDEFINED_FUNCTION` error at VM-execution time, the same\n * forward-reference philosophy `LOAD_VAR`/`UNDEFINED_VARIABLE` already\n * uses, rather than any parse-time registry lookup.\n * If the parens never balance, this falls through to the ordinary\n * `LOAD_VAR` path (a malformed expression surfaces its own parse error\n * shortly after, from the normal expression grammar).\n */\n private parseUserFunctionDefOrCall(nameToken: Token, builder: BytecodeBuilder): void {\n const closeIdx = this.findMatchingRParen(this.current);\n if (closeIdx === null) {\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(nameToken.value);\n return;\n }\n const afterClose = this.tokens[closeIdx + 1];\n if (afterClose?.type === TokenTypes.EQUALS) {\n this.parseUserFunctionDefinition(nameToken, builder);\n } else {\n this.parseUserFunctionCall(nameToken, builder);\n }\n }\n\n /**\n * A parameter name, accepted as either `IDENT` or `UNIT`, matches this\n * codebase's established `:name = value` variable-name policy\n * (`VariableParselet.ts` explicitly accepts `UNIT`-typed tokens too, e.g.\n * `:b = 5` for the \"b\" bits unit) since common short parameter names\n * like `h`/`l`/`b`/`t`/`s`/`m` collide with real unit abbreviations\n * (hour, liter, bits, ton, second, meter, ...) and lex as `UNIT`, not\n * `IDENT`.\n */\n private consumeParamName(): string {\n const token = this.peek();\n if (token?.type === TokenTypes.IDENT || token?.type === TokenTypes.UNIT) {\n this.consume();\n return token.value;\n }\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_INVALID_PARAM_NAME\",\n `Expected a parameter name but got \"${token?.type ?? \"end of input\"}\"${token ? ` (\"${token.value}\")` : \"\"}`,\n { actualType: token?.type },\n );\n }\n\n private parseUserFunctionDefinition(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n const params: string[] = [];\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n params.push(this.consumeParamName());\n while (this.match(TokenTypes.COMMA)) {\n params.push(this.consumeParamName());\n }\n }\n this.consume(TokenTypes.RPAREN);\n this.consume(TokenTypes.EQUALS);\n\n if (params.length === 0) {\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_NO_PARAMS\",\n `\"${nameToken.value}()\" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,\n { name: nameToken.value },\n );\n }\n\n // Compile the body into its OWN independent BytecodeBuilder, reusing\n // the SAME parser/token stream but directing emission elsewhere.\n // `parseExpression(minBp, _builder)` sets `this.builder = _builder`\n // with NO automatic restore, explicitly restoring via `setBuilder()`\n // afterward (not a `finally`, since a thrown parse error here should\n // propagate as-is; there's no further use of `this.builder` on that\n // path before the whole parse aborts) avoids silently emitting\n // whatever parses next (in this same expression, or, via\n // ExpressionEngine's builder pool, a LATER, unrelated line) into a\n // stale, already-.build()'d body builder.\n const bodyBuilder = new BytecodeBuilder();\n this.parseExpression(BindingPower.Lowest, bodyBuilder);\n this.setBuilder(builder);\n\n const bodyProgram = bodyBuilder.build();\n if (bodyProgram.hasAsync) {\n // v1 scope decision: a function body calling an async plugin\n // (weather, stocks, currency, ...) isn't supported yet, propagating\n // a 'pending' result up through a reentrant executeBytecode() call\n // would need the OUTER expression's own bytecode position/stack\n // state to also be resumable later, which this first pass doesn't\n // implement. Rejecting at DEFINITION time (not call time) gives the\n // clearest possible error, matching this codebase's \"never silently\n // pretend to support something it doesn't\" convention (e.g.\n // addBusinessDays()'s own disclosed holiday-exclusion scope-down).\n throw ErrorFactory.parsing(\n \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n `\"${nameToken.value}(...)\"'s body calls an async operation (weather, stocks, currency, ...) — user-defined function bodies must be synchronous`,\n { name: nameToken.value },\n );\n }\n\n const bodyIdx = builder.emitUserFunctionBody(nameToken.value, params, bodyProgram);\n builder.emitOpcode(OpCode.DEFINE_USER_FUNCTION);\n builder.emitIndex(bodyIdx);\n\n // A definition line has no single input value to echo back the way an\n // assignment does, push a plain confirmation string, matching this\n // codebase's \"never silently produce a misleading numeric 0\" principle.\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(`${nameToken.value}(${params.join(\", \")}) defined`);\n }\n\n private parseUserFunctionCall(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n let argCount = 0;\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n this.consume(TokenTypes.RPAREN);\n\n builder.emitOpcode(OpCode.CALL_USER_FUNCTION);\n builder.emitString(nameToken.value);\n builder.emitByte(argCount);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Token stream navigation (identical API to Parser)\n // ═══════════════════════════════════════════════════════════════════════════════\n\n consume(expectedType?: string): Token {\n const token = this.tokens[this.current];\n if (!token) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_END_OF_INPUT\",\n \"Unexpected end of input\"\n );\n }\n if (expectedType !== undefined) {\n const expectedId = tokenTypeId(expectedType);\n if (token.typeId !== expectedId) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_TOKEN_TYPE\",\n `Expected token type \"${expectedType}\" but got \"${token.type}\" (\"${token.value}\")`,\n { expectedType, actualType: token.type, actualValue: token.value }\n );\n }\n }\n this.current++;\n return token;\n }\n\n match(expectedType: string): boolean {\n const token = this.peek();\n if (token && token.typeId === tokenTypeId(expectedType)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n peek(): Token | undefined {\n return this.tokens[this.current];\n }\n\n /**\n * Read-only lookahead `offset` tokens past the current position, without\n * consuming anything, `peekAt(0)` is equivalent to {@link peek}.\n * `this.tokens` is a plain in-memory array (not a stream), so this is a\n * simple, safe index read; no rewind/checkpoint mechanism is needed since\n * nothing is consumed.\n */\n peekAt(offset: number): Token | undefined {\n return this.tokens[this.current + offset];\n }\n\n previous(): Token | undefined {\n return this.current > 0 ? this.tokens[this.current - 1] : undefined;\n }\n\n private advance(): void {\n this.current++;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Builder access, set before parse, read by inline prefix handlers\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /** Set the builder to use for the current parse. Called by ExpressionEngine. */\n setBuilder(builder: BytecodeBuilder): void {\n this.builder = builder;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Diagnostics\n // ═══════════════════════════════════════════════════════════════════════════════\n\n private fireParseletMatched(\n parselet: { category: string },\n token: Token,\n isPrefix: boolean,\n bindingPower?: number\n ): void {\n const pipeline = this.diagnosticPipeline!;\n const event: DiagnosticEvent & { type: \"parselet_matched\" } = {\n type: DiagnosticEventType.ParseletMatched,\n elapsedNs: 0,\n expression: this.currentExpression,\n tokenType: token.type,\n tokenValue: token.value,\n parseletCategory: parselet.category,\n parseletType: parselet.constructor?.name ?? \"unknown\",\n isPrefix,\n bindingPower,\n tokenOffset: token.offset || 0,\n };\n pipeline.fireParseletMatched(event);\n }\n}\n"]}