solve-engine 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/{PackageCompatibility-Bn5jnBtA.d.cts → PackageCompatibility-Cv7zjqSV.d.cts} +1 -1
  2. package/dist/{PackageCompatibility-CIvq2MP5.d.ts → PackageCompatibility-DBsZ0l2a.d.ts} +1 -1
  3. package/dist/{PackageRegistry-dpdurBVO.d.cts → PackageRegistry-BSGQ6saH.d.cts} +9 -2
  4. package/dist/{PackageRegistry-DzeiWcv4.d.ts → PackageRegistry-DRbqNJfI.d.ts} +9 -2
  5. package/dist/{ScopeManager-C2LDOrDx.d.ts → ScopeManager-DkpnlKuz.d.ts} +1 -1
  6. package/dist/{ScopeManager-D7uMXbhS.d.cts → ScopeManager-t6SnP6Ce.d.cts} +1 -1
  7. package/dist/{VMCheckpoints-I9jg3jWR.d.cts → VMCheckpoints-C_jQvABf.d.cts} +2 -2
  8. package/dist/{VMCheckpoints-CGyFhivM.d.ts → VMCheckpoints-CsHmQVaD.d.ts} +2 -2
  9. package/dist/{chunk-6KFVG6UY.cjs → chunk-2LFLR3VZ.cjs} +2 -2
  10. package/dist/chunk-2LFLR3VZ.cjs.map +1 -0
  11. package/dist/{chunk-LR4E4A4W.cjs → chunk-32GC2FHC.cjs} +2 -2
  12. package/dist/{chunk-LR4E4A4W.cjs.map → chunk-32GC2FHC.cjs.map} +1 -1
  13. package/dist/chunk-5FO4PDIG.js +2 -0
  14. package/dist/chunk-5FO4PDIG.js.map +1 -0
  15. package/dist/{chunk-WN5CMP4T.cjs → chunk-6C6IPUBH.cjs} +3 -3
  16. package/dist/chunk-6C6IPUBH.cjs.map +1 -0
  17. package/dist/{chunk-SZGK6RIP.cjs → chunk-7BXPCWKM.cjs} +2 -2
  18. package/dist/{chunk-SZGK6RIP.cjs.map → chunk-7BXPCWKM.cjs.map} +1 -1
  19. package/dist/chunk-7NXAZJDB.js +3 -0
  20. package/dist/chunk-7NXAZJDB.js.map +1 -0
  21. package/dist/{chunk-EYRBENHC.js → chunk-E2Q3PQ2G.js} +3 -3
  22. package/dist/{chunk-EYRBENHC.js.map → chunk-E2Q3PQ2G.js.map} +1 -1
  23. package/dist/{chunk-UI6IFGBT.js → chunk-G7TBEQRQ.js} +2 -2
  24. package/dist/chunk-G7TBEQRQ.js.map +1 -0
  25. package/dist/{chunk-L3FPQSGN.js → chunk-KVTOV3TZ.js} +2 -2
  26. package/dist/{chunk-L3FPQSGN.js.map → chunk-KVTOV3TZ.js.map} +1 -1
  27. package/dist/{chunk-SUXRZWH2.cjs → chunk-OVKDDTXO.cjs} +3 -3
  28. package/dist/{chunk-SUXRZWH2.cjs.map → chunk-OVKDDTXO.cjs.map} +1 -1
  29. package/dist/{chunk-6CY44ZPG.js → chunk-TN5E6JU6.js} +2 -2
  30. package/dist/{chunk-6CY44ZPG.js.map → chunk-TN5E6JU6.js.map} +1 -1
  31. package/dist/{chunk-4J7XZSZJ.cjs → chunk-U2UZJX5W.cjs} +4 -4
  32. package/dist/chunk-U2UZJX5W.cjs.map +1 -0
  33. package/dist/chunk-VAGS5JS7.cjs +2 -0
  34. package/dist/chunk-VAGS5JS7.cjs.map +1 -0
  35. package/dist/{chunk-UDQ57ZRX.cjs → chunk-X3R7B7XM.cjs} +2 -2
  36. package/dist/{chunk-UDQ57ZRX.cjs.map → chunk-X3R7B7XM.cjs.map} +1 -1
  37. package/dist/{chunk-GOIQYUWV.js → chunk-YAHGSBMC.js} +2 -2
  38. package/dist/{chunk-GOIQYUWV.js.map → chunk-YAHGSBMC.js.map} +1 -1
  39. package/dist/{chunk-XR7HEC7B.js → chunk-YU3PACLE.js} +4 -4
  40. package/dist/chunk-YU3PACLE.js.map +1 -0
  41. package/dist/constants.cjs +1 -1
  42. package/dist/constants.js +1 -1
  43. package/dist/engine.cjs +1 -1
  44. package/dist/engine.d.cts +48 -5
  45. package/dist/engine.d.ts +48 -5
  46. package/dist/engine.js +1 -1
  47. package/dist/index.cjs +1 -1
  48. package/dist/index.d.cts +4 -4
  49. package/dist/index.d.ts +4 -4
  50. package/dist/index.js +1 -1
  51. package/dist/language.d.cts +3 -3
  52. package/dist/language.d.ts +3 -3
  53. package/dist/lexer.cjs +1 -1
  54. package/dist/lexer.js +1 -1
  55. package/dist/normalizer.cjs +1 -1
  56. package/dist/normalizer.js +1 -1
  57. package/dist/packages.cjs +1 -1
  58. package/dist/packages.d.cts +2 -2
  59. package/dist/packages.d.ts +2 -2
  60. package/dist/packages.js +1 -1
  61. package/dist/testing.cjs +2 -2
  62. package/dist/testing.d.cts +3 -3
  63. package/dist/testing.d.ts +3 -3
  64. package/dist/testing.js +1 -1
  65. package/dist/vm.d.cts +3 -3
  66. package/dist/vm.d.ts +3 -3
  67. package/dist/worker.cjs +2 -2
  68. package/dist/worker.d.cts +2 -2
  69. package/dist/worker.d.ts +2 -2
  70. package/dist/worker.js +1 -1
  71. package/package.json +1 -1
  72. package/dist/chunk-4J7XZSZJ.cjs.map +0 -1
  73. package/dist/chunk-6KFVG6UY.cjs.map +0 -1
  74. package/dist/chunk-APN442VD.cjs +0 -2
  75. package/dist/chunk-APN442VD.cjs.map +0 -1
  76. package/dist/chunk-JSPKKNPQ.js +0 -3
  77. package/dist/chunk-JSPKKNPQ.js.map +0 -1
  78. package/dist/chunk-QXQE7X4S.js +0 -2
  79. package/dist/chunk-QXQE7X4S.js.map +0 -1
  80. package/dist/chunk-UI6IFGBT.js.map +0 -1
  81. package/dist/chunk-WN5CMP4T.cjs.map +0 -1
  82. package/dist/chunk-XR7HEC7B.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lexer/ExpressionLexer.ts"],"names":["registerAllTokenTypes","buildCharClassTable","table","i","isUnicodeSpace","cc","LexerToken","type","typeId","value","text","offset","lineBreaks","line","col","sourceEnd","TWO_CHAR_OPS","OP_MAP","EXPRESSION_INDICATOR_CODES","set","opCodes","c","_ExpressionLexer","localeCode","lookup","getLocale","k","v","knownUnits","rule","m","tokenTypeId","plugin","keyword","tokenType","lower","ErrorFactory","chars","first","second","builtInSecondMap","inner","unit","toRemove","r","input","results","docLen","lineStart","lineEnd","lineNumber","classification","lineText","tokens","rawToken","savedLen","inlineSolves","charSpans","span","nlChar","len","tokenIndex","openSpan","collectedSpans","c0","identLower","kwType","opType","token","pos","start","startCol","next","hasIntPart","d1","d2","d3","d4","isGroupOfExactlyThree","hasDecimal","nextCc","hasExponent","ec","identText","fullText","localeKwType","lookPos","parenPos","isWord","ch","isAlpha","wordEnd","hasAlpha","word","keywordType","c1","secondMap","twoCharType","commentPos","pluginInner","pluginType","end","indicatorCodes","from","after","hashPos","p","n","hasInline","idx","hashCount","count","trailPos","digitPos","tPos","tc","closePos","trail","onlySkippable","code","savedInput","savedPos","result","sPos","exprStart","exprEnd","expression","hexEnd","tagEnd","name","ExpressionLexer"],"mappings":"yNAOAA,mBAAAA,EAAsB,CA8GtB,SAASC,CAAAA,EAAkC,CACzC,IAAMC,CAAAA,CAAQ,IAAI,UAAA,CAAW,GAAG,EAGhC,IAAA,IAASC,CAAAA,CAAI,EAAA,CAAIA,CAAAA,EAAK,GAAIA,CAAAA,EAAAA,CAAKD,CAAAA,CAAMC,CAAC,CAAA,CAAI,EAG1C,IAAA,IAASA,CAAAA,CAAI,EAAA,CAAIA,CAAAA,EAAK,GAAIA,CAAAA,EAAAA,CAAKD,CAAAA,CAAMC,CAAC,CAAA,CAAI,EAG1C,IAAA,IAASA,CAAAA,CAAI,EAAA,CAAIA,CAAAA,EAAK,IAAKA,CAAAA,EAAAA,CAAKD,CAAAA,CAAMC,CAAC,CAAA,CAAI,EAG3C,OAAAD,CAAAA,CAAM,EAAE,CAAA,CAAI,EAGZA,CAAAA,CAAM,EAAE,CAAA,CAAI,CAAA,CAGZA,EAAM,EAAE,CAAA,CAAI,CAAA,CACZA,CAAAA,CAAM,CAAC,CAAA,CAAK,CAAA,CACZA,CAAAA,CAAM,EAAE,EAAI,CA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A,GAAO,EAAA,EAAMA,IAAO,EAAA,CAAI,MAC5BK,CAAAA,GACF,CAEA,IAAM3D,CAAAA,CAAOmC,CAAAA,CAAM,KAAA,CAAMyB,CAAAA,CAAOD,CAAG,CAAA,CACnC,OAAA,IAAA,CAAK,GAAA,CAAMA,CAAAA,CACJ,IAAI/D,CAAAA,CAAW,SAAA,CAAWyB,mBAAAA,CAAY,SAAS,EAAGrB,CAAAA,CAAMA,CAAAA,CAAM4D,CAAAA,CAAO,CAAA,CAAG,KAAK,IAAA,CAAMC,CAAQ,CACpG,CACF,EAhrDajD,CAAAA,CACa,UAAA,CAAarB,CAAAA,EAAoB,KAD9CiI,CAAAA,CAAN5G","file":"chunk-6KFVG6UY.cjs","sourcesContent":["import { Token, tokenTypeId, registerAllTokenTypes } from '@solve-js/lexer/Token';\nimport { knownUnits } from '@solve-js/lexer/units';\nimport { getLocale, type ILocale } from '@solve-js/constants/locales';\nimport { ErrorFactory } from '@solve-js/errors/UnifiedErrorFramework';\nimport type { TokenLookup } from '@solve-js/lexer/TokenClassRegistry';\n\n// Bootstrap all token types at module load\nregisterAllTokenTypes();\n\n// ── Markdown line classification (Phase B) ──────────────────────────────\n\n/** What a line is, structurally, before anything tries to evaluate it. */\nexport type MarkdownLineType =\n | 'expression'\n | 'prose'\n | 'heading'\n | 'blockquote'\n | 'list'\n | 'code_fence'\n | 'math_fence'\n | 'table'\n | 'table_separator'\n | 'hr'\n | 'wikilink'\n | 'comment'\n | 'empty';\n\n/**\n * What a line is and whether it holds anything to evaluate.\n *\n * Produced by a character-level scan that never consults the keyword, unit or\n * operator tables, so any lexer gives the same answer for the same line. See\n * `__tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts`.\n */\nexport interface LineClassification {\n /** The type of this markdown line */\n type: MarkdownLineType;\n /** Whether this line should be skipped (no expression evaluation) */\n skip: boolean;\n /** Whether the line contains inline solve markers (`s`...``) */\n hasInlineSolve: boolean;\n /**\n * Offset of the first evaluable character, when structural markup precedes\n * it. Absolute, in the same coordinates the classification was asked for,\n * and absent when the whole line is evaluable.\n *\n * A list marker is markup, not arithmetic. `- 100 + 20` is a bullet holding\n * `100 + 20`, but `-` is also a prefix operator, so without this the line\n * evaluated as negative one hundred and answered -80: a wrong answer that\n * looks like a right one. `*` and `+` in the same position could not even do\n * that, one erroring and the other correct by luck, so the three markers\n * disagreed with each other about the same document.\n *\n * Consumers must slice both the text and the token stream from here, or the\n * two describe different lines.\n */\n contentOffset?: number;\n}\n\n/** Inline solve position with precise coordinates */\nexport interface InlineSolveSpan {\n /** Character offset of the `s`` marker */\n start: number;\n /** Character offset past the closing `` ` `` */\n end: number;\n /** The expression text between the backticks */\n expression: string;\n /** 1-based column of the `s`` marker */\n columnNumber: number;\n /** Token index of INLINE_SOLVE_START in the line's token array (set during tokenization). */\n startTokenIndex?: number;\n /** Token index of closing BACKTICK_OPEN in the line's token array (set during tokenization). */\n endTokenIndex?: number;\n}\n\n/**\n * Result from a single line processed by scanDocument().\n * Combines line classification, tokenized tokens, and inline solve spans\n * into a single structure, eliminating the need for separate classifyLine()\n * findInlineSolves(), and per-line Lexer.reset() calls.\n */\nexport interface ScanLineResult {\n /** The raw line text (without trailing newline). */\n text: string;\n /** 1-based line number within the document. */\n lineNumber: number;\n /** Character offset of the line start within the document. */\n startOffset: number;\n /** Character offset of the line end (before newline). */\n endOffset: number;\n /** The line classification. */\n classification: LineClassification;\n /** Tokenized tokens (empty array if line is skipped). */\n tokens: Token[];\n /** Inline solve spans found in this line (empty if none). */\n inlineSolves: InlineSolveSpan[];\n}\n\n// ── Character class constants ─────────────────────────────────────────────\n// Used as the result of the CHAR_CLASS lookup table. V8 compiles the\n// outer switch on these small integer constants into a jump table.\nconst enum CharClass {\n SKIP = 0, // Invalid / control / unicode fallback\n WHITESPACE = 1, // space, tab, \\n, \\r\n DIGIT = 2, // 0-9\n ALPHA = 3, // a-z, A-Z, _\n DOT = 4, // . (could be decimal point or DOT token)\n OPERATOR = 5, // + - * / ^ % ( ) [ ] { } , : ; = ? & | ~ ! < >\n QUOTE = 6, // \"\n HASH = 7, // # (comment)\n DOLLAR = 8, // $\n POUND = 9, // £ (U+00A3)\n EURO = 10, // € (U+20AC)\n BACKTICK = 11, // `\n}\n\n// ── Static character class table (built once at module load) ──────────────\nfunction buildCharClassTable(): Uint8Array {\n const table = new Uint8Array(128);\n\n // Digits 0-9\n for (let i = 48; i <= 57; i++) table[i] = CharClass.DIGIT;\n\n // Uppercase A-Z\n for (let i = 65; i <= 90; i++) table[i] = CharClass.ALPHA;\n\n // Lowercase a-z\n for (let i = 97; i <= 122; i++) table[i] = CharClass.ALPHA;\n\n // Underscore\n table[95] = CharClass.ALPHA;\n\n // Dot\n table[46] = CharClass.DOT;\n\n // Whitespace\n table[32] = CharClass.WHITESPACE; // space\n table[9] = CharClass.WHITESPACE; // tab\n table[10] = CharClass.WHITESPACE; // \\n\n table[13] = CharClass.WHITESPACE; // \\r\n\n // Operators / punctuation\n table[33] = CharClass.OPERATOR; // !\n table[37] = CharClass.OPERATOR; // %\n table[38] = CharClass.OPERATOR; // &\n table[40] = CharClass.OPERATOR; // (\n table[41] = CharClass.OPERATOR; // )\n table[42] = CharClass.OPERATOR; // *\n table[43] = CharClass.OPERATOR; // +\n table[44] = CharClass.OPERATOR; // ,\n table[45] = CharClass.OPERATOR; // -\n table[47] = CharClass.OPERATOR; // /\n table[58] = CharClass.OPERATOR; // :\n table[59] = CharClass.OPERATOR; // ;\n table[60] = CharClass.OPERATOR; // <\n table[61] = CharClass.OPERATOR; // =\n table[62] = CharClass.OPERATOR; // >\n table[63] = CharClass.OPERATOR; // ?\n table[91] = CharClass.OPERATOR; // [\n table[93] = CharClass.OPERATOR; // ]\n table[94] = CharClass.OPERATOR; // ^\n table[123] = CharClass.OPERATOR; // {\n table[124] = CharClass.OPERATOR; // |\n table[125] = CharClass.OPERATOR; // }\n table[126] = CharClass.OPERATOR; // ~\n // \"@\" was previously unclassified (defaulted to CharClass.SKIP, silently\n // dropped before ever reaching OP_MAP). See OP_MAP's own \"@\" entry doc\n // comment for why this is being activated now.\n table[64] = CharClass.OPERATOR; // @\n\n // Other\n table[34] = CharClass.QUOTE; // \"\n table[35] = CharClass.HASH; // #\n table[36] = CharClass.DOLLAR; // $\n table[96] = CharClass.BACKTICK; // `\n\n return table;\n}\n\n/**\n * Whether a non-ASCII code point separates tokens rather than joining them.\n *\n * The CHAR_CLASS table above is 128 entries wide, so every code point past\n * ASCII falls through to one branch that reads it as part of an identifier.\n * That is right for `café`, `日本語` and emoji, and wrong for the dozen or so\n * code points that are whitespace without being ASCII whitespace. Without this,\n * a no-break space between two operands JOINED them: `1<NBSP>+<NBSP>1` lexed as\n * one identifier and reported \"Undefined variable: 1 + 1\", and a byte-order\n * mark at the head of a file did the same to its first line. Both arrive\n * constantly in pasted text, from a web page, a word processor, a spreadsheet\n * export, or a Windows editor that writes a BOM.\n *\n * The zero-width JOINERS are deliberately absent. U+200D is what holds a family\n * emoji together as one grapheme, and U+200C is its non-joining partner; both\n * bind their neighbours rather than separating them, so they stay identifier\n * characters. U+200B, the zero-width SPACE, is a separator despite being\n * invisible, which is exactly why it is worth handling: it is unreadable on\n * screen and would otherwise silently break the line it lands in.\n *\n * @param cc - A UTF-16 code unit, only meaningful for values >= 128.\n * @returns True when the character should be skipped like a space.\n */\nfunction isUnicodeSpace(cc: number): boolean {\n return (\n cc === 0x0085 || // NEL, next line\n cc === 0x00A0 || // no-break space\n cc === 0x1680 || // ogham space mark\n (cc >= 0x2000 && cc <= 0x200A) || // en quad through hair space, incl. figure/thin space\n cc === 0x200B || // zero-width space\n cc === 0x2028 || // line separator\n cc === 0x2029 || // paragraph separator\n cc === 0x202F || // narrow no-break space\n cc === 0x205F || // medium mathematical space\n cc === 0x3000 || // ideographic space\n cc === 0xFEFF // byte-order mark / zero-width no-break space\n );\n}\n\n// ── Monomorphic Token class ───────────────────────────────────────────────\n// V8 assigns a single stable HiddenClass because all properties are\n// initialized in the constructor and never added/removed afterwards.\n// This enables fast property access (inline cache hits) and allows\n// allocation in V8's nursery (cheap GC).\n// All 9 fields are always set, no optional fields, no different shapes.\n/**\n * A token, as the lexer produces it.\n *\n * A class rather than an object literal because tokens are created on every\n * keystroke and a shared hidden class keeps that path predictable for the\n * engine running it.\n */\nexport class LexerToken implements Token {\n constructor(\n public type: string,\n public typeId: number,\n public value: string,\n public text: string,\n public offset: number,\n public lineBreaks: number,\n public line: number,\n public col: number,\n /** See {@link Token.sourceEnd}. Set only on normalizer-fused tokens. */\n public sourceEnd?: number,\n ) {}\n}\n\n// ── Two-character operator lookup ─────────────────────────────────────────\n// Maps first-char → (second-char → token type). Used for operators like\n// ==, !=, >=, <=, **, <<, >>.\ninterface TwoCharOpMap {\n [firstChar: number]: { [secondChar: number]: string };\n}\nconst TWO_CHAR_OPS: TwoCharOpMap = {\n 61: { 61: 'EQUALITY', 62: 'THEREFORE' }, // ==, => (opposite char order from >='s GTE below — no collision)\n 33: { 61: 'NEQ' }, // !=\n 62: { 61: 'GTE' }, // >=\n 60: { 61: 'LTE' }, // <=\n 38: { 38: 'LOGICAL_AND' }, // &&\n 124: { 124: 'LOGICAL_OR' }, // ||\n 43: { 61: 'PLUS_EQUALS' }, // += (compound assignment, running totals)\n 45: { 61: 'MINUS_EQUALS' }, // -= (neither + nor - had a two-char op before)\n // Note: ** is NOT a single token, the existing moo lexer emits two\n // separate STAR tokens, and the parser consumes them that way.\n // 42: { 42: 'EXPONENT' }, // **, disabled for moo compatibility\n};\n// Note: LSHIFT (<<) and RSHIFT (>>) are handled separately because\n// 60 is also used for LTE, so we check LTE first then LSHIFT.\n\n// ── Single-character operator lookup ──────────────────────────────────────\nconst OP_MAP: Record<number, string> = {\n 43: 'PLUS', // +\n 45: 'MINUS', // -\n 42: 'STAR', // *\n 47: 'SLASH', // /\n 94: 'CARET', // ^\n 37: 'PERCENT', // %\n 40: 'LPAREN', // (\n 41: 'RPAREN', // )\n 91: 'LBRACKET', // [\n 93: 'RBRACKET', // ]\n 123: 'LBRACE', // {\n 125: 'RBRACE', // }\n 44: 'COMMA', // ,\n 58: 'COLON', // :\n 59: 'SEMICOLON',// ;\n 61: 'EQUALS', // =\n 63: 'QUESTION', // ?\n 33: 'BANG', // !\n 38: 'BIT_AND', // &\n 124: 'BIT_OR', // |\n 60: 'LT', // <\n 62: 'GT', // >\n 126: 'BIT_NOT', // ~\n // \"@\", activates the token type name already dormant-reserved for this\n // exact purpose (see Token.ts's OVER/RATE_AT doc comment and\n // normalizer/TokenNormalizer.ts's NON_WORD_NAMES, both of which already\n // anticipated \"AT\" as a future \"@\" symbol token before this addition).\n // Backs the time package's video-timecode literal's alternate fps\n // separator (`01:02:03:04 @ 30fps`, equivalent to `... at 30fps`). See\n // packages/time/parselets/VideoTimecodeParselet.ts.\n 64: 'AT', // @\n};\n\n/**\n * Plugin interface for extending the ExpressionLexer with custom tokens.\n *\n * Plugins can register:\n * - `keywords`: Map identifier strings to custom token types (checked after locale keywords).\n * - `operators`: Map multi-character operator sequences to custom token types.\n * - `units`: Register additional unit identifiers (checked alongside built-in units).\n *\n * Multi-word phrase matching has been moved to the TokenNormalizer post-lexer\n * stage. To register phrase patterns, use `IEnginePackage.normalizerRules` instead.\n *\n * All registrations are additive, built-in patterns still work.\n */\nexport interface LexerVocabulary {\n /**\n * Keyword → tokenType mappings. Each key is a lowercase identifier that,\n * when encountered, will emit the specified token type instead of IDENT.\n * These are checked AFTER the locale's built-in keywordMap, so locale\n * keywords take priority.\n */\n keywords?: Record<string, string>;\n\n /**\n * Multi-character operator → tokenType mappings. Each key is the exact\n * character sequence (e.g., \"::\", \"->\", \"=>\") and the value is the token\n * type to emit. Two-character operators take priority during matching.\n * Built-in operators (==, !=, >=, <=, <<, >>) always take priority.\n */\n operators?: Record<string, string>;\n\n /**\n * Additional unit identifiers to recognize (e.g., \"gp\", \"osrs\", \"tile\").\n * These are checked alongside the built-in `knownUnits` set.\n */\n units?: string[];\n\n /**\n * Whole-line patterns matched against the RAW line text, BEFORE any\n * per-character tokenization begins.\n *\n * Every other extension point in this file (`keywords`/`operators`/\n * `units`, plus `IEnginePackage.phrases`/`normalizerRules`) transforms\n * a token STREAM -- they all assume the line is, at some granularity,\n * valid Solve syntax. This hook exists for the one shape that isn't:\n * a package whose grammar captures arbitrary free-form text terminated\n * by a fixed marker (e.g. a natural-language query ending in `= ?`),\n * where the text itself (\"distance to the moon\") would never tokenize\n * or parse as a normal expression and must be captured verbatim\n * instead -- see `packages/knowledge/` for the reference use.\n *\n * Each entry's `pattern` is tested (via `RegExp.exec`) against the\n * full, untrimmed line text. If it matches AND capture group 1 is\n * non-empty after trimming, the ENTIRE line becomes a single\n * synthetic token of `tokenType` whose `value`/`text` is the trimmed\n * capture group -- the character-by-character scanner never runs for\n * that line. Patterns are tried in registration order; the first\n * match wins. A package registering a rule here still needs a\n * `prefixParselets` entry for `tokenType` to actually consume the\n * resulting token.\n *\n * Because this bypasses tokenization entirely, a matching line can\n * contain characters that would otherwise be lexer errors (unmatched\n * quotes, stray symbols, ...) -- by design, since the whole point is\n * to hand the package raw text the normal pipeline was never meant to\n * parse.\n */\n rawLinePatterns?: Array<{ pattern: RegExp; tokenType: string }>;\n}\n\n// ── Expression gating (L1) ──────────────────────────────────────────────\n// Pre-computed Set of character codes that indicate an expression might\n// be present. Used by hasExpressionIndicators() to gate prose lines\n// before full tokenization.\n//\n// NOTE: Currently unused, L1 prose gating was removed from classifyFromPositions()\n// because it incorrectly skipped keyword-only lines (\"pi\"), single identifiers\n// (\"hello\"), and short alpha lines. Retained for future re-implementation with\n// keyword-awareness and proper test coverage.\nconst EXPRESSION_INDICATOR_CODES = (() => {\n const set = new Set<number>();\n // Digits 0-9\n for (let i = 48; i <= 57; i++) set.add(i);\n // Operators / punctuation\n // Note: colon (58) is intentionally excluded, it's common in prose\n // (e.g., \"Subject: Hello world\") and would cause false-positive\n // expression classification. Variable assignment lines like\n // \":myVar = 5\" are still caught by '=' and digit indicators.\n const opCodes = [43, 45, 42, 47, 94, 37, 40, 41, 91, 93, 123, 125, 61, 60, 62, 33, 38, 124, 126, 59, 63];\n for (const c of opCodes) set.add(c);\n // Currency\n set.add(36); // $\n set.add(0x00A3); // £\n set.add(0x20AC); // €\n set.add(0x00A5); // ¥\n set.add(0x20BD); // ₽\n set.add(0x20A9); // ₩\n // Backtick (inline solve)\n set.add(96); // `\n // Dot (could be decimal)\n set.add(46); // .\n // Hash (comment, still an expression indicator)\n set.add(35); // #\n return set;\n})();\n\n// ── ExpressionLexer ───────────────────────────────────────────────────────\n/**\n * Character-by-character tokenizer for expression text.\n *\n * Scans a raw line/expression string into a stream of typed tokens\n * (numbers, identifiers, operators, units, keywords, ...), handling\n * markdown-line classification (`classifyLine`), inline `` s`...` `` solve\n * spans, and package-contributed vocabulary (registered via\n * {@link registerVocabulary}/{@link unregisterVocabulary}, keywords\n * operators, and units a package wants recognized as their own token\n * types rather than falling through to generic identifiers).\n *\n * Most consumers should use the higher-level {@link Lexer} wrapper, which\n * adds streaming `next()`/`peek()` access over this class's scan results.\n */\nexport class ExpressionLexer {\n private static readonly CHAR_CLASS = buildCharClassTable();\n /**\n * Configured TokenLookup from TokenClassRegistry. When set, replaces\n * the internal keyword map and unit set with registry-built equivalents.\n * Enables data-driven keyword/unit registration across locale keywords,\n * provider keywords, and plugins.\n *\n * Set at construction time via the constructor parameter. Plugin-registered\n * keywords/units (via registerVocabulary()) are checked alongside\n * the configuredLookup, neither source is bypassed.\n */\tprivate configuredLookup: TokenLookup | null = null;\n\n\t// Instance state\n private input: string = '';\n private pos: number = 0;\n private len: number = 0;\n\n // Line / column tracking (1-indexed)\n private line: number = 1;\n private lineStartPos: number = 0;\n\n // Open-bracket context stack for the current line, one entry per unclosed\n // `(`/`[`, `true` when a comma inside it is a separator rather than a\n // thousands group. A `[` (vector/matrix) and a CALL `(` (`rgb(255,255,255)`,\n // preceded by an identifier) are separator contexts; a bare GROUPING `(`\n // (`(1,000)`, preceded by an operator or the line start) is not, so a\n // parenthesised thousands number still reads as one scalar. The number scanner\n // consults the innermost entry. Tracked here because the flat token stream\n // carries no nesting otherwise; reset per line, so an unbalanced bracket\n // cannot bleed the decision into the next.\n private groupingStack: boolean[] = [];\n\n // Keyword map: lowercase identifier → token type (locale keywords only)\n private keywordMap: Map<string, string>;\n\n // ── Merged lookup collections (keywordMap + pluginKeywordMap, knownUnits + pluginUnits)\n private mergedKeywords: Map<string, string>;\n private mergedUnits: Set<string>;\n\n // Plugin-extensible keyword map (merged with locale keywordMap)\n private pluginKeywordMap: Map<string, string> = new Map();\n\n // Plugin-extensible two-char operators: firstChar → (secondChar → tokenType)\n private pluginOperators: Map<number, Map<number, string>> = new Map();\n\n // Plugin-extensible units (merged with knownUnits)\n private pluginUnits: Set<string> = new Set();\t// Fast-path guards: skip plugin lookups entirely when no plugins registered\n\tprivate hasPluginOps = false;\n\n // Locale for function-identifier lookups\n private localeCode: string;\n private locale: ILocale;\n\n /**\n * Inline solve spans collected during the most recent tokenization pass.\n * Populated by [Symbol.iterator]() and consumed by scanDocument().\n */\n _inlineSolveSpans: InlineSolveSpan[] = [];\n\n // Plugin-extensible raw-line patterns. See LexerVocabulary.rawLinePatterns.\n private pluginRawLinePatterns: Array<{ pattern: RegExp; tokenType: string }> = [];\n\n /**\n * If a `rawLinePatterns` rule matches the FULL text most recently passed\n * to {@link reset}, this holds the single synthetic token that\n * {@link tokenizeAll} should return instead of running the\n * character-by-character scanner. Cleared (re-evaluated) on every\n * {@link reset} call. `null` when no plugin registered any raw-line\n * patterns, or none matched, the overwhelmingly common case, checked\n * with a `length === 0` guard before ever touching this field so a\n * plugin-free lexer pays zero cost for the feature.\n */\n private pendingRawLineToken: Token | null = null;\n\n /**\n * Test `text` against every registered `rawLinePatterns` rule, in\n * registration order. Returns a synthetic token for the first rule\n * whose `pattern` matches AND whose capture group 1 is non-empty after\n * trimming; returns `null` if no rule matches (the normal\n * character-by-character scanner should run instead).\n */\n private matchRawLine(text: string): Token | null {\n for (const rule of this.pluginRawLinePatterns) {\n const m = rule.pattern.exec(text);\n if (m && typeof m[1] === 'string') {\n const value = m[1].trim();\n if (value.length > 0) {\n return new LexerToken(rule.tokenType, tokenTypeId(rule.tokenType), value, value, 0, 0, this.line, 1);\n }\n }\n }\n return null;\n }\n\n /** Rebuild merged keyword and unit collections after plugin registration. */\n private rebuildMergedCollections(): void {\n this.mergedKeywords = new Map([...this.keywordMap, ...this.pluginKeywordMap]);\n this.mergedUnits = new Set([...knownUnits, ...this.pluginUnits]);\n }\n\n constructor(localeCode = 'en', lookup?: TokenLookup) {\n this.localeCode = localeCode;\n this.locale = getLocale(localeCode);\n this.configuredLookup = lookup ?? null;\n this.keywordMap = new Map<string, string>();\n for (const [k, v] of Object.entries(this.locale.keywordMap)) {\n this.keywordMap.set(k.toLowerCase(), v);\n }\n this.mergedKeywords = new Map(this.keywordMap);\n this.mergedUnits = new Set(knownUnits);\n }\n\n /**\n * Register a plugin to extend the lexer with custom tokens.\n *\n * All registrations are additive, built-in patterns still work.\n * Keywords, operators, and units from the plugin are merged\n * with existing ones. Calling multiple times adds more entries.\n *\n * Note: multi-word phrases are now handled by the TokenNormalizer\n * (see `IEnginePackage.normalizerRules`), not the lexer.\n *\n * Built-in tokens CANNOT be overridden. Throws a EngineError if the\n * plugin attempts to register a keyword, operator, or unit\n * that conflicts with a built-in one.\n */\n registerVocabulary(plugin: LexerVocabulary): void {\n if (plugin.keywords) {\n for (const [keyword, tokenType] of Object.entries(plugin.keywords)) {\n const lower = keyword.toLowerCase();\n // Guard: prevent overriding built-in locale keywords\n if (this.keywordMap.has(lower)) {\n throw ErrorFactory.config(\n 'PLUGIN_KEYWORD_COLLISION',\n `Plugin keyword \"${keyword}\" conflicts with built-in keyword ` +\n `(type: ${this.keywordMap.get(lower)}). Built-in keywords cannot be overridden.`,\n { keyword, builtinType: this.keywordMap.get(lower) }\n );\n }\n this.pluginKeywordMap.set(lower, tokenType);\n }\n this.rebuildMergedCollections();\n }\n\n if (plugin.operators) {\n this.hasPluginOps = true;\n for (const [chars, tokenType] of Object.entries(plugin.operators)) {\n // Only support 2-char operators for the fast path\n if (chars.length === 2) {\n const first = chars.charCodeAt(0);\n const second = chars.charCodeAt(1);\n\n // Guard: prevent overriding built-in two-char operators (==, !=, >=, <=)\n const builtInSecondMap = TWO_CHAR_OPS[first];\n if (builtInSecondMap && builtInSecondMap[second] !== undefined) {\n throw ErrorFactory.config(\n 'PLUGIN_OPERATOR_COLLISION',\n `Plugin operator \"${chars}\" conflicts with built-in operator ` +\n `(type: ${builtInSecondMap[second]}). Built-in operators cannot be overridden.`,\n { operator: chars, builtinType: builtInSecondMap[second] }\n );\n }\n // Guard: prevent overriding LSHIFT (<<) and RSHIFT (>>)\n if (first === 60 && second === 60) {\n throw ErrorFactory.config(\n 'PLUGIN_OPERATOR_COLLISION',\n `Plugin operator \"${chars}\" conflicts with built-in operator ` +\n `(type: LSHIFT). Built-in operators cannot be overridden.`,\n { operator: chars, builtinType: 'LSHIFT' }\n );\n }\n if (first === 62 && second === 62) {\n throw ErrorFactory.config(\n 'PLUGIN_OPERATOR_COLLISION',\n `Plugin operator \"${chars}\" conflicts with built-in operator ` +\n `(type: RSHIFT). Built-in operators cannot be overridden.`,\n { operator: chars, builtinType: 'RSHIFT' }\n );\n }\n // Guard: prevent overriding comment sequences (//)\n if (first === 47 && second === 47) {\n throw ErrorFactory.config(\n 'PLUGIN_OPERATOR_COLLISION',\n `Plugin operator \"${chars}\" conflicts with built-in comment sequence. ` +\n `Comment sequences cannot be overridden.`,\n { operator: chars, builtinType: 'COMMENT' }\n );\n }\n\n let inner = this.pluginOperators.get(first);\n if (!inner) {\n inner = new Map();\n this.pluginOperators.set(first, inner);\n }\n inner.set(second, tokenType);\n }\n }\n }\n\n if (plugin.units) {\n for (const unit of plugin.units) {\n // Guard: prevent overriding built-in units\n if (knownUnits.has(unit)) {\n throw ErrorFactory.config(\n 'PLUGIN_UNIT_COLLISION',\n `Plugin unit \"${unit}\" conflicts with a built-in unit. ` +\n `Built-in units cannot be overridden.`,\n { unit }\n );\n }\n this.pluginUnits.add(unit);\n }\n this.rebuildMergedCollections();\n }\n\n if (plugin.rawLinePatterns) {\n this.pluginRawLinePatterns.push(...plugin.rawLinePatterns);\n }\n }\n\n /**\n * Unregister a plugin, removing its custom tokens from the lexer.\n *\n * This is the inverse of registerVocabulary(). All keywords, operators,\n * and units registered by the plugin are removed. After\n * unregistration, those tokens will revert to their default behavior\n * (e.g., keywords become IDENT, operators become ERROR).\n *\n * Calling unregisterVocabulary with a plugin that was never registered\n * is safe, it simply has no effect.\n */\n unregisterVocabulary(plugin: LexerVocabulary): void {\n if (plugin.keywords) {\n for (const keyword of Object.keys(plugin.keywords)) {\n this.pluginKeywordMap.delete(keyword.toLowerCase());\n }\n \n this.rebuildMergedCollections();\n }\n\n if (plugin.operators) {\n for (const chars of Object.keys(plugin.operators)) {\n if (chars.length === 2) {\n const first = chars.charCodeAt(0);\n const second = chars.charCodeAt(1);\n const inner = this.pluginOperators.get(first);\n if (inner) {\n inner.delete(second);\n if (inner.size === 0) {\n this.pluginOperators.delete(first);\n }\n }\n }\n }\n this.hasPluginOps = this.pluginOperators.size > 0;\n }\n\n if (plugin.units) {\n for (const unit of plugin.units) {\n this.pluginUnits.delete(unit);\n }\n \n this.rebuildMergedCollections();\n }\n\n if (plugin.rawLinePatterns) {\n const toRemove = new Set(plugin.rawLinePatterns);\n this.pluginRawLinePatterns = this.pluginRawLinePatterns.filter((r) => !toRemove.has(r));\n }\n }\n\n reset(input: string): void {\n this.input = input;\n this.pos = 0;\n this.len = input.length;\n this.line = 1;\n this.lineStartPos = 0;\n this.pendingRawLineToken = this.pluginRawLinePatterns.length > 0 ? this.matchRawLine(input) : null;\n }\n\n /**\n * Scan a full document text in a single pass, classifying each line and\n * tokenizing non-skipped lines.\n *\n * Replaces the separate classifyLine() + findInlineSolves() + per-line\n * reset() + tokenizeAll() pattern with a single character-by-character\n * walk through the entire document. Key benefits:\n *\n * - **Single reset()**: `this.pos`, `this.len`, `this.line`, and\n * `this.lineStartPos` are set once for the whole document, not per-line.\n * - **Single classification**: classifyLine() runs once per line inline;\n * skipped lines are jumped over without tokenization.\n * - **Shared tokenization**: Non-skipped lines are tokenized using the\n * existing state machine, yielding Token[] without per-line reset().\n * - **Inline solve detection**: findInlineSolves() is called only for\n * lines that classifyLine() marks as having inline solves.\n *\n * Tokenization is scoped to each line by temporarily restricting\n * `this.len` to the line end position, so the [Symbol.iterator]\n * generator naturally stops at the line boundary. After tokenization,\n * `this.len` is restored and `this.pos` advances past the newline.\n *\n * @param text The full document text (with newlines).\n * @returns Array of ScanLineResult, one per line, in document order.\n */\n scanDocument(text: string): ScanLineResult[] {\n this.input = text;\n this.pos = 0;\n this.len = text.length;\n this.line = 1;\n this.lineStartPos = 0;\n\n const results: ScanLineResult[] = [];\n const input = this.input;\n const docLen = this.len;\n\n while (this.pos < docLen) {\n const lineStart = this.pos;\n\n // ── Find end of current line (newline boundary) ───────────────\n let lineEnd = this.pos;\n while (lineEnd < docLen) {\n const cc = input.charCodeAt(lineEnd);\n if (cc === 10 || cc === 13) break; // \\n or \\r\n lineEnd++;\n }\n\n const lineNumber = this.line;\n\n // ── Classify the line ─────────────────────────────────────────\n // Uses classifyFromPositions() to read from this.input directly\n // avoids allocating a substring and keeps classification reads\n // within the same memory region as tokenization.\n const classification = this.classifyFromPositions(lineStart, lineEnd);\n\n // ── Slice line text for ScanLineResult.text ────────────────\n // Hoisted above tokenization (rather than after, as originally) so the\n // raw-line-pattern check below can test the exact substring a plugin\n // registered via `LexerVocabulary.rawLinePatterns`. See reset()/\n // tokenizeAll() for the single-expression-string equivalent of this\n // same check.\n const lineText = input.slice(lineStart, lineEnd);\n\n // ── Tokenize non-skipped lines ────────────────────────────────\n let tokens: Token[] = [];\n if (!classification.skip) {\n const rawToken = this.pluginRawLinePatterns.length > 0 ? this.matchRawLine(lineText) : null;\n if (rawToken) {\n tokens = [rawToken];\n } else {\n // Scope tokenization to just this line by temporarily restricting len.\n // The [Symbol.iterator]() generator captures `this.len` at call time,\n // so creating the iterator AFTER setting this.len = lineEnd ensures\n // tokenization stops at the line boundary. After tokenization,\n // this.pos will be at lineEnd (the newline position).\n const savedLen = this.len;\n this.len = lineEnd;\n // Start past any structural marker, so the marker never becomes a\n // token. Token source offsets stay absolute, so everything\n // downstream (spans, highlighting, inline solves) still lines up\n // with the raw document.\n if (classification.contentOffset !== undefined) this.pos = classification.contentOffset;\n tokens = Array.from(this);\n this.len = savedLen;\n // this.pos is now at lineEnd, advance past newline below\n }\n }\n\n // ── Detect inline solves ──────────────────────────────────────\n // Two data sources are merged:\n // 1. _inlineSolveSpans, token indices collected inline during\n // [Symbol.iterator](). Provides correct startTokenIndex /\n // endTokenIndex. Also handles \\` escape (skips the pair\n // instead of closing the span early).\n // 2. findInlineSolves(), character-level string scan for\n // expression text. Still needed because token-based\n // reconstruction loses whitespace (the lexer skips spaces),\n // which breaks multi-word expressions like\n // \"2 weeks in days\" → \"2weeksindays\" (wrong tokenization).\n let inlineSolves: InlineSolveSpan[] = [];\n if (classification.hasInlineSolve) {\n if (!classification.skip && tokens.length > 0) {\n const charSpans = this.findInlineSolves(lineText);\n inlineSolves = this._inlineSolveSpans.map((span, i) => ({\n start: charSpans[i]?.start ?? 0,\n end: charSpans[i]?.end ?? 0,\n expression: charSpans[i]?.expression ?? '',\n columnNumber: charSpans[i]?.columnNumber ?? span.columnNumber,\n startTokenIndex: span.startTokenIndex,\n endTokenIndex: span.endTokenIndex,\n }));\n } else {\n // Skipped lines weren't tokenized, fall back to string scan\n inlineSolves = this.findInlineSolves(lineText);\n }\n }\n\n results.push({\n text: lineText,\n lineNumber,\n startOffset: lineStart,\n endOffset: lineEnd,\n classification,\n tokens,\n inlineSolves,\n });\n\n // ── Advance past newline ─────────────────────────────────────\n this.pos = lineEnd;\n if (this.pos < docLen) {\n const nlChar = input.charCodeAt(this.pos);\n if (nlChar === 13) { // \\r\n this.pos++;\n if (this.pos < docLen && input.charCodeAt(this.pos) === 10) {\n this.pos++; // skip \\n in \\r\\n\n }\n } else if (nlChar === 10) { // \\n\n this.pos++;\n }\n }\n this.line++;\n this.lineStartPos = this.pos;\n }\n\n return results;\n }\n\n /**\n * Tokenize an expression string into an array of Tokens.\n *\n * Delegates to the lazy [Symbol.iterator]() generator and collects all\n * yielded tokens via Array.from(). For memory-sensitive use cases, prefer\n * iterating the lexer directly with for...of to avoid array allocation.\n *\n * Optimizations:\n * - CHAR_CLASS jump table (Uint8Array) → switch on small integers\n * - Direct character-code dispatch (c0 cached pattern)\n * - Mathematical digit parsing (integer math, not slice+parseFloat)\n * - Inline operator tokenizer with two-char peek-ahead\n * - Whitespace eliminated in-lexer (never emitted)\n * - 0-char and 1-char fast paths\n */\n tokenizeAll(): Token[] {\n if (this.pendingRawLineToken) {\n this._inlineSolveSpans = [];\n return [this.pendingRawLineToken];\n }\n return Array.from(this);\n }\n\n // ── Lazy iterator ─────────────────────────────────────────────────────\n /**\n * Lazy token-by-token generator. Yields each token without allocating an\n * intermediate Token[] array. Supports for...of and spread usage.\n *\n * Usage:\n * for (const t of lexer) { ... } // lazy, no array allocation\n * const tokens = [...lexer]; // materializes via spread\n * const tokens = lexer.tokenizeAll(); // materializes via Array.from()\n *\n * IMPORTANT: This generator captures `this.len` ONCE at creation time\n * (const len = this.len). `scanDocument()` relies on this behavior to\n * scope tokenization to a single line by temporarily restricting\n * `this.len` to the line end position before creating the iterator.\n * Do NOT refactor to re-read `this.len` mid-loop without also updating\n * `scanDocument()`.\n */\n *[Symbol.iterator](): Generator<Token, void, undefined> {\n const len = this.len;\n\n // ── 0-char fast path ────────────────────────────────────────────────\n if (len === 0) { this._inlineSolveSpans = []; return; }\n\n // Inline solve tracking state, collected inline during tokenization\n let tokenIndex = 0;\n let openSpan: { startTokenIndex: number; startColumn: number } | null = null;\n const collectedSpans: InlineSolveSpan[] = [];\n\n // ── 1-char fast path ────────────────────────────────────────────────\n if (len === 1) {\n const c0 = this.input.charCodeAt(0);\n const cc = ExpressionLexer.CHAR_CLASS[c0] ?? CharClass.SKIP;\n\n switch (cc) {\n case CharClass.DIGIT:\n case CharClass.DOT:\n yield new LexerToken('NUMBER', tokenTypeId('NUMBER'), this.input, this.input, 0, 0, 1, 1);\n tokenIndex++;\n break;\n\n case CharClass.ALPHA: {\n const input = this.input;\n const identLower = input.toLowerCase();\n // Use pre-merged collections (built-in + plugin), single lookup each\n if (this.mergedUnits.has(input)) {\n yield new LexerToken('UNIT', tokenTypeId('UNIT'), input, input, 0, 0, 1, 1);\n } else {\n const kwType = this.mergedKeywords.get(identLower);\n if (kwType) {\n yield new LexerToken(kwType, tokenTypeId(kwType), input, input, 0, 0, 1, 1);\n } else {\n yield new LexerToken('IDENT', tokenTypeId('IDENT'), input, input, 0, 0, 1, 1);\n }\n }\n tokenIndex++;\n break;\n }\n\n case CharClass.OPERATOR: {\n const opType = OP_MAP[c0];\n if (opType) {\n yield new LexerToken(opType, tokenTypeId(opType), this.input, this.input, 0, 0, 1, 1);\n tokenIndex++;\n }\n break;\n }\n\n case CharClass.QUOTE:\n // Delegate to tokenizeString for correctness (handles unterminated)\n this.pos = 0;\n yield this.tokenizeString();\n tokenIndex++;\n break;\n\n case CharClass.HASH:\n // Delegate to tokenizeComment for correctness\n this.pos = 0;\n yield this.tokenizeComment();\n tokenIndex++;\n break;\n\n case CharClass.DOLLAR:\n yield new LexerToken('DOLLAR', tokenTypeId('DOLLAR'), '$', '$', 0, 0, 1, 1);\n tokenIndex++;\n break;\n\n case CharClass.BACKTICK:\n // s` is 2 chars, openSpan can never be set in the 1-char fast path\n yield new LexerToken('BACKTICK_OPEN', tokenTypeId('BACKTICK_OPEN'), '`', '`', 0, 0, 1, 1);\n tokenIndex++;\n break;\n\n default: {\n // CharClass.SKIP, includes non-ASCII characters (code >= 128)\n if (isUnicodeSpace(c0)) {\n // A line holding nothing but a no-break space or a byte-order mark\n // holds no expression, exactly as a line holding one space does.\n // Yielding an IDENT for it made it an undefined variable instead.\n } else if (c0 === 0x00D7) { // × → STAR\n yield new LexerToken('STAR', tokenTypeId('STAR'), '\\u00D7', '\\u00D7', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x00F7) { // ÷ → SLASH\n yield new LexerToken('SLASH', tokenTypeId('SLASH'), '\\u00F7', '\\u00F7', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x00B1) { // U+00B1 plus-minus sign, the uncertainty operator\n yield new LexerToken('PLUS_MINUS', tokenTypeId('PLUS_MINUS'), '\\u00B1', '\\u00B1', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x2260) { // ≠ → NEQ\n yield new LexerToken('NEQ', tokenTypeId('NEQ'), '\\u2260', '\\u2260', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x00A3) { // £\n yield new LexerToken('POUND', tokenTypeId('POUND'), '\\u00A3', '\\u00A3', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20AC) { // €\n yield new LexerToken('EURO', tokenTypeId('EURO'), '\\u20AC', '\\u20AC', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x00A5) { // ¥\n yield new LexerToken('YEN', tokenTypeId('YEN'), '¥', '¥', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20BD) { // ₽\n yield new LexerToken('RUBLE', tokenTypeId('RUBLE'), '₽', '₽', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20A9) { // ₩\n yield new LexerToken('WON', tokenTypeId('WON'), '₩', '₩', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20B9) { // ₹ (Indian rupee) — see uom/CurrencyAliases.ts\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₹', '₹', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20BA) { // ₺ (Turkish lira)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₺', '₺', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20B4) { // ₴ (Ukrainian hryvnia)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₴', '₴', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20AA) { // ₪ (Israeli new shekel)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₪', '₪', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20AB) { // ₫ (Vietnamese dong)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₫', '₫', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20A6) { // ₦ (Nigerian naira)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₦', '₦', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 === 0x20B1) { // ₱ (Philippine peso)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₱', '₱', 0, 0, 1, 1);\n tokenIndex++;\n } else if (c0 >= 128) {\n // Unknown unicode, treat as IDENT for forward compatibility\n yield new LexerToken('IDENT', tokenTypeId('IDENT'), this.input, this.input, 0, 0, 1, 1);\n tokenIndex++;\n }\n break;\n }\n }\n this._inlineSolveSpans = collectedSpans;\n return;\n }\n\n const input = this.input;\n // Fresh nesting stack for this pass (see the field's doc).\n this.groupingStack.length = 0;\n\n // ── Main tokenization loop ──────────────────────────────────────────\n while (this.pos < len) {\n const c0 = input.charCodeAt(this.pos);\n const cc = ExpressionLexer.CHAR_CLASS[c0] ?? CharClass.SKIP;\n\n // ── Escaped backtick inside inline solve ────────────────────────\n // \\` is treated as an escaped backtick, skip both characters\n // without closing the inline solve span. Without this, the\n // backtick would close the span early, producing wrong expression\n // text for expressions like s`hello \\` world`.\n if (openSpan && c0 === 92 && this.pos + 1 < len && input.charCodeAt(this.pos + 1) === 96) {\n this.pos += 2; // skip \\ and `\n continue;\n }\n\n switch (cc) {\n // ── Whitespace, skip entirely, track newlines ────────────────\n case CharClass.WHITESPACE:\n this.pos++;\n if (c0 === 10) { // \\n\n this.line++;\n this.lineStartPos = this.pos;\n this.groupingStack.length = 0; // each line groups thousands on its own\n } else if (c0 === 13) { // \\r\n this.line++;\n if (this.pos < len && input.charCodeAt(this.pos) === 10) {\n this.pos++; // skip \\n in \\r\\n\n }\n this.lineStartPos = this.pos;\n this.groupingStack.length = 0;\n }\n break;\n\n // ── Digit, inline number tokenizer ───────────────────────────\n case CharClass.DIGIT:\n yield this.tokenizeNumber();\n tokenIndex++;\n break;\n\n // ── Alpha / underscore, identifier or keyword ────────────────\n case CharClass.ALPHA: {\n const token = this.tokenizeIdentifier();\n if (token.type === 'INLINE_SOLVE_START') {\n openSpan = { startTokenIndex: tokenIndex, startColumn: token.col };\n }\n yield token;\n tokenIndex++;\n break;\n }\n\n // ── Dot, could be decimal (.5) or DOT token ─────────────────\n case CharClass.DOT:\n if (this.pos + 1 < len) {\n const nextCc = ExpressionLexer.CHAR_CLASS[input.charCodeAt(this.pos + 1)] ?? CharClass.SKIP;\n if (nextCc === CharClass.DIGIT) {\n yield this.tokenizeNumber();\n } else {\n const col = this.pos - this.lineStartPos + 1;\n yield new LexerToken('DOT', tokenTypeId('DOT'), '.', '.', this.pos, 0, this.line, col);\n this.pos++;\n }\n } else {\n const col = this.pos - this.lineStartPos + 1;\n yield new LexerToken('DOT', tokenTypeId('DOT'), '.', '.', this.pos, 0, this.line, col);\n this.pos++;\n }\n tokenIndex++;\n break;\n\n // ── Operator / punctuation ────────────────────────────────────\n case CharClass.OPERATOR:\n yield this.tokenizeOperator();\n tokenIndex++;\n break;\n\n // ── String literal ────────────────────────────────────────────\n case CharClass.QUOTE:\n yield this.tokenizeString();\n tokenIndex++;\n break;\n\n // ── Comment (# or //) ─────────────────────────────────────────\n case CharClass.HASH:\n yield this.tokenizeComment();\n tokenIndex++;\n break;\n\n // ── Dollar sign $ ─────────────────────────────────────────────\n case CharClass.DOLLAR: {\n const col = this.pos - this.lineStartPos + 1;\n yield new LexerToken('DOLLAR', tokenTypeId('DOLLAR'), '$', '$', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n break;\n }\n\n // ── Backtick ` ───────────────────────────────────────────────\n case CharClass.BACKTICK: {\n const col = this.pos - this.lineStartPos + 1;\n yield new LexerToken('BACKTICK_OPEN', tokenTypeId('BACKTICK_OPEN'), '`', '`', this.pos, 0, this.line, col);\n this.pos++;\n if (openSpan) {\n const span = openSpan; // narrow for TS\n collectedSpans.push({\n start: 0, end: 0, expression: '',\n columnNumber: span.startColumn,\n startTokenIndex: span.startTokenIndex,\n endTokenIndex: tokenIndex,\n });\n openSpan = null;\n }\n tokenIndex++;\n break;\n }\n\n // ── Non-ASCII characters ─────────────────────────────────────\n default: {\n const col = this.pos - this.lineStartPos + 1;\n if (isUnicodeSpace(c0)) {\n // Separates its neighbours instead of joining them. See\n // isUnicodeSpace()'s doc comment: this branch is why a sum pasted\n // out of a web page or a spreadsheet evaluates at all.\n this.pos++;\n if (c0 === 0x2028 || c0 === 0x2029 || c0 === 0x0085) {\n // The three that are line breaks rather than spaces, tracked the\n // same way \"\\n\" is above so a later token reports its own line.\n this.line++;\n this.lineStartPos = this.pos;\n }\n } else if (c0 === 0x00D7) { // × → STAR\n yield new LexerToken('STAR', tokenTypeId('STAR'), '\\u00D7', '\\u00D7', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x00F7) { // ÷ → SLASH\n yield new LexerToken('SLASH', tokenTypeId('SLASH'), '\\u00F7', '\\u00F7', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x00B1) { // U+00B1 plus-minus sign, the uncertainty operator\n yield new LexerToken('PLUS_MINUS', tokenTypeId('PLUS_MINUS'), '\\u00B1', '\\u00B1', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x2260) { // ≠ → NEQ\n yield new LexerToken('NEQ', tokenTypeId('NEQ'), '\\u2260', '\\u2260', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x00A3) { // £\n yield new LexerToken('POUND', tokenTypeId('POUND'), '\\u00A3', '\\u00A3', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20AC) { // €\n yield new LexerToken('EURO', tokenTypeId('EURO'), '\\u20AC', '\\u20AC', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x00A5) { // ¥\n yield new LexerToken('YEN', tokenTypeId('YEN'), '¥', '¥', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20BD) { // ₽\n yield new LexerToken('RUBLE', tokenTypeId('RUBLE'), '₽', '₽', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20A9) { // ₩\n yield new LexerToken('WON', tokenTypeId('WON'), '₩', '₩', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20B9) { // ₹ (Indian rupee) — see uom/CurrencyAliases.ts\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₹', '₹', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20BA) { // ₺ (Turkish lira)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₺', '₺', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20B4) { // ₴ (Ukrainian hryvnia)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₴', '₴', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20AA) { // ₪ (Israeli new shekel)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₪', '₪', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20AB) { // ₫ (Vietnamese dong)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₫', '₫', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20A6) { // ₦ (Nigerian naira)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₦', '₦', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 === 0x20B1) { // ₱ (Philippine peso)\n yield new LexerToken('CURRENCY_SYMBOL', tokenTypeId('CURRENCY_SYMBOL'), '₱', '₱', this.pos, 0, this.line, col);\n this.pos++;\n tokenIndex++;\n } else if (c0 >= 128) {\n // Unknown unicode, treat as IDENT for forward compatibility.\n // tokenizeIdentifier() now includes cc >= 128 in its reading loop,\n // so this properly advances past all consecutive Unicode chars.\n yield this.tokenizeIdentifier();\n tokenIndex++;\n } else {\n // Unknown ASCII, silently skip\n this.pos++;\n }\n break;\n }\n }\n }\n this._inlineSolveSpans = collectedSpans;\n }\n\n // ── Inline number tokenizer ────────────────────────────────────────────\n /**\n * Character-by-character number parsing.\n *\n * Supports: integers, floats, scientific notation (1.5e10, 1.5e-10),\n * hex (0xFF), binary (0b1010), octal (0o17), BigInt suffix (123n),\n * thousands separators (1,234 or 1.234.567).\n *\n * Returns a LexerToken and advances `this.pos` past the number.\n */\n private tokenizeNumber(): Token {\n const input = this.input;\n const len = this.len;\n let pos = this.pos;\n const start = pos;\n const startCol = pos - this.lineStartPos + 1;\n let cc: number;\n\n // ── Hex literal: 0x / 0X ───────────────────────────────────────────\n if (input.charCodeAt(pos) === 48 && pos + 1 < len) {\n const next = input.charCodeAt(pos + 1);\n if (next === 0x78 || next === 0x58) { // 'x' or 'X'\n pos += 2;\n while (\n pos < len &&\n ((cc = input.charCodeAt(pos)),\n (cc >= 48 && cc <= 57) || (cc >= 65 && cc <= 70) || (cc >= 97 && cc <= 102))\n ) {\n pos++;\n }\n const text = input.slice(start, pos);\n this.pos = pos;\n return new LexerToken('NUMBER', tokenTypeId('NUMBER'), text, text, start, 0, this.line, startCol);\n }\n // ── Binary literal: 0b / 0B ─────────────────────────────────────\n if (next === 0x62 || next === 0x42) { // 'b' or 'B'\n pos += 2;\n while (pos < len && ((cc = input.charCodeAt(pos)), cc === 48 || cc === 49)) {\n pos++;\n }\n const text = input.slice(start, pos);\n this.pos = pos;\n return new LexerToken('NUMBER', tokenTypeId('NUMBER'), text, text, start, 0, this.line, startCol);\n }\n // ── Octal literal: 0o / 0O ───────────────────────────────────────\n if (next === 0x6F || next === 0x4F) { // 'o' or 'O'\n pos += 2;\n while (pos < len && ((cc = input.charCodeAt(pos)), cc >= 48 && cc <= 55)) {\n pos++;\n }\n const text = input.slice(start, pos);\n this.pos = pos;\n return new LexerToken('NUMBER', tokenTypeId('NUMBER'), text, text, start, 0, this.line, startCol);\n }\n }\n\n let hasIntPart = false;\n\n // ── Integer part ───────────────────────────────────────────────────\n while (pos < len && ((cc = input.charCodeAt(pos)), cc >= 48 && cc <= 57)) {\n hasIntPart = true;\n pos++;\n }\n\n // ── Thousands separators, coalesce with digits ────────────────────\n while (hasIntPart && pos < len && (input.charCodeAt(pos) === 44 || input.charCodeAt(pos) === 46)) {\n // A comma inside a call or bracket is an argument/element separator, not a\n // thousands group: `rgb(255,255,255)` is three numbers and `[100,200,300]`\n // a three-element vector, not `255255255`/`100200300`. A comma in a bare\n // grouping paren (`(1,000)`) still groups thousands, and so does a\n // top-level comma (`1,000,000`). The innermost bracket's context decides;\n // the `.` grouping form is context-free and unaffected. See\n // {@link groupingStack}.\n if (\n input.charCodeAt(pos) === 44 &&\n this.groupingStack.length > 0 &&\n this.groupingStack[this.groupingStack.length - 1]\n ) {\n break;\n }\n if (pos + 4 <= len) {\n const d1 = input.charCodeAt(pos + 1);\n const d2 = input.charCodeAt(pos + 2);\n const d3 = input.charCodeAt(pos + 3);\n // A genuine thousands group is always exactly 3 digits, followed\n // by either another separator, or a non-digit (end of number,\n // operator, unit, EOF), never a 4th consecutive digit. Without\n // this check, a plain decimal fraction with 4+ digits after the\n // point, e.g. \"0.0001\", had its first 3 fractional digits\n // misread as a \".\" thousands-group, silently truncating the\n // number to \"0.000\" and leaving the remaining digit(s) as a\n // separate, unrelated NUMBER token right after it (so\n // \"0.0001 BTC to USD\" tokenized as \"0.000\", \"1\", \"BTC\", \"to\",\n // \"USD\", two number literals instead of one, and evaluated to\n // a bare 0 instead of a real BTC quantity).\n const d4 = pos + 4 < len ? input.charCodeAt(pos + 4) : -1;\n const isGroupOfExactlyThree = !(d4 >= 48 && d4 <= 57);\n if (\n d1 >= 48 && d1 <= 57 &&\n d2 >= 48 && d2 <= 57 &&\n d3 >= 48 && d3 <= 57 &&\n isGroupOfExactlyThree\n ) {\n pos += 4;\n hasIntPart = true;\n continue;\n }\n }\n break;\n }\n\n // ── Decimal part (.xxx) ───────────────────────────────────────────\n let hasDecimal = false;\n if (pos < len && input.charCodeAt(pos) === 46) {\n if (pos + 1 < len) {\n const nextCc = input.charCodeAt(pos + 1);\n if (nextCc >= 48 && nextCc <= 57) {\n hasDecimal = true;\n pos++;\n while (pos < len && ((cc = input.charCodeAt(pos)), cc >= 48 && cc <= 57)) {\n pos++;\n }\n }\n }\n }\n\n // ── Exponent (e / E [+-]? \\n+) ────────────────────────────────────\n let hasExponent = false;\n if (pos < len) {\n const ec = input.charCodeAt(pos);\n if (ec === 0x65 || ec === 0x45) { // 'e' or 'E'\n if (pos + 1 < len) {\n const next = input.charCodeAt(pos + 1);\n if (\n (next >= 48 && next <= 57) ||\n next === 43 || next === 45 // + or -\n ) {\n hasExponent = true;\n pos++;\n if (next === 43 || next === 45) pos++;\n while (pos < len && ((cc = input.charCodeAt(pos)), cc >= 48 && cc <= 57)) {\n pos++;\n }\n }\n }\n }\n }\n\n // ── BigInt suffix check ────────────────────────────────────────────\n if (pos < len && input.charCodeAt(pos) === 110) { // 'n'\n if (hasIntPart && !hasDecimal && !hasExponent) {\n pos++;\n const text = input.slice(start, pos);\n this.pos = pos;\n return new LexerToken('BIGINT', tokenTypeId('BIGINT'), text, text, start, 0, this.line, startCol);\n }\n }\n\n // ── Emit NUMBER token ──────────────────────────────────────────────\n const text = input.slice(start, pos);\n this.pos = pos;\n return new LexerToken('NUMBER', tokenTypeId('NUMBER'), text, text, start, 0, this.line, startCol);\n }\n\n // ── Inline identifier / keyword tokenizer ──────────────────────────────\n /**\n * Reads [a-zA-Z_][a-zA-Z0-9_]* and resolves to:\n * - A unit type (via knownUnits, case-sensitive)\n * - A keyword type (via locale keywordMap, case-insensitive)\n * - IDENT if none of the above\n *\n * Multi-word phrases (e.g., \"to the power of\") are handled by the\n * TokenNormalizer post-lexer pass, not the lexer.\n */\n private tokenizeIdentifier(): Token {\n const input = this.input;\n const len = this.len;\n let pos = this.pos;\n const start = pos;\n const startCol = pos - this.lineStartPos + 1;\n let cc: number;\n\n // Read [a-zA-Z0-9_]* plus any Unicode (>= 128) including emoji surrogate pairs.\n // Without this, non-ASCII characters cause an infinite loop: the default case\n // calls tokenizeIdentifier(), the while loop doesn't match the Unicode char,\n // pos never advances, and the outer loop re-reads the same char forever.\n while (\n pos < len &&\n ((cc = input.charCodeAt(pos)),\n (cc >= 48 && cc <= 57) || // 0-9\n (cc >= 65 && cc <= 90) || // A-Z\n (cc >= 97 && cc <= 122) || // a-z\n cc === 95 || // _\n (cc >= 128 && !isUnicodeSpace(cc))) // Unicode (accented chars, emoji, etc.), but not Unicode whitespace\n ) {\n pos++;\n }\n\n const identText = input.slice(start, pos);\n const identLower = identText.toLowerCase();\n\n // ── Inline solve marker: s` (lowercase 's' followed by backtick) ──\n if (identLower === 's' && pos < len && input.charCodeAt(pos) === 96) {\n pos++;\n this.pos = pos;\n const fullText = input.slice(start, pos);\n return new LexerToken('INLINE_SOLVE_START', tokenTypeId('INLINE_SOLVE_START'), fullText, fullText, start, 0, this.line, startCol);\n }\n\n // ── Unit lookup (case-sensitive)\n const isKnownUnit = this.mergedUnits.has(identText);\n if (isKnownUnit) {\n if (!this.isFollowedByLParen(pos)) {\n this.pos = pos;\n return new LexerToken('UNIT', tokenTypeId('UNIT'), identText, identText, start, 0, this.line, startCol);\n }\n }\n\n // ── Keyword lookup (case-insensitive)\n const localeKwType = this.mergedKeywords.get(identLower);\n if (localeKwType) {\n this.pos = pos;\n return new LexerToken(localeKwType, tokenTypeId(localeKwType), identText, identText, start, 0, this.line, startCol);\n }\n\n // ── Fall through: emit IDENT\n // Multi-word phrases are now handled by the TokenNormalizer post-lexer pass,\n // which keeps the lexer slim and focused on single-token production.\n this.pos = pos;\n return new LexerToken('IDENT', tokenTypeId('IDENT'), identText, identText, start, 0, this.line, startCol);\n }\n\n /**\n * Peek past in-expression whitespace (space, tab) from `pos` to check\n * if the next significant character is '('.\n */\n private isFollowedByLParen(pos: number): boolean {\n const len = this.len;\n let lookPos = pos;\n while (lookPos < len) {\n const cc = this.input.charCodeAt(lookPos);\n if (cc === 40) return true;\n if (cc !== 32 && cc !== 9) break;\n lookPos++;\n }\n return false;\n }\n\n // ── Inline operator tokenizer ─────────────────────────────────────────\n /**\n * Whether the `(` at `parenPos` opens a function call rather than a bare\n * grouping, deciding whether a comma inside it is a separator or a thousands\n * group (see {@link groupingStack}).\n *\n * It is a call when the nearest non-whitespace character before it belongs to\n * the value the call applies to: a closing `)`/`]` (a call on a result), or an\n * IDENTIFIER (`rgb(`, `vec2(`). A run of digits alone is a number, not an\n * identifier, so `2(1,000)` is implicit multiplication over the grouping\n * `(1,000)`, not a call, while `vec2(` and `atan2(` (identifiers that end in a\n * digit) are calls. A `(` after an operator, a comma, or the line start is a\n * grouping.\n */\n private precededByCallTarget(parenPos: number): boolean {\n const input = this.input;\n const start = this.lineStartPos;\n let i = parenPos - 1;\n while (i >= start && (input.charCodeAt(i) === 32 || input.charCodeAt(i) === 9)) i--; // skip spaces/tabs\n if (i < start) return false; // line start (or only whitespace before): a grouping\n const c = input.charCodeAt(i);\n const isWord = (ch: number): boolean =>\n (ch >= 48 && ch <= 57) || (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch === 95;\n const isAlpha = (ch: number): boolean =>\n (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch === 95;\n // A non-word char before \"(\" (an operator, a comma, a `)`/`]`, or the line\n // start) is a grouping. There is no curried/first-class call or index-\n // application in this grammar, so `)(` and `](` are implicit multiplication\n // over a grouping (`(2)(1,000)` is `2 * 1000`), not a call. The only call\n // targets are an identifier or a FUNC keyword, handled below.\n if (!isWord(c)) return false;\n // Walk back over the whole word run. A bare number run (`2(1,000)`) is\n // implicit multiplication over a grouping, not a call.\n const wordEnd = i + 1;\n let hasAlpha = false;\n while (i >= start) {\n const ch = input.charCodeAt(i);\n if (!isWord(ch)) break;\n if (isAlpha(ch)) hasAlpha = true;\n i--;\n }\n if (!hasAlpha) return false;\n // The word is an identifier. A KEYWORD that is not a function name is a\n // word-operator or connective (`mod`, `xor`, `and`, `to`, `in`) or a\n // constant (`pi`, `e`), and the `(...)` after it is a grouped operand, so\n // its comma still groups thousands (`100 mod (1,000)` is `100 mod 1000`).\n // A plain identifier (a function like `rgb`, or a variable) or a function\n // keyword (`sqrt`, `max`) is a real call target, where the comma separates.\n const word = input.slice(i + 1, wordEnd).toLowerCase();\n const keywordType = this.mergedKeywords.get(word);\n return keywordType === undefined || keywordType === \"FUNC\";\n }\n\n /**\n * Reads an operator/punctuation token.\n * Handles two-char operators (==, !=, >=, <=, **) and the special\n * cases << (LSHIFT) and >> (RSHIFT).\n */\n private tokenizeOperator(): Token {\n const input = this.input;\n const pos = this.pos;\n const col = pos - this.lineStartPos + 1;\n const c0 = input.charCodeAt(pos);\n const len = this.len;\n\n // ── Two-character operators ────────────────────────────────────────\n if (pos + 1 < len) {\n const c1 = input.charCodeAt(pos + 1);\n\n // ==, !=, >=, <=\n const secondMap = TWO_CHAR_OPS[c0];\n if (secondMap) {\n const twoCharType = secondMap[c1];\n if (twoCharType) {\n const text = input.slice(pos, pos + 2);\n this.pos = pos + 2;\n return new LexerToken(twoCharType, tokenTypeId(twoCharType), text, text, pos, 0, this.line, col);\n }\n }\n\n // // comment\n if (c0 === 47 && c1 === 47) {\n let commentPos = pos + 2;\n while (commentPos < len) {\n const cc = input.charCodeAt(commentPos);\n if (cc === 10 || cc === 13) break;\n commentPos++;\n }\n const text = input.slice(pos, commentPos);\n this.pos = commentPos;\n return new LexerToken('COMMENT', tokenTypeId('COMMENT'), text, text, pos, 0, this.line, col);\n }\n\n // << (LSHIFT), >> (RSHIFT) and >>> (URSHIFT).\n //\n // >>> is tested before >>, or the two-char match would consume the first\n // two angle brackets and leave a stray > for the parser to choke on.\n if (c0 === 60 && c1 === 60) {\n this.pos = pos + 2;\n return new LexerToken('LSHIFT', tokenTypeId('LSHIFT'), '<<', '<<', pos, 0, this.line, col);\n }\n if (c0 === 62 && c1 === 62) {\n if (input.charCodeAt(pos + 2) === 62) {\n this.pos = pos + 3;\n return new LexerToken('URSHIFT', tokenTypeId('URSHIFT'), '>>>', '>>>', pos, 0, this.line, col);\n }\n this.pos = pos + 2;\n return new LexerToken('RSHIFT', tokenTypeId('RSHIFT'), '>>', '>>', pos, 0, this.line, col);\n }\n\n // ── Plugin-registered two-char operators ──────────────────────\n if (this.hasPluginOps) {\n const pluginInner = this.pluginOperators.get(c0);\n if (pluginInner) {\n const pluginType = pluginInner.get(c1);\n if (pluginType) {\n const text = input.slice(pos, pos + 2);\n this.pos = pos + 2;\n return new LexerToken(pluginType, tokenTypeId(pluginType), text, text, pos, 0, this.line, col);\n }\n }\n }\n }\n\n // ── Single-character operator ──────────────────────────────────────\n this.pos = pos + 1;\n // Track `(`/`[` nesting so the number scanner can tell a thousands group\n // from an argument/element separator (see {@link groupingStack}). `[` always\n // opens a separator context (a vector/matrix). `(` opens a separator context\n // only when it is a CALL, i.e. it directly follows a value the call applies\n // to, an identifier/unit, or a closing `)`/`]`; a bare GROUPING `(`, after an\n // operator or the line start, keeps thousands so `(1,000)` stays one number.\n // `)`/`]` pop; a stray closer with an empty stack is ignored.\n if (c0 === 91) { // [\n this.groupingStack.push(true);\n } else if (c0 === 40) { // (\n this.groupingStack.push(this.precededByCallTarget(pos));\n } else if (c0 === 41 || c0 === 93) { // ) or ]\n if (this.groupingStack.length > 0) this.groupingStack.pop();\n }\n const opType = OP_MAP[c0];\n const text = input.charAt(pos);\n return new LexerToken(opType || 'ERROR', tokenTypeId(opType || 'ERROR'), text, text, pos, 0, this.line, col);\n }\n\n // ── String literal tokenizer ──────────────────────────────────────────\n /**\n * Reads a double-quoted string literal. Supports backslash escapes.\n *\n * `text` is the raw source slice, quotes included, because that is what\n * `offset` + `text.length` has to span for a host to underline the literal.\n * `value` is the PAYLOAD, quotes excluded, because that is what\n * `PUSH_STRING` puts into the Value.\n *\n * The two used to be the same string. `\"abc\"` carried the five characters\n * `\"abc\"` as its value, which was invisible on screen (the formatter prints\n * the payload raw and the retained quotes landed where a display would have\n * put them back) and not invisible anywhere else: `parseFloat('\"5\"')` is NaN\n * whatever the digits say, so `\"5\" + 5` answered 5.\n *\n * An unterminated literal is an error rather than a string that happens to\n * reach the end of the line. It used to return what it had, so `\"abc` and\n * `\"abc\"` were indistinguishable by payload once the quotes were stripped,\n * which is the other half of why they are stripped here rather than later.\n */\n private tokenizeString(): Token {\n const input = this.input;\n const len = this.len;\n const start = this.pos;\n const startCol = start - this.lineStartPos + 1;\n let pos = start + 1;\n let lineBreaks = 0;\n\n while (pos < len) {\n const c0 = input.charCodeAt(pos);\n if (c0 === 34) {\n pos++;\n const text = input.slice(start, pos);\n const value = input.slice(start + 1, pos - 1);\n this.pos = pos;\n return new LexerToken('STRING', tokenTypeId('STRING'), value, text, start, lineBreaks, this.line, startCol);\n }\n if (c0 === 92 && pos + 1 < len) {\n pos += 2;\n continue;\n }\n if (c0 === 10) {\n this.line++;\n this.lineStartPos = pos + 1;\n lineBreaks++;\n }\n pos++;\n }\n\n this.pos = pos;\n throw ErrorFactory.parsing(\n \"UNTERMINATED_STRING\",\n `Unterminated string literal: ${input.slice(start, pos)}`,\n { literal: input.slice(start, pos), offset: start },\n );\n }\n\n // ── Markdown line scanner (Phase B) ───────────────────────────────────\n\n /**\n * L1 expression gating: quickly determine if a line contains any\n * characters that indicate an expression (digits, operators, currency,\n * backticks, parentheses, etc.).\n *\n * Pure prose lines (e.g., \"The quick brown fox jumps over the lazy dog\")\n * return false and can be skipped without full tokenization (L2).\n *\n * This is a fast character-by-character scan that stops at the first\n * expression indicator. Called once per line in classifyFromPositions().\n */\n static hasExpressionIndicators(input: string, start: number, end: number): boolean {\n const indicatorCodes = EXPRESSION_INDICATOR_CODES;\n for (let i = start; i < end; i++) {\n const cc = input.charCodeAt(i);\n // Check digits and operators via pre-computed Set (O(1) lookup)\n if (indicatorCodes.has(cc)) return true;\n // Unicode math/currency symbols (≥ 128, not in the 128-byte table)\n if (cc >= 128) {\n // ×, ÷, ≠, £, €, ¥, ₽, ₩, common expression symbols\n if (cc === 0x00D7 || cc === 0x00F7 || cc === 0x2260 ||\n cc === 0x00A3 || cc === 0x20AC ||\n cc === 0x00A5 || cc === 0x20BD || cc === 0x20A9) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Classify a line by its character positions within this.input.\n * Reads directly from this.input using start/end boundaries.\n * DOES NOT modify this.pos, purely a read-only classifier.\n */\n /**\n * Advance past the whitespace after a list marker, and past a task-item\n * checkbox if one follows.\n *\n * The checkbox is included because it is markup by the same argument the\n * marker is, and because leaving it stopped the line dead: `- [ ] 100 + 20`\n * lexed `[ ]` as a matrix literal and reported that a matrix cannot be\n * empty, which tells a user writing a to-do list nothing they can act on.\n *\n * @param from - Offset just past the marker character.\n * @param end - Line end, never read past.\n * @returns Offset of the first evaluable character.\n */\n private skipMarkerGap(from: number, end: number): number {\n const input = this.input;\n let pos = from;\n while (pos < end && (input.charCodeAt(pos) === 32 || input.charCodeAt(pos) === 9)) pos++;\n\n // `[ ]`, `[x]`, `[X]`, or any single-character state Obsidian allows.\n if (pos + 2 < end && input.charCodeAt(pos) === 91 && input.charCodeAt(pos + 2) === 93) {\n let after = pos + 3;\n while (after < end && (input.charCodeAt(after) === 32 || input.charCodeAt(after) === 9)) after++;\n // Only when whitespace followed, so `[1,2]` opening a real matrix is\n // never mistaken for a checkbox.\n if (after > pos + 3) return after;\n }\n return pos;\n }\n\n /**\n * The end offset (exclusive) of a `#hex` colour literal starting at `hashPos`,\n * or -1 if the run there is not one. A colour is `#` followed by EXACTLY 3, 4,\n * 6 or 8 hex digits (the CSS forms `#rgb`/`#rgba`/`#rrggbb`/`#rrggbbaa`) and\n * then a boundary, not a longer word or number. This is the one predicate that\n * carves colours out of the two things `#` otherwise means, a markdown heading\n * at line start and a comment mid-line, and it is pure character logic so line\n * classification stays vocabulary-independent. Examples: `#f00`, `#ff0000`,\n * `#deadbeef` match; `# Heading` (space), `#tag`/`#todo` (non-hex letter),\n * `#12345` (length 5), `#ff0000zz` (trailing word) do not.\n */\n private matchHexColourEnd(hashPos: number, end: number): number {\n const input = this.input;\n let p = hashPos + 1;\n let n = 0;\n while (p < end) {\n const c = input.charCodeAt(p);\n const isHex = (c >= 48 && c <= 57) || (c >= 65 && c <= 70) || (c >= 97 && c <= 102);\n if (!isHex) break;\n n++;\n p++;\n }\n if (n !== 3 && n !== 4 && n !== 6 && n !== 8) return -1;\n if (p < end) {\n const c = input.charCodeAt(p);\n const isWord = (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95;\n if (isWord) return -1;\n }\n return p;\n }\n\n private classifyFromPositions(start: number, end: number): LineClassification {\n const len = end;\n\n if (start >= len) {\n return { type: 'empty', skip: true, hasInlineSolve: false };\n }\n\n const input = this.input;\n let pos = start;\n\n while (pos < len) {\n const cc = input.charCodeAt(pos);\n if (cc !== 32 && cc !== 9) break;\n pos++;\n }\n\n if (pos >= len) {\n return { type: 'empty', skip: true, hasInlineSolve: false };\n }\n\n const c0 = input.charCodeAt(pos);\n let hasInline: boolean | undefined;\n\n // ── Heading: #{1,6} ' ' ──────────────────────────────────────────\n if (c0 === 35) {\n // A bare #hex colour is a value, not a heading. A real heading has a space\n // after its #(s), so the colour shape (# + 3/4/6/8 hex digits) never\n // collides with one. This line is tokenized like any expression.\n if (this.matchHexColourEnd(pos, len) !== -1) {\n if (hasInline === undefined) {\n const idx = input.indexOf('s`', pos);\n hasInline = idx !== -1 && idx < len;\n }\n return { type: 'expression', skip: false, hasInlineSolve: hasInline };\n }\n let hashCount = 1;\n while (pos + hashCount < len && input.charCodeAt(pos + hashCount) === 35) {\n hashCount++;\n }\n if (hashCount <= 6 && pos + hashCount < len && input.charCodeAt(pos + hashCount) === 32) {\n return { type: 'heading', skip: true, hasInlineSolve: false };\n }\n return { type: 'heading', skip: true, hasInlineSolve: false };\n }\n\n // ── Blockquote: > ' ' ────────────────────────────────────────────\n if (c0 === 62) {\n if (pos + 1 < len && input.charCodeAt(pos + 1) === 32) {\n return { type: 'blockquote', skip: true, hasInlineSolve: false };\n }\n }\n\n // ── Code fence: ``` or ~~~ ────────────────────────────────────────\n if (c0 === 96 && pos + 2 < len && input.charCodeAt(pos + 1) === 96 && input.charCodeAt(pos + 2) === 96) {\n return { type: 'code_fence', skip: true, hasInlineSolve: false };\n }\n if (c0 === 126 && pos + 2 < len && input.charCodeAt(pos + 1) === 126 && input.charCodeAt(pos + 2) === 126) {\n return { type: 'code_fence', skip: true, hasInlineSolve: false };\n }\n\n // ── Math fence: $$ ────────────────────────────────────────────────\n if (c0 === 36 && pos + 1 < len && input.charCodeAt(pos + 1) === 36) {\n return { type: 'math_fence', skip: true, hasInlineSolve: false };\n }\n\n // ── Horizontal rule: ---, ***, ___ (3+ same char, then only whitespace)\n if (c0 === 45 || c0 === 42 || c0 === 95) {\n let count = 1;\n while (pos + count < len && input.charCodeAt(pos + count) === c0) {\n count++;\n }\n if (count >= 3) {\n let trailPos = pos + count;\n while (trailPos < len && (input.charCodeAt(trailPos) === 32 || input.charCodeAt(trailPos) === 9)) {\n trailPos++;\n }\n if (trailPos >= len) {\n return { type: 'hr', skip: true, hasInlineSolve: false };\n }\n }\n }\n\n // ── Unordered list: - ' ', * ' ', + ' ' ──────────────────────────\n if ((c0 === 45 || c0 === 42 || c0 === 43) && pos + 1 < len && input.charCodeAt(pos + 1) === 32) {\n if (hasInline === undefined) {\n const idx = input.indexOf('s`', pos);\n hasInline = idx !== -1 && idx < len;\n }\n // The space is what makes this a marker rather than an operator, and it\n // is required by CommonMark for exactly that reason. `-100 + 20` has no\n // space and stays arithmetic; `- 100 + 20` is a bullet.\n return { type: 'list', skip: false, hasInlineSolve: hasInline, contentOffset: this.skipMarkerGap(pos + 1, len) };\n }\n\n // ── Ordered list: \\n+ '. ' ────────────────────────────────────────\n if (c0 >= 48 && c0 <= 57) {\n let digitPos = pos;\n while (digitPos < len && input.charCodeAt(digitPos) >= 48 && input.charCodeAt(digitPos) <= 57) {\n digitPos++;\n }\n if (digitPos < len && input.charCodeAt(digitPos) === 46) {\n if (digitPos + 1 < len && input.charCodeAt(digitPos + 1) === 32) {\n if (hasInline === undefined) {\n const idx = input.indexOf('s`', pos);\n hasInline = idx !== -1 && idx < len;\n }\n return { type: 'list', skip: false, hasInlineSolve: hasInline, contentOffset: this.skipMarkerGap(digitPos + 1, len) };\n }\n }\n }\n\n // ── Table / table separator: | ────────────────────────────────────\n if (c0 === 124) {\n let tPos = pos + 1;\n while (tPos < len) {\n const tc = input.charCodeAt(tPos);\n if (tc !== 45 && tc !== 58 && tc !== 124 && tc !== 32 && tc !== 9 && tc !== 13) break;\n tPos++;\n }\n if (tPos >= len) {\n return { type: 'table_separator', skip: true, hasInlineSolve: false };\n }\n }\n\n // ── Wikilink / embed: [[ or ![[ ───────────────────────────────────\n if (c0 === 91 && pos + 1 < len && input.charCodeAt(pos + 1) === 91) {\n const closePos = input.indexOf(']]', pos + 2);\n if (closePos !== -1 && closePos < len) {\n let trailPos = closePos + 2;\n while (trailPos < len && (input.charCodeAt(trailPos) === 32 || input.charCodeAt(trailPos) === 9)) {\n trailPos++;\n }\n if (trailPos >= len) {\n return { type: 'wikilink', skip: true, hasInlineSolve: false };\n }\n }\n }\n if (c0 === 33 && pos + 2 < len && input.charCodeAt(pos + 1) === 91 && input.charCodeAt(pos + 2) === 91) {\n const closePos = input.indexOf(']]', pos + 3);\n if (closePos !== -1 && closePos < len) {\n let trailPos = closePos + 2;\n while (trailPos < len && (input.charCodeAt(trailPos) === 32 || input.charCodeAt(trailPos) === 9)) {\n trailPos++;\n }\n if (trailPos >= len) {\n return { type: 'wikilink', skip: true, hasInlineSolve: false };\n }\n }\n }\n\n // ── Comment: // ──────────────────────────────────────────────────\n if (c0 === 47 && pos + 1 < len && input.charCodeAt(pos + 1) === 47) {\n return { type: 'comment', skip: true, hasInlineSolve: false };\n }\n\n // ── Default: expression or prose line ─────────────────────────────\n if (c0 === 62) {\n let trail = pos + 1;\n while (trail < len && (input.charCodeAt(trail) === 32 || input.charCodeAt(trail) === 9)) trail++;\n if (trail >= len) return { type: 'blockquote', skip: true, hasInlineSolve: false };\n }\n if (c0 === 45 || c0 === 42 || c0 === 43) {\n let trail = pos + 1;\n while (trail < len && (input.charCodeAt(trail) === 32 || input.charCodeAt(trail) === 9)) trail++;\n if (trail >= len) return { type: 'list', skip: false, hasInlineSolve: false };\n }\n if (hasInline === undefined) {\n const idx = input.indexOf('s`', pos);\n hasInline = idx !== -1 && idx < len;\n }\n\n // A line built only from characters the tokenizer discards produces no\n // tokens, so it has nothing to evaluate. Whitespace-only lines already\n // classify as empty above; the gap was an unknown ASCII character like a\n // backslash, which the lexer skips (it falls through to CharClass.SKIP)\n // rather than tokenising. A run of them (\"\\\\\", \"\\\\\\\\\") reached the\n // expression path, lexed to an empty token stream, and the engine reported\n // that stream as the number 0: a result on screen for a line that holds no\n // expression at all. Classify it as empty, the same as a blank line, so\n // every surface (the batch parse, the incremental evaluator, and the\n // playground's shouldEvaluateLine) skips it rather than answering 0. A\n // non-ASCII code point is real content (it lexes as an IDENT for forward\n // compatibility), so only ASCII whitespace and skip characters count here.\n if (!hasInline) {\n let onlySkippable = true;\n for (let i = pos; i < len; i++) {\n const code = input.charCodeAt(i);\n if (code >= 128 || ExpressionLexer.CHAR_CLASS[code] > CharClass.WHITESPACE) {\n onlySkippable = false;\n break;\n }\n }\n if (onlySkippable) {\n return { type: 'empty', skip: true, hasInlineSolve: false };\n }\n }\n\n // Return expression, all non-markdown-structure lines are tokenized.\n // (L1 prose gating removed: it incorrectly skipped keyword-only lines\n // like \"pi\", single identifiers like \"hello\", and any line without\n // digits/operators/currency. Can be re-added with keyword-awareness\n // and proper test coverage.)\n return { type: 'expression', skip: false, hasInlineSolve: hasInline };\n }\n\n /**\n * Classify a single line of markdown text.\n */\n classifyLine(lineText: string): LineClassification {\n const savedInput = this.input;\n const savedLen = this.len;\n const savedPos = this.pos;\n this.input = lineText;\n this.len = lineText.length;\n this.pos = 0;\n const result = this.classifyFromPositions(0, lineText.length);\n this.input = savedInput;\n this.len = savedLen;\n this.pos = savedPos;\n return result;\n }\n\n /**\n * Every keyword this lexer currently recognizes, locale keywords\n * (`pi`, `sqrt`, `convert`, ...) merged with any plugin-contributed ones\n * from `registerVocabulary()` (e.g. a package's custom keywords), mapped to\n * the token type they lex to. A snapshot copy, not a live reference\n * mutating the return value has no effect on the lexer.\n */\n getKeywords(): Record<string, string> {\n return Object.fromEntries(this.mergedKeywords);\n }\n\n /**\n * Find all inline solve markers in a line with precise coordinate mapping.\n */\n findInlineSolves(lineText: string): InlineSolveSpan[] {\n const results: InlineSolveSpan[] = [];\n const len = lineText.length;\n let pos = 0;\n\n while (pos < len) {\n const sPos = lineText.indexOf('s`', pos);\n if (sPos === -1) break;\n\n const exprStart = sPos + 2;\n\n let exprEnd = exprStart;\n while (exprEnd < len) {\n const cc = lineText.charCodeAt(exprEnd);\n if (cc === 92 && exprEnd + 1 < len) {\n exprEnd += 2;\n continue;\n }\n if (cc === 96) break;\n exprEnd++;\n }\n\n if (exprEnd >= len) {\n exprEnd = len;\n }\n\n const expression = lineText.slice(exprStart, exprEnd);\n const end = exprEnd < len ? exprEnd + 1 : exprEnd;\n\n results.push({\n start: sPos,\n end,\n expression,\n columnNumber: sPos + 1,\n });\n\n pos = end;\n }\n\n return results;\n }\n\n // ── Comment tokenizer ─────────────────────────────────────────────────\n /**\n * Reads a comment: # to end of line, or // to end of line.\n */\n private tokenizeComment(): Token {\n const input = this.input;\n const len = this.len;\n const start = this.pos;\n const startCol = start - this.lineStartPos + 1;\n\n // A `#hex` colour literal is not a comment. Recognised here (the single\n // choke-point both `#` call sites reach) so `#ff0000` becomes a HEX_COLOUR\n // token while `# comment`, `#tag`, `#face` (length 4 all-hex still counts as a\n // colour) and `// c` stay comments. Only fires when the char is `#`, never `/`.\n if (input.charCodeAt(start) === 35) {\n const hexEnd = this.matchHexColourEnd(start, len);\n if (hexEnd !== -1) {\n const text = input.slice(start, hexEnd);\n this.pos = hexEnd;\n return new LexerToken('HEX_COLOUR', tokenTypeId('HEX_COLOUR'), text, text, start, 0, this.line, startCol);\n }\n\n // A bounded `#tag` annotation: `#` then a letter then a run of\n // `[A-Za-z0-9_-]`, consuming only the tag, not the rest of the line. So\n // `1200 #housing // note` keeps the `// note` comment, and a mid-line tag\n // no longer swallows the line. `# ` (space) and `#123` (leading digit)\n // still fall through to a comment; a line-start `#` is a heading\n // (classified elsewhere); a `#hex` colour is caught above.\n const first = input.charCodeAt(start + 1);\n const isLetter = (first >= 65 && first <= 90) || (first >= 97 && first <= 122);\n if (isLetter) {\n let tagEnd = start + 2;\n while (tagEnd < len) {\n const c = input.charCodeAt(tagEnd);\n const isTagChar = (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 45;\n if (!isTagChar) break;\n tagEnd++;\n }\n // Store the name without the `#`, matching how LINE_REF keeps the bare\n // number.\n const name = input.slice(start + 1, tagEnd);\n this.pos = tagEnd;\n return new LexerToken('TAG', tokenTypeId('TAG'), name, name, start, 0, this.line, startCol);\n }\n }\n\n let pos = this.pos;\n\n if (pos + 1 < len && input.charCodeAt(pos + 1) === 47) {\n pos += 2;\n } else {\n pos++;\n }\n\n while (pos < len) {\n const c0 = input.charCodeAt(pos);\n if (c0 === 10 || c0 === 13) break;\n pos++;\n }\n\n const text = input.slice(start, pos);\n this.pos = pos;\n return new LexerToken('COMMENT', tokenTypeId('COMMENT'), text, text, start, 0, this.line, startCol);\n }\n}"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var chunk6KFVG6UY_cjs=require('./chunk-6KFVG6UY.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkSOMGSIO4_cjs=require('./chunk-SOMGSIO4.cjs');var k={maxPasses:100,maxTokens:1e4,onFusion:()=>{}};function N(a,e,t){let r=t[0],n=t[t.length-1],o=new chunk6KFVG6UY_cjs.a(a,chunk5IJD5L3O_cjs.c(a),e,e,r.offset,r.lineBreaks??0,r.line,r.col);return o.sourceEnd=n.sourceEnd??n.offset+n.text.length,o}function C(a,e){let t=e[e.length-1];t&&(a.sourceEnd=t.sourceEnd??t.offset+t.text.length);}var v=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],I=(()=>{let a=v.map(r=>chunk5IJD5L3O_cjs.c(r)),e=Math.max(...a)+1,t=new Uint8Array(e);for(let r of a)t[r]=1;return t})(),L=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.phraseTrie=new T;this.options={...k,...e};}register(e){this.rules.push(e),this.sortedRulesCache=null;}unregister(e){this.rules=this.rules.filter(t=>t.name!==e),this.sortedRulesCache=null;}clear(){this.rules=[],this.sortedRulesCache=null,this.phraseTrie=new T;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,t)=>t.priority-e.priority)),this.sortedRulesCache}get ruleCount(){return this.rules.length}addPhrase(e,t){this.phraseTrie.addPhrase(e,t);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,t){if(e.length===0)return e;let r=this.getSortedRules(),n=t??this.options.onFusion,o=this.options.maxPasses,s=this.options.maxTokens,i=e,m=true,d=0;for(;m&&d<o;){m=false,d++;let h=[],c=0;for(;c<i.length;){let E=false,y=i[c].typeId;if(y>=I.length||I[y]===0){let u=this.phraseTrie.matchAt(i,c);if(u){let l=i.slice(c,c+u.consumed);for(let p of u.replacement)h.push(p);u.consumed>1&&u.replacement.length===1&&(C(u.replacement[0],l),n({rule:u.ruleName??"phrase-trie",sourceTokens:l,fusedToken:u.replacement[0]})),c+=u.consumed,m=true;continue}}for(let u of r){let l=u.match(i,c);if(l){let p=i.slice(c,c+l.consumed);for(let g of l.replacement)h.push(g);if(l.consumed>1&&l.replacement.length===1)C(l.replacement[0],p),n({rule:u.name,sourceTokens:p,fusedToken:l.replacement[0]});else if(l.consumed>1&&l.replacement.length<l.consumed)for(let g of l.replacement)n({rule:u.name,sourceTokens:p,fusedToken:g});c+=l.consumed,m=true,E=true;break}}E||(h.push(i[c]),c++);}if(h.length>s)throw chunkSOMGSIO4_cjs.c.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${h.length}) exceeds safety limit (${s})`,{tokenCount:h.length,maxTokens:s});i=h;}return i}};var T=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,t){let r=e.toLowerCase().trim().split(/\s+/);if(r.length===0||r[0]==="")return;this.startWords.add(r[0]);let n=r[0],o;if(this.root.has(n)?o=this.root.get(n):(o={children:new Map,terminal:null},this.root.set(n,o)),r.length===1){o.terminal={tokenType:t,phrase:e,consumed:1};return}for(let s=1;s<r.length;s++){let i=r[s];o.children.has(i)||o.children.set(i,{children:new Map,terminal:null}),o=o.children.get(i);}o.terminal={tokenType:t,phrase:e,consumed:r.length};}matchAt(e,t){if(t>=e.length)return null;let r=e[t].value.toLowerCase();if(!this.startWords.has(r))return null;let n=this.root.get(r);if(!n)return null;let o=null,s=1;if(n.terminal){let i=e.slice(t,t+1);o={consumed:1,replacement:[N(n.terminal.tokenType,n.terminal.phrase,i)],ruleName:n.terminal.phrase};}for(let i=t+1;i<e.length&&n?.children;i++){let m=e[i].value.toLowerCase();if(n=n.children.get(m),!n)break;if(s++,n.terminal){let d=e.slice(t,t+s);o={consumed:s,replacement:[N(n.terminal.tokenType,n.terminal.phrase,d)],ruleName:n.terminal.phrase};}}return o}get size(){return this.root.size}getAllPhrases(){let e={},t=(r,n)=>{r.terminal&&(e[n.join(" ")]=r.terminal.tokenType);for(let[o,s]of r.children)t(s,[...n,o]);};for(let[r,n]of this.root)t(n,[r]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var w=new Set(["per","a","an","each","every"]),S=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function x(a=50,e){let t=e??(r=>S.has(r.toLowerCase()));return {name:"implicit:multiply",priority:a,match(r,n){if(n+1>=r.length)return null;let o=r[n],s=r[n+1],i=s.value.toLowerCase();if(t(i)||w.has(i)&&r[n+2]?.type==="UNIT"||!((o.type==="NUMBER"||o.type==="RPAREN")&&(s.type==="IDENT"||s.type==="LPAREN"||s.type==="PI"||s.type==="E")))return null;let d=new chunk6KFVG6UY_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",s.offset,0,s.line,s.col);return {consumed:1,replacement:[o,d]}}}}function U(a,e){let t=[];for(let r=0;r<e;r++){let n=a[r];if(n.type==="LBRACKET")t.push(true);else if(n.type==="LPAREN"){let o=a[r-1],s=!!o&&(o.type==="MAP"||o.type==="REDUCE"||o.type==="SUM_FN"||o.type==="PROD_FN"||o.type==="IDENT"&&(o.value.toLowerCase()==="map"||o.value.toLowerCase()==="reduce"||o.value.toLowerCase()==="sum"||o.value.toLowerCase()==="prod"));t.push(s);}else (n.type==="RBRACKET"||n.type==="RPAREN")&&t.pop();}return t.length>0&&t[t.length-1]}function W(){return [x()]}var Y={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","divide by":"DIVIDE_BY","multiplied by":"MULTIPLY_BY","divided by":"DIVIDE_BY"};exports.a=T;exports.b=N;exports.c=L;exports.d=x;exports.e=U;exports.f=W;exports.g=Y;//# sourceMappingURL=chunk-APN442VD.cjs.map
2
- //# sourceMappingURL=chunk-APN442VD.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":["DEFAULT_OPTIONS","createFusedToken","type","text","sourceTokens","first","last","token","LexerToken","tokenTypeId","recordSourceSpan","fused","NON_WORD_NAMES","NON_WORD_TABLE","ids","n","len","table","id","TokenNormalizer","options","PhraseTrie","rule","ruleName","r","a","b","phrase","tokenType","word","tokens","onFusion","sorted","fusionHandler","maxPasses","maxTokens","current","changed","passCount","result","pos","matched","tid","trieMatch","rt","match","ErrorFactory","words","firstWord","node","i","best","depth","collect","path","child","RATE_DENOMINATOR_WORDS","PHRASE_START_WORDS","implicitMultiplyRule","priority","canStart","phraseGuard","t","next","nextValue","starToken","isInsideRangeContext","safeStack","prev","opensMapReduceCall","createBuiltinNormalizerRules","BUILTIN_PHRASES"],"mappings":"uKA2EA,IAAMA,CAAAA,CAA+C,CACnD,SAAA,CAAW,GAAA,CACX,UAAW,GAAA,CACX,QAAA,CAAU,IAAM,CAAC,CACnB,CAAA,CAwBO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACO,CACP,IAAMC,CAAAA,CAAQD,CAAAA,CAAa,CAAC,CAAA,CACtBE,EAAOF,CAAAA,CAAaA,CAAAA,CAAa,MAAA,CAAS,CAAC,CAAA,CAC3CG,CAAAA,CAAQ,IAAIC,mBAAAA,CAChBN,EACAO,mBAAAA,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AA,CAAqB,CAAC,CAACD,CAAAA,GAC3BA,CAAAA,CAAK,IAAA,GAAS,KAAA,EAASA,CAAAA,CAAK,OAAS,QAAA,EAAYA,CAAAA,CAAK,IAAA,GAAS,QAAA,EAAYA,EAAK,IAAA,GAAS,SAAA,EACxFA,CAAAA,CAAK,IAAA,GAAS,UAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,KAAA,CAAM,WAAA,KAAkB,QAAA,EAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,KAAA,CAAM,aAAY,GAAM,MAAA,CAAA,CAAA,CAE/KD,CAAAA,CAAU,IAAA,CAAKE,CAAkB,EACnC,CAAA,KAAA,CAAWP,CAAAA,CAAE,OAAS,UAAA,EAAcA,CAAAA,CAAE,IAAA,GAAS,QAAA,GAC7CK,EAAU,GAAA,GAEd,CACA,OAAOA,EAAU,MAAA,CAAS,CAAA,EAAKA,CAAAA,CAAUA,CAAAA,CAAU,MAAA,CAAS,CAAC,CAC/D,CAoBO,SAASG,CAAAA,EAAiD,CAC/D,OAAO,CAELZ,CAAAA,EACF,CACF,KASaa,CAAAA,CAA0C,CACtD,iBAAA,CAAmB,OAAA,CACnB,UAAA,CAAY,OAAA,CACZ,aAAA,CAAe,aAAA,CACf,cAAe,aAAA,CACf,UAAA,CAAY,UAAA,CACZ,aAAA,CAAe,cACf,WAAA,CAAa,WAAA,CAKb,eAAA,CAAiB,aAAA,CACjB,aAAc,WACf","file":"chunk-APN442VD.cjs","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n this.rules.push(rule);\n this.sortedRulesCache = null;\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // ── Priority-sorted rules, cached across calls, see getSortedRules() ──\n const sorted = this.getSortedRules();\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n const result: Token[] = [];\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try every rule in priority order at this position\n for (const rule of sorted) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged\n result.push(current[pos]);\n pos++;\n }\n }\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (result.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${result.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: result.length, maxTokens }\n );\n }\n\n current = result;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Check trigger conditions ──\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}.\n */\nexport const BUILTIN_PHRASES: Record<string, string> = {\n\t\"to the power of\": \"CARET\",\n\t\"power of\": \"CARET\",\n\t\"increase by\": \"INCREASE_BY\",\n\t\"decrease by\": \"DECREASE_BY\",\n\t\"times by\": \"TIMES_BY\",\n\t\"multiply by\": \"MULTIPLY_BY\",\n\t\"divide by\": \"DIVIDE_BY\",\n\t// The past-tense spellings, which is how the operation is usually written\n\t// out: \"3 multiplied by 4\". Same tokens, so no new parselets. Both this\n\t// branch and the parity branch added \"multiplied by\" independently; the\n\t// merge kept both copies and the locale table rejected the duplicate key.\n\t\"multiplied by\": \"MULTIPLY_BY\",\n\t\"divided by\": \"DIVIDE_BY\",\n};\n\n//#endregion\n"]}
@@ -1,3 +0,0 @@
1
- import {a}from'./chunk-RAF57WYO.js';import {l,g}from'./chunk-XR7HEC7B.js';import {b as b$1}from'./chunk-76F3LCIL.js';import {J as J$1,K}from'./chunk-W2JAR233.js';import {h,i,N as N$1}from'./chunk-EVAOPEO4.js';import {b}from'./chunk-L3FPQSGN.js';import {c as c$1}from'./chunk-GOIQYUWV.js';import {c,b as b$2}from'./chunk-MPB7KUN5.js';var D=class{constructor(){this.root=null;}get length(){return this.root?this.root.size:0}get isEmpty(){return this.root===null}getAt(e){if(!(e<0||e>=(this.root?.size??0)))return this.nodeAt(this.root,e).lineId}insertAt(e,t){let[n,r]=E(this.root,e);this.root=C(C(n,Y(t)),r);}deleteAt(e){if(e<0||e>=(this.root?.size??0))return;let[t,n]=E(this.root,e),[r,s]=E(n,1),i=r?r.lineId:void 0;return this.root=C(t,s),i}spliceAt(e,t,n){let r=Math.max(0,e),s=Math.min(Math.max(0,t),(this.root?.size??0)-r),[i,a]=E(this.root,r),[l,o]=E(a,s),c=ee(l),d=T(n,0,n.length);return this.root=C(C(i,d),o),c}replaceAll(e){this.root=T(e,0,e.length);}getRange(e,t){let n=Math.max(0,e),r=Math.min((this.root?.size??0)-1,t);if(n>r)return [];let s=[];return this.collectRange(this.root,n,r,0,s),s}clear(){this.root=null;}*[Symbol.iterator](){yield*this.inOrder(this.root);}*inOrder(e){e&&(yield*this.inOrder(e.left),yield e.lineId,yield*this.inOrder(e.right));}nodeAt(e,t){let n=e.left?e.left.size:0;return t<n?this.nodeAt(e.left,t):t===n?e:this.nodeAt(e.right,t-n-1)}collectRange(e,t,n,r,s){if(!e)return;let i=e.left?e.left.size:0,a=r+i;a>t&&e.left&&this.collectRange(e.left,t,n,r,s),a>=t&&a<=n&&s.push(e.lineId),a<n&&e.right&&this.collectRange(e.right,t,n,a+1,s);}};function Y(u){return {lineId:u,size:1,priority:Math.random(),left:null,right:null}}function M(u){u.size=1+(u.left?u.left.size:0)+(u.right?u.right.size:0);}function C(u,e){return u?e?u.priority>e.priority?(u.right=C(u.right,e),M(u),u):(e.left=C(u,e.left),M(e),e):u:e}function E(u,e){if(!u)return [null,null];let t=u.left?u.left.size:0;if(e<=t){let[n,r]=E(u.left,e);return u.left=r,M(u),[n,u]}else {let[n,r]=E(u.right,e-t-1);return u.right=n,M(u),[u,r]}}function ee(u){let e=[];return z(u,e),e}function z(u,e){u&&(z(u.left,e),e.push(u.lineId),z(u.right,e));}function T(u,e,t){if(e>=t)return null;let n=Math.floor((e+t)/2),r=te(n);return {lineId:u[n],size:t-e,priority:r,left:T(u,e,n),right:T(u,n+1,t)}}function te(u){let e=u;return e=(e>>16^e)*73244475,e=(e>>16^e)*73244475,e=e>>16^e,e/4294967295}var N=class{constructor(e=b.performance.maxDocumentLines){this.lines=new Map;this.orderTree=new D;this.nextLineId=1;this._positionCache=null;this.dirtyLineIds=new Set;this.maxLines=e;}setDocument(e){if(b$1(e,this.maxLines)>this.maxLines)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${this.maxLines.toLocaleString("en-US")} lines, which is the most the engine will hold at once`,{maxLines:this.maxLines});this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.dirtyLineIds.clear(),this.nextLineId=1;let n=e.split(`
2
- `),r=new Array(n.length);for(let s=0;s<n.length;s++){let i=this.nextLineId++;r[s]=i,this.lines.set(i,{lineId:i,textHash:a(n[s]),text:n[s],expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:n[s].trim().length===0,inlineSolveCount:0});}this.orderTree.replaceAll(r);for(let s of r)this.dirtyLineIds.add(s);}applyChanges(e){let t=[],n=[],r=[...e].sort((s,i)=>i.startLine-s.startLine);for(let s of r){let i=s.startLine-1,a$1=[];for(let o of s.insertLines){let c=this.nextLineId++;a$1.push(c),t.push(c),this.lines.set(c,{lineId:c,textHash:a(o),text:o,expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:o.trim().length===0,inlineSolveCount:0});}for(let o of a$1)this.dirtyLineIds.add(o);let l=this.orderTree.spliceAt(i,s.deleteCount,a$1);for(let o of l)n.push(o),this.lines.delete(o),this.dirtyLineIds.delete(o);}return this._positionCache=null,{inserted:t,removed:n}}insertLines(e,t){let n={startLine:e,deleteCount:0,insertLines:t};return this.applyChanges([n]).inserted}deleteLines(e,t){let n={startLine:e,deleteCount:t-e+1,insertLines:[]};return this.applyChanges([n]).removed}editLine(e,t){let n=this.getLineAt(e);if(!n)return false;let r=a(t);return r===n.textHash?false:(n.text=t,n.textHash=r,n.expressions=[],n.bytecodes=[],n.results=[],n.result=null,n.inlineSolveCount=0,n.dirty=true,this.dirtyLineIds.add(n.lineId),n.isEmpty=t.trim().length===0,true)}getLineAt(e){let t=e-1,n=this.orderTree.getAt(t);if(n!==void 0)return this.lines.get(n)}getLinePosition(e){if(this._positionCache)return this._positionCache.get(e)??-1;this._positionCache=new Map;let t=1;for(let n of this.orderTree)this._positionCache.set(n,t++);return this._positionCache.get(e)??-1}getVisibleLines(e,t){let n=this.orderTree.getRange(e-1,t-1),r=[];for(let s of n){let i=this.lines.get(s);i&&r.push(i);}return r}getAllLines(){return this.getVisibleLines(1,this.lineCount)}getLineById(e){return this.lines.get(e)}getDirtyLines(){let e=[];for(let t of this.lines.values())t.dirty&&e.push(t);return e}hasAnyDirtyLineBefore(e){for(let t of this.dirtyLineIds){let n=this.getLinePosition(t);if(n>=1&&n<e)return true}return false}hasAnyDirtyVariableDefLineBefore(e){for(let t of this.dirtyLineIds){let n=this.lines.get(t);if(!n||!n.isVariableDef)continue;let r=this.getLinePosition(t);if(r>=1&&r<e)return true}return false}get dirtyCount(){return this.dirtyLineIds.size}isBytecodeValid(e,t){let n=this.lines.get(e);return n!==void 0&&n.textHash===t}markClean(e){let t=this.lines.get(e);t&&(t.dirty=false,this.dirtyLineIds.delete(e));}markDirtyByLineNumber(e){let t=this.getLineAt(e);t&&(t.dirty=true,this.dirtyLineIds.add(t.lineId));}markDirty(e){let t=this.lines.get(e);t&&(t.dirty=true,this.dirtyLineIds.add(e));}invalidateAll(){for(let e of this.lines.values())e.dirty=true;this.dirtyLineIds=new Set(this.lines.keys());}updateLineResult(e,t,n,r,s,i,a,l=0){let o=this.lines.get(e);o&&(o.results=t,o.result=t[0]?.[0]??null,o.bytecodes=n,o.expressions=r,o.reads=s,o.writes=i,o.isVariableDef=a,o.inlineSolveCount=l,o.dirty=false,this.dirtyLineIds.delete(e));}updateLineCompiled(e,t,n,r,s,i,a=0){let l=this.lines.get(e);l&&(l.expressions=t,l.bytecodes=n,l.reads=r,l.writes=s,l.isVariableDef=i,l.inlineSolveCount=a);}get lineCount(){return this.orderTree.length}get isEmpty(){return this.orderTree.isEmpty}*[Symbol.iterator](){for(let e of this.orderTree){let t=this.lines.get(e);t&&(yield t);}}clear(){this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.nextLineId=1;}toJSON(){return {lineCount:this.lineCount,lines:this.getAllLines().map(e=>({lineId:e.lineId,text:e.text.substring(0,80),textHash:e.textHash,dirty:e.dirty,isVariableDef:e.isVariableDef,isEmpty:e.isEmpty,hasBytecode:e.bytecodes.length>0,hasResult:e.results.length>0,inlineSolveCount:e.inlineSolveCount,reads:e.reads,writes:e.writes}))}}};var A=class{constructor(){this.worker=null;this.nextId=1;this.pending=new Map;}ensureWorker(){return this.worker?this.worker:(this.worker=g(),this.worker.onmessage=e=>{let t=e.data;if(!t||t.type!=="COMPILE_RESULT")return;let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id);let r=[];for(let s of t.results)r.push(this.reconstructResult(s));n.resolve(r);},this.worker.onerror=e=>{for(let[t,n]of this.pending)n.reject(new Error(`Compilation worker error: ${e.message}`)),this.pending.delete(t);},this.worker)}async compileBatch(e){if(e.length===0)return [];let t=this.ensureWorker(),n=this.nextId++;return new Promise((r,s)=>{this.pending.set(n,{resolve:r,reject:s}),t.postMessage({type:"COMPILE_BATCH",id:n,items:e});})}storeResults(e,t){let n=new Map;for(let i of e){if(i.error)continue;let a=t.getLineById(i.lineId);if(!a||a.textHash!==i.compiledAgainstHash)continue;let l=n.get(i.lineId);l||(l={bytecodes:[],reads:new Set,writes:new Set,isVariableDef:false,expressions:a.expressions.length>0?[...a.expressions]:[],textHash:i.compiledAgainstHash},n.set(i.lineId,l)),l.bytecodes.push(i.program);for(let o of i.reads)l.reads.add(o);for(let o of i.writes)l.writes.add(o);i.isVariableDef&&(l.isVariableDef=true);}let s=0;for(let[i,a]of n){if(a.bytecodes.length===0)continue;let o=t.getLineById(i)?.inlineSolveCount??0;t.updateLineCompiled(i,a.expressions,a.bytecodes,[...a.reads],[...a.writes],a.isVariableDef,o),s+=a.bytecodes.length;}return s}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.pending.clear());}get isActive(){return this.worker!==null}reconstructResult(e){if(e.error)return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},reads:[],writes:[],isVariableDef:false,error:e.error};let t=e.opcodesLength>0?new Uint8Array(e.opcodesBuffer,0,e.opcodesLength):new Uint8Array(0),n=e.numbersLength>0?new Float64Array(e.numbersBuffer,0,e.numbersLength):new Float64Array(0),r={opcodes:t,numbers:n,strings:e.strings,hasAsync:false};return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:r,reads:e.reads,writes:e.writes,isVariableDef:e.isVariableDef,error:null}}};var O=128,R=3,J=6,Z=2,Q=R,P=class u{constructor(){this.lastViewportStart=null;this.savedDirection=null;this.pageAccess=new Map;this.accessSeq=0;}static pageForLine(e){return Math.floor((e-1)/O)}static pageRange(e,t){return {startLine:e*O+1,endLine:Math.min((e+1)*O,t)}}detectDirection(e){return this.lastViewportStart===null?null:e.startLine>this.lastViewportStart?"down":e.startLine<this.lastViewportStart?"up":null}maintainAfterEval(e,t){this.savedDirection=this.detectDirection(e),this.lastViewportStart=e.startLine;let n=t.lineCount,r=u.pageForLine(e.startLine),s=u.pageForLine(e.endLine),i=u.pageForLine(n),a=Math.max(0,r-R),l=Math.min(i,s+R),o=Math.max(0,r-J),c=Math.min(i,s+J);for(let p=a;p<=l;p++)this.touchPage(p);for(let p=o;p<=c;p++)p>=a&&p<=l||this.evictPageResults(p,t,n);let d=o-1,h=Math.max(0,d-Q+1);for(let p=h;p<=d;p++)this.evictPageBytecode(p,t,n);let f=c+1,g=Math.min(i,f+Q-1);for(let p=f;p<=g;p++)this.evictPageBytecode(p,t,n);}getPreloadTargets(e,t){let n=this.savedDirection;if(!n)return [];let r=[],s=u.pageForLine(e.endLine),i=u.pageForLine(e.startLine),a=u.pageForLine(t.lineCount),l=[];if(n==="down"){let o=s+R+1,c=Math.min(o+Z-1,a);for(let d=o;d<=c&&d<=a;d++)l.push(d);}else {let o=i-R-1;for(let c=o;c>o-Z&&c>=0;c--)l.push(c);}for(let o of l){let c=u.pageRange(o,t.lineCount);for(let d=c.startLine;d<=c.endLine;d++){let h=t.getLineAt(d);if(h&&h.dirty&&!(h.bytecodes.length>0&&!h.isVariableDef)&&!h.isEmpty)if(h.expressions.length>0)for(let f of h.expressions)f.trim()&&r.push({lineId:h.lineId,expression:f,textHash:h.textHash});else {let f=c$1.findInlineSolves(h.text);if(f.length>0)for(let g of f)g.expression.trim()&&r.push({lineId:h.lineId,expression:g.expression,textHash:h.textHash});else {let g=h.text.trim();g&&r.push({lineId:h.lineId,expression:g,textHash:h.textHash});}}}}return r}clear(){this.pageAccess.clear(),this.accessSeq=0,this.lastViewportStart=null,this.savedDirection=null;}touchPage(e){this.pageAccess.set(e,++this.accessSeq);}evictPageResults(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);i&&!i.isVariableDef&&i.results.length>0&&(i.results=[],i.result=null);}}evictPageBytecode(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);!i||i.isVariableDef||(i.bytecodes.length>0||i.results.length>0)&&(i.bytecodes=[],i.results=[],i.result=null,t.markDirty(i.lineId));}}};var X=(r=>(r[r.Tier1=1]="Tier1",r[r.Tier2=2]="Tier2",r[r.Tier3=3]="Tier3",r[r.Skipped=0]="Skipped",r))(X||{}),F=class{constructor(e,t,n){this.compilationWorker=null;this.globalUnsubscribe=null;this.doc=e,this.engine=t,this.dag=t.getDag(),this.checkpointer=n??null,this.pageManager=new P,this.engine.setDocumentModel(this.doc),this.globalUnsubscribe=J$1.subscribe(r=>{for(let s of this.dag.getAffectedLines(K(r)))this.doc.markDirtyByLineNumber(s);});}evaluate(e,t){this.engine.setKeystrokeSignal(t??null),h();try{this.reseedAccumulators();let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(e.endLine,i);for(let l=1;l<=a;l++){let o=this.doc.getLineAt(l);if(!o){s.skipped++;continue}let c=l>=e.startLine&&l<=e.endLine,d=this.evaluateSingleLine(o,l,c);n.push(d),d.tier===1?s.tier1++:d.tier===2?s.tier2++:d.tier===3?s.tier3++:s.skipped++,d.results&&c&&r.set(l,d.results.flat());}return this.pageManager.maintainAfterEval(e,this.doc),{lines:n,resultMap:r,tierCounts:s}}finally{this.engine.setKeystrokeSignal(null),i();}}backgroundCompile(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef)continue;let a=this.evaluateSingleLine(i,s,false);t.push(a);}return t}dispatchBackgroundCompiles(e){let t=this.collectInvisibleCompileTargets(e);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}terminateWorker(){this.compilationWorker&&(this.compilationWorker.terminate(),this.compilationWorker=null),this.globalUnsubscribe&&(this.globalUnsubscribe(),this.globalUnsubscribe=null);}getDoc(){return this.doc}evaluateAll(e){let t={startLine:1,endLine:this.doc.lineCount};return this.evaluate(t,e)}setViewport(e,t){if(this.engine.setKeystrokeSignal(t??null),e.startLine>1&&this.hasDirtyLinesBefore(e.startLine))return this.checkpointer?.clear(),this.evaluate(e,t);this.pageManager.maintainAfterEval(e,this.doc),this.preloadNextPages(e),this.restoreTo(e.startLine-1),h();try{return this.collectEvalResults(e.startLine,e.endLine)}finally{this.engine.setKeystrokeSignal(null),i();}}applyTransaction(e){let t=new Set;for(let s of e)for(let i=0;i<s.deleteCount;i++){let a=s.startLine+i,l=this.dag.getWrites(a);for(let o of l)t.add(o);this.dag.removeLine(a),this.engine.getLineCache().removeAllForLine(a);}let n=new Set;for(let s of t){let i=this.dag.getAffectedLines(s);for(let a of i){let l=this.doc.getLineAt(a);l&&n.add(l.lineId);}}let r=this.doc.applyChanges(e);this.checkpointer?.clear();for(let s of n)this.doc.markDirty(s);return this.dag.clear(),{inserted:r.inserted,removed:r.removed}}reseedAccumulators(){let e=this.engine.resetAccumulators();if(e.size===0)return;let t=this.doc.lineCount;for(let n=1;n<=t;n++){let r=this.dag.getWrites(n);if(r.size!==0){for(let s of r)if(e.has(s)){this.doc.markDirtyByLineNumber(n);break}}}}collectEvalResults(e,t){let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(t,i);for(let l=e;l<=a;l++){let o=this.doc.getLineAt(l);if(!o)continue;let c=this.evaluateSingleLine(o,l,true);n.push(c),c.tier===1?s.tier1++:c.tier===2?s.tier2++:c.tier===3?s.tier3++:s.skipped++,c.results&&r.set(l,c.results.flat());}return {lines:n,resultMap:r,tierCounts:s}}hasDirtyLinesBefore(e){return this.doc.hasAnyDirtyVariableDefLineBefore(e)}evaluateSingleLine(e,t,n){let r={lineId:e.lineId,lineNumber:t};if(e.isEmpty||l(e.text))return e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null};let{expressions:s,inlineSolveCount:i}=this.extractExpressions(e);return s.length===0?(e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null}):e.dirty?n?this.evaluateTier1(e,t,s,i,r):e.bytecodes.length>0&&e.bytecodes.length===s.length&&!e.isVariableDef?{...r,tier:0,result:null,error:null}:this.evaluateTier3(e,t,s,i,r):n&&e.bytecodes.length>0?this.evaluateTier2(e,t,r):{...r,tier:0,result:null,error:null}}evaluateTier1(e,t,n,r,s){let i=[],a=[],l=new Set,o=new Set,c=false,d=null,h=null,f=false,g=false;for(let b of n){if(!b.trim())continue;let y=null,L;try{let m=this.engine.evaluateLine(t,b);y=[m],d=m,L=this.engine.getLineCache().get(t,b);}catch(m){let S=m instanceof Error?m.message:String(m);h||(h=S),f=true,y=null;}if(y&&y.some(m=>m.type===12)&&(g=true),y?i.push(y):i.push([N$1("eval_failed",h??"unknown error")]),L){a.push(L.bytecode);for(let m of L.readVariables)l.add(m);L.writeVariable&&(o.add(L.writeVariable),c=true);}else try{let{program:m,reads:S,writes:I}=this.engine.compileExpression(b);a.push(m);for(let x of S)l.add(x);for(let x of I)o.add(x);I.length>0&&(c=!0);}catch(m){if(a.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),m instanceof b$2&&m.context){let S=m.context.reads,I=m.context.writes;if(Array.isArray(S))for(let x of S)l.add(x);if(Array.isArray(I))for(let x of I)o.add(x);}}}let p=[...l],v=[...o];return f||g?(this.doc.updateLineCompiled(e.lineId,n,a,p,v,c,r),e.results=i,e.result=i[0]?.[0]??null,e.inlineSolveCount=r,e.expressions=n):this.doc.updateLineResult(e.lineId,i,a,n,p,v,c,r),this.dag.registerLine(t,p,v),this.checkpointer&&v.length>0&&!f&&!g&&this.checkpointer.snapshot(t,e.lineId,v),{...s,tier:1,result:d,results:i,error:h}}evaluateTier2(e,t,n){if(e.bytecodes.length===0)return {...n,tier:0,result:null,error:null};let r=[],s=null,i=null,a=false;for(let l of e.bytecodes)if(l.opcodes.length!==0)try{let o=this.engine.executeCached(l,t);s=o,r.push([o]);}catch(o){let c=o instanceof Error?o.message:String(o);i||(i=c),a=true,r.push([N$1("exec_failed",c)]);}return this.dag.registerLine(t,e.reads,e.writes),e.results=r,e.result=r[0]?.[0]??null,a&&this.doc.markDirty(e.lineId),{...n,tier:2,result:s,results:r,error:i}}evaluateTier3(e,t,n,r,s){let i=[],a=new Set,l=new Set,o=false,c=null,d=null,h=false,f=false;for(let v of n)if(v.trim())try{let{program:b,reads:y,writes:L}=this.engine.compileExpression(v);i.push(b);for(let m of y)a.add(m);for(let m of L)l.add(m);L.length>0&&(o=!0),L.length>0&&b.opcodes.length>0&&(c=this.engine.executeCached(b,t),c&&c.type===12&&(f=!0));}catch(b){let y=b instanceof Error?b.message:String(b);d||(d=y),h=true,i.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false});}let g=[...a],p=[...l];return this.doc.updateLineCompiled(e.lineId,n,i,g,p,o,r),this.dag.registerLine(t,g,p),o&&c&&!h&&!f&&(e.results=[[c]],e.result=c,this.doc.markClean(e.lineId),this.checkpointer&&this.checkpointer.snapshot(t,e.lineId,p)),{...s,tier:3,result:c,results:o&&c&&!h&&!f?[[c]]:void 0,error:d}}restoreTo(e){this.checkpointer&&this.checkpointer.restoreTo(e);}getCheckpointer(){return this.checkpointer}getPageManager(){return this.pageManager}preloadNextPages(e){let t=this.pageManager.getPreloadTargets(e,this.doc);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}collectInvisibleCompileTargets(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef||i.isEmpty||l(i.text))continue;let{expressions:a}=this.extractExpressions(i);if(a.length!==0)for(let l of a)l.trim()&&t.push({lineId:i.lineId,expression:l,textHash:i.textHash});}return t}extractExpressions(e){if(e.expressions.length>0)return {expressions:e.expressions,inlineSolveCount:e.inlineSolveCount};let t=e.text.trim();if(t.length===0)return {expressions:[],inlineSolveCount:0};let n=c$1.findInlineSolves(e.text);return n.length>0?{expressions:n.map(r=>r.expression),inlineSolveCount:n.length}:{expressions:[t],inlineSolveCount:0}}};export{N as a,X as b,F as c};//# sourceMappingURL=chunk-JSPKKNPQ.js.map
3
- //# sourceMappingURL=chunk-JSPKKNPQ.js.map