solve-engine 2.32.0 → 2.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{EngineError-CqGtaT_v.d.cts → EngineError-Bm4OYmw8.d.cts} +6 -0
- package/dist/{EngineError-CqGtaT_v.d.ts → EngineError-Bm4OYmw8.d.ts} +6 -0
- package/dist/{Lexer-CqFjYoRA.d.ts → Lexer-DPn5dfCH.d.ts} +1 -13
- package/dist/{Lexer-sCI05tqO.d.cts → Lexer-DaWkCu84.d.cts} +1 -13
- package/dist/{PackageCompatibility-phvSFP4f.d.ts → PackageCompatibility-CkzZfoJ3.d.ts} +1 -1
- package/dist/{PackageCompatibility-Bn-T_xKW.d.cts → PackageCompatibility-E_5GtcQW.d.cts} +1 -1
- package/dist/{PackageRegistry-C78jVkI9.d.ts → PackageRegistry-DSqic8kz.d.ts} +132 -23
- package/dist/{PackageRegistry-B-C1duZw.d.cts → PackageRegistry-js47hr28.d.cts} +132 -23
- package/dist/{Parselet-Dgymjxzd.d.ts → Parselet-CQjcHOKw.d.ts} +13 -6
- package/dist/{Parselet-DF3864la.d.cts → Parselet-s1sRRn8H.d.cts} +13 -6
- package/dist/{TokenNormalizer-Pe3_390t.d.cts → TokenNormalizer-D382VSYh.d.cts} +4 -1
- package/dist/{TokenNormalizer-IF7nPRMp.d.ts → TokenNormalizer-DAzPp-j1.d.ts} +4 -1
- package/dist/{VMBuiltins-BkKzhj6C.d.cts → VMBuiltins-JCavlQUj.d.cts} +53 -18
- package/dist/{VMBuiltins-Du9y8sEo.d.ts → VMBuiltins-qgzA6qGi.d.ts} +53 -18
- package/dist/{VMCheckpoints-WdUQrdc9.d.cts → VMCheckpoints-BxPzmdu0.d.cts} +2 -2
- package/dist/{VMCheckpoints-gvy_yxYh.d.ts → VMCheckpoints-DjjE92mf.d.ts} +2 -2
- package/dist/{Value-BYHw-x7q.d.cts → Value-2TIKi-YL.d.cts} +19 -0
- package/dist/{Value-BYHw-x7q.d.ts → Value-2TIKi-YL.d.ts} +19 -0
- package/dist/{WorkerError-DTrl3Jag.d.ts → WorkerError-BaN8_eok.d.ts} +1 -1
- package/dist/{WorkerError-CRoM8Ju1.d.cts → WorkerError-CexHHmbb.d.cts} +1 -1
- package/dist/{chunk-IJE4AEDX.js → chunk-24OW3AAU.js} +3 -3
- package/dist/{chunk-IJE4AEDX.js.map → chunk-24OW3AAU.js.map} +1 -1
- package/dist/{chunk-CAJTDZ5B.cjs → chunk-2XOLAHW6.cjs} +2 -2
- package/dist/{chunk-CAJTDZ5B.cjs.map → chunk-2XOLAHW6.cjs.map} +1 -1
- package/dist/{chunk-AGCNMEP2.cjs → chunk-3MG7VIPL.cjs} +2 -2
- package/dist/{chunk-AGCNMEP2.cjs.map → chunk-3MG7VIPL.cjs.map} +1 -1
- package/dist/chunk-4ASM522I.js +2 -0
- package/dist/chunk-4ASM522I.js.map +1 -0
- package/dist/{chunk-KH4QXKLT.js → chunk-4MD5L23F.js} +2 -2
- package/dist/{chunk-KH4QXKLT.js.map → chunk-4MD5L23F.js.map} +1 -1
- package/dist/{chunk-IQVSCL2R.js → chunk-4XWZXP6I.js} +3 -3
- package/dist/{chunk-IQVSCL2R.js.map → chunk-4XWZXP6I.js.map} +1 -1
- package/dist/{chunk-RELMEWY6.js → chunk-6G2NES2I.js} +2 -2
- package/dist/chunk-6G2NES2I.js.map +1 -0
- package/dist/{chunk-CDE2ZUGG.js → chunk-6NL7RBAG.js} +2 -2
- package/dist/{chunk-CDE2ZUGG.js.map → chunk-6NL7RBAG.js.map} +1 -1
- package/dist/{chunk-SUAGBRQ7.cjs → chunk-6SYU4MH7.cjs} +2 -2
- package/dist/chunk-6SYU4MH7.cjs.map +1 -0
- package/dist/chunk-72J5V7SN.cjs +2 -0
- package/dist/chunk-72J5V7SN.cjs.map +1 -0
- package/dist/{chunk-TSJ4RQLZ.js → chunk-AENL3Z66.js} +2 -2
- package/dist/{chunk-TSJ4RQLZ.js.map → chunk-AENL3Z66.js.map} +1 -1
- package/dist/chunk-APYRNAU2.js +2 -0
- package/dist/chunk-APYRNAU2.js.map +1 -0
- package/dist/{chunk-AXTYQFIV.cjs → chunk-D7URPV5Z.cjs} +3 -3
- package/dist/{chunk-AXTYQFIV.cjs.map → chunk-D7URPV5Z.cjs.map} +1 -1
- package/dist/chunk-DB5ISONG.js +2 -0
- package/dist/chunk-DB5ISONG.js.map +1 -0
- package/dist/chunk-DGDVY6XI.js +3 -0
- package/dist/chunk-DGDVY6XI.js.map +1 -0
- package/dist/chunk-EOKHRS2T.js +2 -0
- package/dist/chunk-EOKHRS2T.js.map +1 -0
- package/dist/{chunk-NQFCXLEF.js → chunk-EOO6M65F.js} +2 -2
- package/dist/{chunk-NQFCXLEF.js.map → chunk-EOO6M65F.js.map} +1 -1
- package/dist/{chunk-A764BY7L.cjs → chunk-EQNKDTMX.cjs} +2 -2
- package/dist/{chunk-A764BY7L.cjs.map → chunk-EQNKDTMX.cjs.map} +1 -1
- package/dist/chunk-FESR6PZI.cjs +2 -0
- package/dist/chunk-FESR6PZI.cjs.map +1 -0
- package/dist/chunk-G2LCDR52.cjs +3 -0
- package/dist/chunk-G2LCDR52.cjs.map +1 -0
- package/dist/chunk-G5TZ6TDA.js +2 -0
- package/dist/chunk-G5TZ6TDA.js.map +1 -0
- package/dist/chunk-GDLYXRMA.cjs +2 -0
- package/dist/chunk-GDLYXRMA.cjs.map +1 -0
- package/dist/{chunk-7DJYS5PO.cjs → chunk-HSTGWWU2.cjs} +2 -2
- package/dist/{chunk-7DJYS5PO.cjs.map → chunk-HSTGWWU2.cjs.map} +1 -1
- package/dist/{chunk-OE2DBN4K.js → chunk-INMJ7ZXL.js} +2 -2
- package/dist/chunk-INMJ7ZXL.js.map +1 -0
- package/dist/chunk-ITH2RLRG.js +5 -0
- package/dist/chunk-ITH2RLRG.js.map +1 -0
- package/dist/{chunk-5AKT36UK.cjs → chunk-K3PZ66XR.cjs} +2 -2
- package/dist/{chunk-5AKT36UK.cjs.map → chunk-K3PZ66XR.cjs.map} +1 -1
- package/dist/chunk-LI6LYJDA.cjs +2 -0
- package/dist/chunk-LI6LYJDA.cjs.map +1 -0
- package/dist/{chunk-WQGHJAW2.cjs → chunk-M4UC2PB6.cjs} +2 -2
- package/dist/{chunk-WQGHJAW2.cjs.map → chunk-M4UC2PB6.cjs.map} +1 -1
- package/dist/chunk-O7HF345B.js +2 -0
- package/dist/chunk-O7HF345B.js.map +1 -0
- package/dist/{chunk-CM2WM5CM.cjs → chunk-OBZJKZ2F.cjs} +2 -2
- package/dist/{chunk-CM2WM5CM.cjs.map → chunk-OBZJKZ2F.cjs.map} +1 -1
- package/dist/{chunk-Q7TBBV62.cjs → chunk-P5YWBIIU.cjs} +2 -2
- package/dist/chunk-P5YWBIIU.cjs.map +1 -0
- package/dist/chunk-PICFFFJV.js +3 -0
- package/dist/chunk-PICFFFJV.js.map +1 -0
- package/dist/{chunk-P43SV4NJ.cjs → chunk-QOOTRUY7.cjs} +3 -3
- package/dist/{chunk-P43SV4NJ.cjs.map → chunk-QOOTRUY7.cjs.map} +1 -1
- package/dist/chunk-R3W53ZMP.cjs +2 -0
- package/dist/chunk-R3W53ZMP.cjs.map +1 -0
- package/dist/chunk-RMDCGYZM.js +2 -0
- package/dist/chunk-RMDCGYZM.js.map +1 -0
- package/dist/{chunk-CB3EXUM2.js → chunk-RU3KGJRA.js} +2 -2
- package/dist/chunk-RU3KGJRA.js.map +1 -0
- package/dist/chunk-S3SPDK6N.cjs +2 -0
- package/dist/chunk-S3SPDK6N.cjs.map +1 -0
- package/dist/chunk-SF5QVUEI.cjs +3 -0
- package/dist/chunk-SF5QVUEI.cjs.map +1 -0
- package/dist/{chunk-FXB5GCBT.js → chunk-TJKN466F.js} +2 -2
- package/dist/{chunk-FXB5GCBT.js.map → chunk-TJKN466F.js.map} +1 -1
- package/dist/{chunk-VLX7ZVK4.js → chunk-U5MESNRT.js} +2 -2
- package/dist/{chunk-VLX7ZVK4.js.map → chunk-U5MESNRT.js.map} +1 -1
- package/dist/chunk-WCVPXBCW.cjs +5 -0
- package/dist/chunk-WCVPXBCW.cjs.map +1 -0
- package/dist/{chunk-YWF6C2IO.cjs → chunk-WFT3XUSH.cjs} +2 -2
- package/dist/{chunk-YWF6C2IO.cjs.map → chunk-WFT3XUSH.cjs.map} +1 -1
- package/dist/{chunk-3ZGFAE3Q.js → chunk-X2GQAKL2.js} +2 -2
- package/dist/{chunk-3ZGFAE3Q.js.map → chunk-X2GQAKL2.js.map} +1 -1
- package/dist/{chunk-G3POUURF.js → chunk-YID47OPR.js} +2 -2
- package/dist/{chunk-G3POUURF.js.map → chunk-YID47OPR.js.map} +1 -1
- package/dist/chunk-YV4GDW5A.cjs +2 -0
- package/dist/chunk-YV4GDW5A.cjs.map +1 -0
- package/dist/chunk-ZSXQP7PD.cjs +2 -0
- package/dist/chunk-ZSXQP7PD.cjs.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +10 -10
- package/dist/engine.d.ts +10 -10
- package/dist/engine.js +1 -1
- package/dist/engine.worker.cjs +1 -1
- package/dist/engine.worker.cjs.map +1 -1
- package/dist/engine.worker.js +1 -1
- package/dist/engine.worker.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +9 -9
- package/dist/language.d.ts +9 -9
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +3 -3
- package/dist/lexer.d.ts +3 -3
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.d.cts +2 -2
- package/dist/normalizer.d.ts +2 -2
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +8 -8
- package/dist/packages.d.ts +8 -8
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +3 -3
- package/dist/parser.d.ts +3 -3
- package/dist/parser.js +1 -1
- package/dist/{pipeline-BYkKNpql.d.cts → pipeline-Bum6y1B9.d.cts} +1 -1
- package/dist/{pipeline-Cl7KW8CB.d.ts → pipeline-DOo3KHaq.d.ts} +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +69 -3
- package/dist/resolvers.d.ts +69 -3
- package/dist/resolvers.js +1 -1
- package/dist/temporal.cjs +1 -1
- package/dist/temporal.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +9 -9
- package/dist/testing.d.ts +9 -9
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +35 -2
- package/dist/uom.d.ts +35 -2
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +6 -6
- package/dist/vm.d.ts +6 -6
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +9 -9
- package/dist/worker.d.ts +9 -9
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4DR5RBHQ.cjs +0 -2
- package/dist/chunk-4DR5RBHQ.cjs.map +0 -1
- package/dist/chunk-4IC5OARK.js +0 -3
- package/dist/chunk-4IC5OARK.js.map +0 -1
- package/dist/chunk-7ODHPWQC.js +0 -5
- package/dist/chunk-7ODHPWQC.js.map +0 -1
- package/dist/chunk-A755LVPT.cjs +0 -2
- package/dist/chunk-A755LVPT.cjs.map +0 -1
- package/dist/chunk-AF6NDOIE.js +0 -2
- package/dist/chunk-AF6NDOIE.js.map +0 -1
- package/dist/chunk-B2NL65FI.js +0 -2
- package/dist/chunk-B2NL65FI.js.map +0 -1
- package/dist/chunk-CB3EXUM2.js.map +0 -1
- package/dist/chunk-DUFEONVN.cjs +0 -3
- package/dist/chunk-DUFEONVN.cjs.map +0 -1
- package/dist/chunk-IJHL3LMH.js +0 -2
- package/dist/chunk-IJHL3LMH.js.map +0 -1
- package/dist/chunk-LCYQQFUH.cjs +0 -2
- package/dist/chunk-LCYQQFUH.cjs.map +0 -1
- package/dist/chunk-LP3JYC3A.js +0 -2
- package/dist/chunk-LP3JYC3A.js.map +0 -1
- package/dist/chunk-OE2DBN4K.js.map +0 -1
- package/dist/chunk-OKKGPINQ.cjs +0 -5
- package/dist/chunk-OKKGPINQ.cjs.map +0 -1
- package/dist/chunk-OM7NOHJF.cjs +0 -2
- package/dist/chunk-OM7NOHJF.cjs.map +0 -1
- package/dist/chunk-PTXUWGRR.js +0 -3
- package/dist/chunk-PTXUWGRR.js.map +0 -1
- package/dist/chunk-Q7TBBV62.cjs.map +0 -1
- package/dist/chunk-RELMEWY6.js.map +0 -1
- package/dist/chunk-SFM4XFGJ.js +0 -2
- package/dist/chunk-SFM4XFGJ.js.map +0 -1
- package/dist/chunk-SRAU3BLV.cjs +0 -3
- package/dist/chunk-SRAU3BLV.cjs.map +0 -1
- package/dist/chunk-SUAGBRQ7.cjs.map +0 -1
- package/dist/chunk-UNKZ5XRC.cjs +0 -2
- package/dist/chunk-UNKZ5XRC.cjs.map +0 -1
- package/dist/chunk-WU7SBKVU.cjs +0 -2
- package/dist/chunk-WU7SBKVU.cjs.map +0 -1
- package/dist/chunk-X5K72MBV.js +0 -2
- package/dist/chunk-X5K72MBV.js.map +0 -1
- package/dist/chunk-ZVPZQ66D.cjs +0 -2
- package/dist/chunk-ZVPZQ66D.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-APYRNAU2.js';import {c}from'./chunk-FAO6DQ74.js';import {c as c$1}from'./chunk-6G2NES2I.js';var N=32,_=2;function I(a){return a.shape!==void 0?a.shape:a.startTokenTypes!==void 0?[{types:a.startTokenTypes}]:[]}var x=class{constructor(e){this.rules=e;let r=e.length,t=Math.max(1,Math.ceil(r/N));this.words=t,this.scratch=new Uint32Array(t);let s=e.map(I),n=0;for(let l of s)for(let c$1 of l)for(let p of c$1.types??[])n=Math.max(n,c(p));this.typeRows=n+1;let i=0;for(let l of s)i=Math.max(i,l.length);i=Math.min(i,_),this.allRules=new Uint32Array(t);for(let l=0;l<r;l++)this.allRules[l/N|0]|=1<<l%N;let u=[];for(let l=0;l<i;l++)u.push(this.buildPlane(s,l,t));this.planes=u;}buildPlane(e,r,t){let s={byType:new Uint32Array(this.typeRows*t),typeAny:new Uint32Array(t),atEnd:new Uint32Array(t),typeHasValues:new Uint8Array(this.typeRows),byValue:new Map,valueAny:new Uint32Array(t)};for(let n=0;n<e.length;n++){let i=e[n][r],u=n/N|0,l=1<<n%N,c$1=i?.types;if(c$1===void 0)s.typeAny[u]|=l,s.atEnd[u]|=l;else for(let d of c$1)s.byType[c(d)*t+u]|=l;let p=i?.values;if(p===void 0)s.valueAny[u]|=l;else {for(let d of p){let h=d.toLowerCase(),o=s.byValue.get(h);o===void 0&&(o=new Uint32Array(t),s.byValue.set(h,o)),o[u]|=l;}if(c$1===void 0)s.typeHasValues.fill(1);else for(let d of c$1){let h=c(d);h<this.typeRows&&(s.typeHasValues[h]=1);}}}return s}get size(){return this.rules.length}get depth(){return this.planes.length}candidates(e,r){let t=this.words,s=this.scratch,n=this.planes,i=e.length;if(n.length===0)return s.set(this.allRules),s;for(let u=0;u<n.length;u++){let l=n[u],c=r+u;if(c>=i){if(u===0)s.set(l.atEnd);else for(let o=0;o<t;o++)s[o]&=l.atEnd[o];continue}let p=e[c],d=p.typeId,h=d>=0&&d<this.typeRows?d*t:-1;if(u===0)if(h>=0)for(let o=0;o<t;o++)s[o]=l.byType[h+o]|l.typeAny[o];else s.set(l.typeAny);else if(h>=0)for(let o=0;o<t;o++)s[o]&=l.byType[h+o]|l.typeAny[o];else for(let o=0;o<t;o++)s[o]&=l.typeAny[o];if(h>=0&&l.typeHasValues[d]===1){let o=p.value,R=z(o)?o.toLowerCase():o,g=l.byValue.get(R);for(let T=0;T<t;T++)s[T]&=(g===void 0?0:g[T])|l.valueAny[T];}if(k(s))return s}return s}};function k(a){for(let e=0;e<a.length;e++)if(a[e]!==0)return false;return true}function z(a){for(let e=0;e<a.length;e++){let r=a.charCodeAt(e);if(r>=65&&r<=90||r>=128)return true}return false}function v(a){return z(a)?a.toLowerCase():a}var B={maxPasses:100,maxTokens:1e4,onFusion:()=>{},ignoreRuleIndex:false};function M(a$1,e,r){let t=r[0],s=r[r.length-1],n=new a(a$1,c(a$1),e,e,t.offset,t.lineBreaks??0,t.line,t.col);return n.sourceEnd=s.sourceEnd??s.offset+s.text.length,n}function P(a,e){let r=e[e.length-1];r&&(a.sourceEnd=r.sourceEnd??r.offset+r.text.length);}var D=["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"],U=(()=>{let a=D.map(t=>c(t)),e=Math.max(...a)+1,r=new Uint8Array(e);for(let t of a)r[t]=1;return r})(),L=new Set;function F(a){a.shape!==void 0&&a.shape.length>0||a.startTokenTypes===void 0&&a.unshapedReason===void 0&&(L.has(a.name)||(L.add(a.name),console.warn(`[TokenNormalizer] Rule "${a.name}" declares no \`shape\`, so it is tried at every token of every line and slows down documents that never use it. Declare the tokens it can start at, e.g. shape: [{ types: ["IDENT"], values: ["myword"] }, { types: ["LPAREN"] }]. If it genuinely cannot be described that way, set \`unshapedReason\` to say why and this warning will stop.`)));}var O=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.ruleIndexCache=null;this.candidateBuffer=[];this.normalizeCalls=0;this.phraseTrie=new w;this.ruleShapesCache=null;this.options={...B,...e};}register(e){F(e),this.rules.push(e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}unregister(e){this.rules=this.rules.filter(r=>r.name!==e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}clear(){this.rules=[],this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null,this.phraseTrie=new w;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,r)=>r.priority-e.priority)),this.sortedRulesCache}getRuleIndex(){return this.ruleIndexCache===null&&(this.ruleIndexCache=new x(this.getSortedRules())),this.ruleIndexCache}rulesAt(e,r){if(e===null)return this.options.ignoreRuleIndex?this.getSortedRules():this.rulesForTokenType(r);let t=this.candidateBuffer;t.length=0;let s=this.getRuleIndex().rules;for(let n=0;n<e.length;n++){let i=e[n]>>>0,u=n*32;for(;i!==0;)(i&1)!==0&&t.push(s[u]),i>>>=1,u++;}return t}rulesForTokenType(e){let r=this.rulesByTokenType.get(e);return r===void 0&&(r=this.getSortedRules().filter(t=>{let s=I(t)[0];return s?.types===void 0||s.types.includes(e)}),this.rulesByTokenType.set(e,r)),r}get ruleCount(){return this.rules.length}getRuleShapes(){if(this.ruleShapesCache!==null)return this.ruleShapesCache;let e=this.getRuleIndex();return this.ruleShapesCache=this.getSortedRules().map(r=>{let t=I(r);return {name:r.name,priority:r.priority,shape:t,unshapedReason:r.unshapedReason,indexedSlots:Math.min(t.length,e.depth)}}),this.ruleShapesCache}getCandidateCounts(e){let r=this.getRuleIndex(),t=[];for(let s=0;s<e.length;s++){let n=r.candidates(e,s),i=0;for(let u=0;u<n.length;u++){let l=n[u]>>>0;for(;l!==0;)i+=l&1,l>>>=1;}t.push(i);}return t}addPhrase(e,r){this.phraseTrie.addPhrase(e,r);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,r){if(e.length===0)return e;let t=r??this.options.onFusion,s=this.options.maxPasses,n=this.options.maxTokens,i=this.normalizeCalls>0;i||(this.normalizeCalls=1);let u=i&&!this.options.ignoreRuleIndex,l=u?this.getRuleIndex():null,c=e,p=true,d=0;for(;p&&d<s;){p=false,d++;let h=null,o=0;for(;o<c.length;){let g=false,T=c[o].typeId;if(T>=U.length||U[T]===0){let m=this.phraseTrie.matchAt(c,o);if(m){let f=c.slice(o,o+m.consumed);h===null&&(h=c.slice(0,o));for(let A of m.replacement)h.push(A);m.consumed>1&&m.replacement.length===1&&(P(m.replacement[0],f),t({rule:m.ruleName??"phrase-trie",sourceTokens:f,fusedToken:m.replacement[0]})),o+=m.consumed,p=true;continue}}let S=u?l.candidates(c,o):null;if(S!==null&&k(S)){h!==null&&h.push(c[o]),o++;continue}for(let m of this.rulesAt(S,c[o].type)){let f=m.match(c,o);if(f){let A=c.slice(o,o+f.consumed);h===null&&(h=c.slice(0,o));for(let b of f.replacement)h.push(b);if(f.consumed>1&&f.replacement.length===1)P(f.replacement[0],A),t({rule:m.name,sourceTokens:A,fusedToken:f.replacement[0]});else if(f.consumed>1&&f.replacement.length<f.consumed)for(let b of f.replacement)t({rule:m.name,sourceTokens:A,fusedToken:b});o+=f.consumed,p=true,g=true;break}}g||(h!==null&&h.push(c[o]),o++);}if(h===null)break;let R=h;if(R.length>n)throw c$1.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${R.length}) exceeds safety limit (${n})`,{tokenCount:R.length,maxTokens:n});c=R;}if(p)throw c$1.validation("NORMALIZER_PASS_LIMIT_EXCEEDED",`Normalization was still changing the token stream after ${s} passes`,{maxPasses:s,tokenCount:c.length});return c}};var w=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,r){let t=e.toLowerCase().trim().split(/\s+/);if(t.length===0||t[0]==="")return;this.startWords.add(t[0]);let s=t[0],n;if(this.root.has(s)?n=this.root.get(s):(n={children:new Map,terminal:null},this.root.set(s,n)),t.length===1){n.terminal={tokenType:r,phrase:e,consumed:1};return}for(let i=1;i<t.length;i++){let u=t[i];n.children.has(u)||n.children.set(u,{children:new Map,terminal:null}),n=n.children.get(u);}n.terminal={tokenType:r,phrase:e,consumed:t.length};}matchAt(e,r){if(r>=e.length)return null;let t=e[r].type;if(t==="TAG"||t.startsWith("TAG_"))return null;let s=v(e[r].value);if(!this.startWords.has(s))return null;let n=this.root.get(s);if(!n)return null;let i=null,u=1;if(n.terminal&&e[r].type!==n.terminal.tokenType){let l=e.slice(r,r+1);i={consumed:1,replacement:[M(n.terminal.tokenType,n.terminal.phrase,l)],ruleName:n.terminal.phrase};}for(let l=r+1;l<e.length&&n?.children;l++){let c=e[l].type;if(c==="TAG"||c.startsWith("TAG_"))break;let p=v(e[l].value);if(n=n.children.get(p),!n)break;if(u++,n.terminal){let d=e.slice(r,r+u);i={consumed:u,replacement:[M(n.terminal.tokenType,n.terminal.phrase,d)],ruleName:n.terminal.phrase};}}return i}get size(){return this.root.size}getAllPhrases(){let e={},r=(t,s)=>{t.terminal&&(e[s.join(" ")]=t.terminal.tokenType);for(let[n,i]of t.children)r(i,[...s,n]);};for(let[t,s]of this.root)r(s,[t]);return e}canStart(e){return this.startWords.has(v(e))}};var W=new Set(["per","a","an","each","every"]),H=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function V(a$1=50,e){let r=e??(t=>H.has(t.toLowerCase()));return {name:"implicit:multiply",priority:a$1,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT","LPAREN","PI","E"]}],match(t,s){if(s+1>=t.length)return null;let n=t[s],i=t[s+1];if(!((n.type==="NUMBER"||n.type==="RPAREN")&&(i.type==="IDENT"||i.type==="LPAREN"||i.type==="PI"||i.type==="E")))return null;let l=i.value.toLowerCase();if(r(l)||W.has(l)&&t[s+2]?.type==="UNIT")return null;let c$1=new a("STAR",c("STAR"),"*","*",i.offset,0,i.line,i.col);return {consumed:1,replacement:[n,c$1]}}}}function se(a,e){let r=[];for(let t=0;t<e;t++){let s=a[t];if(s.type==="LBRACKET")r.push(true);else if(s.type==="LPAREN"){let n=a[t-1],i=!!n&&(n.type==="MAP"||n.type==="REDUCE"||n.type==="SUM_FN"||n.type==="PROD_FN"||n.type==="IDENT"&&(n.value.toLowerCase()==="map"||n.value.toLowerCase()==="reduce"||n.value.toLowerCase()==="sum"||n.value.toLowerCase()==="prod"));r.push(i);}else (s.type==="RBRACKET"||s.type==="RPAREN")&&r.pop();}return r.length>0&&r[r.length-1]}function oe(){return [V()]}export{w as a,M as b,O as c,V as d,se as e,oe as f};//# sourceMappingURL=chunk-DB5ISONG.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-DB5ISONG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/normalizer/RuleIndex.ts","../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":["WORD_BITS","MAX_PLANES","effectiveShape","rule","RuleIndex","sortedRules","n","w","shapes","maxTypeId","shape","slot","t","tokenTypeId","depth","i","planes","k","plane","word","bit","types","values","raw","value","mask","id","tokens","pos","scratch","len","at","token","typeId","base","lowered","hasUpper","named","isEmptyMask","c","lowerCased","DEFAULT_OPTIONS","createFusedToken","type","text","sourceTokens","first","last","LexerToken","recordSourceSpan","fused","NON_WORD_NAMES","NON_WORD_TABLE","ids","table","warnedUnshapedRules","warnIfUnshaped","TokenNormalizer","options","PhraseTrie","ruleName","a","b","buffer","rules","bits","index","list","counts","phrase","tokenType","onFusion","fusionHandler","maxPasses","maxTokens","warmedUp","useIndex","ruleIndex","current","changed","passCount","result","matched","tid","trieMatch","rt","candidates","match","passResult","ErrorFactory","words","firstWord","node","startType","best","contType","collect","path","child","RATE_DENOMINATOR_WORDS","PHRASE_START_WORDS","implicitMultiplyRule","priority","canStart","phraseGuard","next","nextValue","starToken","isInsideRangeContext","safeStack","prev","opensMapReduceCall","createBuiltinNormalizerRules"],"mappings":"mHAiEA,IAAMA,CAAAA,CAAY,EAAA,CAeZC,CAAAA,CAAa,CAAA,CASZ,SAASC,CAAAA,CAAeC,CAAAA,CAA2C,CACzE,OAAIA,CAAAA,CAAK,KAAA,GAAU,MAAA,CAAkBA,EAAK,KAAA,CACtCA,CAAAA,CAAK,eAAA,GAAoB,MAAA,CAAkB,CAAC,CAAE,KAAA,CAAOA,CAAAA,CAAK,eAAgB,CAAC,CAAA,CACxE,EACR,CA8BO,IAAMC,CAAAA,CAAN,KAAgB,CA2BtB,WAAA,CAAYC,CAAAA,CAAwC,CACnD,IAAA,CAAK,KAAA,CAAQA,CAAAA,CACb,IAAMC,CAAAA,CAAID,CAAAA,CAAY,MAAA,CAChBE,CAAAA,CAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAG,IAAA,CAAK,IAAA,CAAKD,EAAIN,CAAS,CAAC,CAAA,CAC9C,IAAA,CAAK,KAAA,CAAQO,CAAAA,CACb,IAAA,CAAK,OAAA,CAAU,IAAI,WAAA,CAAYA,CAAC,CAAA,CAEhC,IAAMC,CAAAA,CAASH,CAAAA,CAAY,GAAA,CAAIH,CAAc,EAOzCO,CAAAA,CAAY,CAAA,CAChB,IAAA,IAAWC,CAAAA,IAASF,CAAAA,CACnB,IAAA,IAAWG,GAAAA,IAAQD,CAAAA,CAClB,IAAA,IAAWE,CAAAA,IAAKD,GAAAA,CAAK,KAAA,EAAS,EAAC,CAAGF,CAAAA,CAAY,IAAA,CAAK,IAAIA,CAAAA,CAAWI,CAAAA,CAAYD,CAAC,CAAC,CAAA,CAGlF,IAAA,CAAK,QAAA,CAAWH,CAAAA,CAAY,EAE5B,IAAIK,CAAAA,CAAQ,CAAA,CACZ,IAAA,IAAWJ,CAAAA,IAASF,CAAAA,CAAQM,CAAAA,CAAQ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AA,EAAcA,CAAAA,CAAE,IAAA,GAAS,QAAA,GAC7CiG,CAAAA,CAAU,GAAA,GAEd,CACA,OAAOA,CAAAA,CAAU,MAAA,CAAS,CAAA,EAAKA,CAAAA,CAAUA,CAAAA,CAAU,MAAA,CAAS,CAAC,CAC/D,CAoBO,SAASG,EAAAA,EAAiD,CAC/D,OAAO,CAELX,CAAAA,EACF,CACF","file":"chunk-DB5ISONG.js","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * RuleIndex, a conjunctive bitmask prefilter over the normalizer's rules.\n *\n * ## Problem\n * The normalizer tries every rule eligible at a position, at every position.\n * The `startTokenTypes` hint buckets rules by the type of the token they start\n * at, which helps only where that type is selective. It is not: the thirteen\n * call-fusion rules all declare `[\"IDENT\"]`, the commonest token in prose, and\n * the rules firing on a bare `NUMBER` all share that one type too. Measured\n * against the built-in package set, the `IDENT` bucket held 53 of 57 rules and\n * the `NUMBER` bucket 45, because a rule declaring no hint has to be tried\n * everywhere.\n *\n * ## Solution\n * Rules discriminate on different things, so no single axis separates them.\n * A rule declares its leading {@link RuleSlot} shape, and this builds one\n * lookup plane per slot: a flat `Uint32Array` of rule bitmasks indexed by token\n * type id, so a lookup is an array load rather than a hash. A position ANDs the\n * planes together and iterates only the surviving bits, which for most\n * positions is none at all.\n *\n * Rejecting a position therefore costs a few loads and ANDs instead of\n * forty-odd closure calls, and one AND tests 32 rules at once. That the common\n * answer is \"no rule can fire here\" is the point.\n *\n * ## Why planes rather than a fingerprint\n * A superimposed code (OR the hashed types of a window into one word, AND\n * against a per-rule required fingerprint) looks like the cheaper way to reach\n * depth, but it is a per-RULE test with no way to invert it into a lookup, so\n * it stays O(rules) per position. These planes are the same conjunctive test\n * done exactly, at O(rules / 32) and with no false positives. Token types\n * number a couple of hundred, small enough to table, so there is nothing to\n * gain by approximating.\n *\n * ## Ordering\n * Bit `i` is the rule at index `i` of the priority-sorted rule list, so\n * iterating bits from low to high visits rules in exactly the order the\n * unindexed scan did. Ties keep registration order, because the sort is stable.\n * This is what makes the index a pure filter rather than a behaviour change,\n * and `NormalizerIndexFidelity.spec` pins it.\n *\n * ## Safety\n * The contract runs one way: a slot admitting MORE than the rule can match\n * costs a `match()` that returns null, which is what happens today; a slot\n * admitting LESS makes the rule unreachable, a silent bug. So indexing fewer\n * planes than were declared is always safe, which is why {@link MAX_PLANES}\n * can be tuned on evidence rather than being a correctness decision. Only\n * over-narrow declarations are dangerous, and those are what the fidelity spec\n * hunts for.\n *\n * @module RuleIndex\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { NormalizerRule, RuleSlot } from \"./NormalizerRule\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n//#endregion\n//#region ─── Constants ────────────────────────────────────────────────────────\n\n/** Bits per word in the masks below. */\nconst WORD_BITS = 32;\n\n/**\n * How many leading slots are indexed, however many a rule declares.\n *\n * Each plane costs a load and an AND at every position, unconditionally, while\n * only positions surviving the earlier planes can benefit from a later one.\n * After two planes most positions have no candidates left, so a third would tax\n * every token to save a couple of `match()` calls on the few that reach it.\n *\n * Two is a measured default, not a limit of the design: raising it is a\n * one-line change, and lowering it can never break a rule (see this module's\n * Safety note). Rules may declare deeper shapes freely; the extra slots simply\n * go unindexed and are checked by `match()` as before.\n */\nconst MAX_PLANES = 2;\n\n//#endregion\n//#region ─── Shape normalisation ──────────────────────────────────────────────\n\n/**\n * A rule's effective shape, folding the older {@link NormalizerRule.startTokenTypes}\n * into the general form. `shape` wins when both are present.\n */\nexport function effectiveShape(rule: NormalizerRule): readonly RuleSlot[] {\n\tif (rule.shape !== undefined) return rule.shape;\n\tif (rule.startTokenTypes !== undefined) return [{ types: rule.startTokenTypes }];\n\treturn [];\n}\n\n//#endregion\n//#region ─── RuleIndex ────────────────────────────────────────────────────────\n\n/** One indexed slot position: the type plane, plus the value axis for it. */\ninterface Plane {\n\t/** `[typeId * words + w]`, rules whose slot admits `typeId`. */\n\treadonly byType: Uint32Array;\n\t/** Rules constraining no type here, admitted at a type with no row. */\n\treadonly typeAny: Uint32Array;\n\t/**\n\t * Rules constraining no type here, and so the only ones still admissible\n\t * when the stream ends before this slot.\n\t */\n\treadonly atEnd: Uint32Array;\n\t/** `[typeId]`, 1 when a value-constraining rule admits this type here. */\n\treadonly typeHasValues: Uint8Array;\n\t/** Lower-cased word to the rules naming it at this slot. */\n\treadonly byValue: Map<string, Uint32Array>;\n\t/** Rules constraining no value here. */\n\treadonly valueAny: Uint32Array;\n}\n\n/**\n * A conjunctive bitmask prefilter over a priority-sorted rule list.\n *\n * Built once per rule-set mutation (registration time), then read only. See\n * this module's overview for the shape and the ordering guarantee.\n */\nexport class RuleIndex {\n\t/** The priority-sorted rules. Bit `i` of every mask refers to `rules[i]`. */\n\treadonly rules: readonly NormalizerRule[];\n\n\t/** Words per mask, `ceil(rules.length / 32)`. */\n\treadonly words: number;\n\n\t/** Number of token type ids with their own row, exclusive upper bound. */\n\tprivate readonly typeRows: number;\n\n\t/** One per indexed slot, at most {@link MAX_PLANES}. */\n\tprivate readonly planes: readonly Plane[];\n\n\t/** Reused across positions so the hot path allocates nothing. */\n\tprivate readonly scratch: Uint32Array;\n\n\t/**\n\t * Every rule's bit set.\n\t *\n\t * Returned when there are no planes at all, which happens when no rule\n\t * declares a shape. Without it {@link candidates} would hand back an\n\t * unwritten scratch buffer, i.e. \"no rule can fire anywhere\", and every\n\t * rule would silently stop running. The all-admitted answer is the correct\n\t * one: a rule that constrains nothing can match anywhere.\n\t */\n\tprivate readonly allRules: Uint32Array;\n\n\tconstructor(sortedRules: readonly NormalizerRule[]) {\n\t\tthis.rules = sortedRules;\n\t\tconst n = sortedRules.length;\n\t\tconst w = Math.max(1, Math.ceil(n / WORD_BITS));\n\t\tthis.words = w;\n\t\tthis.scratch = new Uint32Array(w);\n\n\t\tconst shapes = sortedRules.map(effectiveShape);\n\n\t\t// Size the type-indexed rows to cover every type any rule names. A token\n\t\t// whose id lands past this (a plugin type minted after the index was\n\t\t// built, say) falls back to the \"constrains nothing\" masks, which is\n\t\t// correct rather than merely safe: a rule naming types cannot match a\n\t\t// type it did not name, and a rule naming none can match anywhere.\n\t\tlet maxTypeId = 0;\n\t\tfor (const shape of shapes) {\n\t\t\tfor (const slot of shape) {\n\t\t\t\tfor (const t of slot.types ?? []) maxTypeId = Math.max(maxTypeId, tokenTypeId(t));\n\t\t\t}\n\t\t}\n\t\tthis.typeRows = maxTypeId + 1;\n\n\t\tlet depth = 0;\n\t\tfor (const shape of shapes) depth = Math.max(depth, shape.length);\n\t\tdepth = Math.min(depth, MAX_PLANES);\n\n\t\tthis.allRules = new Uint32Array(w);\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tthis.allRules[(i / WORD_BITS) | 0] |= 1 << (i % WORD_BITS);\n\t\t}\n\n\t\tconst planes: Plane[] = [];\n\t\tfor (let k = 0; k < depth; k++) {\n\t\t\tplanes.push(this.buildPlane(shapes, k, w));\n\t\t}\n\t\tthis.planes = planes;\n\t}\n\n\t/** Build the lookup plane for slot `k`. */\n\tprivate buildPlane(shapes: readonly (readonly RuleSlot[])[], k: number, w: number): Plane {\n\t\tconst plane: Plane = {\n\t\t\tbyType: new Uint32Array(this.typeRows * w),\n\t\t\ttypeAny: new Uint32Array(w),\n\t\t\tatEnd: new Uint32Array(w),\n\t\t\ttypeHasValues: new Uint8Array(this.typeRows),\n\t\t\tbyValue: new Map<string, Uint32Array>(),\n\t\t\tvalueAny: new Uint32Array(w),\n\t\t};\n\n\t\tfor (let i = 0; i < shapes.length; i++) {\n\t\t\tconst slot: RuleSlot | undefined = shapes[i][k];\n\t\t\tconst word = (i / WORD_BITS) | 0;\n\t\t\tconst bit = 1 << (i % WORD_BITS);\n\n\t\t\t// ── Types ──\n\t\t\tconst types = slot?.types;\n\t\t\tif (types === undefined) {\n\t\t\t\t// Constrains nothing here, so admitted at every type, at a type\n\t\t\t\t// with no row, and past the end of the stream.\n\t\t\t\t//\n\t\t\t\t// Deliberately NOT written into every row of `byType`. Doing that\n\t\t\t\t// made construction O(rules x tokenTypes), tens of thousands of\n\t\t\t\t// writes for a table most of which is the same bit, and the\n\t\t\t\t// engine builds an index per instance: a cold parse of a short\n\t\t\t\t// document paid for it without ever amortising it. The lookup\n\t\t\t\t// ORs `typeAny` in instead, which is one extra operation per word\n\t\t\t\t// on a path that already does several.\n\t\t\t\tplane.typeAny[word] |= bit;\n\t\t\t\tplane.atEnd[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const t of types) plane.byType[tokenTypeId(t) * w + word] |= bit;\n\t\t\t}\n\n\t\t\t// ── Values ──\n\t\t\tconst values = slot?.values;\n\t\t\tif (values === undefined) {\n\t\t\t\tplane.valueAny[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const raw of values) {\n\t\t\t\t\tconst value = raw.toLowerCase();\n\t\t\t\t\tlet mask = plane.byValue.get(value);\n\t\t\t\t\tif (mask === undefined) {\n\t\t\t\t\t\tmask = new Uint32Array(w);\n\t\t\t\t\t\tplane.byValue.set(value, mask);\n\t\t\t\t\t}\n\t\t\t\t\tmask[word] |= bit;\n\t\t\t\t}\n\t\t\t\t// The value axis is only worth a map lookup at a type some\n\t\t\t\t// value-constraining rule admits here.\n\t\t\t\tif (types === undefined) {\n\t\t\t\t\tplane.typeHasValues.fill(1);\n\t\t\t\t} else {\n\t\t\t\t\tfor (const t of types) {\n\t\t\t\t\t\tconst id = tokenTypeId(t);\n\t\t\t\t\t\tif (id < this.typeRows) plane.typeHasValues[id] = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn plane;\n\t}\n\n\t/** Number of indexed rules. */\n\tget size(): number { return this.rules.length; }\n\n\t/** How many slot positions are indexed. */\n\tget depth(): number { return this.planes.length; }\n\n\t/**\n\t * The candidate mask for a position, written into a reused scratch buffer\n\t * and returned. Bits are rule indices, ascending bit order being descending\n\t * priority. The buffer is overwritten by the next call, so read it before\n\t * calling again.\n\t *\n\t * @param tokens - The stream being walked\n\t * @param pos - The position to test\n\t */\n\tcandidates(tokens: readonly { typeId: number; value: string }[], pos: number): Uint32Array {\n\t\tconst w = this.words;\n\t\tconst scratch = this.scratch;\n\t\tconst planes = this.planes;\n\t\tconst len = tokens.length;\n\n\t\tif (planes.length === 0) {\n\t\t\tscratch.set(this.allRules);\n\t\t\treturn scratch;\n\t\t}\n\n\t\tfor (let k = 0; k < planes.length; k++) {\n\t\t\tconst plane = planes[k];\n\t\t\tconst at = pos + k;\n\n\t\t\tif (at >= len) {\n\t\t\t\t// The stream ends before this slot, so only rules that constrain\n\t\t\t\t// nothing here remain admissible.\n\t\t\t\tif (k === 0) { scratch.set(plane.atEnd); }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.atEnd[i]; }\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst token = tokens[at];\n\t\t\tconst typeId = token.typeId;\n\t\t\tconst base = typeId >= 0 && typeId < this.typeRows ? typeId * w : -1;\n\n\t\t\t// `typeAny` holds the rules that constrain no type at this slot, so\n\t\t\t// they are admitted whatever the token is; see the construction note.\n\t\t\tif (k === 0) {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] = plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { scratch.set(plane.typeAny); }\n\t\t\t} else {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] &= plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.typeAny[i]; }\n\t\t\t}\n\n\t\t\t// The value axis costs a map lookup and possibly a lower-casing, so\n\t\t\t// it is consulted only at a type some value-constraining rule names.\n\t\t\tif (base >= 0 && plane.typeHasValues[typeId] === 1) {\n\t\t\t\tconst value = token.value;\n\t\t\t\tconst lowered = hasUpper(value) ? value.toLowerCase() : value;\n\t\t\t\tconst named = plane.byValue.get(lowered);\n\t\t\t\tfor (let i = 0; i < w; i++) {\n\t\t\t\t\tscratch[i] &= (named === undefined ? 0 : named[i]) | plane.valueAny[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isEmptyMask(scratch)) return scratch;\n\t\t}\n\n\t\treturn scratch;\n\t}\n}\n\n/** Whether every bit of a mask returned by {@link RuleIndex.candidates} is clear. */\nexport function isEmptyMask(mask: Uint32Array): boolean {\n\tfor (let i = 0; i < mask.length; i++) if (mask[i] !== 0) return false;\n\treturn true;\n}\n\n/**\n * Whether a string contains an ASCII upper-case letter.\n *\n * `toLowerCase()` allocates even when it changes nothing, and identifiers in\n * running prose are overwhelmingly already lower case, so this scan pays for\n * itself by skipping the allocation in the common case.\n */\nexport function hasUpper(value: string): boolean {\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst c = value.charCodeAt(i);\n\t\t// A-Z, or anything outside ASCII: `Ü` lowers to `ü`, and the keys this\n\t\t// guards were built with a full toLowerCase(), so a non-ASCII word takes\n\t\t// the slow path and meets its key in the case the key was built in.\n\t\tif ((c >= 65 && c <= 90) || c >= 128) return true;\n\t}\n\treturn false;\n}\n\n/** `value` in the case the index and the phrase trie key on: lowered only when it has to be. */\nexport function lowerCased(value: string): string {\n\treturn hasUpper(value) ? value.toLowerCase() : value;\n}\n\n//#endregion\n","//#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, RuleSlot, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { RuleIndex, isEmptyMask, effectiveShape } from \"./RuleIndex\";\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 * Try every registered rule at every position, ignoring both the shape\n * index and the first-token buckets the first call uses.\n *\n * Diagnostic only, and much slower. It exists so the filtered walks can be\n * compared against the exhaustive one over a corpus: each filter is pure,\n * so all of them must agree token for token, and a rule whose declared\n * {@link NormalizerRule.shape} is too narrow shows up as a difference rather\n * than as a feature that quietly stopped working.\n * `NormalizerIndexFidelity.spec` and `RuleHintsMatchGuards.spec` are the\n * consumers.\n *\n * @default false\n */\n ignoreRuleIndex?: boolean;\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 ignoreRuleIndex: false,\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 * Rule names already warned about, so a rule registered into many engines\n * says it once rather than once per engine.\n */\nconst warnedUnshapedRules = new Set<string>();\n\n/**\n * Warn when a rule declares neither a shape nor a reason for not having one.\n *\n * An unshaped rule is tried at every position of every line, so its cost is\n * paid by every document rather than only by the feature it implements. The\n * warning names the rule and points at the two ways out, and it fires once per\n * rule name per process: a warning a package author sees on every engine they\n * construct is one they learn to filter out, which would make it worse than\n * useless.\n *\n * Deliberately not an error. A rule without a shape is correct, only slower,\n * and refusing to register it would break every package written before the\n * field existed.\n */\nfunction warnIfUnshaped(rule: NormalizerRule): void {\n if (rule.shape !== undefined && rule.shape.length > 0) return;\n if (rule.startTokenTypes !== undefined) return;\n if (rule.unshapedReason !== undefined) return;\n if (warnedUnshapedRules.has(rule.name)) return;\n warnedUnshapedRules.add(rule.name);\n console.warn(\n `[TokenNormalizer] Rule \"${rule.name}\" declares no \\`shape\\`, so it is tried at every ` +\n `token of every line and slows down documents that never use it. Declare the tokens it ` +\n `can start at, e.g. shape: [{ types: [\"IDENT\"], values: [\"myword\"] }, { types: [\"LPAREN\"] }]. ` +\n `If it genuinely cannot be described that way, set \\`unshapedReason\\` to say why and this ` +\n `warning will stop.`,\n );\n}\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 * Per-token-type view of the priority-sorted rules, for the one\n * {@link normalize} call that runs before the index exists: for a token\n * type, the rules whose first declared slot admits it (or constrains no\n * type at all), in the same priority order {@link getSortedRules} produces.\n * See {@link rulesForTokenType}. Built once per distinct type and cached,\n * invalidated alongside {@link sortedRulesCache}.\n */\n private rulesByTokenType = new Map<string, NormalizerRule[]>();\n\n /**\n * Shape index over the priority-sorted rules, rebuilt alongside\n * {@link sortedRulesCache}. `null` means \"stale, rebuild on next use\".\n *\n * This is what turns the per-position scan from \"try every rule that could\n * fire on this token type\" into \"AND a few lookup planes and try what\n * survives\", which is usually nothing. See {@link RuleIndex}.\n */\n private ruleIndexCache: RuleIndex | null = null;\n\n /** Reused by {@link rulesAt} so a position's candidate list costs no allocation. */\n private candidateBuffer: NormalizerRule[] = [];\n\n /**\n * How many times {@link normalize} has run, capped once the index is in use.\n *\n * The index costs a few tens of microseconds to build and pays that back\n * within a line or two, but an engine that normalises exactly once, which is\n * what evaluating a single expression on a fresh engine does, would never\n * reach the payback. Skipping the build on the first call keeps that case at\n * the cost it had before the index existed, and a document reaches line two\n * immediately. The first call is not unfiltered, though: it reads the same\n * first-slot types the index would, through {@link rulesForTokenType}, so a\n * single expression still skips every rule that could not start at its\n * tokens.\n */\n private normalizeCalls = 0;\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 warnIfUnshaped(rule);\n this.rules.push(rule);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = 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 this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = 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.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = 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 * The shape index over the priority-sorted rules, built on first use after\n * a mutation and cached. See {@link RuleIndex}.\n */\n private getRuleIndex(): RuleIndex {\n if (this.ruleIndexCache === null) {\n this.ruleIndexCache = new RuleIndex(this.getSortedRules());\n }\n return this.ruleIndexCache;\n }\n\n /**\n * The rules to try at a position, in priority order.\n *\n * With a candidate mask, walks its set bits low to high, which is descending\n * priority because bit `i` is the rule at index `i` of the priority-sorted\n * list.\n *\n * The walk shifts a bit at a time rather than jumping to the next set bit\n * with `Math.clz32(bits & -bits)`, which is the idiomatic form and was 36x\n * SLOWER here: 45us per line against 1.2us, measured over the built-in rule\n * set. `clz32` is specified on uint32 and the masks come out of a\n * `Uint32Array` as doubles above 2^31, so every call pays a conversion that\n * swamps the handful of iterations it saves. A de Bruijn table matched the\n * shift scan to within noise and needs a magic constant, so the plain shift\n * wins on both counts. Worst case is 32 iterations per word of pure integer\n * work.\n *\n * With `null` there is no index to consult, for one of two reasons: this is\n * the first call, which reads the first-token bucket from\n * {@link rulesForTokenType}, or {@link NormalizerOptions.ignoreRuleIndex} is\n * set, which is the exhaustive scan every filter is measured against. Both\n * hand back a cached list directly, since the caller only reads it.\n *\n * With a mask, returns a buffer reused across positions, so the caller must\n * finish with it before calling again. Copying the surviving rules out here\n * rather than yielding them lazily is deliberate twice over: it keeps the\n * mask's own scratch buffer from being read after the next position\n * overwrites it, and it avoids a generator on the hottest loop in the pass.\n */\n private rulesAt(mask: Uint32Array | null, type: string): readonly NormalizerRule[] {\n if (mask === null) {\n return this.options.ignoreRuleIndex ? this.getSortedRules() : this.rulesForTokenType(type);\n }\n\n const buffer = this.candidateBuffer;\n buffer.length = 0;\n const rules = this.getRuleIndex().rules;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n let index = w * 32;\n while (bits !== 0) {\n if ((bits & 1) !== 0) buffer.push(rules[index]);\n bits >>>= 1;\n index++;\n }\n }\n return buffer;\n }\n\n /**\n * The priority-sorted rules that could start at a token of `type`, for the\n * first {@link normalize} call, which runs before the index is built.\n *\n * The filter is the first slot of each rule's {@link effectiveShape}: a rule\n * naming types there is bucketed under exactly those, and one naming none is\n * in every bucket. That is the same declaration the index reads at its first\n * plane, only without the value axis, so a rule the bucket omits is one the\n * index would omit too, and one that would have returned null here anyway.\n * An earlier version read only the older `startTokenTypes` hint, which most\n * rules had by then replaced with a `shape`, so the first call tried nearly\n * every rule at every position and a fresh engine evaluating one expression\n * paid several times the rule calls of the second line of a document.\n *\n * Built once per distinct type and cached until the rule set changes.\n */\n private rulesForTokenType(type: string): NormalizerRule[] {\n let list = this.rulesByTokenType.get(type);\n if (list === undefined) {\n list = this.getSortedRules().filter((rule) => {\n const first = effectiveShape(rule)[0];\n return first?.types === undefined || first.types.includes(type);\n });\n this.rulesByTokenType.set(type, list);\n }\n return list;\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 /**\n * Every registered rule with the shape it declared, for diagnostic display.\n *\n * Exposes what the index is actually working with: a rule that declares a\n * shape is only tried where that shape can match, and one that declares none\n * is tried at every position of every line. Which is which is invisible from\n * the outside otherwise, and it is the difference between a package that\n * costs the documents that use it and one that costs all of them, so the\n * playground draws it.\n *\n * Returned in priority order, highest first, which is the order the\n * normalizer tries them in.\n */\n private ruleShapesCache: Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> | null = null;\n\n getRuleShapes(): Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> {\n // Memoised: the answer depends only on the rule set, but the diagnostic\n // pipeline builds a stage per LINE, so recomputing it there made a\n // 25-line document walk every rule 25 times to produce 25 identical lists.\n if (this.ruleShapesCache !== null) return this.ruleShapesCache;\n const index = this.getRuleIndex();\n this.ruleShapesCache = this.getSortedRules().map((rule) => {\n const shape = effectiveShape(rule);\n return {\n name: rule.name,\n priority: rule.priority,\n shape,\n unshapedReason: rule.unshapedReason,\n indexedSlots: Math.min(shape.length, index.depth),\n };\n });\n return this.ruleShapesCache;\n }\n\n /**\n * How many rules could fire at each position of `tokens`, against the total.\n *\n * The point of the index is that most positions admit no rule at all, and\n * this is what makes that visible rather than asserted.\n */\n getCandidateCounts(tokens: Token[]): number[] {\n const index = this.getRuleIndex();\n const counts: number[] = [];\n for (let pos = 0; pos < tokens.length; pos++) {\n const mask = index.candidates(tokens, pos);\n let n = 0;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n while (bits !== 0) { n += bits & 1; bits >>>= 1; }\n }\n counts.push(n);\n }\n return counts;\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, or the\n * stream is still changing after maxPasses passes (a rule chain that never\n * settles): NORMALIZER_PASS_LIMIT_EXCEEDED, rather than a stream that is\n * quietly whatever the last pass left.\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 // Rules reach a position through one of three filters, resolved once\n // below: the shape index, the first-token buckets on the very first call,\n // or no filter at all under `ignoreRuleIndex`. See rulesAt().\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n // Hoisted out of the pass loop: the rule set cannot change mid-normalize,\n // so the index is resolved once rather than per position.\n const warmedUp = this.normalizeCalls > 0;\n if (!warmedUp) this.normalizeCalls = 1;\n const useIndex = warmedUp && !this.options.ignoreRuleIndex;\n const ruleIndex = useIndex ? this.getRuleIndex() : null;\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 // Built lazily: a pass that changes nothing must not allocate an array\n // and copy every token into it only to throw the copy away. `null` means\n // \"nothing has changed yet, `current` is still the answer\"; the first\n // rule to fire calls ensureResult() to materialise it. A document whose\n // lines mostly normalise to themselves is the common case, and it now\n // costs no allocation at all.\n let result: Token[] | null = null;\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 if (result === null) result = current.slice(0, pos);\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, in priority order, only the rules whose declared shape admits\n // this position. The index is a pure filter: bit order is priority\n // order, and a rule it excludes would have returned null here anyway\n // (see RuleIndex). `ignoreRuleIndex` restores the exhaustive scan so\n // the two can be compared.\n const candidates = useIndex\n ? ruleIndex!.candidates(current, pos)\n : null;\n if (candidates !== null && isEmptyMask(candidates)) {\n // Nothing can fire here. This is the common case in running prose,\n // and reaching it costs a few array loads rather than one call per\n // registered rule.\n if (result !== null) result.push(current[pos]);\n pos++;\n continue;\n }\n for (const rule of this.rulesAt(candidates, current[pos].type)) {\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 if (result === null) result = current.slice(0, pos);\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 // Only copied when an earlier position already forced the array.\n if (result !== null) result.push(current[pos]);\n pos++;\n }\n }\n\n // Nothing fired anywhere in this pass, so the stream is already its own\n // normal form and `changed` is false; the loop is about to end.\n if (result === null) break;\n const passResult: Token[] = result;\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (passResult.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 (${passResult.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: passResult.length, maxTokens }\n );\n }\n\n current = passResult;\n }\n\n // The loop above ends either because a pass changed nothing (the stream\n // is its own normal form) or because the pass budget ran out with the\n // stream still moving. The second used to return the last pass's output\n // as if it were the answer; a rule chain that never settles is a bug in\n // a rule, and the caller should hear about it.\n if (changed) {\n throw ErrorFactory.validation(\n \"NORMALIZER_PASS_LIMIT_EXCEEDED\",\n `Normalization was still changing the token stream after ${maxPasses} passes`,\n { maxPasses, tokenCount: current.length }\n );\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\";\nimport { lowerCased } from \"./RuleIndex\";\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// ── A tag token never takes part in phrase fusion (#197, #213) ──\n\t\t// A `#tag` is a typed token, not a bare word, so it must not start or\n\t\t// complete a phrase. The trie matches on written value alone, so without\n\t\t// this guard a tag whose name equals a phrase or a phrase-continuation\n\t\t// word (`1200 #assuming`, `total of #column`) is fused into that grammar\n\t\t// before the category-tag rules ever run, and the tag is lost.\n\t\t//\n\t\t// The guard also covers the fused aggregate tokens the tags package emits\n\t\t// (`TAG_SUM` / `TAG_COUNT` / `TAG_AVERAGE`), whose value is the tag NAME:\n\t\t// otherwise `total of #assuming` fuses correctly to TAG_SUM(\"assuming\"),\n\t\t// then the trie re-reads that value on the next pass and turns it back\n\t\t// into the finance ASSUMING keyword (#213). The whole `TAG` / `TAG_*`\n\t\t// namespace belongs to the tags package.\n\t\tconst startType = tokens[pos].type;\n\t\tif (startType === \"TAG\" || startType.startsWith(\"TAG_\")) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = lowerCased(tokens[pos].value);\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. A token that already carries the\n\t\t// phrase's type is the fusion, not a word to fuse: proposing it again made\n\t\t// every pass a change, so a line holding `assuming` ran the normaliser to\n\t\t// its pass budget on every evaluation, and the result was whatever the\n\t\t// last pass left.\n\t\tif (node.terminal && tokens[pos].type !== node.terminal.tokenType) {\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 contType = tokens[i].type;\n\t\t\tif (contType === \"TAG\" || contType.startsWith(\"TAG_\")) break; // a tag token can't continue a phrase (#197, #213)\n\t\t\tconst word = lowerCased(tokens[i].value);\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(lowerCased(word));\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 // Both slots are exactly the `triggers` test below, which is the whole\n // condition: a value or closing bracket, then something a multiplication\n // could apply to.\n shape: [\n { types: [\"NUMBER\", \"RPAREN\"] },\n { types: [\"IDENT\", \"LPAREN\", \"PI\", \"E\"] },\n ],\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 // ── Check trigger conditions ──\n // Ordered FIRST deliberately. The two guards below only ever suppress a\n // match, so testing them after the trigger cannot change any result, and\n // the first of them allocates a lower-cased copy of the next token's\n // value. Running that ahead of a pair of type comparisons meant every\n // position in the document paid a string allocation and a set lookup to\n // reach a test that rejects nearly all of them.\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 // ── 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 // ── 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}. The table\n * itself lives in `lexer/BuiltinPhrases.ts`, shared with the lexer's token\n * lookup, and is re-exported here so existing imports keep working.\n */\nexport { BUILTIN_PHRASES } from \"@solve-js/lexer/BuiltinPhrases\";\n\n//#endregion\n"]}
|