solve-engine 2.23.0 → 2.25.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 (226) hide show
  1. package/README.md +82 -32
  2. package/dist/{BytecodeBuilder-aqVa7Plx.d.cts → BytecodeBuilder-DSWKZi4f.d.cts} +11 -9
  3. package/dist/{BytecodeBuilder-aqVa7Plx.d.ts → BytecodeBuilder-DSWKZi4f.d.ts} +11 -9
  4. package/dist/{Configuration-BGQn-cJ8.d.cts → Configuration-DnzYPmoK.d.cts} +33 -0
  5. package/dist/{Configuration-BGQn-cJ8.d.ts → Configuration-DnzYPmoK.d.ts} +33 -0
  6. package/dist/{EngineError-DTk7I7hZ.d.cts → EngineError-fR1K1rvx.d.cts} +6 -0
  7. package/dist/{EngineError-DTk7I7hZ.d.ts → EngineError-fR1K1rvx.d.ts} +6 -0
  8. package/dist/{Lexer-CqagTewQ.d.ts → Lexer-Bmctxl0n.d.ts} +84 -35
  9. package/dist/{Lexer-CCHFDcgP.d.cts → Lexer-aB95pjoX.d.cts} +84 -35
  10. package/dist/{PackageCompatibility-BGXSFuL9.d.ts → PackageCompatibility-BludTs7v.d.ts} +1 -1
  11. package/dist/{PackageCompatibility-BZCqaTOO.d.cts → PackageCompatibility-CUVg8tmt.d.cts} +1 -1
  12. package/dist/{PackageRegistry-BRoVOYzg.d.ts → PackageRegistry-DT-x32OM.d.ts} +67 -14
  13. package/dist/{PackageRegistry-rMGnTh7W.d.cts → PackageRegistry-Dvn4i2QK.d.cts} +67 -14
  14. package/dist/{Parselet-Bkbp9CKD.d.cts → Parselet-BawfGuTF.d.cts} +8 -2
  15. package/dist/{Parselet-B-WyUtX4.d.ts → Parselet-DqTbbtWA.d.ts} +8 -2
  16. package/dist/{ScopeManager-gB9UengK.d.ts → ScopeManager-B636am7Y.d.ts} +39 -8
  17. package/dist/{ScopeManager-bCYewWVt.d.cts → ScopeManager-CdwX0VTw.d.cts} +39 -8
  18. package/dist/{TokenNormalizer-OTPS0Otq.d.ts → TokenNormalizer-CLBtiE8M.d.ts} +45 -26
  19. package/dist/{TokenNormalizer-MXaKLJ_m.d.cts → TokenNormalizer-CjTDmHgB.d.cts} +45 -26
  20. package/dist/{VMCheckpoints-DGar9Yg8.d.cts → VMCheckpoints-CYqeq8IV.d.cts} +3 -3
  21. package/dist/{VMCheckpoints-BDRY1Kx8.d.ts → VMCheckpoints-DDlxNssY.d.ts} +3 -3
  22. package/dist/{Value-DCTqTSeP.d.cts → Value-Ds3Gy07C.d.cts} +1 -1
  23. package/dist/{Value-DCTqTSeP.d.ts → Value-Ds3Gy07C.d.ts} +1 -1
  24. package/dist/{WorkerError-DGBNM3gA.d.cts → WorkerError-B1dF3VYT.d.cts} +1 -1
  25. package/dist/{WorkerError-DpZgKRks.d.ts → WorkerError-dneODN-u.d.ts} +1 -1
  26. package/dist/{chunk-YAONCEAW.cjs → chunk-4BAUQE6A.cjs} +3 -3
  27. package/dist/{chunk-YAONCEAW.cjs.map → chunk-4BAUQE6A.cjs.map} +1 -1
  28. package/dist/chunk-4BRTUFTH.js +2 -0
  29. package/dist/chunk-4BRTUFTH.js.map +1 -0
  30. package/dist/chunk-4NZXCHQL.cjs +2 -0
  31. package/dist/chunk-4NZXCHQL.cjs.map +1 -0
  32. package/dist/chunk-57PSJQQW.js +3 -0
  33. package/dist/chunk-57PSJQQW.js.map +1 -0
  34. package/dist/chunk-634ILVMP.cjs +2 -0
  35. package/dist/chunk-634ILVMP.cjs.map +1 -0
  36. package/dist/{chunk-HMC7FJO7.js → chunk-63ZOOUOL.js} +2 -2
  37. package/dist/{chunk-HMC7FJO7.js.map → chunk-63ZOOUOL.js.map} +1 -1
  38. package/dist/chunk-72PYPENZ.js +2 -0
  39. package/dist/chunk-72PYPENZ.js.map +1 -0
  40. package/dist/chunk-77KI7AKJ.cjs +2 -0
  41. package/dist/chunk-77KI7AKJ.cjs.map +1 -0
  42. package/dist/chunk-7DP57BA7.js +2 -0
  43. package/dist/chunk-7DP57BA7.js.map +1 -0
  44. package/dist/chunk-7N3IJSWF.js +5 -0
  45. package/dist/chunk-7N3IJSWF.js.map +1 -0
  46. package/dist/chunk-BMXYR5LI.cjs +2 -0
  47. package/dist/chunk-BMXYR5LI.cjs.map +1 -0
  48. package/dist/chunk-DUYTXLO2.js +2 -0
  49. package/dist/chunk-DUYTXLO2.js.map +1 -0
  50. package/dist/chunk-EL2XUOWX.js +2 -0
  51. package/dist/chunk-EL2XUOWX.js.map +1 -0
  52. package/dist/chunk-FYAMQFZZ.cjs +3 -0
  53. package/dist/chunk-FYAMQFZZ.cjs.map +1 -0
  54. package/dist/chunk-FYTB7SDP.cjs +2 -0
  55. package/dist/chunk-FYTB7SDP.cjs.map +1 -0
  56. package/dist/chunk-GBCN7FNV.cjs +2 -0
  57. package/dist/chunk-GBCN7FNV.cjs.map +1 -0
  58. package/dist/{chunk-7E7NXKQ5.js → chunk-IJHL3LMH.js} +2 -2
  59. package/dist/chunk-IJHL3LMH.js.map +1 -0
  60. package/dist/{chunk-4ETS224G.js → chunk-JFZ5SLF7.js} +2 -2
  61. package/dist/{chunk-4ETS224G.js.map → chunk-JFZ5SLF7.js.map} +1 -1
  62. package/dist/chunk-JSM3O7EM.cjs +2 -0
  63. package/dist/chunk-JSM3O7EM.cjs.map +1 -0
  64. package/dist/chunk-MZMA32NE.js +3 -0
  65. package/dist/chunk-MZMA32NE.js.map +1 -0
  66. package/dist/chunk-N4SSR7Q6.js +2 -0
  67. package/dist/chunk-N4SSR7Q6.js.map +1 -0
  68. package/dist/{chunk-TL545PXW.cjs → chunk-NEGZZB7F.cjs} +2 -2
  69. package/dist/{chunk-TL545PXW.cjs.map → chunk-NEGZZB7F.cjs.map} +1 -1
  70. package/dist/{chunk-3GR46UOX.js → chunk-NMU5E7W7.js} +2 -2
  71. package/dist/{chunk-3GR46UOX.js.map → chunk-NMU5E7W7.js.map} +1 -1
  72. package/dist/chunk-OB2VX4IL.js +2 -0
  73. package/dist/chunk-OB2VX4IL.js.map +1 -0
  74. package/dist/{chunk-MRRMIBHE.js → chunk-OONQ3V3I.js} +2 -2
  75. package/dist/{chunk-MRRMIBHE.js.map → chunk-OONQ3V3I.js.map} +1 -1
  76. package/dist/{chunk-N37PUZJR.cjs → chunk-RAPEZR5L.cjs} +2 -2
  77. package/dist/{chunk-N37PUZJR.cjs.map → chunk-RAPEZR5L.cjs.map} +1 -1
  78. package/dist/{chunk-KEA5HRL3.js → chunk-RDYXH7ML.js} +2 -2
  79. package/dist/{chunk-KEA5HRL3.js.map → chunk-RDYXH7ML.js.map} +1 -1
  80. package/dist/{chunk-3SSMOVWB.cjs → chunk-SAF3B3AX.cjs} +2 -2
  81. package/dist/{chunk-3SSMOVWB.cjs.map → chunk-SAF3B3AX.cjs.map} +1 -1
  82. package/dist/chunk-SPOVFRZO.cjs +5 -0
  83. package/dist/chunk-SPOVFRZO.cjs.map +1 -0
  84. package/dist/{chunk-75JLWK4L.cjs → chunk-SQHBOWES.cjs} +2 -2
  85. package/dist/{chunk-75JLWK4L.cjs.map → chunk-SQHBOWES.cjs.map} +1 -1
  86. package/dist/chunk-UF5XMZTT.js +2 -0
  87. package/dist/chunk-UF5XMZTT.js.map +1 -0
  88. package/dist/chunk-UV3EUIBT.cjs +3 -0
  89. package/dist/chunk-UV3EUIBT.cjs.map +1 -0
  90. package/dist/chunk-VMSCRVNX.cjs +2 -0
  91. package/dist/chunk-VMSCRVNX.cjs.map +1 -0
  92. package/dist/{chunk-J7ABVGZH.cjs → chunk-WGP4UUO5.cjs} +2 -2
  93. package/dist/{chunk-J7ABVGZH.cjs.map → chunk-WGP4UUO5.cjs.map} +1 -1
  94. package/dist/chunk-XBGK3TTU.cjs +3 -0
  95. package/dist/chunk-XBGK3TTU.cjs.map +1 -0
  96. package/dist/chunk-XHQYHXRE.js +3 -0
  97. package/dist/chunk-XHQYHXRE.js.map +1 -0
  98. package/dist/chunk-XX55RR4Q.js +3 -0
  99. package/dist/chunk-XX55RR4Q.js.map +1 -0
  100. package/dist/chunk-YBQPEWT7.cjs +3 -0
  101. package/dist/chunk-YBQPEWT7.cjs.map +1 -0
  102. package/dist/{chunk-CHSO3DCS.js → chunk-ZDCZ5IDD.js} +3 -3
  103. package/dist/{chunk-CHSO3DCS.js.map → chunk-ZDCZ5IDD.js.map} +1 -1
  104. package/dist/{chunk-LNZNJSRW.cjs → chunk-ZVPZQ66D.cjs} +2 -2
  105. package/dist/chunk-ZVPZQ66D.cjs.map +1 -0
  106. package/dist/constants.cjs +1 -1
  107. package/dist/constants.d.cts +1 -1
  108. package/dist/constants.d.ts +1 -1
  109. package/dist/constants.js +1 -1
  110. package/dist/engine.cjs +1 -1
  111. package/dist/engine.d.cts +12 -12
  112. package/dist/engine.d.ts +12 -12
  113. package/dist/engine.js +1 -1
  114. package/dist/errors.cjs +1 -1
  115. package/dist/errors.d.cts +3 -3
  116. package/dist/errors.d.ts +3 -3
  117. package/dist/errors.js +1 -1
  118. package/dist/format.cjs +1 -1
  119. package/dist/format.d.cts +1 -1
  120. package/dist/format.d.ts +1 -1
  121. package/dist/format.js +1 -1
  122. package/dist/index.cjs +1 -1
  123. package/dist/index.cjs.map +1 -1
  124. package/dist/index.d.cts +14 -12
  125. package/dist/index.d.ts +14 -12
  126. package/dist/index.js +1 -1
  127. package/dist/index.js.map +1 -1
  128. package/dist/language.d.cts +11 -11
  129. package/dist/language.d.ts +11 -11
  130. package/dist/lexer.cjs +1 -1
  131. package/dist/lexer.cjs.map +1 -1
  132. package/dist/lexer.d.cts +8 -7
  133. package/dist/lexer.d.ts +8 -7
  134. package/dist/lexer.js +1 -1
  135. package/dist/lexer.js.map +1 -1
  136. package/dist/normalizer.cjs +1 -1
  137. package/dist/normalizer.d.cts +16 -10
  138. package/dist/normalizer.d.ts +16 -10
  139. package/dist/normalizer.js +1 -1
  140. package/dist/packages.cjs +1 -1
  141. package/dist/packages.d.cts +10 -10
  142. package/dist/packages.d.ts +10 -10
  143. package/dist/packages.js +1 -1
  144. package/dist/parser.cjs +1 -1
  145. package/dist/parser.d.cts +4 -4
  146. package/dist/parser.d.ts +4 -4
  147. package/dist/parser.js +1 -1
  148. package/dist/{pipeline-B4wf3M1h.d.cts → pipeline-69q2tsLE.d.cts} +1 -1
  149. package/dist/{pipeline-QIT4iD8f.d.ts → pipeline-DTqGLPsV.d.ts} +1 -1
  150. package/dist/resolvers.cjs +1 -1
  151. package/dist/resolvers.d.cts +19 -3
  152. package/dist/resolvers.d.ts +19 -3
  153. package/dist/resolvers.js +1 -1
  154. package/dist/testing.cjs +2 -2
  155. package/dist/testing.d.cts +11 -11
  156. package/dist/testing.d.ts +11 -11
  157. package/dist/testing.js +1 -1
  158. package/dist/uom.cjs +1 -1
  159. package/dist/uom.d.cts +2 -2
  160. package/dist/uom.d.ts +2 -2
  161. package/dist/uom.js +1 -1
  162. package/dist/vm.cjs +1 -1
  163. package/dist/vm.d.cts +8 -8
  164. package/dist/vm.d.ts +8 -8
  165. package/dist/vm.js +1 -1
  166. package/dist/worker.cjs +2 -2
  167. package/dist/worker.cjs.map +1 -1
  168. package/dist/worker.d.cts +34 -25
  169. package/dist/worker.d.ts +34 -25
  170. package/dist/worker.js +1 -1
  171. package/dist/worker.js.map +1 -1
  172. package/package.json +5 -5
  173. package/dist/chunk-42JXN3BH.js +0 -5
  174. package/dist/chunk-42JXN3BH.js.map +0 -1
  175. package/dist/chunk-4DJJIUQF.js +0 -2
  176. package/dist/chunk-4DJJIUQF.js.map +0 -1
  177. package/dist/chunk-6YM67DWH.cjs +0 -3
  178. package/dist/chunk-6YM67DWH.cjs.map +0 -1
  179. package/dist/chunk-7E7NXKQ5.js.map +0 -1
  180. package/dist/chunk-7SZBEE5R.cjs +0 -2
  181. package/dist/chunk-7SZBEE5R.cjs.map +0 -1
  182. package/dist/chunk-A5M4QZIK.js +0 -2
  183. package/dist/chunk-A5M4QZIK.js.map +0 -1
  184. package/dist/chunk-AF7HQN6I.js +0 -2
  185. package/dist/chunk-AF7HQN6I.js.map +0 -1
  186. package/dist/chunk-ALY4ZMYO.js +0 -2
  187. package/dist/chunk-ALY4ZMYO.js.map +0 -1
  188. package/dist/chunk-BRJ4RT5U.js +0 -2
  189. package/dist/chunk-BRJ4RT5U.js.map +0 -1
  190. package/dist/chunk-CO2BI6WL.cjs +0 -3
  191. package/dist/chunk-CO2BI6WL.cjs.map +0 -1
  192. package/dist/chunk-EN3CDYOS.cjs +0 -2
  193. package/dist/chunk-EN3CDYOS.cjs.map +0 -1
  194. package/dist/chunk-EQDT42JG.js +0 -3
  195. package/dist/chunk-EQDT42JG.js.map +0 -1
  196. package/dist/chunk-FMMT5C5H.cjs +0 -3
  197. package/dist/chunk-FMMT5C5H.cjs.map +0 -1
  198. package/dist/chunk-FP6Z6PYR.js +0 -2
  199. package/dist/chunk-FP6Z6PYR.js.map +0 -1
  200. package/dist/chunk-H3JXNH7X.cjs +0 -3
  201. package/dist/chunk-H3JXNH7X.cjs.map +0 -1
  202. package/dist/chunk-HZOLIL5T.js +0 -3
  203. package/dist/chunk-HZOLIL5T.js.map +0 -1
  204. package/dist/chunk-JVMINMAB.js +0 -2
  205. package/dist/chunk-JVMINMAB.js.map +0 -1
  206. package/dist/chunk-JYLNQOPU.cjs +0 -2
  207. package/dist/chunk-JYLNQOPU.cjs.map +0 -1
  208. package/dist/chunk-KRXO3MOW.cjs +0 -2
  209. package/dist/chunk-KRXO3MOW.cjs.map +0 -1
  210. package/dist/chunk-KVLJDOZ7.cjs +0 -5
  211. package/dist/chunk-KVLJDOZ7.cjs.map +0 -1
  212. package/dist/chunk-LNZNJSRW.cjs.map +0 -1
  213. package/dist/chunk-O3BDXOQJ.js +0 -2
  214. package/dist/chunk-O3BDXOQJ.js.map +0 -1
  215. package/dist/chunk-PIZQIQVM.js +0 -3
  216. package/dist/chunk-PIZQIQVM.js.map +0 -1
  217. package/dist/chunk-QTSDIDAS.js +0 -3
  218. package/dist/chunk-QTSDIDAS.js.map +0 -1
  219. package/dist/chunk-SGIDBZ4T.cjs +0 -2
  220. package/dist/chunk-SGIDBZ4T.cjs.map +0 -1
  221. package/dist/chunk-UNKSCVIL.cjs +0 -2
  222. package/dist/chunk-UNKSCVIL.cjs.map +0 -1
  223. package/dist/chunk-USQ4KL6S.cjs +0 -2
  224. package/dist/chunk-USQ4KL6S.cjs.map +0 -1
  225. package/dist/chunk-XDXIPVZB.cjs +0 -2
  226. package/dist/chunk-XDXIPVZB.cjs.map +0 -1
@@ -1,2 +0,0 @@
1
- import {c as c$2}from'./chunk-JP4JMQOG.js';import {b,a as a$2,e,d}from'./chunk-O3BDXOQJ.js';import {c,a}from'./chunk-IJMNVBIS.js';import {a as a$1}from'./chunk-LHLW7JLS.js';import {c as c$1}from'./chunk-PIZQIQVM.js';var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",p){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r;let a=a$1(r).display;this.decimalSeparator=a.decimalSeparator,this.thousandsSeparator=a.thousandsSeparator,this.pluginFunctionIndex=p;}getLocaleCode(){return this.localeCode}setDiagnosticPipeline(e,t){this.diagnosticPipeline=e,this.currentExpression=t??"";}load(e,t){if(t===false){this.tokens=e,this.current=0,this.depth=0;return}let r=c(a.LPAREN),p=c(a.RPAREN),a$1=0;for(let l=0;l<e.length;l++)e[l].typeId===r?a$1++:e[l].typeId===p&&a$1--;this.tokens=a$1===0?e:this.balanceParens(e,a$1),this.current=0,this.depth=0;}balanceParens(e,t){let r=e.slice();if(t>0){let p=c(a.RPAREN);for(let a$1=0;a$1<t;a$1++){let l=e[e.length-1];r.push({type:a.RPAREN,typeId:p,value:")",text:")",offset:l?l.offset+l.text.length:0,lineBreaks:0,line:l?l.line:1,col:l?l.col+l.text.length:1});}}else if(t<0){let p=c(a.LPAREN);for(let a$1=0;a$1<-t;a$1++)r.unshift({type:a.LPAREN,typeId:p,value:"(",text:"(",offset:0,lineBreaks:0,line:1,col:1});}return r}parseExpression(e=0,t){if(t&&(this.builder=t),this.depth++,this.depth>this.maxDepth)throw this.depth--,c$1.parsing("NESTING_DEPTH_EXCEEDED",`Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,{maxDepth:this.maxDepth,currentDepth:this.depth});let r=this.consume();if(!r)throw this.depth--,c$1.parsing("UNEXPECTED_END","Unexpected end of expression");this.parsePrefix(r);let p=this.tokens,a=p.length,l=n.BP_TABLE,o=this.registry,c=this.builder,d=this.current;for(;d<a;){let h=p[d];if(!h)break;let I=l[h.typeId];if(I>0){if(I<=e)break;if(this.diagnosticPipeline){let m=o.getInfix(h.typeId);m&&this.fireParseletMatched(m,h,false,I);}this.current=++d;let f=h.typeId;if(f===n.PERCENT_ID)c.emitOpcode(10),c.emitNumber(100),c.emitOpcode(23),c.emitOpcode(74);else if(!(f===n.CARET_ID&&this.tryEmitMatrixCaretOp(c))){let m=f===n.CARET_ID?I-1:I+1;this.parseExpression(m,c),c.emitOpcode(n.INFIX_OPCODE[f]);}}else {let f=o.getInfix(h.typeId);if(!f||f.bindingPower<=e)break;this.current=++d,this.diagnosticPipeline&&this.fireParseletMatched(f,h,false,f.bindingPower),this.infixMinBindingPower=e,f.parse(this,r,h,c);}d=this.current;}this.current=d,this.depth--;}parsePrefix(e$1){let t=this.builder,r=e$1.typeId;if(this.diagnosticPipeline){let a=this.registry.getPrefix(r);a&&this.fireParseletMatched(a,e$1,true);}switch(r){case n.NUMBER_ID:{let a,l=null,o=e$1.value;if(this.decimalSeparator==="."){let c=0,d=o.length>0;for(let h=0;h<o.length;h++){let I=o.charCodeAt(h);if(!(I>=48&&I<=57)){if(I===46&&c===0){c=1;continue}d=false;break}}if(d){if(c===1){t.emitOpcode(16),t.emitString(o);return}t.emitOpcode(10),t.emitNumber(+o);return}}if(o.startsWith("0x")||o.startsWith("0X")){if(a=parseInt(o,16),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${o}"`,{raw:o})}else if(o.startsWith("0b")||o.startsWith("0B")){if(a=parseInt(o.slice(2),2),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${o}"`,{raw:o})}else if(o.startsWith("0o")||o.startsWith("0O")){if(a=parseInt(o.slice(2),8),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${o}"`,{raw:o})}else if(D.test(o))a=parseFloat(o.split(".").join(""));else {let c=this.decimalSeparator,d=this.thousandsSeparator,h=o;d&&h.indexOf(d)!==-1&&(h=h.split(d).join("")),c&&c!=="."&&(h=h.replace(c,".")),a=parseFloat(h),T.test(h)&&(l=h);}if(l!==null){t.emitOpcode(16),t.emitString(l);return}t.emitOpcode(10),t.emitNumber(a);return}case n.BIGINT_ID:{t.emitOpcode(11),t.emitString(e(e$1.value,this.localeCode));return}case n.STRING_ID:{t.emitOpcode(13),t.emitString(e$1.value);return}case n.IDENT_ID:{if(this.peek()?.typeId===n.LPAREN_ID){this.parseUserFunctionDefOrCall(e$1,t);return}t.emitOpcode(60),t.emitString(e$1.value);return}case n.LPAREN_ID:{this.parseExpression(0,t);let a$1=1;for(;this.match(a.COMMA);)this.parseExpression(0,t),a$1++;this.consume(a.RPAREN),a$1>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(a$1));return}case n.MINUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let p=this.registry.getPrefix(r);if(!p)throw c$1.parsing("NO_PREFIX_PARSELET",`No prefix parselet found for token: ${e$1.type} ("${e$1.value}")`,{tokenType:e$1.type,tokenValue:e$1.value});p.parse(this,e$1,t);}tryEmitMatrixCaretOp(e){for(let t of n.CARET_SUFFIX_RULES)if(t.matches(this))return t.emit(this,e),true;return false}findMatchingRParen(e){let t=0;for(let r=e;r<this.tokens.length;r++){let p=this.tokens[r];if(p.typeId===n.LPAREN_ID)t++;else if(p.typeId===n.RPAREN_ID&&(t--,t===0))return r}return null}parseUserFunctionDefOrCall(e,t){let r=this.findMatchingRParen(this.current);if(r===null){t.emitOpcode(60),t.emitString(e.value);return}this.tokens[r+1]?.type===a.EQUALS?this.parseUserFunctionDefinition(e,t):this.parseUserFunctionCall(e,t);}consumeParamName(){let e=this.peek();if(e?.type===a.IDENT||e?.type===a.UNIT)return this.consume(),e.value;throw c$1.parsing("USER_FUNCTION_INVALID_PARAM_NAME",`Expected a parameter name but got "${e?.type??"end of input"}"${e?` ("${e.value}")`:""}`,{actualType:e?.type})}parseUserFunctionDefinition(e,t){this.consume(a.LPAREN);let r=[];if(this.peek()?.type!==a.RPAREN)for(r.push(this.consumeParamName());this.match(a.COMMA);)r.push(this.consumeParamName());if(this.consume(a.RPAREN),this.consume(a.EQUALS),r.length===0)throw c$1.parsing("USER_FUNCTION_NO_PARAMS",`"${e.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)`,{name:e.value});let p=new d(this.pluginFunctionIndex);this.parseExpression(a$2.Lowest,p),this.setBuilder(t);let a$1=p.build();if(a$1.hasAsync)throw c$1.parsing("FUNCTION_BODY_MUST_BE_SYNCHRONOUS",`"${e.value}(...)"'s body calls an async operation (weather, stocks, currency, ...) \u2014 user-defined function bodies must be synchronous`,{name:e.value});let l=t.emitUserFunctionBody(e.value,r,a$1);t.emitOpcode(150),t.emitIndex(l),t.emitOpcode(13),t.emitString(`${e.value}(${r.join(", ")}) defined`);}parseUserFunctionCall(e,t){this.consume(a.LPAREN);let r=0;if(this.peek()?.type!==a.RPAREN)for(this.parseExpression(a$2.Lowest,t),r++;this.match(a.COMMA);)this.parseExpression(a$2.Lowest,t),r++;this.consume(a.RPAREN),t.emitOpcode(151),t.emitString(e.value),t.emitByte(r);}consume(e){let t=this.tokens[this.current];if(!t)throw c$1.parsing("UNEXPECTED_END_OF_INPUT","Unexpected end of input");if(e!==void 0){let r=c(e);if(t.typeId!==r)throw c$1.parsing("UNEXPECTED_TOKEN_TYPE",`Expected token type "${e}" but got "${t.type}" ("${t.value}")`,{expectedType:e,actualType:t.type,actualValue:t.value})}return this.current++,t}match(e){let t=this.peek();return t&&t.typeId===c(e)?(this.advance(),true):false}peek(){return this.tokens[this.current]}peekAt(e){return this.tokens[this.current+e]}previous(){return this.current>0?this.tokens[this.current-1]:void 0}advance(){this.current++;}setBuilder(e){this.builder=e;}fireParseletMatched(e,t,r,p){let a=this.diagnosticPipeline,l={type:c$2.ParseletMatched,elapsedNs:0,expression:this.currentExpression,tokenType:t.type,tokenValue:t.value,parseletCategory:e.category,parseletType:e.constructor?.name??"unknown",isPrefix:r,bindingPower:p,tokenOffset:t.offset||0};a.fireParseletMatched(l);}};n.BP_TABLE=b(),n.NUMBER_ID=c(a.NUMBER),n.BIGINT_ID=c(a.BIGINT),n.STRING_ID=c(a.STRING),n.IDENT_ID=c(a.IDENT),n.LPAREN_ID=c(a.LPAREN),n.RPAREN_ID=c(a.RPAREN),n.MINUS_ID=c(a.MINUS),n.PLUS_ID=c(a.PLUS),n.KEYWORD_ID=c(a.KEYWORD),n.STAR_ID=c(a.STAR),n.SLASH_ID=c(a.SLASH),n.MOD_ID=c(a.MOD),n.CARET_ID=c(a.CARET),n.LSHIFT_ID=c(a.LSHIFT),n.RSHIFT_ID=c(a.RSHIFT),n.URSHIFT_ID=c(a.URSHIFT),n.BIT_AND_ID=c(a.BIT_AND),n.BIT_OR_ID=c(a.BIT_OR),n.BIT_XOR_ID=c(a.BIT_XOR),n.PERCENT_ID=c(a.PERCENT),n.OF_ID=c(a.OF),n.INFIX_OPCODE={[c(a.PLUS)]:20,[c(a.MINUS)]:21,[c(a.STAR)]:22,[c(a.SLASH)]:23,[c(a.MOD)]:24,[c(a.CARET)]:25,[c(a.LSHIFT)]:30,[c(a.RSHIFT)]:31,[c(a.URSHIFT)]:32,[c(a.BIT_AND)]:33,[c(a.BIT_OR)]:34,[c(a.BIT_XOR)]:35,[c(a.OF)]:22},n.CARET_SUFFIX_RULES=[{name:"transpose (^T)",matches:e=>{let t=e.peek();return t?.type===a.IDENT&&t.value==="T"},emit:(e,t)=>{e.advance(),t.emitOpcode(51),t.emitIndex(63),t.emitIndex(1);}},{name:"inverse (^-1)",matches:e=>{if(e.peek()?.typeId!==n.MINUS_ID)return false;let r=e.peekAt(1);return r?.type===a.NUMBER&&r.value==="1"},emit:(e,t)=>{e.advance(),e.advance(),t.emitOpcode(51),t.emitIndex(65),t.emitIndex(1);}}];var v=n;var y=class{constructor(){this.prefixParselets=new Map;this.infixParselets=new Map;this.prefixById=new Map;this.infixById=new Map;}registerPrefix(e,t){let r=this.prefixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Prefix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.prefixParselets.set(e,t),this.prefixById.set(c(e),t);}registerInfix(e,t){let r=this.infixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Infix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.infixParselets.set(e,t),this.infixById.set(c(e),t);}getAllPrefix(){let e=[];for(let[t,r]of this.prefixParselets)e.push({tokenType:t,bindingPower:r.bindingPower??a$2.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let p=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:p,rightBindingPower:p+1,category:r.category});}return e}get prefixCount(){return this.prefixParselets.size}get infixCount(){return this.infixParselets.size}getPrefix(e){return typeof e=="number"?this.prefixById.get(e):this.prefixParselets.get(e)}getInfix(e){return typeof e=="number"?this.infixById.get(e):this.infixParselets.get(e)}hasPrefix(e){return this.prefixParselets.has(e)}hasInfix(e){return this.infixParselets.has(e)}clear(){this.prefixParselets.clear(),this.infixParselets.clear(),this.prefixById.clear(),this.infixById.clear();}},H=new y;export{v as a,y as b,H as c};//# sourceMappingURL=chunk-JVMINMAB.js.map
2
- //# sourceMappingURL=chunk-JVMINMAB.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/parser/PrecedenceParser.ts","../src/parser/registry/ParseletRegistry.ts"],"names":["CHAINED_DOT_THOUSANDS_GROUPS","PLAIN_DECIMAL","_PrecedenceParser","parseletRegistry","maxDepth","localeCode","pluginFunctionIndex","display","getLocale","pipeline","expression","tokens","hasParens","LPAREN_ID","tokenTypeId","TokenTypes","RPAREN_ID","openCount","i","result","lastToken","minBp","_builder","ErrorFactory","token","len","bpTable","registry","builder","idx","lookahead","bp","infixParselet","typeId","rightBp","parselet","v","decimalText","raw","dots","plain","c","decimalSep","thousandsSep","normalized","bigIntLiteralDigits","count","BindingPower","prefixParselet","rule","openIdx","depth","t","nameToken","closeIdx","params","bodyBuilder","BytecodeBuilder","bodyProgram","bodyIdx","argCount","expectedType","expectedId","offset","isPrefix","bindingPower","event","DiagnosticEventType","buildBindingPowerTable","p","next","afterMinus","PrecedenceParser","ParseletRegistry","tokenType","existing","left","sharedParseletRegistry"],"mappings":"wNAmBA,IAAMA,CAAAA,CAA+B,wBAAA,CAU/BC,CAAAA,CAAgB,YAAA,CAqBTC,CAAAA,CAAN,MAAMA,CAAiB,CAwF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,IAAA,CAAMC,CAAAA,CAAmD,CAvFrI,IAAA,CAAQ,MAAA,CAAkB,EAAC,CAC3B,IAAA,CAAQ,OAAA,CAAU,CAAA,CAClB,IAAA,CAAQ,KAAA,CAAQ,CAAA,CAWhB,IAAA,CAAQ,iBAAA,CAA4B,EAAA,CAiBpC,IAAA,CAAA,oBAAA,CAAuB,CAAA,CA0DrB,IAAA,CAAK,QAAA,CAAWH,CAAAA,CAChB,IA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AyB,IAAIJ","file":"chunk-JVMINMAB.js","sourcesContent":["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 * A plain fractional literal: digits, exactly one dot, digits, nothing else.\n *\n * The gate for compiling to PUSH_DECIMAL. It admits \"0.10\", \"1.005\", \".5\" and\n * \"5.\" and refuses anything with an exponent (\"2.5e-3\"), which parses as an\n * ordinary double instead, since scientific notation has no exact base-ten\n * value this representation would keep.\n */\nconst PLAIN_DECIMAL = /^\\d*\\.\\d*$/;\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 /** The locale's decimal separator, cached from {@link localeCode}. */\n private readonly decimalSeparator: string;\n\n /** The locale's thousands separator, cached from {@link localeCode}. */\n private readonly thousandsSeparator: string;\n\n /**\n * The binding power the current infix parselet is being invoked at, i.e. the\n * `minBp` of the expression it sits inside. Set immediately before each Tier-2\n * parselet runs. A parselet that decides whether to swallow a following\n * loose operator (UomLiteralParselet with a trailing `in`/`to`) reads this to\n * respect precedence it cannot otherwise see: `120 km / 2 hours in kph` must\n * group as `(120 km / 2 hours) in kph`, not `120 km / (2 hours in kph)`.\n */\n infixMinBindingPower = 0;\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 /** Shared with every BytecodeBuilder so a nested-body builder resolves plugin calls by name. */\n private pluginFunctionIndex?: ReadonlyMap<string, number>;\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\", pluginFunctionIndex?: ReadonlyMap<string, number>) {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n // Read once, not once per number literal. `localeCode` is set here and\n // never reassigned, so these cannot go stale, and the profile had\n // getLocale() plus its property chain inside the hot NUMBER path.\n const display = getLocale(localeCode).display;\n this.decimalSeparator = display.decimalSeparator;\n this.thousandsSeparator = display.thousandsSeparator;\n this.pluginFunctionIndex = pluginFunctionIndex;\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 // Expose the level this parselet is bound at, so one that peeks past its\n // own token (a unit literal weighing whether a trailing `in`/`to` is\n // its own or an outer operator's) can respect precedence. See\n // infixMinBindingPower's doc comment.\n this.infixMinBindingPower = minBp;\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 // The exact dot-decimal text for a literal written with a fractional\n // point, so it can be pushed as PUSH_DECIMAL and keep its precision\n // where it later meets money. Stays null for every integer shape\n // (hex/bin/oct, chained-dot grouping, plain integers), which push the\n // ordinary PUSH_NUMBER and are unchanged.\n let decimalText: string | null = null;\n const raw = token.value;\n\n // Fast path: plain digits, with at most one \".\".\n //\n // Most literals in a document are `144`, `1200`, `0.85`. The general\n // path below reaches the same answer for them only after six\n // startsWith() calls, two regular expressions and a split/join that\n // allocated whether or not the separator was present; a CPU profile put\n // this whole case at over a third of parse-and-compile. One character\n // scan settles it instead.\n //\n // Guarded on the decimal separator being \".\", which is what makes a\n // lone dot unambiguous. Where \".\" groups thousands instead, `1.234`\n // means one thousand two hundred and thirty-four, so that locale has to\n // keep taking the general path.\n if (this.decimalSeparator === \".\") {\n let dots = 0;\n let plain = raw.length > 0;\n for (let i = 0; i < raw.length; i++) {\n const c = raw.charCodeAt(i);\n if (c >= 48 && c <= 57) continue;\n if (c === 46 && dots === 0) { dots = 1; continue; }\n plain = false;\n break;\n }\n if (plain) {\n // One dot with digits optional on either side is exactly what\n // PLAIN_DECIMAL matches, so this agrees with it: that is the signal\n // for the exact-decimal opcode rather than a double.\n if (dots === 1) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(raw);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(+raw);\n return;\n }\n }\n\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 decimalSep = this.decimalSeparator;\n const thousandsSep = this.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation).\n // The indexOf guard stops that pair allocating an array and a string\n // for the many literals that contain no separator at all.\n if (thousandsSep && normalized.indexOf(thousandsSep) !== -1) {\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 // A plain fractional literal (digits, one dot, digits) is what carries\n // an exact decimal. Scientific notation like \"2.5e-3\" has a dot too\n // but no exact base-ten form worth the trouble, so it stays a\n // PUSH_NUMBER double, and so does any integer (grouping stripped).\n if (PLAIN_DECIMAL.test(normalized)) decimalText = normalized;\n }\n if (decimalText !== null) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(decimalText);\n return;\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(this.pluginFunctionIndex);\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","import { PrefixParselet, InfixParselet } from \"@solve-js/parser/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. Nothing writes to it now\n * that the global package-registration path is gone; it remains only so the\n * `@solve-js/parser` escape hatch keeps a stable shape.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkHG4NPDN5_cjs=require('./chunk-HG4NPDN5.cjs'),chunkEN3CDYOS_cjs=require('./chunk-EN3CDYOS.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",p){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r;let a=chunkS3DFU33X_cjs.a(r).display;this.decimalSeparator=a.decimalSeparator,this.thousandsSeparator=a.thousandsSeparator,this.pluginFunctionIndex=p;}getLocaleCode(){return this.localeCode}setDiagnosticPipeline(e,t){this.diagnosticPipeline=e,this.currentExpression=t??"";}load(e,t){if(t===false){this.tokens=e,this.current=0,this.depth=0;return}let r=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.LPAREN),p=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.RPAREN),a=0;for(let l=0;l<e.length;l++)e[l].typeId===r?a++:e[l].typeId===p&&a--;this.tokens=a===0?e:this.balanceParens(e,a),this.current=0,this.depth=0;}balanceParens(e,t){let r=e.slice();if(t>0){let p=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.RPAREN);for(let a=0;a<t;a++){let l=e[e.length-1];r.push({type:chunk5IJD5L3O_cjs.a.RPAREN,typeId:p,value:")",text:")",offset:l?l.offset+l.text.length:0,lineBreaks:0,line:l?l.line:1,col:l?l.col+l.text.length:1});}}else if(t<0){let p=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.LPAREN);for(let a=0;a<-t;a++)r.unshift({type:chunk5IJD5L3O_cjs.a.LPAREN,typeId:p,value:"(",text:"(",offset:0,lineBreaks:0,line:1,col:1});}return r}parseExpression(e=0,t){if(t&&(this.builder=t),this.depth++,this.depth>this.maxDepth)throw this.depth--,chunkCO2BI6WL_cjs.c.parsing("NESTING_DEPTH_EXCEEDED",`Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,{maxDepth:this.maxDepth,currentDepth:this.depth});let r=this.consume();if(!r)throw this.depth--,chunkCO2BI6WL_cjs.c.parsing("UNEXPECTED_END","Unexpected end of expression");this.parsePrefix(r);let p=this.tokens,a=p.length,l=n.BP_TABLE,o=this.registry,c=this.builder,d=this.current;for(;d<a;){let h=p[d];if(!h)break;let I=l[h.typeId];if(I>0){if(I<=e)break;if(this.diagnosticPipeline){let m=o.getInfix(h.typeId);m&&this.fireParseletMatched(m,h,false,I);}this.current=++d;let f=h.typeId;if(f===n.PERCENT_ID)c.emitOpcode(10),c.emitNumber(100),c.emitOpcode(23),c.emitOpcode(74);else if(!(f===n.CARET_ID&&this.tryEmitMatrixCaretOp(c))){let m=f===n.CARET_ID?I-1:I+1;this.parseExpression(m,c),c.emitOpcode(n.INFIX_OPCODE[f]);}}else {let f=o.getInfix(h.typeId);if(!f||f.bindingPower<=e)break;this.current=++d,this.diagnosticPipeline&&this.fireParseletMatched(f,h,false,f.bindingPower),this.infixMinBindingPower=e,f.parse(this,r,h,c);}d=this.current;}this.current=d,this.depth--;}parsePrefix(e){let t=this.builder,r=e.typeId;if(this.diagnosticPipeline){let a=this.registry.getPrefix(r);a&&this.fireParseletMatched(a,e,true);}switch(r){case n.NUMBER_ID:{let a,l=null,o=e.value;if(this.decimalSeparator==="."){let c=0,d=o.length>0;for(let h=0;h<o.length;h++){let I=o.charCodeAt(h);if(!(I>=48&&I<=57)){if(I===46&&c===0){c=1;continue}d=false;break}}if(d){if(c===1){t.emitOpcode(16),t.emitString(o);return}t.emitOpcode(10),t.emitNumber(+o);return}}if(o.startsWith("0x")||o.startsWith("0X")){if(a=parseInt(o,16),Number.isNaN(a))throw chunkCO2BI6WL_cjs.c.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${o}"`,{raw:o})}else if(o.startsWith("0b")||o.startsWith("0B")){if(a=parseInt(o.slice(2),2),Number.isNaN(a))throw chunkCO2BI6WL_cjs.c.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${o}"`,{raw:o})}else if(o.startsWith("0o")||o.startsWith("0O")){if(a=parseInt(o.slice(2),8),Number.isNaN(a))throw chunkCO2BI6WL_cjs.c.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${o}"`,{raw:o})}else if(D.test(o))a=parseFloat(o.split(".").join(""));else {let c=this.decimalSeparator,d=this.thousandsSeparator,h=o;d&&h.indexOf(d)!==-1&&(h=h.split(d).join("")),c&&c!=="."&&(h=h.replace(c,".")),a=parseFloat(h),T.test(h)&&(l=h);}if(l!==null){t.emitOpcode(16),t.emitString(l);return}t.emitOpcode(10),t.emitNumber(a);return}case n.BIGINT_ID:{t.emitOpcode(11),t.emitString(chunkEN3CDYOS_cjs.e(e.value,this.localeCode));return}case n.STRING_ID:{t.emitOpcode(13),t.emitString(e.value);return}case n.IDENT_ID:{if(this.peek()?.typeId===n.LPAREN_ID){this.parseUserFunctionDefOrCall(e,t);return}t.emitOpcode(60),t.emitString(e.value);return}case n.LPAREN_ID:{this.parseExpression(0,t);let a=1;for(;this.match(chunk5IJD5L3O_cjs.a.COMMA);)this.parseExpression(0,t),a++;this.consume(chunk5IJD5L3O_cjs.a.RPAREN),a>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(a));return}case n.MINUS_ID:{this.parseExpression(chunkEN3CDYOS_cjs.a.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(chunkEN3CDYOS_cjs.a.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let p=this.registry.getPrefix(r);if(!p)throw chunkCO2BI6WL_cjs.c.parsing("NO_PREFIX_PARSELET",`No prefix parselet found for token: ${e.type} ("${e.value}")`,{tokenType:e.type,tokenValue:e.value});p.parse(this,e,t);}tryEmitMatrixCaretOp(e){for(let t of n.CARET_SUFFIX_RULES)if(t.matches(this))return t.emit(this,e),true;return false}findMatchingRParen(e){let t=0;for(let r=e;r<this.tokens.length;r++){let p=this.tokens[r];if(p.typeId===n.LPAREN_ID)t++;else if(p.typeId===n.RPAREN_ID&&(t--,t===0))return r}return null}parseUserFunctionDefOrCall(e,t){let r=this.findMatchingRParen(this.current);if(r===null){t.emitOpcode(60),t.emitString(e.value);return}this.tokens[r+1]?.type===chunk5IJD5L3O_cjs.a.EQUALS?this.parseUserFunctionDefinition(e,t):this.parseUserFunctionCall(e,t);}consumeParamName(){let e=this.peek();if(e?.type===chunk5IJD5L3O_cjs.a.IDENT||e?.type===chunk5IJD5L3O_cjs.a.UNIT)return this.consume(),e.value;throw chunkCO2BI6WL_cjs.c.parsing("USER_FUNCTION_INVALID_PARAM_NAME",`Expected a parameter name but got "${e?.type??"end of input"}"${e?` ("${e.value}")`:""}`,{actualType:e?.type})}parseUserFunctionDefinition(e,t){this.consume(chunk5IJD5L3O_cjs.a.LPAREN);let r=[];if(this.peek()?.type!==chunk5IJD5L3O_cjs.a.RPAREN)for(r.push(this.consumeParamName());this.match(chunk5IJD5L3O_cjs.a.COMMA);)r.push(this.consumeParamName());if(this.consume(chunk5IJD5L3O_cjs.a.RPAREN),this.consume(chunk5IJD5L3O_cjs.a.EQUALS),r.length===0)throw chunkCO2BI6WL_cjs.c.parsing("USER_FUNCTION_NO_PARAMS",`"${e.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)`,{name:e.value});let p=new chunkEN3CDYOS_cjs.d(this.pluginFunctionIndex);this.parseExpression(chunkEN3CDYOS_cjs.a.Lowest,p),this.setBuilder(t);let a=p.build();if(a.hasAsync)throw chunkCO2BI6WL_cjs.c.parsing("FUNCTION_BODY_MUST_BE_SYNCHRONOUS",`"${e.value}(...)"'s body calls an async operation (weather, stocks, currency, ...) \u2014 user-defined function bodies must be synchronous`,{name:e.value});let l=t.emitUserFunctionBody(e.value,r,a);t.emitOpcode(150),t.emitIndex(l),t.emitOpcode(13),t.emitString(`${e.value}(${r.join(", ")}) defined`);}parseUserFunctionCall(e,t){this.consume(chunk5IJD5L3O_cjs.a.LPAREN);let r=0;if(this.peek()?.type!==chunk5IJD5L3O_cjs.a.RPAREN)for(this.parseExpression(chunkEN3CDYOS_cjs.a.Lowest,t),r++;this.match(chunk5IJD5L3O_cjs.a.COMMA);)this.parseExpression(chunkEN3CDYOS_cjs.a.Lowest,t),r++;this.consume(chunk5IJD5L3O_cjs.a.RPAREN),t.emitOpcode(151),t.emitString(e.value),t.emitByte(r);}consume(e){let t=this.tokens[this.current];if(!t)throw chunkCO2BI6WL_cjs.c.parsing("UNEXPECTED_END_OF_INPUT","Unexpected end of input");if(e!==void 0){let r=chunk5IJD5L3O_cjs.c(e);if(t.typeId!==r)throw chunkCO2BI6WL_cjs.c.parsing("UNEXPECTED_TOKEN_TYPE",`Expected token type "${e}" but got "${t.type}" ("${t.value}")`,{expectedType:e,actualType:t.type,actualValue:t.value})}return this.current++,t}match(e){let t=this.peek();return t&&t.typeId===chunk5IJD5L3O_cjs.c(e)?(this.advance(),true):false}peek(){return this.tokens[this.current]}peekAt(e){return this.tokens[this.current+e]}previous(){return this.current>0?this.tokens[this.current-1]:void 0}advance(){this.current++;}setBuilder(e){this.builder=e;}fireParseletMatched(e,t,r,p){let a=this.diagnosticPipeline,l={type:chunkHG4NPDN5_cjs.c.ParseletMatched,elapsedNs:0,expression:this.currentExpression,tokenType:t.type,tokenValue:t.value,parseletCategory:e.category,parseletType:e.constructor?.name??"unknown",isPrefix:r,bindingPower:p,tokenOffset:t.offset||0};a.fireParseletMatched(l);}};n.BP_TABLE=chunkEN3CDYOS_cjs.b(),n.NUMBER_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.NUMBER),n.BIGINT_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.BIGINT),n.STRING_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.STRING),n.IDENT_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.IDENT),n.LPAREN_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.LPAREN),n.RPAREN_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.RPAREN),n.MINUS_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.MINUS),n.PLUS_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.PLUS),n.KEYWORD_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.KEYWORD),n.STAR_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.STAR),n.SLASH_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.SLASH),n.MOD_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.MOD),n.CARET_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.CARET),n.LSHIFT_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.LSHIFT),n.RSHIFT_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.RSHIFT),n.URSHIFT_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.URSHIFT),n.BIT_AND_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.BIT_AND),n.BIT_OR_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.BIT_OR),n.BIT_XOR_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.BIT_XOR),n.PERCENT_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.PERCENT),n.OF_ID=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.OF),n.INFIX_OPCODE={[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.PLUS)]:20,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.MINUS)]:21,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.STAR)]:22,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.SLASH)]:23,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.MOD)]:24,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.CARET)]:25,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.LSHIFT)]:30,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.RSHIFT)]:31,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.URSHIFT)]:32,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.BIT_AND)]:33,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.BIT_OR)]:34,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.BIT_XOR)]:35,[chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.OF)]:22},n.CARET_SUFFIX_RULES=[{name:"transpose (^T)",matches:e=>{let t=e.peek();return t?.type===chunk5IJD5L3O_cjs.a.IDENT&&t.value==="T"},emit:(e,t)=>{e.advance(),t.emitOpcode(51),t.emitIndex(63),t.emitIndex(1);}},{name:"inverse (^-1)",matches:e=>{if(e.peek()?.typeId!==n.MINUS_ID)return false;let r=e.peekAt(1);return r?.type===chunk5IJD5L3O_cjs.a.NUMBER&&r.value==="1"},emit:(e,t)=>{e.advance(),e.advance(),t.emitOpcode(51),t.emitIndex(65),t.emitIndex(1);}}];var v=n;var y=class{constructor(){this.prefixParselets=new Map;this.infixParselets=new Map;this.prefixById=new Map;this.infixById=new Map;}registerPrefix(e,t){let r=this.prefixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Prefix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.prefixParselets.set(e,t),this.prefixById.set(chunk5IJD5L3O_cjs.c(e),t);}registerInfix(e,t){let r=this.infixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Infix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.infixParselets.set(e,t),this.infixById.set(chunk5IJD5L3O_cjs.c(e),t);}getAllPrefix(){let e=[];for(let[t,r]of this.prefixParselets)e.push({tokenType:t,bindingPower:r.bindingPower??chunkEN3CDYOS_cjs.a.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let p=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:p,rightBindingPower:p+1,category:r.category});}return e}get prefixCount(){return this.prefixParselets.size}get infixCount(){return this.infixParselets.size}getPrefix(e){return typeof e=="number"?this.prefixById.get(e):this.prefixParselets.get(e)}getInfix(e){return typeof e=="number"?this.infixById.get(e):this.infixParselets.get(e)}hasPrefix(e){return this.prefixParselets.has(e)}hasInfix(e){return this.infixParselets.has(e)}clear(){this.prefixParselets.clear(),this.infixParselets.clear(),this.prefixById.clear(),this.infixById.clear();}},H=new y;exports.a=v;exports.b=y;exports.c=H;//# sourceMappingURL=chunk-JYLNQOPU.cjs.map
2
- //# sourceMappingURL=chunk-JYLNQOPU.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/parser/PrecedenceParser.ts","../src/parser/registry/ParseletRegistry.ts"],"names":["CHAINED_DOT_THOUSANDS_GROUPS","PLAIN_DECIMAL","_PrecedenceParser","parseletRegistry","maxDepth","localeCode","pluginFunctionIndex","display","getLocale","pipeline","expression","tokens","hasParens","LPAREN_ID","tokenTypeId","TokenTypes","RPAREN_ID","openCount","i","result","lastToken","minBp","_builder","ErrorFactory","token","len","bpTable","registry","builder","idx","lookahead","bp","infixParselet","typeId","rightBp","parselet","v","decimalText","raw","dots","plain","c","decimalSep","thousandsSep","normalized","bigIntLiteralDigits","count","BindingPower","prefixParselet","rule","openIdx","depth","t","nameToken","closeIdx","params","bodyBuilder","BytecodeBuilder","bodyProgram","bodyIdx","argCount","expectedType","expectedId","offset","isPrefix","bindingPower","event","DiagnosticEventType","buildBindingPowerTable","p","next","afterMinus","PrecedenceParser","ParseletRegistry","tokenType","existing","left","sharedParseletRegistry"],"mappings":"2QAmBA,IAAMA,CAAAA,CAA+B,wBAAA,CAU/BC,CAAAA,CAAgB,YAAA,CAqBTC,CAAAA,CAAN,MAAMA,CAAiB,CAwF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,IAAA,CAAMC,CAAAA,CAAmD,CAvFrI,IAAA,CAAQ,MAAA,CAAkB,EAAC,CAC3B,IAAA,CAAQ,OAAA,CAAU,CAAA,CAClB,IAAA,CAAQ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QAAA,CAASA,CAAAA,CAA4B,CACpC,OAAO,IAAA,CAAK,cAAA,CAAe,GAAA,CAAIA,CAAS,CACzC,CAEA,KAAA,EAAc,CACb,IAAA,CAAK,eAAA,CAAgB,KAAA,EAAM,CAC3B,IAAA,CAAK,cAAA,CAAe,KAAA,EAAM,CAC1B,IAAA,CAAK,UAAA,CAAW,KAAA,EAAM,CACtB,IAAA,CAAK,SAAA,CAAU,KAAA,GAChB,CACD,CAAA,CAUaG,EAAyB,IAAIJ","file":"chunk-JYLNQOPU.cjs","sourcesContent":["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 * A plain fractional literal: digits, exactly one dot, digits, nothing else.\n *\n * The gate for compiling to PUSH_DECIMAL. It admits \"0.10\", \"1.005\", \".5\" and\n * \"5.\" and refuses anything with an exponent (\"2.5e-3\"), which parses as an\n * ordinary double instead, since scientific notation has no exact base-ten\n * value this representation would keep.\n */\nconst PLAIN_DECIMAL = /^\\d*\\.\\d*$/;\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 /** The locale's decimal separator, cached from {@link localeCode}. */\n private readonly decimalSeparator: string;\n\n /** The locale's thousands separator, cached from {@link localeCode}. */\n private readonly thousandsSeparator: string;\n\n /**\n * The binding power the current infix parselet is being invoked at, i.e. the\n * `minBp` of the expression it sits inside. Set immediately before each Tier-2\n * parselet runs. A parselet that decides whether to swallow a following\n * loose operator (UomLiteralParselet with a trailing `in`/`to`) reads this to\n * respect precedence it cannot otherwise see: `120 km / 2 hours in kph` must\n * group as `(120 km / 2 hours) in kph`, not `120 km / (2 hours in kph)`.\n */\n infixMinBindingPower = 0;\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 /** Shared with every BytecodeBuilder so a nested-body builder resolves plugin calls by name. */\n private pluginFunctionIndex?: ReadonlyMap<string, number>;\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\", pluginFunctionIndex?: ReadonlyMap<string, number>) {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n // Read once, not once per number literal. `localeCode` is set here and\n // never reassigned, so these cannot go stale, and the profile had\n // getLocale() plus its property chain inside the hot NUMBER path.\n const display = getLocale(localeCode).display;\n this.decimalSeparator = display.decimalSeparator;\n this.thousandsSeparator = display.thousandsSeparator;\n this.pluginFunctionIndex = pluginFunctionIndex;\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 // Expose the level this parselet is bound at, so one that peeks past its\n // own token (a unit literal weighing whether a trailing `in`/`to` is\n // its own or an outer operator's) can respect precedence. See\n // infixMinBindingPower's doc comment.\n this.infixMinBindingPower = minBp;\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 // The exact dot-decimal text for a literal written with a fractional\n // point, so it can be pushed as PUSH_DECIMAL and keep its precision\n // where it later meets money. Stays null for every integer shape\n // (hex/bin/oct, chained-dot grouping, plain integers), which push the\n // ordinary PUSH_NUMBER and are unchanged.\n let decimalText: string | null = null;\n const raw = token.value;\n\n // Fast path: plain digits, with at most one \".\".\n //\n // Most literals in a document are `144`, `1200`, `0.85`. The general\n // path below reaches the same answer for them only after six\n // startsWith() calls, two regular expressions and a split/join that\n // allocated whether or not the separator was present; a CPU profile put\n // this whole case at over a third of parse-and-compile. One character\n // scan settles it instead.\n //\n // Guarded on the decimal separator being \".\", which is what makes a\n // lone dot unambiguous. Where \".\" groups thousands instead, `1.234`\n // means one thousand two hundred and thirty-four, so that locale has to\n // keep taking the general path.\n if (this.decimalSeparator === \".\") {\n let dots = 0;\n let plain = raw.length > 0;\n for (let i = 0; i < raw.length; i++) {\n const c = raw.charCodeAt(i);\n if (c >= 48 && c <= 57) continue;\n if (c === 46 && dots === 0) { dots = 1; continue; }\n plain = false;\n break;\n }\n if (plain) {\n // One dot with digits optional on either side is exactly what\n // PLAIN_DECIMAL matches, so this agrees with it: that is the signal\n // for the exact-decimal opcode rather than a double.\n if (dots === 1) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(raw);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(+raw);\n return;\n }\n }\n\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 decimalSep = this.decimalSeparator;\n const thousandsSep = this.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation).\n // The indexOf guard stops that pair allocating an array and a string\n // for the many literals that contain no separator at all.\n if (thousandsSep && normalized.indexOf(thousandsSep) !== -1) {\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 // A plain fractional literal (digits, one dot, digits) is what carries\n // an exact decimal. Scientific notation like \"2.5e-3\" has a dot too\n // but no exact base-ten form worth the trouble, so it stays a\n // PUSH_NUMBER double, and so does any integer (grouping stripped).\n if (PLAIN_DECIMAL.test(normalized)) decimalText = normalized;\n }\n if (decimalText !== null) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(decimalText);\n return;\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(this.pluginFunctionIndex);\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","import { PrefixParselet, InfixParselet } from \"@solve-js/parser/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. Nothing writes to it now\n * that the global package-registration path is gone; it remains only so the\n * `@solve-js/parser` escape hatch keeps a stable shape.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunkUSQ4KL6S_cjs=require('./chunk-USQ4KL6S.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunkJ4LSAHCY_cjs=require('./chunk-J4LSAHCY.cjs');var u=(s=>(s.Main="main",s.Inline="inline",s.String="string",s))(u||{});var l=class{constructor(e="en",t){this.currentState="main";this.hasPeeked=false;this.tokens=[];this.tokenIdx=0;this.expressionLexer=new chunkUSQ4KL6S_cjs.b(e,t);}reset(e,t){let s=t??"main";if(this.currentState=s,this.hasPeeked=false,this.peekedToken=void 0,s==="main"){if(this.expressionLexer.classifyLine(e).skip){this.tokens=[],this.tokenIdx=0;return}this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}else this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}classifyLine(e){return this.expressionLexer.classifyLine(e)}findInlineSolves(e){return this.expressionLexer.findInlineSolves(e)}getKeywords(){return this.expressionLexer.getKeywords()}next(){if(this.hasPeeked)return this.hasPeeked=false,this.peekedToken;if(this.tokenIdx<this.tokens.length)return this.tokens[this.tokenIdx++]}peek(){return this.hasPeeked?this.peekedToken:(this.peekedToken=this.next(),this.hasPeeked=true,this.peekedToken)}[Symbol.iterator](){return this.tokens[Symbol.iterator]()}registerVocabulary(e){this.expressionLexer.registerVocabulary(e);}unregisterVocabulary(e){this.expressionLexer.unregisterVocabulary(e);}resetExpression(e){this.currentState="main",this.hasPeeked=false,this.peekedToken=void 0,this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}scanDocument(e){return this.expressionLexer.scanDocument(e)}getState(){return this.currentState}setState(e){this.currentState=e;}getHighlightTokens(e){let t=this.expressionLexer.classifyLine(e);return t.skip&&e.startsWith("> ")?this.collectHighlightTokens(e.slice(2)):t.skip?[]:this.collectHighlightTokens(e)}getHighlightTokenObjects(e){let t=this.expressionLexer.classifyLine(e);return t.skip&&e.startsWith("> ")?this.collectTokenObjects(e.slice(2)):t.skip?[]:this.collectTokenObjects(e)}collectTokenObjects(e){this.resetExpression(e);let t=[];for(let s of this)s.type==="WS"||s.type==="NEWLINE"||s.type.startsWith("MD_")||s.type==="INLINE_SOLVE_START"||s.type==="BACKTICK_CLOSE"||t.push(s);return t}collectHighlightTokens(e){return this.collectTokenObjects(e).map(t=>({type:t.type,value:t.value,offset:t.offset,col:t.col,length:t.text.length,category:chunkY7O4D3BJ_cjs.d(t.type)}))}},T=new l("en",void 0);var n=class{constructor(){this.classes=[];this.localeKeywordMap=null;this.localePhraseMap=null;this.unitNames=null;}register(e){this.classes.push(e);}unregister(e){this.classes=this.classes.filter(t=>t.tokenType!==e);}setLocale(e,t){this.localeKeywordMap=e,this.localePhraseMap=t??null;}setUnits(e){this.unitNames=e;}build(){let e=new Map;if(this.localeKeywordMap)for(let[r,i]of Object.entries(this.localeKeywordMap))e.set(r.toLowerCase(),i);let t=[...this.classes].sort((r,i)=>(r.priority??0)-(i.priority??0));for(let r of t)for(let i of Object.keys(r.keywords))e.set(i.toLowerCase(),r.tokenType);let s=this.buildPhraseTrie(),o=this.buildPhraseStartWords();return {keywordToType:e,phraseTrie:s,phraseStartWords:o,unitNames:this.unitNames??new Set}}buildPhraseTrie(){let e={children:new Map};if(this.localePhraseMap)for(let[t,s]of Object.entries(this.localePhraseMap))this.insertPhrase(e,t.toLowerCase(),s);for(let t of this.classes)if(t.phrases)for(let s of Object.keys(t.phrases))this.insertPhrase(e,s.toLowerCase(),t.tokenType);return e.children.size>0?e:null}insertPhrase(e,t,s){let o=t.split(" "),r=e;for(let i of o)r.children.has(i)||r.children.set(i,{children:new Map}),r=r.children.get(i);r.type||(r.type=s);}buildPhraseStartWords(){let e=new Set;if(this.localePhraseMap)for(let t of Object.keys(this.localePhraseMap)){let s=t.split(" ")[0].toLowerCase();e.add(s);}for(let t of this.classes)if(t.phrases)for(let s of Object.keys(t.phrases)){let o=s.split(" ")[0].toLowerCase();e.add(o);}return e}};var k={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","multiplied by":"MULTIPLY_BY","divide by":"DIVIDE_BY"};function P(a="en"){let e=chunkS3DFU33X_cjs.a(a),t=new n;return t.setLocale(e.keywordMap,k),t.setUnits(chunkJ4LSAHCY_cjs.a),t.build()}exports.a=u;exports.b=l;exports.c=T;exports.d=P;//# sourceMappingURL=chunk-KRXO3MOW.cjs.map
2
- //# sourceMappingURL=chunk-KRXO3MOW.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lexer/LexerState.ts","../src/lexer/Lexer.ts","../src/lexer/TokenClassRegistry.ts","../src/lexer/tokenRegistration.ts"],"names":["LexerState","Lexer","localeCode","tokenLookup","ExpressionLexer","input","state","newState","lineText","plugin","text","classification","result","token","getTokenCategory","sharedLexer","TokenClassRegistry","tokenClass","tokenType","c","keywordMap","phraseMap","unitNames","keywordToType","keyword","sorted","a","b","tc","phraseTrie","phraseStartWords","root","phrase","words","node","word","startWords","first","BUILTIN_PHRASES","buildTokenLookup","locale","getLocale","registry","knownUnits"],"mappings":"yNAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACXA,EAAA,IAAA,CAAO,MAAA,CACPA,EAAA,MAAA,CAAS,QAAA,CACTA,EAAA,MAAA,CAAS,QAAA,CAHEA,OAAA,EAAA,ECaL,IAAMC,EAAN,KAAY,CAkBjB,YAAYC,CAAAA,CAAa,IAAA,CAAMC,EAA2B,CAf1D,IAAA,CAAQ,aAA2B,MAAA,CAEnC,IAAA,CAAQ,UAAY,KAAA,CAIpB,IAAA,CAAQ,OAAkB,EAAC,CAC3B,KAAQ,QAAA,CAAmB,CAAA,CAYzB,KAAK,eAAA,CAAkB,IAAIC,oBAAgBF,CAAAA,CAAYC,CAAW,EACpE,CAEA,KAAA,CAAME,EAAeC,CAAAA,CAA0B,CAC7C,IAAMC,CAAAA,CAAWD,CAAAA,EAAS,OAQ1B,GAPA,IAAA,CAAK,aAAeC,CAAAA,CACpB,IAAA,CAAK,UAAY,KAAA,CACjB,IAAA,CAAK,YAAc,MAAA,CAKfA,CAAAA,GAAa,OAAiB,CAEhC,GADuB,KAAK,eAAA,CAAgB,YAAA,CAAaF,CAAK,CAAA,CAC3C,IAAA,CAAM,CACvB,IAAA,CAAK,MAAA,CAAS,EAAC,CACf,IA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C,iBAAA,CAAmB,OAAA,CACnB,WAAY,OAAA,CACZ,aAAA,CAAe,cACf,aAAA,CAAe,aAAA,CACf,WAAY,UAAA,CACZ,aAAA,CAAe,cACf,eAAA,CAAiB,aAAA,CACjB,YAAa,WACf,CAAA,CAiBO,SAASC,CAAAA,CAAiBrC,CAAAA,CAAa,KAAmB,CAC/D,IAAMsC,EAAkBC,mBAAAA,CAAUvC,CAAU,EACtCwC,CAAAA,CAAW,IAAI1B,EAGrB,OAAA0B,CAAAA,CAAS,UAAUF,CAAAA,CAAO,UAAA,CAAYF,CAAe,CAAA,CAGrDI,CAAAA,CAAS,SAASC,mBAAU,CAAA,CAGrBD,CAAAA,CAAS,KAAA,EAClB","file":"chunk-KRXO3MOW.cjs","sourcesContent":["/**\n * Lexer state machine modes.\n * - Main: document-level scanning with markdown classification\n * - Inline: expression embedded in markdown inline solve (`s\\`...\\``)\n * - String: inside a double-quoted string literal\n */\nexport enum LexerState {\n\tMain = \"main\",\n\tInline = \"inline\",\n\tString = \"string\",\n}\n","import { ExpressionLexer, LineClassification, LexerVocabulary, type ScanLineResult } from \"./ExpressionLexer\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { LexerState } from \"@solve-js/lexer/LexerState\";\nimport { getTokenCategory } from \"@solve-js/language/TokenCategoryMap\";\nimport type { TokenCategory } from \"@solve-js/language/TokenCategory\";\nimport type { TokenLookup } from \"@solve-js/lexer/TokenClassRegistry\";\n\n/**\n * Public tokenizer wrapper around {@link ExpressionLexer}.\n *\n * `ExpressionLexer` does the actual character-by-character scanning;\n * `Lexer` adds a materialized-token-array streaming interface\n * (`next()`/`peek()`) plus line-classification state (`reset()`) so\n * callers can iterate a line's tokens without re-scanning on each peek.\n *\n * Each `ExpressionEngine` instance owns its own `Lexer`, and packages\n * extend it via {@link registerVocabulary} (keywords, operators, units)\n * see `IEnginePackage.lexerVocabulary`.\n */\nexport class Lexer {\n /** Expression-mode lexer (Phase A: V8-optimized, replaces moo) */\n private expressionLexer: ExpressionLexer;\n private currentState: LexerState = LexerState.Main;\n private peekedToken: Token | undefined;\n private hasPeeked = false;\n\n // Materialized token array from the last reset() call, used for\n // next()/peek() streaming access.\n private tokens: Token[] = [];\n private tokenIdx: number = 0;\n\n /**\n * @param localeCode - Locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @param tokenLookup - Optional TokenLookup from TokenClassRegistry.\n * When provided, configures ExpressionLexer to use registry-built\n * keyword/unit/phrase lookups instead of internal instance maps.\n */\n constructor(localeCode = \"en\", tokenLookup?: TokenLookup) {\n // Pass the lookup directly to ExpressionLexer's constructor, it's an\n // instance field now, not a static. Each Lexer instance gets its own\n // isolated lookup, preventing cross-instance corruption.\n this.expressionLexer = new ExpressionLexer(localeCode, tokenLookup);\n }\n\n reset(input: string, state?: LexerState): void {\n const newState = state ?? LexerState.Main;\n this.currentState = newState;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n\n // Phase B: Main state classifies the line with the markdown scanner.\n // Skip lines (headings, fences, HRs, etc.) produce empty token arrays.\n // Expression lines and lines with inline solves are tokenized normally.\n if (newState === LexerState.Main) {\n const classification = this.expressionLexer.classifyLine(input);\n if (classification.skip) {\n this.tokens = [];\n this.tokenIdx = 0;\n return;\n }\n // Expression line or markdown line with inline solves, tokenize.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n } else {\n // Non-main states (Inline, String), expression tokenization.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n }\n\n /**\n * Classify a single line of markdown text (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n classifyLine(lineText: string): LineClassification {\n return this.expressionLexer.classifyLine(lineText);\n }\n\n /**\n * Find all inline solve markers in a line (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n findInlineSolves(lineText: string) {\n return this.expressionLexer.findInlineSolves(lineText);\n }\n\n /**\n * Every keyword this lexer currently recognizes (locale + plugin-contributed),\n * mapped to the token type it lexes to. Delegates to the ExpressionLexer.\n */\n getKeywords(): Record<string, string> {\n return this.expressionLexer.getKeywords();\n }\n\n next(): Token | undefined {\n if (this.hasPeeked) {\n this.hasPeeked = false;\n return this.peekedToken;\n }\n // Materialized token array (ExpressionLexer path).\n if (this.tokenIdx < this.tokens.length) {\n return this.tokens[this.tokenIdx++];\n }\n return undefined;\n }\n\n peek(): Token | undefined {\n if (this.hasPeeked) return this.peekedToken;\n this.peekedToken = this.next();\n this.hasPeeked = true;\n return this.peekedToken;\n }\n\n [Symbol.iterator](): Iterator<Token> {\n return this.tokens[Symbol.iterator]();\n }\n\n /**\n * Register a plugin to extend the lexer with custom tokens.\n * Delegates to the underlying ExpressionLexer.\n *\n * @see LexerVocabulary for the supported extension points.\n */\n registerVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.registerVocabulary(plugin);\n }\n\n /**\n * Unregister a plugin, removing its custom tokens from the lexer.\n * Delegates to the underlying ExpressionLexer.\n */\n unregisterVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.unregisterVocabulary(plugin);\n }\n\n /**\n * Reset the lexer for expression-only text, skips the classifyLine()\n * overhead in reset() for callers that already know the input is an\n * evaluable expression (e.g., after isEmptyLine() confirmed non-skip).\n */\n resetExpression(input: string): void {\n this.currentState = LexerState.Main;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n\n /**\n * Scan a full document in one pass, classifying each line and\n * tokenizing non-skipped lines. Delegates to ExpressionLexer.\n *\n * @returns ScanLineResult[], one per line, with classification + tokens.\n */\n scanDocument(text: string): ScanLineResult[] {\n return this.expressionLexer.scanDocument(text);\n }\n\n getState(): LexerState {\n return this.currentState;\n }\n\n setState(state: LexerState): void {\n this.currentState = state;\n }\n\n getHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n\n // For blockquote lines, strip the \"> \" prefix and tokenize the expression content.\n // This lets expressions inside blockquotes (e.g., \"> 1 + 2\") get syntax highlighted\n // while pure structural lines (headings, code fences) remain unhighlighted.\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectHighlightTokens(lineText.slice(2));\n }\n\n if (classification.skip) {\n return [];\n }\n\n return this.collectHighlightTokens(lineText);\n }\n\n /**\n * The same tokens {@link getHighlightTokens} reduces, before reduction.\n *\n * Exists because normalization operates on tokens, not on the flattened\n * shape, and a consumer that wants phrase-fused highlighting has to run the\n * normalizer between the two. See `LanguageService.getSemanticTokens`.\n *\n * @param lineText - One line of source.\n * @returns Every token on the line that is worth painting, unreduced.\n */\n getHighlightTokenObjects(lineText: string): Token[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectTokenObjects(lineText.slice(2));\n }\n if (classification.skip) return [];\n return this.collectTokenObjects(lineText);\n }\n\n private collectTokenObjects(lineText: string): Token[] {\n this.resetExpression(lineText);\n const result: Token[] = [];\n for (const token of this) {\n if (token.type === \"WS\" || token.type === \"NEWLINE\") continue;\n if (token.type.startsWith(\"MD_\")) continue;\n if (token.type === \"INLINE_SOLVE_START\" || token.type === \"BACKTICK_CLOSE\") continue;\n result.push(token);\n }\n return result;\n }\n\n private collectHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n return this.collectTokenObjects(lineText).map(token => ({\n type: token.type,\n value: token.value,\n offset: token.offset,\n col: token.col,\n // `text`, not `value`: this is a span into the source, and the two\n // differ for a string literal, whose value is the payload while its\n // text still carries the quote characters the reader typed.\n length: token.text.length,\n category: getTokenCategory(token.type),\n }));\n }\n}\n\n/**\n * A lexer for operations that do not depend on registered vocabulary.\n *\n * Line classification and inline-solve detection read characters looking for\n * headings, comment markers, fences and backtick spans, and never consult the\n * keyword, unit or operator tables. Every lexer therefore returns the same\n * answer, so the callers that have no engine to ask can use this one. Checked\n * by `__tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts`.\n *\n * Do not tokenize with this. An engine's own lexer carries the vocabulary its\n * packages registered; this one carries none.\n */\nexport const sharedLexer = new Lexer(\"en\", undefined);","/**\n * TokenClass, Plugin-extensible keyword registration for the Lexer.\n *\n * Providers call `registry.register(tokenClass)` to teach the lexer about\n * their keywords. The registry merges locale keywords, provider keywords,\n * phrase mappings, and unit names into an optimized TokenLookup structure\n * consumed by the Lexer.\n *\n * @example\n * registry.register({\n * tokenType: 'CARET',\n * keywords: {},\n * phrases: { 'to the power of': true, 'power of': true },\n * priority: 10,\n * description: 'Exponentiation operators (x^y)',\n * });\n */\nexport interface TokenClass {\n /** The token type string produced by the lexer (e.g., \"FUNC\", \"PI\", \"CARET\").\n * Must match a token type that a ParseletRegistry has a parselet for. */\n tokenType: string;\n\n /** Single-word keywords (case-insensitive). The lexer lowercases input\n * before lookup, so these should be lowercase. Example:\n * { sqrt: true, abs: true, sin: true, cos: true } for tokenType \"FUNC\" */\n keywords: Record<string, boolean>;\n\n /** Multi-word phrases (case-insensitive). Matched by the built-in PhraseMatcher\n * via the phrase trie. Example:\n * { \"to the power of\": true, \"power of\": true } for tokenType \"CARET\" */\n phrases?: Record<string, boolean>;\n\n /** Priority for conflict resolution. When two TokenClasses register\n * the same keyword, the higher-priority class wins. Locale keywords\n * have priority 0 (set via setLocale). Providers should use\n * priority >= 10 to override locale defaults. Default: 0 */\n priority?: number;\n\n /** Human-readable description for debugging and introspection */\n description?: string;\n}\n\n// ── Phrase Trie ──────────────────────────────────────────────────────────────\n\n/** Trie node for multi-word phrase matching. */\nexport interface PhraseNode {\n /** Complete phrase token type (null = intermediate node) */\n type?: string;\n children: Map<string, PhraseNode>;\n}\n\n// ── TokenLookup, Optimized lookup structure for the Lexer ──────────────────\n\n/**\n * The optimized lookup structure built by TokenClassRegistry.build().\n * Consumed by the Lexer for O(1) keyword → token type lookups and\n * O(word-count) phrase matching.\n */\nexport interface TokenLookup {\n /** Lowercase keyword → token type. O(1) Map lookup. */\n keywordToType: Map<string, string>;\n\n /** Phrase trie for multi-word matching. Root node with children maps.\n * Null if no phrases registered. */\n phraseTrie: PhraseNode | null;\n\n /** Set of lowercase first-words of all registered phrases.\n * Used by the lexer to emit IDENT (not a phrase keyword) for words\n * that start multi-word phrases, deferring to the PhraseMatcher.\n *\n * Example: \"to\" is in phraseStartWords because \"to the power of\" is a phrase.\n * When the lexer sees \"to\", it emits IDENT and lets the phrase matcher\n * combine \"to the power of\" into a single CARET token.\n *\n * This prevents plugins from accidentally overriding phrase-start words.\n */\n phraseStartWords: Set<string>;\n\n /** Case-sensitive unit names for UNIT fallback after keyword lookup fails. */\n unitNames: ReadonlySet<string>;\n}\n\n// ── TokenClassRegistry ───────────────────────────────────────────────────────\n\n/**\n * Central registry for keyword→token-type mappings.\n *\n * Providers register TokenClasses; locales provide keyword maps;\n * units provide a name set. `build()` merges all sources into an\n * optimized TokenLookup consumed by the Lexer.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0)\n * 2. Provider keywords (sorted by priority ascending, higher priority wins)\n *\n * Unit names are stored separately (checked AFTER keyword lookup fails).\n * Phrases are stored in a trie for O(phrase-length) matching.\n */\nexport class TokenClassRegistry {\n private classes: TokenClass[] = [];\n private localeKeywordMap: Record<string, string> | null = null;\n private localePhraseMap: Record<string, string> | null = null;\n private unitNames: ReadonlySet<string> | null = null;\n\n /**\n * Register a provider's TokenClass. Must be called BEFORE build().\n * Can be called multiple times to add more entries.\n *\n * Built-in token types CANNOT be overridden, throws a EngineError\n * if the TokenClass attempts to register a keyword that conflicts\n * with an already-registered token type.\n */\n register(tokenClass: TokenClass): void {\n this.classes.push(tokenClass);\n }\n\n /**\n * Unregister all TokenClasses for a given token type.\n * Useful for plugin unload. Requires rebuild() to take effect.\n */\n unregister(tokenType: string): void {\n this.classes = this.classes.filter(c => c.tokenType !== tokenType);\n }\n\n /**\n * Set the locale's keyword→type map and optional phrase map.\n * Called on locale change. Priority 0 (cannot override providers with higher priority).\n */\n setLocale(keywordMap: Record<string, string>, phraseMap?: Record<string, string>): void {\n this.localeKeywordMap = keywordMap;\n this.localePhraseMap = phraseMap ?? null;\n }\n\n /**\n * Set the unit name set. Called when unit list changes.\n * Units are stored separately (checked AFTER keyword lookup fails).\n *\n * Takes a ReadonlySet because the caller's set is derived from the\n * conversion tables and must not be mutated; this class only ever reads it.\n */\n setUnits(unitNames: ReadonlySet<string>): void {\n this.unitNames = unitNames;\n }\n\n /**\n * Build the optimized TokenLookup from all registered sources.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0)\n * 2. Provider classes (sorted by priority ascending)\n *\n * Returns a frozen TokenLookup that the Lexer consumes.\n * Call build() again after register()/setLocale()/setUnits() changes.\n */\n build(): TokenLookup {\n const keywordToType = new Map<string, string>();\n\n // Layer 1: Locale keywords (priority 0, lowest)\n if (this.localeKeywordMap) {\n for (const [keyword, tokenType] of Object.entries(this.localeKeywordMap)) {\n keywordToType.set(keyword.toLowerCase(), tokenType);\n }\n }\n\n // Layer 2: Provider keywords (sorted by priority ascending, higher wins)\n const sorted = [...this.classes].sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n for (const tc of sorted) {\n for (const keyword of Object.keys(tc.keywords)) {\n keywordToType.set(keyword.toLowerCase(), tc.tokenType);\n }\n }\n\n // Build phrase trie from locale + provider phrases\n const phraseTrie = this.buildPhraseTrie();\n\n // Build phraseStartWords set (first word of every phrase)\n const phraseStartWords = this.buildPhraseStartWords();\n\n return {\n keywordToType,\n phraseTrie,\n phraseStartWords,\n unitNames: this.unitNames ?? new Set(),\n };\n }\n\n // ── Private helpers ─────────────────────────────────────────────────────\n\n private buildPhraseTrie(): PhraseNode | null {\n const root: PhraseNode = { children: new Map() };\n\n // Layer 1: Locale phrases\n if (this.localePhraseMap) {\n for (const [phrase, tokenType] of Object.entries(this.localePhraseMap)) {\n this.insertPhrase(root, phrase.toLowerCase(), tokenType);\n }\n }\n\n // Layer 2: Provider phrases\n for (const tc of this.classes) {\n if (!tc.phrases) continue;\n for (const phrase of Object.keys(tc.phrases)) {\n this.insertPhrase(root, phrase.toLowerCase(), tc.tokenType);\n }\n }\n\n return root.children.size > 0 ? root : null;\n }\n\n private insertPhrase(root: PhraseNode, phrase: string, tokenType: string): void {\n const words = phrase.split(' ');\n let node = root;\n for (const word of words) {\n if (!node.children.has(word)) {\n node.children.set(word, { children: new Map() });\n }\n node = node.children.get(word)!;\n }\n // Only set type if not already set, first-registered (locale) wins\n if (!node.type) {\n node.type = tokenType;\n }\n }\n\n private buildPhraseStartWords(): Set<string> {\n const startWords = new Set<string>();\n\n // Locale phrase first words\n if (this.localePhraseMap) {\n for (const phrase of Object.keys(this.localePhraseMap)) {\n const first = phrase.split(' ')[0].toLowerCase();\n startWords.add(first);\n }\n }\n\n // Provider phrase first words\n for (const tc of this.classes) {\n if (!tc.phrases) continue;\n for (const phrase of Object.keys(tc.phrases)) {\n const first = phrase.split(' ')[0].toLowerCase();\n startWords.add(first);\n }\n }\n\n return startWords;\n }\n}","/**\n * tokenRegistration.ts, Bootstrap for building TokenLookup from locale, units, and phrases.\n *\n * This module centralizes the assembly of the TokenLookup consumed by ExpressionLexer.\n * It merges:\n * 1. Locale keywords (from ILocale.keywordMap)\n * 2. Built-in phrase patterns (to the power of, increase by, etc.)\n * 3. Known unit names (from units.ts)\n *\n * The resulting TokenLookup is frozen and passed to ExpressionLexer.configuredLookup\n * at construction time, enabling data-driven keyword/unit/phrase resolution.\n */\nimport { TokenClassRegistry } from '@solve-js/lexer/TokenClassRegistry';\nimport type { TokenLookup } from '@solve-js/lexer/TokenClassRegistry';\nimport { getLocale, type ILocale } from '@solve-js/constants/locales';\nimport { knownUnits } from '@solve-js/lexer/units';\n\n// ── Built-in phrase map ───────────────────────────────────────────────────\n// These are the multi-word expressions handled as compound tokens.\n// Matched by the PhraseMatcher (trie-based) in ExpressionLexer.tryMatchPhrase().\nconst BUILTIN_PHRASES: Record<string, string> = {\n 'to the power of': 'CARET',\n 'power of': 'CARET',\n 'increase by': 'INCREASE_BY',\n 'decrease by': 'DECREASE_BY',\n 'times by': 'TIMES_BY',\n 'multiply by': 'MULTIPLY_BY',\n 'multiplied by': 'MULTIPLY_BY',\n 'divide by': 'DIVIDE_BY',\n};\n\n/**\n * Build a TokenLookup from locale keywords, known units, and built-in phrases.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0, lowest, can be overridden by providers)\n * 2. Built-in phrases (via locale phraseMap)\n * 3. Known units (checked AFTER keyword lookup fails, via unitNames set)\n *\n * The resulting TokenLookup replaces the internal keyword map, unit set,\n * phrase trie, and phraseStartWords in ExpressionLexer when set via\n * ExpressionLexer.configuredLookup.\n *\n * @param localeCode - The locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @returns A frozen TokenLookup ready for consumption by the lexer.\n */\nexport function buildTokenLookup(localeCode = 'en'): TokenLookup {\n const locale: ILocale = getLocale(localeCode);\n const registry = new TokenClassRegistry();\n\n // Layer 1: Locale keywords (priority 0, lowest)\n registry.setLocale(locale.keywordMap, BUILTIN_PHRASES);\n\n // Layer 2: Known units (checked after keyword lookup)\n registry.setUnits(knownUnits);\n\n // Build and return the lookup\n return registry.build();\n}\n"]}