solve-engine 2.5.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BytecodeBuilder-DGGeByAP.d.cts → BytecodeBuilder-BGq9ZiO3.d.cts} +2 -1
- package/dist/{BytecodeBuilder-DGGeByAP.d.ts → BytecodeBuilder-BGq9ZiO3.d.ts} +2 -1
- package/dist/{PackageCompatibility-UsSZIfHs.d.ts → PackageCompatibility-4QtIErfx.d.ts} +1 -1
- package/dist/{PackageCompatibility-cEClSSkz.d.cts → PackageCompatibility-CCdud__Q.d.cts} +1 -1
- package/dist/{PackageRegistry-B3yJHSxX.d.ts → PackageRegistry-B7wkfSrY.d.ts} +5 -5
- package/dist/{PackageRegistry-BsLmAVZJ.d.cts → PackageRegistry-Hx85XD01.d.cts} +5 -5
- package/dist/{Parselet-C4Wu055_.d.cts → Parselet-CTNpfuEB.d.cts} +2 -2
- package/dist/{Parselet-B-zoPrTa.d.ts → Parselet-DONNUpur.d.ts} +2 -2
- package/dist/{ScopeManager-DkpnlKuz.d.ts → ScopeManager-BkbDXK_R.d.ts} +3 -3
- package/dist/{ScopeManager-t6SnP6Ce.d.cts → ScopeManager-Cvgypcu4.d.cts} +3 -3
- package/dist/{VMCheckpoints-CsHmQVaD.d.ts → VMCheckpoints-9zBQnTsN.d.ts} +3 -3
- package/dist/{VMCheckpoints-C_jQvABf.d.cts → VMCheckpoints-CBMGiSqw.d.cts} +3 -3
- package/dist/{Value-CCi_Eecs.d.cts → Value-D1XlMwe2.d.cts} +40 -5
- package/dist/{Value-CCi_Eecs.d.ts → Value-D1XlMwe2.d.ts} +40 -5
- package/dist/chunk-3AVWA5IZ.cjs +2 -0
- package/dist/chunk-3AVWA5IZ.cjs.map +1 -0
- package/dist/chunk-3DD2RVBI.cjs +3 -0
- package/dist/chunk-3DD2RVBI.cjs.map +1 -0
- package/dist/{chunk-RDMJNRDO.js → chunk-4XTD4B77.js} +3 -3
- package/dist/{chunk-RDMJNRDO.js.map → chunk-4XTD4B77.js.map} +1 -1
- package/dist/chunk-5FGOIDLS.cjs +2 -0
- package/dist/chunk-5FGOIDLS.cjs.map +1 -0
- package/dist/chunk-5OIXCVB2.js +3 -0
- package/dist/chunk-5OIXCVB2.js.map +1 -0
- package/dist/{chunk-NGJMCVH4.cjs → chunk-B4P4M4ZW.cjs} +3 -3
- package/dist/{chunk-NGJMCVH4.cjs.map → chunk-B4P4M4ZW.cjs.map} +1 -1
- package/dist/{chunk-TWC7K3ZX.js → chunk-GHW2X7PS.js} +2 -2
- package/dist/{chunk-TWC7K3ZX.js.map → chunk-GHW2X7PS.js.map} +1 -1
- package/dist/chunk-GKDZ7TSX.cjs +2 -0
- package/dist/chunk-GKDZ7TSX.cjs.map +1 -0
- package/dist/{chunk-7RTKJMYS.js → chunk-HMEZJXLX.js} +2 -2
- package/dist/{chunk-7RTKJMYS.js.map → chunk-HMEZJXLX.js.map} +1 -1
- package/dist/{chunk-FDE5HWDI.cjs → chunk-HOQU47MF.cjs} +2 -2
- package/dist/{chunk-FDE5HWDI.cjs.map → chunk-HOQU47MF.cjs.map} +1 -1
- package/dist/chunk-IO374J6Z.js +2 -0
- package/dist/chunk-IO374J6Z.js.map +1 -0
- package/dist/{chunk-D5MTMRHS.cjs → chunk-KSDTVFXA.cjs} +4 -4
- package/dist/{chunk-D5MTMRHS.cjs.map → chunk-KSDTVFXA.cjs.map} +1 -1
- package/dist/{chunk-YUJNMUKM.cjs → chunk-OVQ3V4CG.cjs} +2 -2
- package/dist/{chunk-YUJNMUKM.cjs.map → chunk-OVQ3V4CG.cjs.map} +1 -1
- package/dist/{chunk-XNIWQHXY.js → chunk-P6BLASAA.js} +2 -2
- package/dist/{chunk-XNIWQHXY.js.map → chunk-P6BLASAA.js.map} +1 -1
- package/dist/{chunk-AXMQG5TS.cjs → chunk-R7T3NGUE.cjs} +2 -2
- package/dist/{chunk-AXMQG5TS.cjs.map → chunk-R7T3NGUE.cjs.map} +1 -1
- package/dist/{chunk-CT5TC3JX.cjs → chunk-SOSUS2SK.cjs} +3 -3
- package/dist/chunk-SOSUS2SK.cjs.map +1 -0
- package/dist/chunk-SWKYVSMP.js +2 -0
- package/dist/chunk-SWKYVSMP.js.map +1 -0
- package/dist/chunk-T4Y5XOT2.js +3 -0
- package/dist/chunk-T4Y5XOT2.js.map +1 -0
- package/dist/{chunk-LOM3H5ZD.js → chunk-T52Y5G24.js} +4 -4
- package/dist/{chunk-LOM3H5ZD.js.map → chunk-T52Y5G24.js.map} +1 -1
- package/dist/{chunk-JFAJN3C2.cjs → chunk-VBSMA7WJ.cjs} +2 -2
- package/dist/chunk-VBSMA7WJ.cjs.map +1 -0
- package/dist/{chunk-RSF25YSJ.js → chunk-VYWGUMFW.js} +2 -2
- package/dist/{chunk-RSF25YSJ.js.map → chunk-VYWGUMFW.js.map} +1 -1
- package/dist/chunk-XTM4HTRB.js +2 -0
- package/dist/{chunk-LBNX7TXI.js.map → chunk-XTM4HTRB.js.map} +1 -1
- package/dist/{chunk-E6Z4NQAS.js → chunk-YNMMRH44.js} +2 -2
- package/dist/chunk-YNMMRH44.js.map +1 -0
- package/dist/chunk-Z5KBBQOJ.cjs +2 -0
- package/dist/{chunk-YFWAR766.cjs.map → chunk-Z5KBBQOJ.cjs.map} +1 -1
- package/dist/chunk-ZJPAPBP3.js +2 -0
- package/dist/chunk-ZJPAPBP3.js.map +1 -0
- package/dist/{chunk-N7N7MPMK.cjs → chunk-ZOOVGXMK.cjs} +2 -2
- package/dist/{chunk-N7N7MPMK.cjs.map → chunk-ZOOVGXMK.cjs.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +8 -8
- package/dist/engine.d.ts +8 -8
- package/dist/engine.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.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +1 -1
- package/dist/language.d.cts +7 -7
- package/dist/language.d.ts +7 -7
- 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 +4 -4
- package/dist/parser.d.ts +4 -4
- package/dist/parser.js +1 -1
- package/dist/{pipeline-72QmQlGx.d.ts → pipeline-BH7BFOTJ.d.ts} +3 -3
- package/dist/{pipeline-DCQicwWX.d.cts → pipeline-DY0rhgQG.d.cts} +3 -3
- package/dist/resolvers.d.cts +2 -2
- package/dist/resolvers.d.ts +2 -2
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +7 -7
- package/dist/testing.d.ts +7 -7
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +2 -2
- package/dist/uom.d.ts +2 -2
- 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 +22 -6
- package/dist/worker.d.ts +22 -6
- package/dist/worker.js +2 -2
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2HQWM5OB.js +0 -3
- package/dist/chunk-2HQWM5OB.js.map +0 -1
- package/dist/chunk-6G3PMEPA.js +0 -2
- package/dist/chunk-6G3PMEPA.js.map +0 -1
- package/dist/chunk-6INX773F.cjs +0 -2
- package/dist/chunk-6INX773F.cjs.map +0 -1
- package/dist/chunk-6ZNNPXXE.cjs +0 -3
- package/dist/chunk-6ZNNPXXE.cjs.map +0 -1
- package/dist/chunk-ANJPS6FF.cjs +0 -2
- package/dist/chunk-ANJPS6FF.cjs.map +0 -1
- package/dist/chunk-B5NBFGNP.js +0 -3
- package/dist/chunk-B5NBFGNP.js.map +0 -1
- package/dist/chunk-CT5TC3JX.cjs.map +0 -1
- package/dist/chunk-E6Z4NQAS.js.map +0 -1
- package/dist/chunk-EVAOPEO4.js +0 -2
- package/dist/chunk-EVAOPEO4.js.map +0 -1
- package/dist/chunk-JFAJN3C2.cjs.map +0 -1
- package/dist/chunk-LBNX7TXI.js +0 -2
- package/dist/chunk-PS272DZJ.cjs +0 -2
- package/dist/chunk-PS272DZJ.cjs.map +0 -1
- package/dist/chunk-QEYTENAK.js +0 -2
- package/dist/chunk-QEYTENAK.js.map +0 -1
- package/dist/chunk-YFWAR766.cjs +0 -2
|
@@ -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","pipeline","expression","tokens","hasParens","LPAREN_ID","tokenTypeId","TokenTypes","RPAREN_ID","openCount","i","result","lastToken","minBp","_builder","ErrorFactory","token","len","bpTable","registry","builder","idx","lookahead","bp","infixParselet","typeId","rightBp","parselet","v","decimalText","raw","locale","getLocale","decimalSep","thousandsSep","normalized","bigIntLiteralDigits","count","BindingPower","prefixParselet","rule","openIdx","depth","t","nameToken","closeIdx","params","bodyBuilder","BytecodeBuilder","bodyProgram","bodyIdx","argCount","expectedType","expectedId","offset","isPrefix","bindingPower","event","DiagnosticEventType","buildBindingPowerTable","p","next","afterMinus","PrecedenceParser","ParseletRegistry","tokenType","existing","left","sharedParseletRegistry"],"mappings":"2QAmBA,IAAMA,CAAAA,CAA+B,wBAAA,CAU/BC,CAAAA,CAAgB,YAAA,CAqBTC,CAAAA,CAAN,MAAMA,CAAiB,CAkF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,KAAMC,CAAAA,CAAmD,CAjFrI,IAAA,CAAQ,MAAA,CAA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AA,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,CAAAA,CAAyB,IAAIJ","file":"chunk-FDE5HWDI.cjs","sourcesContent":["import { ParseletRegistry } from \"@solve-js/parser/registry/ParseletRegistry\";\nimport { Token, tokenTypeId, TokenTypes } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DiagnosticPipeline, DiagnosticEventType, type DiagnosticEvent } from \"@solve-js/diagnostics\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower, buildBindingPowerTable } from \"@solve-js/parser/BindingPower\";\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { bigIntLiteralDigits } from \"@solve-js/parser/BigIntLiteral\";\n\n/**\n * Matches a CHAINED thousands-grouped integer using \".\" as the group\n * separator (e.g. \"1.234.567\"), independent of locale. Kept in sync with\n * the identical constant in NumberParselet.ts (not imported from there\n * that file transitively re-imports PrecedenceParser via Parser.ts's\n * `export { PrecedenceParser as Parser }`, so importing the other\n * direction would create a circular dependency for the sake of one\n * regex literal). See NumberParselet.ts's copy for the full explanation.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/**\n * A plain fractional literal: digits, exactly one dot, digits, nothing else.\n *\n * The gate for compiling to PUSH_DECIMAL. It admits \"0.10\", \"1.005\", \".5\" and\n * \"5.\" and refuses anything with an exponent (\"2.5e-3\"), which parses as an\n * ordinary double instead, since scientific notation has no exact base-ten\n * value this representation would keep.\n */\nconst PLAIN_DECIMAL = /^\\d*\\.\\d*$/;\n\n/**\n * ── Hybrid Precedence Climbing Parser ─────────────────────────────────────────\n *\n * Two-tier dispatch strategy:\n *\n * Tier 1 (Fast Path): Inline switch on token.typeId for built-in operators.\n * - Prefix: NUMBER, IDENT, LPAREN, MINUS, PLUS, STRING\n * - Infix: checked via static BP_TABLE (Uint8Array indexed by typeId)\n * - No Map.get(), no parselet function call overhead for ~95% of tokens\n *\n * Tier 2 (Plugin Path): ParseletRegistry fallback for custom/plugin tokens.\n * - Prefix: Map.get(tokenTypeId) for PrefixParselet\n * - Infix: Map.get(tokenTypeId) for InfixParselet\n * - Full flexibility for custom syntax\n *\n * The parser emits directly to a BytecodeBuilder, no AST intermediate.\n * Implements the same public API as the legacy Parser class so existing\n * parselets continue to work without modification.\n */\nexport class PrecedenceParser {\n private tokens: Token[] = [];\n private current = 0;\n private depth = 0;\n private maxDepth: number;\n\n /** Cached registry reference, avoids property chain in hot loop */\n private registry: ParseletRegistry;\n\n /** BytecodeBuilder, set before each parseExpression call */\n private builder!: BytecodeBuilder;\n\n /** Diagnostic pipeline for parselet-matched events */\n private diagnosticPipeline: DiagnosticPipeline | undefined;\n private currentExpression: string = \"\";\n private localeCode: string;\n\n /**\n * The binding power the current infix parselet is being invoked at, i.e. the\n * `minBp` of the expression it sits inside. Set immediately before each Tier-2\n * parselet runs. A parselet that decides whether to swallow a following\n * loose operator (UomLiteralParselet with a trailing `in`/`to`) reads this to\n * respect precedence it cannot otherwise see: `120 km / 2 hours in kph` must\n * group as `(120 km / 2 hours) in kph`, not `120 km / (2 hours in kph)`.\n */\n infixMinBindingPower = 0;\n\n /**\n * Static binding power table, built once at module load, shared across all instances.\n * Index = tokenTypeId, value = binding power (0 = not a built-in infix).\n */\n static readonly BP_TABLE: Uint8Array = buildBindingPowerTable();\n\n // ── Pre-computed token type IDs for inline dispatch ────────────────────────\n // Prefix built-ins\n private static readonly NUMBER_ID = tokenTypeId(TokenTypes.NUMBER);\n private static readonly BIGINT_ID = tokenTypeId(TokenTypes.BIGINT);\n private static readonly STRING_ID = tokenTypeId(TokenTypes.STRING);\n private static readonly IDENT_ID = tokenTypeId(TokenTypes.IDENT);\n private static readonly LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n private static readonly RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n private static readonly MINUS_ID = tokenTypeId(TokenTypes.MINUS);\n private static readonly PLUS_ID = tokenTypeId(TokenTypes.PLUS);\n private static readonly KEYWORD_ID = tokenTypeId(TokenTypes.KEYWORD);\n\n // Infix built-ins (Tier 1, full inline emission)\n private static readonly STAR_ID = tokenTypeId(TokenTypes.STAR);\n private static readonly SLASH_ID = tokenTypeId(TokenTypes.SLASH);\n private static readonly MOD_ID = tokenTypeId(TokenTypes.MOD);\n private static readonly CARET_ID = tokenTypeId(TokenTypes.CARET);\n private static readonly LSHIFT_ID = tokenTypeId(TokenTypes.LSHIFT);\n private static readonly RSHIFT_ID = tokenTypeId(TokenTypes.RSHIFT);\n private static readonly URSHIFT_ID = tokenTypeId(TokenTypes.URSHIFT);\n private static readonly BIT_AND_ID = tokenTypeId(TokenTypes.BIT_AND);\n private static readonly BIT_OR_ID = tokenTypeId(TokenTypes.BIT_OR);\n private static readonly BIT_XOR_ID = tokenTypeId(TokenTypes.BIT_XOR);\n private static readonly PERCENT_ID = tokenTypeId(TokenTypes.PERCENT);\n private static readonly OF_ID = tokenTypeId(TokenTypes.OF);\n\n /**\n * Inline opcode map for Tier 1 infix operators.\n * tokenTypeId → OpCode. PERCENT and CARET are handled specially (not in this map).\n */\n private static readonly INFIX_OPCODE: Record<number, OpCode> = {\n [tokenTypeId(TokenTypes.PLUS)]: OpCode.ADD,\n [tokenTypeId(TokenTypes.MINUS)]: OpCode.SUB,\n [tokenTypeId(TokenTypes.STAR)]: OpCode.MUL,\n [tokenTypeId(TokenTypes.SLASH)]: OpCode.DIV,\n [tokenTypeId(TokenTypes.MOD)]: OpCode.MOD,\n [tokenTypeId(TokenTypes.CARET)]: OpCode.EXP,\n [tokenTypeId(TokenTypes.LSHIFT)]: OpCode.LSHIFT,\n [tokenTypeId(TokenTypes.RSHIFT)]: OpCode.RSHIFT,\n [tokenTypeId(TokenTypes.URSHIFT)]: OpCode.URSHIFT,\n [tokenTypeId(TokenTypes.BIT_AND)]: OpCode.BIT_AND,\n [tokenTypeId(TokenTypes.BIT_OR)]: OpCode.BIT_OR,\n [tokenTypeId(TokenTypes.BIT_XOR)]: OpCode.BIT_XOR,\n [tokenTypeId(TokenTypes.OF)]: OpCode.MUL,\n };\n\n /** Shared with every BytecodeBuilder so a nested-body builder resolves plugin calls by name. */\n private pluginFunctionIndex?: ReadonlyMap<string, number>;\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\", pluginFunctionIndex?: ReadonlyMap<string, number>) {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n this.pluginFunctionIndex = pluginFunctionIndex;\n }\n\n /** Get locale code for NumberParselet to normalize separators */\n getLocaleCode(): string {\n return this.localeCode;\n }\n\n /**\n * Set the diagnostic pipeline for parselet matching events.\n * Cleared after each non-cached parse to avoid holding refs.\n */\n setDiagnosticPipeline(pipeline: DiagnosticPipeline | undefined, expression: string): void {\n this.diagnosticPipeline = pipeline;\n this.currentExpression = expression ?? \"\";\n }\n\n /**\n * Load tokens for parsing. Identical to Parser.load().\n *\n * @param hasParens - if false, skips the O(n) paren balance scan (~90% of expressions)\n */\n load(tokens: Token[], hasParens?: boolean): void {\n if (hasParens === false) {\n this.tokens = tokens;\n this.current = 0;\n this.depth = 0;\n return;\n }\n // Paren scan: count balance to skip array copy for balanced expressions.\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n let openCount = 0;\n for (let i = 0; i < tokens.length; i++) {\n if (tokens[i].typeId === LPAREN_ID) openCount++;\n else if (tokens[i].typeId === RPAREN_ID) openCount--;\n }\n this.tokens = openCount === 0 ? tokens : this.balanceParens(tokens, openCount);\n this.current = 0;\n this.depth = 0;\n }\n\n /**\n * Auto-balance unmatched parentheses.\n */\n private balanceParens(tokens: Token[], openCount: number): Token[] {\n const result = tokens.slice();\n if (openCount > 0) {\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n for (let i = 0; i < openCount; i++) {\n const lastToken = tokens[tokens.length - 1];\n result.push({\n type: TokenTypes.RPAREN,\n typeId: RPAREN_ID,\n value: \")\",\n text: \")\",\n offset: lastToken ? lastToken.offset + lastToken.text.length : 0,\n lineBreaks: 0,\n line: lastToken ? lastToken.line : 1,\n col: lastToken ? lastToken.col + lastToken.text.length : 1,\n } as Token);\n }\n } else if (openCount < 0) {\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n for (let i = 0; i < -openCount; i++) {\n result.unshift({\n type: TokenTypes.LPAREN,\n typeId: LPAREN_ID,\n value: \"(\",\n text: \"(\",\n offset: 0,\n lineBreaks: 0,\n line: 1,\n col: 1,\n } as Token);\n }\n }\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Main entry point: precedence climbing parse expression\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a full expression starting at the current token position.\n *\n * @param minBp - minimum binding power (precedence climbing threshold).\n * For left-associative operators, the recursive call uses `bp + 1`.\n * For right-associative operators (^), it uses `bp - 1`.\n * @param _builder - accepted for parselet API compatibility; always uses `this.builder`.\n */\n parseExpression(minBp: number = 0, _builder?: BytecodeBuilder): void {\n // Accept builder via parameter for backward compatibility with the old Parser API.\n // The ExpressionEngine always calls setBuilder() before parseExpression(),\n // but tests and parselets pass builder as a parameter.\n if (_builder) {\n this.builder = _builder;\n }\n this.depth++;\n if (this.depth > this.maxDepth) {\n this.depth--;\n throw ErrorFactory.parsing(\n \"NESTING_DEPTH_EXCEEDED\",\n `Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,\n { maxDepth: this.maxDepth, currentDepth: this.depth }\n );\n }\n\n const token = this.consume();\n if (!token) {\n this.depth--;\n throw ErrorFactory.parsing(\"UNEXPECTED_END\", \"Unexpected end of expression\");\n }\n\n // ── Prefix ──────────────────────────────────────────────────────────────\n this.parsePrefix(token);\n\n // ── Infix loop (precedence climbing with inline Tier 1 dispatch) ──────────\n const tokens = this.tokens;\n const len = tokens.length;\n const bpTable = PrecedenceParser.BP_TABLE;\n const registry = this.registry;\n const builder = this.builder;\n let idx = this.current;\n\n while (idx < len) {\n const lookahead = tokens[idx];\n if (!lookahead) break;\n\n const bp = bpTable[lookahead.typeId];\n if (bp > 0) {\n // Tier 1: Built-in infix, full inline emission, zero parselet delegation\n if (bp <= minBp) break;\n\n if (this.diagnosticPipeline) {\n // Fast path skips the registry, but built-ins are still registered\n // there (for introspection/tests), look them up only in this\n // diagnostics-only branch so the playground's \"matched parselets\"\n // view isn't permanently blind to every arithmetic operator.\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (infixParselet) {\n this.fireParseletMatched(infixParselet, lookahead, false, bp);\n }\n }\n\n this.current = ++idx;\n const typeId = lookahead.typeId;\n\n if (typeId === PrecedenceParser.PERCENT_ID) {\n // Postfix: no right operand. \"50%\" → Percentage holding 0.5.\n //\n // Must stay byte-for-byte equivalent to PercentParselet, which is\n // the Tier-2 registration of the same operator. This path is the one\n // that actually runs for ordinary expressions, so a change made only\n // in the parselet does nothing at all: that is exactly how the\n // divide-by-100 here outlived its replacement and kept `200 + 10%`\n // answering 200.10.\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(100);\n builder.emitOpcode(OpCode.DIV);\n builder.emitOpcode(OpCode.TO_PERCENTAGE);\n } else if (typeId === PrecedenceParser.CARET_ID && this.tryEmitMatrixCaretOp(builder)) {\n // `^T` (transpose) or `^-1` (inverse), already fully handled\n // including consuming their own trailing tokens.\n } else {\n // Infix: parse right operand, then emit opcode.\n // Right-associative for CARET (^), left-associative for all others.\n //\n // The threshold has to be bp - 1, not bp. The loop above breaks on\n // `bp <= minBp`, so a right operand parsed at `bp` stops at the next\n // `^` exactly as one parsed at `bp + 1` does: the old special case\n // was dead code and \"2 ^ 3 ^ 2\" grouped left, answering 64. One\n // below lets the recursive call keep consuming `^`, which is what\n // makes it 2^(3^2) = 512, as in mathematics, Python, Ruby and\n // JavaScript's `**`.\n //\n // Nothing else sits between Exponent (50) and Product (40), so\n // 49 cannot collide with another operator's level. Unary minus is\n // unaffected: it parses its operand at Prefix (60), above `^`\n // either way, so \"-2 ^ 2\" is still (-2)^2 = 4.\n const rightBp = (typeId === PrecedenceParser.CARET_ID) ? bp - 1 : bp + 1;\n this.parseExpression(rightBp, builder);\n builder.emitOpcode(PrecedenceParser.INFIX_OPCODE[typeId]);\n }\n } else {\n // Tier 2: Plugin parselet fallback, full flexibility for custom syntax\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (!infixParselet) break;\n if (infixParselet.bindingPower <= minBp) break;\n\n this.current = ++idx;\n\n if (this.diagnosticPipeline) {\n this.fireParseletMatched(infixParselet, lookahead, false, infixParselet.bindingPower);\n }\n // Expose the level this parselet is bound at, so one that peeks past its\n // own token (a unit literal weighing whether a trailing `in`/`to` is\n // its own or an outer operator's) can respect precedence. See\n // infixMinBindingPower's doc comment.\n this.infixMinBindingPower = minBp;\n // Parselet handles its own recursion for right operand internally\n infixParselet.parse(this, token, lookahead, builder);\n }\n\n idx = this.current;\n }\n\n this.current = idx;\n this.depth--;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Prefix dispatch: inline switch for built-ins, parselet registry for plugins\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a prefix token. Built-in tokens (NUMBER, IDENT, LPAREN, etc.) are\n * handled inline with zero registry lookup. Everything else falls through\n * to the parselet registry (Tier 2).\n */\n private parsePrefix(token: Token): void {\n const builder = this.builder;\n const typeId = token.typeId;\n\n if (this.diagnosticPipeline) {\n // Fast path below skips the registry for built-ins, but they're still\n // registered there (for introspection/tests), look up here so the\n // playground's \"matched parselets\" view isn't permanently blind to\n // every number, identifier, paren, and unary operator.\n const parselet = this.registry.getPrefix(typeId);\n if (parselet) {\n this.fireParseletMatched(parselet, token, true);\n }\n }\n\n switch (typeId) {\n // ── Numeric literals ──────────────────────────────────────────────────\n case PrecedenceParser.NUMBER_ID: {\n // Parse number with locale-aware separator normalization\n let v: number;\n // The exact dot-decimal text for a literal written with a fractional\n // point, so it can be pushed as PUSH_DECIMAL and keep its precision\n // where it later meets money. Stays null for every integer shape\n // (hex/bin/oct, chained-dot grouping, plain integers), which push the\n // ordinary PUSH_NUMBER and are unchanged.\n let decimalText: string | null = null;\n const raw = token.value;\n if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n v = parseInt(raw, 16);\n // A prefix with no digits after it (\"0x\" alone) makes parseInt\n // return NaN. This used to push straight through as a silent\n // NaN Number value instead of a visible error.\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid hex literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0b\") || raw.startsWith(\"0B\")) {\n v = parseInt(raw.slice(2), 2);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid binary literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0o\") || raw.startsWith(\"0O\")) {\n v = parseInt(raw.slice(2), 8);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid octal literal: \"${raw}\"`, { raw });\n }\n } else if (CHAINED_DOT_THOUSANDS_GROUPS.test(raw)) {\n // The lexer accepts \".\" as a thousands-group separator\n // independent of locale (ExpressionLexer's number-scanning\n // \"Thousands separators\" block), but the locale-based\n // normalization below only strips the ACTIVE locale's own\n // configured thousandsSeparator character, for \"en\" that's\n // \",\", not \".\", so a chained dot-grouped literal like\n // \"1.234.567\" fell through to parseFloat() untouched, which\n // stops at the second \".\" and silently truncated it to 1.234\n // (over 99% of the digits dropped, with no error). This is the\n // REAL number-parsing path for actual evaluation, Tier 1 of\n // the two-tier dispatch above always returns for NUMBER_ID, so\n // NumberParselet.parse() (which has the identical fix) never\n // actually runs except via direct unit tests / the \"matched\n // parselets\" diagnostic display.\n v = parseFloat(raw.split(\".\").join(\"\"));\n } else {\n const locale = getLocale(this.localeCode);\n const decimalSep = locale.display.decimalSeparator;\n const thousandsSep = locale.display.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation)\n if (thousandsSep) {\n normalized = normalized.split(thousandsSep).join(\"\");\n }\n // Replace locale decimal separator with \".\" for JavaScript parsing\n if (decimalSep && decimalSep !== \".\") {\n normalized = normalized.replace(decimalSep, \".\");\n }\n v = parseFloat(normalized);\n // A plain fractional literal (digits, one dot, digits) is what carries\n // an exact decimal. Scientific notation like \"2.5e-3\" has a dot too\n // but no exact base-ten form worth the trouble, so it stays a\n // PUSH_NUMBER double, and so does any integer (grouping stripped).\n if (PLAIN_DECIMAL.test(normalized)) decimalText = normalized;\n }\n if (decimalText !== null) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(decimalText);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(v);\n return;\n }\n\n case PrecedenceParser.BIGINT_ID: {\n // Strips the `n` and any thousands grouping the lexer coalesced in.\n // This used to be `raw.slice(0, -1)` and nothing else, so `1.000n`\n // reached BigInt(\"1.000\") and threw a raw SyntaxError. See\n // parser/BigIntLiteral.ts, which the parselet tier shares.\n builder.emitOpcode(OpCode.PUSH_BIGINT);\n builder.emitString(bigIntLiteralDigits(token.value, this.localeCode));\n return;\n }\n\n case PrecedenceParser.STRING_ID: {\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(token.value);\n return;\n }\n\n // ── Identifiers (variables) ────────────────────────────────────────────\n case PrecedenceParser.IDENT_ID: {\n // An identifier immediately followed by \"(\" may be a user-defined\n // function DEFINITION (`f(x) = ...`) or CALL (`f(5)`). See\n // parseUserFunctionDefOrCall's doc comment for the full\n // disambiguation. Only the (cheap) LPAREN check runs for the\n // overwhelmingly common case of a bare identifier with nothing\n // following it.\n if (this.peek()?.typeId === PrecedenceParser.LPAREN_ID) {\n this.parseUserFunctionDefOrCall(token, builder);\n return;\n }\n // IDENT tokens map to LOAD_VAR by default. The IdentifierParselet\n // and VariableParselet add STORE_VAR for assignments, those are\n // handled via the parselet registry below. Note this is also how a\n // user-defined function's own PARAMETER references compile. See\n // UserFunctionDef's doc comment in BytecodeBuilder.ts for why there\n // is no separate parameter-load opcode: `LOAD_VAR` resolution\n // dynamically checks the VM's innermost call frame first.\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(token.value);\n return;\n }\n\n // ── Grouping / bare-tuple vector literal ─────────────────────────────────\n // `(expr)` groups for precedence; `(x, y[, z[, w]])` is the bare-tuple\n // vector literal documented as an alternative to vec2/vec3/vec4(...)\n // (wiki: Arithmetic/Vector). This Tier-1 case is what actually runs for\n // every LPAREN in production parsing, GroupParselet.ts mirrors this\n // logic for registry-introspection/diagnostic-listing purposes, but a\n // package can never override LPAREN's dispatch here (Tier 1 always\n // wins over the ParseletRegistry fallback below), so both must be kept\n // in sync by hand.\n case PrecedenceParser.LPAREN_ID: {\n this.parseExpression(0, builder);\n let count = 1;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(0, builder);\n count++;\n }\n this.consume(TokenTypes.RPAREN);\n if (count > 1) {\n // Legacy bare-tuple vector sugar, a 1xN row-vector Matrix (see\n // packages/vector/parselets/VectorParselet.ts's comment).\n builder.emitOpcode(OpCode.MAT_NEW);\n builder.emitIndex(1);\n builder.emitIndex(count);\n }\n return;\n }\n\n // ── Unary operators ───────────────────────────────────────────────────\n case PrecedenceParser.MINUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.NEG);\n return;\n }\n\n case PrecedenceParser.PLUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.POS);\n return;\n }\n\n // ── Keyword constants ─────────────────────────────────────────────────\n case PrecedenceParser.KEYWORD_ID: {\n // Keywords are handled by parselets (pi→PI, e→E, etc.)\n // Fall through to registry below.\n }\n }\n\n // ── Tier 2: Plugin/parselet prefix path ──────────────────────────────────\n const prefixParselet = this.registry.getPrefix(typeId);\n if (!prefixParselet) {\n throw ErrorFactory.parsing(\n \"NO_PREFIX_PARSELET\",\n `No prefix parselet found for token: ${token.type} (\"${token.value}\")`,\n { tokenType: token.type, tokenValue: token.value }\n );\n }\n\n prefixParselet.parse(this, token, builder);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // The \"Tier-1 shape-exception\" pattern\n // ═══════════════════════════════════════════════════════════════════════════════\n //\n // Tier 1 exists purely for performance, avoid a Map lookup + parselet call\n // on ~95% of tokens (see this file's own module doc comment above). A\n // recurring consequence: any grammar shape tied to a Tier-1 token type can\n // ONLY be implemented by hand-editing this switch, since a package-\n // registered ParseletRegistry parselet for that same token type would\n // simply never run in production (Tier 1 always wins over the registry\n // fallback). Five confirmed instances of this tension exist in this file\n // (plus one that had to move OUTSIDE it entirely):\n // 1. NUMBER_ID, the full locale-aware number-literal parsing (hex/\n // binary/octal, chained-dot thousands grouping, decimal-separator\n // normalization) is inlined in parsePrefix() above; NumberParselet.ts's\n // own copy is dead code for real evaluation, kept registered only for\n // the \"matched parselets\" diagnostic view.\n // 2. IDENT_ID, parseUserFunctionDefOrCall's lookahead (below) disambig-\n // uates a function DEFINITION from a CALL from a plain variable load.\n // 3. LPAREN_ID, the bare-tuple vector-literal sugar (\"(x,y[,z[,w]])\" ->\n // MAT_NEW) is inlined in parsePrefix() above; GroupParselet.ts mirrors\n // it for introspection only and must be kept in sync by hand.\n // 4. CARET_ID, the transpose/inverse suffix table just below.\n // 5. PLUS_ID, the locale word \"and\" lexes as PLUS (Tier-1, fixed Sum\n // binding power), so a registry parselet can never intercept it the\n // way LogicalParselet.ts intercepts \"or\"/&&/||; unlike the other four,\n // there's no SHAPE to special-case on here (the token itself IS the\n // operator), so the workaround lives entirely outside this file, as a\n // runtime Boolean/Boolean type-check inside vm/VM.ts's OpCode.ADD\n // handler instead.\n //\n // Deliberate non-goal: none of this is exposed as an IEnginePackage\n // extension point (unlike prefixParselets/infixParselets). Letting\n // third-party packages register their own Tier-1 shape-matchers would put\n // per-package matcher iteration on a genuinely hot path (every CARET/\n // NUMBER/IDENT/LPAREN/PLUS token, matched or not), a materially bigger\n // separate product decision than \"make this one table more concise,\" and\n // not one this pattern write-up makes.\n\n /**\n * A single `^`-suffix shape: `matches` peeks ahead (consuming nothing) to\n * check whether this shape starts at the current position; `emit` is only\n * called immediately after `matches` returned true for that SAME position,\n * and is responsible for consuming that shape's own trailing tokens and\n * emitting its bytecode.\n */\n private static readonly CARET_SUFFIX_RULES: ReadonlyArray<{\n name: string;\n matches(parser: PrecedenceParser): boolean;\n emit(parser: PrecedenceParser, builder: BytecodeBuilder): void;\n }> = [\n {\n name: \"transpose (^T)\",\n matches: (p) => {\n const next = p.peek();\n return next?.type === TokenTypes.IDENT && next.value === \"T\";\n },\n emit: (p, builder) => {\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(63); // transpose — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n {\n name: \"inverse (^-1)\",\n matches: (p) => {\n const next = p.peek();\n if (next?.typeId !== PrecedenceParser.MINUS_ID) return false;\n const afterMinus = p.peekAt(1);\n return afterMinus?.type === TokenTypes.NUMBER && afterMinus.value === \"1\";\n },\n emit: (p, builder) => {\n p.advance();\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(65); // inv — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n ];\n\n /**\n * After a `^` token (already consumed by the Tier-1 infix loop above),\n * checks {@link CARET_SUFFIX_RULES} in order for a shape that means\n * something other than ordinary exponentiation: `^T` (transpose) and `^-1`\n * (matrix inverse, LITERALLY the integer exponent `-1`; `^-2`, `^-1.5`\n * etc. still mean ordinary exponentiation). On a match, the rule's `emit`\n * consumes that shape's own tokens and this returns `true`. On no match,\n * consumes NOTHING, returning `false` so the caller falls through to\n * ordinary `EXP` parsing.\n *\n * Every rule dispatches purely on SHAPE, never on operand type (unknowable\n * at parse time): `inv()`'s own handler (`VMBuiltins.ts` index 65) returns\n * `1/x` for a plain Number, byte-identical to what `Math.pow(x, -1)`\n * already computed for `x^-1` before this feature existed, and a real\n * matrix inverse for a Matrix, so `5^-1` still means exactly what it always\n * has; only a Matrix operand actually inverts.\n *\n * Adding a future `^`-suffix shape is a new table entry here, not a new\n * if-block. See the \"Tier-1 shape-exception\" pattern write-up above for\n * why this table can't instead be a package-registered parselet.\n */\n private tryEmitMatrixCaretOp(builder: BytecodeBuilder): boolean {\n for (const rule of PrecedenceParser.CARET_SUFFIX_RULES) {\n if (rule.matches(this)) {\n rule.emit(this, builder);\n return true;\n }\n }\n return false;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // User-defined, parameterized, reusable functions (f(x) = 2*x + 1, then f(5))\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * From an LPAREN token index, scan forward tracking paren depth and\n * return the index of the matching RPAREN, or `null` if the parens never\n * balance before the token stream ends. No emission, no position\n * advance. Same class of technique as {@link balanceParens}'s own\n * pre-scan, just exposed mid-parse instead of only at `load()` time.\n * `openIdx` must point AT the LPAREN itself.\n */\n private findMatchingRParen(openIdx: number): number | null {\n let depth = 0;\n for (let i = openIdx; i < this.tokens.length; i++) {\n const t = this.tokens[i];\n if (t.typeId === PrecedenceParser.LPAREN_ID) depth++;\n else if (t.typeId === PrecedenceParser.RPAREN_ID) {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n }\n\n /**\n * Disambiguates a bare `IDENT` immediately followed by `(` between three\n * things, using ONLY a bracket-depth scan (no backtracking, nothing is\n * consumed until the shape is known):\n * - `f(x) = expr`, a DEFINITION: the matching `)` is followed by `=`.\n * - `f(5)`, a CALL to a (possibly not-yet-defined) function: anything\n * else. This was never valid syntax before this feature (a bare\n * `IDENT` immediately before `(` has no pre-existing \"plain variable\n * read + separately grouped `(...)`\" meaning to preserve, confirmed\n * via `BuiltinNormalizerRules.ts`'s `implicitMultiplyRule()`, which\n * only inserts an implicit `*` for `NUMBER/RPAREN` immediately before\n * `IDENT/LPAREN`, never for a bare `IDENT` immediately before\n * `LPAREN`). Always commits to a CALL; an unregistered name produces a\n * clear `UNDEFINED_FUNCTION` error at VM-execution time, the same\n * forward-reference philosophy `LOAD_VAR`/`UNDEFINED_VARIABLE` already\n * uses, rather than any parse-time registry lookup.\n * If the parens never balance, this falls through to the ordinary\n * `LOAD_VAR` path (a malformed expression surfaces its own parse error\n * shortly after, from the normal expression grammar).\n */\n private parseUserFunctionDefOrCall(nameToken: Token, builder: BytecodeBuilder): void {\n const closeIdx = this.findMatchingRParen(this.current);\n if (closeIdx === null) {\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(nameToken.value);\n return;\n }\n const afterClose = this.tokens[closeIdx + 1];\n if (afterClose?.type === TokenTypes.EQUALS) {\n this.parseUserFunctionDefinition(nameToken, builder);\n } else {\n this.parseUserFunctionCall(nameToken, builder);\n }\n }\n\n /**\n * A parameter name, accepted as either `IDENT` or `UNIT`, matches this\n * codebase's established `:name = value` variable-name policy\n * (`VariableParselet.ts` explicitly accepts `UNIT`-typed tokens too, e.g.\n * `:b = 5` for the \"b\" bits unit) since common short parameter names\n * like `h`/`l`/`b`/`t`/`s`/`m` collide with real unit abbreviations\n * (hour, liter, bits, ton, second, meter, ...) and lex as `UNIT`, not\n * `IDENT`.\n */\n private consumeParamName(): string {\n const token = this.peek();\n if (token?.type === TokenTypes.IDENT || token?.type === TokenTypes.UNIT) {\n this.consume();\n return token.value;\n }\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_INVALID_PARAM_NAME\",\n `Expected a parameter name but got \"${token?.type ?? \"end of input\"}\"${token ? ` (\"${token.value}\")` : \"\"}`,\n { actualType: token?.type },\n );\n }\n\n private parseUserFunctionDefinition(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n const params: string[] = [];\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n params.push(this.consumeParamName());\n while (this.match(TokenTypes.COMMA)) {\n params.push(this.consumeParamName());\n }\n }\n this.consume(TokenTypes.RPAREN);\n this.consume(TokenTypes.EQUALS);\n\n if (params.length === 0) {\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_NO_PARAMS\",\n `\"${nameToken.value}()\" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,\n { name: nameToken.value },\n );\n }\n\n // Compile the body into its OWN independent BytecodeBuilder, reusing\n // the SAME parser/token stream but directing emission elsewhere.\n // `parseExpression(minBp, _builder)` sets `this.builder = _builder`\n // with NO automatic restore, explicitly restoring via `setBuilder()`\n // afterward (not a `finally`, since a thrown parse error here should\n // propagate as-is; there's no further use of `this.builder` on that\n // path before the whole parse aborts) avoids silently emitting\n // whatever parses next (in this same expression, or, via\n // ExpressionEngine's builder pool, a LATER, unrelated line) into a\n // stale, already-.build()'d body builder.\n const bodyBuilder = new BytecodeBuilder(this.pluginFunctionIndex);\n this.parseExpression(BindingPower.Lowest, bodyBuilder);\n this.setBuilder(builder);\n\n const bodyProgram = bodyBuilder.build();\n if (bodyProgram.hasAsync) {\n // v1 scope decision: a function body calling an async plugin\n // (weather, stocks, currency, ...) isn't supported yet, propagating\n // a 'pending' result up through a reentrant executeBytecode() call\n // would need the OUTER expression's own bytecode position/stack\n // state to also be resumable later, which this first pass doesn't\n // implement. Rejecting at DEFINITION time (not call time) gives the\n // clearest possible error, matching this codebase's \"never silently\n // pretend to support something it doesn't\" convention (e.g.\n // addBusinessDays()'s own disclosed holiday-exclusion scope-down).\n throw ErrorFactory.parsing(\n \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n `\"${nameToken.value}(...)\"'s body calls an async operation (weather, stocks, currency, ...) — user-defined function bodies must be synchronous`,\n { name: nameToken.value },\n );\n }\n\n const bodyIdx = builder.emitUserFunctionBody(nameToken.value, params, bodyProgram);\n builder.emitOpcode(OpCode.DEFINE_USER_FUNCTION);\n builder.emitIndex(bodyIdx);\n\n // A definition line has no single input value to echo back the way an\n // assignment does, push a plain confirmation string, matching this\n // codebase's \"never silently produce a misleading numeric 0\" principle.\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(`${nameToken.value}(${params.join(\", \")}) defined`);\n }\n\n private parseUserFunctionCall(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n let argCount = 0;\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n this.consume(TokenTypes.RPAREN);\n\n builder.emitOpcode(OpCode.CALL_USER_FUNCTION);\n builder.emitString(nameToken.value);\n builder.emitByte(argCount);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Token stream navigation (identical API to Parser)\n // ═══════════════════════════════════════════════════════════════════════════════\n\n consume(expectedType?: string): Token {\n const token = this.tokens[this.current];\n if (!token) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_END_OF_INPUT\",\n \"Unexpected end of input\"\n );\n }\n if (expectedType !== undefined) {\n const expectedId = tokenTypeId(expectedType);\n if (token.typeId !== expectedId) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_TOKEN_TYPE\",\n `Expected token type \"${expectedType}\" but got \"${token.type}\" (\"${token.value}\")`,\n { expectedType, actualType: token.type, actualValue: token.value }\n );\n }\n }\n this.current++;\n return token;\n }\n\n match(expectedType: string): boolean {\n const token = this.peek();\n if (token && token.typeId === tokenTypeId(expectedType)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n peek(): Token | undefined {\n return this.tokens[this.current];\n }\n\n /**\n * Read-only lookahead `offset` tokens past the current position, without\n * consuming anything, `peekAt(0)` is equivalent to {@link peek}.\n * `this.tokens` is a plain in-memory array (not a stream), so this is a\n * simple, safe index read; no rewind/checkpoint mechanism is needed since\n * nothing is consumed.\n */\n peekAt(offset: number): Token | undefined {\n return this.tokens[this.current + offset];\n }\n\n previous(): Token | undefined {\n return this.current > 0 ? this.tokens[this.current - 1] : undefined;\n }\n\n private advance(): void {\n this.current++;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Builder access, set before parse, read by inline prefix handlers\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /** Set the builder to use for the current parse. Called by ExpressionEngine. */\n setBuilder(builder: BytecodeBuilder): void {\n this.builder = builder;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Diagnostics\n // ═══════════════════════════════════════════════════════════════════════════════\n\n private fireParseletMatched(\n parselet: { category: string },\n token: Token,\n isPrefix: boolean,\n bindingPower?: number\n ): void {\n const pipeline = this.diagnosticPipeline!;\n const event: DiagnosticEvent & { type: \"parselet_matched\" } = {\n type: DiagnosticEventType.ParseletMatched,\n elapsedNs: 0,\n expression: this.currentExpression,\n tokenType: token.type,\n tokenValue: token.value,\n parseletCategory: parselet.category,\n parseletType: parselet.constructor?.name ?? \"unknown\",\n isPrefix,\n bindingPower,\n tokenOffset: token.offset || 0,\n };\n pipeline.fireParseletMatched(event);\n }\n}\n","import { PrefixParselet, InfixParselet } from \"@solve-js/parser/Parselet\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\n\n/**\n * The one binding-power field a parselet may expose beyond what its interface\n * requires, read only for diagnostic display.\n *\n * `InfixParselet` requires `bindingPower`; `PrefixParselet` declares none, and\n * some prefix parselets carry one anyway. That single field is the whole\n * optional surface deliberately. A `leftBindingPower`/`rightBindingPower` pair\n * used to be read here as well, and reading a name off an object this way finds\n * PRIVATE fields too, since TypeScript's `private` exists only at compile time:\n * `BinaryOpParselet` holds a private `rightBindingPower` meaning \"the minimum\n * power to parse my right operand at\", which is a different quantity from \"the\n * power at which I bind to my right\" and differs from it by one. Reading it\n * silently reported that other number. So neither is read.\n *\n * `category` is not here: both interfaces already declare it.\n */\ninterface ParseletBindingPowers {\n\treadonly bindingPower?: number;\n}\n\n/** Reads the optional binding-power field off a parselet for diagnostics. */\nfunction bindingPowersOf(parselet: PrefixParselet | InfixParselet): ParseletBindingPowers {\n\treturn parselet as ParseletBindingPowers;\n}\n\n/**\n * Dual-keyed ParseletRegistry, accepts both string token types and\n * integer token type IDs for fast dispatch in the Parser hot path.\n *\n * Providers call registerPrefix(\"NUMBER\", ...) with string token types.\n * Internally, we populate both string-keyed and integer-keyed maps so\n * Parser.parseExpression() can use token.typeId (integer) for lookup\n * while diagnostics and error messages use token.type (string).\n *\n * Performance: Integer Map.get() avoids string hashing, saving ~2-5ns\n * per dispatch. With ~10-15 dispatches per expression, that's ~20-75ns.\n */\nexport class ParseletRegistry {\n\t// String-keyed maps (kept for diagnostics + backwards compat)\n\tprivate prefixParselets: Map<string, PrefixParselet> = new Map();\n\tprivate infixParselets: Map<string, InfixParselet> = new Map();\n\n\t// Integer-keyed maps for parser hot path\n\tprivate prefixById: Map<number, PrefixParselet> = new Map();\n\tprivate infixById: Map<number, InfixParselet> = new Map();\n\n\t/**\n\t * Register a prefix parselet for `tokenType`.\n\t *\n\t * If another parselet is already registered for this token type, it is\n\t * silently overwritten by default (`Map.set()` semantics), the old\n\t * parselet is simply unreachable from then on, with no error. This is\n\t * a real footgun for third-party packages: two packages independently\n\t * choosing the same custom token type will collide with zero signal\n\t * about which one \"won\". Mirrors ResolverRegistry.register()'s and\n\t * ExpressionEngine.registerPackage()'s existing \"warn and replace\"\n\t * pattern for the same class of problem at the resolver-namespace and\n\t * package-name levels.\n\t *\n\t * Note: this warns about registry-level collisions only. It does NOT\n\t * detect the separate case where `tokenType` is one of PrecedenceParser's\n\t * Tier-1 fast-path token types (NUMBER, STRING, IDENT, LPAREN, MINUS,\n\t * PLUS, and the Tier-1 infix operators), those are deliberately kept\n\t * registered here for introspection/diagnostics even though Tier-1\n\t * always intercepts them before this registry is consulted (see\n\t * PrecedenceParser.parsePrefix()'s docs), so warning there would\n\t * misfire on that intentional, already-documented pattern.\n\t */\n\tregisterPrefix(tokenType: string, parselet: PrefixParselet): void {\n\t\tconst existing = this.prefixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Prefix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.prefixParselets.set(tokenType, parselet);\n\t\tthis.prefixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/** Register an infix parselet for `tokenType`. See {@link registerPrefix} for the collision-warning behavior this mirrors. */\n\tregisterInfix(tokenType: string, parselet: InfixParselet): void {\n\t\tconst existing = this.infixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Infix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.infixParselets.set(tokenType, parselet);\n\t\tthis.infixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/**\n\t * Iterate all registered prefix parselets for diagnostic display.\n\t *\n\t * `PrefixParselet` declares no binding power, and this used to read a field\n\t * of that name and report 0 for every one of them. 0 is not a neutral\n\t * wrong answer: it is the value that means \"not an operator, stop the\n\t * expression\", so a host drawing a table from this was told none of them\n\t * bind at all. A prefix parselet in this parser has no per-parselet power\n\t * to report, they all bind at the prefix level and each chooses for itself\n\t * at what power to parse its own operand, so that level is what is\n\t * reported. A parselet that does carry its own `bindingPower` still wins.\n\t */\n\tgetAllPrefix(): Array<{ tokenType: string; bindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; bindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.prefixParselets) {\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tbindingPower: bindingPowersOf(parselet).bindingPower ?? BindingPower.Prefix,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterate all registered infix parselets for diagnostic display.\n\t *\n\t * The field an `InfixParselet` actually declares is `bindingPower`. This\n\t * used to read `leftBindingPower` and `rightBindingPower`, which no\n\t * parselet in this codebase declares, so both reads were `undefined`, both\n\t * fell to the `?? 0` default, and the public `getParseletRegistry()`\n\t * reported a binding power of 0 for every one of the ~60 infix operators.\n\t * A host building a precedence table from it was told `*` and `+` bind\n\t * equally, and that neither binds at all.\n\t *\n\t * The left/right split: `bindingPower` is the LEFT power, and the right is\n\t * one higher. That is the standard encoding for a left-associative\n\t * operator, and it is what the parser itself does, see\n\t * `PrecedenceParser.parseExpression()`'s `bp + 1` for the right operand.\n\t * Every operator is reported that way, `^` included. Associativity is not\n\t * something a parselet declares, it is a property of how each one calls\n\t * `parseExpression`, so this API cannot report it without a new field on\n\t * the interface. See {@link ParseletBindingPowers} for why scraping a\n\t * plausible-looking one off the parselet is worse than not reporting it.\n\t */\n\tgetAllInfix(): Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.infixParselets) {\n\t\t\tconst left = bindingPowersOf(parselet).bindingPower ?? 0;\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tleftBindingPower: left,\n\t\t\t\trightBindingPower: left + 1,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Number of registered prefix parselets. */\n\tget prefixCount(): number { return this.prefixParselets.size; }\n\n\t/** Number of registered infix parselets. */\n\tget infixCount(): number { return this.infixParselets.size; }\n\n\t/**\n\t * Get prefix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings\n\t * (diagnostics, error messages, backwards compatibility).\n\t */\n\tgetPrefix(tokenType: string | number): PrefixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.prefixById.get(tokenType);\n\t\treturn this.prefixParselets.get(tokenType);\n\t}\n\n\t/**\n\t * Get infix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings.\n\t */\n\tgetInfix(tokenType: string | number): InfixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.infixById.get(tokenType);\n\t\treturn this.infixParselets.get(tokenType);\n\t}\n\n\thasPrefix(tokenType: string): boolean {\n\t\treturn this.prefixParselets.has(tokenType);\n\t}\n\n\thasInfix(tokenType: string): boolean {\n\t\treturn this.infixParselets.has(tokenType);\n\t}\n\n\tclear(): void {\n\t\tthis.prefixParselets.clear();\n\t\tthis.infixParselets.clear();\n\t\tthis.prefixById.clear();\n\t\tthis.infixById.clear();\n\t}\n}\n\n/**\n * A process-wide parselet registry.\n *\n * @deprecated An engine builds its own registry and does not read this one, so\n * registering here reaches nothing that evaluates. Nothing writes to it now\n * that the global package-registration path is gone; it remains only so the\n * `@solve-js/parser` escape hatch keeps a stable shape.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/PrecedenceParser.ts","../src/parser/registry/ParseletRegistry.ts"],"names":["CHAINED_DOT_THOUSANDS_GROUPS","PLAIN_DECIMAL","_PrecedenceParser","parseletRegistry","maxDepth","localeCode","pluginFunctionIndex","pipeline","expression","tokens","hasParens","LPAREN_ID","tokenTypeId","TokenTypes","RPAREN_ID","openCount","i","result","lastToken","minBp","_builder","ErrorFactory","token","len","bpTable","registry","builder","idx","lookahead","bp","infixParselet","typeId","rightBp","parselet","v","decimalText","raw","locale","getLocale","decimalSep","thousandsSep","normalized","bigIntLiteralDigits","count","BindingPower","prefixParselet","rule","openIdx","depth","t","nameToken","closeIdx","params","bodyBuilder","BytecodeBuilder","bodyProgram","bodyIdx","argCount","expectedType","expectedId","offset","isPrefix","bindingPower","event","DiagnosticEventType","buildBindingPowerTable","p","next","afterMinus","PrecedenceParser","ParseletRegistry","tokenType","existing","left","sharedParseletRegistry"],"mappings":"2QAmBA,IAAMA,CAAAA,CAA+B,wBAAA,CAU/BC,CAAAA,CAAgB,YAAA,CAqBTC,CAAAA,CAAN,MAAMA,CAAiB,CAkF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,KAAMC,CAAAA,CAAmD,CAjFrI,IAAA,CAAQ,MAAA,CAAkB,EAAC,CAC3B,IAAA,CAAQ,OAAA,CAAU,CAAA,CAClB,IAAA,CAAQ,KAAA,CAAQ,CAAA,CAWhB,IAAA,CAAQ,iBAAA,CAA4B,GAWpC,IAAA,CAAA,oBAAA,CAAuB,CAAA,CA0DrB,IAAA,CAAK,QAAA,CAAWH,CAAAA,CAChB,IAAA,CAAK,QAAA,CAAWC,CAAAA,CAChB,IAAA,CAAK,UAAA,CAAaC,CAAAA,CAClB,IAAA,CAAK,mBAAA,CAAsBC,EAC7B,CAGA,aAAA,EAAwB,CACtB,OAAO,IAAA,CAAK,UACd,CAMA,qBAAA,CAAsBC,CAAAA,CAA0CC,CAAAA,CAA0B,CACx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cesContent":["import { ParseletRegistry } from \"@solve-js/parser/registry/ParseletRegistry\";\nimport { Token, tokenTypeId, TokenTypes } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DiagnosticPipeline, DiagnosticEventType, type DiagnosticEvent } from \"@solve-js/diagnostics\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower, buildBindingPowerTable } from \"@solve-js/parser/BindingPower\";\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { bigIntLiteralDigits } from \"@solve-js/parser/BigIntLiteral\";\n\n/**\n * Matches a CHAINED thousands-grouped integer using \".\" as the group\n * separator (e.g. \"1.234.567\"), independent of locale. Kept in sync with\n * the identical constant in NumberParselet.ts (not imported from there\n * that file transitively re-imports PrecedenceParser via Parser.ts's\n * `export { PrecedenceParser as Parser }`, so importing the other\n * direction would create a circular dependency for the sake of one\n * regex literal). See NumberParselet.ts's copy for the full explanation.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/**\n * A plain fractional literal: digits, exactly one dot, digits, nothing else.\n *\n * The gate for compiling to PUSH_DECIMAL. It admits \"0.10\", \"1.005\", \".5\" and\n * \"5.\" and refuses anything with an exponent (\"2.5e-3\"), which parses as an\n * ordinary double instead, since scientific notation has no exact base-ten\n * value this representation would keep.\n */\nconst PLAIN_DECIMAL = /^\\d*\\.\\d*$/;\n\n/**\n * ── Hybrid Precedence Climbing Parser ─────────────────────────────────────────\n *\n * Two-tier dispatch strategy:\n *\n * Tier 1 (Fast Path): Inline switch on token.typeId for built-in operators.\n * - Prefix: NUMBER, IDENT, LPAREN, MINUS, PLUS, STRING\n * - Infix: checked via static BP_TABLE (Uint8Array indexed by typeId)\n * - No Map.get(), no parselet function call overhead for ~95% of tokens\n *\n * Tier 2 (Plugin Path): ParseletRegistry fallback for custom/plugin tokens.\n * - Prefix: Map.get(tokenTypeId) for PrefixParselet\n * - Infix: Map.get(tokenTypeId) for InfixParselet\n * - Full flexibility for custom syntax\n *\n * The parser emits directly to a BytecodeBuilder, no AST intermediate.\n * Implements the same public API as the legacy Parser class so existing\n * parselets continue to work without modification.\n */\nexport class PrecedenceParser {\n private tokens: Token[] = [];\n private current = 0;\n private depth = 0;\n private maxDepth: number;\n\n /** Cached registry reference, avoids property chain in hot loop */\n private registry: ParseletRegistry;\n\n /** BytecodeBuilder, set before each parseExpression call */\n private builder!: BytecodeBuilder;\n\n /** Diagnostic pipeline for parselet-matched events */\n private diagnosticPipeline: DiagnosticPipeline | undefined;\n private currentExpression: string = \"\";\n private localeCode: string;\n\n /**\n * The binding power the current infix parselet is being invoked at, i.e. the\n * `minBp` of the expression it sits inside. Set immediately before each Tier-2\n * parselet runs. A parselet that decides whether to swallow a following\n * loose operator (UomLiteralParselet with a trailing `in`/`to`) reads this to\n * respect precedence it cannot otherwise see: `120 km / 2 hours in kph` must\n * group as `(120 km / 2 hours) in kph`, not `120 km / (2 hours in kph)`.\n */\n infixMinBindingPower = 0;\n\n /**\n * Static binding power table, built once at module load, shared across all instances.\n * Index = tokenTypeId, value = binding power (0 = not a built-in infix).\n */\n static readonly BP_TABLE: Uint8Array = buildBindingPowerTable();\n\n // ── Pre-computed token type IDs for inline dispatch ────────────────────────\n // Prefix built-ins\n private static readonly NUMBER_ID = tokenTypeId(TokenTypes.NUMBER);\n private static readonly BIGINT_ID = tokenTypeId(TokenTypes.BIGINT);\n private static readonly STRING_ID = tokenTypeId(TokenTypes.STRING);\n private static readonly IDENT_ID = tokenTypeId(TokenTypes.IDENT);\n private static readonly LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n private static readonly RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n private static readonly MINUS_ID = tokenTypeId(TokenTypes.MINUS);\n private static readonly PLUS_ID = tokenTypeId(TokenTypes.PLUS);\n private static readonly KEYWORD_ID = tokenTypeId(TokenTypes.KEYWORD);\n\n // Infix built-ins (Tier 1, full inline emission)\n private static readonly STAR_ID = tokenTypeId(TokenTypes.STAR);\n private static readonly SLASH_ID = tokenTypeId(TokenTypes.SLASH);\n private static readonly MOD_ID = tokenTypeId(TokenTypes.MOD);\n private static readonly CARET_ID = tokenTypeId(TokenTypes.CARET);\n private static readonly LSHIFT_ID = tokenTypeId(TokenTypes.LSHIFT);\n private static readonly RSHIFT_ID = tokenTypeId(TokenTypes.RSHIFT);\n private static readonly URSHIFT_ID = tokenTypeId(TokenTypes.URSHIFT);\n private static readonly BIT_AND_ID = tokenTypeId(TokenTypes.BIT_AND);\n private static readonly BIT_OR_ID = tokenTypeId(TokenTypes.BIT_OR);\n private static readonly BIT_XOR_ID = tokenTypeId(TokenTypes.BIT_XOR);\n private static readonly PERCENT_ID = tokenTypeId(TokenTypes.PERCENT);\n private static readonly OF_ID = tokenTypeId(TokenTypes.OF);\n\n /**\n * Inline opcode map for Tier 1 infix operators.\n * tokenTypeId → OpCode. PERCENT and CARET are handled specially (not in this map).\n */\n private static readonly INFIX_OPCODE: Record<number, OpCode> = {\n [tokenTypeId(TokenTypes.PLUS)]: OpCode.ADD,\n [tokenTypeId(TokenTypes.MINUS)]: OpCode.SUB,\n [tokenTypeId(TokenTypes.STAR)]: OpCode.MUL,\n [tokenTypeId(TokenTypes.SLASH)]: OpCode.DIV,\n [tokenTypeId(TokenTypes.MOD)]: OpCode.MOD,\n [tokenTypeId(TokenTypes.CARET)]: OpCode.EXP,\n [tokenTypeId(TokenTypes.LSHIFT)]: OpCode.LSHIFT,\n [tokenTypeId(TokenTypes.RSHIFT)]: OpCode.RSHIFT,\n [tokenTypeId(TokenTypes.URSHIFT)]: OpCode.URSHIFT,\n [tokenTypeId(TokenTypes.BIT_AND)]: OpCode.BIT_AND,\n [tokenTypeId(TokenTypes.BIT_OR)]: OpCode.BIT_OR,\n [tokenTypeId(TokenTypes.BIT_XOR)]: OpCode.BIT_XOR,\n [tokenTypeId(TokenTypes.OF)]: OpCode.MUL,\n };\n\n /** Shared with every BytecodeBuilder so a nested-body builder resolves plugin calls by name. */\n private pluginFunctionIndex?: ReadonlyMap<string, number>;\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\", pluginFunctionIndex?: ReadonlyMap<string, number>) {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n this.pluginFunctionIndex = pluginFunctionIndex;\n }\n\n /** Get locale code for NumberParselet to normalize separators */\n getLocaleCode(): string {\n return this.localeCode;\n }\n\n /**\n * Set the diagnostic pipeline for parselet matching events.\n * Cleared after each non-cached parse to avoid holding refs.\n */\n setDiagnosticPipeline(pipeline: DiagnosticPipeline | undefined, expression: string): void {\n this.diagnosticPipeline = pipeline;\n this.currentExpression = expression ?? \"\";\n }\n\n /**\n * Load tokens for parsing. Identical to Parser.load().\n *\n * @param hasParens - if false, skips the O(n) paren balance scan (~90% of expressions)\n */\n load(tokens: Token[], hasParens?: boolean): void {\n if (hasParens === false) {\n this.tokens = tokens;\n this.current = 0;\n this.depth = 0;\n return;\n }\n // Paren scan: count balance to skip array copy for balanced expressions.\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n let openCount = 0;\n for (let i = 0; i < tokens.length; i++) {\n if (tokens[i].typeId === LPAREN_ID) openCount++;\n else if (tokens[i].typeId === RPAREN_ID) openCount--;\n }\n this.tokens = openCount === 0 ? tokens : this.balanceParens(tokens, openCount);\n this.current = 0;\n this.depth = 0;\n }\n\n /**\n * Auto-balance unmatched parentheses.\n */\n private balanceParens(tokens: Token[], openCount: number): Token[] {\n const result = tokens.slice();\n if (openCount > 0) {\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n for (let i = 0; i < openCount; i++) {\n const lastToken = tokens[tokens.length - 1];\n result.push({\n type: TokenTypes.RPAREN,\n typeId: RPAREN_ID,\n value: \")\",\n text: \")\",\n offset: lastToken ? lastToken.offset + lastToken.text.length : 0,\n lineBreaks: 0,\n line: lastToken ? lastToken.line : 1,\n col: lastToken ? lastToken.col + lastToken.text.length : 1,\n } as Token);\n }\n } else if (openCount < 0) {\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n for (let i = 0; i < -openCount; i++) {\n result.unshift({\n type: TokenTypes.LPAREN,\n typeId: LPAREN_ID,\n value: \"(\",\n text: \"(\",\n offset: 0,\n lineBreaks: 0,\n line: 1,\n col: 1,\n } as Token);\n }\n }\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Main entry point: precedence climbing parse expression\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a full expression starting at the current token position.\n *\n * @param minBp - minimum binding power (precedence climbing threshold).\n * For left-associative operators, the recursive call uses `bp + 1`.\n * For right-associative operators (^), it uses `bp - 1`.\n * @param _builder - accepted for parselet API compatibility; always uses `this.builder`.\n */\n parseExpression(minBp: number = 0, _builder?: BytecodeBuilder): void {\n // Accept builder via parameter for backward compatibility with the old Parser API.\n // The ExpressionEngine always calls setBuilder() before parseExpression(),\n // but tests and parselets pass builder as a parameter.\n if (_builder) {\n this.builder = _builder;\n }\n this.depth++;\n if (this.depth > this.maxDepth) {\n this.depth--;\n throw ErrorFactory.parsing(\n \"NESTING_DEPTH_EXCEEDED\",\n `Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,\n { maxDepth: this.maxDepth, currentDepth: this.depth }\n );\n }\n\n const token = this.consume();\n if (!token) {\n this.depth--;\n throw ErrorFactory.parsing(\"UNEXPECTED_END\", \"Unexpected end of expression\");\n }\n\n // ── Prefix ──────────────────────────────────────────────────────────────\n this.parsePrefix(token);\n\n // ── Infix loop (precedence climbing with inline Tier 1 dispatch) ──────────\n const tokens = this.tokens;\n const len = tokens.length;\n const bpTable = PrecedenceParser.BP_TABLE;\n const registry = this.registry;\n const builder = this.builder;\n let idx = this.current;\n\n while (idx < len) {\n const lookahead = tokens[idx];\n if (!lookahead) break;\n\n const bp = bpTable[lookahead.typeId];\n if (bp > 0) {\n // Tier 1: Built-in infix, full inline emission, zero parselet delegation\n if (bp <= minBp) break;\n\n if (this.diagnosticPipeline) {\n // Fast path skips the registry, but built-ins are still registered\n // there (for introspection/tests), look them up only in this\n // diagnostics-only branch so the playground's \"matched parselets\"\n // view isn't permanently blind to every arithmetic operator.\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (infixParselet) {\n this.fireParseletMatched(infixParselet, lookahead, false, bp);\n }\n }\n\n this.current = ++idx;\n const typeId = lookahead.typeId;\n\n if (typeId === PrecedenceParser.PERCENT_ID) {\n // Postfix: no right operand. \"50%\" → Percentage holding 0.5.\n //\n // Must stay byte-for-byte equivalent to PercentParselet, which is\n // the Tier-2 registration of the same operator. This path is the one\n // that actually runs for ordinary expressions, so a change made only\n // in the parselet does nothing at all: that is exactly how the\n // divide-by-100 here outlived its replacement and kept `200 + 10%`\n // answering 200.10.\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(100);\n builder.emitOpcode(OpCode.DIV);\n builder.emitOpcode(OpCode.TO_PERCENTAGE);\n } else if (typeId === PrecedenceParser.CARET_ID && this.tryEmitMatrixCaretOp(builder)) {\n // `^T` (transpose) or `^-1` (inverse), already fully handled\n // including consuming their own trailing tokens.\n } else {\n // Infix: parse right operand, then emit opcode.\n // Right-associative for CARET (^), left-associative for all others.\n //\n // The threshold has to be bp - 1, not bp. The loop above breaks on\n // `bp <= minBp`, so a right operand parsed at `bp` stops at the next\n // `^` exactly as one parsed at `bp + 1` does: the old special case\n // was dead code and \"2 ^ 3 ^ 2\" grouped left, answering 64. One\n // below lets the recursive call keep consuming `^`, which is what\n // makes it 2^(3^2) = 512, as in mathematics, Python, Ruby and\n // JavaScript's `**`.\n //\n // Nothing else sits between Exponent (50) and Product (40), so\n // 49 cannot collide with another operator's level. Unary minus is\n // unaffected: it parses its operand at Prefix (60), above `^`\n // either way, so \"-2 ^ 2\" is still (-2)^2 = 4.\n const rightBp = (typeId === PrecedenceParser.CARET_ID) ? bp - 1 : bp + 1;\n this.parseExpression(rightBp, builder);\n builder.emitOpcode(PrecedenceParser.INFIX_OPCODE[typeId]);\n }\n } else {\n // Tier 2: Plugin parselet fallback, full flexibility for custom syntax\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (!infixParselet) break;\n if (infixParselet.bindingPower <= minBp) break;\n\n this.current = ++idx;\n\n if (this.diagnosticPipeline) {\n this.fireParseletMatched(infixParselet, lookahead, false, infixParselet.bindingPower);\n }\n // Expose the level this parselet is bound at, so one that peeks past its\n // own token (a unit literal weighing whether a trailing `in`/`to` is\n // its own or an outer operator's) can respect precedence. See\n // infixMinBindingPower's doc comment.\n this.infixMinBindingPower = minBp;\n // Parselet handles its own recursion for right operand internally\n infixParselet.parse(this, token, lookahead, builder);\n }\n\n idx = this.current;\n }\n\n this.current = idx;\n this.depth--;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Prefix dispatch: inline switch for built-ins, parselet registry for plugins\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a prefix token. Built-in tokens (NUMBER, IDENT, LPAREN, etc.) are\n * handled inline with zero registry lookup. Everything else falls through\n * to the parselet registry (Tier 2).\n */\n private parsePrefix(token: Token): void {\n const builder = this.builder;\n const typeId = token.typeId;\n\n if (this.diagnosticPipeline) {\n // Fast path below skips the registry for built-ins, but they're still\n // registered there (for introspection/tests), look up here so the\n // playground's \"matched parselets\" view isn't permanently blind to\n // every number, identifier, paren, and unary operator.\n const parselet = this.registry.getPrefix(typeId);\n if (parselet) {\n this.fireParseletMatched(parselet, token, true);\n }\n }\n\n switch (typeId) {\n // ── Numeric literals ──────────────────────────────────────────────────\n case PrecedenceParser.NUMBER_ID: {\n // Parse number with locale-aware separator normalization\n let v: number;\n // The exact dot-decimal text for a literal written with a fractional\n // point, so it can be pushed as PUSH_DECIMAL and keep its precision\n // where it later meets money. Stays null for every integer shape\n // (hex/bin/oct, chained-dot grouping, plain integers), which push the\n // ordinary PUSH_NUMBER and are unchanged.\n let decimalText: string | null = null;\n const raw = token.value;\n if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n v = parseInt(raw, 16);\n // A prefix with no digits after it (\"0x\" alone) makes parseInt\n // return NaN. This used to push straight through as a silent\n // NaN Number value instead of a visible error.\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid hex literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0b\") || raw.startsWith(\"0B\")) {\n v = parseInt(raw.slice(2), 2);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid binary literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0o\") || raw.startsWith(\"0O\")) {\n v = parseInt(raw.slice(2), 8);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid octal literal: \"${raw}\"`, { raw });\n }\n } else if (CHAINED_DOT_THOUSANDS_GROUPS.test(raw)) {\n // The lexer accepts \".\" as a thousands-group separator\n // independent of locale (ExpressionLexer's number-scanning\n // \"Thousands separators\" block), but the locale-based\n // normalization below only strips the ACTIVE locale's own\n // configured thousandsSeparator character, for \"en\" that's\n // \",\", not \".\", so a chained dot-grouped literal like\n // \"1.234.567\" fell through to parseFloat() untouched, which\n // stops at the second \".\" and silently truncated it to 1.234\n // (over 99% of the digits dropped, with no error). This is the\n // REAL number-parsing path for actual evaluation, Tier 1 of\n // the two-tier dispatch above always returns for NUMBER_ID, so\n // NumberParselet.parse() (which has the identical fix) never\n // actually runs except via direct unit tests / the \"matched\n // parselets\" diagnostic display.\n v = parseFloat(raw.split(\".\").join(\"\"));\n } else {\n const locale = getLocale(this.localeCode);\n const decimalSep = locale.display.decimalSeparator;\n const thousandsSep = locale.display.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation)\n if (thousandsSep) {\n normalized = normalized.split(thousandsSep).join(\"\");\n }\n // Replace locale decimal separator with \".\" for JavaScript parsing\n if (decimalSep && decimalSep !== \".\") {\n normalized = normalized.replace(decimalSep, \".\");\n }\n v = parseFloat(normalized);\n // A plain fractional literal (digits, one dot, digits) is what carries\n // an exact decimal. Scientific notation like \"2.5e-3\" has a dot too\n // but no exact base-ten form worth the trouble, so it stays a\n // PUSH_NUMBER double, and so does any integer (grouping stripped).\n if (PLAIN_DECIMAL.test(normalized)) decimalText = normalized;\n }\n if (decimalText !== null) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(decimalText);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(v);\n return;\n }\n\n case PrecedenceParser.BIGINT_ID: {\n // Strips the `n` and any thousands grouping the lexer coalesced in.\n // This used to be `raw.slice(0, -1)` and nothing else, so `1.000n`\n // reached BigInt(\"1.000\") and threw a raw SyntaxError. See\n // parser/BigIntLiteral.ts, which the parselet tier shares.\n builder.emitOpcode(OpCode.PUSH_BIGINT);\n builder.emitString(bigIntLiteralDigits(token.value, this.localeCode));\n return;\n }\n\n case PrecedenceParser.STRING_ID: {\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(token.value);\n return;\n }\n\n // ── Identifiers (variables) ────────────────────────────────────────────\n case PrecedenceParser.IDENT_ID: {\n // An identifier immediately followed by \"(\" may be a user-defined\n // function DEFINITION (`f(x) = ...`) or CALL (`f(5)`). See\n // parseUserFunctionDefOrCall's doc comment for the full\n // disambiguation. Only the (cheap) LPAREN check runs for the\n // overwhelmingly common case of a bare identifier with nothing\n // following it.\n if (this.peek()?.typeId === PrecedenceParser.LPAREN_ID) {\n this.parseUserFunctionDefOrCall(token, builder);\n return;\n }\n // IDENT tokens map to LOAD_VAR by default. The IdentifierParselet\n // and VariableParselet add STORE_VAR for assignments, those are\n // handled via the parselet registry below. Note this is also how a\n // user-defined function's own PARAMETER references compile. See\n // UserFunctionDef's doc comment in BytecodeBuilder.ts for why there\n // is no separate parameter-load opcode: `LOAD_VAR` resolution\n // dynamically checks the VM's innermost call frame first.\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(token.value);\n return;\n }\n\n // ── Grouping / bare-tuple vector literal ─────────────────────────────────\n // `(expr)` groups for precedence; `(x, y[, z[, w]])` is the bare-tuple\n // vector literal documented as an alternative to vec2/vec3/vec4(...)\n // (wiki: Arithmetic/Vector). This Tier-1 case is what actually runs for\n // every LPAREN in production parsing, GroupParselet.ts mirrors this\n // logic for registry-introspection/diagnostic-listing purposes, but a\n // package can never override LPAREN's dispatch here (Tier 1 always\n // wins over the ParseletRegistry fallback below), so both must be kept\n // in sync by hand.\n case PrecedenceParser.LPAREN_ID: {\n this.parseExpression(0, builder);\n let count = 1;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(0, builder);\n count++;\n }\n this.consume(TokenTypes.RPAREN);\n if (count > 1) {\n // Legacy bare-tuple vector sugar, a 1xN row-vector Matrix (see\n // packages/vector/parselets/VectorParselet.ts's comment).\n builder.emitOpcode(OpCode.MAT_NEW);\n builder.emitIndex(1);\n builder.emitIndex(count);\n }\n return;\n }\n\n // ── Unary operators ───────────────────────────────────────────────────\n case PrecedenceParser.MINUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.NEG);\n return;\n }\n\n case PrecedenceParser.PLUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.POS);\n return;\n }\n\n // ── Keyword constants ─────────────────────────────────────────────────\n case PrecedenceParser.KEYWORD_ID: {\n // Keywords are handled by parselets (pi→PI, e→E, etc.)\n // Fall through to registry below.\n }\n }\n\n // ── Tier 2: Plugin/parselet prefix path ──────────────────────────────────\n const prefixParselet = this.registry.getPrefix(typeId);\n if (!prefixParselet) {\n throw ErrorFactory.parsing(\n \"NO_PREFIX_PARSELET\",\n `No prefix parselet found for token: ${token.type} (\"${token.value}\")`,\n { tokenType: token.type, tokenValue: token.value }\n );\n }\n\n prefixParselet.parse(this, token, builder);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // The \"Tier-1 shape-exception\" pattern\n // ═══════════════════════════════════════════════════════════════════════════════\n //\n // Tier 1 exists purely for performance, avoid a Map lookup + parselet call\n // on ~95% of tokens (see this file's own module doc comment above). A\n // recurring consequence: any grammar shape tied to a Tier-1 token type can\n // ONLY be implemented by hand-editing this switch, since a package-\n // registered ParseletRegistry parselet for that same token type would\n // simply never run in production (Tier 1 always wins over the registry\n // fallback). Five confirmed instances of this tension exist in this file\n // (plus one that had to move OUTSIDE it entirely):\n // 1. NUMBER_ID, the full locale-aware number-literal parsing (hex/\n // binary/octal, chained-dot thousands grouping, decimal-separator\n // normalization) is inlined in parsePrefix() above; NumberParselet.ts's\n // own copy is dead code for real evaluation, kept registered only for\n // the \"matched parselets\" diagnostic view.\n // 2. IDENT_ID, parseUserFunctionDefOrCall's lookahead (below) disambig-\n // uates a function DEFINITION from a CALL from a plain variable load.\n // 3. LPAREN_ID, the bare-tuple vector-literal sugar (\"(x,y[,z[,w]])\" ->\n // MAT_NEW) is inlined in parsePrefix() above; GroupParselet.ts mirrors\n // it for introspection only and must be kept in sync by hand.\n // 4. CARET_ID, the transpose/inverse suffix table just below.\n // 5. PLUS_ID, the locale word \"and\" lexes as PLUS (Tier-1, fixed Sum\n // binding power), so a registry parselet can never intercept it the\n // way LogicalParselet.ts intercepts \"or\"/&&/||; unlike the other four,\n // there's no SHAPE to special-case on here (the token itself IS the\n // operator), so the workaround lives entirely outside this file, as a\n // runtime Boolean/Boolean type-check inside vm/VM.ts's OpCode.ADD\n // handler instead.\n //\n // Deliberate non-goal: none of this is exposed as an IEnginePackage\n // extension point (unlike prefixParselets/infixParselets). Letting\n // third-party packages register their own Tier-1 shape-matchers would put\n // per-package matcher iteration on a genuinely hot path (every CARET/\n // NUMBER/IDENT/LPAREN/PLUS token, matched or not), a materially bigger\n // separate product decision than \"make this one table more concise,\" and\n // not one this pattern write-up makes.\n\n /**\n * A single `^`-suffix shape: `matches` peeks ahead (consuming nothing) to\n * check whether this shape starts at the current position; `emit` is only\n * called immediately after `matches` returned true for that SAME position,\n * and is responsible for consuming that shape's own trailing tokens and\n * emitting its bytecode.\n */\n private static readonly CARET_SUFFIX_RULES: ReadonlyArray<{\n name: string;\n matches(parser: PrecedenceParser): boolean;\n emit(parser: PrecedenceParser, builder: BytecodeBuilder): void;\n }> = [\n {\n name: \"transpose (^T)\",\n matches: (p) => {\n const next = p.peek();\n return next?.type === TokenTypes.IDENT && next.value === \"T\";\n },\n emit: (p, builder) => {\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(63); // transpose — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n {\n name: \"inverse (^-1)\",\n matches: (p) => {\n const next = p.peek();\n if (next?.typeId !== PrecedenceParser.MINUS_ID) return false;\n const afterMinus = p.peekAt(1);\n return afterMinus?.type === TokenTypes.NUMBER && afterMinus.value === \"1\";\n },\n emit: (p, builder) => {\n p.advance();\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(65); // inv — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n ];\n\n /**\n * After a `^` token (already consumed by the Tier-1 infix loop above),\n * checks {@link CARET_SUFFIX_RULES} in order for a shape that means\n * something other than ordinary exponentiation: `^T` (transpose) and `^-1`\n * (matrix inverse, LITERALLY the integer exponent `-1`; `^-2`, `^-1.5`\n * etc. still mean ordinary exponentiation). On a match, the rule's `emit`\n * consumes that shape's own tokens and this returns `true`. On no match,\n * consumes NOTHING, returning `false` so the caller falls through to\n * ordinary `EXP` parsing.\n *\n * Every rule dispatches purely on SHAPE, never on operand type (unknowable\n * at parse time): `inv()`'s own handler (`VMBuiltins.ts` index 65) returns\n * `1/x` for a plain Number, byte-identical to what `Math.pow(x, -1)`\n * already computed for `x^-1` before this feature existed, and a real\n * matrix inverse for a Matrix, so `5^-1` still means exactly what it always\n * has; only a Matrix operand actually inverts.\n *\n * Adding a future `^`-suffix shape is a new table entry here, not a new\n * if-block. See the \"Tier-1 shape-exception\" pattern write-up above for\n * why this table can't instead be a package-registered parselet.\n */\n private tryEmitMatrixCaretOp(builder: BytecodeBuilder): boolean {\n for (const rule of PrecedenceParser.CARET_SUFFIX_RULES) {\n if (rule.matches(this)) {\n rule.emit(this, builder);\n return true;\n }\n }\n return false;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // User-defined, parameterized, reusable functions (f(x) = 2*x + 1, then f(5))\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * From an LPAREN token index, scan forward tracking paren depth and\n * return the index of the matching RPAREN, or `null` if the parens never\n * balance before the token stream ends. No emission, no position\n * advance. Same class of technique as {@link balanceParens}'s own\n * pre-scan, just exposed mid-parse instead of only at `load()` time.\n * `openIdx` must point AT the LPAREN itself.\n */\n private findMatchingRParen(openIdx: number): number | null {\n let depth = 0;\n for (let i = openIdx; i < this.tokens.length; i++) {\n const t = this.tokens[i];\n if (t.typeId === PrecedenceParser.LPAREN_ID) depth++;\n else if (t.typeId === PrecedenceParser.RPAREN_ID) {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n }\n\n /**\n * Disambiguates a bare `IDENT` immediately followed by `(` between three\n * things, using ONLY a bracket-depth scan (no backtracking, nothing is\n * consumed until the shape is known):\n * - `f(x) = expr`, a DEFINITION: the matching `)` is followed by `=`.\n * - `f(5)`, a CALL to a (possibly not-yet-defined) function: anything\n * else. This was never valid syntax before this feature (a bare\n * `IDENT` immediately before `(` has no pre-existing \"plain variable\n * read + separately grouped `(...)`\" meaning to preserve, confirmed\n * via `BuiltinNormalizerRules.ts`'s `implicitMultiplyRule()`, which\n * only inserts an implicit `*` for `NUMBER/RPAREN` immediately before\n * `IDENT/LPAREN`, never for a bare `IDENT` immediately before\n * `LPAREN`). Always commits to a CALL; an unregistered name produces a\n * clear `UNDEFINED_FUNCTION` error at VM-execution time, the same\n * forward-reference philosophy `LOAD_VAR`/`UNDEFINED_VARIABLE` already\n * uses, rather than any parse-time registry lookup.\n * If the parens never balance, this falls through to the ordinary\n * `LOAD_VAR` path (a malformed expression surfaces its own parse error\n * shortly after, from the normal expression grammar).\n */\n private parseUserFunctionDefOrCall(nameToken: Token, builder: BytecodeBuilder): void {\n const closeIdx = this.findMatchingRParen(this.current);\n if (closeIdx === null) {\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(nameToken.value);\n return;\n }\n const afterClose = this.tokens[closeIdx + 1];\n if (afterClose?.type === TokenTypes.EQUALS) {\n this.parseUserFunctionDefinition(nameToken, builder);\n } else {\n this.parseUserFunctionCall(nameToken, builder);\n }\n }\n\n /**\n * A parameter name, accepted as either `IDENT` or `UNIT`, matches this\n * codebase's established `:name = value` variable-name policy\n * (`VariableParselet.ts` explicitly accepts `UNIT`-typed tokens too, e.g.\n * `:b = 5` for the \"b\" bits unit) since common short parameter names\n * like `h`/`l`/`b`/`t`/`s`/`m` collide with real unit abbreviations\n * (hour, liter, bits, ton, second, meter, ...) and lex as `UNIT`, not\n * `IDENT`.\n */\n private consumeParamName(): string {\n const token = this.peek();\n if (token?.type === TokenTypes.IDENT || token?.type === TokenTypes.UNIT) {\n this.consume();\n return token.value;\n }\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_INVALID_PARAM_NAME\",\n `Expected a parameter name but got \"${token?.type ?? \"end of input\"}\"${token ? ` (\"${token.value}\")` : \"\"}`,\n { actualType: token?.type },\n );\n }\n\n private parseUserFunctionDefinition(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n const params: string[] = [];\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n params.push(this.consumeParamName());\n while (this.match(TokenTypes.COMMA)) {\n params.push(this.consumeParamName());\n }\n }\n this.consume(TokenTypes.RPAREN);\n this.consume(TokenTypes.EQUALS);\n\n if (params.length === 0) {\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_NO_PARAMS\",\n `\"${nameToken.value}()\" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,\n { name: nameToken.value },\n );\n }\n\n // Compile the body into its OWN independent BytecodeBuilder, reusing\n // the SAME parser/token stream but directing emission elsewhere.\n // `parseExpression(minBp, _builder)` sets `this.builder = _builder`\n // with NO automatic restore, explicitly restoring via `setBuilder()`\n // afterward (not a `finally`, since a thrown parse error here should\n // propagate as-is; there's no further use of `this.builder` on that\n // path before the whole parse aborts) avoids silently emitting\n // whatever parses next (in this same expression, or, via\n // ExpressionEngine's builder pool, a LATER, unrelated line) into a\n // stale, already-.build()'d body builder.\n const bodyBuilder = new BytecodeBuilder(this.pluginFunctionIndex);\n this.parseExpression(BindingPower.Lowest, bodyBuilder);\n this.setBuilder(builder);\n\n const bodyProgram = bodyBuilder.build();\n if (bodyProgram.hasAsync) {\n // v1 scope decision: a function body calling an async plugin\n // (weather, stocks, currency, ...) isn't supported yet, propagating\n // a 'pending' result up through a reentrant executeBytecode() call\n // would need the OUTER expression's own bytecode position/stack\n // state to also be resumable later, which this first pass doesn't\n // implement. Rejecting at DEFINITION time (not call time) gives the\n // clearest possible error, matching this codebase's \"never silently\n // pretend to support something it doesn't\" convention (e.g.\n // addBusinessDays()'s own disclosed holiday-exclusion scope-down).\n throw ErrorFactory.parsing(\n \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n `\"${nameToken.value}(...)\"'s body calls an async operation (weather, stocks, currency, ...) — user-defined function bodies must be synchronous`,\n { name: nameToken.value },\n );\n }\n\n const bodyIdx = builder.emitUserFunctionBody(nameToken.value, params, bodyProgram);\n builder.emitOpcode(OpCode.DEFINE_USER_FUNCTION);\n builder.emitIndex(bodyIdx);\n\n // A definition line has no single input value to echo back the way an\n // assignment does, push a plain confirmation string, matching this\n // codebase's \"never silently produce a misleading numeric 0\" principle.\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(`${nameToken.value}(${params.join(\", \")}) defined`);\n }\n\n private parseUserFunctionCall(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n let argCount = 0;\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n this.consume(TokenTypes.RPAREN);\n\n builder.emitOpcode(OpCode.CALL_USER_FUNCTION);\n builder.emitString(nameToken.value);\n builder.emitByte(argCount);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Token stream navigation (identical API to Parser)\n // ═══════════════════════════════════════════════════════════════════════════════\n\n consume(expectedType?: string): Token {\n const token = this.tokens[this.current];\n if (!token) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_END_OF_INPUT\",\n \"Unexpected end of input\"\n );\n }\n if (expectedType !== undefined) {\n const expectedId = tokenTypeId(expectedType);\n if (token.typeId !== expectedId) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_TOKEN_TYPE\",\n `Expected token type \"${expectedType}\" but got \"${token.type}\" (\"${token.value}\")`,\n { expectedType, actualType: token.type, actualValue: token.value }\n );\n }\n }\n this.current++;\n return token;\n }\n\n match(expectedType: string): boolean {\n const token = this.peek();\n if (token && token.typeId === tokenTypeId(expectedType)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n peek(): Token | undefined {\n return this.tokens[this.current];\n }\n\n /**\n * Read-only lookahead `offset` tokens past the current position, without\n * consuming anything, `peekAt(0)` is equivalent to {@link peek}.\n * `this.tokens` is a plain in-memory array (not a stream), so this is a\n * simple, safe index read; no rewind/checkpoint mechanism is needed since\n * nothing is consumed.\n */\n peekAt(offset: number): Token | undefined {\n return this.tokens[this.current + offset];\n }\n\n previous(): Token | undefined {\n return this.current > 0 ? this.tokens[this.current - 1] : undefined;\n }\n\n private advance(): void {\n this.current++;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Builder access, set before parse, read by inline prefix handlers\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /** Set the builder to use for the current parse. Called by ExpressionEngine. */\n setBuilder(builder: BytecodeBuilder): void {\n this.builder = builder;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Diagnostics\n // ═══════════════════════════════════════════════════════════════════════════════\n\n private fireParseletMatched(\n parselet: { category: string },\n token: Token,\n isPrefix: boolean,\n bindingPower?: number\n ): void {\n const pipeline = this.diagnosticPipeline!;\n const event: DiagnosticEvent & { type: \"parselet_matched\" } = {\n type: DiagnosticEventType.ParseletMatched,\n elapsedNs: 0,\n expression: this.currentExpression,\n tokenType: token.type,\n tokenValue: token.value,\n parseletCategory: parselet.category,\n parseletType: parselet.constructor?.name ?? \"unknown\",\n isPrefix,\n bindingPower,\n tokenOffset: token.offset || 0,\n };\n pipeline.fireParseletMatched(event);\n }\n}\n","import { PrefixParselet, InfixParselet } from \"@solve-js/parser/Parselet\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\n\n/**\n * The one binding-power field a parselet may expose beyond what its interface\n * requires, read only for diagnostic display.\n *\n * `InfixParselet` requires `bindingPower`; `PrefixParselet` declares none, and\n * some prefix parselets carry one anyway. That single field is the whole\n * optional surface deliberately. A `leftBindingPower`/`rightBindingPower` pair\n * used to be read here as well, and reading a name off an object this way finds\n * PRIVATE fields too, since TypeScript's `private` exists only at compile time:\n * `BinaryOpParselet` holds a private `rightBindingPower` meaning \"the minimum\n * power to parse my right operand at\", which is a different quantity from \"the\n * power at which I bind to my right\" and differs from it by one. Reading it\n * silently reported that other number. So neither is read.\n *\n * `category` is not here: both interfaces already declare it.\n */\ninterface ParseletBindingPowers {\n\treadonly bindingPower?: number;\n}\n\n/** Reads the optional binding-power field off a parselet for diagnostics. */\nfunction bindingPowersOf(parselet: PrefixParselet | InfixParselet): ParseletBindingPowers {\n\treturn parselet as ParseletBindingPowers;\n}\n\n/**\n * Dual-keyed ParseletRegistry, accepts both string token types and\n * integer token type IDs for fast dispatch in the Parser hot path.\n *\n * Providers call registerPrefix(\"NUMBER\", ...) with string token types.\n * Internally, we populate both string-keyed and integer-keyed maps so\n * Parser.parseExpression() can use token.typeId (integer) for lookup\n * while diagnostics and error messages use token.type (string).\n *\n * Performance: Integer Map.get() avoids string hashing, saving ~2-5ns\n * per dispatch. With ~10-15 dispatches per expression, that's ~20-75ns.\n */\nexport class ParseletRegistry {\n\t// String-keyed maps (kept for diagnostics + backwards compat)\n\tprivate prefixParselets: Map<string, PrefixParselet> = new Map();\n\tprivate infixParselets: Map<string, InfixParselet> = new Map();\n\n\t// Integer-keyed maps for parser hot path\n\tprivate prefixById: Map<number, PrefixParselet> = new Map();\n\tprivate infixById: Map<number, InfixParselet> = new Map();\n\n\t/**\n\t * Register a prefix parselet for `tokenType`.\n\t *\n\t * If another parselet is already registered for this token type, it is\n\t * silently overwritten by default (`Map.set()` semantics), the old\n\t * parselet is simply unreachable from then on, with no error. This is\n\t * a real footgun for third-party packages: two packages independently\n\t * choosing the same custom token type will collide with zero signal\n\t * about which one \"won\". Mirrors ResolverRegistry.register()'s and\n\t * ExpressionEngine.registerPackage()'s existing \"warn and replace\"\n\t * pattern for the same class of problem at the resolver-namespace and\n\t * package-name levels.\n\t *\n\t * Note: this warns about registry-level collisions only. It does NOT\n\t * detect the separate case where `tokenType` is one of PrecedenceParser's\n\t * Tier-1 fast-path token types (NUMBER, STRING, IDENT, LPAREN, MINUS,\n\t * PLUS, and the Tier-1 infix operators), those are deliberately kept\n\t * registered here for introspection/diagnostics even though Tier-1\n\t * always intercepts them before this registry is consulted (see\n\t * PrecedenceParser.parsePrefix()'s docs), so warning there would\n\t * misfire on that intentional, already-documented pattern.\n\t */\n\tregisterPrefix(tokenType: string, parselet: PrefixParselet): void {\n\t\tconst existing = this.prefixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Prefix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.prefixParselets.set(tokenType, parselet);\n\t\tthis.prefixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/** Register an infix parselet for `tokenType`. See {@link registerPrefix} for the collision-warning behavior this mirrors. */\n\tregisterInfix(tokenType: string, parselet: InfixParselet): void {\n\t\tconst existing = this.infixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Infix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.infixParselets.set(tokenType, parselet);\n\t\tthis.infixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/**\n\t * Iterate all registered prefix parselets for diagnostic display.\n\t *\n\t * `PrefixParselet` declares no binding power, and this used to read a field\n\t * of that name and report 0 for every one of them. 0 is not a neutral\n\t * wrong answer: it is the value that means \"not an operator, stop the\n\t * expression\", so a host drawing a table from this was told none of them\n\t * bind at all. A prefix parselet in this parser has no per-parselet power\n\t * to report, they all bind at the prefix level and each chooses for itself\n\t * at what power to parse its own operand, so that level is what is\n\t * reported. A parselet that does carry its own `bindingPower` still wins.\n\t */\n\tgetAllPrefix(): Array<{ tokenType: string; bindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; bindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.prefixParselets) {\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tbindingPower: bindingPowersOf(parselet).bindingPower ?? BindingPower.Prefix,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterate all registered infix parselets for diagnostic display.\n\t *\n\t * The field an `InfixParselet` actually declares is `bindingPower`. This\n\t * used to read `leftBindingPower` and `rightBindingPower`, which no\n\t * parselet in this codebase declares, so both reads were `undefined`, both\n\t * fell to the `?? 0` default, and the public `getParseletRegistry()`\n\t * reported a binding power of 0 for every one of the ~60 infix operators.\n\t * A host building a precedence table from it was told `*` and `+` bind\n\t * equally, and that neither binds at all.\n\t *\n\t * The left/right split: `bindingPower` is the LEFT power, and the right is\n\t * one higher. That is the standard encoding for a left-associative\n\t * operator, and it is what the parser itself does, see\n\t * `PrecedenceParser.parseExpression()`'s `bp + 1` for the right operand.\n\t * Every operator is reported that way, `^` included. Associativity is not\n\t * something a parselet declares, it is a property of how each one calls\n\t * `parseExpression`, so this API cannot report it without a new field on\n\t * the interface. See {@link ParseletBindingPowers} for why scraping a\n\t * plausible-looking one off the parselet is worse than not reporting it.\n\t */\n\tgetAllInfix(): Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.infixParselets) {\n\t\t\tconst left = bindingPowersOf(parselet).bindingPower ?? 0;\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tleftBindingPower: left,\n\t\t\t\trightBindingPower: left + 1,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Number of registered prefix parselets. */\n\tget prefixCount(): number { return this.prefixParselets.size; }\n\n\t/** Number of registered infix parselets. */\n\tget infixCount(): number { return this.infixParselets.size; }\n\n\t/**\n\t * Get prefix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings\n\t * (diagnostics, error messages, backwards compatibility).\n\t */\n\tgetPrefix(tokenType: string | number): PrefixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.prefixById.get(tokenType);\n\t\treturn this.prefixParselets.get(tokenType);\n\t}\n\n\t/**\n\t * Get infix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings.\n\t */\n\tgetInfix(tokenType: string | number): InfixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.infixById.get(tokenType);\n\t\treturn this.infixParselets.get(tokenType);\n\t}\n\n\thasPrefix(tokenType: string): boolean {\n\t\treturn this.prefixParselets.has(tokenType);\n\t}\n\n\thasInfix(tokenType: string): boolean {\n\t\treturn this.infixParselets.has(tokenType);\n\t}\n\n\tclear(): void {\n\t\tthis.prefixParselets.clear();\n\t\tthis.infixParselets.clear();\n\t\tthis.prefixById.clear();\n\t\tthis.infixById.clear();\n\t}\n}\n\n/**\n * A process-wide parselet registry.\n *\n * @deprecated An engine builds its own registry and does not read this one, so\n * registering here reaches nothing that evaluates. Nothing writes to it now\n * that the global package-registration path is gone; it remains only so the\n * `@solve-js/parser` escape hatch keeps a stable shape.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c}from'./chunk-MPB7KUN5.js';var m=0,l=0,p=Number.POSITIVE_INFINITY,d=0,h=Number.POSITIVE_INFINITY;function b(e,t,r){return c.execution({code:"ALLOCATION_LIMIT_EXCEEDED",message:`Evaluating this expression would materialise ${e.toLocaleString("en-US")} ${t}, past the limit of ${p.toLocaleString("en-US")} elements for one evaluation`,expected:`at most ${p.toLocaleString("en-US")} elements materialised while evaluating one expression`,found:`a request for ${e.toLocaleString("en-US")} more ${t}, on top of ${r.toLocaleString("en-US")} already materialised`,suggestion:"use a smaller collection or matrix, or raise the engine's vm.maxAllocatedElements setting",context:{requested:e,what:t,used:r,limit:p}})}function w(e){m++===0&&(l=0,p=e.getMaxAllocatedElements(),d=0,h=e.getMaxFunctionCalls());}function _(){m>0&&m--;}function T(e,t){if(m!==0){if(!(e>=0))throw b(e,t,l);if(l+=e,l>p)throw b(e,t,l-e)}}function N(e,t){if(m!==0&&(!(e>=0)||l+e>p))throw b(e,t,l)}function R(e,t){return N(e,t),new Array(e)}function P(){if(m!==0&&++d>h)throw c.execution({code:"FUNCTION_CALL_LIMIT_EXCEEDED",message:`Evaluating this expression would make more than ${h.toLocaleString("en-US")} user-defined-function calls, which is the limit for one evaluation`,expected:`at most ${h.toLocaleString("en-US")} function calls while evaluating one expression`,found:"a call past that limit, from a chain of functions that each call others more than once",suggestion:"check for a function that calls itself (or a chain of them) more times than intended, or raise the engine's vm.maxFunctionCalls setting",context:{calls:d,callLimit:h}})}var E=(n=>(n[n.Number=0]="Number",n[n.Hex=1]="Hex",n[n.BigInt=2]="BigInt",n[n.String=3]="String",n[n.Datetime=4]="Datetime",n[n.Percentage=5]="Percentage",n[n.Uom=6]="Uom",n[n.Matrix=7]="Matrix",n[n.Range=8]="Range",n[n.Symbolic=9]="Symbolic",n[n.Boolean=10]="Boolean",n[n.Unit=11]="Unit",n[n.Pending=12]="Pending",n[n.Error=13]="Error",n[n.Colour=14]="Colour",n[n.Split=15]="Split",n[n.Chart=16]="Chart",n))(E||{}),f=class f{constructor(t=512){this.arena=[];this.index=0;this.initialSize=t;for(let r=0;r<t;r++)this.arena.push(new a(0,0));}acquire(t,r,o){if(this.index<this.arena.length){let s=this.arena[this.index++];return s.recycle(t,r,o),s}let y=new a(t,r,o);return this.arena.push(y),this.index++,y}reset(){let t=this.index;this.index=0,!(this.arena.length<=this.initialSize)&&(this.arena.length<=t*f.SHRINK_WHEN_HOLDING_TIMES||(this.arena.length=Math.max(this.initialSize,t*f.KEEP_TIMES)));}get usage(){return this.index}get capacity(){return this.arena.length}};f.SHRINK_WHEN_HOLDING_TIMES=4,f.KEEP_TIMES=2;var g=f,i=null,u=false;function A(e){return i||(i=new g(e)),i.reset(),u=true,i}function O(){u=false;}function v(){return u}function $(e){let t=new a(e.type,e.value,e.unit);return e.exact!==void 0&&(t.exact=e.exact),e.rational!==void 0&&(t.rational=e.rational),e.uncertainty!==void 0&&(t.uncertainty=e.uncertainty),t}var I=process.env.NODE_ENV==="development";function q(e){return I&&!v()&&(e.toNumber(),Object.freeze(e)),e}var a=class{constructor(t,r,o){this.type=t,this.value=r,this.unit=o,typeof r=="number"&&(this._cachedNumber=r);}recycle(t,r,o){this.type=t,this.value=r,this.unit=o,this._cachedNumber=typeof r=="number"?r:void 0,this.timedOut=void 0,this.exact=void 0,this.rational=void 0,this.uncertainty=void 0,this.decimalPlaces=void 0;}isNumber(){return this.type===0}isHex(){return this.type===1}isBigInt(){return this.type===2}isString(){return this.type===3}isMatrix(){return this.type===7}isVectorShape(){if(this.type!==7)return false;let t=this.value;return t.rows===1||t.cols===1}isRange(){return this.type===8}isColour(){return this.type===14}isChart(){return this.type===16}isSymbolic(){return this.type===9}isError(){return this.type===13}isPending(){return this.type===12}isFault(){return this.type===13||this.type===12}get errorCode(){return this.type===13?this.value:void 0}get errorMessage(){return this.type===13?this.unit:void 0}toNumber(){if(this.type===12||this.type===13)return 0;if(this.type===7){let r=this.value;return r.rows===1&&r.cols===1&&typeof r.data[0]=="number"?r.data[0]:0}if(this.type===8||this.type===14||this.type===16)return 0;if(this.type===15)return this.value.shares[0].value;if(this.type===9)return 0;if(this.type===10)return this.value===true?1:0;if(this._cachedNumber!==void 0)return this._cachedNumber;if(typeof this.value=="bigint")return this._cachedNumber=Number(this.value),this._cachedNumber;let t=parseFloat(this.value);return this._cachedNumber=isNaN(t)?0:t,this._cachedNumber}isNaN(){if(this.type===12||this.type===13)return false;if(this.type===7){let t=this.value;return t.rows===1&&t.cols===1&&typeof t.data[0]=="number"?isNaN(t.data[0]):false}return this.type===8||this.type===14||this.type===15||this.type===16||this.type===9||this.type===10?false:typeof this.value=="number"?isNaN(this.value):typeof this.value=="bigint"?false:isNaN(parseFloat(this.value))}};function x(e){return u&&i?i.acquire(0,e):new a(0,e)}function B(e,t){let r=x(e);return r.exact=t,r}function H(e,t){let r=x(e);return r.rational=t,r}function k(e,t){let r=x(e);return r.uncertainty=t,r}function j(e,t="hex"){let r=t==="hex"?void 0:t;return u&&i?i.acquire(1,e,r):new a(1,e,r)}function K(e){return u&&i?i.acquire(2,e):new a(2,e)}function z(e){return u&&i?i.acquire(3,e):new a(3,e)}function D(e,t){return u&&i?i.acquire(6,e,t):new a(6,e,t)}function Y(e,t,r){let o=D(e,t);return o.exact=r,o}function W(e,t,r){return D(e,`${t}/${r}`)}function X(e){return typeof e=="string"&&e.includes("/")}function G(e){let t=e.indexOf("/");if(t<0)throw c.internal("INVALID_RATE_UNIT",`splitRateUnit: "${e}" is not a rate unit (expected "numerator/denominator")`,{unit:e});return {numerator:e.slice(0,t),denominator:e.slice(t+1)}}var V="timecode@";function J(e){return `${V}${e}`}function C(e){return typeof e=="string"&&e.startsWith(V)}function Q(e){if(!C(e))throw c.internal("INVALID_TIMECODE_UNIT",`timecodeFps: "${e}" is not a timecode unit (expected "timecode@<fps>")`,{unit:e});return parseFloat(e.slice(V.length))}function S(e,t,r){T(r.length,"matrix cells");let o=r.some(s=>typeof s=="object"&&s!==null&&"kind"in s),y={rows:e,cols:t,data:r,hasSymbolic:o};return u&&i?i.acquire(7,y):new a(7,y)}function Z(e){return S(1,e.length,e)}function ee(e){return S(e.length,1,e)}function te(e,t){let r={min:e,max:t};return u&&i?i.acquire(8,r):new a(8,r)}function re(e){return u&&i?i.acquire(14,e):new a(14,e)}function ne(e){return u&&i?i.acquire(15,e):new a(15,e)}function ie(e){return u&&i?i.acquire(16,e):new a(16,e)}function ae(e){return u&&i?i.acquire(9,e):new a(9,e)}function ue(e){return u&&i?i.acquire(10,e):new a(10,e)}function oe(e){return u&&i?i.acquire(4,e):new a(4,e)}function le(e){return u&&i?i.acquire(5,e):new a(5,e)}function se(e){return new a(12,e)}function ce(e,t){return new a(13,e,t)}function pe(e,t,r){return e.type===13||e.type===12?e:t!==void 0&&(t.type===13||t.type===12)?t:r!==void 0&&(r.type===13||r.type===12)?r:null}function me(e){for(let t=0;t<e.length;t++){let r=e[t];if(r.type===13||r.type===12)return r}return null}export{C as A,Q as B,S as C,Z as D,ee as E,te as F,re as G,ne as H,ie as I,ae as J,ue as K,oe as L,le as M,se as N,ce as O,pe as P,me as Q,w as a,_ as b,T as c,N as d,R as e,P as f,E as g,A as h,O as i,v as j,$ as k,q as l,a as m,x as n,B as o,H as p,k as q,j as r,K as s,z as t,D as u,Y as v,W as w,X as x,G as y,J as z};//# sourceMappingURL=chunk-IO374J6Z.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-IO374J6Z.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vm/AllocationBudget.ts","../src/vm/Value.ts"],"names":["depth","used","limit","calls","callLimit","exceeded","requested","what","alreadyUsed","ErrorFactory","beginEvaluation","vm","endEvaluation","chargeAllocation","count","checkAllocation","checkedArray","chargeFunctionCall","ValueType","_ValueArena","initialSize","i","Value","type","value","unit","v","usedLastCycle","ValueArena","_arena","_arenaActive","enableValueArena","size","disableValueArena","isArenaActive","persistentValue","p","isDevelopmentBuild","freezeIfDev","m","result","numberValue","n","numberValueExact","exact","numberValueRational","rational","numberValueUncertain","uncertainty","hexValue","base","tag","bigIntValue","stringValue","s","uomValue","uomValueExact","rateValue","magnitude","numeratorUnit","denominatorUnit","isRateUnit","splitRateUnit","idx","TIMECODE_UNIT_PREFIX","timecodeUnit","fps","isTimecodeUnit","timecodeFps","matrixValue","rows","cols","data","hasSymbolic","cell","rowVectorValue","colVectorValue","rangeValue","min","max","colourValue","c","splitValue","chartValue","symbolicValue","node","boolValue","b","datetimeValue","percentageValue","pendingValue","queryKey","errorValue","code","message","faultedOperand","a","faultedIn","values"],"mappings":"oCAwDA,IAAIA,EAAQ,CAAA,CAGRC,CAAAA,CAAO,EAGPC,CAAAA,CAA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ceiling on how much memory one evaluation is allowed to ask for.\n *\n * The VM's other two counters bound how many opcodes run and how deep the value\n * stack gets, and both are checked BETWEEN opcodes. That leaves a hole the size\n * of a single opcode: whatever one opcode allocates in a loop of its own is\n * invisible to both, so twenty-four characters of input (`map(10*x,\n * 0:2000000000)`) could allocate until V8 aborted the process, which no\n * `try`/`catch` in the host can contain. Per-site caps close one hole each and\n * do not compose: two collections that are individually legal are legal\n * together, and an operation whose result is the PRODUCT of two legal inputs (a\n * matrix multiply) is bounded by neither of them.\n *\n * This is the counter that composes. Everything an evaluation materialises is\n * charged against one running tally, so the bound is on the total rather than\n * on any single step, and a new opcode inherits it by allocating through\n * {@link chargedArray} or by building a Value through a constructor that\n * already charges ({@link matrixValue}).\n *\n * The tally is module state rather than something threaded through every\n * signature. `executeBytecode()` opens an evaluation and every charge inside\n * that window lands on it, which is what lets a helper five call levels down\n * (`vm/MatrixOps.ts`'s `collectionToValues()`) charge without the four frames\n * in between passing a parameter along, and what keeps a charge down to an add\n * and a compare. This mirrors the value arena in `vm/Value.ts`, which is\n * ambient for the same reason and rests on the same fact: `executeBytecode()`\n * is synchronous, so exactly one evaluation is ever in flight in a realm.\n *\n * An \"element\" is one thing a user's input caused to exist: a `Value` in an\n * expanded collection, a cell in a matrix. They are counted rather than\n * measured in bytes, because a count is the quantity every call site already\n * has in hand before it allocates, and asking V8 how big something is costs\n * more than the allocation being guarded.\n *\n * A second tally lives here for the same structural reason and not because it\n * counts the same thing: {@link chargeFunctionCall} bounds how many\n * user-defined-function calls one evaluation may make in total. Surviving\n * reentry is the whole property both need, and this module is where reentry is\n * already tracked.\n *\n * @module AllocationBudget\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\n\n/**\n * How deep the evaluation is: 0 outside one, higher inside a reentrant call.\n *\n * `executeBytecode()` re-enters itself for a user-defined function call, a map\n * or reduce transform body, and an algebra verb's bound-unknown body. Only the\n * outermost entry clears the tally, so a runaway recursion cannot refresh its\n * own allowance the way it can refresh `maxInstructions` (each reentrant call\n * gets a fresh local instruction count, which is why function recursion needed\n * a separate guard of its own).\n */\nlet depth = 0;\n\n/** Elements charged so far in the evaluation currently in flight. */\nlet used = 0;\n\n/** The in-flight evaluation's ceiling, read from its VM when the evaluation opened. */\nlet limit = Number.POSITIVE_INFINITY;\n\n/** User-defined-function calls made so far in the evaluation currently in flight. */\nlet calls = 0;\n\n/** The in-flight evaluation's call ceiling, read from its VM when the evaluation opened. */\nlet callLimit = Number.POSITIVE_INFINITY;\n\n/**\n * The refusal itself, built in one place so the wording of the engine's most\n * likely \"this is too big\" message is not reinvented per site.\n */\nfunction exceeded(requested: number, what: string, alreadyUsed: number): Error {\n\treturn ErrorFactory.execution({\n\t\tcode: \"ALLOCATION_LIMIT_EXCEEDED\",\n\t\tmessage:\n\t\t\t`Evaluating this expression would materialise ${requested.toLocaleString(\"en-US\")} ${what}, ` +\n\t\t\t`past the limit of ${limit.toLocaleString(\"en-US\")} elements for one evaluation`,\n\t\texpected: `at most ${limit.toLocaleString(\"en-US\")} elements materialised while evaluating one expression`,\n\t\tfound: `a request for ${requested.toLocaleString(\"en-US\")} more ${what}, on top of ${alreadyUsed.toLocaleString(\"en-US\")} already materialised`,\n\t\tsuggestion: \"use a smaller collection or matrix, or raise the engine's vm.maxAllocatedElements setting\",\n\t\tcontext: { requested, what, used: alreadyUsed, limit },\n\t});\n}\n\n/**\n * Open an evaluation, taking its ceiling from the VM about to run it.\n *\n * @param vm - The VM running this program. Only consulted on the outermost\n * entry, so a reentrant call costs one increment.\n */\nexport function beginEvaluation(vm: VM): void {\n\tif (depth++ === 0) {\n\t\tused = 0;\n\t\tlimit = vm.getMaxAllocatedElements();\n\t\tcalls = 0;\n\t\tcallLimit = vm.getMaxFunctionCalls();\n\t}\n}\n\n/** Close the innermost evaluation. Always call from a `finally`, so a throw cannot leave one open. */\nexport function endEvaluation(): void {\n\tif (depth > 0) depth--;\n}\n\n/**\n * Record elements materialised by the evaluation in flight.\n *\n * Each thing is charged exactly once, where it comes into existence: a matrix\n * in `matrixValue()`, an expanded collection where it is expanded. A site that\n * knows a size in advance and whose result will be charged on birth uses\n * {@link checkAllocation} instead, so that refusing early does not mean\n * counting twice.\n *\n * Outside an evaluation this is a plain no-op rather than an error:\n * `matrixValue()` and the `vm/MatrixOps.ts` helpers are exported and get called\n * by tests, by the formatter and by hosts with no evaluation in flight, and\n * none of those is user input being executed.\n *\n * @param count - How many elements now exist.\n * @param what - What they are, in the plural and in a user's words (\"matrix\n * cells\", \"collection elements\"). Quoted verbatim in the error, so it should\n * name the thing rather than the code that makes it.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` when this evaluation has had enough.\n * Recoverable: it describes this expression, not the engine.\n */\nexport function chargeAllocation(count: number, what: string): void {\n\tif (depth === 0) return;\n\t// Written as a negated `>=` so that NaN takes this branch. A NaN count would\n\t// otherwise be added to the tally and make every later `used > limit`\n\t// comparison false, silently switching the guard off for the rest of the\n\t// evaluation, which is the one failure mode a safety limit must not have.\n\tif (!(count >= 0)) throw exceeded(count, what, used);\n\tused += count;\n\tif (used > limit) throw exceeded(count, what, used - count);\n}\n\n/**\n * Refuse an allocation this evaluation cannot afford, without recording it.\n *\n * For the sites that know how big a result will be BEFORE building it and whose\n * result is charged later, when it is born. A matrix product is the case that\n * matters: its size is the product of two operands that are each affordable, so\n * it has to be refused from the shapes alone, before `matrixMultiply()` takes\n * the memory. Charging here as well as at birth would bill every matrix twice\n * and halve the ceiling the host asked for.\n *\n * @param count - How many elements the result would have.\n * @param what - What they are, in the plural. See {@link chargeAllocation}.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` when the evaluation could not afford them.\n */\nexport function checkAllocation(count: number, what: string): void {\n\tif (depth === 0) return;\n\tif (!(count >= 0) || used + count > limit) throw exceeded(count, what, used);\n}\n\n/**\n * Check that an array is affordable, then allocate it.\n *\n * The intended way to build any user-sized array inside the VM whose contents\n * end up inside a Value that charges on birth, so that \"ask before you take\" is\n * a property of the allocator rather than something each new opcode has to be\n * told.\n *\n * @param count - Element count, checked before a single element exists.\n * @param what - What the elements are, in the plural. See {@link chargeAllocation}.\n * @returns An empty array of that length.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` before allocating anything, when the\n * evaluation cannot afford it.\n */\nexport function checkedArray<T>(count: number, what: string): T[] {\n\tcheckAllocation(count, what);\n\treturn new Array<T>(count);\n}\n\n/**\n * Record one user-defined-function call, and refuse the one past the ceiling.\n *\n * Lives in this module rather than in the VM for the single reason the element\n * tally does: it has to survive `executeBytecode()` re-entering itself. A call\n * count kept per invocation would be reset by the very calls it is counting,\n * which is exactly what happens to `maxInstructions` and exactly why counting\n * instructions could never bound this.\n *\n * The thing being bounded is BREADTH, which no existing guard could see.\n * `maxFunctionRecursionDepth` bounds nesting, and a doubling chain\n * (`f22(v) = f21(v) + f21(v)`, twenty-two lines of it) nests only twenty-two\n * deep while making 2,097,152 calls, which was a fatal heap abort in under a\n * second. Depth 22 against a limit of 50 is comfortably legal, and it was.\n *\n * @throws `FUNCTION_CALL_LIMIT_EXCEEDED` when this evaluation has made\n * enough. Recoverable: the engine is fine, this line is not.\n */\nexport function chargeFunctionCall(): void {\n\tif (depth === 0) return;\n\tif (++calls > callLimit) {\n\t\tthrow ErrorFactory.execution({\n\t\t\tcode: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n\t\t\tmessage:\n\t\t\t\t`Evaluating this expression would make more than ${callLimit.toLocaleString(\"en-US\")} ` +\n\t\t\t\t`user-defined-function calls, which is the limit for one evaluation`,\n\t\t\texpected: `at most ${callLimit.toLocaleString(\"en-US\")} function calls while evaluating one expression`,\n\t\t\tfound: \"a call past that limit, from a chain of functions that each call others more than once\",\n\t\t\tsuggestion: \"check for a function that calls itself (or a chain of them) more times than intended, or raise the engine's vm.maxFunctionCalls setting\",\n\t\t\tcontext: { calls, callLimit },\n\t\t});\n\t}\n}\n\n/**\n * Elements charged so far in the evaluation in flight, or in the one that just\n * finished. For tests and for a host reporting on a refusal.\n *\n * @returns The running tally.\n */\nexport function allocationUsed(): number {\n\treturn used;\n}\n\n/**\n * User-defined-function calls made so far in the evaluation in flight, or in\n * the one that just finished. For tests and for a host reporting on a refusal.\n *\n * @returns The running tally.\n */\nexport function functionCallsUsed(): number {\n\treturn calls;\n}\n\n/**\n * Drop all in-flight evaluation state.\n *\n * For tests that need a known starting point, and as a repair for a host that\n * somehow lost an `endEvaluation()`. Ordinary execution never needs it:\n * `executeBytecode()` pairs its own begin and end in a `finally`, and the\n * outermost begin clears the tally regardless of what came before.\n */\nexport function resetAllocationTracking(): void {\n\tdepth = 0;\n\tused = 0;\n\tlimit = Number.POSITIVE_INFINITY;\n\tcalls = 0;\n\tcallLimit = Number.POSITIVE_INFINITY;\n}\n","import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { chargeAllocation } from \"@solve-js/vm/AllocationBudget\";\nimport type { SymbolicNode, Rational } from \"@solve-js/symbolic\";\nimport type { DecimalData } from \"@solve-js/decimal\";\n\n/**\n * A single matrix cell. `boolean` covers element-wise comparison results\n * (`[1,6;3,8] < [5,2;7,4]` produces a Matrix of booleans, not numbers). A\n * `SymbolicNode` cell is a free-variable algebraic entry, e.g. `s =\n * [sx,0,0;0,sy,0;0,0,1]` where `sx`/`sy` are never assigned, so those\n * cells store a real `SymbolicNode` (a bare `var` node initially) rather\n * than degrading to `0`. See `MatrixOps.ts`'s `entryToSymbolic()`/\n * `symbolicToEntry()` for the two-way conversion every symbolic-aware\n * matrix op (multiply, inverse, determinant) uses.\n */\nexport type MatrixEntry = number | boolean | SymbolicNode;\n\n/**\n * A general rows×cols matrix, a vector is just a 1×N (row) or N×1 (column)\n * matrix. `data` is COLUMN-MAJOR (`data[row + col*rows]`), matching the\n * spec's own `a[index]` column-major indexing semantics directly (no\n * translation needed for single-index reads). `hasSymbolic` lets every\n * numeric matrix op fast-path the all-numeric case with one boolean check,\n * mirroring `binaryOp()`'s existing Number+Number fast path, computed by\n * `matrixValue()` itself (true the moment any cell is a `SymbolicNode`\n * object rather than a plain number/boolean), not something callers set\n * by hand.\n */\nexport interface MatrixData {\n\treadonly rows: number;\n\treadonly cols: number;\n\treadonly data: readonly MatrixEntry[];\n\treadonly hasSymbolic: boolean;\n}\n\n/** A first-class integer range `min:max`, both bounds inclusive. */\nexport interface RangeData {\n\treadonly min: number;\n\treadonly max: number;\n}\n\n/**\n * How a colour was authored, and therefore how it should display. It never\n * changes the channels: a colour is always stored as canonical sRGB (`r`,`g`,`b`\n * integers 0-255, `a` in 0-1), and `format` only decides whether `formatValue`\n * renders it as `#rrggbb`, `rgb(...)`, `hsl(...)` or a named keyword.\n */\nexport type ColourFormat = \"hex\" | \"rgb\" | \"rgba\" | \"hsl\" | \"hsla\" | \"named\";\n\n/**\n * A colour value. Canonical channels are sRGB (`r`,`g`,`b` are integers 0-255,\n * `a` is 0-1); HSL is never stored, it is derived on demand for display and for\n * hue/saturation/lightness operations, then re-quantised back to RGBA. A\n * `lighten` followed by an equal `darken` returns to within one rounding step of\n * the original (integer channels re-quantise each way), and does not drift on\n * repetition, rather than storing both HSL and RGB and letting them disagree.\n * `format`\n * records the authored/display form; `name` carries the CSS keyword only when\n * `format === \"named\"` (e.g. `\"rebeccapurple\"`). Lives in a {@link Value}'s\n * `value` slot exactly as {@link MatrixData}/{@link RangeData} do.\n */\nexport interface ColourData {\n\treadonly r: number;\n\treadonly g: number;\n\treadonly b: number;\n\treadonly a: number;\n\treadonly format: ColourFormat;\n\treadonly name?: string;\n}\n\n/**\n * One tier of a bill split: an amount and how many people pay it. An even\n * split is a single share; the odd-penny case is two shares (the base amount\n * most people pay, then the base plus a cent that the remaining `count` pay),\n * so the shares always add back to the exact total. `exact` carries the\n * base-ten cents of a currency share so display rounds from the decimal rather\n * than a drifted double, exactly as money does everywhere else.\n */\nexport interface SplitShare {\n\treadonly value: number;\n\treadonly exact?: DecimalData;\n\treadonly count: number;\n}\n\n/**\n * The result of a per-person bill split (`split $180 between 4`). `unit` is the\n * currency code when the amount was money, undefined for a bare number.\n * `shares` is ordered base-first: `shares[0]` is the \"each\" amount, and a\n * second share, when present, is the slightly larger amount the odd penny falls\n * on. Lives in a {@link Value}'s `value` slot exactly as {@link ColourData} and\n * {@link RangeData} do, a display-only payload the formatter renders.\n */\nexport interface SplitData {\n\treadonly unit?: string;\n\treadonly shares: readonly SplitShare[];\n}\n\n/**\n * What a {@link ChartData} draws, and therefore how a host renders it: a\n * `sparkline` is a tiny inline line with no axes, a `plot` a framed curve over a\n * domain. New kinds (a bar chart, a scatter) are added here, and every host that\n * switches on `kind` keeps working for the ones it already knows.\n */\nexport type ChartKind = \"sparkline\" | \"plot\";\n\n/**\n * A chart specification: the DATA to draw, never pixels. One shape holds every\n * visual the engine produces, `[1,2,3] as sparkline` and `plot sin(x) from 0 to\n * 2pi` alike, so a host reads `kind` to choose a renderer and draws `points`\n * scaled to `domain` × `range`. The engine brings the numbers; the developer\n * brings the charting library. `label` is the plain-text answer a reader without\n * a canvas still gets. A sparkline's points are `(index, value)`; a plot's are\n * `(x, y)`. Lives in a {@link Value}'s `value` slot exactly as\n * {@link MatrixData}/{@link ColourData} do (issues #186, #187).\n */\nexport interface ChartData {\n\treadonly kind: ChartKind;\n\t/** The points to draw, `(x, y)`. A sparkline indexes x from 0. */\n\treadonly points: readonly (readonly [number, number])[];\n\t/** The plain-text answer, e.g. `sin(x) over [0, 6.28]` or the series itself. */\n\treadonly label: string;\n\t/** The x-axis extent `[min, max]`. */\n\treadonly domain: readonly [number, number];\n\t/** The y-axis extent `[min, max]`, for scaling the drawn height. */\n\treadonly range: readonly [number, number];\n\t/** The source expression, for a plot; absent for a sparkline. */\n\treadonly expr?: string;\n}\n\n/**\n * Discriminated union tag for {@link Value} objects.\n *\n * Determines the runtime type of a Value and how its `value` field should\n * be interpreted. Used by the VM for type-aware dispatch in arithmetic,\n * comparison, and conversion operations.\n */\nexport enum ValueType {\n\t/** Plain 64-bit floating point number (IEEE 754 double) */\n\tNumber = 0,\n\tHex = 1,\n\tBigInt = 2,\n\tString = 3,\n\tDatetime = 4,\n\tPercentage = 5,\n\tUom = 6,\n\t/** General rows×cols matrix (a vector is a 1×N or N×1 matrix). Value is {@link MatrixData}. */\n\tMatrix = 7,\n\t/** A first-class integer range `min:max`, both inclusive. Value is {@link RangeData}. */\n\tRange = 8,\n\t/** A symbolic/algebraic expression tree (free-variable formula, not a concrete number). Value is a `SymbolicNode` (`@solve-js/symbolic`). */\n\tSymbolic = 9,\n\t/** Boolean true/false. Value is `boolean`. */\n\tBoolean = 10,\n\t/** Unit of measurement token (lexer only, not a runtime value). */\n\tUnit = 11,\n\t/** Async result pending resolution. Value stores the queryKey string. */\n\tPending = 12,\n\t/** Plugin-raised error propagated through the DAG. Value stores error code, unit stores message. */\n\tError = 13,\n\t/** A colour (hex/rgb/hsl/named). Value is {@link ColourData}. */\n\tColour = 14,\n\t/** A per-person bill split (`split $180 between 4`). Value is {@link SplitData}. */\n\tSplit = 15,\n\t/** A chart to draw (`[1,2,3] as sparkline`, `plot sin(x) from 0 to 2pi`). Value is {@link ChartData}. */\n\tChart = 16,\n}\n\n// ── ValueArena ────────────────────────────────────────────────────────────\n// Phase 5.3: Bump-allocator arena for zero-allocation Value reuse during scroll.\n// Instead of allocating new Value objects per instruction, we pre-allocate a\n// block and bump an index. A single arena.reset() per scroll frame recycles all\n// Values, no per-value release overhead, no GC pressure during 60fps scrolling.\n\n/**\n * Bump-allocator arena for zero-allocation Value reuse during scroll.\n *\n * Instead of allocating new Value objects per instruction, pre-allocates a\n * block and bumps an index. `arena.reset()` per scroll frame recycles all\n * Values, no per-value release overhead, no GC pressure during 60fps scrolling.\n *\n * Only active during Tier 2 scroll execution (ThreeTierEvaluator).\n */\nexport class ValueArena {\n\tprivate arena: Value[] = [];\n\tprivate index: number = 0;\n\t/** The block size to come back down to. Kept so {@link reset} can. */\n\tprivate readonly initialSize: number;\n\n\t/**\n\t * How much more than the last cycle needed the arena may go on holding\n\t * before it gives the difference back, and how much of it it keeps when it\n\t * does.\n\t *\n\t * A bump allocator that grows to serve one expensive line is working as\n\t * intended; one that never comes down is a leak wearing a cache's clothes.\n\t * `map(x*1, 1:100000)` is an ordinary line by every limit the engine has,\n\t * and it took the arena from 512 Values to 300,004, about 24MB that stayed\n\t * live through two forced full collections and through every later `1 + 1`,\n\t * because `acquire()` handles overflow with `push()` and `reset()` only\n\t * zeroed the bump index. The instance is module-level and survives\n\t * `disableValueArena()` on purpose, so that high-water mark was for the\n\t * life of the process.\n\t *\n\t * Keeping twice what the last cycle used, and only shrinking once holding\n\t * four times that, is what stops the release from becoming a different\n\t * performance bug: a steady scroll uses about the same number of Values\n\t * every frame, so it never meets the condition at all, and an alternating\n\t * heavy/light document degrades at worst to allocating the Values it would\n\t * have allocated with no arena in the first place.\n\t */\n\tprivate static readonly SHRINK_WHEN_HOLDING_TIMES = 4;\n\tprivate static readonly KEEP_TIMES = 2;\n\n\t/** Pre-allocate initial block. 512 Values covers ~30-line viewport comfortably. */\n\tconstructor(initialSize: number = 512) {\n\t\tthis.initialSize = initialSize;\n\t\tfor (let i = 0; i < initialSize; i++) {\n\t\t\tthis.arena.push(new Value(ValueType.Number, 0));\n\t\t}\n\t}\n\n\t/** Bump-allocate a recycled Value. Falls back to allocation only for overflow. */\n\tacquire(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode, unit?: string): Value {\n\t\tif (this.index < this.arena.length) {\n\t\t\tconst v = this.arena[this.index++];\n\t\t\tv.recycle(type, value, unit);\n\t\t\treturn v;\n\t\t}\n\t\t// Arena overflow, allocate fresh (rare, only for very complex expressions)\n\t\tconst v = new Value(type, value, unit);\n\t\tthis.arena.push(v);\n\t\tthis.index++;\n\t\treturn v;\n\t}\n\n\t/**\n\t * Reset for the next scroll frame, releasing a block the last frame turned\n\t * out not to need.\n\t *\n\t * Still O(1) in the ordinary case: one comparison against what the cycle\n\t * that just ended used, and the truncation only on the frame after an\n\t * unusually expensive one. Reading the usage here rather than at\n\t * `disableValueArena()` is what makes the policy \"the first cycle that does\n\t * not need the block gives it back\", which is the first thing a host does\n\t * after the line that grew it.\n\t */\n\treset(): void {\n\t\tconst usedLastCycle = this.index;\n\t\tthis.index = 0;\n\t\tif (this.arena.length <= this.initialSize) return;\n\t\tif (this.arena.length <= usedLastCycle * ValueArena.SHRINK_WHEN_HOLDING_TIMES) return;\n\t\t// Never below the initial block, and never above what is already held,\n\t\t// so this only ever truncates.\n\t\tthis.arena.length = Math.max(this.initialSize, usedLastCycle * ValueArena.KEEP_TIMES);\n\t}\n\n\t/** Current arena utilization (for diagnostics). */\n\tget usage(): number { return this.index; }\n\tget capacity(): number { return this.arena.length; }\n}\n\n// Module-level arena toggle. Single-threaded JS, so global state is safe.\n// The arena is ONLY active during Tier 2 scroll execution, the ThreeTierEvaluator\n// enables it before evaluating visible lines and disables it after.\n//\n// The arena INSTANCE survives disable(): constructing a ValueArena allocates\n// its whole initial block (512 Values), so dropping it on every disable would\n// pay that allocation cost again on the next enable, more garbage than the\n// arena saves. Instead, an `_arenaActive` flag gates use of the long-lived\n// instance; enable() just resets the bump index.\nlet _arena: ValueArena | null = null;\nlet _arenaActive = false;\n\n/** Enable the Value arena for zero-allocation scroll execution. */\nexport function enableValueArena(size?: number): ValueArena {\n\tif (!_arena) _arena = new ValueArena(size);\n\t_arena.reset();\n\t_arenaActive = true;\n\treturn _arena;\n}\n\n/** Disable the arena (returns to normal GC-collected allocation). */\nexport function disableValueArena(): void {\n\t_arenaActive = false;\n}\n\n/** Check if arena is active (used by STORE_VAR / HALT to decide cloning). */\nexport function isArenaActive(): boolean {\n\treturn _arenaActive;\n}\n\n/**\n * Allocate a Value that persists beyond the current arena cycle.\n * Used for values stored in variables (STORE_VAR) and final expression results\n * (HALT return), these must survive arena.reset() in the next scroll frame.\n */\nexport function persistentValue(v: Value): Value {\n\tconst p = new Value(v.type, v.value, v.unit);\n\t// The exact sidecar has to survive being stored in a variable, or a\n\t// referenced money value would silently drop back to the double: \"a = $0.10,\n\t// b = $0.20, a + b\" must still be exact across the STORE_VAR round trip.\n\tif (v.exact !== undefined) p.exact = v.exact;\n\t// The rational sidecar survives the same round trip, so \"a = 1/3, a + a + a\"\n\t// is exactly 1 rather than the drifted double a stored fraction would carry.\n\tif (v.rational !== undefined) p.rational = v.rational;\n\t// The uncertainty sidecar survives too, so \"a = 12.3 +/- 0.5, a * 4\" still\n\t// propagates the tolerance across the STORE_VAR round trip.\n\tif (v.uncertainty !== undefined) p.uncertainty = v.uncertainty;\n\treturn p;\n}\n\n// ── Dev-mode immutability guard (Part II, L5, Value model hardening) ──\n//\n// Value is documented immutable by convention, not enforcement: the arena\n// mutates objects in place via recycle() (by design, for Tier-2 scroll\n// performance), so Value can never be unconditionally frozen. This guard\n// freezes a Value ONLY when it is safe to do so, i.e. NOT while the arena\n// is active, since an arena-active Value may still be recycled later in\n// the same scroll frame. It is a no-op outside development builds (matches\n// the existing `process.env.NODE_ENV === \"development\"` convention used by\n// the app-layer logger) so there is zero runtime cost in production.\nconst isDevelopmentBuild = process.env.NODE_ENV === \"development\";\n\n/**\n * Freeze a Value in development builds, catching accidental external\n * mutation of \"immutable\" results early. Safe to call unconditionally\n * it is a no-op in production and a no-op whenever the arena is active\n * (an arena-active Value may still be recycle()'d before this scroll\n * frame ends, and freezing it would make recycle() throw).\n *\n * Intended for values leaving a public evaluation boundary\n * (ExpressionEngine.evaluateLine* / evaluateExpression), not for values\n * still moving through internal VM/arena machinery.\n */\nexport function freezeIfDev<T extends Value>(value: T): T {\n\tif (isDevelopmentBuild && !isArenaActive()) {\n\t\t// toNumber() lazily memoizes _cachedNumber for bigint/string values\n\t\t// (Number/Hex are already eagerly cached by the constructor), warm\n\t\t// it now so a later toNumber() call on the frozen object doesn't\n\t\t// try to write to a frozen field.\n\t\tvalue.toNumber();\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\n\n/**\n * Universal runtime value for the solve-js VM.\n *\n * Carries a {@link ValueType} discriminant, a polymorphic `value` payload,\n * and an optional `unit` string (for UoM values). Treated as immutable after\n * construction, the arena reuses objects internally via `recycle()`, but\n * external code should never mutate Value fields.\n *\n * A cached `_cachedNumber` avoids repeated `toNumber()` computation on\n * hot paths (ADD/SUB/MUL in the VM dispatch loop).\n */\nexport class Value {\n\t// Cached numeric representation, computed once on first toNumber() call.\n\t// Cleared on recycle() when the arena reuses this Value for a new value.\n\tprivate _cachedNumber: number | undefined;\n\n\t// Fields are NOT readonly, the arena reuses Value objects by calling\n\t// recycle() which overwrites all fields. External code should treat Values\n\t// as immutable after construction (arena handles mutation internally).\n\tpublic type: ValueType;\n\tpublic value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode;\n\tpublic unit?: string;\n\t/** Set by async resolvers when a fetch timed out, the result is a fallback (typically 0). */\n\tpublic timedOut?: boolean;\n\t/**\n\t * The exact base-ten value this Value stands for, when it has one.\n\t *\n\t * A sidecar rather than a replacement for `value`: money and decimal-point\n\t * literals set it to a {@link DecimalData} so that same-currency arithmetic\n\t * and display can be exact (\"$0.10 + $0.20\" is \"$0.30\", not\n\t * \"$0.30000000000000004\"), while `value` stays the nearest double so every\n\t * existing consumer that reads `.value` or `toNumber()` is unchanged. The\n\t * plain Number-times-Number fast paths deliberately ignore it, which is why\n\t * a bare \"0.1 + 0.2\" still answers the double it always did: exactness is\n\t * carried only where a unit-bearing operand asks for it. Cleared by\n\t * {@link recycle} so a reused arena Value never inherits a stale exact.\n\t */\n\tpublic exact?: DecimalData;\n\t/**\n\t * The exact rational value this Value stands for, when it has one.\n\t *\n\t * The second sidecar, the same shape as {@link exact} and for the same\n\t * reason: a fraction has no exact base-ten form (`1/3` is not any decimal),\n\t * so exact fraction arithmetic needs a numerator/denominator pair rather\n\t * than a coefficient and a scale. Integer division seeds it (\"1/3\" carries\n\t * the {@link Rational} 1/3), and `+`, `-`, `*`, `/` between rational-bearing\n\t * numbers keep it reduced, so \"1/49 * 49\" is exactly 1 and \"5/6 - 1/6 - 1/6\n\t * - 1/6 - 1/6 - 1/6\" is exactly 0 rather than the 1.6e-16 the doubles drift\n\t * to. `value` still holds the nearest double, recomputed from the exact\n\t * rational so accumulation error never creeps in, which is why the default\n\t * display and every `.value`/`toNumber()` reader are unchanged. Only a\n\t * fraction written with \"/\" carries it, so a decimal literal (\"0.1\") and a\n\t * transcendental result (\"sqrt(2)\") stay the plain doubles they were.\n\t * Cleared by {@link recycle} alongside {@link exact}.\n\t */\n\tpublic rational?: Rational;\n\t/**\n\t * The one-sigma uncertainty (standard error) this value carries, when it\n\t * has one.\n\t *\n\t * The third sidecar, the same shape as {@link exact} and {@link rational}\n\t * and for the same reason: a measurement written `12.3 ± 0.5` is still the\n\t * number 12.3 everywhere it is read as one, so the type stays\n\t * {@link ValueType.Number} and `value` stays the center, while this non\n\t * negative field carries the tolerance. The `±` (or ASCII `+/-`) operator\n\t * seeds it, and `+`, `-`, `*`, `/` propagate it in quadrature for\n\t * independent errors (see `vm/VMConversion.ts`'s `uncertainOp`). Everything\n\t * else (a comparison, a transcendental function, a unit conversion) reads\n\t * the center through `toNumber()` and drops the tolerance, which is why a\n\t * value with no uncertainty behaves exactly as a plain number always did.\n\t * Cleared by {@link recycle} alongside the other two sidecars.\n\t */\n\tpublic uncertainty?: number;\n\t/**\n\t * The number of decimal places this value should DISPLAY at, when it has been\n\t * given an explicit precision.\n\t *\n\t * A display sidecar, not a value one: `value` is unchanged, so every\n\t * `.value`/`toNumber()` reader and all arithmetic behave exactly as before,\n\t * and a value with no `decimalPlaces` formats the way it always did (the\n\t * global two-place default with trailing zeros trimmed). It is set only by an\n\t * explicit precision request, `<x> to N dp` and `round(x, N)`, so that\n\t * `3.14159 to 4 dp` shows `3.1416` and `1.5 to 2 dp` shows `1.50` rather than\n\t * the value being rounded but then displayed at the default two places. It is\n\t * NOT propagated through arithmetic (a later `+ 1` re-decides precision),\n\t * which is why nothing that did not ask for a precision is affected. Cleared\n\t * by {@link recycle} alongside the other sidecars.\n\t */\n\tpublic decimalPlaces?: number;\n\n\tconstructor(\n\t\ttype: ValueType,\n\t\tvalue: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode,\n\t\tunit?: string\n\t) {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t\tthis.unit = unit;\n\t\t// Eagerly cache for Number and Hex types (the most common case).\n\t\t// This avoids a method call + type-check on first toNumber().\n\t\tif (typeof value === 'number') {\n\t\t\tthis._cachedNumber = value;\n\t\t}\n\t}\n\n\t/**\n\t * Phase 5.3: Reset all fields for arena reuse.\n\t * Called by ValueArena.acquire(), zero allocation, just field assignment.\n\t */\n\trecycle(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode, unit?: string): void {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t\tthis.unit = unit;\n\t\t// Clear cache, value changed, cached number is stale.\n\t\t// Re-eager-cache for Number type (most common).\n\t\tthis._cachedNumber = typeof value === 'number' ? value : undefined;\n\t\t// Clear timeout flag, recycled Values shouldn't inherit stale metadata.\n\t\tthis.timedOut = undefined;\n\t\t// Clear the exact sidecar for the same reason: a reused Value that once\n\t\t// held money must not carry that money's decimal into a plain number.\n\t\tthis.exact = undefined;\n\t\t// The rational sidecar clears with it: a reused Value that once held a\n\t\t// fraction must not carry that fraction into a plain number.\n\t\tthis.rational = undefined;\n\t\t// The uncertainty sidecar clears the same way: a reused Value that once\n\t\t// carried a tolerance must not lend it to a plain number.\n\t\tthis.uncertainty = undefined;\n\t\t// The display-precision sidecar clears too: a reused Value that once had\n\t\t// an explicit `to N dp` must not display a plain number at that precision.\n\t\tthis.decimalPlaces = undefined;\n\t}\n\n\tisNumber(): this is Value & { value: number } {\n\t\treturn this.type === ValueType.Number;\n\t}\n\n\tisHex(): this is Value & { value: number } {\n\t\treturn this.type === ValueType.Hex;\n\t}\n\n\tisBigInt(): this is Value & { value: bigint } {\n\t\treturn this.type === ValueType.BigInt;\n\t}\n\n\tisString(): this is Value & { value: string } {\n\t\treturn this.type === ValueType.String;\n\t}\n\n\tisMatrix(): this is Value & { value: MatrixData } {\n\t\treturn this.type === ValueType.Matrix;\n\t}\n\n\t/** A Matrix shaped like a vector, 1×N (row) or N×1 (column). */\n\tisVectorShape(): boolean {\n\t\tif (this.type !== ValueType.Matrix) return false;\n\t\tconst m = this.value as MatrixData;\n\t\treturn m.rows === 1 || m.cols === 1;\n\t}\n\n\tisRange(): this is Value & { value: RangeData } {\n\t\treturn this.type === ValueType.Range;\n\t}\n\n\tisColour(): this is Value & { value: ColourData } {\n\t\treturn this.type === ValueType.Colour;\n\t}\n\n\tisChart(): this is Value & { value: ChartData } {\n\t\treturn this.type === ValueType.Chart;\n\t}\n\n\tisSymbolic(): this is Value & { value: SymbolicNode } {\n\t\treturn this.type === ValueType.Symbolic;\n\t}\n\n\t/**\n\t * An Error value: a fault carrying a code and message, propagated through the\n\t * DAG when a plugin or opcode cannot produce a quantity.\n\t *\n\t * An Error reads as the number 0 through {@link toNumber}, so a numeric\n\t * consumer that does not check this first cannot tell the fault apart from a\n\t * real zero: exactly the silently-wrong result the engine guards against\n\t * internally with {@link faultedOperand}. A host reading a live {@link Value}\n\t * off a result should branch on this (or {@link isFault}) before trusting the\n\t * number, and read {@link errorCode}/{@link errorMessage} for the detail.\n\t */\n\tisError(): boolean {\n\t\treturn this.type === ValueType.Error;\n\t}\n\n\t/**\n\t * A Pending value: an async result that has not yet resolved, holding the\n\t * query key it is waiting on. Reads as 0 through {@link toNumber}, the same\n\t * caveat as {@link isError}: a settled value arrives on a later evaluation.\n\t */\n\tisPending(): boolean {\n\t\treturn this.type === ValueType.Pending;\n\t}\n\n\t/**\n\t * Either fault, an Error or a Pending: the single predicate to check before\n\t * trusting {@link toNumber}. It mirrors the internal {@link faultedOperand}\n\t * rule that every opcode applies to its operands, so a host reading a result\n\t * makes the same distinction the engine does rather than computing with a\n\t * zero it cannot tell from a real one.\n\t */\n\tisFault(): boolean {\n\t\treturn this.type === ValueType.Error || this.type === ValueType.Pending;\n\t}\n\n\t/**\n\t * The stable {@link ErrorFactory} code of an Error value, else `undefined`.\n\t *\n\t * The code is the machine-branchable identifier (the message is the\n\t * human-facing text, {@link errorMessage}). It reads from the same slot\n\t * {@link errorValue} writes, so it is defined for exactly the values\n\t * {@link isError} accepts and `undefined` for every other type.\n\t */\n\tget errorCode(): string | undefined {\n\t\treturn this.type === ValueType.Error ? (this.value as string) : undefined;\n\t}\n\n\t/**\n\t * The human-facing message of an Error value, else `undefined`. Paired with\n\t * {@link errorCode}, which carries the branchable identifier.\n\t */\n\tget errorMessage(): string | undefined {\n\t\treturn this.type === ValueType.Error ? this.unit : undefined;\n\t}\n\n\ttoNumber(): number {\n\t\t// Pending/Error have no numeric representation at all, 0 (established\n\t\t// convention). A genuinely multi-cell Matrix has no single numeric\n\t\t// representation either (real callers branch on `.isMatrix()` BEFORE\n\t\t// reaching this fallback. See e.g. VM.ts's MUL/comparison dispatch)\n\t\t// but a 1x1 Matrix, the shape `float(x)`'s legacy sugar produces, see\n\t\t// packages/vector/parselets/FloatParselet.ts, IS a scalar in every\n\t\t// meaningful sense, so it degrades to that single cell's numeric value\n\t\t// rather than 0 (this exact case used to work \"by accident\" pre-Matrix,\n\t\t// since `parseFloat([2].toString())` happened to yield `2`).\n\t\tif (this.type === ValueType.Pending) return 0;\n\t\tif (this.type === ValueType.Error) return 0;\n\t\tif (this.type === ValueType.Matrix) {\n\t\t\tconst m = this.value as MatrixData;\n\t\t\tif (m.rows === 1 && m.cols === 1 && typeof m.data[0] === \"number\") return m.data[0];\n\t\t\treturn 0;\n\t\t}\n\t\tif (this.type === ValueType.Range) return 0;\n\t\t// A colour is a struct of channels, not a scalar; like Matrix/Range it has\n\t\t// no single numeric reading. Callers branch on `.isColour()` first.\n\t\tif (this.type === ValueType.Colour) return 0;\n\t\t// A chart is a set of points, not a scalar; callers branch on `.isChart()`.\n\t\tif (this.type === ValueType.Chart) return 0;\n\t\t// A split is a structured multi-share result; its scalar reading is the\n\t\t// \"each\" (base) share, so a numeric consumer or the worker DTO's number\n\t\t// field still gets a sensible value where a caller does not branch first.\n\t\tif (this.type === ValueType.Split) return (this.value as SplitData).shares[0].value;\n\t\t// A symbolic expression has no single concrete numeric value by\n\t\t// definition (it's a free-variable formula), 0, matching the\n\t\t// Pending/Error/Range convention. Real callers branch on\n\t\t// `.isSymbolic()` BEFORE reaching this fallback (see\n\t\t// `VMConversion.ts`'s `binaryOp()`).\n\t\tif (this.type === ValueType.Symbolic) return 0;\n\t\t// A boolean has an obvious numeric reading and no branch used to give it\n\t\t// one, so it fell through to `parseFloat(true)` -> NaN -> 0, and BOTH\n\t\t// booleans read as zero: `true == false` answered true, and every\n\t\t// arithmetic path that mixes a boolean with a number (\"true and 5\")\n\t\t// contributed nothing. 1/0 is the reading every language with a numeric\n\t\t// boolean coercion uses, and the one `if 1 then` already implies.\n\t\tif (this.type === ValueType.Boolean) return this.value === true ? 1 : 0;\n\n\t\tif (this._cachedNumber !== undefined) return this._cachedNumber;\n\n\t\tif (typeof this.value === 'bigint') {\n\t\t\tthis._cachedNumber = Number(this.value);\n\t\t\treturn this._cachedNumber;\n\t\t}\n\t\t// Prevent silent NaN propagation from non-numeric strings\n\t\tconst result = parseFloat(this.value as string);\n\t\tthis._cachedNumber = isNaN(result) ? 0 : result;\n\t\treturn this._cachedNumber;\n\t}\n\n\tisNaN(): boolean {\n\t\tif (this.type === ValueType.Pending) return false;\n\t\tif (this.type === ValueType.Error) return false;\n\t\tif (this.type === ValueType.Matrix) {\n\t\t\tconst m = this.value as MatrixData;\n\t\t\tif (m.rows === 1 && m.cols === 1 && typeof m.data[0] === \"number\") return isNaN(m.data[0]);\n\t\t\treturn false;\n\t\t}\n\t\tif (this.type === ValueType.Range) return false;\n\t\tif (this.type === ValueType.Colour) return false;\n\t\tif (this.type === ValueType.Split) return false;\n\t\tif (this.type === ValueType.Chart) return false;\n\t\tif (this.type === ValueType.Symbolic) return false;\n\t\t// Matches toNumber()'s boolean reading above. Without this a Boolean\n\t\t// reached the string branch at the bottom and `parseFloat(true)` made\n\t\t// every boolean report itself as NaN.\n\t\tif (this.type === ValueType.Boolean) return false;\n\t\tif (typeof this.value === 'number') return isNaN(this.value);\n\t\tif (typeof this.value === 'bigint') return false;\n\t\treturn isNaN(parseFloat(this.value as string));\n\t}\n}\n\n/**\n * Create a Number-typed Value. Uses the arena when active for zero-allocation.\n * This is the most common factory, over 90% of all Value creations.\n */\nexport function numberValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Number, n);\n\treturn new Value(ValueType.Number, n);\n}\n\n/**\n * A Number that also carries the exact decimal it was written as.\n *\n * The type stays {@link ValueType.Number} and `value` stays the nearest double,\n * so this Value behaves exactly like any other number everywhere it is read as\n * one. The `exact` sidecar only matters when it later meets a currency: that is\n * what lets \"$0.70 * 1.10\" be exact while \"0.1 + 0.2\" stays the double it was.\n * Decimal-point literals are compiled to this (see the PUSH_DECIMAL opcode).\n */\nexport function numberValueExact(n: number, exact: DecimalData): Value {\n\tconst v = numberValue(n);\n\tv.exact = exact;\n\treturn v;\n}\n\n/**\n * A Number that also carries the exact rational it evaluates to.\n *\n * The rational counterpart of {@link numberValueExact}: the type stays\n * {@link ValueType.Number} and `value` stays the nearest double (recomputed\n * from the rational, so a chain of fraction operations never accumulates\n * float error), so this reads as an ordinary number everywhere. The `rational`\n * sidecar is what keeps the next fraction operation and any `as fraction`\n * exact. Integer division produces this (see the DIV opcode).\n */\nexport function numberValueRational(n: number, rational: Rational): Value {\n\tconst v = numberValue(n);\n\tv.rational = rational;\n\treturn v;\n}\n\n/**\n * A Number that also carries a one-sigma uncertainty (standard error).\n *\n * The uncertainty counterpart of {@link numberValueExact}: the type stays\n * {@link ValueType.Number} and `value` stays the center, so this reads as an\n * ordinary number everywhere. The `uncertainty` sidecar is what lets `+`, `-`,\n * `*`, `/` propagate the tolerance in quadrature. The `±` operator produces\n * this (see the MAKE_UNCERTAIN opcode), as does any of those four ops when an\n * operand already carries one. The magnitude is stored as given, callers pass a\n * non-negative value (`Math.abs` at the seam, quadrature results are already\n * non-negative).\n */\nexport function numberValueUncertain(n: number, uncertainty: number): Value {\n\tconst v = numberValue(n);\n\tv.uncertainty = uncertainty;\n\treturn v;\n}\n\n/** Which base a {@link ValueType.Hex} value is displayed in. */\nexport type DisplayBase = \"hex\" | \"bin\" | \"oct\";\n\n/**\n * Create a Hex-typed Value: a **number** that displays in another base.\n *\n * The type is numeric on purpose, and that is the whole point of it. A base is\n * a way of writing a quantity, not a different kind of quantity, so `0xFF + 1`\n * has to be 256. Returning a string instead makes it 1, because a string reads\n * as zero in arithmetic, and nothing about that failure is visible at the point\n * of use.\n *\n * @param n - The number itself, in full precision. A `bigint` is accepted for\n * the same reason the type is numeric at all: `12345678901234567890n as hex`\n * has an exact answer, and forcing it through a double first rendered\n * 0xAB54A98CEB1F0800 for a value ending 0AD2.\n * @param base - How to display it, defaulting to hexadecimal. Carried in the\n * `unit` slot, which is free for this type.\n */\nexport function hexValue(n: number | bigint, base: DisplayBase = \"hex\"): Value {\n\tconst tag = base === \"hex\" ? undefined : base;\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Hex, n, tag);\n\treturn new Value(ValueType.Hex, n, tag);\n}\n\n/** Create a BigInt-typed Value (arbitrary-precision integer). */\nexport function bigIntValue(n: bigint): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.BigInt, n);\n\treturn new Value(ValueType.BigInt, n);\n}\n\n/** Create a String-typed Value. */\nexport function stringValue(s: string): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.String, s);\n\treturn new Value(ValueType.String, s);\n}\n\n/** Create a Unit-of-Measurement Value (typed number with unit annotation). */\nexport function uomValue(n: number, unit: string): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Uom, n, unit);\n\treturn new Value(ValueType.Uom, n, unit);\n}\n\n/**\n * A unit-of-measurement Value that also carries an exact decimal magnitude.\n *\n * This is how money keeps its precision: `value` is the nearest double (so\n * `toNumber()` and every existing Uom path are unchanged), and `exact` is the\n * decimal the amount really is. Same-currency arithmetic reads `exact` to stay\n * exact, and the formatter reads it to round a half-cent the way a ledger does\n * rather than the way `toFixed` does on a double.\n */\nexport function uomValueExact(n: number, unit: string, exact: DecimalData): Value {\n\tconst v = uomValue(n, unit);\n\tv.exact = exact;\n\treturn v;\n}\n\n// ── Rate, \"quantity per unit of something\" (SoulverCore: `$99/week`\n// `3 hours/day`, `30 fps`). Represented as a `ValueType.Uom` (no new\n// ValueType, a rate IS a unit-of-measurement, just a compound one) whose\n// `unit` string is `\"<numerator>/<denominator>\"`. The numerator is an\n// opaque label (may be a real convertible unit like \"USD\"/\"km\", or a bare\n// tag like \"frames\" that the `convert` package doesn't know about, rate\n// arithmetic never needs to convert the numerator, only compare it for\n// equality when combining two rates). The denominator MUST be a unit\n// `convertUnit()`/`getMeasure()` (uom/UomConverter.ts) recognizes, since\n// that's the part rate arithmetic actually rescales. See `vm/VM.ts`'s\n// `RATE_CONVERT`/`RATE_MUL`/`RATE_DIV` opcodes for the operations built on\n// this representation.\n\n/** Create a Rate value: `magnitude` of `numeratorUnit` per one `denominatorUnit`. */\nexport function rateValue(magnitude: number, numeratorUnit: string, denominatorUnit: string): Value {\n\treturn uomValue(magnitude, `${numeratorUnit}/${denominatorUnit}`);\n}\n\n/** Whether `unit` is a compound rate unit (`\"X/Y\"`) rather than a plain unit. */\nexport function isRateUnit(unit: string | undefined): unit is string {\n\treturn typeof unit === \"string\" && unit.includes(\"/\");\n}\n\n/**\n * Split a rate unit string into its numerator/denominator halves.\n * @throws if `unit` isn't a rate unit, check with {@link isRateUnit} first.\n */\nexport function splitRateUnit(unit: string): { numerator: string; denominator: string } {\n\tconst idx = unit.indexOf(\"/\");\n\tif (idx < 0) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INVALID_RATE_UNIT\",\n\t\t\t`splitRateUnit: \"${unit}\" is not a rate unit (expected \"numerator/denominator\")`,\n\t\t\t{ unit },\n\t\t);\n\t}\n\treturn { numerator: unit.slice(0, idx), denominator: unit.slice(idx + 1) };\n}\n\n/** Join a numerator/denominator pair back into a rate unit string. */\nexport function joinRateUnit(numeratorUnit: string, denominatorUnit: string): string {\n\treturn `${numeratorUnit}/${denominatorUnit}`;\n}\n\n// ── Video timecode, \"HH:MM:SS:FF at a given fps\" (SoulverCore: video\n// editing timecode literals, e.g. `01:02:03:04 at 30fps`). Represented the\n// same way Rate is above: NOT a new ValueType, just a `ValueType.Uom` whose\n// `unit` string is `\"timecode@<fps>\"` and whose numeric `value` is the\n// TOTAL FRAME COUNT since 00:00:00:00 at that fps, e.g. \"00:00:01:00 at\n// 30fps\" is `Uom(30, \"timecode@30\")`.\n//\n// Storing the total frame count (rather than four separate H/M/S/F fields)\n// means ordinary integer addition/subtraction on the numeric value is\n// ALREADY correct carry/borrow-aware arithmetic with zero extra logic\n// e.g. \"frame 29 + 2 frames\" at 30fps is just `29 + 2 = 31`, and 31 total\n// frames at 30fps IS frame 1 of the next second, with no explicit carry\n// step required. Carry/borrow only needs to be reconstructed when\n// converting a total frame count back into HH:MM:SS:FF display notation\n// see `packages/time/timecode/TimecodeMath.ts`'s `framesToTimecodeString()`.\n// See `vm/VM.ts`'s ADD/SUB dispatch for the arithmetic built on this\n// representation (timecode + frames, + duration, + timecode, - timecode).\n\nconst TIMECODE_UNIT_PREFIX = \"timecode@\";\n\n/** Build a timecode Uom unit string embedding its frame rate, e.g. `timecodeUnit(30)` -> `\"timecode@30\"`. */\nexport function timecodeUnit(fps: number): string {\n\treturn `${TIMECODE_UNIT_PREFIX}${fps}`;\n}\n\n/** Whether `unit` is a compound video-timecode unit (`\"timecode@<fps>\"`). */\nexport function isTimecodeUnit(unit: string | undefined): unit is string {\n\treturn typeof unit === \"string\" && unit.startsWith(TIMECODE_UNIT_PREFIX);\n}\n\n/**\n * Extract the fps from a timecode unit string.\n * @throws if `unit` isn't a timecode unit, check with {@link isTimecodeUnit} first.\n */\nexport function timecodeFps(unit: string): number {\n\tif (!isTimecodeUnit(unit)) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INVALID_TIMECODE_UNIT\",\n\t\t\t`timecodeFps: \"${unit}\" is not a timecode unit (expected \"timecode@<fps>\")`,\n\t\t\t{ unit },\n\t\t);\n\t}\n\treturn parseFloat(unit.slice(TIMECODE_UNIT_PREFIX.length));\n}\n\n/**\n * Create a Matrix value from an explicit shape + column-major data array.\n * `data.length` must equal `rows*cols`, callers building a matrix from\n * row-major source syntax (e.g. the `[1,2;3,4]` literal) must transpose\n * into column-major order before calling this; see `MatrixOps.ts`'s\n * `rowMajorToColumnMajor()`.\n */\nexport function matrixValue(rows: number, cols: number, data: readonly MatrixEntry[]): Value {\n\t// Every matrix in the engine is born here, which makes this the one place\n\t// that can charge for one without each producer having to remember to. The\n\t// charge lands after `data` exists, so it is a backstop rather than a\n\t// refusal: it cannot stop a single allocation that is already fatal (the\n\t// sites whose size is knowable in advance charge before allocating, see\n\t// `vm/VM.ts`'s matrix cases), but it does stop the second one, and it means\n\t// an opcode added later inherits the bound without being told about it.\n\t// Free in relative terms: the hasSymbolic scan just below is already O(n)\n\t// over the same cells.\n\tchargeAllocation(data.length, \"matrix cells\");\n\t// A SymbolicNode cell is the only object-typed MatrixEntry variant\n\t// (number/boolean are primitives), a cheap, always-correct way to\n\t// derive hasSymbolic without asking every caller to track it by hand.\n\t// The `\"kind\" in cell` half is a tripwire, not redundancy. MatrixEntry is\n\t// `number | boolean | SymbolicNode`, so an object cell should always be a\n\t// node; requiring the discriminant means a Rational that escaped\n\t// MatrixOps.ts's symbolicToEntry() shows up as a wrong result rather than as\n\t// a matrix that silently believes it is symbolic.\n\tconst hasSymbolic = data.some(cell => typeof cell === \"object\" && cell !== null && \"kind\" in cell);\n\tconst m: MatrixData = { rows, cols, data, hasSymbolic };\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Matrix, m);\n\treturn new Value(ValueType.Matrix, m);\n}\n\n/** A 1×N row-vector Matrix, row-major and column-major storage are identical for a single row. */\nexport function rowVectorValue(data: readonly number[]): Value {\n\treturn matrixValue(1, data.length, data);\n}\n\n/** An N×1 column-vector Matrix, row-major and column-major storage are identical for a single column. */\nexport function colVectorValue(data: readonly number[]): Value {\n\treturn matrixValue(data.length, 1, data);\n}\n\n/** Create a Range value, a first-class integer range `min:max`, both bounds inclusive. */\nexport function rangeValue(min: number, max: number): Value {\n\tconst r: RangeData = { min, max };\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Range, r);\n\treturn new Value(ValueType.Range, r);\n}\n\n/**\n * Create a Colour value from canonical sRGB channels plus a display format.\n * Arena-backed like the other synchronous factories; the `ColourData` struct in\n * the `value` slot is immutable, so arena recycle is safe with no extra clearing\n * (matching {@link matrixValue}/{@link rangeValue}).\n */\nexport function colourValue(c: ColourData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Colour, c);\n\treturn new Value(ValueType.Colour, c);\n}\n\n/**\n * Create a Split value from its structured per-share payload. Arena-backed like\n * the other synchronous factories; the {@link SplitData} struct in the `value`\n * slot is immutable, so arena recycle is safe with no extra clearing (matching\n * {@link colourValue}/{@link rangeValue}).\n */\nexport function splitValue(data: SplitData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Split, data);\n\treturn new Value(ValueType.Split, data);\n}\n\n/** Create a Chart value from its specification. Arena-backed like the other\n * struct factories; the {@link ChartData} in the `value` slot is immutable, so\n * arena recycle is safe with no extra clearing. */\nexport function chartValue(data: ChartData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Chart, data);\n\treturn new Value(ValueType.Chart, data);\n}\n\n/** Create a Symbolic value, a free-variable algebraic expression tree (`symbolic/SymbolicNode.ts`'s `SymbolicNode`), not a concrete number. */\nexport function symbolicValue(node: SymbolicNode): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Symbolic, node);\n\treturn new Value(ValueType.Symbolic, node);\n}\n\n\n\n/** Create a Boolean-typed Value. */\nexport function boolValue(b: boolean): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Boolean, b);\n\treturn new Value(ValueType.Boolean, b);\n}\n\n/** Create a Datetime-typed Value (Unix timestamp in milliseconds). */\nexport function datetimeValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Datetime, n);\n\treturn new Value(ValueType.Datetime, n);\n}\n\n/** Create a Percentage-typed Value (stored as fraction, e.g. 0.5 for 50%). */\nexport function percentageValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Percentage, n);\n\treturn new Value(ValueType.Percentage, n);\n}\n\n/**\n * Create a Pending value, signals that an async result is not yet resolved.\n * The value field stores the queryKey string for deduplication and diagnostics.\n * Pending values should NEVER be stored in the arena (they persist across\n * scroll frames until resolution completes).\n */\nexport function pendingValue(queryKey: string): Value {\n\treturn new Value(ValueType.Pending, queryKey);\n}\n\n/**\n * Create an Error value, propagated through the DAG when a plugin raises an error.\n * The value field stores the EngineError code, unit stores the message.\n * Downstream consumers (lines that depend on errored data) bubble this up.\n * Should NEVER be stored in the arena.\n */\nexport function errorValue(code: string, message: string): Value {\n\treturn new Value(ValueType.Error, code, message);\n}\n\n/**\n * The first operand carrying a fault rather than a quantity, if any does.\n *\n * `Error` and `Pending` both read as the number 0 through {@link Value.toNumber},\n * by a convention that only holds up as long as nothing asks. Every opcode and\n * builtin that reaches for an operand's number without asking its type first\n * therefore computes with a zero it cannot tell apart from a real one, and\n * hands back an answer dressed in whatever type it was going to produce\n * anyway. That is how `(5 kg to m) to s` came to answer `0.00 s`: the failed\n * conversion is an Error, the second conversion read it as zero, and the unit\n * the reader asked for made the result look like a conversion that worked.\n *\n * Operands are checked left to right, matching evaluation order, and the\n * faulted Value is returned AS IT IS rather than replaced with a fresh one, so\n * the original code and message (or the pending query key) reach the caller\n * unchanged. `binaryOp` (vm/VMConversion.ts) and `OpCode.EXP` already did this\n * inline; this is the same rule for every other site, in one place so a site\n * added later can adopt it in a line.\n *\n * Three operands cover every call site in the VM (`MAT_INDEX2` and `MAT_SLICE`\n * are the widest). A variadic signature would allocate an arguments array on\n * paths that run per instruction; see {@link faultedIn} for the list case.\n *\n * @returns The faulted operand, or `null` when all of them carry a value.\n */\nexport function faultedOperand(a: Value, b?: Value, c?: Value): Value | null {\n\tif (a.type === ValueType.Error || a.type === ValueType.Pending) return a;\n\tif (b !== undefined && (b.type === ValueType.Error || b.type === ValueType.Pending)) return b;\n\tif (c !== undefined && (c.type === ValueType.Error || c.type === ValueType.Pending)) return c;\n\treturn null;\n}\n\n/**\n * {@link faultedOperand} over an already-built list, for the call sites that\n * have one (a builtin's arguments, a plugin function's).\n *\n * @returns The first faulted element, or `null` when every element carries a value.\n */\nexport function faultedIn(values: readonly Value[]): Value | null {\n\tfor (let i = 0; i < values.length; i++) {\n\t\tconst v = values[i];\n\t\tif (v.type === ValueType.Error || v.type === ValueType.Pending) return v;\n\t}\n\treturn null;\n}\n"]}
|