solve-engine 2.23.0 → 2.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -32
- package/dist/{Configuration-BGQn-cJ8.d.cts → Configuration-DnzYPmoK.d.cts} +33 -0
- package/dist/{Configuration-BGQn-cJ8.d.ts → Configuration-DnzYPmoK.d.ts} +33 -0
- package/dist/{EngineError-DTk7I7hZ.d.cts → EngineError-D1kXsjIj.d.cts} +4 -0
- package/dist/{EngineError-DTk7I7hZ.d.ts → EngineError-D1kXsjIj.d.ts} +4 -0
- package/dist/{PackageCompatibility-BGXSFuL9.d.ts → PackageCompatibility-Bq82y0ZN.d.ts} +1 -1
- package/dist/{PackageCompatibility-BZCqaTOO.d.cts → PackageCompatibility-CeAPVHZr.d.cts} +1 -1
- package/dist/{PackageRegistry-rMGnTh7W.d.cts → PackageRegistry-B9-7fJGH.d.cts} +16 -11
- package/dist/{PackageRegistry-BRoVOYzg.d.ts → PackageRegistry-CDEgfhT_.d.ts} +16 -11
- package/dist/{Parselet-Bkbp9CKD.d.cts → Parselet-4oH5OuRt.d.cts} +1 -1
- package/dist/{Parselet-B-WyUtX4.d.ts → Parselet-BwDqKFfK.d.ts} +1 -1
- package/dist/{ScopeManager-gB9UengK.d.ts → ScopeManager-BQBhlDAu.d.ts} +38 -7
- package/dist/{ScopeManager-bCYewWVt.d.cts → ScopeManager-DrXB3Nvm.d.cts} +38 -7
- package/dist/{VMCheckpoints-DGar9Yg8.d.cts → VMCheckpoints-BK32PTl2.d.cts} +2 -2
- package/dist/{VMCheckpoints-BDRY1Kx8.d.ts → VMCheckpoints-C5jC92o3.d.ts} +2 -2
- package/dist/{Value-DCTqTSeP.d.cts → Value-Ds3Gy07C.d.cts} +1 -1
- package/dist/{Value-DCTqTSeP.d.ts → Value-Ds3Gy07C.d.ts} +1 -1
- package/dist/{WorkerError-DpZgKRks.d.ts → WorkerError-CVQbs6_D.d.ts} +1 -1
- package/dist/{WorkerError-DGBNM3gA.d.cts → WorkerError-DaNWQFp1.d.cts} +1 -1
- package/dist/chunk-2BXNZM3G.js +2 -0
- package/dist/chunk-2BXNZM3G.js.map +1 -0
- package/dist/chunk-2JSNWYYA.cjs +3 -0
- package/dist/chunk-2JSNWYYA.cjs.map +1 -0
- package/dist/{chunk-J7ABVGZH.cjs → chunk-2VE4OW4A.cjs} +2 -2
- package/dist/{chunk-J7ABVGZH.cjs.map → chunk-2VE4OW4A.cjs.map} +1 -1
- package/dist/{chunk-HMC7FJO7.js → chunk-3SHWTGTP.js} +2 -2
- package/dist/{chunk-HMC7FJO7.js.map → chunk-3SHWTGTP.js.map} +1 -1
- package/dist/{chunk-EN3CDYOS.cjs → chunk-5GL4SAVH.cjs} +2 -2
- package/dist/{chunk-EN3CDYOS.cjs.map → chunk-5GL4SAVH.cjs.map} +1 -1
- package/dist/{chunk-SGIDBZ4T.cjs → chunk-72N3ZRVE.cjs} +2 -2
- package/dist/chunk-72N3ZRVE.cjs.map +1 -0
- package/dist/{chunk-CHSO3DCS.js → chunk-7EP36NXE.js} +3 -3
- package/dist/{chunk-CHSO3DCS.js.map → chunk-7EP36NXE.js.map} +1 -1
- package/dist/chunk-A4JV7HRB.js +3 -0
- package/dist/chunk-A4JV7HRB.js.map +1 -0
- package/dist/chunk-AUOE7MFI.cjs +2 -0
- package/dist/chunk-AUOE7MFI.cjs.map +1 -0
- package/dist/chunk-BDF4VCQX.js +3 -0
- package/dist/chunk-BDF4VCQX.js.map +1 -0
- package/dist/{chunk-3SSMOVWB.cjs → chunk-CDNJZBM3.cjs} +2 -2
- package/dist/{chunk-3SSMOVWB.cjs.map → chunk-CDNJZBM3.cjs.map} +1 -1
- package/dist/{chunk-YAONCEAW.cjs → chunk-CMZSK6FY.cjs} +3 -3
- package/dist/{chunk-YAONCEAW.cjs.map → chunk-CMZSK6FY.cjs.map} +1 -1
- package/dist/chunk-D2Q2VFJ6.js +2 -0
- package/dist/chunk-D2Q2VFJ6.js.map +1 -0
- package/dist/{chunk-75JLWK4L.cjs → chunk-DA7M6H63.cjs} +2 -2
- package/dist/{chunk-75JLWK4L.cjs.map → chunk-DA7M6H63.cjs.map} +1 -1
- package/dist/chunk-ELQQKZN3.cjs +3 -0
- package/dist/{chunk-PIZQIQVM.js.map → chunk-ELQQKZN3.cjs.map} +1 -1
- package/dist/chunk-F7QIBC4B.cjs +3 -0
- package/dist/chunk-F7QIBC4B.cjs.map +1 -0
- package/dist/chunk-GP4H5OIT.js +3 -0
- package/dist/chunk-GP4H5OIT.js.map +1 -0
- package/dist/chunk-HQ7BKXG7.js +2 -0
- package/dist/chunk-HQ7BKXG7.js.map +1 -0
- package/dist/{chunk-KRXO3MOW.cjs → chunk-IHAZL4EF.cjs} +2 -2
- package/dist/chunk-IHAZL4EF.cjs.map +1 -0
- package/dist/{chunk-7E7NXKQ5.js → chunk-IJHL3LMH.js} +2 -2
- package/dist/chunk-IJHL3LMH.js.map +1 -0
- package/dist/{chunk-3GR46UOX.js → chunk-IPSOWFCA.js} +2 -2
- package/dist/{chunk-3GR46UOX.js.map → chunk-IPSOWFCA.js.map} +1 -1
- package/dist/chunk-LM6ZQUEU.js +2 -0
- package/dist/chunk-LM6ZQUEU.js.map +1 -0
- package/dist/{chunk-N37PUZJR.cjs → chunk-LTJV3VJE.cjs} +2 -2
- package/dist/{chunk-N37PUZJR.cjs.map → chunk-LTJV3VJE.cjs.map} +1 -1
- package/dist/chunk-MWWAKZOD.cjs +3 -0
- package/dist/chunk-MWWAKZOD.cjs.map +1 -0
- package/dist/chunk-NUF66H57.js +5 -0
- package/dist/chunk-NUF66H57.js.map +1 -0
- package/dist/{chunk-MRRMIBHE.js → chunk-OMHRBKAT.js} +2 -2
- package/dist/{chunk-MRRMIBHE.js.map → chunk-OMHRBKAT.js.map} +1 -1
- package/dist/{chunk-4ETS224G.js → chunk-PTQCHMYA.js} +2 -2
- package/dist/{chunk-4ETS224G.js.map → chunk-PTQCHMYA.js.map} +1 -1
- package/dist/{chunk-4DJJIUQF.js → chunk-PWWQZFAE.js} +2 -2
- package/dist/chunk-PWWQZFAE.js.map +1 -0
- package/dist/chunk-RE6AIU6Y.js +3 -0
- package/dist/chunk-RE6AIU6Y.js.map +1 -0
- package/dist/chunk-RECRD45C.cjs +5 -0
- package/dist/chunk-RECRD45C.cjs.map +1 -0
- package/dist/{chunk-O3BDXOQJ.js → chunk-RENO2AWO.js} +2 -2
- package/dist/{chunk-O3BDXOQJ.js.map → chunk-RENO2AWO.js.map} +1 -1
- package/dist/chunk-RMCN5WFO.cjs +2 -0
- package/dist/chunk-RMCN5WFO.cjs.map +1 -0
- package/dist/{chunk-TL545PXW.cjs → chunk-RN3ISTM3.cjs} +2 -2
- package/dist/{chunk-TL545PXW.cjs.map → chunk-RN3ISTM3.cjs.map} +1 -1
- package/dist/{chunk-JYLNQOPU.cjs → chunk-S46R5QZP.cjs} +2 -2
- package/dist/{chunk-JYLNQOPU.cjs.map → chunk-S46R5QZP.cjs.map} +1 -1
- package/dist/{chunk-USQ4KL6S.cjs → chunk-UPH22K2T.cjs} +2 -2
- package/dist/chunk-UPH22K2T.cjs.map +1 -0
- package/dist/{chunk-KEA5HRL3.js → chunk-UXR7JIPX.js} +2 -2
- package/dist/{chunk-KEA5HRL3.js.map → chunk-UXR7JIPX.js.map} +1 -1
- package/dist/chunk-UY3ID6JF.cjs +2 -0
- package/dist/chunk-UY3ID6JF.cjs.map +1 -0
- package/dist/{chunk-JVMINMAB.js → chunk-WFOQRPA6.js} +2 -2
- package/dist/{chunk-JVMINMAB.js.map → chunk-WFOQRPA6.js.map} +1 -1
- package/dist/{chunk-AF7HQN6I.js → chunk-XFJABR3B.js} +2 -2
- package/dist/chunk-XFJABR3B.js.map +1 -0
- package/dist/{chunk-LNZNJSRW.cjs → chunk-ZVPZQ66D.cjs} +2 -2
- package/dist/chunk-ZVPZQ66D.cjs.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.d.cts +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +9 -9
- package/dist/engine.d.ts +9 -9
- 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.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -9
- package/dist/index.d.ts +11 -9
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +8 -8
- package/dist/language.d.ts +8 -8
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.d.cts +14 -8
- package/dist/normalizer.d.ts +14 -8
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +7 -7
- package/dist/packages.d.ts +7 -7
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +3 -3
- package/dist/parser.d.ts +3 -3
- package/dist/parser.js +1 -1
- package/dist/{pipeline-B4wf3M1h.d.cts → pipeline-69q2tsLE.d.cts} +1 -1
- package/dist/{pipeline-QIT4iD8f.d.ts → pipeline-DTqGLPsV.d.ts} +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +18 -2
- package/dist/resolvers.d.ts +18 -2
- package/dist/resolvers.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +8 -8
- package/dist/testing.d.ts +8 -8
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +1 -1
- package/dist/uom.d.ts +1 -1
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +7 -7
- package/dist/vm.d.ts +7 -7
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +31 -22
- package/dist/worker.d.ts +31 -22
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-42JXN3BH.js +0 -5
- package/dist/chunk-42JXN3BH.js.map +0 -1
- package/dist/chunk-4DJJIUQF.js.map +0 -1
- package/dist/chunk-6YM67DWH.cjs +0 -3
- package/dist/chunk-6YM67DWH.cjs.map +0 -1
- package/dist/chunk-7E7NXKQ5.js.map +0 -1
- package/dist/chunk-7SZBEE5R.cjs +0 -2
- package/dist/chunk-7SZBEE5R.cjs.map +0 -1
- package/dist/chunk-A5M4QZIK.js +0 -2
- package/dist/chunk-A5M4QZIK.js.map +0 -1
- package/dist/chunk-AF7HQN6I.js.map +0 -1
- package/dist/chunk-ALY4ZMYO.js +0 -2
- package/dist/chunk-ALY4ZMYO.js.map +0 -1
- package/dist/chunk-BRJ4RT5U.js +0 -2
- package/dist/chunk-BRJ4RT5U.js.map +0 -1
- package/dist/chunk-CO2BI6WL.cjs +0 -3
- package/dist/chunk-CO2BI6WL.cjs.map +0 -1
- package/dist/chunk-EQDT42JG.js +0 -3
- package/dist/chunk-EQDT42JG.js.map +0 -1
- package/dist/chunk-FMMT5C5H.cjs +0 -3
- package/dist/chunk-FMMT5C5H.cjs.map +0 -1
- package/dist/chunk-FP6Z6PYR.js +0 -2
- package/dist/chunk-FP6Z6PYR.js.map +0 -1
- package/dist/chunk-H3JXNH7X.cjs +0 -3
- package/dist/chunk-H3JXNH7X.cjs.map +0 -1
- package/dist/chunk-HZOLIL5T.js +0 -3
- package/dist/chunk-HZOLIL5T.js.map +0 -1
- package/dist/chunk-KRXO3MOW.cjs.map +0 -1
- package/dist/chunk-KVLJDOZ7.cjs +0 -5
- package/dist/chunk-KVLJDOZ7.cjs.map +0 -1
- package/dist/chunk-LNZNJSRW.cjs.map +0 -1
- package/dist/chunk-PIZQIQVM.js +0 -3
- package/dist/chunk-QTSDIDAS.js +0 -3
- package/dist/chunk-QTSDIDAS.js.map +0 -1
- package/dist/chunk-SGIDBZ4T.cjs.map +0 -1
- package/dist/chunk-UNKSCVIL.cjs +0 -2
- package/dist/chunk-UNKSCVIL.cjs.map +0 -1
- package/dist/chunk-USQ4KL6S.cjs.map +0 -1
- package/dist/chunk-XDXIPVZB.cjs +0 -2
- package/dist/chunk-XDXIPVZB.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkELQQKZN3_cjs=require('./chunk-ELQQKZN3.cjs');var d="2.24.0";var m=d;var l={date:{maxOffsetYears:100,minOffsetYears:-100,defaultFormat:"YYYY-MM-DD",inputOrder:"auto"},performance:{defaultCacheSize:2e3,maxDocumentLines:1e5},validation:{maxExpressionLength:2e3,maxComplexity:500,maxNestingDepth:50,autoBalanceParens:false},vm:{maxStackDepth:200,maxInstructions:5e4,maxCollectionSize:1e5,maxAllocatedElements:2e6,maxFunctionCalls:1e4,maxGoalSeekIterations:100},worker:{maxConcurrentWorkers:4,idleTimeoutMs:3e4,maxRetries:3,baseBackoffMs:1e3},diagnostic:{enabled:false,vmTraceEnabled:false},backgroundRefresh:{enabled:false},network:{enabled:true}};function r(s,e){return {date:{...s.date,...e.date},performance:{...s.performance,...e.performance},validation:{...s.validation,...e.validation},vm:{...s.vm,...e.vm},worker:{...s.worker,...e.worker},diagnostic:{...s.diagnostic,...e.diagnostic},backgroundRefresh:{...s.backgroundRefresh,...e.backgroundRefresh},network:{...s.network,...e.network}}}var c=class{constructor(e={}){this.config=r(l,e);}get(e){let o=e.split("."),t=this.config;for(let i of o)if(t&&typeof t=="object"&&i in t)t=t[i];else throw chunkELQQKZN3_cjs.c.config("CONFIG_PATH_NOT_FOUND",`Configuration path not found: ${e}`,{path:e});return t}set(e,o){let t=e.split(".");if(t.length<2)throw chunkELQQKZN3_cjs.c.config("INVALID_CONFIG_PATH",`Invalid path: ${e}. Must be in format 'section.property'`,{path:e});let i=t[0],u=t[1];if(!(i in this.config))throw chunkELQQKZN3_cjs.c.config("CONFIG_SECTION_NOT_FOUND",`Configuration section not found: ${i}`,{section:i,path:e});let a=this.config[i];if(a&&typeof a=="object")a[u]=o;else throw chunkELQQKZN3_cjs.c.config("CONFIG_PROPERTY_NOT_FOUND",`Configuration property not found: ${e}`,{path:e})}getConfig(){return r(this.config,{})}update(e){this.config=r(this.config,e);}reset(){this.config=r(l,{});}validate(){let e=[];return this.config.performance.maxDocumentLines>1e5&&e.push("maxDocumentLines cannot exceed 100,000"),this.config.date.maxOffsetYears>1e3&&e.push("maxOffsetYears cannot exceed 1000"),{valid:e.length===0,error:e.join("; "),warnings:[]}}};exports.a=m;exports.b=l;exports.c=r;exports.d=c;//# sourceMappingURL=chunk-UY3ID6JF.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-UY3ID6JF.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/constants/version.ts","../src/constants/Configuration.ts"],"names":["version","ENGINE_VERSION","DEFAULT_CONFIG","mergeEngineConfig","base","override","ConfigManager","config","path","keys","current","key","ErrorFactory","value","section","property","sectionConfig","errors"],"mappings":"mEAEE,IAAAA,EAAW,QAAA,CCcN,IAAMC,EAAyBD,ECoX/B,IAAME,EAA+B,CACzC,IAAA,CAAM,CAIJ,cAAA,CAAgB,GAAA,CAChB,eAAgB,IAAA,CAChB,aAAA,CAAe,aACf,UAAA,CAAY,MACd,EACA,WAAA,CAAa,CAIX,gBAAA,CAAkB,GAAA,CAalB,iBAAkB,GACpB,CAAA,CACC,WAAY,CACV,mBAAA,CAAqB,IACrB,aAAA,CAAe,GAAA,CACf,gBAAiB,EAAA,CACjB,iBAAA,CAAmB,KACrB,CAAA,CACA,EAAA,CAAI,CACF,aAAA,CAAe,GAAA,CACf,gBAAiB,GAAA,CAKjB,iBAAA,CAAmB,GAAA,CAInB,oBAAA,CAAsB,IAMtB,gBAAA,CAAkB,GAAA,CA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,EAAE,CAC1C,CAKA,OAAOI,CAAAA,CAAqC,CAC1C,KAAK,MAAA,CAASJ,CAAAA,CAAkB,KAAK,MAAA,CAAQI,CAAM,EACrD,CAcA,KAAA,EAAc,CACZ,IAAA,CAAK,MAAA,CAASJ,CAAAA,CAAkBD,CAAAA,CAAgB,EAAE,EACpD,CAKA,QAAA,EAA6B,CAC3B,IAAMe,CAAAA,CAAmB,GAGzB,OAAI,IAAA,CAAK,OAAO,WAAA,CAAY,gBAAA,CAAmB,KAC7CA,CAAAA,CAAO,IAAA,CAAK,wCAAwC,CAAA,CAIlD,IAAA,CAAK,OAAO,IAAA,CAAK,cAAA,CAAiB,KACpCA,CAAAA,CAAO,IAAA,CAAK,mCAAmC,CAAA,CAG1C,CACL,MAAOA,CAAAA,CAAO,MAAA,GAAW,EACzB,KAAA,CAAOA,CAAAA,CAAO,KAAK,IAAI,CAAA,CACvB,SAAU,EACZ,CACF,CACF","file":"chunk-UY3ID6JF.cjs","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.24.0\",\n \"description\": \"An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.\",\n \"keywords\": [\n \"expression-evaluator\",\n \"calculator\",\n \"bytecode-vm\",\n \"parser\",\n \"lexer\",\n \"dsl\",\n \"markdown\",\n \"obsidian\"\n ],\n \"license\": \"MIT\",\n \"author\": \"Liam Riddell\",\n \"homepage\": \"https://liamriddell.github.io/solve-engine/\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/LiamRiddell/solve-engine.git\",\n \"directory\": \"packages/engine\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/LiamRiddell/solve-engine/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"LICENSE\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./engine\": {\n \"import\": {\n \"types\": \"./dist/engine.d.ts\",\n \"default\": \"./dist/engine.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.d.cts\",\n \"default\": \"./dist/engine.cjs\"\n }\n },\n \"./vm\": {\n \"import\": {\n \"types\": \"./dist/vm.d.ts\",\n \"default\": \"./dist/vm.js\"\n },\n \"require\": {\n \"types\": \"./dist/vm.d.cts\",\n \"default\": \"./dist/vm.cjs\"\n }\n },\n \"./format\": {\n \"import\": {\n \"types\": \"./dist/format.d.ts\",\n \"default\": \"./dist/format.js\"\n },\n \"require\": {\n \"types\": \"./dist/format.d.cts\",\n \"default\": \"./dist/format.cjs\"\n }\n },\n \"./language\": {\n \"import\": {\n \"types\": \"./dist/language.d.ts\",\n \"default\": \"./dist/language.js\"\n },\n \"require\": {\n \"types\": \"./dist/language.d.cts\",\n \"default\": \"./dist/language.cjs\"\n }\n },\n \"./packages\": {\n \"import\": {\n \"types\": \"./dist/packages.d.ts\",\n \"default\": \"./dist/packages.js\"\n },\n \"require\": {\n \"types\": \"./dist/packages.d.cts\",\n \"default\": \"./dist/packages.cjs\"\n }\n },\n \"./constants\": {\n \"import\": {\n \"types\": \"./dist/constants.d.ts\",\n \"default\": \"./dist/constants.js\"\n },\n \"require\": {\n \"types\": \"./dist/constants.d.cts\",\n \"default\": \"./dist/constants.cjs\"\n }\n },\n \"./lexer\": {\n \"import\": {\n \"types\": \"./dist/lexer.d.ts\",\n \"default\": \"./dist/lexer.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexer.d.cts\",\n \"default\": \"./dist/lexer.cjs\"\n }\n },\n \"./parser\": {\n \"import\": {\n \"types\": \"./dist/parser.d.ts\",\n \"default\": \"./dist/parser.js\"\n },\n \"require\": {\n \"types\": \"./dist/parser.d.cts\",\n \"default\": \"./dist/parser.cjs\"\n }\n },\n \"./normalizer\": {\n \"import\": {\n \"types\": \"./dist/normalizer.d.ts\",\n \"default\": \"./dist/normalizer.js\"\n },\n \"require\": {\n \"types\": \"./dist/normalizer.d.cts\",\n \"default\": \"./dist/normalizer.cjs\"\n }\n },\n \"./resolvers\": {\n \"import\": {\n \"types\": \"./dist/resolvers.d.ts\",\n \"default\": \"./dist/resolvers.js\"\n },\n \"require\": {\n \"types\": \"./dist/resolvers.d.cts\",\n \"default\": \"./dist/resolvers.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/errors.d.ts\",\n \"default\": \"./dist/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/errors.d.cts\",\n \"default\": \"./dist/errors.cjs\"\n }\n },\n \"./utilities\": {\n \"import\": {\n \"types\": \"./dist/utilities.d.ts\",\n \"default\": \"./dist/utilities.js\"\n },\n \"require\": {\n \"types\": \"./dist/utilities.d.cts\",\n \"default\": \"./dist/utilities.cjs\"\n }\n },\n \"./uom\": {\n \"import\": {\n \"types\": \"./dist/uom.d.ts\",\n \"default\": \"./dist/uom.js\"\n },\n \"require\": {\n \"types\": \"./dist/uom.d.cts\",\n \"default\": \"./dist/uom.cjs\"\n }\n },\n \"./services\": {\n \"import\": {\n \"types\": \"./dist/services.d.ts\",\n \"default\": \"./dist/services.js\"\n },\n \"require\": {\n \"types\": \"./dist/services.d.cts\",\n \"default\": \"./dist/services.cjs\"\n }\n },\n \"./worker\": {\n \"import\": {\n \"types\": \"./dist/worker.d.ts\",\n \"default\": \"./dist/worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/worker.d.cts\",\n \"default\": \"./dist/worker.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepublishOnly\": \"npm run build && node ../../scripts/assert-publishable.mjs .\",\n \"dev\": \"tsup --watch\",\n \"test\": \"jest --config jest.config.cjs --no-coverage\",\n \"typecheck\": \"tsgo --noEmit --skipLibCheck\",\n \"typecheck:tsc\": \"tsc --noEmit --skipLibCheck\"\n },\n \"dependencies\": {\n \"@tanstack/query-core\": \"^5.100.10\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^30.4.1\",\n \"@types/node\": \"^26.2.0\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.4.2\",\n \"ts-jest\": \"^29.4.12\",\n \"tsup\": \"8.5.1\",\n \"typescript\": \"5.9.3\"\n },\n \"//sideEffects\": \"Load-bearing claim, not boilerplate. tsup's splitting emits bare chunk imports at the top of dist/index.js, and this field tells Rollup, webpack and Vite they may delete them, which esbuild reports as [ignored-bare-import] once per import during `npm run size`. The engine does have module-level work to lose: registerAllTokenTypes(), _PrecedenceParser.BP_TABLE and its cached token ids, and several process-wide registries. It is safe because every chunk doing that work is also imported for its bindings somewhere, so no bundler can drop it. That is a property of how tsup currently splits the code rather than a design guarantee, so `npm run smoke:bundled` (scripts/check-tree-shaking.mjs) proves it on every run of `npm run verify` instead of assuming it, and its header explains the two fixes if it ever stops holding.\",\n \"sideEffects\": false\n}\n","/**\n * The running engine's own semver version, sourced directly from this\n * package's package.json so it can never drift from what's actually\n * published. Exists so IEnginePackage.engineVersion range checks\n * (api/EngineVersionCompatibility.ts) have something real to check\n * against.\n */\nimport { version } from \"../../package.json\";\n\n/**\n * The running engine's version, taken from package.json.\n *\n * What a package's `engineVersion` range is checked against at registration.\n * A prerelease is compared by its coerced release version, so a 1.0.0 beta\n * satisfies `^1.0.0`. See `api/EngineVersionCompatibility.ts`.\n */\nexport const ENGINE_VERSION: string = version;\n","/**\n * Configuration Module for solve-js Engine\n * \n * This module provides the **single source of truth** for all engine configuration.\n * Every configurable aspect of the engine, from safety limits and performance\n * budgets to VM constraints and worker pool sizing, is defined here.\n * \n * ### Design principles\n * \n * 1. **Engine owns its config.** The engine defines its own config shape and defaults.\n * Consumers (e.g., the Obsidian plugin) pass partial overrides; all unspecified\n * fields fall back to `DEFAULT_CONFIG`.\n * \n * 2. **Self-documenting.** Every interface and field has descriptive JSDoc so the\n * config is understandable at a glance, whether you're using the engine as an\n * npm package or reading the source.\n * \n * 3. **Minimal consumer knowledge.** Consumers only need to pass `Partial<EngineConfig>`.\n * They don't need to replicate the full config shape, just the fields they\n * want to override.\n * \n * @module Configuration\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A host's test for whether a calendar date is a public holiday, given the\n * `Date` for that day at local midnight. Return `true` to exclude it from\n * working-day arithmetic.\n */\nexport type HolidayPredicate = (date: Date) => boolean;\n\n/**\n * The host-supplied public-holiday calendar, in the same \"bring your own data\"\n * shape the stocks and weather packages already use for a host callback (see\n * `packages/stocks/StocksPackage.ts`): weekends are decidable from the date\n * alone, holidays are not, so they come from the host or not at all.\n *\n * Either a {@link HolidayPredicate}, for a host that computes holidays itself\n * (an existing library, a region rule), or an iterable of specific dates as\n * `YYYY-MM-DD` strings, epoch-millisecond numbers or `Date` objects, for a host\n * that just has a list. Resolved to one internal predicate by\n * `vm/HolidayCalendar.ts`'s `resolveHolidayPredicate()`.\n *\n * Left unset, working-day arithmetic skips weekends only, which is the honest\n * default: the engine excludes exactly the days it can prove are non-working.\n */\nexport type HolidayCalendar = HolidayPredicate | Iterable<string | number | Date>;\n\n/**\n * Date-related configuration.\n * Controls the bounds and formatting for date/time expression evaluation\n * (e.g., `today + 20 days`, `last monday`).\n */\n/**\n * How an ambiguous all-numeric date literal is read.\n *\n * - `'auto'`: by separator, the historic behaviour. A slash date is\n * day-first (`25/12/2023`), a hyphen date is month-first (`12-25-2023`)\n * unless its first group is four digits, which makes it ISO (`2023-12-25`).\n * - `'DMY'` / `'MDY'` / `'YMD'`: a fixed order for every numeric separator, so\n * a host can match its readers' locale. `'MDY'` is what lets a US reader's\n * `12/25/2023` parse, which `'auto'` refuses because the slash defaults to\n * day-first.\n *\n * Only the all-numeric literals are affected. A spelled-out month (`March 9,\n * 2024`) is never ambiguous, and an ISO timestamp is always read as ISO.\n */\nexport type DateInputOrder = 'auto' | 'DMY' | 'MDY' | 'YMD';\n\n/** Date-related engine configuration: offset limits, input order, holidays. */\nexport interface DateConfig {\n /**\n * The order an ambiguous all-numeric date literal is read in. Defaults to\n * `'auto'` (by separator, the historic behaviour). See {@link DateInputOrder}.\n */\n readonly inputOrder: DateInputOrder;\n /**\n * How far forward a date offset whose COST grows with the offset may reach,\n * in years. Enforced by `vm/VM.ts`'s `addBusinessDays()`.\n *\n * Bounds the walk, not the calendar. Every other date offset in the engine\n * is arithmetic on a Date field, so `today + 100000 days` costs exactly what\n * one day costs and needs no ceiling; workdays are the one offset that has\n * to step day by day, because which days are skipped depends on where each\n * step lands. `today + 100000000 workdays` therefore froze the host for\n * thirteen seconds inside a single ADD opcode (where `vm.maxInstructions`\n * cannot see it) and then answered \"Invalid Date\", and a trillion never\n * returned at all.\n *\n * Release hardening: this field was declared, documented as a \"safety\n * limit\", and read nowhere, so it bounded nothing. A limit a host can\n * configure and the engine ignores is worse than no limit, because it reads\n * as protection that is not there.\n */\n readonly maxOffsetYears: number;\n /** How far BACK the same walk may reach, in years, as a negative number. See {@link maxOffsetYears}. */\n readonly minOffsetYears: number;\n /** Default date string format for display (moment.js format string) */\n readonly defaultFormat: string;\n /**\n * Public-holiday calendar for working-day arithmetic (`N working days after\n * <date>`, `working days between <date> and <date>`, `<date> + N workdays`).\n * See {@link HolidayCalendar}.\n *\n * Optional and unset by default: with no calendar, working-day arithmetic\n * skips weekends only. A host that wants holidays excluded too supplies one\n * here (`new ExpressionEngine({ config: { date: { holidays } } })`), the\n * same way stocks and weather take a host data source. Threaded into the VM\n * by `engine/ExpressionEngine.ts` exactly as {@link maxOffsetYears} is,\n * because working-day math is a VM operation several grammar forms share, so\n * the calendar has to be one source the VM owns rather than per-package state\n * the VM cannot see.\n */\n readonly holidays?: HolidayCalendar;\n}\n\n/**\n * Performance-related configuration.\n * Controls caching, timeouts, and processing limits to prevent runaway\n * resource consumption on large documents.\n */\nexport interface PerformanceConfig {\n /**\n * Maximum number of entries in {@link ExpressionEngine}'s bytecode cache\n * (per-instance, keyed by expression text) before the oldest entry is\n * evicted. Raise this for documents with many distinct expressions if\n * repeated re-evaluation (e.g. scrolling) is re-parsing instead of\n * hitting cache, bug fix (release hardening pass): this field used to\n * be read nowhere; the cache size was a hardcoded, unconfigurable\n * constant. Note this does NOT bound {@link LineCache}, which has no\n * size limit of its own.\n */\n readonly defaultCacheSize: number;\n /**\n * Maximum lines a document may have for the engine to process it in one\n * pass. Enforced by `ExpressionEngine.parseDocument()` and by\n * `engine/DocumentModel.ts`'s `setDocument()`, the two entry points that\n * take a whole document.\n *\n * A document costs memory per line whatever each line says: a parsed line\n * record, a cache entry, a dependency-graph node. Two hundred thousand\n * lines of `1 + 1` therefore exhausted the heap and aborted the process\n * before any per-line limit had anything to object to, which is the same\n * shape of hole as an unbounded expression and needs the same kind of\n * ceiling. Refusing the document names the limit; a host that genuinely has\n * a larger one raises this field.\n *\n * Release hardening: declared and read nowhere until now.\n */\n readonly maxDocumentLines: number;\n}\n\n/**\n * Validation / safety-limit configuration.\n * Protects against runaway expressions that could cause excessive memory use\n * or stack overflow. These limits are checked during lexing and parsing.\n */\n/** Bounds on untrusted input: expression length and nesting depth. */\nexport interface ValidationConfig {\n /** Maximum expression length in characters. Prevents excessively long strings from entering the pipeline. */\n readonly maxExpressionLength: number;\n /** Maximum expression complexity score (`tokens + functionCalls×5 + nestingDepth×10`). Protects against deeply nested or combinatorially complex expressions. */\n readonly maxComplexity: number;\n /** Maximum parentheses nesting depth. Prevents stack overflow in the recursive-descent parser. */\n readonly maxNestingDepth: number;\n /**\n * Auto-balance unmatched parentheses by appending missing closing parens\n * or prepending missing opening parens. When disabled, unbalanced expressions\n * cause parse errors instead of being silently corrected.\n *\n * Disabled by default for strict parsing. Enable for forgiving user input\n * (e.g., chat-style calculators where users often omit closing parens).\n * Has zero overhead when disabled, the O(n) paren-count scan is skipped.\n */\n readonly autoBalanceParens: boolean;\n}\n\n/**\n * Worker pool configuration.\n * Controls the parallel execution workers used for batch evaluation.\n */\nexport interface WorkerConfig {\n /** Maximum number of concurrent Web Workers allowed */\n readonly maxConcurrentWorkers: number;\n /** Time (ms) a worker stays alive while idle before being terminated */\n readonly idleTimeoutMs: number;\n /** Maximum retry attempts for a failed worker operation */\n readonly maxRetries: number;\n /** Base backoff delay (ms) between retries (exponential backoff applied on top) */\n readonly baseBackoffMs: number;\n} /**\n * Diagnostic / telemetry configuration.\n * Controls the diagnostic event pipeline for profiling and debugging.\n * All diagnostics are disabled by default for maximum production performance.\n */\n export interface DiagnosticConfig {\n /** Master switch: enable the diagnostic pipeline (collectors receive events for all pipeline stages) */\n readonly enabled: boolean;\n /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */\n readonly vmTraceEnabled: boolean;\n }\n\n /**\n * Proactive background refresh of live async values.\n *\n * Off by default. When a live value (a stock quote, an FX rate) has gone\n * stale, today it only refetches on the next re-evaluation (a keystroke), so a\n * note left open silently ages. With this enabled, the engine drives a refetch\n * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the\n * values currently on screen, and pushes the fresh result to the host through\n * the same event stream the pull path uses. It needs timers and a live editor\n * consuming that stream, so a headless or batch host leaves it off.\n */\n export interface BackgroundRefreshConfig {\n /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */\n readonly enabled: boolean;\n }\n\n /**\n * Whether the engine may reach the network at all.\n *\n * On by default, which is the historic behaviour: a city name or a currency\n * pair in a line fetches live data from a public endpoint as soon as the\n * line evaluates. A host embedding the engine somewhere that must not make\n * outbound requests (an offline document, a sandboxed evaluation, a tenant\n * with egress rules) switches it off here and gets the same engine with no\n * egress: every live-data form answers with a `NETWORK_DISABLED` error\n * naming the setting, instead of a request.\n *\n * The gate closes before any request is made. It stops every async\n * resolver a package registers (weather, currency, stocks, crypto,\n * knowledge, and any host-supplied one) unless the resolver declares\n * itself `local` (it reads engine state, never a network; the engine's own\n * global-variable resolver is the one built-in case). It also refuses the\n * result of a plugin function that returns a promise. That last case is a\n * boundary rather than a guarantee: such a function has already run by the\n * time the engine sees the promise, so a package that fetches inside a\n * plugin function rather than through an async resolver may still have\n * started its request. The documented shape for live data is the resolver\n * (`createQueryResolver`), which this gate stops cold.\n *\n * Rates a host primes by hand (`currencyExchangeService.primeRates`) keep\n * working with the network off, which is what an offline host with its own\n * rate table wants.\n */\n export interface NetworkConfig {\n /** Master switch. When false, no async resolver runs and no live value is fetched. */\n readonly enabled: boolean;\n }\n\n /**\n * Virtual Machine configuration.\n * Controls the internal bytecode VM that executes compiled expressions.\n */\n export interface VMConfig {\n /** Maximum stack depth (value slots) for VM execution, prevents stack overflow in recursive/pratt-parser generated bytecode */\n readonly maxStackDepth: number;\n /** Maximum opcodes executed per expression, halts runaway infinite loops */\n readonly maxInstructions: number;\n /**\n * Maximum elements a collection may be expanded to before `map`/`reduce`/\n * `sum`/`prod` will iterate it.\n *\n * A Range is stored as its two bounds and costs nothing until something\n * materializes it, at which point it becomes one Value per element. Twenty\n * characters (`sum(x, 1:100000000)`) therefore asked for a hundred million\n * of them, and neither `maxInstructions` nor `maxStackDepth` could see it:\n * the expansion happens inside a single opcode, so the instruction counter\n * is never consulted while it runs, and the elements never reach the value\n * stack. V8 aborted the whole process with \"Reached heap limit\", which a\n * host embedding the engine cannot catch.\n */\n readonly maxCollectionSize: number;\n /**\n * Maximum elements (collection Values, matrix cells) one evaluation may\n * materialize in total.\n *\n * `maxCollectionSize` above bounds a single collection. This bounds the sum\n * of everything an expression asks for, which is a different question and\n * the one that actually protects the host: two collections that are\n * individually legal are legal together, and an operation whose result is\n * the PRODUCT of two legal operands is bounded by neither of them. A matrix\n * multiply is exactly that shape, so three lines within every other limit\n * (`:a = map(1*x, 0:20000)`, `:b = transpose(a)`, `b * a`) asked for four\n * hundred million cells and aborted the process.\n *\n * Counted in elements rather than bytes, because a count is what a call\n * site has before it allocates. An element is 8 bytes as a numeric matrix\n * cell and closer to a hundred as a full Value, so the default is worth\n * roughly 16 MB of matrix or 200 MB of expanded collection: far past any\n * document and far short of what an editor cannot survive.\n */\n readonly maxAllocatedElements: number;\n /**\n * Maximum user-defined-function calls one evaluation may make in TOTAL,\n * however deeply or widely they nest.\n *\n * `maxFunctionRecursionDepth` bounds how DEEP calls nest and cannot see\n * how MANY there are, and those are different numbers. Twenty-two lines of\n * `f(n)(v) = f(n-1)(v) + f(n-1)(v)` reach a depth of only 22 against a\n * limit of 50, and make 2,097,152 calls doing it: a fatal heap abort in\n * under a second. `maxInstructions` cannot bound it either, because\n * `executeBytecode()` re-enters itself per call and each reentrant call\n * gets its OWN instruction count, so recursion refreshes its allowance on\n * the way in. This is the tally that does not refresh; see\n * `vm/AllocationBudget.ts`, which holds it for the same reason it holds\n * the element tally.\n *\n * Counted in calls rather than in the instructions they run, because the\n * call is the thing that multiplies: every call allocates a frame, its\n * arguments and its result whatever its body says.\n */\n readonly maxFunctionCalls: number;\n /**\n * Hard ceiling on how many bisection steps goal seek (`solve line N for\n * <var> = <target>`, see `packages/goalseek/`) may take before it gives up\n * with a structured error rather than continuing.\n *\n * Goal seek re-evaluates the target line's expression once per step while\n * narrowing an interval, and an untrusted document must never be able to\n * make that loop spin. `maxInstructions` bounds each individual\n * re-evaluation, but not how many of them the search performs, so this is\n * the tally that bounds the search itself, the same reason `maxFunctionCalls`\n * exists alongside `maxInstructions`. Bisection halves the interval every\n * step, so a hundred steps resolves an input to roughly one part in 2^100:\n * far past any precision a document needs, and a definite stop either way.\n */\n readonly maxGoalSeekIterations: number;\n }\n\n/**\n * Complete engine configuration.\n *\n * Every field has a default in `DEFAULT_CONFIG`. To customize, pass a\n * `Partial<EngineConfig>` when constructing `ExpressionEngine`. Only the\n * sections/fields you supply are overridden; all others use their defaults.\n *\n * @example\n * ```typescript\n * import { ExpressionEngine } from \"solve-js\";\n *\n * const engine = new ExpressionEngine({ config: {\n * validation: {\n * maxExpressionLength: 1000,\n * maxComplexity: 200,\n * },\n * // date, performance, vm, worker, diagnostic all use defaults\n * } });\n * ```\n */\nexport interface EngineConfig {\n /** Date/time expression evaluation bounds and formatting */\n readonly date: DateConfig;\n /** Performance budgets and cache sizing */\n readonly performance: PerformanceConfig;\n /** Safety limits for expression complexity */\n readonly validation: ValidationConfig;\n /** Internal bytecode VM configuration */\n readonly vm: VMConfig;\n /** Parallel worker pool configuration */\n readonly worker: WorkerConfig;\n /** Diagnostic pipeline configuration */\n readonly diagnostic: DiagnosticConfig;\n /** Proactive background refresh of live async values */\n readonly backgroundRefresh: BackgroundRefreshConfig;\n /** Whether live data may be fetched at all. See {@link NetworkConfig}. */\n readonly network: NetworkConfig;\n }\n\n/**\n * A partial {@link EngineConfig} override, one section at a time.\n *\n * Overrides are merged per section over {@link DEFAULT_CONFIG}, so you can set a\n * single field of one section (`{ validation: { maxExpressionLength: 1000 } }`)\n * and keep every other default in that section. A plain `Partial<EngineConfig>`\n * cannot express that, it demands a whole section object, which is why the\n * documented overrides never typechecked against it. This is the type the\n * constructor and {@link createEngine} accept.\n */\nexport type EngineConfigOverride = {\n readonly [K in keyof EngineConfig]?: Partial<EngineConfig[K]>;\n};\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: EngineConfig = {\n date: {\n // A century of workdays is about 26,000 steps, which is microseconds,\n // and past any offset a person means. The walk is what these bound; see\n // DateConfig above for why no other date offset needs a ceiling.\n maxOffsetYears: 100,\n minOffsetYears: -100,\n defaultFormat: 'YYYY-MM-DD',\n inputOrder: 'auto',\n },\n performance: {\n // Preserves the effective cache size the hardcoded (now-removed)\n // BYTECODE_CACHE_MAX_ENTRIES constant had, so wiring this field up\n // doesn't silently shrink the default cache for existing consumers.\n defaultCacheSize: 2000,\n // Raised from the 10,000 this field was declared with, which was never\n // enforced and turned out to be under what this engine already supports:\n // its paging design is tested against a 20,000-line document\n // (`engine/PageManager.ts` and its spec) and its throughput benchmark\n // parses a 50,000-line one. Twice the largest of those, and the same\n // number `ConfigManager.validate()` already refuses to go above.\n //\n // Measured under a 256MB heap: setting a 100,000-line document costs\n // 64MB, evaluating every line of a 20,000-line one costs 106MB, and\n // 200,000 lines aborts the process before a single expression is looked\n // at. A host with a small heap should lower this; the ceiling is here to\n // stop the size that cannot work anywhere.\n maxDocumentLines: 100000,\n },\n validation: {\n maxExpressionLength: 2000,\n maxComplexity: 500,\n maxNestingDepth: 50,\n autoBalanceParens: false,\n },\n vm: {\n maxStackDepth: 200,\n maxInstructions: 50000,\n // Two orders of magnitude above anything a person types by hand (the\n // longest range in the test suite is 1000 elements) and small enough\n // that expanding it is measured in milliseconds rather than in whether\n // the host survives.\n maxCollectionSize: 100000,\n // Twenty times the single-collection ceiling above, so an expression may\n // legitimately handle a number of large collections, and two hundred\n // times below the allocation that took the process down.\n maxAllocatedElements: 2000000,\n // Six hundred times the largest call count any test or example makes\n // (five levels of composition is sixteen calls), and small enough that\n // the calls it does allow cost single-digit megabytes rather than the\n // heap. A document that needs more than ten thousand calls on one line\n // is doing something a calculator was not built for.\n maxFunctionCalls: 10000,\n // A hundred bisection steps resolve an input to one part in 2^100, far\n // finer than any document needs and a firm stop for an untrusted one. A\n // continuous, monotonic relationship converges in tens of steps, well\n // under this; hitting it means the target is unreachable or the\n // relationship is not the smooth one goal seek assumes.\n maxGoalSeekIterations: 100,\n },\n worker: {\n maxConcurrentWorkers: 4,\n idleTimeoutMs: 30000,\n maxRetries: 3,\n baseBackoffMs: 1000,\n },\n diagnostic: {\n enabled: false,\n vmTraceEnabled: false,\n },\n backgroundRefresh: {\n enabled: false,\n },\n network: {\n // On, because it is what every existing consumer gets today. A host that\n // must not make outbound requests turns it off; see NetworkConfig.\n enabled: true,\n },\n };\n\n/**\n * Merge a partial config override onto a base `EngineConfig`, section by\n * section, `{ ...base.section, ...override.section }` for each of the 8\n * top-level sections, not a single top-level spread.\n *\n * A shallow `{ ...base, ...override }` at the TOP level replaces an entire\n * section wholesale the moment a caller overrides even one field in it\n * (e.g. `{ performance: { defaultCacheSize: 500 } }` would silently drop\n * every other `performance.*` field back to `undefined`, not to its\n * default). This function exists specifically so every config consumer\n * shares one correct merge instead of each hand-rolling (and risking) its\n * own. `ConfigManager` and `ExpressionEngine` both call this rather than\n * either duplicating the section list or instantiating a whole\n * `ConfigManager` just to reuse its private merge logic.\n */\nexport function mergeEngineConfig(\n base: EngineConfig,\n override: EngineConfigOverride\n): EngineConfig {\n return {\n date: { ...base.date, ...override.date },\n performance: { ...base.performance, ...override.performance },\n validation: { ...base.validation, ...override.validation },\n vm: { ...base.vm, ...override.vm },\n worker: { ...base.worker, ...override.worker },\n diagnostic: { ...base.diagnostic, ...override.diagnostic },\n backgroundRefresh: { ...base.backgroundRefresh, ...override.backgroundRefresh },\n network: { ...base.network, ...override.network },\n };\n}\n\n/**\n * Configuration manager for engine settings\n *\n * @example\n * ```typescript\n * const configManager = new ConfigManager();\n * configManager.set('performance.defaultCacheSize', 2000);\n * const cacheSize = configManager.get('performance.defaultCacheSize');\n * ```\n */\nexport class ConfigManager {\n private config: EngineConfig;\n\n constructor(config: Partial<EngineConfig> = {}) {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, config);\n }\n\n /**\n * Get configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @returns Configuration value\n */\n get<T>(path: string): T {\n const keys = path.split('.');\n let current: unknown = this.config;\n\n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PATH_NOT_FOUND\",\n `Configuration path not found: ${path}`,\n { path }\n );\n }\n }\n\n return current as T;\n }\n\n /**\n * Set configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @param value - New value\n */\n set<T>(path: string, value: T): void {\n const keys = path.split('.');\n if (keys.length < 2) {\n throw ErrorFactory.config(\n \"INVALID_CONFIG_PATH\",\n `Invalid path: ${path}. Must be in format 'section.property'`,\n { path }\n );\n }\n \n const section = keys[0];\n const property = keys[1];\n \n if (!(section in this.config)) {\n throw ErrorFactory.config(\n \"CONFIG_SECTION_NOT_FOUND\",\n `Configuration section not found: ${section}`,\n { section, path }\n );\n }\n \n const sectionConfig = this.config[section as keyof EngineConfig];\n if (sectionConfig && typeof sectionConfig === 'object') {\n (sectionConfig as unknown as Record<string, unknown>)[property] = value;\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PROPERTY_NOT_FOUND\",\n `Configuration property not found: ${path}`,\n { path }\n );\n }\n }\n\n /**\n * Get complete configuration.\n *\n * A detached copy, section objects included. A top-level spread would hand\n * the caller this manager's own section objects, so `getConfig().vm.x = 1`\n * would be an undeclared back door into {@link set}, bypassing its path\n * validation and reaching every later {@link get}.\n */\n getConfig(): EngineConfig {\n return mergeEngineConfig(this.config, {});\n }\n\n /**\n * Update multiple configuration values\n */\n update(config: Partial<EngineConfig>): void {\n this.config = mergeEngineConfig(this.config, config);\n }\n\n /**\n * Reset to default configuration.\n *\n * Goes through {@link mergeEngineConfig} for the same reason the constructor\n * does. A top-level `{ ...DEFAULT_CONFIG }` copies the six section\n * references, not the sections, so after a reset this manager's\n * `performance` object WAS `DEFAULT_CONFIG.performance` and the next\n * `set('performance.x', ...)` wrote into the module constant. That constant\n * is what every `ExpressionEngine` is built from, so one manager's reset\n * could change the cache size, instruction ceiling or allocation budget of\n * every engine constructed later in the process.\n */\n reset(): void {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, {});\n }\n\n /**\n * Validate configuration values\n */\n validate(): ValidationResult {\n const errors: string[] = [];\n\n // Validate performance config\n if (this.config.performance.maxDocumentLines > 100000) {\n errors.push('maxDocumentLines cannot exceed 100,000');\n }\n\n // Validate date config\n if (this.config.date.maxOffsetYears > 1000) {\n errors.push('maxOffsetYears cannot exceed 1000');\n }\n\n return {\n valid: errors.length === 0,\n error: errors.join('; '),\n warnings: []\n };\n }\n}\n\n/**\n * Result type for {@link ConfigManager.validate}.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {c as c$2}from'./chunk-JP4JMQOG.js';import {b,a as a$2,e,d}from'./chunk-O3BDXOQJ.js';import {c,a}from'./chunk-IJMNVBIS.js';import {a as a$1}from'./chunk-LHLW7JLS.js';import {c as c$1}from'./chunk-PIZQIQVM.js';var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",p){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r;let a=a$1(r).display;this.decimalSeparator=a.decimalSeparator,this.thousandsSeparator=a.thousandsSeparator,this.pluginFunctionIndex=p;}getLocaleCode(){return this.localeCode}setDiagnosticPipeline(e,t){this.diagnosticPipeline=e,this.currentExpression=t??"";}load(e,t){if(t===false){this.tokens=e,this.current=0,this.depth=0;return}let r=c(a.LPAREN),p=c(a.RPAREN),a$1=0;for(let l=0;l<e.length;l++)e[l].typeId===r?a$1++:e[l].typeId===p&&a$1--;this.tokens=a$1===0?e:this.balanceParens(e,a$1),this.current=0,this.depth=0;}balanceParens(e,t){let r=e.slice();if(t>0){let p=c(a.RPAREN);for(let a$1=0;a$1<t;a$1++){let l=e[e.length-1];r.push({type:a.RPAREN,typeId:p,value:")",text:")",offset:l?l.offset+l.text.length:0,lineBreaks:0,line:l?l.line:1,col:l?l.col+l.text.length:1});}}else if(t<0){let p=c(a.LPAREN);for(let a$1=0;a$1<-t;a$1++)r.unshift({type:a.LPAREN,typeId:p,value:"(",text:"(",offset:0,lineBreaks:0,line:1,col:1});}return r}parseExpression(e=0,t){if(t&&(this.builder=t),this.depth++,this.depth>this.maxDepth)throw this.depth--,c$1.parsing("NESTING_DEPTH_EXCEEDED",`Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,{maxDepth:this.maxDepth,currentDepth:this.depth});let r=this.consume();if(!r)throw this.depth--,c$1.parsing("UNEXPECTED_END","Unexpected end of expression");this.parsePrefix(r);let p=this.tokens,a=p.length,l=n.BP_TABLE,o=this.registry,c=this.builder,d=this.current;for(;d<a;){let h=p[d];if(!h)break;let I=l[h.typeId];if(I>0){if(I<=e)break;if(this.diagnosticPipeline){let m=o.getInfix(h.typeId);m&&this.fireParseletMatched(m,h,false,I);}this.current=++d;let f=h.typeId;if(f===n.PERCENT_ID)c.emitOpcode(10),c.emitNumber(100),c.emitOpcode(23),c.emitOpcode(74);else if(!(f===n.CARET_ID&&this.tryEmitMatrixCaretOp(c))){let m=f===n.CARET_ID?I-1:I+1;this.parseExpression(m,c),c.emitOpcode(n.INFIX_OPCODE[f]);}}else {let f=o.getInfix(h.typeId);if(!f||f.bindingPower<=e)break;this.current=++d,this.diagnosticPipeline&&this.fireParseletMatched(f,h,false,f.bindingPower),this.infixMinBindingPower=e,f.parse(this,r,h,c);}d=this.current;}this.current=d,this.depth--;}parsePrefix(e$1){let t=this.builder,r=e$1.typeId;if(this.diagnosticPipeline){let a=this.registry.getPrefix(r);a&&this.fireParseletMatched(a,e$1,true);}switch(r){case n.NUMBER_ID:{let a,l=null,o=e$1.value;if(this.decimalSeparator==="."){let c=0,d=o.length>0;for(let h=0;h<o.length;h++){let I=o.charCodeAt(h);if(!(I>=48&&I<=57)){if(I===46&&c===0){c=1;continue}d=false;break}}if(d){if(c===1){t.emitOpcode(16),t.emitString(o);return}t.emitOpcode(10),t.emitNumber(+o);return}}if(o.startsWith("0x")||o.startsWith("0X")){if(a=parseInt(o,16),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${o}"`,{raw:o})}else if(o.startsWith("0b")||o.startsWith("0B")){if(a=parseInt(o.slice(2),2),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${o}"`,{raw:o})}else if(o.startsWith("0o")||o.startsWith("0O")){if(a=parseInt(o.slice(2),8),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${o}"`,{raw:o})}else if(D.test(o))a=parseFloat(o.split(".").join(""));else {let c=this.decimalSeparator,d=this.thousandsSeparator,h=o;d&&h.indexOf(d)!==-1&&(h=h.split(d).join("")),c&&c!=="."&&(h=h.replace(c,".")),a=parseFloat(h),T.test(h)&&(l=h);}if(l!==null){t.emitOpcode(16),t.emitString(l);return}t.emitOpcode(10),t.emitNumber(a);return}case n.BIGINT_ID:{t.emitOpcode(11),t.emitString(e(e$1.value,this.localeCode));return}case n.STRING_ID:{t.emitOpcode(13),t.emitString(e$1.value);return}case n.IDENT_ID:{if(this.peek()?.typeId===n.LPAREN_ID){this.parseUserFunctionDefOrCall(e$1,t);return}t.emitOpcode(60),t.emitString(e$1.value);return}case n.LPAREN_ID:{this.parseExpression(0,t);let a$1=1;for(;this.match(a.COMMA);)this.parseExpression(0,t),a$1++;this.consume(a.RPAREN),a$1>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(a$1));return}case n.MINUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let p=this.registry.getPrefix(r);if(!p)throw c$1.parsing("NO_PREFIX_PARSELET",`No prefix parselet found for token: ${e$1.type} ("${e$1.value}")`,{tokenType:e$1.type,tokenValue:e$1.value});p.parse(this,e$1,t);}tryEmitMatrixCaretOp(e){for(let t of n.CARET_SUFFIX_RULES)if(t.matches(this))return t.emit(this,e),true;return false}findMatchingRParen(e){let t=0;for(let r=e;r<this.tokens.length;r++){let p=this.tokens[r];if(p.typeId===n.LPAREN_ID)t++;else if(p.typeId===n.RPAREN_ID&&(t--,t===0))return r}return null}parseUserFunctionDefOrCall(e,t){let r=this.findMatchingRParen(this.current);if(r===null){t.emitOpcode(60),t.emitString(e.value);return}this.tokens[r+1]?.type===a.EQUALS?this.parseUserFunctionDefinition(e,t):this.parseUserFunctionCall(e,t);}consumeParamName(){let e=this.peek();if(e?.type===a.IDENT||e?.type===a.UNIT)return this.consume(),e.value;throw c$1.parsing("USER_FUNCTION_INVALID_PARAM_NAME",`Expected a parameter name but got "${e?.type??"end of input"}"${e?` ("${e.value}")`:""}`,{actualType:e?.type})}parseUserFunctionDefinition(e,t){this.consume(a.LPAREN);let r=[];if(this.peek()?.type!==a.RPAREN)for(r.push(this.consumeParamName());this.match(a.COMMA);)r.push(this.consumeParamName());if(this.consume(a.RPAREN),this.consume(a.EQUALS),r.length===0)throw c$1.parsing("USER_FUNCTION_NO_PARAMS",`"${e.value}()" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,{name:e.value});let p=new d(this.pluginFunctionIndex);this.parseExpression(a$2.Lowest,p),this.setBuilder(t);let a$1=p.build();if(a$1.hasAsync)throw c$1.parsing("FUNCTION_BODY_MUST_BE_SYNCHRONOUS",`"${e.value}(...)"'s body calls an async operation (weather, stocks, currency, ...) \u2014 user-defined function bodies must be synchronous`,{name:e.value});let l=t.emitUserFunctionBody(e.value,r,a$1);t.emitOpcode(150),t.emitIndex(l),t.emitOpcode(13),t.emitString(`${e.value}(${r.join(", ")}) defined`);}parseUserFunctionCall(e,t){this.consume(a.LPAREN);let r=0;if(this.peek()?.type!==a.RPAREN)for(this.parseExpression(a$2.Lowest,t),r++;this.match(a.COMMA);)this.parseExpression(a$2.Lowest,t),r++;this.consume(a.RPAREN),t.emitOpcode(151),t.emitString(e.value),t.emitByte(r);}consume(e){let t=this.tokens[this.current];if(!t)throw c$1.parsing("UNEXPECTED_END_OF_INPUT","Unexpected end of input");if(e!==void 0){let r=c(e);if(t.typeId!==r)throw c$1.parsing("UNEXPECTED_TOKEN_TYPE",`Expected token type "${e}" but got "${t.type}" ("${t.value}")`,{expectedType:e,actualType:t.type,actualValue:t.value})}return this.current++,t}match(e){let t=this.peek();return t&&t.typeId===c(e)?(this.advance(),true):false}peek(){return this.tokens[this.current]}peekAt(e){return this.tokens[this.current+e]}previous(){return this.current>0?this.tokens[this.current-1]:void 0}advance(){this.current++;}setBuilder(e){this.builder=e;}fireParseletMatched(e,t,r,p){let a=this.diagnosticPipeline,l={type:c$2.ParseletMatched,elapsedNs:0,expression:this.currentExpression,tokenType:t.type,tokenValue:t.value,parseletCategory:e.category,parseletType:e.constructor?.name??"unknown",isPrefix:r,bindingPower:p,tokenOffset:t.offset||0};a.fireParseletMatched(l);}};n.BP_TABLE=b(),n.NUMBER_ID=c(a.NUMBER),n.BIGINT_ID=c(a.BIGINT),n.STRING_ID=c(a.STRING),n.IDENT_ID=c(a.IDENT),n.LPAREN_ID=c(a.LPAREN),n.RPAREN_ID=c(a.RPAREN),n.MINUS_ID=c(a.MINUS),n.PLUS_ID=c(a.PLUS),n.KEYWORD_ID=c(a.KEYWORD),n.STAR_ID=c(a.STAR),n.SLASH_ID=c(a.SLASH),n.MOD_ID=c(a.MOD),n.CARET_ID=c(a.CARET),n.LSHIFT_ID=c(a.LSHIFT),n.RSHIFT_ID=c(a.RSHIFT),n.URSHIFT_ID=c(a.URSHIFT),n.BIT_AND_ID=c(a.BIT_AND),n.BIT_OR_ID=c(a.BIT_OR),n.BIT_XOR_ID=c(a.BIT_XOR),n.PERCENT_ID=c(a.PERCENT),n.OF_ID=c(a.OF),n.INFIX_OPCODE={[c(a.PLUS)]:20,[c(a.MINUS)]:21,[c(a.STAR)]:22,[c(a.SLASH)]:23,[c(a.MOD)]:24,[c(a.CARET)]:25,[c(a.LSHIFT)]:30,[c(a.RSHIFT)]:31,[c(a.URSHIFT)]:32,[c(a.BIT_AND)]:33,[c(a.BIT_OR)]:34,[c(a.BIT_XOR)]:35,[c(a.OF)]:22},n.CARET_SUFFIX_RULES=[{name:"transpose (^T)",matches:e=>{let t=e.peek();return t?.type===a.IDENT&&t.value==="T"},emit:(e,t)=>{e.advance(),t.emitOpcode(51),t.emitIndex(63),t.emitIndex(1);}},{name:"inverse (^-1)",matches:e=>{if(e.peek()?.typeId!==n.MINUS_ID)return false;let r=e.peekAt(1);return r?.type===a.NUMBER&&r.value==="1"},emit:(e,t)=>{e.advance(),e.advance(),t.emitOpcode(51),t.emitIndex(65),t.emitIndex(1);}}];var v=n;var y=class{constructor(){this.prefixParselets=new Map;this.infixParselets=new Map;this.prefixById=new Map;this.infixById=new Map;}registerPrefix(e,t){let r=this.prefixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Prefix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.prefixParselets.set(e,t),this.prefixById.set(c(e),t);}registerInfix(e,t){let r=this.infixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Infix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.infixParselets.set(e,t),this.infixById.set(c(e),t);}getAllPrefix(){let e=[];for(let[t,r]of this.prefixParselets)e.push({tokenType:t,bindingPower:r.bindingPower??a$2.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let p=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:p,rightBindingPower:p+1,category:r.category});}return e}get prefixCount(){return this.prefixParselets.size}get infixCount(){return this.infixParselets.size}getPrefix(e){return typeof e=="number"?this.prefixById.get(e):this.prefixParselets.get(e)}getInfix(e){return typeof e=="number"?this.infixById.get(e):this.infixParselets.get(e)}hasPrefix(e){return this.prefixParselets.has(e)}hasInfix(e){return this.infixParselets.has(e)}clear(){this.prefixParselets.clear(),this.infixParselets.clear(),this.prefixById.clear(),this.infixById.clear();}},H=new y;export{v as a,y as b,H as c};//# sourceMappingURL=chunk-JVMINMAB.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {c as c$2}from'./chunk-JP4JMQOG.js';import {b,a as a$2,e,d}from'./chunk-RENO2AWO.js';import {c,a}from'./chunk-IJMNVBIS.js';import {a as a$1}from'./chunk-LHLW7JLS.js';import {c as c$1}from'./chunk-BDF4VCQX.js';var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",p){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r;let a=a$1(r).display;this.decimalSeparator=a.decimalSeparator,this.thousandsSeparator=a.thousandsSeparator,this.pluginFunctionIndex=p;}getLocaleCode(){return this.localeCode}setDiagnosticPipeline(e,t){this.diagnosticPipeline=e,this.currentExpression=t??"";}load(e,t){if(t===false){this.tokens=e,this.current=0,this.depth=0;return}let r=c(a.LPAREN),p=c(a.RPAREN),a$1=0;for(let l=0;l<e.length;l++)e[l].typeId===r?a$1++:e[l].typeId===p&&a$1--;this.tokens=a$1===0?e:this.balanceParens(e,a$1),this.current=0,this.depth=0;}balanceParens(e,t){let r=e.slice();if(t>0){let p=c(a.RPAREN);for(let a$1=0;a$1<t;a$1++){let l=e[e.length-1];r.push({type:a.RPAREN,typeId:p,value:")",text:")",offset:l?l.offset+l.text.length:0,lineBreaks:0,line:l?l.line:1,col:l?l.col+l.text.length:1});}}else if(t<0){let p=c(a.LPAREN);for(let a$1=0;a$1<-t;a$1++)r.unshift({type:a.LPAREN,typeId:p,value:"(",text:"(",offset:0,lineBreaks:0,line:1,col:1});}return r}parseExpression(e=0,t){if(t&&(this.builder=t),this.depth++,this.depth>this.maxDepth)throw this.depth--,c$1.parsing("NESTING_DEPTH_EXCEEDED",`Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,{maxDepth:this.maxDepth,currentDepth:this.depth});let r=this.consume();if(!r)throw this.depth--,c$1.parsing("UNEXPECTED_END","Unexpected end of expression");this.parsePrefix(r);let p=this.tokens,a=p.length,l=n.BP_TABLE,o=this.registry,c=this.builder,d=this.current;for(;d<a;){let h=p[d];if(!h)break;let I=l[h.typeId];if(I>0){if(I<=e)break;if(this.diagnosticPipeline){let m=o.getInfix(h.typeId);m&&this.fireParseletMatched(m,h,false,I);}this.current=++d;let f=h.typeId;if(f===n.PERCENT_ID)c.emitOpcode(10),c.emitNumber(100),c.emitOpcode(23),c.emitOpcode(74);else if(!(f===n.CARET_ID&&this.tryEmitMatrixCaretOp(c))){let m=f===n.CARET_ID?I-1:I+1;this.parseExpression(m,c),c.emitOpcode(n.INFIX_OPCODE[f]);}}else {let f=o.getInfix(h.typeId);if(!f||f.bindingPower<=e)break;this.current=++d,this.diagnosticPipeline&&this.fireParseletMatched(f,h,false,f.bindingPower),this.infixMinBindingPower=e,f.parse(this,r,h,c);}d=this.current;}this.current=d,this.depth--;}parsePrefix(e$1){let t=this.builder,r=e$1.typeId;if(this.diagnosticPipeline){let a=this.registry.getPrefix(r);a&&this.fireParseletMatched(a,e$1,true);}switch(r){case n.NUMBER_ID:{let a,l=null,o=e$1.value;if(this.decimalSeparator==="."){let c=0,d=o.length>0;for(let h=0;h<o.length;h++){let I=o.charCodeAt(h);if(!(I>=48&&I<=57)){if(I===46&&c===0){c=1;continue}d=false;break}}if(d){if(c===1){t.emitOpcode(16),t.emitString(o);return}t.emitOpcode(10),t.emitNumber(+o);return}}if(o.startsWith("0x")||o.startsWith("0X")){if(a=parseInt(o,16),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${o}"`,{raw:o})}else if(o.startsWith("0b")||o.startsWith("0B")){if(a=parseInt(o.slice(2),2),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${o}"`,{raw:o})}else if(o.startsWith("0o")||o.startsWith("0O")){if(a=parseInt(o.slice(2),8),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${o}"`,{raw:o})}else if(D.test(o))a=parseFloat(o.split(".").join(""));else {let c=this.decimalSeparator,d=this.thousandsSeparator,h=o;d&&h.indexOf(d)!==-1&&(h=h.split(d).join("")),c&&c!=="."&&(h=h.replace(c,".")),a=parseFloat(h),T.test(h)&&(l=h);}if(l!==null){t.emitOpcode(16),t.emitString(l);return}t.emitOpcode(10),t.emitNumber(a);return}case n.BIGINT_ID:{t.emitOpcode(11),t.emitString(e(e$1.value,this.localeCode));return}case n.STRING_ID:{t.emitOpcode(13),t.emitString(e$1.value);return}case n.IDENT_ID:{if(this.peek()?.typeId===n.LPAREN_ID){this.parseUserFunctionDefOrCall(e$1,t);return}t.emitOpcode(60),t.emitString(e$1.value);return}case n.LPAREN_ID:{this.parseExpression(0,t);let a$1=1;for(;this.match(a.COMMA);)this.parseExpression(0,t),a$1++;this.consume(a.RPAREN),a$1>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(a$1));return}case n.MINUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let p=this.registry.getPrefix(r);if(!p)throw c$1.parsing("NO_PREFIX_PARSELET",`No prefix parselet found for token: ${e$1.type} ("${e$1.value}")`,{tokenType:e$1.type,tokenValue:e$1.value});p.parse(this,e$1,t);}tryEmitMatrixCaretOp(e){for(let t of n.CARET_SUFFIX_RULES)if(t.matches(this))return t.emit(this,e),true;return false}findMatchingRParen(e){let t=0;for(let r=e;r<this.tokens.length;r++){let p=this.tokens[r];if(p.typeId===n.LPAREN_ID)t++;else if(p.typeId===n.RPAREN_ID&&(t--,t===0))return r}return null}parseUserFunctionDefOrCall(e,t){let r=this.findMatchingRParen(this.current);if(r===null){t.emitOpcode(60),t.emitString(e.value);return}this.tokens[r+1]?.type===a.EQUALS?this.parseUserFunctionDefinition(e,t):this.parseUserFunctionCall(e,t);}consumeParamName(){let e=this.peek();if(e?.type===a.IDENT||e?.type===a.UNIT)return this.consume(),e.value;throw c$1.parsing("USER_FUNCTION_INVALID_PARAM_NAME",`Expected a parameter name but got "${e?.type??"end of input"}"${e?` ("${e.value}")`:""}`,{actualType:e?.type})}parseUserFunctionDefinition(e,t){this.consume(a.LPAREN);let r=[];if(this.peek()?.type!==a.RPAREN)for(r.push(this.consumeParamName());this.match(a.COMMA);)r.push(this.consumeParamName());if(this.consume(a.RPAREN),this.consume(a.EQUALS),r.length===0)throw c$1.parsing("USER_FUNCTION_NO_PARAMS",`"${e.value}()" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,{name:e.value});let p=new d(this.pluginFunctionIndex);this.parseExpression(a$2.Lowest,p),this.setBuilder(t);let a$1=p.build();if(a$1.hasAsync)throw c$1.parsing("FUNCTION_BODY_MUST_BE_SYNCHRONOUS",`"${e.value}(...)"'s body calls an async operation (weather, stocks, currency, ...) \u2014 user-defined function bodies must be synchronous`,{name:e.value});let l=t.emitUserFunctionBody(e.value,r,a$1);t.emitOpcode(150),t.emitIndex(l),t.emitOpcode(13),t.emitString(`${e.value}(${r.join(", ")}) defined`);}parseUserFunctionCall(e,t){this.consume(a.LPAREN);let r=0;if(this.peek()?.type!==a.RPAREN)for(this.parseExpression(a$2.Lowest,t),r++;this.match(a.COMMA);)this.parseExpression(a$2.Lowest,t),r++;this.consume(a.RPAREN),t.emitOpcode(151),t.emitString(e.value),t.emitByte(r);}consume(e){let t=this.tokens[this.current];if(!t)throw c$1.parsing("UNEXPECTED_END_OF_INPUT","Unexpected end of input");if(e!==void 0){let r=c(e);if(t.typeId!==r)throw c$1.parsing("UNEXPECTED_TOKEN_TYPE",`Expected token type "${e}" but got "${t.type}" ("${t.value}")`,{expectedType:e,actualType:t.type,actualValue:t.value})}return this.current++,t}match(e){let t=this.peek();return t&&t.typeId===c(e)?(this.advance(),true):false}peek(){return this.tokens[this.current]}peekAt(e){return this.tokens[this.current+e]}previous(){return this.current>0?this.tokens[this.current-1]:void 0}advance(){this.current++;}setBuilder(e){this.builder=e;}fireParseletMatched(e,t,r,p){let a=this.diagnosticPipeline,l={type:c$2.ParseletMatched,elapsedNs:0,expression:this.currentExpression,tokenType:t.type,tokenValue:t.value,parseletCategory:e.category,parseletType:e.constructor?.name??"unknown",isPrefix:r,bindingPower:p,tokenOffset:t.offset||0};a.fireParseletMatched(l);}};n.BP_TABLE=b(),n.NUMBER_ID=c(a.NUMBER),n.BIGINT_ID=c(a.BIGINT),n.STRING_ID=c(a.STRING),n.IDENT_ID=c(a.IDENT),n.LPAREN_ID=c(a.LPAREN),n.RPAREN_ID=c(a.RPAREN),n.MINUS_ID=c(a.MINUS),n.PLUS_ID=c(a.PLUS),n.KEYWORD_ID=c(a.KEYWORD),n.STAR_ID=c(a.STAR),n.SLASH_ID=c(a.SLASH),n.MOD_ID=c(a.MOD),n.CARET_ID=c(a.CARET),n.LSHIFT_ID=c(a.LSHIFT),n.RSHIFT_ID=c(a.RSHIFT),n.URSHIFT_ID=c(a.URSHIFT),n.BIT_AND_ID=c(a.BIT_AND),n.BIT_OR_ID=c(a.BIT_OR),n.BIT_XOR_ID=c(a.BIT_XOR),n.PERCENT_ID=c(a.PERCENT),n.OF_ID=c(a.OF),n.INFIX_OPCODE={[c(a.PLUS)]:20,[c(a.MINUS)]:21,[c(a.STAR)]:22,[c(a.SLASH)]:23,[c(a.MOD)]:24,[c(a.CARET)]:25,[c(a.LSHIFT)]:30,[c(a.RSHIFT)]:31,[c(a.URSHIFT)]:32,[c(a.BIT_AND)]:33,[c(a.BIT_OR)]:34,[c(a.BIT_XOR)]:35,[c(a.OF)]:22},n.CARET_SUFFIX_RULES=[{name:"transpose (^T)",matches:e=>{let t=e.peek();return t?.type===a.IDENT&&t.value==="T"},emit:(e,t)=>{e.advance(),t.emitOpcode(51),t.emitIndex(63),t.emitIndex(1);}},{name:"inverse (^-1)",matches:e=>{if(e.peek()?.typeId!==n.MINUS_ID)return false;let r=e.peekAt(1);return r?.type===a.NUMBER&&r.value==="1"},emit:(e,t)=>{e.advance(),e.advance(),t.emitOpcode(51),t.emitIndex(65),t.emitIndex(1);}}];var v=n;var y=class{constructor(){this.prefixParselets=new Map;this.infixParselets=new Map;this.prefixById=new Map;this.infixById=new Map;}registerPrefix(e,t){let r=this.prefixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Prefix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.prefixParselets.set(e,t),this.prefixById.set(c(e),t);}registerInfix(e,t){let r=this.infixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Infix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.infixParselets.set(e,t),this.infixById.set(c(e),t);}getAllPrefix(){let e=[];for(let[t,r]of this.prefixParselets)e.push({tokenType:t,bindingPower:r.bindingPower??a$2.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let p=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:p,rightBindingPower:p+1,category:r.category});}return e}get prefixCount(){return this.prefixParselets.size}get infixCount(){return this.infixParselets.size}getPrefix(e){return typeof e=="number"?this.prefixById.get(e):this.prefixParselets.get(e)}getInfix(e){return typeof e=="number"?this.infixById.get(e):this.infixParselets.get(e)}hasPrefix(e){return this.prefixParselets.has(e)}hasInfix(e){return this.infixParselets.has(e)}clear(){this.prefixParselets.clear(),this.infixParselets.clear(),this.prefixById.clear(),this.infixById.clear();}},H=new y;export{v as a,y as b,H as c};//# sourceMappingURL=chunk-WFOQRPA6.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-WFOQRPA6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/PrecedenceParser.ts","../src/parser/registry/ParseletRegistry.ts"],"names":["CHAINED_DOT_THOUSANDS_GROUPS","PLAIN_DECIMAL","_PrecedenceParser","parseletRegistry","maxDepth","localeCode","pluginFunctionIndex","display","getLocale","pipeline","expression","tokens","hasParens","LPAREN_ID","tokenTypeId","TokenTypes","RPAREN_ID","openCount","i","result","lastToken","minBp","_builder","ErrorFactory","token","len","bpTable","registry","builder","idx","lookahead","bp","infixParselet","typeId","rightBp","parselet","v","decimalText","raw","dots","plain","c","decimalSep","thousandsSep","normalized","bigIntLiteralDigits","count","BindingPower","prefixParselet","rule","openIdx","depth","t","nameToken","closeIdx","params","bodyBuilder","BytecodeBuilder","bodyProgram","bodyIdx","argCount","expectedType","expectedId","offset","isPrefix","bindingPower","event","DiagnosticEventType","buildBindingPowerTable","p","next","afterMinus","PrecedenceParser","ParseletRegistry","tokenType","existing","left","sharedParseletRegistry"],"mappings":"wNAmBA,IAAMA,CAAAA,CAA+B,wBAAA,CAU/BC,CAAAA,CAAgB,YAAA,CAqBTC,CAAAA,CAAN,MAAMA,CAAiB,CAwF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,IAAA,CAAMC,CAAAA,CAAmD,CAvFrI,IAAA,CAAQ,MAAA,CAAkB,EAAC,CAC3B,IAAA,CAAQ,OAAA,CAAU,CAAA,CAClB,IAAA,CAAQ,KAAA,CAAQ,CAAA,CAWhB,IAAA,CAAQ,iBAAA,CAA4B,EAAA,CAiBpC,IAAA,CAAA,oBAAA,CAAuB,CAAA,CA0DrB,IAAA,CAAK,QAAA,CAAWH,CAAAA,CAChB,IAAA,CAAK,QAAA,CAAWC,CAAAA,CAChB,IAAA,CAAK,UAAA,CAAaC,CAAAA,CAIlB,IAAME,CAAAA,CAAUC,GAAAA,CAAUH,CAAU,CAAA,CAAE,OAAA,CACtC,IAAA,CAAK,gBAAA,CAAmBE,CAAAA,CAAQ,gBAAA,CAChC,IAAA,CAAK,kBAAA,CAAq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A,CAAmBA,CAAAA,CAAO,CAAA,CAC1B,QAAA,CAAUzC,CAAAA,CAAS,QACpB,CAAC,EACF,CACA,OAAOhB,CACR,CAGA,IAAI,WAAA,EAAsB,CAAE,OAAO,IAAA,CAAK,eAAA,CAAgB,IAAM,CAG9D,IAAI,UAAA,EAAqB,CAAE,OAAO,IAAA,CAAK,cAAA,CAAe,IAAM,CAO5D,SAAA,CAAUuD,CAAAA,CAAwD,CACjE,OAAI,OAAOA,CAAAA,EAAc,QAAA,CAAiB,IAAA,CAAK,UAAA,CAAW,GAAA,CAAIA,CAAS,CAAA,CAChE,IAAA,CAAK,eAAA,CAAgB,GAAA,CAAIA,CAAS,CAC1C,CAMA,QAAA,CAASA,CAAAA,CAAuD,CAC/D,OAAI,OAAOA,CAAAA,EAAc,QAAA,CAAiB,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAS,CAAA,CAC/D,IAAA,CAAK,cAAA,CAAe,GAAA,CAAIA,CAAS,CACzC,CAEA,SAAA,CAAUA,CAAAA,CAA4B,CACrC,OAAO,IAAA,CAAK,eAAA,CAAgB,GAAA,CAAIA,CAAS,CAC1C,CAEA,QAAA,CAASA,CAAAA,CAA4B,CACpC,OAAO,IAAA,CAAK,cAAA,CAAe,GAAA,CAAIA,CAAS,CACzC,CAEA,KAAA,EAAc,CACb,IAAA,CAAK,eAAA,CAAgB,KAAA,EAAM,CAC3B,IAAA,CAAK,cAAA,CAAe,KAAA,EAAM,CAC1B,IAAA,CAAK,UAAA,CAAW,KAAA,EAAM,CACtB,IAAA,CAAK,SAAA,CAAU,KAAA,GAChB,CACD,CAAA,CAUaG,EAAyB,IAAIJ","file":"chunk-JVMINMAB.js","sourcesContent":["import { ParseletRegistry } from \"@solve-js/parser/registry/ParseletRegistry\";\nimport { Token, tokenTypeId, TokenTypes } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DiagnosticPipeline, DiagnosticEventType, type DiagnosticEvent } from \"@solve-js/diagnostics\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower, buildBindingPowerTable } from \"@solve-js/parser/BindingPower\";\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { bigIntLiteralDigits } from \"@solve-js/parser/BigIntLiteral\";\n\n/**\n * Matches a CHAINED thousands-grouped integer using \".\" as the group\n * separator (e.g. \"1.234.567\"), independent of locale. Kept in sync with\n * the identical constant in NumberParselet.ts (not imported from there\n * that file transitively re-imports PrecedenceParser via Parser.ts's\n * `export { PrecedenceParser as Parser }`, so importing the other\n * direction would create a circular dependency for the sake of one\n * regex literal). See NumberParselet.ts's copy for the full explanation.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/**\n * A plain fractional literal: digits, exactly one dot, digits, nothing else.\n *\n * The gate for compiling to PUSH_DECIMAL. It admits \"0.10\", \"1.005\", \".5\" and\n * \"5.\" and refuses anything with an exponent (\"2.5e-3\"), which parses as an\n * ordinary double instead, since scientific notation has no exact base-ten\n * value this representation would keep.\n */\nconst PLAIN_DECIMAL = /^\\d*\\.\\d*$/;\n\n/**\n * ── Hybrid Precedence Climbing Parser ─────────────────────────────────────────\n *\n * Two-tier dispatch strategy:\n *\n * Tier 1 (Fast Path): Inline switch on token.typeId for built-in operators.\n * - Prefix: NUMBER, IDENT, LPAREN, MINUS, PLUS, STRING\n * - Infix: checked via static BP_TABLE (Uint8Array indexed by typeId)\n * - No Map.get(), no parselet function call overhead for ~95% of tokens\n *\n * Tier 2 (Plugin Path): ParseletRegistry fallback for custom/plugin tokens.\n * - Prefix: Map.get(tokenTypeId) for PrefixParselet\n * - Infix: Map.get(tokenTypeId) for InfixParselet\n * - Full flexibility for custom syntax\n *\n * The parser emits directly to a BytecodeBuilder, no AST intermediate.\n * Implements the same public API as the legacy Parser class so existing\n * parselets continue to work without modification.\n */\nexport class PrecedenceParser {\n private tokens: Token[] = [];\n private current = 0;\n private depth = 0;\n private maxDepth: number;\n\n /** Cached registry reference, avoids property chain in hot loop */\n private registry: ParseletRegistry;\n\n /** BytecodeBuilder, set before each parseExpression call */\n private builder!: BytecodeBuilder;\n\n /** Diagnostic pipeline for parselet-matched events */\n private diagnosticPipeline: DiagnosticPipeline | undefined;\n private currentExpression: string = \"\";\n private localeCode: string;\n\n /** The locale's decimal separator, cached from {@link localeCode}. */\n private readonly decimalSeparator: string;\n\n /** The locale's thousands separator, cached from {@link localeCode}. */\n private readonly thousandsSeparator: string;\n\n /**\n * The binding power the current infix parselet is being invoked at, i.e. the\n * `minBp` of the expression it sits inside. Set immediately before each Tier-2\n * parselet runs. A parselet that decides whether to swallow a following\n * loose operator (UomLiteralParselet with a trailing `in`/`to`) reads this to\n * respect precedence it cannot otherwise see: `120 km / 2 hours in kph` must\n * group as `(120 km / 2 hours) in kph`, not `120 km / (2 hours in kph)`.\n */\n infixMinBindingPower = 0;\n\n /**\n * Static binding power table, built once at module load, shared across all instances.\n * Index = tokenTypeId, value = binding power (0 = not a built-in infix).\n */\n static readonly BP_TABLE: Uint8Array = buildBindingPowerTable();\n\n // ── Pre-computed token type IDs for inline dispatch ────────────────────────\n // Prefix built-ins\n private static readonly NUMBER_ID = tokenTypeId(TokenTypes.NUMBER);\n private static readonly BIGINT_ID = tokenTypeId(TokenTypes.BIGINT);\n private static readonly STRING_ID = tokenTypeId(TokenTypes.STRING);\n private static readonly IDENT_ID = tokenTypeId(TokenTypes.IDENT);\n private static readonly LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n private static readonly RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n private static readonly MINUS_ID = tokenTypeId(TokenTypes.MINUS);\n private static readonly PLUS_ID = tokenTypeId(TokenTypes.PLUS);\n private static readonly KEYWORD_ID = tokenTypeId(TokenTypes.KEYWORD);\n\n // Infix built-ins (Tier 1, full inline emission)\n private static readonly STAR_ID = tokenTypeId(TokenTypes.STAR);\n private static readonly SLASH_ID = tokenTypeId(TokenTypes.SLASH);\n private static readonly MOD_ID = tokenTypeId(TokenTypes.MOD);\n private static readonly CARET_ID = tokenTypeId(TokenTypes.CARET);\n private static readonly LSHIFT_ID = tokenTypeId(TokenTypes.LSHIFT);\n private static readonly RSHIFT_ID = tokenTypeId(TokenTypes.RSHIFT);\n private static readonly URSHIFT_ID = tokenTypeId(TokenTypes.URSHIFT);\n private static readonly BIT_AND_ID = tokenTypeId(TokenTypes.BIT_AND);\n private static readonly BIT_OR_ID = tokenTypeId(TokenTypes.BIT_OR);\n private static readonly BIT_XOR_ID = tokenTypeId(TokenTypes.BIT_XOR);\n private static readonly PERCENT_ID = tokenTypeId(TokenTypes.PERCENT);\n private static readonly OF_ID = tokenTypeId(TokenTypes.OF);\n\n /**\n * Inline opcode map for Tier 1 infix operators.\n * tokenTypeId → OpCode. PERCENT and CARET are handled specially (not in this map).\n */\n private static readonly INFIX_OPCODE: Record<number, OpCode> = {\n [tokenTypeId(TokenTypes.PLUS)]: OpCode.ADD,\n [tokenTypeId(TokenTypes.MINUS)]: OpCode.SUB,\n [tokenTypeId(TokenTypes.STAR)]: OpCode.MUL,\n [tokenTypeId(TokenTypes.SLASH)]: OpCode.DIV,\n [tokenTypeId(TokenTypes.MOD)]: OpCode.MOD,\n [tokenTypeId(TokenTypes.CARET)]: OpCode.EXP,\n [tokenTypeId(TokenTypes.LSHIFT)]: OpCode.LSHIFT,\n [tokenTypeId(TokenTypes.RSHIFT)]: OpCode.RSHIFT,\n [tokenTypeId(TokenTypes.URSHIFT)]: OpCode.URSHIFT,\n [tokenTypeId(TokenTypes.BIT_AND)]: OpCode.BIT_AND,\n [tokenTypeId(TokenTypes.BIT_OR)]: OpCode.BIT_OR,\n [tokenTypeId(TokenTypes.BIT_XOR)]: OpCode.BIT_XOR,\n [tokenTypeId(TokenTypes.OF)]: OpCode.MUL,\n };\n\n /** Shared with every BytecodeBuilder so a nested-body builder resolves plugin calls by name. */\n private pluginFunctionIndex?: ReadonlyMap<string, number>;\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\", pluginFunctionIndex?: ReadonlyMap<string, number>) {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n // Read once, not once per number literal. `localeCode` is set here and\n // never reassigned, so these cannot go stale, and the profile had\n // getLocale() plus its property chain inside the hot NUMBER path.\n const display = getLocale(localeCode).display;\n this.decimalSeparator = display.decimalSeparator;\n this.thousandsSeparator = display.thousandsSeparator;\n this.pluginFunctionIndex = pluginFunctionIndex;\n }\n\n /** Get locale code for NumberParselet to normalize separators */\n getLocaleCode(): string {\n return this.localeCode;\n }\n\n /**\n * Set the diagnostic pipeline for parselet matching events.\n * Cleared after each non-cached parse to avoid holding refs.\n */\n setDiagnosticPipeline(pipeline: DiagnosticPipeline | undefined, expression: string): void {\n this.diagnosticPipeline = pipeline;\n this.currentExpression = expression ?? \"\";\n }\n\n /**\n * Load tokens for parsing. Identical to Parser.load().\n *\n * @param hasParens - if false, skips the O(n) paren balance scan (~90% of expressions)\n */\n load(tokens: Token[], hasParens?: boolean): void {\n if (hasParens === false) {\n this.tokens = tokens;\n this.current = 0;\n this.depth = 0;\n return;\n }\n // Paren scan: count balance to skip array copy for balanced expressions.\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n let openCount = 0;\n for (let i = 0; i < tokens.length; i++) {\n if (tokens[i].typeId === LPAREN_ID) openCount++;\n else if (tokens[i].typeId === RPAREN_ID) openCount--;\n }\n this.tokens = openCount === 0 ? tokens : this.balanceParens(tokens, openCount);\n this.current = 0;\n this.depth = 0;\n }\n\n /**\n * Auto-balance unmatched parentheses.\n */\n private balanceParens(tokens: Token[], openCount: number): Token[] {\n const result = tokens.slice();\n if (openCount > 0) {\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n for (let i = 0; i < openCount; i++) {\n const lastToken = tokens[tokens.length - 1];\n result.push({\n type: TokenTypes.RPAREN,\n typeId: RPAREN_ID,\n value: \")\",\n text: \")\",\n offset: lastToken ? lastToken.offset + lastToken.text.length : 0,\n lineBreaks: 0,\n line: lastToken ? lastToken.line : 1,\n col: lastToken ? lastToken.col + lastToken.text.length : 1,\n } as Token);\n }\n } else if (openCount < 0) {\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n for (let i = 0; i < -openCount; i++) {\n result.unshift({\n type: TokenTypes.LPAREN,\n typeId: LPAREN_ID,\n value: \"(\",\n text: \"(\",\n offset: 0,\n lineBreaks: 0,\n line: 1,\n col: 1,\n } as Token);\n }\n }\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Main entry point: precedence climbing parse expression\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a full expression starting at the current token position.\n *\n * @param minBp - minimum binding power (precedence climbing threshold).\n * For left-associative operators, the recursive call uses `bp + 1`.\n * For right-associative operators (^), it uses `bp - 1`.\n * @param _builder - accepted for parselet API compatibility; always uses `this.builder`.\n */\n parseExpression(minBp: number = 0, _builder?: BytecodeBuilder): void {\n // Accept builder via parameter for backward compatibility with the old Parser API.\n // The ExpressionEngine always calls setBuilder() before parseExpression(),\n // but tests and parselets pass builder as a parameter.\n if (_builder) {\n this.builder = _builder;\n }\n this.depth++;\n if (this.depth > this.maxDepth) {\n this.depth--;\n throw ErrorFactory.parsing(\n \"NESTING_DEPTH_EXCEEDED\",\n `Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,\n { maxDepth: this.maxDepth, currentDepth: this.depth }\n );\n }\n\n const token = this.consume();\n if (!token) {\n this.depth--;\n throw ErrorFactory.parsing(\"UNEXPECTED_END\", \"Unexpected end of expression\");\n }\n\n // ── Prefix ──────────────────────────────────────────────────────────────\n this.parsePrefix(token);\n\n // ── Infix loop (precedence climbing with inline Tier 1 dispatch) ──────────\n const tokens = this.tokens;\n const len = tokens.length;\n const bpTable = PrecedenceParser.BP_TABLE;\n const registry = this.registry;\n const builder = this.builder;\n let idx = this.current;\n\n while (idx < len) {\n const lookahead = tokens[idx];\n if (!lookahead) break;\n\n const bp = bpTable[lookahead.typeId];\n if (bp > 0) {\n // Tier 1: Built-in infix, full inline emission, zero parselet delegation\n if (bp <= minBp) break;\n\n if (this.diagnosticPipeline) {\n // Fast path skips the registry, but built-ins are still registered\n // there (for introspection/tests), look them up only in this\n // diagnostics-only branch so the playground's \"matched parselets\"\n // view isn't permanently blind to every arithmetic operator.\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (infixParselet) {\n this.fireParseletMatched(infixParselet, lookahead, false, bp);\n }\n }\n\n this.current = ++idx;\n const typeId = lookahead.typeId;\n\n if (typeId === PrecedenceParser.PERCENT_ID) {\n // Postfix: no right operand. \"50%\" → Percentage holding 0.5.\n //\n // Must stay byte-for-byte equivalent to PercentParselet, which is\n // the Tier-2 registration of the same operator. This path is the one\n // that actually runs for ordinary expressions, so a change made only\n // in the parselet does nothing at all: that is exactly how the\n // divide-by-100 here outlived its replacement and kept `200 + 10%`\n // answering 200.10.\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(100);\n builder.emitOpcode(OpCode.DIV);\n builder.emitOpcode(OpCode.TO_PERCENTAGE);\n } else if (typeId === PrecedenceParser.CARET_ID && this.tryEmitMatrixCaretOp(builder)) {\n // `^T` (transpose) or `^-1` (inverse), already fully handled\n // including consuming their own trailing tokens.\n } else {\n // Infix: parse right operand, then emit opcode.\n // Right-associative for CARET (^), left-associative for all others.\n //\n // The threshold has to be bp - 1, not bp. The loop above breaks on\n // `bp <= minBp`, so a right operand parsed at `bp` stops at the next\n // `^` exactly as one parsed at `bp + 1` does: the old special case\n // was dead code and \"2 ^ 3 ^ 2\" grouped left, answering 64. One\n // below lets the recursive call keep consuming `^`, which is what\n // makes it 2^(3^2) = 512, as in mathematics, Python, Ruby and\n // JavaScript's `**`.\n //\n // Nothing else sits between Exponent (50) and Product (40), so\n // 49 cannot collide with another operator's level. Unary minus is\n // unaffected: it parses its operand at Prefix (60), above `^`\n // either way, so \"-2 ^ 2\" is still (-2)^2 = 4.\n const rightBp = (typeId === PrecedenceParser.CARET_ID) ? bp - 1 : bp + 1;\n this.parseExpression(rightBp, builder);\n builder.emitOpcode(PrecedenceParser.INFIX_OPCODE[typeId]);\n }\n } else {\n // Tier 2: Plugin parselet fallback, full flexibility for custom syntax\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (!infixParselet) break;\n if (infixParselet.bindingPower <= minBp) break;\n\n this.current = ++idx;\n\n if (this.diagnosticPipeline) {\n this.fireParseletMatched(infixParselet, lookahead, false, infixParselet.bindingPower);\n }\n // Expose the level this parselet is bound at, so one that peeks past its\n // own token (a unit literal weighing whether a trailing `in`/`to` is\n // its own or an outer operator's) can respect precedence. See\n // infixMinBindingPower's doc comment.\n this.infixMinBindingPower = minBp;\n // Parselet handles its own recursion for right operand internally\n infixParselet.parse(this, token, lookahead, builder);\n }\n\n idx = this.current;\n }\n\n this.current = idx;\n this.depth--;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Prefix dispatch: inline switch for built-ins, parselet registry for plugins\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a prefix token. Built-in tokens (NUMBER, IDENT, LPAREN, etc.) are\n * handled inline with zero registry lookup. Everything else falls through\n * to the parselet registry (Tier 2).\n */\n private parsePrefix(token: Token): void {\n const builder = this.builder;\n const typeId = token.typeId;\n\n if (this.diagnosticPipeline) {\n // Fast path below skips the registry for built-ins, but they're still\n // registered there (for introspection/tests), look up here so the\n // playground's \"matched parselets\" view isn't permanently blind to\n // every number, identifier, paren, and unary operator.\n const parselet = this.registry.getPrefix(typeId);\n if (parselet) {\n this.fireParseletMatched(parselet, token, true);\n }\n }\n\n switch (typeId) {\n // ── Numeric literals ──────────────────────────────────────────────────\n case PrecedenceParser.NUMBER_ID: {\n // Parse number with locale-aware separator normalization\n let v: number;\n // The exact dot-decimal text for a literal written with a fractional\n // point, so it can be pushed as PUSH_DECIMAL and keep its precision\n // where it later meets money. Stays null for every integer shape\n // (hex/bin/oct, chained-dot grouping, plain integers), which push the\n // ordinary PUSH_NUMBER and are unchanged.\n let decimalText: string | null = null;\n const raw = token.value;\n\n // Fast path: plain digits, with at most one \".\".\n //\n // Most literals in a document are `144`, `1200`, `0.85`. The general\n // path below reaches the same answer for them only after six\n // startsWith() calls, two regular expressions and a split/join that\n // allocated whether or not the separator was present; a CPU profile put\n // this whole case at over a third of parse-and-compile. One character\n // scan settles it instead.\n //\n // Guarded on the decimal separator being \".\", which is what makes a\n // lone dot unambiguous. Where \".\" groups thousands instead, `1.234`\n // means one thousand two hundred and thirty-four, so that locale has to\n // keep taking the general path.\n if (this.decimalSeparator === \".\") {\n let dots = 0;\n let plain = raw.length > 0;\n for (let i = 0; i < raw.length; i++) {\n const c = raw.charCodeAt(i);\n if (c >= 48 && c <= 57) continue;\n if (c === 46 && dots === 0) { dots = 1; continue; }\n plain = false;\n break;\n }\n if (plain) {\n // One dot with digits optional on either side is exactly what\n // PLAIN_DECIMAL matches, so this agrees with it: that is the signal\n // for the exact-decimal opcode rather than a double.\n if (dots === 1) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(raw);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(+raw);\n return;\n }\n }\n\n if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n v = parseInt(raw, 16);\n // A prefix with no digits after it (\"0x\" alone) makes parseInt\n // return NaN. This used to push straight through as a silent\n // NaN Number value instead of a visible error.\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid hex literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0b\") || raw.startsWith(\"0B\")) {\n v = parseInt(raw.slice(2), 2);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid binary literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0o\") || raw.startsWith(\"0O\")) {\n v = parseInt(raw.slice(2), 8);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid octal literal: \"${raw}\"`, { raw });\n }\n } else if (CHAINED_DOT_THOUSANDS_GROUPS.test(raw)) {\n // The lexer accepts \".\" as a thousands-group separator\n // independent of locale (ExpressionLexer's number-scanning\n // \"Thousands separators\" block), but the locale-based\n // normalization below only strips the ACTIVE locale's own\n // configured thousandsSeparator character, for \"en\" that's\n // \",\", not \".\", so a chained dot-grouped literal like\n // \"1.234.567\" fell through to parseFloat() untouched, which\n // stops at the second \".\" and silently truncated it to 1.234\n // (over 99% of the digits dropped, with no error). This is the\n // REAL number-parsing path for actual evaluation, Tier 1 of\n // the two-tier dispatch above always returns for NUMBER_ID, so\n // NumberParselet.parse() (which has the identical fix) never\n // actually runs except via direct unit tests / the \"matched\n // parselets\" diagnostic display.\n v = parseFloat(raw.split(\".\").join(\"\"));\n } else {\n const decimalSep = this.decimalSeparator;\n const thousandsSep = this.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation).\n // The indexOf guard stops that pair allocating an array and a string\n // for the many literals that contain no separator at all.\n if (thousandsSep && normalized.indexOf(thousandsSep) !== -1) {\n normalized = normalized.split(thousandsSep).join(\"\");\n }\n // Replace locale decimal separator with \".\" for JavaScript parsing\n if (decimalSep && decimalSep !== \".\") {\n normalized = normalized.replace(decimalSep, \".\");\n }\n v = parseFloat(normalized);\n // A plain fractional literal (digits, one dot, digits) is what carries\n // an exact decimal. Scientific notation like \"2.5e-3\" has a dot too\n // but no exact base-ten form worth the trouble, so it stays a\n // PUSH_NUMBER double, and so does any integer (grouping stripped).\n if (PLAIN_DECIMAL.test(normalized)) decimalText = normalized;\n }\n if (decimalText !== null) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(decimalText);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(v);\n return;\n }\n\n case PrecedenceParser.BIGINT_ID: {\n // Strips the `n` and any thousands grouping the lexer coalesced in.\n // This used to be `raw.slice(0, -1)` and nothing else, so `1.000n`\n // reached BigInt(\"1.000\") and threw a raw SyntaxError. See\n // parser/BigIntLiteral.ts, which the parselet tier shares.\n builder.emitOpcode(OpCode.PUSH_BIGINT);\n builder.emitString(bigIntLiteralDigits(token.value, this.localeCode));\n return;\n }\n\n case PrecedenceParser.STRING_ID: {\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(token.value);\n return;\n }\n\n // ── Identifiers (variables) ────────────────────────────────────────────\n case PrecedenceParser.IDENT_ID: {\n // An identifier immediately followed by \"(\" may be a user-defined\n // function DEFINITION (`f(x) = ...`) or CALL (`f(5)`). See\n // parseUserFunctionDefOrCall's doc comment for the full\n // disambiguation. Only the (cheap) LPAREN check runs for the\n // overwhelmingly common case of a bare identifier with nothing\n // following it.\n if (this.peek()?.typeId === PrecedenceParser.LPAREN_ID) {\n this.parseUserFunctionDefOrCall(token, builder);\n return;\n }\n // IDENT tokens map to LOAD_VAR by default. The IdentifierParselet\n // and VariableParselet add STORE_VAR for assignments, those are\n // handled via the parselet registry below. Note this is also how a\n // user-defined function's own PARAMETER references compile. See\n // UserFunctionDef's doc comment in BytecodeBuilder.ts for why there\n // is no separate parameter-load opcode: `LOAD_VAR` resolution\n // dynamically checks the VM's innermost call frame first.\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(token.value);\n return;\n }\n\n // ── Grouping / bare-tuple vector literal ─────────────────────────────────\n // `(expr)` groups for precedence; `(x, y[, z[, w]])` is the bare-tuple\n // vector literal documented as an alternative to vec2/vec3/vec4(...)\n // (wiki: Arithmetic/Vector). This Tier-1 case is what actually runs for\n // every LPAREN in production parsing, GroupParselet.ts mirrors this\n // logic for registry-introspection/diagnostic-listing purposes, but a\n // package can never override LPAREN's dispatch here (Tier 1 always\n // wins over the ParseletRegistry fallback below), so both must be kept\n // in sync by hand.\n case PrecedenceParser.LPAREN_ID: {\n this.parseExpression(0, builder);\n let count = 1;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(0, builder);\n count++;\n }\n this.consume(TokenTypes.RPAREN);\n if (count > 1) {\n // Legacy bare-tuple vector sugar, a 1xN row-vector Matrix (see\n // packages/vector/parselets/VectorParselet.ts's comment).\n builder.emitOpcode(OpCode.MAT_NEW);\n builder.emitIndex(1);\n builder.emitIndex(count);\n }\n return;\n }\n\n // ── Unary operators ───────────────────────────────────────────────────\n case PrecedenceParser.MINUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.NEG);\n return;\n }\n\n case PrecedenceParser.PLUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.POS);\n return;\n }\n\n // ── Keyword constants ─────────────────────────────────────────────────\n case PrecedenceParser.KEYWORD_ID: {\n // Keywords are handled by parselets (pi→PI, e→E, etc.)\n // Fall through to registry below.\n }\n }\n\n // ── Tier 2: Plugin/parselet prefix path ──────────────────────────────────\n const prefixParselet = this.registry.getPrefix(typeId);\n if (!prefixParselet) {\n throw ErrorFactory.parsing(\n \"NO_PREFIX_PARSELET\",\n `No prefix parselet found for token: ${token.type} (\"${token.value}\")`,\n { tokenType: token.type, tokenValue: token.value }\n );\n }\n\n prefixParselet.parse(this, token, builder);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // The \"Tier-1 shape-exception\" pattern\n // ═══════════════════════════════════════════════════════════════════════════════\n //\n // Tier 1 exists purely for performance, avoid a Map lookup + parselet call\n // on ~95% of tokens (see this file's own module doc comment above). A\n // recurring consequence: any grammar shape tied to a Tier-1 token type can\n // ONLY be implemented by hand-editing this switch, since a package-\n // registered ParseletRegistry parselet for that same token type would\n // simply never run in production (Tier 1 always wins over the registry\n // fallback). Five confirmed instances of this tension exist in this file\n // (plus one that had to move OUTSIDE it entirely):\n // 1. NUMBER_ID, the full locale-aware number-literal parsing (hex/\n // binary/octal, chained-dot thousands grouping, decimal-separator\n // normalization) is inlined in parsePrefix() above; NumberParselet.ts's\n // own copy is dead code for real evaluation, kept registered only for\n // the \"matched parselets\" diagnostic view.\n // 2. IDENT_ID, parseUserFunctionDefOrCall's lookahead (below) disambig-\n // uates a function DEFINITION from a CALL from a plain variable load.\n // 3. LPAREN_ID, the bare-tuple vector-literal sugar (\"(x,y[,z[,w]])\" ->\n // MAT_NEW) is inlined in parsePrefix() above; GroupParselet.ts mirrors\n // it for introspection only and must be kept in sync by hand.\n // 4. CARET_ID, the transpose/inverse suffix table just below.\n // 5. PLUS_ID, the locale word \"and\" lexes as PLUS (Tier-1, fixed Sum\n // binding power), so a registry parselet can never intercept it the\n // way LogicalParselet.ts intercepts \"or\"/&&/||; unlike the other four,\n // there's no SHAPE to special-case on here (the token itself IS the\n // operator), so the workaround lives entirely outside this file, as a\n // runtime Boolean/Boolean type-check inside vm/VM.ts's OpCode.ADD\n // handler instead.\n //\n // Deliberate non-goal: none of this is exposed as an IEnginePackage\n // extension point (unlike prefixParselets/infixParselets). Letting\n // third-party packages register their own Tier-1 shape-matchers would put\n // per-package matcher iteration on a genuinely hot path (every CARET/\n // NUMBER/IDENT/LPAREN/PLUS token, matched or not), a materially bigger\n // separate product decision than \"make this one table more concise,\" and\n // not one this pattern write-up makes.\n\n /**\n * A single `^`-suffix shape: `matches` peeks ahead (consuming nothing) to\n * check whether this shape starts at the current position; `emit` is only\n * called immediately after `matches` returned true for that SAME position,\n * and is responsible for consuming that shape's own trailing tokens and\n * emitting its bytecode.\n */\n private static readonly CARET_SUFFIX_RULES: ReadonlyArray<{\n name: string;\n matches(parser: PrecedenceParser): boolean;\n emit(parser: PrecedenceParser, builder: BytecodeBuilder): void;\n }> = [\n {\n name: \"transpose (^T)\",\n matches: (p) => {\n const next = p.peek();\n return next?.type === TokenTypes.IDENT && next.value === \"T\";\n },\n emit: (p, builder) => {\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(63); // transpose — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n {\n name: \"inverse (^-1)\",\n matches: (p) => {\n const next = p.peek();\n if (next?.typeId !== PrecedenceParser.MINUS_ID) return false;\n const afterMinus = p.peekAt(1);\n return afterMinus?.type === TokenTypes.NUMBER && afterMinus.value === \"1\";\n },\n emit: (p, builder) => {\n p.advance();\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(65); // inv — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n ];\n\n /**\n * After a `^` token (already consumed by the Tier-1 infix loop above),\n * checks {@link CARET_SUFFIX_RULES} in order for a shape that means\n * something other than ordinary exponentiation: `^T` (transpose) and `^-1`\n * (matrix inverse, LITERALLY the integer exponent `-1`; `^-2`, `^-1.5`\n * etc. still mean ordinary exponentiation). On a match, the rule's `emit`\n * consumes that shape's own tokens and this returns `true`. On no match,\n * consumes NOTHING, returning `false` so the caller falls through to\n * ordinary `EXP` parsing.\n *\n * Every rule dispatches purely on SHAPE, never on operand type (unknowable\n * at parse time): `inv()`'s own handler (`VMBuiltins.ts` index 65) returns\n * `1/x` for a plain Number, byte-identical to what `Math.pow(x, -1)`\n * already computed for `x^-1` before this feature existed, and a real\n * matrix inverse for a Matrix, so `5^-1` still means exactly what it always\n * has; only a Matrix operand actually inverts.\n *\n * Adding a future `^`-suffix shape is a new table entry here, not a new\n * if-block. See the \"Tier-1 shape-exception\" pattern write-up above for\n * why this table can't instead be a package-registered parselet.\n */\n private tryEmitMatrixCaretOp(builder: BytecodeBuilder): boolean {\n for (const rule of PrecedenceParser.CARET_SUFFIX_RULES) {\n if (rule.matches(this)) {\n rule.emit(this, builder);\n return true;\n }\n }\n return false;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // User-defined, parameterized, reusable functions (f(x) = 2*x + 1, then f(5))\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * From an LPAREN token index, scan forward tracking paren depth and\n * return the index of the matching RPAREN, or `null` if the parens never\n * balance before the token stream ends. No emission, no position\n * advance. Same class of technique as {@link balanceParens}'s own\n * pre-scan, just exposed mid-parse instead of only at `load()` time.\n * `openIdx` must point AT the LPAREN itself.\n */\n private findMatchingRParen(openIdx: number): number | null {\n let depth = 0;\n for (let i = openIdx; i < this.tokens.length; i++) {\n const t = this.tokens[i];\n if (t.typeId === PrecedenceParser.LPAREN_ID) depth++;\n else if (t.typeId === PrecedenceParser.RPAREN_ID) {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n }\n\n /**\n * Disambiguates a bare `IDENT` immediately followed by `(` between three\n * things, using ONLY a bracket-depth scan (no backtracking, nothing is\n * consumed until the shape is known):\n * - `f(x) = expr`, a DEFINITION: the matching `)` is followed by `=`.\n * - `f(5)`, a CALL to a (possibly not-yet-defined) function: anything\n * else. This was never valid syntax before this feature (a bare\n * `IDENT` immediately before `(` has no pre-existing \"plain variable\n * read + separately grouped `(...)`\" meaning to preserve, confirmed\n * via `BuiltinNormalizerRules.ts`'s `implicitMultiplyRule()`, which\n * only inserts an implicit `*` for `NUMBER/RPAREN` immediately before\n * `IDENT/LPAREN`, never for a bare `IDENT` immediately before\n * `LPAREN`). Always commits to a CALL; an unregistered name produces a\n * clear `UNDEFINED_FUNCTION` error at VM-execution time, the same\n * forward-reference philosophy `LOAD_VAR`/`UNDEFINED_VARIABLE` already\n * uses, rather than any parse-time registry lookup.\n * If the parens never balance, this falls through to the ordinary\n * `LOAD_VAR` path (a malformed expression surfaces its own parse error\n * shortly after, from the normal expression grammar).\n */\n private parseUserFunctionDefOrCall(nameToken: Token, builder: BytecodeBuilder): void {\n const closeIdx = this.findMatchingRParen(this.current);\n if (closeIdx === null) {\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(nameToken.value);\n return;\n }\n const afterClose = this.tokens[closeIdx + 1];\n if (afterClose?.type === TokenTypes.EQUALS) {\n this.parseUserFunctionDefinition(nameToken, builder);\n } else {\n this.parseUserFunctionCall(nameToken, builder);\n }\n }\n\n /**\n * A parameter name, accepted as either `IDENT` or `UNIT`, matches this\n * codebase's established `:name = value` variable-name policy\n * (`VariableParselet.ts` explicitly accepts `UNIT`-typed tokens too, e.g.\n * `:b = 5` for the \"b\" bits unit) since common short parameter names\n * like `h`/`l`/`b`/`t`/`s`/`m` collide with real unit abbreviations\n * (hour, liter, bits, ton, second, meter, ...) and lex as `UNIT`, not\n * `IDENT`.\n */\n private consumeParamName(): string {\n const token = this.peek();\n if (token?.type === TokenTypes.IDENT || token?.type === TokenTypes.UNIT) {\n this.consume();\n return token.value;\n }\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_INVALID_PARAM_NAME\",\n `Expected a parameter name but got \"${token?.type ?? \"end of input\"}\"${token ? ` (\"${token.value}\")` : \"\"}`,\n { actualType: token?.type },\n );\n }\n\n private parseUserFunctionDefinition(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n const params: string[] = [];\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n params.push(this.consumeParamName());\n while (this.match(TokenTypes.COMMA)) {\n params.push(this.consumeParamName());\n }\n }\n this.consume(TokenTypes.RPAREN);\n this.consume(TokenTypes.EQUALS);\n\n if (params.length === 0) {\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_NO_PARAMS\",\n `\"${nameToken.value}()\" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,\n { name: nameToken.value },\n );\n }\n\n // Compile the body into its OWN independent BytecodeBuilder, reusing\n // the SAME parser/token stream but directing emission elsewhere.\n // `parseExpression(minBp, _builder)` sets `this.builder = _builder`\n // with NO automatic restore, explicitly restoring via `setBuilder()`\n // afterward (not a `finally`, since a thrown parse error here should\n // propagate as-is; there's no further use of `this.builder` on that\n // path before the whole parse aborts) avoids silently emitting\n // whatever parses next (in this same expression, or, via\n // ExpressionEngine's builder pool, a LATER, unrelated line) into a\n // stale, already-.build()'d body builder.\n const bodyBuilder = new BytecodeBuilder(this.pluginFunctionIndex);\n this.parseExpression(BindingPower.Lowest, bodyBuilder);\n this.setBuilder(builder);\n\n const bodyProgram = bodyBuilder.build();\n if (bodyProgram.hasAsync) {\n // v1 scope decision: a function body calling an async plugin\n // (weather, stocks, currency, ...) isn't supported yet, propagating\n // a 'pending' result up through a reentrant executeBytecode() call\n // would need the OUTER expression's own bytecode position/stack\n // state to also be resumable later, which this first pass doesn't\n // implement. Rejecting at DEFINITION time (not call time) gives the\n // clearest possible error, matching this codebase's \"never silently\n // pretend to support something it doesn't\" convention (e.g.\n // addBusinessDays()'s own disclosed holiday-exclusion scope-down).\n throw ErrorFactory.parsing(\n \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n `\"${nameToken.value}(...)\"'s body calls an async operation (weather, stocks, currency, ...) — user-defined function bodies must be synchronous`,\n { name: nameToken.value },\n );\n }\n\n const bodyIdx = builder.emitUserFunctionBody(nameToken.value, params, bodyProgram);\n builder.emitOpcode(OpCode.DEFINE_USER_FUNCTION);\n builder.emitIndex(bodyIdx);\n\n // A definition line has no single input value to echo back the way an\n // assignment does, push a plain confirmation string, matching this\n // codebase's \"never silently produce a misleading numeric 0\" principle.\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(`${nameToken.value}(${params.join(\", \")}) defined`);\n }\n\n private parseUserFunctionCall(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n let argCount = 0;\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n this.consume(TokenTypes.RPAREN);\n\n builder.emitOpcode(OpCode.CALL_USER_FUNCTION);\n builder.emitString(nameToken.value);\n builder.emitByte(argCount);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Token stream navigation (identical API to Parser)\n // ═══════════════════════════════════════════════════════════════════════════════\n\n consume(expectedType?: string): Token {\n const token = this.tokens[this.current];\n if (!token) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_END_OF_INPUT\",\n \"Unexpected end of input\"\n );\n }\n if (expectedType !== undefined) {\n const expectedId = tokenTypeId(expectedType);\n if (token.typeId !== expectedId) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_TOKEN_TYPE\",\n `Expected token type \"${expectedType}\" but got \"${token.type}\" (\"${token.value}\")`,\n { expectedType, actualType: token.type, actualValue: token.value }\n );\n }\n }\n this.current++;\n return token;\n }\n\n match(expectedType: string): boolean {\n const token = this.peek();\n if (token && token.typeId === tokenTypeId(expectedType)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n peek(): Token | undefined {\n return this.tokens[this.current];\n }\n\n /**\n * Read-only lookahead `offset` tokens past the current position, without\n * consuming anything, `peekAt(0)` is equivalent to {@link peek}.\n * `this.tokens` is a plain in-memory array (not a stream), so this is a\n * simple, safe index read; no rewind/checkpoint mechanism is needed since\n * nothing is consumed.\n */\n peekAt(offset: number): Token | undefined {\n return this.tokens[this.current + offset];\n }\n\n previous(): Token | undefined {\n return this.current > 0 ? this.tokens[this.current - 1] : undefined;\n }\n\n private advance(): void {\n this.current++;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Builder access, set before parse, read by inline prefix handlers\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /** Set the builder to use for the current parse. Called by ExpressionEngine. */\n setBuilder(builder: BytecodeBuilder): void {\n this.builder = builder;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Diagnostics\n // ═══════════════════════════════════════════════════════════════════════════════\n\n private fireParseletMatched(\n parselet: { category: string },\n token: Token,\n isPrefix: boolean,\n bindingPower?: number\n ): void {\n const pipeline = this.diagnosticPipeline!;\n const event: DiagnosticEvent & { type: \"parselet_matched\" } = {\n type: DiagnosticEventType.ParseletMatched,\n elapsedNs: 0,\n expression: this.currentExpression,\n tokenType: token.type,\n tokenValue: token.value,\n parseletCategory: parselet.category,\n parseletType: parselet.constructor?.name ?? \"unknown\",\n isPrefix,\n bindingPower,\n tokenOffset: token.offset || 0,\n };\n pipeline.fireParseletMatched(event);\n }\n}\n","import { PrefixParselet, InfixParselet } from \"@solve-js/parser/Parselet\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\n\n/**\n * The one binding-power field a parselet may expose beyond what its interface\n * requires, read only for diagnostic display.\n *\n * `InfixParselet` requires `bindingPower`; `PrefixParselet` declares none, and\n * some prefix parselets carry one anyway. That single field is the whole\n * optional surface deliberately. A `leftBindingPower`/`rightBindingPower` pair\n * used to be read here as well, and reading a name off an object this way finds\n * PRIVATE fields too, since TypeScript's `private` exists only at compile time:\n * `BinaryOpParselet` holds a private `rightBindingPower` meaning \"the minimum\n * power to parse my right operand at\", which is a different quantity from \"the\n * power at which I bind to my right\" and differs from it by one. Reading it\n * silently reported that other number. So neither is read.\n *\n * `category` is not here: both interfaces already declare it.\n */\ninterface ParseletBindingPowers {\n\treadonly bindingPower?: number;\n}\n\n/** Reads the optional binding-power field off a parselet for diagnostics. */\nfunction bindingPowersOf(parselet: PrefixParselet | InfixParselet): ParseletBindingPowers {\n\treturn parselet as ParseletBindingPowers;\n}\n\n/**\n * Dual-keyed ParseletRegistry, accepts both string token types and\n * integer token type IDs for fast dispatch in the Parser hot path.\n *\n * Providers call registerPrefix(\"NUMBER\", ...) with string token types.\n * Internally, we populate both string-keyed and integer-keyed maps so\n * Parser.parseExpression() can use token.typeId (integer) for lookup\n * while diagnostics and error messages use token.type (string).\n *\n * Performance: Integer Map.get() avoids string hashing, saving ~2-5ns\n * per dispatch. With ~10-15 dispatches per expression, that's ~20-75ns.\n */\nexport class ParseletRegistry {\n\t// String-keyed maps (kept for diagnostics + backwards compat)\n\tprivate prefixParselets: Map<string, PrefixParselet> = new Map();\n\tprivate infixParselets: Map<string, InfixParselet> = new Map();\n\n\t// Integer-keyed maps for parser hot path\n\tprivate prefixById: Map<number, PrefixParselet> = new Map();\n\tprivate infixById: Map<number, InfixParselet> = new Map();\n\n\t/**\n\t * Register a prefix parselet for `tokenType`.\n\t *\n\t * If another parselet is already registered for this token type, it is\n\t * silently overwritten by default (`Map.set()` semantics), the old\n\t * parselet is simply unreachable from then on, with no error. This is\n\t * a real footgun for third-party packages: two packages independently\n\t * choosing the same custom token type will collide with zero signal\n\t * about which one \"won\". Mirrors ResolverRegistry.register()'s and\n\t * ExpressionEngine.registerPackage()'s existing \"warn and replace\"\n\t * pattern for the same class of problem at the resolver-namespace and\n\t * package-name levels.\n\t *\n\t * Note: this warns about registry-level collisions only. It does NOT\n\t * detect the separate case where `tokenType` is one of PrecedenceParser's\n\t * Tier-1 fast-path token types (NUMBER, STRING, IDENT, LPAREN, MINUS,\n\t * PLUS, and the Tier-1 infix operators), those are deliberately kept\n\t * registered here for introspection/diagnostics even though Tier-1\n\t * always intercepts them before this registry is consulted (see\n\t * PrecedenceParser.parsePrefix()'s docs), so warning there would\n\t * misfire on that intentional, already-documented pattern.\n\t */\n\tregisterPrefix(tokenType: string, parselet: PrefixParselet): void {\n\t\tconst existing = this.prefixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Prefix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.prefixParselets.set(tokenType, parselet);\n\t\tthis.prefixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/** Register an infix parselet for `tokenType`. See {@link registerPrefix} for the collision-warning behavior this mirrors. */\n\tregisterInfix(tokenType: string, parselet: InfixParselet): void {\n\t\tconst existing = this.infixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Infix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.infixParselets.set(tokenType, parselet);\n\t\tthis.infixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/**\n\t * Iterate all registered prefix parselets for diagnostic display.\n\t *\n\t * `PrefixParselet` declares no binding power, and this used to read a field\n\t * of that name and report 0 for every one of them. 0 is not a neutral\n\t * wrong answer: it is the value that means \"not an operator, stop the\n\t * expression\", so a host drawing a table from this was told none of them\n\t * bind at all. A prefix parselet in this parser has no per-parselet power\n\t * to report, they all bind at the prefix level and each chooses for itself\n\t * at what power to parse its own operand, so that level is what is\n\t * reported. A parselet that does carry its own `bindingPower` still wins.\n\t */\n\tgetAllPrefix(): Array<{ tokenType: string; bindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; bindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.prefixParselets) {\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tbindingPower: bindingPowersOf(parselet).bindingPower ?? BindingPower.Prefix,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterate all registered infix parselets for diagnostic display.\n\t *\n\t * The field an `InfixParselet` actually declares is `bindingPower`. This\n\t * used to read `leftBindingPower` and `rightBindingPower`, which no\n\t * parselet in this codebase declares, so both reads were `undefined`, both\n\t * fell to the `?? 0` default, and the public `getParseletRegistry()`\n\t * reported a binding power of 0 for every one of the ~60 infix operators.\n\t * A host building a precedence table from it was told `*` and `+` bind\n\t * equally, and that neither binds at all.\n\t *\n\t * The left/right split: `bindingPower` is the LEFT power, and the right is\n\t * one higher. That is the standard encoding for a left-associative\n\t * operator, and it is what the parser itself does, see\n\t * `PrecedenceParser.parseExpression()`'s `bp + 1` for the right operand.\n\t * Every operator is reported that way, `^` included. Associativity is not\n\t * something a parselet declares, it is a property of how each one calls\n\t * `parseExpression`, so this API cannot report it without a new field on\n\t * the interface. See {@link ParseletBindingPowers} for why scraping a\n\t * plausible-looking one off the parselet is worse than not reporting it.\n\t */\n\tgetAllInfix(): Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.infixParselets) {\n\t\t\tconst left = bindingPowersOf(parselet).bindingPower ?? 0;\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tleftBindingPower: left,\n\t\t\t\trightBindingPower: left + 1,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Number of registered prefix parselets. */\n\tget prefixCount(): number { return this.prefixParselets.size; }\n\n\t/** Number of registered infix parselets. */\n\tget infixCount(): number { return this.infixParselets.size; }\n\n\t/**\n\t * Get prefix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings\n\t * (diagnostics, error messages, backwards compatibility).\n\t */\n\tgetPrefix(tokenType: string | number): PrefixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.prefixById.get(tokenType);\n\t\treturn this.prefixParselets.get(tokenType);\n\t}\n\n\t/**\n\t * Get infix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings.\n\t */\n\tgetInfix(tokenType: string | number): InfixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.infixById.get(tokenType);\n\t\treturn this.infixParselets.get(tokenType);\n\t}\n\n\thasPrefix(tokenType: string): boolean {\n\t\treturn this.prefixParselets.has(tokenType);\n\t}\n\n\thasInfix(tokenType: string): boolean {\n\t\treturn this.infixParselets.has(tokenType);\n\t}\n\n\tclear(): void {\n\t\tthis.prefixParselets.clear();\n\t\tthis.infixParselets.clear();\n\t\tthis.prefixById.clear();\n\t\tthis.infixById.clear();\n\t}\n}\n\n/**\n * A process-wide parselet registry.\n *\n * @deprecated An engine builds its own registry and does not read this one, so\n * registering here reaches nothing that evaluates. Nothing writes to it now\n * that the global package-registration path is gone; it remains only so the\n * `@solve-js/parser` escape hatch keeps a stable shape.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/PrecedenceParser.ts","../src/parser/registry/ParseletRegistry.ts"],"names":["CHAINED_DOT_THOUSANDS_GROUPS","PLAIN_DECIMAL","_PrecedenceParser","parseletRegistry","maxDepth","localeCode","pluginFunctionIndex","display","getLocale","pipeline","expression","tokens","hasParens","LPAREN_ID","tokenTypeId","TokenTypes","RPAREN_ID","openCount","i","result","lastToken","minBp","_builder","ErrorFactory","token","len","bpTable","registry","builder","idx","lookahead","bp","infixParselet","typeId","rightBp","parselet","v","decimalText","raw","dots","plain","c","decimalSep","thousandsSep","normalized","bigIntLiteralDigits","count","BindingPower","prefixParselet","rule","openIdx","depth","t","nameToken","closeIdx","params","bodyBuilder","BytecodeBuilder","bodyProgram","bodyIdx","argCount","expectedType","expectedId","offset","isPrefix","bindingPower","event","DiagnosticEventType","buildBindingPowerTable","p","next","afterMinus","PrecedenceParser","ParseletRegistry","tokenType","existing","left","sharedParseletRegistry"],"mappings":"wNAmBA,IAAMA,CAAAA,CAA+B,wBAAA,CAU/BC,CAAAA,CAAgB,YAAA,CAqBTC,CAAAA,CAAN,MAAMA,CAAiB,CAwF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,IAAA,CAAMC,CAAAA,CAAmD,CAvFrI,IAAA,CAAQ,MAAA,CAAkB,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ACzC,CAEA,KAAA,EAAc,CACb,IAAA,CAAK,eAAA,CAAgB,KAAA,EAAM,CAC3B,IAAA,CAAK,cAAA,CAAe,KAAA,EAAM,CAC1B,IAAA,CAAK,UAAA,CAAW,KAAA,EAAM,CACtB,IAAA,CAAK,SAAA,CAAU,KAAA,GAChB,CACD,CAAA,CAUaG,EAAyB,IAAIJ","file":"chunk-WFOQRPA6.js","sourcesContent":["import { ParseletRegistry } from \"@solve-js/parser/registry/ParseletRegistry\";\nimport { Token, tokenTypeId, TokenTypes } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DiagnosticPipeline, DiagnosticEventType, type DiagnosticEvent } from \"@solve-js/diagnostics\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower, buildBindingPowerTable } from \"@solve-js/parser/BindingPower\";\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { bigIntLiteralDigits } from \"@solve-js/parser/BigIntLiteral\";\n\n/**\n * Matches a CHAINED thousands-grouped integer using \".\" as the group\n * separator (e.g. \"1.234.567\"), independent of locale. Kept in sync with\n * the identical constant in NumberParselet.ts (not imported from there\n * that file transitively re-imports PrecedenceParser via Parser.ts's\n * `export { PrecedenceParser as Parser }`, so importing the other\n * direction would create a circular dependency for the sake of one\n * regex literal). See NumberParselet.ts's copy for the full explanation.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/**\n * A plain fractional literal: digits, exactly one dot, digits, nothing else.\n *\n * The gate for compiling to PUSH_DECIMAL. It admits \"0.10\", \"1.005\", \".5\" and\n * \"5.\" and refuses anything with an exponent (\"2.5e-3\"), which parses as an\n * ordinary double instead, since scientific notation has no exact base-ten\n * value this representation would keep.\n */\nconst PLAIN_DECIMAL = /^\\d*\\.\\d*$/;\n\n/**\n * ── Hybrid Precedence Climbing Parser ─────────────────────────────────────────\n *\n * Two-tier dispatch strategy:\n *\n * Tier 1 (Fast Path): Inline switch on token.typeId for built-in operators.\n * - Prefix: NUMBER, IDENT, LPAREN, MINUS, PLUS, STRING\n * - Infix: checked via static BP_TABLE (Uint8Array indexed by typeId)\n * - No Map.get(), no parselet function call overhead for ~95% of tokens\n *\n * Tier 2 (Plugin Path): ParseletRegistry fallback for custom/plugin tokens.\n * - Prefix: Map.get(tokenTypeId) for PrefixParselet\n * - Infix: Map.get(tokenTypeId) for InfixParselet\n * - Full flexibility for custom syntax\n *\n * The parser emits directly to a BytecodeBuilder, no AST intermediate.\n * Implements the same public API as the legacy Parser class so existing\n * parselets continue to work without modification.\n */\nexport class PrecedenceParser {\n private tokens: Token[] = [];\n private current = 0;\n private depth = 0;\n private maxDepth: number;\n\n /** Cached registry reference, avoids property chain in hot loop */\n private registry: ParseletRegistry;\n\n /** BytecodeBuilder, set before each parseExpression call */\n private builder!: BytecodeBuilder;\n\n /** Diagnostic pipeline for parselet-matched events */\n private diagnosticPipeline: DiagnosticPipeline | undefined;\n private currentExpression: string = \"\";\n private localeCode: string;\n\n /** The locale's decimal separator, cached from {@link localeCode}. */\n private readonly decimalSeparator: string;\n\n /** The locale's thousands separator, cached from {@link localeCode}. */\n private readonly thousandsSeparator: string;\n\n /**\n * The binding power the current infix parselet is being invoked at, i.e. the\n * `minBp` of the expression it sits inside. Set immediately before each Tier-2\n * parselet runs. A parselet that decides whether to swallow a following\n * loose operator (UomLiteralParselet with a trailing `in`/`to`) reads this to\n * respect precedence it cannot otherwise see: `120 km / 2 hours in kph` must\n * group as `(120 km / 2 hours) in kph`, not `120 km / (2 hours in kph)`.\n */\n infixMinBindingPower = 0;\n\n /**\n * Static binding power table, built once at module load, shared across all instances.\n * Index = tokenTypeId, value = binding power (0 = not a built-in infix).\n */\n static readonly BP_TABLE: Uint8Array = buildBindingPowerTable();\n\n // ── Pre-computed token type IDs for inline dispatch ────────────────────────\n // Prefix built-ins\n private static readonly NUMBER_ID = tokenTypeId(TokenTypes.NUMBER);\n private static readonly BIGINT_ID = tokenTypeId(TokenTypes.BIGINT);\n private static readonly STRING_ID = tokenTypeId(TokenTypes.STRING);\n private static readonly IDENT_ID = tokenTypeId(TokenTypes.IDENT);\n private static readonly LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n private static readonly RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n private static readonly MINUS_ID = tokenTypeId(TokenTypes.MINUS);\n private static readonly PLUS_ID = tokenTypeId(TokenTypes.PLUS);\n private static readonly KEYWORD_ID = tokenTypeId(TokenTypes.KEYWORD);\n\n // Infix built-ins (Tier 1, full inline emission)\n private static readonly STAR_ID = tokenTypeId(TokenTypes.STAR);\n private static readonly SLASH_ID = tokenTypeId(TokenTypes.SLASH);\n private static readonly MOD_ID = tokenTypeId(TokenTypes.MOD);\n private static readonly CARET_ID = tokenTypeId(TokenTypes.CARET);\n private static readonly LSHIFT_ID = tokenTypeId(TokenTypes.LSHIFT);\n private static readonly RSHIFT_ID = tokenTypeId(TokenTypes.RSHIFT);\n private static readonly URSHIFT_ID = tokenTypeId(TokenTypes.URSHIFT);\n private static readonly BIT_AND_ID = tokenTypeId(TokenTypes.BIT_AND);\n private static readonly BIT_OR_ID = tokenTypeId(TokenTypes.BIT_OR);\n private static readonly BIT_XOR_ID = tokenTypeId(TokenTypes.BIT_XOR);\n private static readonly PERCENT_ID = tokenTypeId(TokenTypes.PERCENT);\n private static readonly OF_ID = tokenTypeId(TokenTypes.OF);\n\n /**\n * Inline opcode map for Tier 1 infix operators.\n * tokenTypeId → OpCode. PERCENT and CARET are handled specially (not in this map).\n */\n private static readonly INFIX_OPCODE: Record<number, OpCode> = {\n [tokenTypeId(TokenTypes.PLUS)]: OpCode.ADD,\n [tokenTypeId(TokenTypes.MINUS)]: OpCode.SUB,\n [tokenTypeId(TokenTypes.STAR)]: OpCode.MUL,\n [tokenTypeId(TokenTypes.SLASH)]: OpCode.DIV,\n [tokenTypeId(TokenTypes.MOD)]: OpCode.MOD,\n [tokenTypeId(TokenTypes.CARET)]: OpCode.EXP,\n [tokenTypeId(TokenTypes.LSHIFT)]: OpCode.LSHIFT,\n [tokenTypeId(TokenTypes.RSHIFT)]: OpCode.RSHIFT,\n [tokenTypeId(TokenTypes.URSHIFT)]: OpCode.URSHIFT,\n [tokenTypeId(TokenTypes.BIT_AND)]: OpCode.BIT_AND,\n [tokenTypeId(TokenTypes.BIT_OR)]: OpCode.BIT_OR,\n [tokenTypeId(TokenTypes.BIT_XOR)]: OpCode.BIT_XOR,\n [tokenTypeId(TokenTypes.OF)]: OpCode.MUL,\n };\n\n /** Shared with every BytecodeBuilder so a nested-body builder resolves plugin calls by name. */\n private pluginFunctionIndex?: ReadonlyMap<string, number>;\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\", pluginFunctionIndex?: ReadonlyMap<string, number>) {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n // Read once, not once per number literal. `localeCode` is set here and\n // never reassigned, so these cannot go stale, and the profile had\n // getLocale() plus its property chain inside the hot NUMBER path.\n const display = getLocale(localeCode).display;\n this.decimalSeparator = display.decimalSeparator;\n this.thousandsSeparator = display.thousandsSeparator;\n this.pluginFunctionIndex = pluginFunctionIndex;\n }\n\n /** Get locale code for NumberParselet to normalize separators */\n getLocaleCode(): string {\n return this.localeCode;\n }\n\n /**\n * Set the diagnostic pipeline for parselet matching events.\n * Cleared after each non-cached parse to avoid holding refs.\n */\n setDiagnosticPipeline(pipeline: DiagnosticPipeline | undefined, expression: string): void {\n this.diagnosticPipeline = pipeline;\n this.currentExpression = expression ?? \"\";\n }\n\n /**\n * Load tokens for parsing. Identical to Parser.load().\n *\n * @param hasParens - if false, skips the O(n) paren balance scan (~90% of expressions)\n */\n load(tokens: Token[], hasParens?: boolean): void {\n if (hasParens === false) {\n this.tokens = tokens;\n this.current = 0;\n this.depth = 0;\n return;\n }\n // Paren scan: count balance to skip array copy for balanced expressions.\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n let openCount = 0;\n for (let i = 0; i < tokens.length; i++) {\n if (tokens[i].typeId === LPAREN_ID) openCount++;\n else if (tokens[i].typeId === RPAREN_ID) openCount--;\n }\n this.tokens = openCount === 0 ? tokens : this.balanceParens(tokens, openCount);\n this.current = 0;\n this.depth = 0;\n }\n\n /**\n * Auto-balance unmatched parentheses.\n */\n private balanceParens(tokens: Token[], openCount: number): Token[] {\n const result = tokens.slice();\n if (openCount > 0) {\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n for (let i = 0; i < openCount; i++) {\n const lastToken = tokens[tokens.length - 1];\n result.push({\n type: TokenTypes.RPAREN,\n typeId: RPAREN_ID,\n value: \")\",\n text: \")\",\n offset: lastToken ? lastToken.offset + lastToken.text.length : 0,\n lineBreaks: 0,\n line: lastToken ? lastToken.line : 1,\n col: lastToken ? lastToken.col + lastToken.text.length : 1,\n } as Token);\n }\n } else if (openCount < 0) {\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n for (let i = 0; i < -openCount; i++) {\n result.unshift({\n type: TokenTypes.LPAREN,\n typeId: LPAREN_ID,\n value: \"(\",\n text: \"(\",\n offset: 0,\n lineBreaks: 0,\n line: 1,\n col: 1,\n } as Token);\n }\n }\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Main entry point: precedence climbing parse expression\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a full expression starting at the current token position.\n *\n * @param minBp - minimum binding power (precedence climbing threshold).\n * For left-associative operators, the recursive call uses `bp + 1`.\n * For right-associative operators (^), it uses `bp - 1`.\n * @param _builder - accepted for parselet API compatibility; always uses `this.builder`.\n */\n parseExpression(minBp: number = 0, _builder?: BytecodeBuilder): void {\n // Accept builder via parameter for backward compatibility with the old Parser API.\n // The ExpressionEngine always calls setBuilder() before parseExpression(),\n // but tests and parselets pass builder as a parameter.\n if (_builder) {\n this.builder = _builder;\n }\n this.depth++;\n if (this.depth > this.maxDepth) {\n this.depth--;\n throw ErrorFactory.parsing(\n \"NESTING_DEPTH_EXCEEDED\",\n `Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,\n { maxDepth: this.maxDepth, currentDepth: this.depth }\n );\n }\n\n const token = this.consume();\n if (!token) {\n this.depth--;\n throw ErrorFactory.parsing(\"UNEXPECTED_END\", \"Unexpected end of expression\");\n }\n\n // ── Prefix ──────────────────────────────────────────────────────────────\n this.parsePrefix(token);\n\n // ── Infix loop (precedence climbing with inline Tier 1 dispatch) ──────────\n const tokens = this.tokens;\n const len = tokens.length;\n const bpTable = PrecedenceParser.BP_TABLE;\n const registry = this.registry;\n const builder = this.builder;\n let idx = this.current;\n\n while (idx < len) {\n const lookahead = tokens[idx];\n if (!lookahead) break;\n\n const bp = bpTable[lookahead.typeId];\n if (bp > 0) {\n // Tier 1: Built-in infix, full inline emission, zero parselet delegation\n if (bp <= minBp) break;\n\n if (this.diagnosticPipeline) {\n // Fast path skips the registry, but built-ins are still registered\n // there (for introspection/tests), look them up only in this\n // diagnostics-only branch so the playground's \"matched parselets\"\n // view isn't permanently blind to every arithmetic operator.\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (infixParselet) {\n this.fireParseletMatched(infixParselet, lookahead, false, bp);\n }\n }\n\n this.current = ++idx;\n const typeId = lookahead.typeId;\n\n if (typeId === PrecedenceParser.PERCENT_ID) {\n // Postfix: no right operand. \"50%\" → Percentage holding 0.5.\n //\n // Must stay byte-for-byte equivalent to PercentParselet, which is\n // the Tier-2 registration of the same operator. This path is the one\n // that actually runs for ordinary expressions, so a change made only\n // in the parselet does nothing at all: that is exactly how the\n // divide-by-100 here outlived its replacement and kept `200 + 10%`\n // answering 200.10.\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(100);\n builder.emitOpcode(OpCode.DIV);\n builder.emitOpcode(OpCode.TO_PERCENTAGE);\n } else if (typeId === PrecedenceParser.CARET_ID && this.tryEmitMatrixCaretOp(builder)) {\n // `^T` (transpose) or `^-1` (inverse), already fully handled\n // including consuming their own trailing tokens.\n } else {\n // Infix: parse right operand, then emit opcode.\n // Right-associative for CARET (^), left-associative for all others.\n //\n // The threshold has to be bp - 1, not bp. The loop above breaks on\n // `bp <= minBp`, so a right operand parsed at `bp` stops at the next\n // `^` exactly as one parsed at `bp + 1` does: the old special case\n // was dead code and \"2 ^ 3 ^ 2\" grouped left, answering 64. One\n // below lets the recursive call keep consuming `^`, which is what\n // makes it 2^(3^2) = 512, as in mathematics, Python, Ruby and\n // JavaScript's `**`.\n //\n // Nothing else sits between Exponent (50) and Product (40), so\n // 49 cannot collide with another operator's level. Unary minus is\n // unaffected: it parses its operand at Prefix (60), above `^`\n // either way, so \"-2 ^ 2\" is still (-2)^2 = 4.\n const rightBp = (typeId === PrecedenceParser.CARET_ID) ? bp - 1 : bp + 1;\n this.parseExpression(rightBp, builder);\n builder.emitOpcode(PrecedenceParser.INFIX_OPCODE[typeId]);\n }\n } else {\n // Tier 2: Plugin parselet fallback, full flexibility for custom syntax\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (!infixParselet) break;\n if (infixParselet.bindingPower <= minBp) break;\n\n this.current = ++idx;\n\n if (this.diagnosticPipeline) {\n this.fireParseletMatched(infixParselet, lookahead, false, infixParselet.bindingPower);\n }\n // Expose the level this parselet is bound at, so one that peeks past its\n // own token (a unit literal weighing whether a trailing `in`/`to` is\n // its own or an outer operator's) can respect precedence. See\n // infixMinBindingPower's doc comment.\n this.infixMinBindingPower = minBp;\n // Parselet handles its own recursion for right operand internally\n infixParselet.parse(this, token, lookahead, builder);\n }\n\n idx = this.current;\n }\n\n this.current = idx;\n this.depth--;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Prefix dispatch: inline switch for built-ins, parselet registry for plugins\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a prefix token. Built-in tokens (NUMBER, IDENT, LPAREN, etc.) are\n * handled inline with zero registry lookup. Everything else falls through\n * to the parselet registry (Tier 2).\n */\n private parsePrefix(token: Token): void {\n const builder = this.builder;\n const typeId = token.typeId;\n\n if (this.diagnosticPipeline) {\n // Fast path below skips the registry for built-ins, but they're still\n // registered there (for introspection/tests), look up here so the\n // playground's \"matched parselets\" view isn't permanently blind to\n // every number, identifier, paren, and unary operator.\n const parselet = this.registry.getPrefix(typeId);\n if (parselet) {\n this.fireParseletMatched(parselet, token, true);\n }\n }\n\n switch (typeId) {\n // ── Numeric literals ──────────────────────────────────────────────────\n case PrecedenceParser.NUMBER_ID: {\n // Parse number with locale-aware separator normalization\n let v: number;\n // The exact dot-decimal text for a literal written with a fractional\n // point, so it can be pushed as PUSH_DECIMAL and keep its precision\n // where it later meets money. Stays null for every integer shape\n // (hex/bin/oct, chained-dot grouping, plain integers), which push the\n // ordinary PUSH_NUMBER and are unchanged.\n let decimalText: string | null = null;\n const raw = token.value;\n\n // Fast path: plain digits, with at most one \".\".\n //\n // Most literals in a document are `144`, `1200`, `0.85`. The general\n // path below reaches the same answer for them only after six\n // startsWith() calls, two regular expressions and a split/join that\n // allocated whether or not the separator was present; a CPU profile put\n // this whole case at over a third of parse-and-compile. One character\n // scan settles it instead.\n //\n // Guarded on the decimal separator being \".\", which is what makes a\n // lone dot unambiguous. Where \".\" groups thousands instead, `1.234`\n // means one thousand two hundred and thirty-four, so that locale has to\n // keep taking the general path.\n if (this.decimalSeparator === \".\") {\n let dots = 0;\n let plain = raw.length > 0;\n for (let i = 0; i < raw.length; i++) {\n const c = raw.charCodeAt(i);\n if (c >= 48 && c <= 57) continue;\n if (c === 46 && dots === 0) { dots = 1; continue; }\n plain = false;\n break;\n }\n if (plain) {\n // One dot with digits optional on either side is exactly what\n // PLAIN_DECIMAL matches, so this agrees with it: that is the signal\n // for the exact-decimal opcode rather than a double.\n if (dots === 1) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(raw);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(+raw);\n return;\n }\n }\n\n if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n v = parseInt(raw, 16);\n // A prefix with no digits after it (\"0x\" alone) makes parseInt\n // return NaN. This used to push straight through as a silent\n // NaN Number value instead of a visible error.\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid hex literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0b\") || raw.startsWith(\"0B\")) {\n v = parseInt(raw.slice(2), 2);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid binary literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0o\") || raw.startsWith(\"0O\")) {\n v = parseInt(raw.slice(2), 8);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid octal literal: \"${raw}\"`, { raw });\n }\n } else if (CHAINED_DOT_THOUSANDS_GROUPS.test(raw)) {\n // The lexer accepts \".\" as a thousands-group separator\n // independent of locale (ExpressionLexer's number-scanning\n // \"Thousands separators\" block), but the locale-based\n // normalization below only strips the ACTIVE locale's own\n // configured thousandsSeparator character, for \"en\" that's\n // \",\", not \".\", so a chained dot-grouped literal like\n // \"1.234.567\" fell through to parseFloat() untouched, which\n // stops at the second \".\" and silently truncated it to 1.234\n // (over 99% of the digits dropped, with no error). This is the\n // REAL number-parsing path for actual evaluation, Tier 1 of\n // the two-tier dispatch above always returns for NUMBER_ID, so\n // NumberParselet.parse() (which has the identical fix) never\n // actually runs except via direct unit tests / the \"matched\n // parselets\" diagnostic display.\n v = parseFloat(raw.split(\".\").join(\"\"));\n } else {\n const decimalSep = this.decimalSeparator;\n const thousandsSep = this.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation).\n // The indexOf guard stops that pair allocating an array and a string\n // for the many literals that contain no separator at all.\n if (thousandsSep && normalized.indexOf(thousandsSep) !== -1) {\n normalized = normalized.split(thousandsSep).join(\"\");\n }\n // Replace locale decimal separator with \".\" for JavaScript parsing\n if (decimalSep && decimalSep !== \".\") {\n normalized = normalized.replace(decimalSep, \".\");\n }\n v = parseFloat(normalized);\n // A plain fractional literal (digits, one dot, digits) is what carries\n // an exact decimal. Scientific notation like \"2.5e-3\" has a dot too\n // but no exact base-ten form worth the trouble, so it stays a\n // PUSH_NUMBER double, and so does any integer (grouping stripped).\n if (PLAIN_DECIMAL.test(normalized)) decimalText = normalized;\n }\n if (decimalText !== null) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(decimalText);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(v);\n return;\n }\n\n case PrecedenceParser.BIGINT_ID: {\n // Strips the `n` and any thousands grouping the lexer coalesced in.\n // This used to be `raw.slice(0, -1)` and nothing else, so `1.000n`\n // reached BigInt(\"1.000\") and threw a raw SyntaxError. See\n // parser/BigIntLiteral.ts, which the parselet tier shares.\n builder.emitOpcode(OpCode.PUSH_BIGINT);\n builder.emitString(bigIntLiteralDigits(token.value, this.localeCode));\n return;\n }\n\n case PrecedenceParser.STRING_ID: {\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(token.value);\n return;\n }\n\n // ── Identifiers (variables) ────────────────────────────────────────────\n case PrecedenceParser.IDENT_ID: {\n // An identifier immediately followed by \"(\" may be a user-defined\n // function DEFINITION (`f(x) = ...`) or CALL (`f(5)`). See\n // parseUserFunctionDefOrCall's doc comment for the full\n // disambiguation. Only the (cheap) LPAREN check runs for the\n // overwhelmingly common case of a bare identifier with nothing\n // following it.\n if (this.peek()?.typeId === PrecedenceParser.LPAREN_ID) {\n this.parseUserFunctionDefOrCall(token, builder);\n return;\n }\n // IDENT tokens map to LOAD_VAR by default. The IdentifierParselet\n // and VariableParselet add STORE_VAR for assignments, those are\n // handled via the parselet registry below. Note this is also how a\n // user-defined function's own PARAMETER references compile. See\n // UserFunctionDef's doc comment in BytecodeBuilder.ts for why there\n // is no separate parameter-load opcode: `LOAD_VAR` resolution\n // dynamically checks the VM's innermost call frame first.\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(token.value);\n return;\n }\n\n // ── Grouping / bare-tuple vector literal ─────────────────────────────────\n // `(expr)` groups for precedence; `(x, y[, z[, w]])` is the bare-tuple\n // vector literal documented as an alternative to vec2/vec3/vec4(...)\n // (wiki: Arithmetic/Vector). This Tier-1 case is what actually runs for\n // every LPAREN in production parsing, GroupParselet.ts mirrors this\n // logic for registry-introspection/diagnostic-listing purposes, but a\n // package can never override LPAREN's dispatch here (Tier 1 always\n // wins over the ParseletRegistry fallback below), so both must be kept\n // in sync by hand.\n case PrecedenceParser.LPAREN_ID: {\n this.parseExpression(0, builder);\n let count = 1;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(0, builder);\n count++;\n }\n this.consume(TokenTypes.RPAREN);\n if (count > 1) {\n // Legacy bare-tuple vector sugar, a 1xN row-vector Matrix (see\n // packages/vector/parselets/VectorParselet.ts's comment).\n builder.emitOpcode(OpCode.MAT_NEW);\n builder.emitIndex(1);\n builder.emitIndex(count);\n }\n return;\n }\n\n // ── Unary operators ───────────────────────────────────────────────────\n case PrecedenceParser.MINUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.NEG);\n return;\n }\n\n case PrecedenceParser.PLUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.POS);\n return;\n }\n\n // ── Keyword constants ─────────────────────────────────────────────────\n case PrecedenceParser.KEYWORD_ID: {\n // Keywords are handled by parselets (pi→PI, e→E, etc.)\n // Fall through to registry below.\n }\n }\n\n // ── Tier 2: Plugin/parselet prefix path ──────────────────────────────────\n const prefixParselet = this.registry.getPrefix(typeId);\n if (!prefixParselet) {\n throw ErrorFactory.parsing(\n \"NO_PREFIX_PARSELET\",\n `No prefix parselet found for token: ${token.type} (\"${token.value}\")`,\n { tokenType: token.type, tokenValue: token.value }\n );\n }\n\n prefixParselet.parse(this, token, builder);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // The \"Tier-1 shape-exception\" pattern\n // ═══════════════════════════════════════════════════════════════════════════════\n //\n // Tier 1 exists purely for performance, avoid a Map lookup + parselet call\n // on ~95% of tokens (see this file's own module doc comment above). A\n // recurring consequence: any grammar shape tied to a Tier-1 token type can\n // ONLY be implemented by hand-editing this switch, since a package-\n // registered ParseletRegistry parselet for that same token type would\n // simply never run in production (Tier 1 always wins over the registry\n // fallback). Five confirmed instances of this tension exist in this file\n // (plus one that had to move OUTSIDE it entirely):\n // 1. NUMBER_ID, the full locale-aware number-literal parsing (hex/\n // binary/octal, chained-dot thousands grouping, decimal-separator\n // normalization) is inlined in parsePrefix() above; NumberParselet.ts's\n // own copy is dead code for real evaluation, kept registered only for\n // the \"matched parselets\" diagnostic view.\n // 2. IDENT_ID, parseUserFunctionDefOrCall's lookahead (below) disambig-\n // uates a function DEFINITION from a CALL from a plain variable load.\n // 3. LPAREN_ID, the bare-tuple vector-literal sugar (\"(x,y[,z[,w]])\" ->\n // MAT_NEW) is inlined in parsePrefix() above; GroupParselet.ts mirrors\n // it for introspection only and must be kept in sync by hand.\n // 4. CARET_ID, the transpose/inverse suffix table just below.\n // 5. PLUS_ID, the locale word \"and\" lexes as PLUS (Tier-1, fixed Sum\n // binding power), so a registry parselet can never intercept it the\n // way LogicalParselet.ts intercepts \"or\"/&&/||; unlike the other four,\n // there's no SHAPE to special-case on here (the token itself IS the\n // operator), so the workaround lives entirely outside this file, as a\n // runtime Boolean/Boolean type-check inside vm/VM.ts's OpCode.ADD\n // handler instead.\n //\n // Deliberate non-goal: none of this is exposed as an IEnginePackage\n // extension point (unlike prefixParselets/infixParselets). Letting\n // third-party packages register their own Tier-1 shape-matchers would put\n // per-package matcher iteration on a genuinely hot path (every CARET/\n // NUMBER/IDENT/LPAREN/PLUS token, matched or not), a materially bigger\n // separate product decision than \"make this one table more concise,\" and\n // not one this pattern write-up makes.\n\n /**\n * A single `^`-suffix shape: `matches` peeks ahead (consuming nothing) to\n * check whether this shape starts at the current position; `emit` is only\n * called immediately after `matches` returned true for that SAME position,\n * and is responsible for consuming that shape's own trailing tokens and\n * emitting its bytecode.\n */\n private static readonly CARET_SUFFIX_RULES: ReadonlyArray<{\n name: string;\n matches(parser: PrecedenceParser): boolean;\n emit(parser: PrecedenceParser, builder: BytecodeBuilder): void;\n }> = [\n {\n name: \"transpose (^T)\",\n matches: (p) => {\n const next = p.peek();\n return next?.type === TokenTypes.IDENT && next.value === \"T\";\n },\n emit: (p, builder) => {\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(63); // transpose — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n {\n name: \"inverse (^-1)\",\n matches: (p) => {\n const next = p.peek();\n if (next?.typeId !== PrecedenceParser.MINUS_ID) return false;\n const afterMinus = p.peekAt(1);\n return afterMinus?.type === TokenTypes.NUMBER && afterMinus.value === \"1\";\n },\n emit: (p, builder) => {\n p.advance();\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(65); // inv — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n ];\n\n /**\n * After a `^` token (already consumed by the Tier-1 infix loop above),\n * checks {@link CARET_SUFFIX_RULES} in order for a shape that means\n * something other than ordinary exponentiation: `^T` (transpose) and `^-1`\n * (matrix inverse, LITERALLY the integer exponent `-1`; `^-2`, `^-1.5`\n * etc. still mean ordinary exponentiation). On a match, the rule's `emit`\n * consumes that shape's own tokens and this returns `true`. On no match,\n * consumes NOTHING, returning `false` so the caller falls through to\n * ordinary `EXP` parsing.\n *\n * Every rule dispatches purely on SHAPE, never on operand type (unknowable\n * at parse time): `inv()`'s own handler (`VMBuiltins.ts` index 65) returns\n * `1/x` for a plain Number, byte-identical to what `Math.pow(x, -1)`\n * already computed for `x^-1` before this feature existed, and a real\n * matrix inverse for a Matrix, so `5^-1` still means exactly what it always\n * has; only a Matrix operand actually inverts.\n *\n * Adding a future `^`-suffix shape is a new table entry here, not a new\n * if-block. See the \"Tier-1 shape-exception\" pattern write-up above for\n * why this table can't instead be a package-registered parselet.\n */\n private tryEmitMatrixCaretOp(builder: BytecodeBuilder): boolean {\n for (const rule of PrecedenceParser.CARET_SUFFIX_RULES) {\n if (rule.matches(this)) {\n rule.emit(this, builder);\n return true;\n }\n }\n return false;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // User-defined, parameterized, reusable functions (f(x) = 2*x + 1, then f(5))\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * From an LPAREN token index, scan forward tracking paren depth and\n * return the index of the matching RPAREN, or `null` if the parens never\n * balance before the token stream ends. No emission, no position\n * advance. Same class of technique as {@link balanceParens}'s own\n * pre-scan, just exposed mid-parse instead of only at `load()` time.\n * `openIdx` must point AT the LPAREN itself.\n */\n private findMatchingRParen(openIdx: number): number | null {\n let depth = 0;\n for (let i = openIdx; i < this.tokens.length; i++) {\n const t = this.tokens[i];\n if (t.typeId === PrecedenceParser.LPAREN_ID) depth++;\n else if (t.typeId === PrecedenceParser.RPAREN_ID) {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n }\n\n /**\n * Disambiguates a bare `IDENT` immediately followed by `(` between three\n * things, using ONLY a bracket-depth scan (no backtracking, nothing is\n * consumed until the shape is known):\n * - `f(x) = expr`, a DEFINITION: the matching `)` is followed by `=`.\n * - `f(5)`, a CALL to a (possibly not-yet-defined) function: anything\n * else. This was never valid syntax before this feature (a bare\n * `IDENT` immediately before `(` has no pre-existing \"plain variable\n * read + separately grouped `(...)`\" meaning to preserve, confirmed\n * via `BuiltinNormalizerRules.ts`'s `implicitMultiplyRule()`, which\n * only inserts an implicit `*` for `NUMBER/RPAREN` immediately before\n * `IDENT/LPAREN`, never for a bare `IDENT` immediately before\n * `LPAREN`). Always commits to a CALL; an unregistered name produces a\n * clear `UNDEFINED_FUNCTION` error at VM-execution time, the same\n * forward-reference philosophy `LOAD_VAR`/`UNDEFINED_VARIABLE` already\n * uses, rather than any parse-time registry lookup.\n * If the parens never balance, this falls through to the ordinary\n * `LOAD_VAR` path (a malformed expression surfaces its own parse error\n * shortly after, from the normal expression grammar).\n */\n private parseUserFunctionDefOrCall(nameToken: Token, builder: BytecodeBuilder): void {\n const closeIdx = this.findMatchingRParen(this.current);\n if (closeIdx === null) {\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(nameToken.value);\n return;\n }\n const afterClose = this.tokens[closeIdx + 1];\n if (afterClose?.type === TokenTypes.EQUALS) {\n this.parseUserFunctionDefinition(nameToken, builder);\n } else {\n this.parseUserFunctionCall(nameToken, builder);\n }\n }\n\n /**\n * A parameter name, accepted as either `IDENT` or `UNIT`, matches this\n * codebase's established `:name = value` variable-name policy\n * (`VariableParselet.ts` explicitly accepts `UNIT`-typed tokens too, e.g.\n * `:b = 5` for the \"b\" bits unit) since common short parameter names\n * like `h`/`l`/`b`/`t`/`s`/`m` collide with real unit abbreviations\n * (hour, liter, bits, ton, second, meter, ...) and lex as `UNIT`, not\n * `IDENT`.\n */\n private consumeParamName(): string {\n const token = this.peek();\n if (token?.type === TokenTypes.IDENT || token?.type === TokenTypes.UNIT) {\n this.consume();\n return token.value;\n }\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_INVALID_PARAM_NAME\",\n `Expected a parameter name but got \"${token?.type ?? \"end of input\"}\"${token ? ` (\"${token.value}\")` : \"\"}`,\n { actualType: token?.type },\n );\n }\n\n private parseUserFunctionDefinition(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n const params: string[] = [];\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n params.push(this.consumeParamName());\n while (this.match(TokenTypes.COMMA)) {\n params.push(this.consumeParamName());\n }\n }\n this.consume(TokenTypes.RPAREN);\n this.consume(TokenTypes.EQUALS);\n\n if (params.length === 0) {\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_NO_PARAMS\",\n `\"${nameToken.value}()\" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,\n { name: nameToken.value },\n );\n }\n\n // Compile the body into its OWN independent BytecodeBuilder, reusing\n // the SAME parser/token stream but directing emission elsewhere.\n // `parseExpression(minBp, _builder)` sets `this.builder = _builder`\n // with NO automatic restore, explicitly restoring via `setBuilder()`\n // afterward (not a `finally`, since a thrown parse error here should\n // propagate as-is; there's no further use of `this.builder` on that\n // path before the whole parse aborts) avoids silently emitting\n // whatever parses next (in this same expression, or, via\n // ExpressionEngine's builder pool, a LATER, unrelated line) into a\n // stale, already-.build()'d body builder.\n const bodyBuilder = new BytecodeBuilder(this.pluginFunctionIndex);\n this.parseExpression(BindingPower.Lowest, bodyBuilder);\n this.setBuilder(builder);\n\n const bodyProgram = bodyBuilder.build();\n if (bodyProgram.hasAsync) {\n // v1 scope decision: a function body calling an async plugin\n // (weather, stocks, currency, ...) isn't supported yet, propagating\n // a 'pending' result up through a reentrant executeBytecode() call\n // would need the OUTER expression's own bytecode position/stack\n // state to also be resumable later, which this first pass doesn't\n // implement. Rejecting at DEFINITION time (not call time) gives the\n // clearest possible error, matching this codebase's \"never silently\n // pretend to support something it doesn't\" convention (e.g.\n // addBusinessDays()'s own disclosed holiday-exclusion scope-down).\n throw ErrorFactory.parsing(\n \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n `\"${nameToken.value}(...)\"'s body calls an async operation (weather, stocks, currency, ...) — user-defined function bodies must be synchronous`,\n { name: nameToken.value },\n );\n }\n\n const bodyIdx = builder.emitUserFunctionBody(nameToken.value, params, bodyProgram);\n builder.emitOpcode(OpCode.DEFINE_USER_FUNCTION);\n builder.emitIndex(bodyIdx);\n\n // A definition line has no single input value to echo back the way an\n // assignment does, push a plain confirmation string, matching this\n // codebase's \"never silently produce a misleading numeric 0\" principle.\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(`${nameToken.value}(${params.join(\", \")}) defined`);\n }\n\n private parseUserFunctionCall(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n let argCount = 0;\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n this.consume(TokenTypes.RPAREN);\n\n builder.emitOpcode(OpCode.CALL_USER_FUNCTION);\n builder.emitString(nameToken.value);\n builder.emitByte(argCount);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Token stream navigation (identical API to Parser)\n // ═══════════════════════════════════════════════════════════════════════════════\n\n consume(expectedType?: string): Token {\n const token = this.tokens[this.current];\n if (!token) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_END_OF_INPUT\",\n \"Unexpected end of input\"\n );\n }\n if (expectedType !== undefined) {\n const expectedId = tokenTypeId(expectedType);\n if (token.typeId !== expectedId) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_TOKEN_TYPE\",\n `Expected token type \"${expectedType}\" but got \"${token.type}\" (\"${token.value}\")`,\n { expectedType, actualType: token.type, actualValue: token.value }\n );\n }\n }\n this.current++;\n return token;\n }\n\n match(expectedType: string): boolean {\n const token = this.peek();\n if (token && token.typeId === tokenTypeId(expectedType)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n peek(): Token | undefined {\n return this.tokens[this.current];\n }\n\n /**\n * Read-only lookahead `offset` tokens past the current position, without\n * consuming anything, `peekAt(0)` is equivalent to {@link peek}.\n * `this.tokens` is a plain in-memory array (not a stream), so this is a\n * simple, safe index read; no rewind/checkpoint mechanism is needed since\n * nothing is consumed.\n */\n peekAt(offset: number): Token | undefined {\n return this.tokens[this.current + offset];\n }\n\n previous(): Token | undefined {\n return this.current > 0 ? this.tokens[this.current - 1] : undefined;\n }\n\n private advance(): void {\n this.current++;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Builder access, set before parse, read by inline prefix handlers\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /** Set the builder to use for the current parse. Called by ExpressionEngine. */\n setBuilder(builder: BytecodeBuilder): void {\n this.builder = builder;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Diagnostics\n // ═══════════════════════════════════════════════════════════════════════════════\n\n private fireParseletMatched(\n parselet: { category: string },\n token: Token,\n isPrefix: boolean,\n bindingPower?: number\n ): void {\n const pipeline = this.diagnosticPipeline!;\n const event: DiagnosticEvent & { type: \"parselet_matched\" } = {\n type: DiagnosticEventType.ParseletMatched,\n elapsedNs: 0,\n expression: this.currentExpression,\n tokenType: token.type,\n tokenValue: token.value,\n parseletCategory: parselet.category,\n parseletType: parselet.constructor?.name ?? \"unknown\",\n isPrefix,\n bindingPower,\n tokenOffset: token.offset || 0,\n };\n pipeline.fireParseletMatched(event);\n }\n}\n","import { PrefixParselet, InfixParselet } from \"@solve-js/parser/Parselet\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\n\n/**\n * The one binding-power field a parselet may expose beyond what its interface\n * requires, read only for diagnostic display.\n *\n * `InfixParselet` requires `bindingPower`; `PrefixParselet` declares none, and\n * some prefix parselets carry one anyway. That single field is the whole\n * optional surface deliberately. A `leftBindingPower`/`rightBindingPower` pair\n * used to be read here as well, and reading a name off an object this way finds\n * PRIVATE fields too, since TypeScript's `private` exists only at compile time:\n * `BinaryOpParselet` holds a private `rightBindingPower` meaning \"the minimum\n * power to parse my right operand at\", which is a different quantity from \"the\n * power at which I bind to my right\" and differs from it by one. Reading it\n * silently reported that other number. So neither is read.\n *\n * `category` is not here: both interfaces already declare it.\n */\ninterface ParseletBindingPowers {\n\treadonly bindingPower?: number;\n}\n\n/** Reads the optional binding-power field off a parselet for diagnostics. */\nfunction bindingPowersOf(parselet: PrefixParselet | InfixParselet): ParseletBindingPowers {\n\treturn parselet as ParseletBindingPowers;\n}\n\n/**\n * Dual-keyed ParseletRegistry, accepts both string token types and\n * integer token type IDs for fast dispatch in the Parser hot path.\n *\n * Providers call registerPrefix(\"NUMBER\", ...) with string token types.\n * Internally, we populate both string-keyed and integer-keyed maps so\n * Parser.parseExpression() can use token.typeId (integer) for lookup\n * while diagnostics and error messages use token.type (string).\n *\n * Performance: Integer Map.get() avoids string hashing, saving ~2-5ns\n * per dispatch. With ~10-15 dispatches per expression, that's ~20-75ns.\n */\nexport class ParseletRegistry {\n\t// String-keyed maps (kept for diagnostics + backwards compat)\n\tprivate prefixParselets: Map<string, PrefixParselet> = new Map();\n\tprivate infixParselets: Map<string, InfixParselet> = new Map();\n\n\t// Integer-keyed maps for parser hot path\n\tprivate prefixById: Map<number, PrefixParselet> = new Map();\n\tprivate infixById: Map<number, InfixParselet> = new Map();\n\n\t/**\n\t * Register a prefix parselet for `tokenType`.\n\t *\n\t * If another parselet is already registered for this token type, it is\n\t * silently overwritten by default (`Map.set()` semantics), the old\n\t * parselet is simply unreachable from then on, with no error. This is\n\t * a real footgun for third-party packages: two packages independently\n\t * choosing the same custom token type will collide with zero signal\n\t * about which one \"won\". Mirrors ResolverRegistry.register()'s and\n\t * ExpressionEngine.registerPackage()'s existing \"warn and replace\"\n\t * pattern for the same class of problem at the resolver-namespace and\n\t * package-name levels.\n\t *\n\t * Note: this warns about registry-level collisions only. It does NOT\n\t * detect the separate case where `tokenType` is one of PrecedenceParser's\n\t * Tier-1 fast-path token types (NUMBER, STRING, IDENT, LPAREN, MINUS,\n\t * PLUS, and the Tier-1 infix operators), those are deliberately kept\n\t * registered here for introspection/diagnostics even though Tier-1\n\t * always intercepts them before this registry is consulted (see\n\t * PrecedenceParser.parsePrefix()'s docs), so warning there would\n\t * misfire on that intentional, already-documented pattern.\n\t */\n\tregisterPrefix(tokenType: string, parselet: PrefixParselet): void {\n\t\tconst existing = this.prefixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Prefix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.prefixParselets.set(tokenType, parselet);\n\t\tthis.prefixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/** Register an infix parselet for `tokenType`. See {@link registerPrefix} for the collision-warning behavior this mirrors. */\n\tregisterInfix(tokenType: string, parselet: InfixParselet): void {\n\t\tconst existing = this.infixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Infix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.infixParselets.set(tokenType, parselet);\n\t\tthis.infixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/**\n\t * Iterate all registered prefix parselets for diagnostic display.\n\t *\n\t * `PrefixParselet` declares no binding power, and this used to read a field\n\t * of that name and report 0 for every one of them. 0 is not a neutral\n\t * wrong answer: it is the value that means \"not an operator, stop the\n\t * expression\", so a host drawing a table from this was told none of them\n\t * bind at all. A prefix parselet in this parser has no per-parselet power\n\t * to report, they all bind at the prefix level and each chooses for itself\n\t * at what power to parse its own operand, so that level is what is\n\t * reported. A parselet that does carry its own `bindingPower` still wins.\n\t */\n\tgetAllPrefix(): Array<{ tokenType: string; bindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; bindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.prefixParselets) {\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tbindingPower: bindingPowersOf(parselet).bindingPower ?? BindingPower.Prefix,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterate all registered infix parselets for diagnostic display.\n\t *\n\t * The field an `InfixParselet` actually declares is `bindingPower`. This\n\t * used to read `leftBindingPower` and `rightBindingPower`, which no\n\t * parselet in this codebase declares, so both reads were `undefined`, both\n\t * fell to the `?? 0` default, and the public `getParseletRegistry()`\n\t * reported a binding power of 0 for every one of the ~60 infix operators.\n\t * A host building a precedence table from it was told `*` and `+` bind\n\t * equally, and that neither binds at all.\n\t *\n\t * The left/right split: `bindingPower` is the LEFT power, and the right is\n\t * one higher. That is the standard encoding for a left-associative\n\t * operator, and it is what the parser itself does, see\n\t * `PrecedenceParser.parseExpression()`'s `bp + 1` for the right operand.\n\t * Every operator is reported that way, `^` included. Associativity is not\n\t * something a parselet declares, it is a property of how each one calls\n\t * `parseExpression`, so this API cannot report it without a new field on\n\t * the interface. See {@link ParseletBindingPowers} for why scraping a\n\t * plausible-looking one off the parselet is worse than not reporting it.\n\t */\n\tgetAllInfix(): Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.infixParselets) {\n\t\t\tconst left = bindingPowersOf(parselet).bindingPower ?? 0;\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tleftBindingPower: left,\n\t\t\t\trightBindingPower: left + 1,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Number of registered prefix parselets. */\n\tget prefixCount(): number { return this.prefixParselets.size; }\n\n\t/** Number of registered infix parselets. */\n\tget infixCount(): number { return this.infixParselets.size; }\n\n\t/**\n\t * Get prefix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings\n\t * (diagnostics, error messages, backwards compatibility).\n\t */\n\tgetPrefix(tokenType: string | number): PrefixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.prefixById.get(tokenType);\n\t\treturn this.prefixParselets.get(tokenType);\n\t}\n\n\t/**\n\t * Get infix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings.\n\t */\n\tgetInfix(tokenType: string | number): InfixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.infixById.get(tokenType);\n\t\treturn this.infixParselets.get(tokenType);\n\t}\n\n\thasPrefix(tokenType: string): boolean {\n\t\treturn this.prefixParselets.has(tokenType);\n\t}\n\n\thasInfix(tokenType: string): boolean {\n\t\treturn this.infixParselets.has(tokenType);\n\t}\n\n\tclear(): void {\n\t\tthis.prefixParselets.clear();\n\t\tthis.infixParselets.clear();\n\t\tthis.prefixById.clear();\n\t\tthis.infixById.clear();\n\t}\n}\n\n/**\n * A process-wide parselet registry.\n *\n * @deprecated An engine builds its own registry and does not read this one, so\n * registering here reaches nothing that evaluates. Nothing writes to it now\n * that the global package-registration path is gone; it remains only so the\n * `@solve-js/parser` escape hatch keeps a stable shape.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n"]}
|