solve-engine 2.27.0 → 2.29.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.
- package/dist/{EngineError-C-kBwYlN.d.cts → EngineError-CqGtaT_v.d.cts} +6 -0
- package/dist/{EngineError-C-kBwYlN.d.ts → EngineError-CqGtaT_v.d.ts} +6 -0
- package/dist/{Lexer-DqtnZMC5.d.ts → Lexer-CqFjYoRA.d.ts} +1 -1
- package/dist/{Lexer-DhGhoAa2.d.cts → Lexer-sCI05tqO.d.cts} +1 -1
- package/dist/{PackageCompatibility-CNiTtC6S.d.cts → PackageCompatibility-Bn-T_xKW.d.cts} +1 -1
- package/dist/{PackageCompatibility-fj_f7uqC.d.ts → PackageCompatibility-phvSFP4f.d.ts} +1 -1
- package/dist/{PackageRegistry-BHBCFswo.d.cts → PackageRegistry-B-C1duZw.d.cts} +3 -3
- package/dist/{PackageRegistry-CNZUwWHJ.d.ts → PackageRegistry-C78jVkI9.d.ts} +3 -3
- package/dist/{VMBuiltins-kv4rr0y5.d.cts → VMBuiltins-BkKzhj6C.d.cts} +1 -1
- package/dist/{VMBuiltins-CZiZRKn-.d.ts → VMBuiltins-Du9y8sEo.d.ts} +1 -1
- package/dist/{VMCheckpoints-yun4ocSv.d.cts → VMCheckpoints-WdUQrdc9.d.cts} +1 -1
- package/dist/{VMCheckpoints-DXze6ypg.d.ts → VMCheckpoints-gvy_yxYh.d.ts} +1 -1
- package/dist/{WorkerError-BLZyNq6M.d.cts → WorkerError-CRoM8Ju1.d.cts} +1 -1
- package/dist/{WorkerError-CfBJYueR.d.ts → WorkerError-DTrl3Jag.d.ts} +1 -1
- package/dist/{chunk-TC23XEAV.js → chunk-2PGGPFF3.js} +2 -2
- package/dist/{chunk-TC23XEAV.js.map → chunk-2PGGPFF3.js.map} +1 -1
- package/dist/{chunk-D4VBWPWN.js → chunk-3ZGFAE3Q.js} +2 -2
- package/dist/{chunk-D4VBWPWN.js.map → chunk-3ZGFAE3Q.js.map} +1 -1
- package/dist/{chunk-ZSLVLMO5.cjs → chunk-4DR5RBHQ.cjs} +2 -2
- package/dist/{chunk-ZSLVLMO5.cjs.map → chunk-4DR5RBHQ.cjs.map} +1 -1
- package/dist/{chunk-ZPHUTCJ5.cjs → chunk-4PILWX4F.cjs} +3 -3
- package/dist/{chunk-ZPHUTCJ5.cjs.map → chunk-4PILWX4F.cjs.map} +1 -1
- package/dist/{chunk-ZDJTDFTR.cjs → chunk-5AKT36UK.cjs} +2 -2
- package/dist/{chunk-ZDJTDFTR.cjs.map → chunk-5AKT36UK.cjs.map} +1 -1
- package/dist/{chunk-BCY2WY5P.js → chunk-6K6ZW4B6.js} +3 -3
- package/dist/{chunk-BCY2WY5P.js.map → chunk-6K6ZW4B6.js.map} +1 -1
- package/dist/{chunk-SE6ZCGZ5.cjs → chunk-7DJYS5PO.cjs} +2 -2
- package/dist/{chunk-SE6ZCGZ5.cjs.map → chunk-7DJYS5PO.cjs.map} +1 -1
- package/dist/{chunk-G2V33LFM.cjs → chunk-A755LVPT.cjs} +2 -2
- package/dist/{chunk-G2V33LFM.cjs.map → chunk-A755LVPT.cjs.map} +1 -1
- package/dist/{chunk-TPPM4QSS.cjs → chunk-A764BY7L.cjs} +2 -2
- package/dist/{chunk-TPPM4QSS.cjs.map → chunk-A764BY7L.cjs.map} +1 -1
- package/dist/{chunk-CQLCTKMX.cjs → chunk-AGCNMEP2.cjs} +2 -2
- package/dist/{chunk-CQLCTKMX.cjs.map → chunk-AGCNMEP2.cjs.map} +1 -1
- package/dist/{chunk-LE6WZLJ4.js → chunk-B2NL65FI.js} +2 -2
- package/dist/{chunk-LE6WZLJ4.js.map → chunk-B2NL65FI.js.map} +1 -1
- package/dist/{chunk-VQO54ZMA.js → chunk-CB3EXUM2.js} +2 -2
- package/dist/{chunk-VQO54ZMA.js.map → chunk-CB3EXUM2.js.map} +1 -1
- package/dist/{chunk-Y7XRA2EV.js → chunk-CDE2ZUGG.js} +2 -2
- package/dist/{chunk-Y7XRA2EV.js.map → chunk-CDE2ZUGG.js.map} +1 -1
- package/dist/{chunk-ZE5KKMBV.cjs → chunk-CM2WM5CM.cjs} +2 -2
- package/dist/{chunk-ZE5KKMBV.cjs.map → chunk-CM2WM5CM.cjs.map} +1 -1
- package/dist/chunk-CT3PD7L3.cjs +3 -0
- package/dist/chunk-CT3PD7L3.cjs.map +1 -0
- package/dist/{chunk-TMQ37JQY.cjs → chunk-DUFEONVN.cjs} +3 -3
- package/dist/{chunk-TMQ37JQY.cjs.map → chunk-DUFEONVN.cjs.map} +1 -1
- package/dist/{chunk-S3ODNMJS.js → chunk-FXB5GCBT.js} +2 -2
- package/dist/{chunk-S3ODNMJS.js.map → chunk-FXB5GCBT.js.map} +1 -1
- package/dist/{chunk-BCR53EIL.js → chunk-G3POUURF.js} +2 -2
- package/dist/{chunk-BCR53EIL.js.map → chunk-G3POUURF.js.map} +1 -1
- package/dist/{chunk-GVL3ZMS7.cjs → chunk-GWV273KZ.cjs} +2 -2
- package/dist/{chunk-GVL3ZMS7.cjs.map → chunk-GWV273KZ.cjs.map} +1 -1
- package/dist/{chunk-ZC2NPRLO.js → chunk-IQVSCL2R.js} +3 -3
- package/dist/{chunk-ZC2NPRLO.js.map → chunk-IQVSCL2R.js.map} +1 -1
- package/dist/{chunk-YSHWNCDH.cjs → chunk-IY3GI2AM.cjs} +4 -4
- package/dist/{chunk-YSHWNCDH.cjs.map → chunk-IY3GI2AM.cjs.map} +1 -1
- package/dist/{chunk-LTUYWJGO.js → chunk-KH4QXKLT.js} +2 -2
- package/dist/{chunk-LTUYWJGO.js.map → chunk-KH4QXKLT.js.map} +1 -1
- package/dist/{chunk-RRUGQ6DM.js → chunk-LP3JYC3A.js} +2 -2
- package/dist/{chunk-RRUGQ6DM.js.map → chunk-LP3JYC3A.js.map} +1 -1
- package/dist/{chunk-BLJ6E577.js → chunk-NQFCXLEF.js} +2 -2
- package/dist/{chunk-BLJ6E577.js.map → chunk-NQFCXLEF.js.map} +1 -1
- package/dist/{chunk-GJZIJK2Q.cjs → chunk-OM7NOHJF.cjs} +2 -2
- package/dist/{chunk-GJZIJK2Q.cjs.map → chunk-OM7NOHJF.cjs.map} +1 -1
- package/dist/{chunk-AZX4NTYN.cjs → chunk-P43SV4NJ.cjs} +3 -3
- package/dist/{chunk-AZX4NTYN.cjs.map → chunk-P43SV4NJ.cjs.map} +1 -1
- package/dist/{chunk-ESZNJQ2C.js → chunk-PTXUWGRR.js} +3 -3
- package/dist/{chunk-ESZNJQ2C.js.map → chunk-PTXUWGRR.js.map} +1 -1
- package/dist/{chunk-2SYYKQ4Q.cjs → chunk-Q7TBBV62.cjs} +2 -2
- package/dist/{chunk-2SYYKQ4Q.cjs.map → chunk-Q7TBBV62.cjs.map} +1 -1
- package/dist/{chunk-REZQFPVX.js → chunk-QOEO7CKE.js} +2 -2
- package/dist/{chunk-REZQFPVX.js.map → chunk-QOEO7CKE.js.map} +1 -1
- package/dist/chunk-RAFOQ4T5.cjs +2 -0
- package/dist/{chunk-QQHHZPEW.cjs.map → chunk-RAFOQ4T5.cjs.map} +1 -1
- package/dist/{chunk-VB6QMU2W.js → chunk-RELMEWY6.js} +3 -3
- package/dist/chunk-RELMEWY6.js.map +1 -0
- package/dist/{chunk-HANGBVEE.js → chunk-SFM4XFGJ.js} +2 -2
- package/dist/{chunk-HANGBVEE.js.map → chunk-SFM4XFGJ.js.map} +1 -1
- package/dist/{chunk-GXO7TSXQ.cjs → chunk-SUAGBRQ7.cjs} +3 -3
- package/dist/chunk-SUAGBRQ7.cjs.map +1 -0
- package/dist/chunk-SYJAH6CD.js +3 -0
- package/dist/{chunk-PQFI55AC.js.map → chunk-SYJAH6CD.js.map} +1 -1
- package/dist/{chunk-UVHD7BBC.js → chunk-TBAUKHEC.js} +3 -3
- package/dist/{chunk-UVHD7BBC.js.map → chunk-TBAUKHEC.js.map} +1 -1
- package/dist/{chunk-YG7UWQFV.js → chunk-VLX7ZVK4.js} +2 -2
- package/dist/{chunk-YG7UWQFV.js.map → chunk-VLX7ZVK4.js.map} +1 -1
- package/dist/{chunk-7RC6RBS6.cjs → chunk-WQGHJAW2.cjs} +2 -2
- package/dist/{chunk-7RC6RBS6.cjs.map → chunk-WQGHJAW2.cjs.map} +1 -1
- package/dist/{chunk-6EYKVQT3.cjs → chunk-WU7SBKVU.cjs} +2 -2
- package/dist/{chunk-6EYKVQT3.cjs.map → chunk-WU7SBKVU.cjs.map} +1 -1
- package/dist/{chunk-LQIRBP4Q.js → chunk-X5K72MBV.js} +2 -2
- package/dist/{chunk-LQIRBP4Q.js.map → chunk-X5K72MBV.js.map} +1 -1
- package/dist/{chunk-CL7DM2FX.js → chunk-YN5H54GM.js} +2 -2
- package/dist/{chunk-CL7DM2FX.js.map → chunk-YN5H54GM.js.map} +1 -1
- package/dist/{chunk-FDKTESBC.cjs → chunk-YWF6C2IO.cjs} +2 -2
- package/dist/{chunk-FDKTESBC.cjs.map → chunk-YWF6C2IO.cjs.map} +1 -1
- package/dist/{chunk-O5PO4D2A.cjs → chunk-ZBMWLTE6.cjs} +2 -2
- package/dist/{chunk-O5PO4D2A.cjs.map → chunk-ZBMWLTE6.cjs.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +6 -6
- package/dist/engine.d.ts +6 -6
- package/dist/engine.js +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/language.d.cts +5 -5
- package/dist/language.d.ts +5 -5
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +3 -3
- package/dist/lexer.d.ts +3 -3
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +4 -4
- package/dist/packages.d.ts +4 -4
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.js +1 -1
- package/dist/temporal.cjs +1 -1
- package/dist/temporal.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +5 -5
- package/dist/testing.d.ts +5 -5
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +3 -3
- package/dist/vm.d.ts +3 -3
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +5 -5
- package/dist/worker.d.ts +5 -5
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DFMAZ6XM.cjs +0 -3
- package/dist/chunk-DFMAZ6XM.cjs.map +0 -1
- package/dist/chunk-GXO7TSXQ.cjs.map +0 -1
- package/dist/chunk-PQFI55AC.js +0 -3
- package/dist/chunk-QQHHZPEW.cjs +0 -2
- package/dist/chunk-VB6QMU2W.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkYBQOQTVL_cjs=require('./chunk-YBQOQTVL.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunkYBQOQTVL_cjs=require('./chunk-YBQOQTVL.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunkSUAGBRQ7_cjs=require('./chunk-SUAGBRQ7.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 f={[chunkYBQOQTVL_cjs.a.PLUS]:o.Sum,[chunkYBQOQTVL_cjs.a.MINUS]:o.Sum,[chunkYBQOQTVL_cjs.a.STAR]:o.Product,[chunkYBQOQTVL_cjs.a.SLASH]:o.Product,[chunkYBQOQTVL_cjs.a.MOD]:o.Product,[chunkYBQOQTVL_cjs.a.CARET]:o.Exponent,[chunkYBQOQTVL_cjs.a.BIT_OR]:o.BitwiseOr,[chunkYBQOQTVL_cjs.a.BIT_XOR]:o.BitwiseXor,[chunkYBQOQTVL_cjs.a.BIT_AND]:o.BitwiseAnd,[chunkYBQOQTVL_cjs.a.LSHIFT]:o.Shift,[chunkYBQOQTVL_cjs.a.RSHIFT]:o.Shift,[chunkYBQOQTVL_cjs.a.URSHIFT]:o.Shift,[chunkYBQOQTVL_cjs.a.PERCENT]:o.Postfix,[chunkYBQOQTVL_cjs.a.OF]:o.Product},h=null;function F(){if(h)return h;let i=0;for(let n of Object.keys(f)){let t=chunkYBQOQTVL_cjs.c(n);t>i&&(i=t);}for(let n of Object.values(chunkYBQOQTVL_cjs.a)){let t=chunkYBQOQTVL_cjs.c(n);t>i&&(i=t);}let e=new Uint8Array(i+1);for(let[n,t]of Object.entries(f)){let u=chunkYBQOQTVL_cjs.c(n);e[u]=t;}return h=e,e}function P(){h=null;}var r=255,A="-0";function m(i,e){if(!Number.isInteger(i)||i<0||i>255)throw chunkSUAGBRQ7_cjs.c.parsing("BYTECODE_OPERAND_OUT_OF_RANGE",`A bytecode ${e} must be an integer from 0 to 255, but ${i} was emitted; the opcode stream stores one byte per operand.`,{value:i,what:e});return i}var O=Object.freeze([]),B=new Float64Array(0),b=class{constructor(e){this.pluginFunctionIndex=e;this.opcodes=[];this.numbers=[];this.strings=[];this.stringIndex=new Map;this.numberIndex=new Map;this._hasAsync=false;this.userFunctionBodies=[];this.anonymousBodies=[];}get pluginIndexMap(){return this.pluginFunctionIndex}emitPluginCall(e,n){let t=this.pluginFunctionIndex?.get(e);if(t===void 0)throw chunkSUAGBRQ7_cjs.c.execution("UNKNOWN_PLUGIN_FUNCTION",`No registered plugin function named "${e}". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,{functionName:e});if(t>65535)throw chunkSUAGBRQ7_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(n);}emitOpcode(e){this.opcodes.push(e),(e===50||e===161)&&(this._hasAsync=true);}emitNumber(e){let n=Object.is(e,-0)?A:e,t=this.numberIndex.get(n);if(t===void 0){if(t=this.numbers.length,t>r)throw chunkSUAGBRQ7_cjs.c.parsing("TOO_MANY_NUMERIC_CONSTANTS",`Expression has more than ${r+1} distinct numeric literals, exceeding the bytecode constant pool's limit.`,{limit:r+1});this.numbers.push(e),this.numberIndex.set(n,t);}this.opcodes.push(t);}emitString(e){let n=this.stringIndex.get(e);if(n===void 0){if(n=this.strings.length,n>r)throw chunkSUAGBRQ7_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(e),this.stringIndex.set(e,n);}this.opcodes.push(n);}emitIndex(e){this.opcodes.push(m(e,"index"));}emitByte(e){this.opcodes.push(m(e,"byte"));}get currentLength(){return this.opcodes.length}emitUserFunctionBody(e,n,t){let u=this.userFunctionBodies.length;if(u>r)throw chunkSUAGBRQ7_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:e,params:n,program:t}),u}emitAnonymousBody(e,n){let t=this.anonymousBodies.length;if(t>r)throw chunkSUAGBRQ7_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:e,program:n}),t}patchJump(e,n){if(e<0||e>=this.opcodes.length)throw chunkSUAGBRQ7_cjs.c.parsing("BYTECODE_OPERAND_OUT_OF_RANGE",`patchJump was asked to write at position ${e}, outside the ${this.opcodes.length} bytes emitted so far.`,{position:e,length:this.opcodes.length});this.opcodes[e]=m(n,"jump target");}build(){return {opcodes:new Uint8Array(this.opcodes),numbers:this.numbers.length>0?new Float64Array(this.numbers):B,strings:this.strings.length>0?[...this.strings]:O,hasAsync:this._hasAsync,userFunctionBodies:this.userFunctionBodies.length>0?[...this.userFunctionBodies]:void 0,anonymousBodies:this.anonymousBodies.length>0?[...this.anonymousBodies]:void 0}}buildInto(e){let n=this.opcodes.length,t=this.numbers.length,u=e&&e.opcodes.length>=n,I=e&&e.numbers.length>=t,g=u?new Uint8Array(e.opcodes.buffer,e.opcodes.byteOffset,n):new Uint8Array(n),p=I?new Float64Array(e.numbers.buffer,e.numbers.byteOffset,t):new Float64Array(t);for(let c=0;c<n;c++)g[c]=this.opcodes[c];for(let c=0;c<t;c++)p[c]=this.numbers[c];return {opcodes:g,numbers:p,strings:[...this.strings],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.numbers.length=0,this.numberIndex.clear()),this.strings.length>0&&(this.strings.length=0,this.stringIndex.clear()),this._hasAsync=false,this.userFunctionBodies.length>0&&(this.userFunctionBodies.length=0),this.anonymousBodies.length>0&&(this.anonymousBodies.length=0);}};var _=/^\d{1,3}(\.\d{3}){2,}$/,y=/^\d+$/;function R(i,e){let n=i.endsWith("n")?i.slice(0,-1):i;if(y.test(n))return n;let t=_.test(n)?n.split(".").join(""):x(n,e);if(!y.test(t)){let u=n.includes(".")?".":n.includes(",")?",":n;throw chunkSUAGBRQ7_cjs.c.parsing("INVALID_NUMBER_LITERAL",`"${i}" is not a whole number: "${u}" separates decimals in the ${e} locale, and a whole number cannot have a fractional part.`,{raw:i,localeCode:e,separator:u})}return t}function x(i,e){let n=chunkS3DFU33X_cjs.a(e).display.thousandsSeparator;return n?i.split(n).join(""):i}exports.a=o;exports.b=F;exports.c=P;exports.d=b;exports.e=R;//# sourceMappingURL=chunk-5AKT36UK.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-5AKT36UK.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","NEGATIVE_ZERO_KEY","checkedOperand","value","what","ErrorFactory","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","op","n","key","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,UAAA,CAAY,EAAA,CACZ,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CAaZ,WAAA,CAAa,EAAA,CAab,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CACZ,UAAA,CAAY,EAAA,CACZ,WAAA,CAAa,EAAA,CACb,KAAA,CAAO,EAAA,CACP,GAAA,CAAK,EAAA,CACL,OAAA,CAAS,EAAA,CAMT,WAAA,CAAa,EAAA,CAIb,QAAA,CAAU,GACV,MAAA,CAAQ,EAAA,CACR,OAAA,CAAS,EAAA,CACT,IAAA,CAAM,EACR,EAiDO,IAAMC,CAAAA,CAA2C,C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AoBF,CAAAA,CAAeD,CAAU,CAAA,CAEhD,GAAI,CAACH,CAAAA,CAAY,IAAA,CAAKK,CAAM,CAAA,CAAG,CAC9B,IAAME,CAAAA,CAAYH,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,GAAA,CAAMA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,GAAA,CAAMA,CAAAA,CAC1F,MAAM9B,mBAAAA,CAAa,OAAA,CAClB,wBAAA,CACA,CAAA,CAAA,EAAI4B,CAAG,CAAA,0BAAA,EAA6BK,CAAS,CAAA,4BAAA,EAA+BJ,CAAU,CAAA,0DAAA,CAAA,CACtF,CAAE,GAAA,CAAAD,CAAAA,CAAK,UAAA,CAAAC,CAAAA,CAAY,SAAA,CAAAI,CAAU,CAC9B,CACD,CACA,OAAOF,CACR,CASA,SAASC,CAAAA,CAAoBE,CAAAA,CAAcL,CAAAA,CAA4B,CACtE,IAAMM,CAAAA,CAAqBC,mBAAAA,CAAUP,CAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA,CACzD,OAAOM,CAAAA,CAAqBD,CAAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-ZDJTDFTR.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 */\nexport const 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/** The `numberIndex` key for negative zero, which `Map` would otherwise fold into positive zero. */\nconst NEGATIVE_ZERO_KEY = \"-0\";\n\n/**\n * An operand that fits the byte the opcode stream stores it in, or a\n * structured refusal. `build()` copies the stream into a `Uint8Array`, which\n * keeps the low eight bits of whatever it is given: an operand of 300 used to\n * become 44 with no error, and the program then read a different constant,\n * plugin function or argument count from the one the parselet emitted. Every\n * raw operand goes through here, so a package author's mistake is reported at\n * compile time as a fault in the package rather than answered with a wrong\n * number.\n */\nfunction checkedOperand(value: number, what: string): number {\n\tif (!Number.isInteger(value) || value < 0 || value > 255) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t`A bytecode ${what} must be an integer from 0 to 255, but ${value} was emitted; the opcode stream stores one byte per operand.`,\n\t\t\t{ value, what }\n\t\t);\n\t}\n\treturn value;\n}\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\t/** Value (or {@link NEGATIVE_ZERO_KEY}) to its slot in `numbers`, so a repeated literal is emitted once. */\n\tprivate numberIndex = new Map<number | 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: interns `n` into the program's constant pool\n\t * (deduplicated, like {@link emitString}) and writes its index into the\n\t * opcode stream (read back by the VM as e.g. `PUSH_NUMBER <idx>`).\n\t *\n\t * Deduplicated so that the 256-entry pool counts distinct values rather\n\t * than occurrences: a long line of repeated literals used to exhaust it\n\t * long before it held 256 different numbers. Negative zero keeps its own\n\t * slot, because `1 / -0` is not `1 / 0`; NaN shares one, since every NaN\n\t * reads the same.\n\t *\n\t * @throws If the pool would exceed 256 distinct entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst key = Object.is(n, -0) ? NEGATIVE_ZERO_KEY : n;\n\t\tlet idx = this.numberIndex.get(key);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.numbers.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_NUMERIC_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct numeric 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.numbers.push(n);\n\t\t\tthis.numberIndex.set(key, idx);\n\t\t}\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(checkedOperand(idx, \"index\"));\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(checkedOperand(b, \"byte\"));\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\tif (position < 0 || position >= this.opcodes.length) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t\t`patchJump was asked to write at position ${position}, outside the ${this.opcodes.length} bytes emitted so far.`,\n\t\t\t\t{ position, length: this.opcodes.length }\n\t\t\t);\n\t\t}\n\t\tthis.opcodes[position] = checkedOperand(target, \"jump target\");\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tif (this.numbers.length > 0) {\n\t\t\tthis.numbers.length = 0;\n\t\t\tthis.numberIndex.clear();\n\t\t}\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","NEGATIVE_ZERO_KEY","checkedOperand","value","what","ErrorFactory","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","op","n","key","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","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AAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-5AKT36UK.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 */\nexport const 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/** The `numberIndex` key for negative zero, which `Map` would otherwise fold into positive zero. */\nconst NEGATIVE_ZERO_KEY = \"-0\";\n\n/**\n * An operand that fits the byte the opcode stream stores it in, or a\n * structured refusal. `build()` copies the stream into a `Uint8Array`, which\n * keeps the low eight bits of whatever it is given: an operand of 300 used to\n * become 44 with no error, and the program then read a different constant,\n * plugin function or argument count from the one the parselet emitted. Every\n * raw operand goes through here, so a package author's mistake is reported at\n * compile time as a fault in the package rather than answered with a wrong\n * number.\n */\nfunction checkedOperand(value: number, what: string): number {\n\tif (!Number.isInteger(value) || value < 0 || value > 255) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t`A bytecode ${what} must be an integer from 0 to 255, but ${value} was emitted; the opcode stream stores one byte per operand.`,\n\t\t\t{ value, what }\n\t\t);\n\t}\n\treturn value;\n}\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\t/** Value (or {@link NEGATIVE_ZERO_KEY}) to its slot in `numbers`, so a repeated literal is emitted once. */\n\tprivate numberIndex = new Map<number | 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: interns `n` into the program's constant pool\n\t * (deduplicated, like {@link emitString}) and writes its index into the\n\t * opcode stream (read back by the VM as e.g. `PUSH_NUMBER <idx>`).\n\t *\n\t * Deduplicated so that the 256-entry pool counts distinct values rather\n\t * than occurrences: a long line of repeated literals used to exhaust it\n\t * long before it held 256 different numbers. Negative zero keeps its own\n\t * slot, because `1 / -0` is not `1 / 0`; NaN shares one, since every NaN\n\t * reads the same.\n\t *\n\t * @throws If the pool would exceed 256 distinct entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst key = Object.is(n, -0) ? NEGATIVE_ZERO_KEY : n;\n\t\tlet idx = this.numberIndex.get(key);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.numbers.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_NUMERIC_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct numeric 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.numbers.push(n);\n\t\t\tthis.numberIndex.set(key, idx);\n\t\t}\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(checkedOperand(idx, \"index\"));\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(checkedOperand(b, \"byte\"));\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\tif (position < 0 || position >= this.opcodes.length) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t\t`patchJump was asked to write at position ${position}, outside the ${this.opcodes.length} bytes emitted so far.`,\n\t\t\t\t{ position, length: this.opcodes.length }\n\t\t\t);\n\t\t}\n\t\tthis.opcodes[position] = checkedOperand(target, \"jump target\");\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tif (this.numbers.length > 0) {\n\t\t\tthis.numbers.length = 0;\n\t\t\tthis.numberIndex.clear();\n\t\t}\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|