solve-engine 2.15.0 → 2.17.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 (174) hide show
  1. package/dist/{BytecodeBuilder-CRYfrFfq.d.cts → BytecodeBuilder-aqVa7Plx.d.cts} +10 -0
  2. package/dist/{BytecodeBuilder-CRYfrFfq.d.ts → BytecodeBuilder-aqVa7Plx.d.ts} +10 -0
  3. package/dist/{EngineError-Cv5q4Rbv.d.cts → EngineError-DTk7I7hZ.d.cts} +24 -0
  4. package/dist/{EngineError-Cv5q4Rbv.d.ts → EngineError-DTk7I7hZ.d.ts} +24 -0
  5. package/dist/{PackageCompatibility-Cl7GF_Iu.d.ts → PackageCompatibility-BGXSFuL9.d.ts} +1 -1
  6. package/dist/{PackageCompatibility-C2IQZ_w3.d.cts → PackageCompatibility-BZCqaTOO.d.cts} +1 -1
  7. package/dist/{PackageRegistry-CK_JoX50.d.ts → PackageRegistry-BRoVOYzg.d.ts} +107 -5
  8. package/dist/{PackageRegistry-CZO1IbS-.d.cts → PackageRegistry-rMGnTh7W.d.cts} +107 -5
  9. package/dist/{Parselet-CK0bNO1l.d.ts → Parselet-B-WyUtX4.d.ts} +5 -1
  10. package/dist/{Parselet-DOGmj6N6.d.cts → Parselet-Bkbp9CKD.d.cts} +5 -1
  11. package/dist/{ScopeManager-BtqiTVjG.d.cts → ScopeManager-bCYewWVt.d.cts} +2 -2
  12. package/dist/{ScopeManager-C6c1WmJD.d.ts → ScopeManager-gB9UengK.d.ts} +2 -2
  13. package/dist/{TokenNormalizer-BfTHg1qt.d.cts → TokenNormalizer-MXaKLJ_m.d.cts} +182 -0
  14. package/dist/{TokenNormalizer-d7F1KQFs.d.ts → TokenNormalizer-OTPS0Otq.d.ts} +182 -0
  15. package/dist/{VMCheckpoints-DJdvpliw.d.ts → VMCheckpoints-BDRY1Kx8.d.ts} +2 -2
  16. package/dist/{VMCheckpoints-BFDlaGse.d.cts → VMCheckpoints-DGar9Yg8.d.cts} +2 -2
  17. package/dist/{WorkerError-FH7KXX4_.d.cts → WorkerError-DGBNM3gA.d.cts} +1 -1
  18. package/dist/{WorkerError-J3v3ix_z.d.ts → WorkerError-DpZgKRks.d.ts} +1 -1
  19. package/dist/{chunk-UZSPBFZN.js → chunk-2DPKJ2SM.js} +2 -2
  20. package/dist/{chunk-UZSPBFZN.js.map → chunk-2DPKJ2SM.js.map} +1 -1
  21. package/dist/{chunk-O3ALJLYC.js → chunk-3GR46UOX.js} +2 -2
  22. package/dist/{chunk-O3ALJLYC.js.map → chunk-3GR46UOX.js.map} +1 -1
  23. package/dist/{chunk-PREIL3IB.cjs → chunk-3SSMOVWB.cjs} +2 -2
  24. package/dist/{chunk-PREIL3IB.cjs.map → chunk-3SSMOVWB.cjs.map} +1 -1
  25. package/dist/{chunk-XK23K3EJ.js → chunk-4ETS224G.js} +2 -2
  26. package/dist/{chunk-XK23K3EJ.js.map → chunk-4ETS224G.js.map} +1 -1
  27. package/dist/{chunk-Q7HPPLMG.js → chunk-5FMYW44V.js} +2 -2
  28. package/dist/{chunk-Q7HPPLMG.js.map → chunk-5FMYW44V.js.map} +1 -1
  29. package/dist/{chunk-GWCBPITD.cjs → chunk-6YM67DWH.cjs} +3 -3
  30. package/dist/{chunk-GWCBPITD.cjs.map → chunk-6YM67DWH.cjs.map} +1 -1
  31. package/dist/{chunk-6U66HQKQ.cjs → chunk-75JLWK4L.cjs} +2 -2
  32. package/dist/{chunk-6U66HQKQ.cjs.map → chunk-75JLWK4L.cjs.map} +1 -1
  33. package/dist/chunk-A2RQUV5H.cjs +5 -0
  34. package/dist/chunk-A2RQUV5H.cjs.map +1 -0
  35. package/dist/{chunk-VJP4GGCW.cjs → chunk-BNCBB4H5.cjs} +2 -2
  36. package/dist/{chunk-VJP4GGCW.cjs.map → chunk-BNCBB4H5.cjs.map} +1 -1
  37. package/dist/{chunk-EEUA3OJ6.cjs → chunk-CEURQXSN.cjs} +2 -2
  38. package/dist/{chunk-EEUA3OJ6.cjs.map → chunk-CEURQXSN.cjs.map} +1 -1
  39. package/dist/chunk-CO2BI6WL.cjs +3 -0
  40. package/dist/chunk-CO2BI6WL.cjs.map +1 -0
  41. package/dist/chunk-EN3CDYOS.cjs +2 -0
  42. package/dist/chunk-EN3CDYOS.cjs.map +1 -0
  43. package/dist/{chunk-GWJJRH32.js → chunk-EQDT42JG.js} +3 -3
  44. package/dist/{chunk-GWJJRH32.js.map → chunk-EQDT42JG.js.map} +1 -1
  45. package/dist/chunk-G2MFTERZ.cjs +2 -0
  46. package/dist/chunk-G2MFTERZ.cjs.map +1 -0
  47. package/dist/chunk-G63TMUL2.js +2 -0
  48. package/dist/chunk-G63TMUL2.js.map +1 -0
  49. package/dist/{chunk-UUAFDZK6.cjs → chunk-H3JXNH7X.cjs} +3 -3
  50. package/dist/{chunk-UUAFDZK6.cjs.map → chunk-H3JXNH7X.cjs.map} +1 -1
  51. package/dist/{chunk-3Y56PSQD.cjs → chunk-HQ2PE6HY.cjs} +3 -3
  52. package/dist/{chunk-3Y56PSQD.cjs.map → chunk-HQ2PE6HY.cjs.map} +1 -1
  53. package/dist/chunk-IES365YJ.cjs +3 -0
  54. package/dist/chunk-IES365YJ.cjs.map +1 -0
  55. package/dist/{chunk-2XZCLDHJ.cjs → chunk-J7ABVGZH.cjs} +2 -2
  56. package/dist/{chunk-2XZCLDHJ.cjs.map → chunk-J7ABVGZH.cjs.map} +1 -1
  57. package/dist/chunk-JVMINMAB.js +2 -0
  58. package/dist/chunk-JVMINMAB.js.map +1 -0
  59. package/dist/chunk-JYLNQOPU.cjs +2 -0
  60. package/dist/chunk-JYLNQOPU.cjs.map +1 -0
  61. package/dist/{chunk-JOIQFDZQ.js → chunk-KEA5HRL3.js} +2 -2
  62. package/dist/{chunk-JOIQFDZQ.js.map → chunk-KEA5HRL3.js.map} +1 -1
  63. package/dist/{chunk-TVE2DNPU.js → chunk-LJFS3XHW.js} +2 -2
  64. package/dist/{chunk-TVE2DNPU.js.map → chunk-LJFS3XHW.js.map} +1 -1
  65. package/dist/{chunk-C5MP74ER.js → chunk-MRRMIBHE.js} +2 -2
  66. package/dist/{chunk-C5MP74ER.js.map → chunk-MRRMIBHE.js.map} +1 -1
  67. package/dist/chunk-N64ZK6CL.cjs +2 -0
  68. package/dist/{chunk-EEVUKZ5B.cjs.map → chunk-N64ZK6CL.cjs.map} +1 -1
  69. package/dist/chunk-O3BDXOQJ.js +2 -0
  70. package/dist/chunk-O3BDXOQJ.js.map +1 -0
  71. package/dist/chunk-PIZQIQVM.js +3 -0
  72. package/dist/chunk-PIZQIQVM.js.map +1 -0
  73. package/dist/chunk-PS5OA7QU.js +5 -0
  74. package/dist/chunk-PS5OA7QU.js.map +1 -0
  75. package/dist/{chunk-IPOU3JTA.js → chunk-QTSDIDAS.js} +3 -3
  76. package/dist/{chunk-IPOU3JTA.js.map → chunk-QTSDIDAS.js.map} +1 -1
  77. package/dist/chunk-RHE3LC4Q.js +2 -0
  78. package/dist/chunk-RHE3LC4Q.js.map +1 -0
  79. package/dist/{chunk-P4ETODMP.js → chunk-RLTH2H3U.js} +2 -2
  80. package/dist/{chunk-P4ETODMP.js.map → chunk-RLTH2H3U.js.map} +1 -1
  81. package/dist/{chunk-WOIJPV7Z.js → chunk-SEOIKHYK.js} +2 -2
  82. package/dist/{chunk-WOIJPV7Z.js.map → chunk-SEOIKHYK.js.map} +1 -1
  83. package/dist/{chunk-W5ELYJ4Z.cjs → chunk-TL545PXW.cjs} +2 -2
  84. package/dist/{chunk-W5ELYJ4Z.cjs.map → chunk-TL545PXW.cjs.map} +1 -1
  85. package/dist/{chunk-FAGFPVYK.cjs → chunk-TRDOYAKJ.cjs} +2 -2
  86. package/dist/{chunk-FAGFPVYK.cjs.map → chunk-TRDOYAKJ.cjs.map} +1 -1
  87. package/dist/chunk-WMISTHB2.cjs +2 -0
  88. package/dist/chunk-WMISTHB2.cjs.map +1 -0
  89. package/dist/{chunk-3PDDKWTJ.js → chunk-XOEZ7UQI.js} +3 -3
  90. package/dist/{chunk-3PDDKWTJ.js.map → chunk-XOEZ7UQI.js.map} +1 -1
  91. package/dist/{chunk-EXCFCHAT.cjs → chunk-XPJGDGJF.cjs} +2 -2
  92. package/dist/{chunk-EXCFCHAT.cjs.map → chunk-XPJGDGJF.cjs.map} +1 -1
  93. package/dist/chunk-YQV4WGXH.js +3 -0
  94. package/dist/chunk-YQV4WGXH.js.map +1 -0
  95. package/dist/constants.cjs +1 -1
  96. package/dist/constants.js +1 -1
  97. package/dist/engine.cjs +1 -1
  98. package/dist/engine.d.cts +8 -8
  99. package/dist/engine.d.ts +8 -8
  100. package/dist/engine.js +1 -1
  101. package/dist/errors.cjs +1 -1
  102. package/dist/errors.d.cts +3 -3
  103. package/dist/errors.d.ts +3 -3
  104. package/dist/errors.js +1 -1
  105. package/dist/format.cjs +1 -1
  106. package/dist/format.js +1 -1
  107. package/dist/index.cjs +1 -1
  108. package/dist/index.d.cts +8 -8
  109. package/dist/index.d.ts +8 -8
  110. package/dist/index.js +1 -1
  111. package/dist/language.d.cts +7 -7
  112. package/dist/language.d.ts +7 -7
  113. package/dist/lexer.cjs +1 -1
  114. package/dist/lexer.js +1 -1
  115. package/dist/normalizer.cjs +1 -1
  116. package/dist/normalizer.d.cts +2 -2
  117. package/dist/normalizer.d.ts +2 -2
  118. package/dist/normalizer.js +1 -1
  119. package/dist/packages.cjs +1 -1
  120. package/dist/packages.d.cts +6 -6
  121. package/dist/packages.d.ts +6 -6
  122. package/dist/packages.js +1 -1
  123. package/dist/parser.cjs +1 -1
  124. package/dist/parser.d.cts +2 -2
  125. package/dist/parser.d.ts +2 -2
  126. package/dist/parser.js +1 -1
  127. package/dist/resolvers.d.cts +1 -1
  128. package/dist/resolvers.d.ts +1 -1
  129. package/dist/testing.cjs +2 -2
  130. package/dist/testing.d.cts +7 -7
  131. package/dist/testing.d.ts +7 -7
  132. package/dist/testing.js +1 -1
  133. package/dist/uom.cjs +1 -1
  134. package/dist/uom.d.cts +1 -1
  135. package/dist/uom.d.ts +1 -1
  136. package/dist/uom.js +1 -1
  137. package/dist/vm.cjs +1 -1
  138. package/dist/vm.d.cts +5 -5
  139. package/dist/vm.d.ts +5 -5
  140. package/dist/vm.js +1 -1
  141. package/dist/worker.cjs +2 -2
  142. package/dist/worker.d.cts +7 -7
  143. package/dist/worker.d.ts +7 -7
  144. package/dist/worker.js +1 -1
  145. package/package.json +1 -1
  146. package/dist/chunk-4IIFFJTJ.js +0 -5
  147. package/dist/chunk-4IIFFJTJ.js.map +0 -1
  148. package/dist/chunk-5SDSIRPL.js +0 -2
  149. package/dist/chunk-5SDSIRPL.js.map +0 -1
  150. package/dist/chunk-AYTEPHRO.js +0 -3
  151. package/dist/chunk-AYTEPHRO.js.map +0 -1
  152. package/dist/chunk-CUDPOWXA.js +0 -2
  153. package/dist/chunk-CUDPOWXA.js.map +0 -1
  154. package/dist/chunk-EEVUKZ5B.cjs +0 -2
  155. package/dist/chunk-FPGYRFJY.cjs +0 -5
  156. package/dist/chunk-FPGYRFJY.cjs.map +0 -1
  157. package/dist/chunk-FVQWN5HZ.cjs +0 -2
  158. package/dist/chunk-FVQWN5HZ.cjs.map +0 -1
  159. package/dist/chunk-HDGARCI2.cjs +0 -2
  160. package/dist/chunk-HDGARCI2.cjs.map +0 -1
  161. package/dist/chunk-IMXSVHQK.cjs +0 -2
  162. package/dist/chunk-IMXSVHQK.cjs.map +0 -1
  163. package/dist/chunk-KKMLFYVW.cjs +0 -3
  164. package/dist/chunk-KKMLFYVW.cjs.map +0 -1
  165. package/dist/chunk-NAZ6PGLS.cjs +0 -3
  166. package/dist/chunk-NAZ6PGLS.cjs.map +0 -1
  167. package/dist/chunk-Q3PSTNSY.js +0 -2
  168. package/dist/chunk-Q3PSTNSY.js.map +0 -1
  169. package/dist/chunk-RC4M6HBX.cjs +0 -2
  170. package/dist/chunk-RC4M6HBX.cjs.map +0 -1
  171. package/dist/chunk-YAZ4DUJJ.js +0 -3
  172. package/dist/chunk-YAZ4DUJJ.js.map +0 -1
  173. package/dist/chunk-YFX53MZF.js +0 -2
  174. package/dist/chunk-YFX53MZF.js.map +0 -1
@@ -1,2 +0,0 @@
1
- 'use strict';var chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunkNAZ6PGLS_cjs=require('./chunk-NAZ6PGLS.cjs');var o={Lowest:0,Assignment:10,LogicalOr:12,LogicalAnd:14,Conjunction:16,BitwiseOr:18,BitwiseXor:20,BitwiseAnd:22,Conditional:24,Shift:27,Sum:30,Product:40,Uncertainty:45,Exponent:50,Prefix:60,Postfix:70,Call:80};var l={[chunk5IJD5L3O_cjs.a.PLUS]:o.Sum,[chunk5IJD5L3O_cjs.a.MINUS]:o.Sum,[chunk5IJD5L3O_cjs.a.STAR]:o.Product,[chunk5IJD5L3O_cjs.a.SLASH]:o.Product,[chunk5IJD5L3O_cjs.a.MOD]:o.Product,[chunk5IJD5L3O_cjs.a.CARET]:o.Exponent,[chunk5IJD5L3O_cjs.a.BIT_OR]:o.BitwiseOr,[chunk5IJD5L3O_cjs.a.BIT_XOR]:o.BitwiseXor,[chunk5IJD5L3O_cjs.a.BIT_AND]:o.BitwiseAnd,[chunk5IJD5L3O_cjs.a.LSHIFT]:o.Shift,[chunk5IJD5L3O_cjs.a.RSHIFT]:o.Shift,[chunk5IJD5L3O_cjs.a.URSHIFT]:o.Shift,[chunk5IJD5L3O_cjs.a.PERCENT]:o.Postfix,[chunk5IJD5L3O_cjs.a.OF]:o.Product},h=null;function N(){if(h)return h;let s=0;for(let e of Object.keys(l)){let t=chunk5IJD5L3O_cjs.c(e);t>s&&(s=t);}for(let e of Object.values(chunk5IJD5L3O_cjs.a)){let t=chunk5IJD5L3O_cjs.c(e);t>s&&(s=t);}let n=new Uint8Array(s+1);for(let[e,t]of Object.entries(l)){let d=chunk5IJD5L3O_cjs.c(e);n[d]=t;}return h=n,n}function O(){h=null;}var r=255,f=class{constructor(n){this.pluginFunctionIndex=n;this.opcodes=[];this.numbers=[];this.strings=[];this.stringIndex=new Map;this._hasAsync=false;this.userFunctionBodies=[];this.anonymousBodies=[];}get pluginIndexMap(){return this.pluginFunctionIndex}emitPluginCall(n,e){let t=this.pluginFunctionIndex?.get(n);if(t===void 0)throw chunkNAZ6PGLS_cjs.c.execution("UNKNOWN_PLUGIN_FUNCTION",`No registered plugin function named "${n}". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,{functionName:n});if(t>65535)throw chunkNAZ6PGLS_cjs.c.parsing("PLUGIN_FUNCTION_INDEX_TOO_LARGE",`Plugin-function index ${t} exceeds the two-byte bytecode limit (65535).`,{index:t});t<=255?(this.emitOpcode(50),this.emitIndex(t)):(this.emitOpcode(161),this.emitIndex(t&255),this.emitIndex(t>>8&255)),this.emitIndex(e);}emitOpcode(n){this.opcodes.push(n),(n===50||n===161)&&(this._hasAsync=true);}emitNumber(n){let e=this.numbers.length;if(e>r)throw chunkNAZ6PGLS_cjs.c.parsing("TOO_MANY_NUMERIC_CONSTANTS",`Expression has more than ${r+1} numeric literals, exceeding the bytecode constant pool's limit.`,{limit:r+1});this.numbers.push(n),this.opcodes.push(e);}emitString(n){let e=this.stringIndex.get(n);if(e===void 0){if(e=this.strings.length,e>r)throw chunkNAZ6PGLS_cjs.c.parsing("TOO_MANY_STRING_CONSTANTS",`Expression has more than ${r+1} distinct string literals, exceeding the bytecode constant pool's limit.`,{limit:r+1});this.strings.push(n),this.stringIndex.set(n,e);}this.opcodes.push(e);}emitIndex(n){this.opcodes.push(n);}emitByte(n){this.opcodes.push(n);}get currentLength(){return this.opcodes.length}emitUserFunctionBody(n,e,t){let d=this.userFunctionBodies.length;if(d>r)throw chunkNAZ6PGLS_cjs.c.parsing("TOO_MANY_FUNCTION_DEFINITIONS",`More than ${r+1} function definitions on one line, exceeding the bytecode constant pool's limit.`,{limit:r+1});return this.userFunctionBodies.push({name:n,params:e,program:t}),d}emitAnonymousBody(n,e){let t=this.anonymousBodies.length;if(t>r)throw chunkNAZ6PGLS_cjs.c.parsing("TOO_MANY_ANONYMOUS_BODIES",`More than ${r+1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,{limit:r+1});return this.anonymousBodies.push({params:n,program:e}),t}patchJump(n,e){this.opcodes[n]=e;}build(){return {opcodes:new Uint8Array(this.opcodes),numbers:new Float64Array(this.numbers),strings:[...this.strings],constants:new Map,hasAsync:this._hasAsync,userFunctionBodies:this.userFunctionBodies.length>0?[...this.userFunctionBodies]:void 0,anonymousBodies:this.anonymousBodies.length>0?[...this.anonymousBodies]:void 0}}buildInto(n){let e=this.opcodes.length,t=this.numbers.length,d=n&&n.opcodes.length>=e,b=n&&n.numbers.length>=t,m=d?new Uint8Array(n.opcodes.buffer,n.opcodes.byteOffset,e):new Uint8Array(e),p=b?new Float64Array(n.numbers.buffer,n.numbers.byteOffset,t):new Float64Array(t);for(let u=0;u<e;u++)m[u]=this.opcodes[u];for(let u=0;u<t;u++)p[u]=this.numbers[u];return {opcodes:m,numbers:p,strings:[...this.strings],constants:new Map,hasAsync:this._hasAsync,userFunctionBodies:this.userFunctionBodies.length>0?[...this.userFunctionBodies]:void 0,anonymousBodies:this.anonymousBodies.length>0?[...this.anonymousBodies]:void 0}}reset(){this.opcodes.length=0,this.numbers.length=0,this.strings.length=0,this.stringIndex.clear(),this._hasAsync=false,this.userFunctionBodies.length=0,this.anonymousBodies.length=0;}};var I=/^\d{1,3}(\.\d{3}){2,}$/,y=/^\d+$/;function S(s,n){let e=s.endsWith("n")?s.slice(0,-1):s;if(y.test(e))return e;let t=I.test(e)?e.split(".").join(""):A(e,n);if(!y.test(t)){let d=e.includes(".")?".":e.includes(",")?",":e;throw chunkNAZ6PGLS_cjs.c.parsing("INVALID_NUMBER_LITERAL",`"${s}" is not a whole number: "${d}" separates decimals in the ${n} locale, and a whole number cannot have a fractional part.`,{raw:s,localeCode:n,separator:d})}return t}function A(s,n){let e=chunkS3DFU33X_cjs.a(n).display.thousandsSeparator;return e?s.split(e).join(""):s}exports.a=o;exports.b=N;exports.c=O;exports.d=f;exports.e=S;//# sourceMappingURL=chunk-FVQWN5HZ.cjs.map
2
- //# sourceMappingURL=chunk-FVQWN5HZ.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","BytecodeBuilder","pluginFunctionIndex","argCount","index","ErrorFactory","op","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","localeCode","withoutSuffix","digits","stripLocaleGrouping","separator","text","thousandsSeparator","getLocale"],"mappings":"uKAWO,IAAMA,CAAAA,CAAe,CAC1B,MAAA,CAAQ,CAAA,CACR,WAAY,EAAA,CACZ,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CAaZ,WAAA,CAAa,GAab,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CACZ,UAAA,CAAY,EAAA,CACZ,YAAa,EAAA,CACb,KAAA,CAAO,EAAA,CACP,GAAA,CAAK,EAAA,CACL,OAAA,CAAS,GAMT,WAAA,CAAa,EAAA,CAIb,SAAU,EAAA,CACV,MAAA,CAAQ,GACR,OAAA,CAAS,EAAA,CACT,IAAA,CAAM,EACR,EAiDA,IAAMC,EAA2C,CAE/C,CAACC,mBAAAA,CAAW,IAAI,EAAOF,CAAAA,CAAa,IACpC,CAACE,mBAAAA,CAAW,KAAK,EAAMF,CAAAA,CAAa,GAAA,CACpC,CAACE,mBAAAA,CAAW,IAAI,EAAOF,CAAAA,CAAa,OAAA,CACpC,CAACE,mBAAAA,CAAW,KAAK,EAAMF,CAAAA,CAAa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CAAAA,CAAc,KAAA,CAAM,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAChCE,CAAAA,CAAoBF,CAAAA,CAAeD,CAAU,CAAA,CAEhD,GAAI,CAACH,CAAAA,CAAY,IAAA,CAAKK,CAAM,EAAG,CAC9B,IAAME,CAAAA,CAAYH,CAAAA,CAAc,QAAA,CAAS,GAAG,EAAI,GAAA,CAAMA,CAAAA,CAAc,SAAS,GAAG,CAAA,CAAI,IAAMA,CAAAA,CAC1F,MAAMtB,mBAAAA,CAAa,OAAA,CAClB,wBAAA,CACA,CAAA,CAAA,EAAIoB,CAAG,CAAA,0BAAA,EAA6BK,CAAS,CAAA,4BAAA,EAA+BJ,CAAU,CAAA,0DAAA,CAAA,CACtF,CAAE,IAAAD,CAAAA,CAAK,UAAA,CAAAC,CAAAA,CAAY,SAAA,CAAAI,CAAU,CAC9B,CACD,CACA,OAAOF,CACR,CASA,SAASC,CAAAA,CAAoBE,EAAcL,CAAAA,CAA4B,CACtE,IAAMM,CAAAA,CAAqBC,mBAAAA,CAAUP,CAAU,EAAE,OAAA,CAAQ,kBAAA,CACzD,OAAOM,CAAAA,CAAqBD,CAAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-FVQWN5HZ.cjs","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when declaring an infix parselet in a\n * package's `infixParselets`. See the built-in packages for examples of\n * picking an appropriate level (e.g. arithmetic `+`/`-` use `Sum`, `*`/`/`\n * use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nconst BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/**\n\t * The per-engine `plugin function name -> registry index` map, wired in by\n\t * the engine so {@link emitPluginCall} can resolve a name at emit time. The\n\t * same object reference is shared with every builder in an engine (the pool\n\t * and each ad-hoc nested-body builder), and the engine populates it as\n\t * packages register, so a parselet never sees the numeric index.\n\t */\n\tconstructor(private readonly pluginFunctionIndex?: ReadonlyMap<string, number>) {}\n\n\t/** The name->index map, so a nested-body builder inherits the same resolution. */\n\tget pluginIndexMap(): ReadonlyMap<string, number> | undefined {\n\t\treturn this.pluginFunctionIndex;\n\t}\n\n\t/**\n\t * Emit a plugin-function call by NAME. The engine assigns each registered\n\t * `pluginFunctions` entry an index at registration; this resolves the name to\n\t * that index and emits `CALL_PLUGIN` + index + argCount. Package authors emit\n\t * through this rather than a hand-allocated index.\n\t */\n\temitPluginCall(name: string, argCount: number): void {\n\t\tconst index = this.pluginFunctionIndex?.get(name);\n\t\tif (index === undefined) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"UNKNOWN_PLUGIN_FUNCTION\",\n\t\t\t\t`No registered plugin function named \"${name}\". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,\n\t\t\t\t{ functionName: name },\n\t\t\t);\n\t\t}\n\t\t// One byte covers the first 256 plugin functions; beyond that, the\n\t\t// wide opcode carries a two-byte little-endian index. Emitting the\n\t\t// narrow form whenever it fits keeps existing bytecode and snapshots\n\t\t// byte-for-byte unchanged. The index cannot exceed 65535 because the\n\t\t// allocator (allocatePluginFunctionIndex) caps it, but guard anyway so\n\t\t// a stray index is a clear error rather than a silently truncated byte.\n\t\tif (index > 0xffff) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\t\t\t\t`Plugin-function index ${index} exceeds the two-byte bytecode limit (65535).`,\n\t\t\t\t{ index },\n\t\t\t);\n\t\t}\n\t\tif (index <= 0xff) {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN);\n\t\t\tthis.emitIndex(index);\n\t\t} else {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN_WIDE);\n\t\t\tthis.emitIndex(index & 0xff); // low byte\n\t\t\tthis.emitIndex((index >> 8) & 0xff); // high byte\n\t\t}\n\t\tthis.emitIndex(argCount);\n\t}\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN || op === OpCode.CALL_PLUGIN_WIDE) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: appends `n` to the program's constant pool and\n\t * writes its index into the opcode stream (read back by the VM as e.g.\n\t * `PUSH_NUMBER <idx>`).\n\t *\n\t * Numeric constants are NOT deduplicated (unlike {@link emitString})\n\t * every call appends a new entry, so an expression with more than\n\t * {@link MAX_CONSTANT_POOL_INDEX}+1 distinct numeric-literal occurrences\n\t * throws rather than silently wrapping the index (see\n\t * `MAX_CONSTANT_POOL_INDEX`'s doc for what that would otherwise do).\n\t *\n\t * @throws If the constant pool would exceed 256 entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst idx = this.numbers.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.numbers.push(n);\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(b);\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tthis.opcodes[position] = target;\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: new Float64Array(this.numbers),\n\t\t\t// Defensive copy: .length = 0 in reset() would clear a shared reference.\n\t\t\t// Strings are rare (only UoM/datetime parselets emit them), so the copy\n\t\t\t// cost is negligible.\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tthis.numbers.length = 0;\n\t\tthis.strings.length = 0;\n\t\tthis.stringIndex.clear();\n\t\tthis._hasAsync = false;\n\t\tthis.userFunctionBodies.length = 0;\n\t\tthis.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkFVQWN5HZ_cjs=require('./chunk-FVQWN5HZ.cjs'),chunkFAGFPVYK_cjs=require('./chunk-FAGFPVYK.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkNAZ6PGLS_cjs=require('./chunk-NAZ6PGLS.cjs');var A=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(67),e.emitIndex(1);}};var O=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(68),e.emitIndex(1);}};function L(t,o){let r=t.peek();if(!r||r.type!=="IDENT"&&r.type!=="UNIT")throw chunkNAZ6PGLS_cjs.c.parsing("SYMBOLIC_REQUIRES_VARIABLE_NAME",`${o} needs the name of an unknown here, as in ${o}(x^2, x).`,{found:r?.type??"end of input"});return t.consume(),r.value}function x(t,o){t.emitOpcode(13),t.emitString(o);}function N(t,o,r){let e=new chunkFVQWN5HZ_cjs.d(o.pluginIndexMap);t.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),t.setBuilder(o);let n=e.build();if(n.hasAsync)throw chunkNAZ6PGLS_cjs.c.parsing("SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS",`${r}'s expression must be synchronous (no weather/stocks/currency calls).`);return n}function I(t,o,r){let e=t.emitAnonymousBody([r],o);t.emitOpcode(159),t.emitIndex(e);}var R=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"solve"),m=o.match("EQUALS")?N(o,e,"solve"):null;o.consume("COMMA");let l=o.peek();if(!l||l.type!=="IDENT"&&l.type!=="UNIT")throw chunkNAZ6PGLS_cjs.c.parsing("SOLVE_REQUIRES_VARIABLE_NAME","solve's second argument must be the name of the unknown to solve for, as in solve(x^2-4=0, x).",{found:l?.type??"end of input"});o.consume(),I(e,n,l.value),m?I(e,m,l.value):(e.emitOpcode(10),e.emitNumber(0)),x(e,l.value),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(69),e.emitIndex(3);}};var g=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"der");o.consume("COMMA");let m=L(o,"der");I(e,n,m),x(e,m),o.match("COMMA")?o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e):(e.emitOpcode(10),e.emitNumber(1)),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(70),e.emitIndex(3);}};var C=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"integral");o.consume("COMMA");let m=L(o,"integral");I(e,n,m),x(e,m),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(71),e.emitIndex(2);}};var M=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"taylor");o.consume("COMMA");let m=L(o,"taylor");I(e,n,m),x(e,m),o.consume("EQUALS"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("COMMA"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(72),e.emitIndex(4);}};var S=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=0;do o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),n++;while(o.match("COMMA"));o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(73),e.emitIndex(n);}};var k=class{constructor(){this.category="Symbolic";}parse(o,r,e){e.emitOpcode(10),e.emitNumber(Number(r.value)),e.emitOpcode(51),e.emitIndex(74),e.emitIndex(1);}};var w=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(75),e.emitIndex(1);}};var v=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(76),e.emitIndex(1);}};var U=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(77),e.emitIndex(1);}};var F=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(78),e.emitIndex(1);}};var h=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(79),e.emitIndex(1);}};function V(t=75){return {name:"symbolic:imaginary-literal",priority:t,match(o,r){let e=o[r];if(!e||e.type!=="NUMBER")return null;let n=o[r+1];return !n||n.type!=="IDENT"||n.value!=="i"||n.offset!==e.offset+e.value.length||o[r+2]?.type==="LPAREN"?null:{consumed:2,replacement:[new chunkFAGFPVYK_cjs.a("IMAGINARY",chunk5IJD5L3O_cjs.c("IMAGINARY"),e.value,e.value,e.offset,0,e.line,e.col)],ruleName:"symbolic:imaginary-literal"}}}}var ie={expand:"EXPAND_FN",factor:"FACTOR_FN",solve:"SOLVE_FN",der:"DER_FN",derivative:"DER_FN",integral:"INTEGRAL_FN",taylor:"TAYLOR_FN",jacobian:"JACOBIAN_FN",conj:"CONJ_FN",re:"RE_FN",im:"IM_FN",cancel:"CANCEL_FN",apart:"APART_FN"};function $(t=80){return {name:"symbolic:call",priority:t,startTokenTypes:["IDENT"],match(o,r){let e=o[r];if(!e||e.type!=="IDENT")return null;let n=ie[e.value.toLowerCase()];return !n||o[r+1]?.type!=="LPAREN"?null:{consumed:1,replacement:[new chunkFAGFPVYK_cjs.a(n,chunk5IJD5L3O_cjs.c(n),e.value,e.value,e.offset,0,e.line,e.col)],ruleName:"symbolic:call"}}}}var j=[{word:"expand",tokenType:"EXPAND_FN",builtinIndex:67,example:"expand((x+1)*(x+2))",expected:"x^2+3x+2",docPage:"algebra.md"},{word:"factor",tokenType:"FACTOR_FN",builtinIndex:68,example:"factor(x^2-4)",expected:"(x-2)*(x+2)",docPage:"algebra.md"},{word:"solve",tokenType:"SOLVE_FN",builtinIndex:69,example:"solve(x^2-4=0, x)",expected:"= [-2, 2]",docPage:"algebra.md"},{word:"der",tokenType:"DER_FN",builtinIndex:70,example:"der(x^3, x)",expected:"3x^2",docPage:"calculus.md"},{word:"integral",tokenType:"INTEGRAL_FN",builtinIndex:71,example:"integral(x^2, x)",expected:"1/3x^3",docPage:"calculus.md"},{word:"taylor",tokenType:"TAYLOR_FN",builtinIndex:72,example:"taylor(exp(x), x=0, 3)",expected:"1/6x^3+0.5x^2+x+1",docPage:"calculus.md"},{word:"jacobian",tokenType:"JACOBIAN_FN",builtinIndex:73,example:"jacobian(x*y, x+y)",expected:"= [y, x; 1, 1]",docPage:"calculus.md"},{word:"conj",tokenType:"CONJ_FN",builtinIndex:75,example:"conj(2+3i)",expected:"2-3i",docPage:"complex.md"},{word:"re",tokenType:"RE_FN",builtinIndex:76,example:"re(2+3i)",expected:"= 2",docPage:"complex.md"},{word:"im",tokenType:"IM_FN",builtinIndex:77,example:"im(2+3i)",expected:"= 3",docPage:"complex.md"},{word:"cancel",tokenType:"CANCEL_FN",builtinIndex:78,example:"cancel((x^2-1)/(x-1))",expected:"x+1",docPage:"algebra.md"},{word:"apart",tokenType:"APART_FN",builtinIndex:79,example:"apart((3x+5)/(x^2-1))",expected:"4/(x-1)-1/(x+1)",docPage:"algebra.md"}],le={name:"solve-symbolic",normalizerRules:[$(),V()],prefixParselets:{EXPAND_FN:new A,FACTOR_FN:new O,SOLVE_FN:new R,DER_FN:new g,INTEGRAL_FN:new C,TAYLOR_FN:new M,JACOBIAN_FN:new S,IMAGINARY:new k,CONJ_FN:new w,RE_FN:new v,IM_FN:new U,CANCEL_FN:new F,APART_FN:new h},tokenCategories:{EXPAND_FN:"keyword",FACTOR_FN:"keyword",SOLVE_FN:"keyword",DER_FN:"keyword",INTEGRAL_FN:"keyword",TAYLOR_FN:"keyword",JACOBIAN_FN:"keyword",IMAGINARY:"number",CONJ_FN:"keyword",RE_FN:"keyword",IM_FN:"keyword",CANCEL_FN:"keyword",APART_FN:"keyword"}},ae=new Set(j.map(t=>t.tokenType));function se(t){return t.some(o=>ae.has(o.type))}var ce=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function H(t){let o=t.trim();if(o.length>=2&&o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1)),!ce.test(o))return null;let r=new Date(o).getTime();return Number.isNaN(r)?null:r}function Eo(t){let o=new Date(t),r=E=>String(E).padStart(2,"0"),e=o.getFullYear(),n=r(o.getMonth()+1),m=r(o.getDate()),l=r(o.getHours()),s=r(o.getMinutes()),c=r(o.getSeconds()),p=-o.getTimezoneOffset(),y=p>=0?"+":"-",a=Math.abs(p),f=r(Math.floor(a/60)),u=r(a%60);return `${e}-${n}-${m}T${l}:${s}:${c}${y}${f}:${u}`}var pe=1e12;function Ao(t){return Math.abs(t)>=pe?t:t*1e3}var D="DATETIME_LITERAL",J=chunk5IJD5L3O_cjs.c(D),Y=/^\d+$/,ue=/^\d{1,2}\.\d{1,2}$/,de=/^\.(\d{2}|\d{4})$/,d=/^\d{1,2}$/;function fe(t){for(let o=0;o<t.length-1;o++){let r=t[o];if((r.sourceEnd??r.offset+r.text.length)!==t[o+1].offset)return false}return true}function b(t){if(t.length===4)return Number(t);if(t.length===2){let o=Number(t);return o<=68?2e3+o:1900+o}return null}function P(t,o,r,e,n){if(o<1||o>12||t<1||t>31)return null;let m=new Date(r,o-1,t);if(m.getFullYear()!==r||m.getMonth()!==o-1||m.getDate()!==t)return null;let l=e[0],s=e.map(p=>p.value).join(""),c=new chunkFAGFPVYK_cjs.a(D,J,String(m.getTime()),s,l.offset,0,l.line,l.col);return {consumed:e.length,replacement:[c],ruleName:n}}var Ne=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?/,Ie=new Set(["NUMBER","MINUS","PLUS","COLON","IDENT"]),xe=16;function ye(t,o,r){let e=t[o];if(e.sourceEnd!==void 0)return null;let n=e.text,m=e.offset+e.text.length,l=[e];for(let f=o+1;f<t.length&&l.length<xe;f++){let u=t[f];if(u.sourceEnd!==void 0||u.offset!==m||!Ie.has(u.type))break;n+=u.text,m=u.offset+u.text.length,l.push(u);}let s=Ne.exec(n);if(s===null)return null;let c=0,p=0;for(let f of l)if(p+=f.text.length,c++,p>=s[0].length)break;if(p!==s[0].length)return null;let y=H(s[0]);if(y===null)return null;let a=new chunkFAGFPVYK_cjs.a(D,J,String(y),s[0],e.offset,0,e.line,e.col,e.offset+s[0].length);return {consumed:c,replacement:[a],ruleName:r}}function Te(t,o,r,e){if(e==="YMD")return t.length!==4||!d.test(o)||!d.test(r)?null:{year:Number(t),month:Number(o),day:Number(r)};if(!d.test(t)||!d.test(o))return null;let n=b(r);return n===null?null:e==="DMY"?{day:Number(t),month:Number(o),year:n}:{day:Number(o),month:Number(t),year:n}}function Mo(t=()=>"auto"){return {name:"datetime:date-literal",priority:70,match(o,r){let e=o[r];if(e.type!=="NUMBER")return null;if(ue.test(e.value)){let a=o[r+1];if(a&&a.type==="NUMBER"&&de.test(a.value)){let[f,u]=e.value.split("."),E=b(a.value.slice(1));if(E!==null){let z=P(Number(f),Number(u),E,[e,a],"datetime:date-literal:dot");if(z)return z}}return null}if(e.value.length===4&&Y.test(e.value)){let a=ye(o,r,"datetime:date-literal:iso-timestamp");if(a)return a}if(!Y.test(e.value))return null;let n=o[r+1];if(!n||n.type!=="SLASH"&&n.type!=="MINUS")return null;let m=o[r+2],l=o[r+3],s=o[r+4];if(!m||m.type!=="NUMBER"||!Y.test(m.value)||!l||l.type!==n.type||!s||s.type!=="NUMBER"||!Y.test(s.value))return null;let c=[e,n,m,l,s];if(!fe(c))return null;let p=t();if(p!=="auto"){let a=Te(e.value,m.value,s.value,p);return a===null?null:P(a.day,a.month,a.year,c,`datetime:date-literal:${p.toLowerCase()}`)}if(n.type==="SLASH"){if(!d.test(e.value)||!d.test(m.value))return null;let a=b(s.value);return a===null?null:P(Number(e.value),Number(m.value),a,c,"datetime:date-literal:european")}if(e.value.length===4)return !d.test(m.value)||!d.test(s.value)?null:P(Number(s.value),Number(m.value),Number(e.value),c,"datetime:date-literal:iso");if(!d.test(e.value)||!d.test(m.value))return null;let y=b(s.value);return y===null?null:P(Number(m.value),Number(e.value),y,c,"datetime:date-literal:us")}}}exports.a=le;exports.b=se;exports.c=H;exports.d=Eo;exports.e=Ao;exports.f=D;exports.g=P;exports.h=Mo;//# sourceMappingURL=chunk-HDGARCI2.cjs.map
2
- //# sourceMappingURL=chunk-HDGARCI2.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/packages/symbolic/parselets/ExpandParselet.ts","../src/packages/symbolic/parselets/FactorParselet.ts","../src/packages/symbolic/parselets/VariableArgument.ts","../src/packages/symbolic/parselets/SolveParselet.ts","../src/packages/symbolic/parselets/DerParselet.ts","../src/packages/symbolic/parselets/IntegralParselet.ts","../src/packages/symbolic/parselets/TaylorParselet.ts","../src/packages/symbolic/parselets/JacobianParselet.ts","../src/packages/symbolic/parselets/ImaginaryParselet.ts","../src/packages/symbolic/parselets/ConjParselet.ts","../src/packages/symbolic/parselets/ReParselet.ts","../src/packages/symbolic/parselets/ImParselet.ts","../src/packages/symbolic/parselets/CancelParselet.ts","../src/packages/symbolic/parselets/ApartParselet.ts","../src/packages/symbolic/normalizer/ImaginaryLiteralNormalizerRule.ts","../src/packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts","../src/packages/symbolic/SymbolicPackage.ts","../src/packages/datetime/Iso8601.ts","../src/packages/datetime/normalizer/DateLiteralNormalizerRule.ts"],"names":["ExpandParselet","parser","_token","builder","BindingPower","FactorParselet","readVariableName","verb","token","ErrorFactory","emitVariableName","name","parseBoundExpression","inner","BytecodeBuilder","program","emitBoundExpression","index","SolveParselet","left","right","variable","DerParselet","expression","IntegralParselet","TaylorParselet","JacobianParselet","count","ImaginaryParselet","_parser","ConjParselet","ReParselet","ImParselet","CancelParselet","ApartParselet","imaginaryLiteralNormalizerRule","priority","tokens","pos","number","suffix","LexerToken","tokenTypeId","SYMBOLIC_WORD_TO_TOKEN_TYPE","symbolicCallNormalizerRule","tokenType","SYMBOLIC_FUNCTIONS","SYMBOLIC_PACKAGE","SYMBOLIC_TOKEN_TYPES","fn","containsSymbolicCall","ISO8601_PATTERN","parseIso8601","s","trimmed","ms","formatIso8601Local","epochMs","d","pad","n","year","month","day","hours","minutes","seconds","offsetMinutesTotal","sign","absOffset","offsetHours","offsetMinutes","MS_TIMESTAMP_THRESHOLD","unixTimestampToEpochMs","DATETIME_LITERAL_TYPE","DATETIME_LITERAL_TYPE_ID","PLAIN_INTEGER","DOT_DAY_MONTH","DOT_LEADING_YEAR","DAY_OR_MONTH","writtenAsOneRun","i","resolveYear","digits","yy","buildDateToken","sourceTokens","ruleName","date","first","text","t","fusedToken","ISO_TIMESTAMP","ISO_TOKEN_TYPES","ISO_MAX_TOKENS","fuseIsoTimestamp","runEnd","window","next","matched","consumed","covered","resolveOrderedGroups","g0","g1","g2","order","dateLiteralNormalizerRule","getInputOrder","t0","t1","dayText","monthText","match","timestamp","sep1","sep2","t2","resolved"],"mappings":"yNAoBO,IAAMA,CAAAA,CAAN,KAA+C,CAA/C,WAAA,EAAA,CACN,IAAA,CAAS,QAAA,CAAW,WAAA,CAEpB,KAAA,CAAMC,CAAAA,CAAgBC,CAAAA,CAAeC,CAAAA,CAAgC,CACpEF,EAA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K,CAAA,CAAG,OAAO,IAAA,CACzE,IAAMlD,CAAAA,CAAOqB,CAAAA,CAAYoC,CAAAA,CAAG,KAAK,CAAA,CACjC,OAAIzD,IAAS,IAAA,CAAa,IAAA,CACnBwB,CAAAA,CAAe,MAAA,CAAOyB,CAAAA,CAAG,KAAK,CAAA,CAAG,MAAA,CAAOC,EAAG,KAAK,CAAA,CAAGlD,CAAAA,CAAMyB,CAAAA,CAAc,gCAAgC,CAChH,CAGA,GAAIwB,EAAG,KAAA,CAAM,MAAA,GAAW,CAAA,CACtB,OAAI,CAAC/B,CAAAA,CAAa,IAAA,CAAKgC,CAAAA,CAAG,KAAK,CAAA,EAAK,CAAChC,CAAAA,CAAa,IAAA,CAAKuC,CAAAA,CAAG,KAAK,CAAA,CAAU,IAAA,CAElEjC,EAAe,MAAA,CAAOiC,CAAAA,CAAG,KAAK,CAAA,CAAG,MAAA,CAAOP,CAAAA,CAAG,KAAK,CAAA,CAAG,OAAOD,CAAAA,CAAG,KAAK,CAAA,CAAGxB,CAAAA,CAAc,2BAA2B,CAAA,CAEvH,GAAI,CAACP,EAAa,IAAA,CAAK+B,CAAAA,CAAG,KAAK,CAAA,EAAK,CAAC/B,CAAAA,CAAa,IAAA,CAAKgC,CAAAA,CAAG,KAAK,CAAA,CAAG,OAAO,IAAA,CACzE,IAAMlD,CAAAA,CAAOqB,CAAAA,CAAYoC,CAAAA,CAAG,KAAK,EACjC,OAAIzD,CAAAA,GAAS,IAAA,CAAa,IAAA,CAEnBwB,CAAAA,CAAe,MAAA,CAAO0B,CAAAA,CAAG,KAAK,EAAG,MAAA,CAAOD,CAAAA,CAAG,KAAK,CAAA,CAAGjD,CAAAA,CAAMyB,CAAAA,CAAc,0BAA0B,CAC1G,CACF,CACF","file":"chunk-HDGARCI2.cjs","sourcesContent":["import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_EXPAND } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `expand(expr)`, multiplying out every product and power.\n *\n * A dedicated parselet rather than a `builtinNameToIndex` entry reached through\n * the ordinary `FunctionCallParselet`, because that route needs the lexer to\n * emit `FUNC` for the word, which means a `keywordMap` entry, which would stop\n * `expand` working as an ordinary variable name. See\n * `normalizer/SymbolicCallNormalizerRule.ts`.\n *\n * The emitted bytecode is an ordinary `CALL_BUILTIN`, so no new opcode and no\n * new VM dispatch arm is involved.\n */\nexport class ExpandParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_EXPAND);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_FACTOR } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `factor(expr)`, writing a polynomial as a product of irreducible factors over the rationals.\n *\n * A dedicated parselet rather than a `builtinNameToIndex` entry reached through\n * the ordinary `FunctionCallParselet`, because that route needs the lexer to\n * emit `FUNC` for the word, which means a `keywordMap` entry, which would stop\n * `expand` working as an ordinary variable name. See\n * `normalizer/SymbolicCallNormalizerRule.ts`.\n *\n * The emitted bytecode is an ordinary `CALL_BUILTIN`, so no new opcode and no\n * new VM dispatch arm is involved.\n */\nexport class FactorParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_FACTOR);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { Parser } from \"@solve-js/parser/Parser\";\nimport { BytecodeBuilder, type BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Reads a bare variable name argument and returns it, consuming the token.\n *\n * Shared by every algebra verb that takes \"which unknown\" as an argument.\n * Compiling the name as an ordinary variable read would require it to already\n * have a value, which is precisely what differentiating or solving with respect\n * to it says it does not.\n *\n * Requiring `IDENT` or `UNIT` here gives the same reserved-word protection\n * `VariableParselet` relies on: a keyword always lexes as its own token type,\n * so it can never reach this position and be taken for a variable name.\n *\n * @param parser - The parser, positioned at the name.\n * @param verb - The calling verb's name, for the error message.\n * @returns The name as written.\n * @throws {EngineError} `SYMBOLIC_REQUIRES_VARIABLE_NAME` when the next token is\n * not a bare name.\n */\nexport function readVariableName(parser: Parser, verb: string): string {\n\tconst token = parser.peek();\n\tif (!token || (token.type !== \"IDENT\" && token.type !== \"UNIT\")) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n\t\t\t`${verb} needs the name of an unknown here, as in ${verb}(x^2, x).`,\n\t\t\t{ found: token?.type ?? \"end of input\" },\n\t\t);\n\t}\n\tparser.consume();\n\treturn token.value;\n}\n\n/** Emits an already-read unknown's name as the String argument the algebra builtins read it as. */\nexport function emitVariableName(builder: BytecodeBuilder, name: string): void {\n\tbuilder.emitOpcode(OpCode.PUSH_STRING);\n\tbuilder.emitString(name);\n}\n\n/**\n * Parses an algebra verb's expression argument into its own independent\n * program, rather than emitting it inline.\n *\n * The verb names its unknown AFTER the expression (`der(x^2, x)`), so the\n * expression has to be held rather than emitted: only once the name is known\n * can it be paired with {@link emitBoundExpression}, which is what makes the\n * name shadow any document value it happens to share. Compiled into an\n * isolated builder exactly like a user-defined function body or a map/reduce\n * transform, and `parseExpression` leaves `parser.builder` pointing at the\n * isolated one with no automatic restore, so the caller's builder is put back\n * before returning.\n *\n * @param parser - The parser, positioned at the start of the expression.\n * @param builder - The builder to restore afterwards.\n * @param verb - The calling verb's name, for the error message.\n * @returns The compiled expression, to be handed to {@link emitBoundExpression}.\n */\nexport function parseBoundExpression(parser: Parser, builder: BytecodeBuilder, verb: string): BytecodeProgram {\n\tconst inner = new BytecodeBuilder(builder.pluginIndexMap);\n\tparser.parseExpression(BindingPower.Lowest, inner);\n\tparser.setBuilder(builder);\n\tconst program = inner.build();\n\tif (program.hasAsync) {\n\t\t// Same v1 restriction every other deferred body carries (user-defined\n\t\t// functions, map/reduce transforms): a reentrant execution cannot\n\t\t// suspend and resume the outer expression around an async result.\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS\",\n\t\t\t`${verb}'s expression must be synchronous (no weather/stocks/currency calls).`,\n\t\t);\n\t}\n\treturn program;\n}\n\n/**\n * Emits a held expression so that it evaluates with `name` bound to itself.\n *\n * This is what makes `der(x^2, x)` mean the derivative of a square rather than\n * the derivative of a constant on a page that also says `:x = 5`. Naming `x` as\n * the verb's argument declares it bound, so within the expression it is an\n * unknown and nothing else, exactly the way a function's parameter shadows a\n * document variable of the same name inside its body. Before this, the\n * expression was compiled inline and its `x` was an ordinary variable read, so\n * the verb received 25 and answered 0 with no indication that it had not been\n * asked the question the user wrote.\n *\n * @param builder - The builder to emit into.\n * @param program - The expression, from {@link parseBoundExpression}.\n * @param name - The unknown the verb named, bound for the expression's evaluation.\n */\nexport function emitBoundExpression(builder: BytecodeBuilder, program: BytecodeProgram, name: string): void {\n\tconst index = builder.emitAnonymousBody([name], program);\n\tbuilder.emitOpcode(OpCode.BIND_UNKNOWN);\n\tbuilder.emitIndex(index);\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { SYMBOLIC_BUILTIN_SOLVE } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `solve(equation, variable)`, for example `solve(x^2-4=0, x)`.\n *\n * Two things here cannot go through the ordinary function-call grammar, which\n * is why this is a hand-written parselet.\n *\n * The first argument contains a bare `=`, which no infix parselet consumes, so\n * an ordinary argument list would fail to parse it. This reads the two sides\n * separately and lets a missing right-hand side default to zero, so\n * `solve(x^2-4, x)` means the same as `solve(x^2-4=0, x)`.\n *\n * The second argument is a *name*, not a value. Compiling it as a `LOAD_VAR`\n * would demand that the variable already exist, which is exactly what solving\n * for it says it does not. Emitting it as a `PUSH_STRING` instead means the\n * builtin receives a plain String value and the VM needs no change at all.\n *\n * Both sides of the equation are held until that name has been read, so each\n * evaluates with the unknown bound to itself rather than to whatever value the\n * document may already have given it. See {@link emitBoundExpression}: with\n * `:x = 5` above it, `solve(x^2-4=0, x)` was solving `21 = 0` and reporting,\n * accurately for the question it was asked and uselessly for the one written,\n * that there is no solution.\n */\nexport class SolveParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst left = parseBoundExpression(parser, builder, \"solve\");\n\t\tconst right = parser.match(\"EQUALS\") ? parseBoundExpression(parser, builder, \"solve\") : null;\n\n\t\tparser.consume(\"COMMA\");\n\t\t// Requiring IDENT or UNIT here is the same protection VariableParselet\n\t\t// relies on: a reserved word always lexes as its own token type, so it\n\t\t// can never reach this position and be mistaken for a variable name.\n\t\tconst variable = parser.peek();\n\t\tif (!variable || (variable.type !== \"IDENT\" && variable.type !== \"UNIT\")) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"SOLVE_REQUIRES_VARIABLE_NAME\",\n\t\t\t\t`solve's second argument must be the name of the unknown to solve for, as in solve(x^2-4=0, x).`,\n\t\t\t\t{ found: variable?.type ?? \"end of input\" },\n\t\t\t);\n\t\t}\n\t\tparser.consume();\n\n\t\temitBoundExpression(builder, left, variable.value);\n\t\tif (right) {\n\t\t\temitBoundExpression(builder, right, variable.value);\n\t\t} else {\n\t\t\t// No `=` written, so the equation is \"this expression equals zero\".\n\t\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\t\tbuilder.emitNumber(0);\n\t\t}\n\t\temitVariableName(builder, variable.value);\n\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_SOLVE);\n\t\tbuilder.emitIndex(3);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_DER } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `der(expr, variable)` and `der(expr, variable, order)`, the symbolic\n * derivative. `derivative` is accepted as the same thing.\n *\n * The variable is emitted as a string rather than compiled as a variable read,\n * for the reason given in {@link readVariableName}, and `expr` is held until\n * that name is known so it can be evaluated with the name bound. See\n * {@link emitBoundExpression}.\n */\nexport class DerParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"der\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"der\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\n\t\t// The order is optional and defaults to a first derivative.\n\t\tif (parser.match(\"COMMA\")) {\n\t\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\t} else {\n\t\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\t\tbuilder.emitNumber(1);\n\t\t}\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_DER);\n\t\tbuilder.emitIndex(3);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { SYMBOLIC_BUILTIN_INTEGRAL } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `integral(expr, variable)`, the indefinite integral, without a constant of\n * integration. `expr` is held until the variable is read so that the named\n * unknown shadows any document value of the same name, see\n * {@link emitBoundExpression}.\n */\nexport class IntegralParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"integral\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"integral\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_INTEGRAL);\n\t\tbuilder.emitIndex(2);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_TAYLOR } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `taylor(expr, variable = point, degree)`, matching Calca's own spelling.\n *\n * The `variable = point` argument is why this needs a hand-written parselet:\n * `EQUALS` has no infix parselet, so an ordinary argument list cannot parse it.\n * Reading the name and the point separately also means the name never has to\n * exist as a variable, and `expr` is held until the name is known so that the\n * name shadows any document value it shares (see {@link emitBoundExpression}).\n * The expansion point is an ordinary value expression and is not shadowed: it\n * is a number, not the unknown.\n */\nexport class TaylorParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"taylor\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"taylor\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\t\tparser.consume(\"EQUALS\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"COMMA\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_TAYLOR);\n\t\tbuilder.emitIndex(4);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_JACOBIAN } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `jacobian(f1, f2, ...)`, the matrix of partial derivatives.\n *\n * Variadic, and the variables are not named: they are taken from the union of\n * the functions' own unknowns, sorted, which is what Calca does. Row `i` is the\n * gradient of the `i`-th function.\n */\nexport class JacobianParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tlet count = 0;\n\t\tdo {\n\t\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\t\tcount++;\n\t\t} while (parser.match(\"COMMA\"));\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_JACOBIAN);\n\t\tbuilder.emitIndex(count);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { SYMBOLIC_BUILTIN_IMAGINARY } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * An imaginary literal, `3i`, fused by\n * `normalizer/ImaginaryLiteralNormalizerRule.ts`.\n *\n * The token carries the numeric part as its value; this pushes that number and\n * lets the builtin turn it into an exact imaginary value. Going through a\n * builtin rather than a dedicated opcode keeps the VM dispatch table untouched,\n * the same choice every other algebra verb made.\n */\nexport class ImaginaryParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(_parser: Parser, token: Token, builder: BytecodeBuilder): void {\n\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\tbuilder.emitNumber(Number(token.value));\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_IMAGINARY);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_CONJ } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `conj(z)`, the complex conjugate.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ConjParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_CONJ);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_RE } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `re(z)`, the real part of a complex value.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ReParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_RE);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_IM } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `im(z)`, the imaginary part of a complex value.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ImParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_IM);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_CANCEL } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `cancel(expr)`, reducing a quotient of polynomials to lowest terms.\n *\n * The simplifier already cancels a common factor automatically; this is the\n * explicit form, for when the intent is to reduce a fraction rather than to\n * evaluate something that happens to contain one.\n */\nexport class CancelParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_CANCEL);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_APART } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `apart(expr)`, splitting a rational function into partial fractions.\n *\n * The inverse of putting a sum of fractions over a common denominator, and the\n * step that makes a rational function integrable.\n */\nexport class ApartParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_APART);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\n\n/**\n * Fuses `3i` into a single imaginary literal, but only when the `i` is written\n * flush against the number.\n *\n * `i` is not claimed as a keyword, and deliberately so. It is one of the most\n * common variable names there is, and this engine's whole trigger-word policy\n * exists to avoid taking words a person would reasonably assign to. `:i = 5`\n * has to keep working, and after this rule it does: the rule only fires on a\n * number immediately followed by the letter, which is the same shape the\n * magnitude suffixes use, and `2.5k` set that precedent.\n *\n * Adjacency is checked by source offset rather than by token order, so `3i` is\n * an imaginary literal while `3 i` and `3 * i` are a number multiplied by a\n * variable named `i`. That is the distinction that keeps both readings\n * available, and it is the reason a bare `i` on its own is still a variable.\n * Write `1i` for the imaginary unit alone.\n */\nexport function imaginaryLiteralNormalizerRule(priority = 75): NormalizerRule {\n\treturn {\n\t\tname: \"symbolic:imaginary-literal\",\n\t\tpriority,\n\t\tmatch(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t\tconst number = tokens[pos];\n\t\t\tif (!number || number.type !== \"NUMBER\") return null;\n\n\t\t\tconst suffix = tokens[pos + 1];\n\t\t\tif (!suffix || suffix.type !== \"IDENT\" || suffix.value !== \"i\") return null;\n\n\t\t\t// Flush against the number, with no space between them.\n\t\t\tif (suffix.offset !== number.offset + number.value.length) return null;\n\n\t\t\t// A following `(` would make this a call, as in `3i(x)`, which is not a\n\t\t\t// shape this claims.\n\t\t\tif (tokens[pos + 2]?.type === \"LPAREN\") return null;\n\n\t\t\treturn {\n\t\t\t\tconsumed: 2,\n\t\t\t\treplacement: [\n\t\t\t\t\tnew LexerToken(\n\t\t\t\t\t\t\"IMAGINARY\",\n\t\t\t\t\t\ttokenTypeId(\"IMAGINARY\"),\n\t\t\t\t\t\tnumber.value,\n\t\t\t\t\t\tnumber.value,\n\t\t\t\t\t\tnumber.offset,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tnumber.line,\n\t\t\t\t\t\tnumber.col,\n\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\truleName: \"symbolic:imaginary-literal\",\n\t\t\t};\n\t\t},\n\t};\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\n\n/**\n * The algebra verbs, mapped to the token type each becomes when it is being\n * called.\n *\n * Kept in one place so {@link SYMBOLIC_FUNCTIONS} in `SymbolicPackage.ts` and\n * this rule cannot disagree about which words the package claims.\n */\nexport const SYMBOLIC_WORD_TO_TOKEN_TYPE: Readonly<Record<string, string>> = {\n\texpand: \"EXPAND_FN\",\n\tfactor: \"FACTOR_FN\",\n\tsolve: \"SOLVE_FN\",\n\tder: \"DER_FN\",\n\tderivative: \"DER_FN\",\n\tintegral: \"INTEGRAL_FN\",\n\ttaylor: \"TAYLOR_FN\",\n\tjacobian: \"JACOBIAN_FN\",\n\tconj: \"CONJ_FN\",\n\tre: \"RE_FN\",\n\tim: \"IM_FN\",\n\tcancel: \"CANCEL_FN\",\n\tapart: \"APART_FN\",\n};\n\n/**\n * Fuses an algebra verb into its own token type, but only when the bare word is\n * immediately followed by `(`.\n *\n * None of these words may be a plain `keywordMap` entry, and the reason is\n * concrete rather than stylistic. A `keywordMap` entry makes the lexer emit a\n * reserved token type everywhere the word appears, which would break\n * `:factor = 1.5` and `:solve = 2` as ordinary variable names. `solve` is also\n * the product's own name and `factor` is an everyday English noun, so both are\n * words a user will reasonably assign to.\n *\n * Mirrors `packages/mapreduce/normalizer/MapReduceCallNormalizerRule.ts`, which\n * exists for exactly this reason for `map`/`reduce`/`sum`/`prod`.\n *\n * @param priority - Rule ordering within the normalizer, defaulting to the same\n * band the map/reduce call rule uses.\n * @returns The normalizer rule.\n */\nexport function symbolicCallNormalizerRule(priority = 80): NormalizerRule {\n\treturn {\n\t\tname: \"symbolic:call\",\n\t\tpriority,\n\t\tstartTokenTypes: [\"IDENT\"],\n\t\tmatch(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t\tconst token = tokens[pos];\n\t\t\tif (!token || token.type !== \"IDENT\") return null;\n\t\t\tconst tokenType = SYMBOLIC_WORD_TO_TOKEN_TYPE[token.value.toLowerCase()];\n\t\t\tif (!tokenType) return null;\n\t\t\tif (tokens[pos + 1]?.type !== \"LPAREN\") return null;\n\n\t\t\treturn {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [\n\t\t\t\t\tnew LexerToken(tokenType, tokenTypeId(tokenType), token.value, token.value, token.offset, 0, token.line, token.col),\n\t\t\t\t],\n\t\t\t\truleName: \"symbolic:call\",\n\t\t\t};\n\t\t},\n\t};\n}\n","import type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { ExpandParselet } from \"./parselets/ExpandParselet\";\nimport { FactorParselet } from \"./parselets/FactorParselet\";\nimport { SolveParselet } from \"./parselets/SolveParselet\";\nimport { DerParselet } from \"./parselets/DerParselet\";\nimport { IntegralParselet } from \"./parselets/IntegralParselet\";\nimport { TaylorParselet } from \"./parselets/TaylorParselet\";\nimport { JacobianParselet } from \"./parselets/JacobianParselet\";\nimport { ImaginaryParselet } from \"./parselets/ImaginaryParselet\";\nimport { ConjParselet } from \"./parselets/ConjParselet\";\nimport { ReParselet } from \"./parselets/ReParselet\";\nimport { ImParselet } from \"./parselets/ImParselet\";\nimport { CancelParselet } from \"./parselets/CancelParselet\";\nimport { ApartParselet } from \"./parselets/ApartParselet\";\nimport { imaginaryLiteralNormalizerRule } from \"./normalizer/ImaginaryLiteralNormalizerRule\";\nimport { symbolicCallNormalizerRule } from \"./normalizer/SymbolicCallNormalizerRule\";\nimport {\n\tSYMBOLIC_BUILTIN_EXPAND,\n\tSYMBOLIC_BUILTIN_FACTOR,\n\tSYMBOLIC_BUILTIN_SOLVE,\n\tSYMBOLIC_BUILTIN_DER,\n\tSYMBOLIC_BUILTIN_INTEGRAL,\n\tSYMBOLIC_BUILTIN_TAYLOR,\n\tSYMBOLIC_BUILTIN_JACOBIAN,\n\tSYMBOLIC_BUILTIN_CONJ,\n\tSYMBOLIC_BUILTIN_RE,\n\tSYMBOLIC_BUILTIN_IM,\n\tSYMBOLIC_BUILTIN_CANCEL,\n\tSYMBOLIC_BUILTIN_APART,\n} from \"./SymbolicBuiltinIndex\";\n\n/**\n * One algebra verb's whole surface, in a single row.\n *\n * Everything a verb needs in order to work is listed here rather than being\n * spread across the normalizer, the parselet registry, the builtin table and\n * the docs, so `__tests__/engine/SymbolicSurfaceParity.spec.ts` can check the\n * pieces actually agree. Shipping a verb whose index has no implementation, or\n * whose parselet is registered under a token type the normalizer never mints,\n * then becomes a failing test rather than a silent dead feature.\n */\nexport interface SymbolicFunctionSurface {\n\t/** The bare word a user types. */\n\treadonly word: string;\n\t/** The token type the normalizer fuses it into when it is followed by `(`. */\n\treadonly tokenType: string;\n\t/** The `CALL_BUILTIN` index its parselet emits. */\n\treadonly builtinIndex: number;\n\t/** A working example, executed by the parity spec through every public entry point. */\n\treadonly example: string;\n\t/** That example's expected formatted result. */\n\treadonly expected: string;\n\t/** The documentation page under `docs/src/content/docs/syntax/` that must show it. */\n\treadonly docPage: string;\n}\n\n/** Every algebra verb this package registers. */\nexport const SYMBOLIC_FUNCTIONS: readonly SymbolicFunctionSurface[] = [\n\t{\n\t\tword: \"expand\",\n\t\ttokenType: \"EXPAND_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_EXPAND,\n\t\texample: \"expand((x+1)*(x+2))\",\n\t\texpected: \"x^2+3x+2\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"factor\",\n\t\ttokenType: \"FACTOR_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_FACTOR,\n\t\texample: \"factor(x^2-4)\",\n\t\texpected: \"(x-2)*(x+2)\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"solve\",\n\t\ttokenType: \"SOLVE_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_SOLVE,\n\t\texample: \"solve(x^2-4=0, x)\",\n\t\texpected: \"= [-2, 2]\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"der\",\n\t\ttokenType: \"DER_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_DER,\n\t\texample: \"der(x^3, x)\",\n\t\texpected: \"3x^2\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"integral\",\n\t\ttokenType: \"INTEGRAL_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_INTEGRAL,\n\t\texample: \"integral(x^2, x)\",\n\t\texpected: \"1/3x^3\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"taylor\",\n\t\ttokenType: \"TAYLOR_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_TAYLOR,\n\t\texample: \"taylor(exp(x), x=0, 3)\",\n\t\texpected: \"1/6x^3+0.5x^2+x+1\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"jacobian\",\n\t\ttokenType: \"JACOBIAN_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_JACOBIAN,\n\t\texample: \"jacobian(x*y, x+y)\",\n\t\texpected: \"= [y, x; 1, 1]\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"conj\",\n\t\ttokenType: \"CONJ_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_CONJ,\n\t\texample: \"conj(2+3i)\",\n\t\texpected: \"2-3i\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"re\",\n\t\ttokenType: \"RE_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_RE,\n\t\texample: \"re(2+3i)\",\n\t\texpected: \"= 2\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"im\",\n\t\ttokenType: \"IM_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_IM,\n\t\texample: \"im(2+3i)\",\n\t\texpected: \"= 3\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"cancel\",\n\t\ttokenType: \"CANCEL_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_CANCEL,\n\t\texample: \"cancel((x^2-1)/(x-1))\",\n\t\texpected: \"x+1\",\n\t\tdocPage: \"algebra.md\",\n\t},\n\t{\n\t\tword: \"apart\",\n\t\ttokenType: \"APART_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_APART,\n\t\texample: \"apart((3x+5)/(x^2-1))\",\n\t\texpected: \"4/(x-1)-1/(x+1)\",\n\t\tdocPage: \"algebra.md\",\n\t},\n];\n\n/**\n * Symbolic algebra verbs: multiplying out, and (in later phases) factoring,\n * solving and calculus.\n *\n * The algebra itself lives in `symbolic/`, which is pure mathematics over the\n * expression tree. This package is only the grammar surface: which words become\n * which tokens, and which parselet emits which builtin call.\n *\n * None of these words is a bare `keywordMap` entry. See\n * `normalizer/SymbolicCallNormalizerRule.ts` for why that matters.\n */\nexport const SYMBOLIC_PACKAGE: IEnginePackage = {\n\tname: \"solve-symbolic\",\n\tnormalizerRules: [symbolicCallNormalizerRule(), imaginaryLiteralNormalizerRule()],\n\tprefixParselets: {\n\t\tEXPAND_FN: new ExpandParselet(),\n\t\tFACTOR_FN: new FactorParselet(),\n\t\tSOLVE_FN: new SolveParselet(),\n\t\tDER_FN: new DerParselet(),\n\t\tINTEGRAL_FN: new IntegralParselet(),\n\t\tTAYLOR_FN: new TaylorParselet(),\n\t\tJACOBIAN_FN: new JacobianParselet(),\n\t\tIMAGINARY: new ImaginaryParselet(),\n\t\tCONJ_FN: new ConjParselet(),\n\t\tRE_FN: new ReParselet(),\n\t\tIM_FN: new ImParselet(),\n\t\tCANCEL_FN: new CancelParselet(),\n\t\tAPART_FN: new ApartParselet(),\n\t},\n\ttokenCategories: {\n\t\tEXPAND_FN: \"keyword\",\n\t\tFACTOR_FN: \"keyword\",\n\t\tSOLVE_FN: \"keyword\",\n\t\tDER_FN: \"keyword\",\n\t\tINTEGRAL_FN: \"keyword\",\n\t\tTAYLOR_FN: \"keyword\",\n\t\tJACOBIAN_FN: \"keyword\",\n\t\tIMAGINARY: \"number\",\n\t\tCONJ_FN: \"keyword\",\n\t\tRE_FN: \"keyword\",\n\t\tIM_FN: \"keyword\",\n\t\tCANCEL_FN: \"keyword\",\n\t\tAPART_FN: \"keyword\",\n\t},\n};\n\n/** The token types the algebra verbs fuse into, for the engine's own \"is this line symbolic\" check. */\nconst SYMBOLIC_TOKEN_TYPES: ReadonlySet<string> = new Set(SYMBOLIC_FUNCTIONS.map(fn => fn.tokenType));\n\n/**\n * Whether a normalized token list calls an algebra verb.\n *\n * `engine/ExpressionEngine.ts` uses this to evaluate such a line in\n * symbolic-tolerant mode without requiring a trailing `=>`, since asking to\n * expand or factor something is already a statement that its unknowns are meant\n * to stay unknown.\n *\n * @param tokens - The normalized tokens for one line.\n * @returns True when any token is an algebra verb.\n */\nexport function containsSymbolicCall(tokens: readonly { type: string }[]): boolean {\n\treturn tokens.some(token => SYMBOLIC_TOKEN_TYPES.has(token.type));\n}\n","/**\n * ISO8601 string <-> epoch-ms helpers backing the datetime package's\n * `<ISO8601 string> to date` and `<date/time> as iso8601` features.\n *\n * SCOPE, revised in 1.0.0: {@link parseIso8601} is now reached by BOTH input\n * shapes. A quoted string literal (`\"2019-04-01T15:30:00+11:00\" to date`)\n * always came here; the bare, unquoted form now does too, fused into one\n * DATETIME_LITERAL by `normalizer/DateLiteralNormalizerRule.ts` before the\n * parser sees it.\n *\n * This file used to record that the bare form was out of scope because it is\n * ambiguous with arithmetic (`2019 - 04 - 01` reads as two subtractions) and\n * would need a dedicated lexer change. The date half of that ambiguity was\n * already settled by the normalizer rule, and the differential run against\n * 1.0.0-beta.6 showed what leaving the other half cost: a bare\n * `2019-04-01T15:30:00+11:00` read its `+11:00` as a clock time being ADDED to\n * the date, and answered TODAY at 11:00. Not the instant, not an error, and\n * formatted as a date, which is the most convincing way to be wrong. The two\n * spellings now answer identically, which is the only defensible arrangement\n * when one of them was always right.\n */\n\n/**\n * Matches a (reasonably) well-formed ISO8601 date or date-time string:\n * `YYYY-MM-DD` optionally followed by `THH:MM[:SS[.fff]][Z|+HH:MM|-HH:MM]`.\n * Deliberately stricter than the native `Date` constructor's very lenient\n * parsing (which also accepts things like `\"April 1, 2019\"`), only a\n * string actually ISO8601-shaped is accepted here, so `\"not a date\" to\n * date` fails loudly instead of silently parsing as `Invalid Date` (or,\n * worse, something the native parser guesses at).\n */\nconst ISO8601_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/**\n * Parse an ISO8601-shaped string into epoch milliseconds.\n *\n * Delegates the actual parsing to the native `Date` constructor, which\n * fully implements the ISO8601 extended format (including \"Z\"/\"+HH:MM\"\n * offsets and a fractional-seconds component) per the ECMA-262 Date Time\n * String Format spec, no custom parsing logic needed, just a stricter\n * shape gate in front of it (see {@link ISO8601_PATTERN}'s doc comment).\n *\n * A date-only string (`\"2019-04-01\"`) parses as UTC midnight; a date-time\n * with no offset and no \"Z\" (`\"2019-04-01T15:30:00\"`) parses in the HOST\n * SYSTEM's local timezone, both are the native `Date` constructor's own\n * spec-mandated behavior, not something this function adds.\n *\n * @returns epoch ms, or `null` if `s` isn't ISO8601-shaped or doesn't\n * parse to a valid instant.\n */\nexport function parseIso8601(s: string): number | null {\n // A `ValueType.String` Value's `.value` used to retain its original\n // surrounding double-quotes, because `tokenizeString()` set the token's\n // value to the raw source slice and `OpCode.PUSH_STRING` pushed that\n // verbatim. It no longer does: the token's `value` is the payload and its\n // `text` is the quoted slice. The strip below stays because this function\n // is also reachable with text that came from somewhere other than a\n // literal, and stripping a pair that is not there is a no-op.\n let trimmed = s.trim();\n if (trimmed.length >= 2 && trimmed.startsWith('\"') && trimmed.endsWith('\"')) {\n trimmed = trimmed.slice(1, -1);\n }\n if (!ISO8601_PATTERN.test(trimmed)) return null;\n const ms = new Date(trimmed).getTime();\n return Number.isNaN(ms) ? null : ms;\n}\n\n/**\n * Format epoch milliseconds as an ISO8601 string with an explicit\n * `+HH:MM`/`-HH:MM` offset, e.g. `\"2019-04-01T15:30:00+11:00\"`.\n *\n * DESIGN NOTE: uses the HOST SYSTEM's local timezone offset for the\n * offset component. This engine's `Datetime` representation is a bare\n * epoch-ms number with no zone tag (see `packages/time/TimePackage.ts`'s\n * doc comment for the same limitation affecting timezone conversion), so\n * there is no per-expression timezone context to draw on otherwise, the\n * process's own local offset (`Date.getTimezoneOffset()`) is the only\n * notion of \"local\" available. No milliseconds component is emitted,\n * matching the precision of the task's own worked example.\n */\nexport function formatIso8601Local(epochMs: number): string {\n const d = new Date(epochMs);\n const pad = (n: number) => String(n).padStart(2, \"0\");\n\n const year = d.getFullYear();\n const month = pad(d.getMonth() + 1);\n const day = pad(d.getDate());\n const hours = pad(d.getHours());\n const minutes = pad(d.getMinutes());\n const seconds = pad(d.getSeconds());\n\n // getTimezoneOffset() is (UTC - local) in minutes, i.e. the SIGN is\n // inverted relative to a \"+HH:MM ahead of UTC\" display offset.\n const offsetMinutesTotal = -d.getTimezoneOffset();\n const sign = offsetMinutesTotal >= 0 ? \"+\" : \"-\";\n const absOffset = Math.abs(offsetMinutesTotal);\n const offsetHours = pad(Math.floor(absOffset / 60));\n const offsetMinutes = pad(absOffset % 60);\n\n return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}${sign}${offsetHours}:${offsetMinutes}`;\n}\n\n/**\n * Magnitude threshold distinguishing a millisecond Unix timestamp from a\n * second Unix timestamp: values at or above this are treated as\n * milliseconds, below it as seconds.\n *\n * Chosen so that \"now\" in EITHER unit sits comfortably on its own side:\n * seconds-since-epoch for the foreseeable future stays in the ~1.7-2.5\n * billion range (1e9-1e10-ish), nowhere near 1e12, while the SAME\n * instant in milliseconds is ~1000x larger, comfortably past 1e12\n * (e.g. \"2024-12-10\" is ~1.73e9 seconds or ~1.73e12 ms). 1e12 sits well\n * clear of both real-world ranges for at least the next few centuries of\n * second-timestamps, so this is a safe, simple magnitude gate rather than\n * a fragile exact boundary.\n */\nconst MS_TIMESTAMP_THRESHOLD = 1e12;\n\n/**\n * Interpret a bare numeric Unix timestamp as epoch milliseconds, applying\n * the magnitude-based seconds-vs-milliseconds disambiguation described by\n * {@link MS_TIMESTAMP_THRESHOLD}.\n */\nexport function unixTimestampToEpochMs(n: number): number {\n return Math.abs(n) >= MS_TIMESTAMP_THRESHOLD ? n : n * 1000;\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\nimport { parseIso8601 } from \"@solve-js/packages/datetime/Iso8601\";\nimport type { DateInputOrder } from \"@solve-js/constants/Configuration\";\n\n/**\n * Token type a fused date literal is rewritten to.\n *\n * One type covers every supported ordering, so the parselet handles the shape\n * rather than the locale.\n */\nexport const DATETIME_LITERAL_TYPE = \"DATETIME_LITERAL\";\nconst DATETIME_LITERAL_TYPE_ID = tokenTypeId(DATETIME_LITERAL_TYPE);\n\n/** A pure digit string, guards against fusing hex/scientific/bigint-suffixed NUMBER tokens. */\nconst PLAIN_INTEGER = /^\\d+$/;\n\n/** First NUMBER token of a dot-separated literal: the lexer's decimal scanner\n * merges \"DD.MM\" into one float-shaped token (see module doc below). */\nconst DOT_DAY_MONTH = /^\\d{1,2}\\.\\d{1,2}$/;\n\n/** Second NUMBER token of a dot-separated literal: the lexer re-enters\n * tokenizeNumber() AT the second dot, so the year keeps its leading dot. */\nconst DOT_LEADING_YEAR = /^\\.(\\d{2}|\\d{4})$/;\n\n/**\n * Day and month groups of a separator-separated literal, in any of the three\n * orderings below: one or two digits, padded or not.\n *\n * Deliberately NOT two digits exactly. Zero-padding is what ISO 8601 requires\n * of a serialized date, but it is not what people type: \"2024-5-3\" is an\n * ordinary way to write a date and has to keep working. The digit count is\n * still bounded because a group of three or more digits is not a date group at\n * all, and the calendar check in {@link buildDateToken} would not catch it on\n * its own (\"030\" reads back as day 30).\n *\n * What actually separates a date from the arithmetic it is spelled like is\n * adjacency, not padding. See {@link writtenAsOneRun}.\n */\nconst DAY_OR_MONTH = /^\\d{1,2}$/;\n\n/**\n * Whether every token in a run touches the next one in the source text, with\n * no whitespace anywhere between the first character and the last.\n *\n * This is the whole basis for telling a date literal apart from the\n * arithmetic it is spelled identically to. A date is written as one\n * uninterrupted run (\"2024-5-3\"); a subtraction chain is written with spaces\n * around its operators (\"2024 - 5 - 3\"). The lexer records that difference in\n * the token offsets and nowhere else, since the tokens themselves are the same\n * five either way:\n *\n * 2024-5-3 NUMBER@0 MINUS@4 NUMBER@5 MINUS@6 NUMBER@7\n * 2024 - 5 - 3 NUMBER@0 MINUS@5 NUMBER@7 MINUS@9 NUMBER@11\n *\n * The same technique, for the same reason, is what tells \"5k\" from \"5 k\" in\n * `arithmetic/normalizer/LargeNumberSuffixNormalizerRule.ts`.\n *\n * ## Why this replaced a zero-padding requirement on the ISO branch\n * The ISO branch briefly required its month and day groups to be padded to two\n * digits, which did stop \"2024 - 5 - 3\" being answered as \"Friday, May 3,\n * 2024\" but also stopped \"2024-5-3\" being a date at all. Padding was never the\n * real distinction, and the rule's own US branch is the proof: it has always\n * accepted unpadded groups, so \"1-1-2020\" and \"12-25-2023\" are both dates\n * today. Requiring padding on one branch of the two was therefore an\n * inconsistency between two spellings of one rule rather than a policy.\n *\n * The US branch's own guard is a 2-or-4-digit trailing year plus the calendar\n * check, and it is NOT safe against spaced arithmetic on its own: before this\n * check existed, \"12 - 25 - 2023\" answered Christmas 2023 instead of -2036,\n * and \"1 - 1 - 2020\" answered New Year's Day instead of -2020. Applying\n * adjacency to the whole run rather than to one branch fixes that at the same\n * time and leaves both branches resting on the same reason.\n *\n * ## Padded but spaced\n * \"2024 - 05 - 03\" is subtraction under this check, and that is the intended\n * reading. Nobody types the spaces when they mean the date, so the spacing is\n * the clearest signal available about which was meant, and the padding is not:\n * a person subtracting may well write \"05\" for the same reason they write\n * \"05\" anywhere else. Choosing the date there would mean no spelling of that\n * subtraction existed.\n *\n * `sourceEnd` is preferred over `text.length` where it is set, because a token\n * an earlier rule fused carries replacement text rather than source text and\n * only `sourceEnd` still describes the span it covers (see\n * `normalizer/TokenNormalizer.ts`'s `createFusedToken`).\n */\nfunction writtenAsOneRun(tokens: Token[]): boolean {\n for (let i = 0; i < tokens.length - 1; i++) {\n const token = tokens[i];\n const end = token.sourceEnd ?? token.offset + token.text.length;\n if (end !== tokens[i + 1].offset) return false;\n }\n return true;\n}\n\n/**\n * Resolves a year token's raw digit text to a 4-digit year.\n *\n * Accepts exactly 2 or 4 digits (matching the wiki's documented formats).\n * A 2-digit year is windowed using the common glibc `strptime(\"%y\")`\n * convention: 00-68 -> 2000-2068, 69-99 -> 1969-1999. Any other digit\n * count (1 or 3 digits) is not a valid year shape and returns null so the\n * caller can decline the match and fall back to ordinary arithmetic.\n */\nfunction resolveYear(digits: string): number | null {\n if (digits.length === 4) return Number(digits);\n if (digits.length === 2) {\n const yy = Number(digits);\n return yy <= 68 ? 2000 + yy : 1900 + yy;\n }\n return null;\n}\n\n/**\n * Converts a validated day/month/year triple into a fused DATETIME_LITERAL\n * token, or null if the triple isn't a real calendar date (e.g. \"30\" for\n * February), letting the caller fall back to treating the source tokens\n * as ordinary arithmetic instead of a date.\n */\nexport function buildDateToken(\n day: number,\n month: number,\n year: number,\n sourceTokens: Token[],\n ruleName: string,\n): NormalizerMatch | null {\n if (month < 1 || month > 12 || day < 1 || day > 31) return null;\n\n // Local midnight, consistent with formatDatetime()'s toLocaleString()\n // display and DATE_NOW's Date.now() epoch, both of which are local-time.\n const date = new Date(year, month - 1, day);\n // Reject calendar rollover (e.g. day=30 in February) rather than silently\n // normalizing to March 2, a rollover almost always means the tokens were\n // never a date to begin with (e.g. \"2-30-5\" as chained subtraction).\n if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {\n return null;\n }\n\n const first = sourceTokens[0];\n const text = sourceTokens.map((t) => t.value).join(\"\");\n const fusedToken = new LexerToken(\n DATETIME_LITERAL_TYPE,\n DATETIME_LITERAL_TYPE_ID,\n String(date.getTime()),\n text,\n first.offset,\n 0,\n first.line,\n first.col,\n );\n\n return { consumed: sourceTokens.length, replacement: [fusedToken], ruleName };\n}\n\n/**\n * A full ISO 8601 timestamp: an ISO date with a time of day, optionally\n * carrying a UTC offset or the `Z` that means one of zero.\n *\n * Anchored at the start and deliberately greedy about the offset, so\n * `...T15:30:00+11:00` matches through the offset rather than stopping at the\n * seconds and leaving `+11:00` behind as an addition. That is what the bare\n * form used to do: `2019-04-01T15:30:00+11:00` read the offset as a clock time\n * being ADDED to the date on its left, and answered today at 11:00. Both\n * halves of that were wrong and neither was visible, which is worse than the\n * bare form simply not being supported.\n *\n * The time of day is required. Without it this would match what the date-only\n * branches below already handle, and they carry the ambiguity rules\n * (adjacency, group shapes) that keep a subtraction chain a subtraction.\n *\n * Matched against reconstructed source text rather than token by token. The\n * lexer has no idea this is one literal, so it emits nine to fourteen tokens\n * for it with the shape depending on the spelling (`T15` arrives as an\n * identifier, `Z` as another, an offset as a PLUS or MINUS with two more\n * numbers), and enumerating those permutations in token patterns is how a\n * spelling gets missed.\n *\n * `T` and `Z` are uppercase only, matching `Iso8601.ts`'s own pattern, which is\n * what actually parses the match. Accepting a spelling here that the parser\n * then refuses would mean the bare form supported more shapes than the quoted\n * one, for no reason a reader could infer.\n */\nconst ISO_TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?/;\n\n/**\n * Token types a run of ISO 8601 timestamp text can lex into. Anything else\n * ends the run, so the reconstruction below can never reach across an operator\n * or a word that is not part of the literal.\n */\nconst ISO_TOKEN_TYPES = new Set([\"NUMBER\", \"MINUS\", \"PLUS\", \"COLON\", \"IDENT\"]);\n\n/**\n * How many tokens the longest supported spelling occupies. `2019-04-01T15:30:00.123+11:00`\n * is fourteen; the cap only bounds the walk, since the match itself decides\n * where the literal ends.\n */\nconst ISO_MAX_TOKENS = 16;\n\n/**\n * Fuses a bare (unquoted) ISO 8601 timestamp into one DATETIME_LITERAL.\n *\n * `Iso8601.ts` could always parse this shape, and still does the parsing here;\n * what it said could not be done without \"a much larger, dedicated lexer\n * change\" was recognising the bare form, on the grounds that it is ambiguous\n * with arithmetic. The date half of that ambiguity was settled by the rule this\n * helper sits inside (a date is written as one uninterrupted run, so\n * `2024 - 5 - 3` stays arithmetic), and the time half is not ambiguous at all:\n * no chain of subtractions contains a `T15:30`.\n *\n * Contiguity in the SOURCE is what makes that true, the same test\n * {@link writtenAsOneRun} applies to the date-only orderings. Every token has\n * to begin exactly where the previous one ended, so `2019-04-01 T15:30` with a\n * space in it, or `2019-04-01 + 11:00` with the offset written as an addition,\n * are left alone: the user who typed a space typed two things.\n *\n * A token an earlier normalizer rule already fused ends the run rather than\n * joining it. Its `text` is replacement text rather than source text (see\n * `normalizer/TokenNormalizer.ts`'s `createFusedToken`), so concatenating it\n * would reconstruct something the user never typed, and nothing that has\n * already been fused into a phrase is part of a timestamp anyway.\n *\n * @returns The fused match, or null when the tokens at `pos` are not a\n * timestamp, when the match would end mid-token, or when the shape is\n * ISO-like but names no real instant (`2019-04-01T25:00:00`).\n */\nfunction fuseIsoTimestamp(tokens: Token[], pos: number, ruleName: string): NormalizerMatch | null {\n const first = tokens[pos];\n if (first.sourceEnd !== undefined) return null;\n let text = first.text;\n let runEnd = first.offset + first.text.length;\n const window: Token[] = [first];\n for (let i = pos + 1; i < tokens.length && window.length < ISO_MAX_TOKENS; i++) {\n const next = tokens[i];\n if (next.sourceEnd !== undefined) break;\n if (next.offset !== runEnd || !ISO_TOKEN_TYPES.has(next.type)) break;\n text += next.text;\n runEnd = next.offset + next.text.length;\n window.push(next);\n }\n\n const matched = ISO_TIMESTAMP.exec(text);\n if (matched === null) return null;\n\n // The literal has to end where a token ends. A match that stopped halfway\n // through one would leave the parser holding a token whose text has already\n // been consumed, so decline and let the ordinary rules have it.\n let consumed = 0;\n let covered = 0;\n for (const token of window) {\n covered += token.text.length;\n consumed++;\n if (covered >= matched[0].length) break;\n }\n if (covered !== matched[0].length) return null;\n\n // The instant comes from the same parser the quoted form uses, so the two\n // spellings cannot drift apart: an offset means what it means there, and a\n // timestamp with no offset is local time, exactly as a bare date literal is\n // local midnight.\n const epochMs = parseIso8601(matched[0]);\n if (epochMs === null) return null;\n\n const fusedToken = new LexerToken(\n DATETIME_LITERAL_TYPE,\n DATETIME_LITERAL_TYPE_ID,\n String(epochMs),\n matched[0],\n first.offset,\n 0,\n first.line,\n first.col,\n first.offset + matched[0].length,\n );\n return { consumed, replacement: [fusedToken], ruleName };\n}\n\n/**\n * Maps the three numeric groups of a slash- or hyphen-separated literal to a\n * (day, month, year) triple under an explicit {@link DateInputOrder}, or null\n * when a group is the wrong shape for its role (a non-4-digit year in `YMD`, a\n * year group that is neither two nor four digits in `DMY`/`MDY`).\n *\n * Only reached when the host has fixed an order; `'auto'` keeps the historic\n * per-separator reading in the rule below and never calls this.\n */\nfunction resolveOrderedGroups(\n g0: string, g1: string, g2: string, order: Exclude<DateInputOrder, \"auto\">,\n): { day: number; month: number; year: number } | null {\n if (order === \"YMD\") {\n if (g0.length !== 4) return null;\n if (!DAY_OR_MONTH.test(g1) || !DAY_OR_MONTH.test(g2)) return null;\n return { year: Number(g0), month: Number(g1), day: Number(g2) };\n }\n // DMY and MDY: two 1-2 digit groups and a trailing 2- or 4-digit year.\n if (!DAY_OR_MONTH.test(g0) || !DAY_OR_MONTH.test(g1)) return null;\n const year = resolveYear(g2);\n if (year === null) return null;\n return order === \"DMY\"\n ? { day: Number(g0), month: Number(g1), year }\n : { day: Number(g1), month: Number(g0), year };\n}\n\n/**\n * NormalizerRule that fuses numeric date literals into a single\n * DATETIME_LITERAL token, per the documented \"Datetime Formats\":\n * - European: DD/MM/YYYY (5 tokens: NUMBER SLASH NUMBER SLASH NUMBER)\n * - US: MM-DD-YYYY (5 tokens: NUMBER MINUS NUMBER MINUS NUMBER)\n * - ISO 8601: YYYY-MM-DD (same 5-token shape as US, disambiguated by the\n * first group being exactly 4 digits)\n * - Dot: DD.MM.YYYY (2 tokens. See below)\n *\n * ## Why the dot format is a 2-token window, not 5\n * ExpressionLexer's tokenizeNumber() treats \".\" adjacent to digits on both\n * sides as a decimal point, not a separator. For \"25.12.2023\" the lexer\n * itself emits only two NUMBER tokens: \"25.12\" (day+month merged into one\n * float-shaped literal) and \".2023\" (the lexer re-enters number scanning\n * AT the second dot, so the year keeps a leading dot). There is no 5-token\n * NUMBER-DOT-NUMBER-DOT-NUMBER shape to match against, the fusion has to\n * happen post-hoc from that 2-token shape instead. This only works for the\n * literal typed with no internal whitespace (e.g. \"25.12.2023\"); a spaced\n * variant (\"25 .12 .2023\") produces three separate leading-dot tokens and\n * is intentionally not supported, out of scope for the documented format.\n *\n * ## Ambiguity with existing arithmetic\n * A date-shaped SLASH or MINUS chain (e.g. \"25/12/2023\" or \"12-25-2023\")\n * previously parsed as chained division/subtraction. This rule\n * deliberately reinterprets any such chain that resolves to a real\n * calendar date as a date literal instead, matching the documented\n * behavior. Chains that aren't valid dates (out-of-range day/month, a\n * February 30, a non-2/4-digit year) fall through unchanged.\n *\n * That reinterpretation only ever claims a chain written as one\n * uninterrupted run of characters. \"25/12/2023\" and \"12-25-2023\" are dates;\n * \"25 / 12 / 2023\" and \"12 - 25 - 2023\", written with the spaces an operator\n * normally gets, stay division and subtraction. {@link writtenAsOneRun}\n * carries the full reasoning, including why this is checked instead of\n * requiring an ISO date's zero-padding.\n *\n * ## Relationship to Iso8601.ts / DatePhrase.ts\n * This is the general-purpose \"bare numeric date literal\" implementation\n * those two files' doc comments referenced as landing on a sibling branch\n * (`feat/safety-limits-datetime-literals`), now ported here. It's\n * intentionally independent of both: `Iso8601.ts` only parses QUOTED\n * STRING literals (`\"2019-04-01...\" to date`), and the Stocks package's\n * `DatePhrase.ts` is a narrower, deliberately-diverging grammar (US-style\n * bare SLASH dates, 4-digit-year-only) scoped to stock-history queries\n * neither of those needed to change for this to land.\n */\nexport function dateLiteralNormalizerRule(\n getInputOrder: () => DateInputOrder = () => \"auto\",\n): NormalizerRule {\n return {\n name: \"datetime:date-literal\",\n priority: 70,\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n const t0 = tokens[pos];\n if (t0.type !== \"NUMBER\") return null;\n\n // ── Dot format: 2-token window (see module doc) ──────────────────\n if (DOT_DAY_MONTH.test(t0.value)) {\n const t1 = tokens[pos + 1];\n if (t1 && t1.type === \"NUMBER\" && DOT_LEADING_YEAR.test(t1.value)) {\n const [dayText, monthText] = t0.value.split(\".\");\n const year = resolveYear(t1.value.slice(1));\n if (year !== null) {\n const match = buildDateToken(\n Number(dayText), Number(monthText), year,\n [t0, t1], \"datetime:date-literal:dot\",\n );\n if (match) return match;\n }\n }\n return null;\n }\n\n // ── ISO 8601 timestamp: as many tokens as the spelling takes ─────\n // Tried before the date-only windows below, which would otherwise fuse\n // the date half of a timestamp and leave the time half to be read as\n // arithmetic. See fuseIsoTimestamp().\n if (t0.value.length === 4 && PLAIN_INTEGER.test(t0.value)) {\n const timestamp = fuseIsoTimestamp(tokens, pos, \"datetime:date-literal:iso-timestamp\");\n if (timestamp) return timestamp;\n }\n\n // ── Slash / minus format: 5-token window ─────────────────────────\n if (!PLAIN_INTEGER.test(t0.value)) return null;\n const sep1 = tokens[pos + 1];\n if (!sep1 || (sep1.type !== \"SLASH\" && sep1.type !== \"MINUS\")) return null;\n const t1 = tokens[pos + 2];\n const sep2 = tokens[pos + 3];\n const t2 = tokens[pos + 4];\n if (!t1 || t1.type !== \"NUMBER\" || !PLAIN_INTEGER.test(t1.value)) return null;\n if (!sep2 || sep2.type !== sep1.type) return null;\n if (!t2 || t2.type !== \"NUMBER\" || !PLAIN_INTEGER.test(t2.value)) return null;\n\n const sourceTokens = [t0, sep1, t1, sep2, t2];\n // The one check that separates every ordering below from the arithmetic\n // it is spelled identically to, and the only one that applies to all\n // three equally. See writtenAsOneRun.\n if (!writtenAsOneRun(sourceTokens)) return null;\n\n // A host-fixed order (DMY/MDY/YMD) reads slash and hyphen dates the same\n // way, so a US reader's `12/25/2023` and an ISO `2023/12/25` both parse.\n // `'auto'` falls through to the historic per-separator reading below.\n const order = getInputOrder();\n if (order !== \"auto\") {\n const resolved = resolveOrderedGroups(t0.value, t1.value, t2.value, order);\n if (resolved === null) return null;\n return buildDateToken(\n resolved.day, resolved.month, resolved.year, sourceTokens,\n `datetime:date-literal:${order.toLowerCase()}`,\n );\n }\n\n if (sep1.type === \"SLASH\") {\n // European: DD/MM/YYYY (always, no ISO-slash variant is documented)\n if (!DAY_OR_MONTH.test(t0.value) || !DAY_OR_MONTH.test(t1.value)) return null;\n const year = resolveYear(t2.value);\n if (year === null) return null;\n return buildDateToken(Number(t0.value), Number(t1.value), year, sourceTokens, \"datetime:date-literal:european\");\n }\n\n // MINUS: ISO (YYYY-MM-DD) if the first group is exactly 4 digits, else US (MM-DD-YYYY)\n if (t0.value.length === 4) {\n if (!DAY_OR_MONTH.test(t1.value) || !DAY_OR_MONTH.test(t2.value)) return null;\n // year=t0, month=t1, day=t2, buildDateToken takes (day, month, year)\n return buildDateToken(Number(t2.value), Number(t1.value), Number(t0.value), sourceTokens, \"datetime:date-literal:iso\");\n }\n if (!DAY_OR_MONTH.test(t0.value) || !DAY_OR_MONTH.test(t1.value)) return null;\n const year = resolveYear(t2.value);\n if (year === null) return null;\n // month=t0, day=t1, year=t2, buildDateToken takes (day, month, year)\n return buildDateToken(Number(t1.value), Number(t0.value), year, sourceTokens, \"datetime:date-literal:us\");\n },\n };\n}\n"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkHG4NPDN5_cjs=require('./chunk-HG4NPDN5.cjs'),chunkFVQWN5HZ_cjs=require('./chunk-FVQWN5HZ.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunkNAZ6PGLS_cjs=require('./chunk-NAZ6PGLS.cjs');var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",o){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r,this.pluginFunctionIndex=o;}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),o=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===o&&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 o=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:o,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 o=chunk5IJD5L3O_cjs.c(chunk5IJD5L3O_cjs.a.LPAREN);for(let a=0;a<-t;a++)r.unshift({type:chunk5IJD5L3O_cjs.a.LPAREN,typeId:o,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--,chunkNAZ6PGLS_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--,chunkNAZ6PGLS_cjs.c.parsing("UNEXPECTED_END","Unexpected end of expression");this.parsePrefix(r);let o=this.tokens,a=o.length,l=n.BP_TABLE,p=this.registry,d=this.builder,f=this.current;for(;f<a;){let u=o[f];if(!u)break;let c=l[u.typeId];if(c>0){if(c<=e)break;if(this.diagnosticPipeline){let m=p.getInfix(u.typeId);m&&this.fireParseletMatched(m,u,false,c);}this.current=++f;let I=u.typeId;if(I===n.PERCENT_ID)d.emitOpcode(10),d.emitNumber(100),d.emitOpcode(23),d.emitOpcode(74);else if(!(I===n.CARET_ID&&this.tryEmitMatrixCaretOp(d))){let m=I===n.CARET_ID?c-1:c+1;this.parseExpression(m,d),d.emitOpcode(n.INFIX_OPCODE[I]);}}else {let I=p.getInfix(u.typeId);if(!I||I.bindingPower<=e)break;this.current=++f,this.diagnosticPipeline&&this.fireParseletMatched(I,u,false,I.bindingPower),this.infixMinBindingPower=e,I.parse(this,r,u,d);}f=this.current;}this.current=f,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,p=e.value;if(p.startsWith("0x")||p.startsWith("0X")){if(a=parseInt(p,16),Number.isNaN(a))throw chunkNAZ6PGLS_cjs.c.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${p}"`,{raw:p})}else if(p.startsWith("0b")||p.startsWith("0B")){if(a=parseInt(p.slice(2),2),Number.isNaN(a))throw chunkNAZ6PGLS_cjs.c.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${p}"`,{raw:p})}else if(p.startsWith("0o")||p.startsWith("0O")){if(a=parseInt(p.slice(2),8),Number.isNaN(a))throw chunkNAZ6PGLS_cjs.c.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${p}"`,{raw:p})}else if(D.test(p))a=parseFloat(p.split(".").join(""));else {let d=chunkS3DFU33X_cjs.a(this.localeCode),f=d.display.decimalSeparator,u=d.display.thousandsSeparator,c=p;u&&(c=c.split(u).join("")),f&&f!=="."&&(c=c.replace(f,".")),a=parseFloat(c),T.test(c)&&(l=c);}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(chunkFVQWN5HZ_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(chunkFVQWN5HZ_cjs.a.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(chunkFVQWN5HZ_cjs.a.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let o=this.registry.getPrefix(r);if(!o)throw chunkNAZ6PGLS_cjs.c.parsing("NO_PREFIX_PARSELET",`No prefix parselet found for token: ${e.type} ("${e.value}")`,{tokenType:e.type,tokenValue:e.value});o.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 o=this.tokens[r];if(o.typeId===n.LPAREN_ID)t++;else if(o.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 chunkNAZ6PGLS_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 chunkNAZ6PGLS_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 o=new chunkFVQWN5HZ_cjs.d(this.pluginFunctionIndex);this.parseExpression(chunkFVQWN5HZ_cjs.a.Lowest,o),this.setBuilder(t);let a=o.build();if(a.hasAsync)throw chunkNAZ6PGLS_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(chunkFVQWN5HZ_cjs.a.Lowest,t),r++;this.match(chunk5IJD5L3O_cjs.a.COMMA);)this.parseExpression(chunkFVQWN5HZ_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 chunkNAZ6PGLS_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 chunkNAZ6PGLS_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,o){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:o,tokenOffset:t.offset||0};a.fireParseletMatched(l);}};n.BP_TABLE=chunkFVQWN5HZ_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??chunkFVQWN5HZ_cjs.a.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let o=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:o,rightBindingPower:o+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-IMXSVHQK.cjs.map
2
- //# sourceMappingURL=chunk-IMXSVHQK.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","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","locale","getLocale","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,CAkF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,KAAMC,CAAAA,CAAmD,CAjFrI,IAAA,CAAQ,MAAA,CAAkB,EAAC,CAC3B,IAAA,CAAQ,OAAA,CAAU,CAAA,CAClB,IAAA,CAAQ,KAAA,CAAQ,CAAA,CAWhB,IAAA,CAAQ,iBAAA,CAA4B,GAWpC,IAAA,CAAA,oBAAA,CAAuB,CAAA,CA0DrB,IAAA,CAAK,QAAA,CAAWH,CAAAA,CAChB,IAAA,CAAK,QAAA,CAAWC,CAAAA,CAChB,IAAA,CAAK,UAAA,CAAaC,CAAAA,CAClB,IAAA,CAAK,mBAAA,CA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A,EAAM,CACtB,IAAA,CAAK,SAAA,CAAU,KAAA,GAChB,CACD,CAAA,CAUaG,CAAAA,CAAyB,IAAIJ","file":"chunk-IMXSVHQK.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 /**\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 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 if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n v = parseInt(raw, 16);\n // A prefix with no digits after it (\"0x\" alone) makes parseInt\n // return NaN. This used to push straight through as a silent\n // NaN Number value instead of a visible error.\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid hex literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0b\") || raw.startsWith(\"0B\")) {\n v = parseInt(raw.slice(2), 2);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid binary literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0o\") || raw.startsWith(\"0O\")) {\n v = parseInt(raw.slice(2), 8);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid octal literal: \"${raw}\"`, { raw });\n }\n } else if (CHAINED_DOT_THOUSANDS_GROUPS.test(raw)) {\n // The lexer accepts \".\" as a thousands-group separator\n // independent of locale (ExpressionLexer's number-scanning\n // \"Thousands separators\" block), but the locale-based\n // normalization below only strips the ACTIVE locale's own\n // configured thousandsSeparator character, for \"en\" that's\n // \",\", not \".\", so a chained dot-grouped literal like\n // \"1.234.567\" fell through to parseFloat() untouched, which\n // stops at the second \".\" and silently truncated it to 1.234\n // (over 99% of the digits dropped, with no error). This is the\n // REAL number-parsing path for actual evaluation, Tier 1 of\n // the two-tier dispatch above always returns for NUMBER_ID, so\n // NumberParselet.parse() (which has the identical fix) never\n // actually runs except via direct unit tests / the \"matched\n // parselets\" diagnostic display.\n v = parseFloat(raw.split(\".\").join(\"\"));\n } else {\n const locale = getLocale(this.localeCode);\n const decimalSep = locale.display.decimalSeparator;\n const thousandsSep = locale.display.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation)\n if (thousandsSep) {\n normalized = normalized.split(thousandsSep).join(\"\");\n }\n // Replace locale decimal separator with \".\" for JavaScript parsing\n if (decimalSep && decimalSep !== \".\") {\n normalized = normalized.replace(decimalSep, \".\");\n }\n v = parseFloat(normalized);\n // 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"]}