@briza/illogical 2.0.2 → 2.1.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.
@@ -21,6 +21,30 @@ function _toPropertyKey(t) {
21
21
  return "symbol" == typeof i ? i : i + "";
22
22
  }
23
23
 
24
+ /**
25
+ * Valid types for context members
26
+ */
27
+
28
+ /**
29
+ * Evaluation Context
30
+ * Holds references used during the evaluation process.
31
+ * Format: key: value.
32
+ */
33
+
34
+ /**
35
+ * Evaluation result
36
+ */
37
+
38
+ let EvaluableType = /*#__PURE__*/function (EvaluableType) {
39
+ EvaluableType["Operand"] = "Operand";
40
+ EvaluableType["Expression"] = "Expression";
41
+ return EvaluableType;
42
+ }({});
43
+
44
+ /**
45
+ * Evaluable
46
+ */
47
+
24
48
  /**
25
49
  * Is number predicate.
26
50
  * @param value Tested value.
@@ -94,30 +118,6 @@ function areAllNumbers(results) {
94
118
  return results.every(isNumber);
95
119
  }
96
120
 
97
- /**
98
- * Valid types for context members
99
- */
100
-
101
- /**
102
- * Evaluation Context
103
- * Holds references used during the evaluation process.
104
- * Format: key: value.
105
- */
106
-
107
- /**
108
- * Evaluation result
109
- */
110
-
111
- let EvaluableType = /*#__PURE__*/function (EvaluableType) {
112
- EvaluableType["Operand"] = "Operand";
113
- EvaluableType["Expression"] = "Expression";
114
- return EvaluableType;
115
- }({});
116
-
117
- /**
118
- * Evaluable
119
- */
120
-
121
121
  /**
122
122
  * Abstract arithmetic expression
123
123
  */
@@ -233,20 +233,20 @@ class Divide extends Arithmetic {
233
233
  }
234
234
  }
235
235
 
236
- const getNumDecimals = num => {
236
+ const getNumDecimals$1 = num => {
237
237
  const numberSplit = num.toString().split('.');
238
238
  return numberSplit.length == 2 ? numberSplit[1].length : 0;
239
239
  };
240
- const operateWithExpectedDecimals = operation => (first, second) => {
241
- const numDecimals1 = getNumDecimals(first);
242
- const numDecimals2 = getNumDecimals(second);
240
+ const operateWithExpectedDecimals$1 = operation => (first, second) => {
241
+ const numDecimals1 = getNumDecimals$1(first);
242
+ const numDecimals2 = getNumDecimals$1(second);
243
243
  const maxDecimals = operation === 'multiply' ? numDecimals1 + numDecimals2 : numDecimals1 > numDecimals2 ? numDecimals1 : numDecimals2;
244
244
  return operation === 'sum' ? Number((first + second).toFixed(maxDecimals)) : operation === 'subtract' ? Number((first - second).toFixed(maxDecimals)) : Number((first * second).toFixed(maxDecimals));
245
245
  };
246
246
 
247
247
  // Operator key
248
248
  const OPERATOR$k = Symbol('MULTIPLY');
249
- const multiplyWithExpectedDecimals = operateWithExpectedDecimals('multiply');
249
+ const multiplyWithExpectedDecimals = operateWithExpectedDecimals$1('multiply');
250
250
 
251
251
  /**
252
252
  * Multiply operation expression
@@ -278,7 +278,7 @@ class Multiply extends Arithmetic {
278
278
 
279
279
  // Operator key
280
280
  const OPERATOR$j = Symbol('SUBTRACT');
281
- const subtractWithExpectedDecimals = operateWithExpectedDecimals('subtract');
281
+ const subtractWithExpectedDecimals = operateWithExpectedDecimals$1('subtract');
282
282
 
283
283
  /**
284
284
  * Subtract operation expression
@@ -310,7 +310,7 @@ class Subtract extends Arithmetic {
310
310
 
311
311
  // Operator key
312
312
  const OPERATOR$i = Symbol('SUM');
313
- const addWithExpectedDecimals = operateWithExpectedDecimals('sum');
313
+ const addWithExpectedDecimals = operateWithExpectedDecimals$1('sum');
314
314
 
315
315
  /**
316
316
  * Sum operation expression
@@ -411,6 +411,7 @@ class Value extends Operand {
411
411
  * {@link Evaluable.serialize}
412
412
  */
413
413
  serialize() {
414
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
414
415
  return this.value;
415
416
  }
416
417
 
@@ -464,21 +465,21 @@ const toDateNumber = value => {
464
465
  return NaN;
465
466
  };
466
467
 
467
- const keyWithArrayIndexRegex = /^(?<currentKey>[^[\]]+?)(?<indexes>(?:\[\d+])+)?$/;
468
- const arrayIndexRegex = /\[(\d+)]/g;
469
- function parseBacktickWrappedKey(key) {
468
+ const keyWithArrayIndexRegex$1 = /^(?<currentKey>[^[\]]+?)(?<indexes>(?:\[\d+])+)?$/;
469
+ const arrayIndexRegex$1 = /\[(\d+)]/g;
470
+ function parseBacktickWrappedKey$1(key) {
470
471
  return key[0] === '`' && key[key.length - 1] === '`' ? key.slice(1, -1) : key;
471
472
  }
472
- function parseKeyComponents(key) {
473
- const unwrappedKey = parseBacktickWrappedKey(key);
473
+ function parseKeyComponents$1(key) {
474
+ const unwrappedKey = parseBacktickWrappedKey$1(key);
474
475
  const keys = [];
475
- const parseResult = keyWithArrayIndexRegex.exec(unwrappedKey);
476
+ const parseResult = keyWithArrayIndexRegex$1.exec(unwrappedKey);
476
477
  if (parseResult) {
477
- const extractedKey = parseBacktickWrappedKey(parseResult?.groups?.currentKey ?? unwrappedKey);
478
+ const extractedKey = parseBacktickWrappedKey$1(parseResult?.groups?.currentKey ?? unwrappedKey);
478
479
  keys.push(extractedKey);
479
480
  const rawIndexes = parseResult?.groups?.indexes;
480
481
  if (rawIndexes) {
481
- for (const indexResult of rawIndexes.matchAll(arrayIndexRegex)) {
482
+ for (const indexResult of rawIndexes.matchAll(arrayIndexRegex$1)) {
482
483
  keys.push(parseInt(indexResult[1]));
483
484
  }
484
485
  }
@@ -487,10 +488,10 @@ function parseKeyComponents(key) {
487
488
  }
488
489
  return keys;
489
490
  }
490
- const parseKeyRegex = /(`[^[\]]+`(\[\d+\])*|[^`.]+)/g;
491
+ const parseKeyRegex$1 = /(`[^[\]]+`(\[\d+\])*|[^`.]+)/g;
491
492
  function parseKey(key) {
492
- const keys = key.match(parseKeyRegex);
493
- return !keys ? [] : keys.flatMap(parseKeyComponents);
493
+ const keys = key.match(parseKeyRegex$1);
494
+ return !keys ? [] : keys.flatMap(parseKeyComponents$1);
494
495
  }
495
496
  const complexKeyExpression = /{([^{}]+)}/;
496
497
  function extractComplexKeys(ctx, key) {
@@ -546,9 +547,12 @@ let DataType = /*#__PURE__*/function (DataType) {
546
547
  }({});
547
548
 
548
549
  // Equivalent to /^.+\.\((Number|String)\)$/
549
- const dataTypeRegex = new RegExp(`^.+\\.\\((${Object.keys(DataType).join('|')})\\)$`);
550
+ const dataTypeRegex$1 = new RegExp(`^.+\\.\\((${Object.keys(DataType).join('|')})\\)$`);
550
551
  const isComplexKey = key => key.indexOf('{') > -1;
551
- const castingRegex = /\.\(.+\)$/;
552
+ function isDataTypeKey$1(k) {
553
+ return k in DataType;
554
+ }
555
+ const castingRegex$1 = /\.\(.+\)$/;
552
556
 
553
557
  /**
554
558
  * Reference operand resolved within the context
@@ -568,10 +572,13 @@ class Reference extends Operand {
568
572
  _defineProperty(this, "valueLookup", void 0);
569
573
  _defineProperty(this, "getKeys", void 0);
570
574
  this.key = key;
571
- const dataTypeMatch = dataTypeRegex.exec(this.key);
575
+ const dataTypeMatch = dataTypeRegex$1.exec(this.key);
572
576
  if (dataTypeMatch) {
573
- this.dataType = DataType[dataTypeMatch[1]];
574
- this.key = this.key.replace(castingRegex, '');
577
+ const dtKey = dataTypeMatch[1];
578
+ if (isDataTypeKey$1(dtKey)) {
579
+ this.dataType = DataType[dtKey];
580
+ }
581
+ this.key = this.key.replace(castingRegex$1, '');
575
582
  }
576
583
  if (isComplexKey(this.key)) {
577
584
  this.valueLookup = context => complexValueLookup(context, this.key);
@@ -859,10 +866,13 @@ class In extends Comparison {
859
866
  if (!leftArray && !rightArray) {
860
867
  throw new Error('invalid IN expression, non of the operands is array');
861
868
  }
862
- if (leftArray) {
869
+ if (Array.isArray(left)) {
863
870
  return left.indexOf(right) > -1;
864
871
  }
865
- return right.indexOf(left) > -1;
872
+ if (Array.isArray(right)) {
873
+ return right.indexOf(left) > -1;
874
+ }
875
+ return false;
866
876
  }
867
877
 
868
878
  /**
@@ -1014,10 +1024,13 @@ class NotIn extends Comparison {
1014
1024
  if (!leftArray && !rightArray) {
1015
1025
  throw new Error('invalid NOT IN expression, one operand must be array');
1016
1026
  }
1017
- if (leftArray) {
1027
+ if (Array.isArray(left)) {
1018
1028
  return left.indexOf(right) === -1;
1019
1029
  }
1020
- return right.indexOf(left) === -1;
1030
+ if (Array.isArray(right)) {
1031
+ return right.indexOf(left) === -1;
1032
+ }
1033
+ return true;
1021
1034
  }
1022
1035
 
1023
1036
  /**
@@ -1064,12 +1077,10 @@ class Overlap extends Comparison {
1064
1077
  if (!Array.isArray(left) || !Array.isArray(right)) {
1065
1078
  throw new Error('invalid OVERLAP expression, both operands must be array');
1066
1079
  }
1067
- const leftArray = left;
1068
- const rightArray = right;
1069
- if (leftArray.length === 0 && rightArray.length === 0) {
1080
+ if (left.length === 0 && right.length === 0) {
1070
1081
  return true;
1071
1082
  }
1072
- return leftArray.some(element => rightArray.includes(element));
1083
+ return left.some(element => right.includes(element));
1073
1084
  }
1074
1085
 
1075
1086
  /**
@@ -1568,11 +1579,8 @@ class Xor extends Logical {
1568
1579
  evaluate(ctx) {
1569
1580
  let res = null;
1570
1581
  for (const operand of this.operands) {
1571
- if (res === null) {
1572
- res = operand.evaluate(ctx);
1573
- } else {
1574
- res = xor(res, operand.evaluate(ctx));
1575
- }
1582
+ const val = Boolean(operand.evaluate(ctx));
1583
+ res = res === null ? val : xor(res, val);
1576
1584
  }
1577
1585
  return res;
1578
1586
  }
@@ -1614,147 +1622,3108 @@ class Xor extends Logical {
1614
1622
  }
1615
1623
 
1616
1624
  /**
1617
- * Collection operand resolved containing mixture of value and references.
1625
+ * Bytecode opcodes for the illogical expression interpreter.
1626
+ *
1627
+ * Each opcode is a small integer. Some opcodes consume the next element(s)
1628
+ * in the bytecode array as operand data (e.g. OP_PUSH_VALUE reads the next
1629
+ * element as the literal value to push).
1618
1630
  */
1619
- class Collection extends Operand {
1620
- /**
1621
- * Get the items in the collection.
1622
- * @returns {Array<Value | Reference>}
1623
- */
1624
- getItems() {
1625
- return this.items;
1626
- }
1627
1631
 
1628
- /**
1629
- * @constructor
1630
- * @param {Operand[]} items Collection of operands.
1631
- */
1632
- constructor(items) {
1633
- super();
1634
- _defineProperty(this, "items", void 0);
1635
- this.items = items;
1632
+ const OP_PUSH_VALUE = 1; // next: literal — push literal onto stack
1633
+ const OP_PUSH_REF_KEY = 6; // next: index into refs (CompactRef string) — ctx[key]
1634
+ const OP_PUSH_REF_KEYS = 7; // next: index into refs (CompactRef string[]) inline multi-key walk
1635
+ const OP_PUSH_REF_TOKENS = 8; // next: index into refs (CompactRef token/dataType obj) — token walk
1636
+ const OP_PUSH_REF_DYNAMIC = 9; // next: index into refs (CompactRef dynamic obj) — runtime substitution
1637
+ const OP_MAKE_COLLECTION = 3; // next: N — pop N items, push as array
1638
+ const OP_PUSH_CONST = 4; // next: constIdx — push consts[constIdx] (static array) onto stack
1639
+ const OP_OVERLAP_CONST = 5; // next: constIdx — pop dynamic array, Set-intersect against consts[constIdx]
1640
+
1641
+ const OP_EQ = 10; // pop 2, push (left === right)
1642
+ const OP_NE = 11; // pop 2, push (left !== right)
1643
+ const OP_GT = 12; // pop 2, push (left > right), with date fallback
1644
+ const OP_GE = 13; // pop 2, push (left >= right), with date fallback
1645
+ const OP_LT = 14; // pop 2, push (left < right), with date fallback
1646
+ const OP_LE = 15; // pop 2, push (left <= right), with date fallback
1647
+ const OP_IN = 16; // pop 2, push membership check (one must be array) — dynamic fallback
1648
+ const OP_NOT_IN = 17; // pop 2, push non-membership check — dynamic fallback
1649
+ const OP_IN_COLLECTION = 45; // next: N — pop scalar, scan N stack items, push membership result
1650
+ const OP_NOT_IN_COLLECTION = 46; // next: N — pop scalar, scan N stack items, push non-membership result
1651
+ const OP_IN_CONST = 49; // next: constIdx — pop scalar, Set-lookup in consts[constIdx], push membership result
1652
+ const OP_NOT_IN_CONST = 50; // next: constIdx — pop scalar, Set-lookup in consts[constIdx], push !membership
1653
+ // next: N, ref0..refN-1, constIdx — resolve each ref inline against Set, no stack alloc
1654
+ const OP_OVERLAP_SCAN_REFS_CONST = 51;
1655
+ // next: ref1Idx, ref2Idx, M, v0, setBIdx0, v1, setBIdx1, ..., vM-1, setBIdxM-1
1656
+ // Inverted-index form: M entries of (literal setA value, constIdx of merged setB).
1657
+ // At runtime: resolve ref1, look up matching entries by value (O(1) via cached Map),
1658
+ // for each match check ref2 ∈ mergedSetB. Refs resolved once; setBs union-merged per setA value.
1659
+ const OP_OR_AND_IN_CONST_2 = 52;
1660
+ const OP_PREFIX = 18; // pop 2, push right.startsWith(left)
1661
+ const OP_SUFFIX = 19; // pop 2, push left.endsWith(right)
1662
+ const OP_OVERLAP = 20; // pop 2, push array intersection check
1663
+ const OP_PRESENT = 21; // pop 1, push (value !== undefined && value !== null)
1664
+ const OP_UNDEFINED = 22; // pop 1, push (value === undefined)
1665
+
1666
+ const OP_SUM = 30; // next: N — pop N numbers, push decimal-corrected sum
1667
+ const OP_SUBTRACT = 31; // next: N — pop N numbers, push decimal-corrected subtraction
1668
+ const OP_MULTIPLY = 32; // next: N — pop N numbers, push decimal-corrected multiplication
1669
+ const OP_DIVIDE = 33; // next: N — pop N numbers, push division result
1670
+
1671
+ const OP_STORE_LOCAL = 47; // next: slot — peek top of stack, store into locals[slot]
1672
+ const OP_LOAD_LOCAL = 48; // next: slot — push locals[slot] onto stack
1673
+
1674
+ const OP_NOT = 40; // pop 1 boolean, push negation
1675
+ const OP_JUMP_IF_FALSE = 41; // next: offset — peek stack; if false jump forward by offset
1676
+ const OP_JUMP_IF_TRUE = 42; // next: offset — peek stack; if true jump forward by offset
1677
+ const OP_POP = 43; // pop and discard top of stack
1678
+ const OP_XOR = 44; // pop 2 booleans, push (a || b) && !(a && b)
1679
+
1680
+ // Logical marker opcodes — emitted after the short-circuit sequence.
1681
+ // The evaluate interpreter skips them (consumes the operand count byte).
1682
+ // The simplify interpreter uses them to identify the operator and arity for residual reconstruction.
1683
+ const OP_AND = 53; // next: N — marker for AND with N operands
1684
+ const OP_OR = 54; // next: N — marker for OR with N operands
1685
+ const OP_NOR = 55; // next: N — marker for NOR with N operands
1686
+ // next: N, ref0..refN-1, constIdx — resolve each ref inline, check ∈ consts[constIdx], no stack alloc
1687
+ const OP_IN_SCAN_REFS_CONST = 56;
1688
+ // next: N, ref0..refN-1, constIdx — resolve each ref inline, check ∉ consts[constIdx], no stack alloc
1689
+ const OP_NOT_IN_SCAN_REFS_CONST = 57;
1690
+
1691
+ /**
1692
+ * Reference path descriptors for the bytecode compiler and interpreter.
1693
+ *
1694
+ * CompactRef is the single runtime type stored in CompiledExpression.refs.
1695
+ * The compiler picks the right opcode per ref kind so the interpreter
1696
+ * dispatches to a dedicated handler with no secondary branching.
1697
+ *
1698
+ * string — OP_PUSH_REF_KEY — ctx[key]
1699
+ * string[] — OP_PUSH_REF_KEYS — inline multi-key walk
1700
+ * CompactRefFull (tokens) — OP_PUSH_REF_TOKENS — token walk + optional cast
1701
+ * CompactRefFull (dynamic) — OP_PUSH_REF_DYNAMIC — runtime {placeholder} substitution
1702
+ */
1703
+
1704
+
1705
+ // array index: [0]
1706
+
1707
+ /** Full compact form for refs that don't fit the short string/string[] forms. */
1708
+
1709
+ /**
1710
+ * Runtime ref representation stored in CompiledExpression.refs:
1711
+ * - `string` → single plain-key (most common)
1712
+ * - `string[]` → multi-key inline path
1713
+ * - `CompactRefFull` → token-based or dynamic
1714
+ */
1715
+
1716
+ // ---------------------------------------------------------------------------
1717
+ // Regex — parsed once at compile time
1718
+ // ---------------------------------------------------------------------------
1719
+ const keyWithArrayIndexRegex = /^(?<currentKey>[^[\]]+?)(?<indexes>(?:\[\d+])+)?$/;
1720
+ const arrayIndexRegex = /\[(\d+)]/g;
1721
+ const parseKeyRegex = /(`[^[\]]+`(\[\d+\])*|[^`.]+)/g;
1722
+ const dataTypeRegex = new RegExp(`^.+\\.\\((${Object.keys(DataType).join('|')})\\)$`);
1723
+ const castingRegex = /\.\(.+\)$/;
1724
+ function parseBacktickWrappedKey(key) {
1725
+ return key[0] === '`' && key[key.length - 1] === '`' ? key.slice(1, -1) : key;
1726
+ }
1727
+ function parseKeyComponents(key) {
1728
+ const unwrapped = parseBacktickWrappedKey(key);
1729
+ const tokens = [];
1730
+ const match = keyWithArrayIndexRegex.exec(unwrapped);
1731
+ if (match) {
1732
+ tokens.push({
1733
+ kind: 'key',
1734
+ value: parseBacktickWrappedKey(match.groups?.currentKey ?? unwrapped)
1735
+ });
1736
+ const rawIndexes = match.groups?.indexes;
1737
+ if (rawIndexes) {
1738
+ for (const idxMatch of rawIndexes.matchAll(arrayIndexRegex)) {
1739
+ tokens.push({
1740
+ kind: 'index',
1741
+ value: parseInt(idxMatch[1])
1742
+ });
1743
+ }
1744
+ }
1745
+ } else {
1746
+ tokens.push({
1747
+ kind: 'key',
1748
+ value: unwrapped
1749
+ });
1636
1750
  }
1751
+ return tokens;
1752
+ }
1753
+ function parseStaticKey(key) {
1754
+ const parts = key.match(parseKeyRegex);
1755
+ return !parts ? [] : parts.flatMap(parseKeyComponents);
1756
+ }
1757
+ function isDataTypeKey(k) {
1758
+ return k in DataType;
1759
+ }
1637
1760
 
1638
- /**
1639
- * Evaluate in the given context.
1640
- * @param {Context} ctx
1641
- * @return {boolean}
1642
- */
1643
- evaluate(ctx) {
1644
- return this.items.map(item => item.evaluate(ctx));
1761
+ /**
1762
+ * Build a CompactRef from a raw reference key string (without the $ prefix).
1763
+ * Called once at compile time; the result is stored in CompiledExpression.refs.
1764
+ */
1765
+ function buildCompactRef(rawKey) {
1766
+ let key = rawKey;
1767
+ let dataType;
1768
+ const dataTypeMatch = dataTypeRegex.exec(key);
1769
+ if (dataTypeMatch) {
1770
+ const dtKey = dataTypeMatch[1];
1771
+ if (!isDataTypeKey(dtKey)) {
1772
+ throw new Error(`unknown DataType: ${dtKey}`);
1773
+ }
1774
+ dataType = DataType[dtKey];
1775
+ key = key.replace(castingRegex, '');
1645
1776
  }
1777
+ const hasDynamic = key.indexOf('{') > -1;
1778
+ if (hasDynamic) {
1779
+ const full = {
1780
+ k: key,
1781
+ d: true
1782
+ };
1783
+ if (dataType !== undefined) {
1784
+ full.t = dataType;
1785
+ }
1786
+ return full;
1787
+ }
1788
+ const tokens = parseStaticKey(key);
1646
1789
 
1647
- /**
1648
- * {@link Evaluable.simplify}
1649
- */
1650
- simplify(...args) {
1651
- const values = [];
1652
- for (const item of this.items) {
1653
- const simplifiedItem = item.simplify(...args);
1654
- if (isEvaluable(simplifiedItem)) {
1655
- return this;
1656
- }
1657
- values.push(simplifiedItem);
1790
+ // Pure key-only path with no dataType → string or string[]
1791
+ if (!dataType && tokens.every(t => t.kind === 'key')) {
1792
+ if (tokens.length === 1) {
1793
+ return tokens[0].value;
1658
1794
  }
1659
- return values;
1795
+ return tokens.map(t => t.value);
1660
1796
  }
1661
1797
 
1662
- /**
1663
- * {@link Evaluable.serialize}
1664
- */
1665
- serialize(options) {
1666
- return this.items.map(item => isEvaluable(item) ? item.serialize(options) : item);
1798
+ // Token-based path (array indexes) or dataType cast
1799
+ const full = {
1800
+ tokens
1801
+ };
1802
+ if (dataType !== undefined) {
1803
+ full.t = dataType;
1667
1804
  }
1805
+ return full;
1806
+ }
1668
1807
 
1669
- /**
1670
- * Get the strict representation of the operand.
1671
- * @return {string}
1672
- */
1673
- toString() {
1674
- return '[' + this.items.map(item => item.toString()).join(', ') + ']';
1808
+ // ---------------------------------------------------------------------------
1809
+ // Runtime resolution called by the interpreter on every evaluate()
1810
+ // ---------------------------------------------------------------------------
1811
+
1812
+ function castValue(value, dataType) {
1813
+ let result;
1814
+ if (dataType === DataType.Number) {
1815
+ result = toNumber(value);
1816
+ } else {
1817
+ result = toString(value);
1818
+ }
1819
+ if (value && result === undefined) {
1820
+ console.warn(`Casting ${value} to ${dataType} resulted in ${result}`);
1675
1821
  }
1822
+ return result;
1676
1823
  }
1677
1824
 
1678
- // Option value whitelist
1825
+ // Matches the innermost {ref} — non-nested braces only
1826
+ const dynamicKeyRegex = /{([^{}]+)}/;
1679
1827
 
1680
- // Parser options
1828
+ /** Type-safe property access on an object narrowed from `unknown`. */
1829
+ function propAt(obj, key) {
1830
+ return Reflect.get(obj, key);
1831
+ }
1832
+
1833
+ /** Narrow a CompactRef to its string form (OP_PUSH_REF_KEY). Throws on mismatch. */
1834
+ function asKeyRef(ref) {
1835
+ if (typeof ref !== 'string') {
1836
+ throw new Error('bytecode integrity: expected string ref');
1837
+ }
1838
+ return ref;
1839
+ }
1840
+
1841
+ /** Narrow a CompactRef to its string[] form (OP_PUSH_REF_KEYS). Throws on mismatch. */
1842
+ function asKeysRef(ref) {
1843
+ if (!Array.isArray(ref)) {
1844
+ throw new Error('bytecode integrity: expected string[] ref');
1845
+ }
1846
+ return ref;
1847
+ }
1848
+
1849
+ /** Narrow a CompactRef to CompactRefFull (OP_PUSH_REF_TOKENS / OP_PUSH_REF_DYNAMIC). Throws on mismatch. */
1850
+ function asFullRef(ref) {
1851
+ if (typeof ref === 'string' || Array.isArray(ref)) {
1852
+ throw new Error('bytecode integrity: expected CompactRefFull ref');
1853
+ }
1854
+ return ref;
1855
+ }
1681
1856
 
1682
1857
  /**
1683
- * Default reference predicate.
1684
- * The "$" symbol at the begging of the operand is used
1685
- * to predicate the reference type.
1686
- * E.g. "$State", "$Country"
1687
- * @param {string} key
1688
- * @return {boolean}
1858
+ * Resolve a multi-key inline path (string[]) against a context.
1859
+ * Used by OP_PUSH_REF_KEYS and OP_PUSH_REF_DYNAMIC (after substitution).
1689
1860
  */
1690
- function defaultReferencePredicate(key) {
1691
- return key[0] === '$';
1861
+ function resolveKeys(ks, ctx) {
1862
+ const p0 = ctx[ks[0]];
1863
+ if (ks.length === 1) {
1864
+ return p0;
1865
+ }
1866
+ if (p0 === undefined || p0 === null || typeof p0 !== 'object' || Array.isArray(p0)) {
1867
+ return undefined;
1868
+ }
1869
+ const p1 = propAt(p0, ks[1]);
1870
+ if (ks.length === 2) {
1871
+ return p1;
1872
+ }
1873
+ if (p1 === undefined || p1 === null || typeof p1 !== 'object' || Array.isArray(p1)) {
1874
+ return undefined;
1875
+ }
1876
+ const p2 = propAt(p1, ks[2]);
1877
+ if (ks.length === 3) {
1878
+ return p2;
1879
+ }
1880
+ let p = p2;
1881
+ for (let k = 3; k < ks.length; k++) {
1882
+ if (p === undefined || p === null || typeof p !== 'object' || Array.isArray(p)) {
1883
+ return undefined;
1884
+ }
1885
+ p = propAt(p, ks[k]);
1886
+ }
1887
+ return p;
1692
1888
  }
1693
1889
 
1694
1890
  /**
1695
- * Default reference transform.
1696
- * It removes the "$" symbol at the begging of the operand name.
1697
- * @param {string} key
1698
- * @return {string}
1891
+ * Resolve a token-based path against a context.
1892
+ * Used by OP_PUSH_REF_TOKENS.
1699
1893
  */
1700
- function defaultReferenceTransform(key) {
1701
- return key.slice(1);
1894
+ function resolveTokens(tokens, dataType, ctx) {
1895
+ const len = tokens.length;
1896
+ let pointer = ctx;
1897
+ for (let i = 0; i < len; i++) {
1898
+ const token = tokens[i];
1899
+ if (pointer === undefined || pointer === null) {
1900
+ return dataType !== undefined ? castValue(undefined, dataType) : undefined;
1901
+ }
1902
+ if (token.kind === 'key') {
1903
+ if (typeof pointer !== 'object' || Array.isArray(pointer)) {
1904
+ return dataType !== undefined ? castValue(undefined, dataType) : undefined;
1905
+ }
1906
+ pointer = propAt(pointer, token.value);
1907
+ } else {
1908
+ if (!Array.isArray(pointer)) {
1909
+ return dataType !== undefined ? castValue(undefined, dataType) : undefined;
1910
+ }
1911
+ pointer = pointer[token.value];
1912
+ }
1913
+ }
1914
+ return dataType !== undefined ? castValue(pointer, dataType) : pointer;
1702
1915
  }
1703
- function defaultReferenceSerialization(key) {
1704
- return `$${key}`;
1916
+
1917
+ /**
1918
+ * Resolve a dynamic ref (with {placeholder} substitution) against a context.
1919
+ * Used by OP_PUSH_REF_DYNAMIC.
1920
+ */
1921
+ function resolveDynamic(key, dataType, ctx) {
1922
+ let current = key;
1923
+ let match = dynamicKeyRegex.exec(current);
1924
+ while (match) {
1925
+ const inner = resolveTokens(parseStaticKey(match[1]), undefined, ctx);
1926
+ if (inner === undefined) {
1927
+ return undefined;
1928
+ }
1929
+ current = current.replace(dynamicKeyRegex, `${inner}`);
1930
+ match = dynamicKeyRegex.exec(current);
1931
+ }
1932
+ const tokens = parseStaticKey(current);
1933
+ const raw = resolveTokens(tokens, undefined, ctx);
1934
+ return dataType !== undefined ? castValue(raw, dataType) : raw;
1705
1935
  }
1706
1936
 
1707
- // Default operator mapping
1708
- // Unique operator key <-> raw expression key
1709
- const defaultOperatorMapping = new Map([
1710
- // Comparison
1711
- [OPERATOR$h, '=='], [OPERATOR$b, '!='], [OPERATOR$f, '>'], [OPERATOR$g, '>='], [OPERATOR$c, '<'], [OPERATOR$d, '<='], [OPERATOR$e, 'IN'], [OPERATOR$a, 'NOT IN'], [OPERATOR$8, 'PREFIX'], [OPERATOR$6, 'SUFFIX'], [OPERATOR$9, 'OVERLAP'], [OPERATOR$5, 'UNDEFINED'], [OPERATOR$7, 'PRESENT'],
1712
- // Logical
1713
- [OPERATOR$4, 'AND'], [OPERATOR$1, 'OR'], [OPERATOR$2, 'NOR'], [OPERATOR, 'XOR'], [OPERATOR$3, 'NOT'],
1714
- // Arithmetic
1715
- [OPERATOR$i, '+'], [OPERATOR$j, '-'], [OPERATOR$k, '*'], [OPERATOR$l, '/']]);
1937
+ /**
1938
+ * Resolve any CompactRef against a context.
1939
+ * Used in ops that embed ref indices but weren't split by kind
1940
+ * (OP_OVERLAP_SCAN_REFS_CONST, OP_OR_AND_IN_CONST_2).
1941
+ */
1942
+ function resolveCompactRef(ref, ctx) {
1943
+ if (typeof ref === 'string') {
1944
+ return ctx[ref];
1945
+ }
1946
+ if (Array.isArray(ref)) {
1947
+ return resolveKeys(ref, ctx);
1948
+ }
1949
+ if (ref.d) {
1950
+ return resolveDynamic(ref.k, ref.t, ctx);
1951
+ }
1952
+ return resolveTokens(ref.tokens ?? [], ref.t, ctx);
1953
+ }
1716
1954
 
1717
1955
  /**
1718
- * Default parser options
1956
+ * Bytecode compiler.
1957
+ *
1958
+ * Transforms a raw ExpressionInput (plain array) into a flat Bytecode array
1959
+ * that the interpreter can execute. This runs once per unique expression;
1960
+ * the result should be cached and reused across evaluate() calls.
1719
1961
  */
1720
- const defaultOptions = {
1721
- referencePredicate: defaultReferencePredicate,
1722
- referenceTransform: defaultReferenceTransform,
1723
- referenceSerialization: defaultReferenceSerialization,
1724
- operatorMapping: defaultOperatorMapping
1725
- };
1726
1962
 
1727
- // Input types
1728
1963
 
1729
- const invalidExpression = 'invalid expression';
1730
- const logicalIfValidOperands = (operands, logical) => {
1731
- if (operands.every(operand => operand instanceof Logical || operand instanceof Comparison)) {
1732
- return logical;
1964
+ // Bytecode is a flat array of numbers (opcodes and index operands) interspersed
1965
+ // with literal Result values (for OP_PUSH_VALUE).
1966
+
1967
+ // Lookup tables built once per Options instance — operator string → opcode.
1968
+ // Stored outside emitExpression so they are not recreated on every compile call.
1969
+
1970
+ function getOperator(m, op) {
1971
+ const v = m.get(op);
1972
+ if (v === undefined) {
1973
+ throw new Error(`operator mapping missing for symbol ${op.toString()}`);
1733
1974
  }
1734
- throw new Error(invalidExpression);
1735
- };
1975
+ return v;
1976
+ }
1977
+ function buildOperatorMaps(opts) {
1978
+ const m = opts.operatorMapping;
1979
+ const get = op => getOperator(m, op);
1980
+ return {
1981
+ binary: {
1982
+ [get(OPERATOR$h)]: OP_EQ,
1983
+ [get(OPERATOR$b)]: OP_NE,
1984
+ [get(OPERATOR$f)]: OP_GT,
1985
+ [get(OPERATOR$g)]: OP_GE,
1986
+ [get(OPERATOR$c)]: OP_LT,
1987
+ [get(OPERATOR$d)]: OP_LE,
1988
+ [get(OPERATOR$e)]: OP_IN,
1989
+ [get(OPERATOR$a)]: OP_NOT_IN,
1990
+ [get(OPERATOR$8)]: OP_PREFIX,
1991
+ [get(OPERATOR$6)]: OP_SUFFIX,
1992
+ [get(OPERATOR$9)]: OP_OVERLAP
1993
+ },
1994
+ arithmetic: {
1995
+ [get(OPERATOR$i)]: OP_SUM,
1996
+ [get(OPERATOR$j)]: OP_SUBTRACT,
1997
+ [get(OPERATOR$k)]: OP_MULTIPLY,
1998
+ [get(OPERATOR$l)]: OP_DIVIDE
1999
+ },
2000
+ presentOp: get(OPERATOR$7),
2001
+ undefinedOp: get(OPERATOR$5),
2002
+ andOp: get(OPERATOR$4),
2003
+ orOp: get(OPERATOR$1),
2004
+ norOp: get(OPERATOR$2),
2005
+ notOp: get(OPERATOR$3),
2006
+ xorOp: get(OPERATOR),
2007
+ inOp: get(OPERATOR$e),
2008
+ notInOp: get(OPERATOR$a),
2009
+ overlapOp: get(OPERATOR$9),
2010
+ eqOp: get(OPERATOR$h)
2011
+ };
2012
+ }
2013
+ function isStaticCollection(raw, opts) {
2014
+ return Array.isArray(raw) && !raw.some(v => typeof v === 'string' && opts.referencePredicate(v));
2015
+ }
2016
+ function isPureRefCollection(raw, opts) {
2017
+ return Array.isArray(raw) && raw.length > 0 && raw.every(v => typeof v === 'string' && opts.referencePredicate(v));
2018
+ }
2019
+ function internConst(items, state) {
2020
+ const key = JSON.stringify(items);
2021
+ let idx = state.constIndex.get(key);
2022
+ if (idx === undefined) {
2023
+ idx = state.consts.length;
2024
+ state.consts.push(items);
2025
+ state.constIndex.set(key, idx);
2026
+ }
2027
+ return idx;
2028
+ }
1736
2029
 
1737
2030
  /**
1738
- * Parser of raw expressions into Evaluable expression
2031
+ * Returns the first context key for a multi-key ref (e.g. 'account' for $account.region),
2032
+ * or undefined for single-key refs (no heuristic needed) and dynamic refs (unknowable statically).
2033
+ * Used by the simplify interpreter to replicate OOP Reference.simplify()'s first-key check.
1739
2034
  */
1740
- class Parser {
1741
- /**
1742
- * @constructor
1743
- * @param {Options?} options Parser options.
1744
- */
1745
- constructor(options) {
1746
- _defineProperty(this, "opts", void 0);
1747
- _defineProperty(this, "expectedRootOperators", void 0);
1748
- _defineProperty(this, "unexpectedRootSymbols", new Set([OPERATOR$i, OPERATOR$j, OPERATOR$k, OPERATOR$l]));
1749
- _defineProperty(this, "referenceCache", new Map());
1750
- this.opts = {
1751
- ...defaultOptions
1752
- };
1753
- // Apply exclusive options overrides
1754
- if (options) {
1755
- for (const key of Object.keys(options)) {
1756
- if (key in this.opts) {
1757
- this.opts[key] = options[key];
2035
+ function getFirstCtxKey(ref) {
2036
+ if (typeof ref === 'string') {
2037
+ return undefined; // single-key ref — OOP checks ctx[key] directly, no first-key shortcut
2038
+ }
2039
+ if (Array.isArray(ref)) {
2040
+ return ref[0]; // multi-key path: first element is the top-level context key
2041
+ }
2042
+ if (ref.d) {
2043
+ return undefined; // dynamic ref with {placeholder}: can't determine first key statically
2044
+ }
2045
+ const tokens = ref.tokens;
2046
+ if (tokens && tokens.length > 0 && tokens[0].kind === 'key') {
2047
+ return tokens[0].value;
2048
+ }
2049
+ return undefined;
2050
+ }
2051
+ function refOpcode(ref) {
2052
+ if (typeof ref === 'string') {
2053
+ return OP_PUSH_REF_KEY;
2054
+ }
2055
+ if (Array.isArray(ref)) {
2056
+ return OP_PUSH_REF_KEYS;
2057
+ }
2058
+ if (ref.d) {
2059
+ return OP_PUSH_REF_DYNAMIC;
2060
+ }
2061
+ return OP_PUSH_REF_TOKENS;
2062
+ }
2063
+ function internRef(raw, state) {
2064
+ const key = state.opts.referenceTransform(raw);
2065
+ let refIndex = state.refIndex.get(key);
2066
+ if (refIndex === undefined) {
2067
+ refIndex = state.refs.length;
2068
+ state.refs.push(buildCompactRef(key));
2069
+ state.refIndex.set(key, refIndex);
2070
+ state.refRawKeys.push(key);
2071
+ state.refKeys.push(raw);
2072
+ }
2073
+ return refIndex;
2074
+ }
2075
+ function emitOperand(raw, state) {
2076
+ const {
2077
+ bytecode,
2078
+ refs,
2079
+ opts
2080
+ } = state;
2081
+ if (Array.isArray(raw)) {
2082
+ const hasDynamic = raw.some(v => typeof v === 'string' && opts.referencePredicate(v));
2083
+ if (hasDynamic) {
2084
+ // CSE: if this dynamic collection has been seen before, reuse the cached local slot
2085
+ const cseKey = JSON.stringify(raw);
2086
+ const existingSlot = state.collectionCse.get(cseKey);
2087
+ if (existingSlot !== undefined) {
2088
+ bytecode.push(OP_LOAD_LOCAL, existingSlot);
2089
+ return;
2090
+ }
2091
+ // First occurrence: emit normally, then store result in a new local slot
2092
+ for (const item of raw) {
2093
+ emitOperand(item, state);
2094
+ }
2095
+ bytecode.push(OP_MAKE_COLLECTION, raw.length);
2096
+ const slot = state.numLocals++;
2097
+ state.collectionCse.set(cseKey, slot);
2098
+ bytecode.push(OP_STORE_LOCAL, slot);
2099
+ return;
2100
+ }
2101
+
2102
+ // Static collection: intern into consts table, emit OP_PUSH_CONST
2103
+ bytecode.push(OP_PUSH_CONST, internConst(raw, state));
2104
+ return;
2105
+ }
2106
+ if (typeof raw === 'string' && opts.referencePredicate(raw)) {
2107
+ const refIndex = internRef(raw, state);
2108
+ bytecode.push(refOpcode(refs[refIndex]), refIndex);
2109
+ return;
2110
+ }
2111
+ bytecode.push(OP_PUSH_VALUE, raw);
2112
+ }
2113
+
2114
+ /**
2115
+ * Return the ref key and static value array for a branch child that is either:
2116
+ * IN(ref, [v1, v2, ...]) — ref ∈ static collection
2117
+ * ==(ref, scalar) — ref === scalar, treated as IN with [scalar]
2118
+ * Returns null if the child does not match either form.
2119
+ */
2120
+ function extractInLikeChild(ca, state) {
2121
+ const op = ca[0];
2122
+ const left = ca[1];
2123
+ if (typeof left !== 'string' || !state.opts.referencePredicate(left)) {
2124
+ return null;
2125
+ }
2126
+ // left is narrowed to string by the guard above
2127
+ const rawRef = left;
2128
+ const refKey = state.opts.referenceTransform(rawRef);
2129
+ if (op === state.maps.inOp) {
2130
+ const right = ca[2];
2131
+ if (!isStaticCollection(right, state.opts)) {
2132
+ return null;
2133
+ }
2134
+ return {
2135
+ rawRef,
2136
+ refKey,
2137
+ vals: right
2138
+ };
2139
+ }
2140
+
2141
+ // == (EQ): scalar equality treated as single-element IN
2142
+ if (op === state.maps.eqOp) {
2143
+ const right = ca[2];
2144
+ if (typeof right === 'string' && state.opts.referencePredicate(right)) {
2145
+ return null;
2146
+ }
2147
+ if (Array.isArray(right)) {
2148
+ return null;
2149
+ }
2150
+ return {
2151
+ rawRef,
2152
+ refKey,
2153
+ vals: [right]
2154
+ };
2155
+ }
2156
+ return null;
2157
+ }
2158
+
2159
+ /**
2160
+ * Check whether an OR expression matches the pattern:
2161
+ * OR( AND(IN-like(ref1, set1), IN-like(ref2, set2)), ... )
2162
+ * where IN-like is either IN(ref, staticSet) or ==(ref, scalar),
2163
+ * and every branch uses the exact same two refs in the same order.
2164
+ *
2165
+ * Builds an inverted index: for each unique value in any setA, union-merges all
2166
+ * setB values across branches where that setA value appears, and emits one
2167
+ * (literal value, mergedSetBIdx) entry per distinct setA value.
2168
+ *
2169
+ * This lets the interpreter do a single O(1) Map lookup on ref1 to find all
2170
+ * relevant setB indices, instead of a linear scan through N setA Sets.
2171
+ * Returns null if the pattern does not match.
2172
+ */
2173
+ function detectOrAndIn2Pattern(arr, state) {
2174
+ const nBranches = arr.length - 1;
2175
+ if (nBranches < 2) {
2176
+ return null;
2177
+ }
2178
+ let ref1Raw = null;
2179
+ let ref2Raw = null;
2180
+ let refKey1 = null;
2181
+ let refKey2 = null;
2182
+
2183
+ // Inverted index: each distinct setA value → merged setB values across all branches containing it
2184
+ const setBValsByAValue = new Map();
2185
+ for (let b = 1; b <= nBranches; b++) {
2186
+ const branch = arr[b];
2187
+ if (!Array.isArray(branch)) {
2188
+ return null;
2189
+ }
2190
+ if (branch[0] !== state.maps.andOp) {
2191
+ return null;
2192
+ }
2193
+ if (branch.length !== 3) {
2194
+ return null;
2195
+ }
2196
+ let extA = null;
2197
+ let extB = null;
2198
+ for (let c = 1; c <= 2; c++) {
2199
+ const child = branch[c];
2200
+ if (!Array.isArray(child)) {
2201
+ return null;
2202
+ }
2203
+ const extracted = extractInLikeChild(child, state);
2204
+ if (extracted === null) {
2205
+ return null;
2206
+ }
2207
+ const {
2208
+ rawRef,
2209
+ refKey
2210
+ } = extracted;
2211
+ if (c === 1) {
2212
+ extA = extracted;
2213
+ if (b === 1) {
2214
+ ref1Raw = rawRef;
2215
+ refKey1 = refKey;
2216
+ } else if (refKey !== refKey1) {
2217
+ return null;
2218
+ }
2219
+ } else {
2220
+ extB = extracted;
2221
+ if (b === 1) {
2222
+ ref2Raw = rawRef;
2223
+ refKey2 = refKey;
2224
+ } else if (refKey !== refKey2) {
2225
+ return null;
2226
+ }
2227
+ }
2228
+ }
2229
+ if (extA === null || extB === null) {
2230
+ return null;
2231
+ }
2232
+
2233
+ // For each value in setA, union-merge all setB values
2234
+ for (const aVal of extA.vals) {
2235
+ let setBVals = setBValsByAValue.get(aVal);
2236
+ if (setBVals === undefined) {
2237
+ setBVals = new Set();
2238
+ setBValsByAValue.set(aVal, setBVals);
2239
+ }
2240
+ for (const bVal of extB.vals) {
2241
+ setBVals.add(bVal);
2242
+ }
2243
+ }
2244
+ }
2245
+ if (ref1Raw === null || ref2Raw === null) {
2246
+ return null;
2247
+ }
2248
+
2249
+ // Build entries: one (literal aVal, mergedSetBIdx) per distinct setA value
2250
+ const entries = [];
2251
+ for (const [aVal, setBVals] of setBValsByAValue) {
2252
+ const mergedSetB = [...setBVals].filter(v => v !== undefined);
2253
+ entries.push([aVal, internConst(mergedSetB, state)]);
2254
+ }
2255
+ return {
2256
+ ref1Raw,
2257
+ ref2Raw,
2258
+ entries
2259
+ };
2260
+ }
2261
+
2262
+ // arr[0] is the operator; operands are arr[1..arr.length-1]
2263
+ function emitShortCircuit(arr, jumpOp, markerOp, state) {
2264
+ const {
2265
+ bytecode
2266
+ } = state;
2267
+ const jumpSlots = [];
2268
+ const last = arr.length - 1;
2269
+ for (let i = 1; i < last; i++) {
2270
+ emitExpression(arr[i], state);
2271
+ bytecode.push(jumpOp);
2272
+ jumpSlots.push(bytecode.length);
2273
+ bytecode.push(0); // placeholder — backpatched below
2274
+ bytecode.push(OP_POP); // discard result before evaluating next operand
2275
+ }
2276
+ emitExpression(arr[last], state);
2277
+ const end = bytecode.length;
2278
+ for (const slot of jumpSlots) {
2279
+ bytecode[slot] = end - slot - 1;
2280
+ }
2281
+
2282
+ // Emit marker so the simplify interpreter knows the operator and operand count
2283
+ bytecode.push(markerOp, last);
2284
+ }
2285
+ function emitExpression(raw, state) {
2286
+ const {
2287
+ bytecode,
2288
+ maps
2289
+ } = state;
2290
+ if (!Array.isArray(raw)) {
2291
+ emitOperand(raw, state);
2292
+ return;
2293
+ }
2294
+ const arr = raw;
2295
+ const operator = arr[0];
2296
+ const nOperands = arr.length - 1;
2297
+ if (typeof operator !== 'string') {
2298
+ emitOperand(raw, state);
2299
+ return;
2300
+ }
2301
+
2302
+ // ---------------------------------------------------------------------------
2303
+ // Logical — short-circuit with jump instructions
2304
+ // ---------------------------------------------------------------------------
2305
+ if (operator === maps.andOp) {
2306
+ emitShortCircuit(arr, OP_JUMP_IF_FALSE, OP_AND, state);
2307
+ return;
2308
+ }
2309
+ if (operator === maps.orOp) {
2310
+ const orAnd2 = detectOrAndIn2Pattern(arr, state);
2311
+ if (orAnd2 !== null) {
2312
+ const {
2313
+ ref1Raw,
2314
+ ref2Raw,
2315
+ entries
2316
+ } = orAnd2;
2317
+ const {
2318
+ bytecode
2319
+ } = state;
2320
+ const ref1Idx = internRef(ref1Raw, state);
2321
+ const ref2Idx = internRef(ref2Raw, state);
2322
+ // Emit: OP_OR_AND_IN_CONST_2 ref1Idx ref2Idx M v0 setBIdx0 v1 setBIdx1 ... vM-1 setBIdxM-1
2323
+ // M is the number of distinct setA values across all branches (after inverted-index merge).
2324
+ bytecode.push(OP_OR_AND_IN_CONST_2, ref1Idx, ref2Idx, entries.length);
2325
+ for (const [aVal, mergedSetBIdx] of entries) {
2326
+ bytecode.push(aVal, mergedSetBIdx);
2327
+ }
2328
+ return;
2329
+ }
2330
+ emitShortCircuit(arr, OP_JUMP_IF_TRUE, OP_OR, state);
2331
+ return;
2332
+ }
2333
+ if (operator === maps.norOp) {
2334
+ // NOR = NOT OR: emit as OR with short-circuit, then negate
2335
+ emitShortCircuit(arr, OP_JUMP_IF_TRUE, OP_NOR, state);
2336
+ bytecode.push(OP_NOT);
2337
+ return;
2338
+ }
2339
+ if (operator === maps.notOp) {
2340
+ emitExpression(arr[1], state);
2341
+ bytecode.push(OP_NOT);
2342
+ return;
2343
+ }
2344
+ if (operator === maps.xorOp) {
2345
+ // XOR is associative: chain binary XOR operations
2346
+ // (A XOR B) XOR C XOR D ...
2347
+ emitExpression(arr[1], state);
2348
+ for (let i = 2; i <= nOperands; i++) {
2349
+ emitExpression(arr[i], state);
2350
+ bytecode.push(OP_XOR);
2351
+ }
2352
+ return;
2353
+ }
2354
+
2355
+ // ---------------------------------------------------------------------------
2356
+ // Comparison — binary (left, right)
2357
+ // ---------------------------------------------------------------------------
2358
+
2359
+ // IN / NOT_IN: optimized paths when one operand is a collection
2360
+ if (operator === maps.inOp || operator === maps.notInOp) {
2361
+ const left = arr[1];
2362
+ const right = arr[2];
2363
+ if (Array.isArray(left) && !Array.isArray(right)) {
2364
+ const leftArr = left;
2365
+ const leftHasDynamic = leftArr.some(v => typeof v === 'string' && state.opts.referencePredicate(v));
2366
+ const constOp = operator === maps.inOp ? OP_IN_CONST : OP_NOT_IN_CONST;
2367
+ const collectionOp = operator === maps.inOp ? OP_IN_COLLECTION : OP_NOT_IN_COLLECTION;
2368
+ if (!leftHasDynamic) {
2369
+ // fully static collection on left — intern as const, Set-lookup the scalar
2370
+ emitExpression(right, state);
2371
+ const opcodePos = bytecode.length;
2372
+ bytecode.push(constOp, internConst(leftArr, state));
2373
+ state.directionEntries.push({
2374
+ pos: opcodePos,
2375
+ dir: 0
2376
+ });
2377
+ } else if (isPureRefCollection(leftArr, state.opts) && !(typeof right === 'string' && state.opts.referencePredicate(right))) {
2378
+ // pure-ref collection on left, concrete scalar on right — inline ref scan, no stack alloc
2379
+ const scanOp = operator === maps.inOp ? OP_IN_SCAN_REFS_CONST : OP_NOT_IN_SCAN_REFS_CONST;
2380
+ const constIdx = internConst([right], state);
2381
+ const opcodePos = bytecode.length;
2382
+ const refIdxs = [];
2383
+ bytecode.push(scanOp, leftArr.length);
2384
+ for (const item of leftArr) {
2385
+ const refIdx = internRef(item, state);
2386
+ bytecode.push(refIdx);
2387
+ refIdxs.push(refIdx);
2388
+ }
2389
+ bytecode.push(constIdx);
2390
+ state.directionEntries.push({
2391
+ pos: opcodePos,
2392
+ dir: 0
2393
+ });
2394
+ state.overlapRefsEntries.push({
2395
+ pos: opcodePos,
2396
+ refIdxs
2397
+ });
2398
+ } else {
2399
+ // mixed dynamic collection on left — inline stack scan
2400
+ for (const item of leftArr) {
2401
+ emitOperand(item, state);
2402
+ }
2403
+ emitExpression(right, state);
2404
+ const opcodePos = bytecode.length;
2405
+ bytecode.push(collectionOp, leftArr.length);
2406
+ state.directionEntries.push({
2407
+ pos: opcodePos,
2408
+ dir: 0
2409
+ });
2410
+ }
2411
+ return;
2412
+ }
2413
+ if (Array.isArray(right) && !Array.isArray(left)) {
2414
+ const rightArr = right;
2415
+ const rightHasDynamic = rightArr.some(v => typeof v === 'string' && state.opts.referencePredicate(v));
2416
+ const constOp = operator === maps.inOp ? OP_IN_CONST : OP_NOT_IN_CONST;
2417
+ const collectionOp = operator === maps.inOp ? OP_IN_COLLECTION : OP_NOT_IN_COLLECTION;
2418
+ if (!rightHasDynamic) {
2419
+ // fully static collection on right — intern as const, Set-lookup the scalar
2420
+ emitExpression(left, state);
2421
+ const opcodePos = bytecode.length;
2422
+ bytecode.push(constOp, internConst(rightArr, state));
2423
+ state.directionEntries.push({
2424
+ pos: opcodePos,
2425
+ dir: 1
2426
+ });
2427
+ } else if (isPureRefCollection(rightArr, state.opts) && !(typeof left === 'string' && state.opts.referencePredicate(left))) {
2428
+ // pure-ref collection on right, concrete scalar on left — inline ref scan, no stack alloc
2429
+ const scanOp = operator === maps.inOp ? OP_IN_SCAN_REFS_CONST : OP_NOT_IN_SCAN_REFS_CONST;
2430
+ const constIdx = internConst([left], state);
2431
+ const opcodePos = bytecode.length;
2432
+ const refIdxs = [];
2433
+ bytecode.push(scanOp, rightArr.length);
2434
+ for (const item of rightArr) {
2435
+ const refIdx = internRef(item, state);
2436
+ bytecode.push(refIdx);
2437
+ refIdxs.push(refIdx);
2438
+ }
2439
+ bytecode.push(constIdx);
2440
+ state.directionEntries.push({
2441
+ pos: opcodePos,
2442
+ dir: 1
2443
+ });
2444
+ state.overlapRefsEntries.push({
2445
+ pos: opcodePos,
2446
+ refIdxs
2447
+ });
2448
+ } else {
2449
+ // mixed dynamic collection on right — inline stack scan
2450
+ for (const item of rightArr) {
2451
+ emitOperand(item, state);
2452
+ }
2453
+ emitExpression(left, state);
2454
+ const opcodePos = bytecode.length;
2455
+ bytecode.push(collectionOp, rightArr.length);
2456
+ state.directionEntries.push({
2457
+ pos: opcodePos,
2458
+ dir: 1
2459
+ });
2460
+ }
2461
+ return;
2462
+ }
2463
+ // both sides are dynamic (refs) — fall through to generic OP_IN / OP_NOT_IN
2464
+ }
2465
+
2466
+ // OVERLAP: if exactly one operand is a static collection, emit optimized path
2467
+ if (operator === maps.overlapOp) {
2468
+ const left = arr[1];
2469
+ const right = arr[2];
2470
+ if (isStaticCollection(left, state.opts) && !isStaticCollection(right, state.opts)) {
2471
+ const constIdx = internConst(left, state);
2472
+ if (isPureRefCollection(right, state.opts)) {
2473
+ // dynamic side is all refs — inline ref indices, resolve+check at runtime, no stack alloc
2474
+ const opcodePos = bytecode.length;
2475
+ bytecode.push(OP_OVERLAP_SCAN_REFS_CONST, right.length);
2476
+ const refIdxs = [];
2477
+ for (const item of right) {
2478
+ if (typeof item !== 'string') {
2479
+ throw new Error('OVERLAP: expected string ref in pure-ref collection');
2480
+ }
2481
+ const refIdx = internRef(item, state);
2482
+ bytecode.push(refIdx);
2483
+ refIdxs.push(refIdx);
2484
+ }
2485
+ bytecode.push(constIdx);
2486
+ state.directionEntries.push({
2487
+ pos: opcodePos,
2488
+ dir: 0
2489
+ });
2490
+ state.overlapRefsEntries.push({
2491
+ pos: opcodePos,
2492
+ refIdxs
2493
+ });
2494
+ } else {
2495
+ emitExpression(right, state);
2496
+ const opcodePos = bytecode.length;
2497
+ bytecode.push(OP_OVERLAP_CONST, constIdx);
2498
+ state.directionEntries.push({
2499
+ pos: opcodePos,
2500
+ dir: 0
2501
+ });
2502
+ }
2503
+ return;
2504
+ }
2505
+ if (isStaticCollection(right, state.opts) && !isStaticCollection(left, state.opts)) {
2506
+ const constIdx = internConst(right, state);
2507
+ if (isPureRefCollection(left, state.opts)) {
2508
+ // dynamic side is all refs — inline ref indices, resolve+check at runtime, no stack alloc
2509
+ const opcodePos = bytecode.length;
2510
+ bytecode.push(OP_OVERLAP_SCAN_REFS_CONST, left.length);
2511
+ const refIdxs = [];
2512
+ for (const item of left) {
2513
+ if (typeof item !== 'string') {
2514
+ throw new Error('OVERLAP: expected string ref in pure-ref collection');
2515
+ }
2516
+ const refIdx = internRef(item, state);
2517
+ bytecode.push(refIdx);
2518
+ refIdxs.push(refIdx);
2519
+ }
2520
+ bytecode.push(constIdx);
2521
+ state.directionEntries.push({
2522
+ pos: opcodePos,
2523
+ dir: 1
2524
+ });
2525
+ state.overlapRefsEntries.push({
2526
+ pos: opcodePos,
2527
+ refIdxs
2528
+ });
2529
+ } else {
2530
+ emitExpression(left, state);
2531
+ const opcodePos = bytecode.length;
2532
+ bytecode.push(OP_OVERLAP_CONST, constIdx);
2533
+ state.directionEntries.push({
2534
+ pos: opcodePos,
2535
+ dir: 1
2536
+ });
2537
+ }
2538
+ return;
2539
+ }
2540
+ // Both static or both dynamic: fall through to generic OP_OVERLAP
2541
+ }
2542
+ if (operator in maps.binary) {
2543
+ emitExpression(arr[1], state);
2544
+ emitExpression(arr[2], state);
2545
+ bytecode.push(maps.binary[operator]);
2546
+ return;
2547
+ }
2548
+
2549
+ // ---------------------------------------------------------------------------
2550
+ // Unary comparison
2551
+ // ---------------------------------------------------------------------------
2552
+ if (operator === maps.presentOp) {
2553
+ emitExpression(arr[1], state);
2554
+ bytecode.push(OP_PRESENT);
2555
+ return;
2556
+ }
2557
+ if (operator === maps.undefinedOp) {
2558
+ emitExpression(arr[1], state);
2559
+ bytecode.push(OP_UNDEFINED);
2560
+ return;
2561
+ }
2562
+
2563
+ // ---------------------------------------------------------------------------
2564
+ // Arithmetic — N operands
2565
+ // ---------------------------------------------------------------------------
2566
+ if (operator in maps.arithmetic) {
2567
+ for (let i = 1; i <= nOperands; i++) {
2568
+ emitExpression(arr[i], state);
2569
+ }
2570
+ bytecode.push(maps.arithmetic[operator], nOperands);
2571
+ return;
2572
+ }
2573
+
2574
+ // ---------------------------------------------------------------------------
2575
+ // Fallback: treat as collection (array of values/refs)
2576
+ // ---------------------------------------------------------------------------
2577
+ emitOperand(raw, state);
2578
+ }
2579
+ /**
2580
+ * Compile a raw ExpressionInput into bytecode.
2581
+ * The result should be cached and reused across evaluate() calls.
2582
+ */
2583
+ function compile(raw, opts) {
2584
+ const maps = buildOperatorMaps(opts);
2585
+ const state = {
2586
+ bytecode: [],
2587
+ refs: [],
2588
+ refIndex: new Map(),
2589
+ refRawKeys: [],
2590
+ refKeys: [],
2591
+ opts,
2592
+ maps,
2593
+ collectionCse: new Map(),
2594
+ numLocals: 0,
2595
+ consts: [],
2596
+ constIndex: new Map(),
2597
+ overlapRefsEntries: [],
2598
+ directionEntries: []
2599
+ };
2600
+ emitExpression(raw, state);
2601
+
2602
+ // Build reverse map: opcode → operator string for residual reconstruction
2603
+ const opNames = {};
2604
+ for (const [str, code] of Object.entries(maps.binary)) {
2605
+ opNames[code] = str;
2606
+ }
2607
+ for (const [str, code] of Object.entries(maps.arithmetic)) {
2608
+ opNames[code] = str;
2609
+ }
2610
+ opNames[OP_NOT] = maps.notOp;
2611
+ opNames[OP_AND] = maps.andOp;
2612
+ opNames[OP_OR] = maps.orOp;
2613
+ opNames[OP_NOR] = maps.norOp;
2614
+ opNames[OP_XOR] = maps.xorOp;
2615
+ opNames[OP_PRESENT] = maps.presentOp;
2616
+ opNames[OP_UNDEFINED] = maps.undefinedOp;
2617
+ opNames[OP_IN_COLLECTION] = maps.inOp;
2618
+ opNames[OP_NOT_IN_COLLECTION] = maps.notInOp;
2619
+ opNames[OP_IN_CONST] = maps.inOp;
2620
+ opNames[OP_NOT_IN_CONST] = maps.notInOp;
2621
+ opNames[OP_OVERLAP_CONST] = maps.overlapOp;
2622
+ opNames[OP_OVERLAP_SCAN_REFS_CONST] = maps.overlapOp;
2623
+ opNames[OP_IN_SCAN_REFS_CONST] = maps.inOp;
2624
+ opNames[OP_NOT_IN_SCAN_REFS_CONST] = maps.notInOp;
2625
+
2626
+ // Pre-build residual Input[] arrays for OP_OVERLAP_SCAN_REFS_CONST — eliminates per-call allocation in the simplifier
2627
+ const overlapRefsResiduals = state.overlapRefsEntries.map(({
2628
+ pos,
2629
+ refIdxs
2630
+ }) => [pos, refIdxs.map(idx => state.refKeys[idx])]);
2631
+
2632
+ // Build direction entries as serializable tuple array
2633
+ const directionMap = state.directionEntries.map(({
2634
+ pos,
2635
+ dir
2636
+ }) => [pos, dir]);
2637
+ return {
2638
+ bytecode: state.bytecode,
2639
+ refs: state.refs,
2640
+ numLocals: state.numLocals,
2641
+ consts: state.consts,
2642
+ opNames,
2643
+ refKeys: state.refKeys,
2644
+ refRawKeys: state.refRawKeys,
2645
+ overlapRefsResiduals,
2646
+ directionMap,
2647
+ refFirstCtxKeys: state.refs.map(getFirstCtxKey)
2648
+ };
2649
+ }
2650
+
2651
+ const getNumDecimals = num => {
2652
+ const numberSplit = num.toString().split('.');
2653
+ return numberSplit.length == 2 ? numberSplit[1].length : 0;
2654
+ };
2655
+ const operateWithExpectedDecimals = operation => (first, second) => {
2656
+ const numDecimals1 = getNumDecimals(first);
2657
+ const numDecimals2 = getNumDecimals(second);
2658
+ const maxDecimals = operation === 'multiply' ? numDecimals1 + numDecimals2 : numDecimals1 > numDecimals2 ? numDecimals1 : numDecimals2;
2659
+ return operation === 'sum' ? Number((first + second).toFixed(maxDecimals)) : operation === 'subtract' ? Number((first - second).toFixed(maxDecimals)) : Number((first * second).toFixed(maxDecimals));
2660
+ };
2661
+
2662
+ /**
2663
+ * Bytecode interpreter.
2664
+ *
2665
+ * Executes a compiled bytecode array against a context object.
2666
+ * Zero allocations in the hot path: uses a pre-allocated stack
2667
+ * and operates on the flat bytecode array directly.
2668
+ */
2669
+
2670
+
2671
+ // Read a numeric value from a bytecode slot — opcodes and index operands are always numbers.
2672
+ // Throws if the slot contains a non-number (guards against compiler bugs).
2673
+ function numAt$1(v) {
2674
+ if (typeof v !== 'number') {
2675
+ throw new Error(`bytecode integrity error: expected number, got ${typeof v}`);
2676
+ }
2677
+ return v;
2678
+ }
2679
+ const addDecimals$1 = operateWithExpectedDecimals('sum');
2680
+ const subtractDecimals$1 = operateWithExpectedDecimals('subtract');
2681
+ const multiplyDecimals$1 = operateWithExpectedDecimals('multiply');
2682
+ const divideDecimals$1 = (a, b) => a / b;
2683
+
2684
+ // Pre-allocated stack — safe because evaluation is synchronous and non-reentrant
2685
+ const MAX_STACK$1 = 512;
2686
+ const stack$1 = new Array(MAX_STACK$1);
2687
+ let stackTop$1 = -1;
2688
+
2689
+ // Pre-allocated locals for CSE collection caching — grown on demand
2690
+ const MAX_LOCALS$1 = 64;
2691
+ const locals$1 = new Array(MAX_LOCALS$1);
2692
+ function relationalCompare$1(left, right, op) {
2693
+ if (isNumber(left) && isNumber(right)) {
2694
+ if (op === OP_GT) {
2695
+ return left > right;
2696
+ }
2697
+ if (op === OP_GE) {
2698
+ return left >= right;
2699
+ }
2700
+ if (op === OP_LT) {
2701
+ return left < right;
2702
+ }
2703
+ return left <= right;
2704
+ }
2705
+ const ld = toDateNumber(left);
2706
+ const rd = toDateNumber(right);
2707
+ if (!isNaN(ld) && !isNaN(rd)) {
2708
+ if (op === OP_GT) {
2709
+ return ld > rd;
2710
+ }
2711
+ if (op === OP_GE) {
2712
+ return ld >= rd;
2713
+ }
2714
+ if (op === OP_LT) {
2715
+ return ld < rd;
2716
+ }
2717
+ return ld <= rd;
2718
+ }
2719
+ return false;
2720
+ }
2721
+ function arithmeticReduce$1(values, op) {
2722
+ if (op === OP_SUM) {
2723
+ return values.reduce(addDecimals$1);
2724
+ }
2725
+ if (op === OP_SUBTRACT) {
2726
+ return values.reduce(subtractDecimals$1);
2727
+ }
2728
+ if (op === OP_MULTIPLY) {
2729
+ return values.reduce(multiplyDecimals$1);
2730
+ }
2731
+ return values.reduce(divideDecimals$1);
2732
+ }
2733
+
2734
+ /**
2735
+ * Execute compiled bytecode against a context.
2736
+ * Returns the top-of-stack value when execution completes.
2737
+ */
2738
+ // Per-compiled-expression Set cache — one WeakMap lookup per interpret() call,
2739
+ // then all Set lookups use plain array indexing by constIdx.
2740
+ const constSetsCache = new WeakMap();
2741
+ function interpret(compiled, ctx) {
2742
+ const {
2743
+ bytecode,
2744
+ refs,
2745
+ consts
2746
+ } = compiled;
2747
+ let constSets = constSetsCache.get(compiled);
2748
+ if (constSets === undefined) {
2749
+ constSets = new Array(consts.length);
2750
+ for (let j = 0; j < consts.length; j++) {
2751
+ constSets[j] = new Set(consts[j]);
2752
+ }
2753
+ constSetsCache.set(compiled, constSets);
2754
+ }
2755
+ const len = bytecode.length;
2756
+ stackTop$1 = -1;
2757
+ let i = 0;
2758
+ while (i < len) {
2759
+ const op = numAt$1(bytecode[i]);
2760
+ switch (op) {
2761
+ // -----------------------------------------------------------------------
2762
+ // Operands
2763
+ // -----------------------------------------------------------------------
2764
+ case OP_PUSH_VALUE:
2765
+ stack$1[++stackTop$1] = bytecode[++i];
2766
+ break;
2767
+ case OP_PUSH_REF_KEY:
2768
+ stack$1[++stackTop$1] = ctx[asKeyRef(refs[numAt$1(bytecode[++i])])];
2769
+ break;
2770
+ case OP_PUSH_REF_KEYS:
2771
+ stack$1[++stackTop$1] = resolveKeys(asKeysRef(refs[numAt$1(bytecode[++i])]), ctx);
2772
+ break;
2773
+ case OP_PUSH_REF_TOKENS:
2774
+ {
2775
+ const ref = asFullRef(refs[numAt$1(bytecode[++i])]);
2776
+ stack$1[++stackTop$1] = resolveTokens(ref.tokens ?? [], ref.t, ctx);
2777
+ break;
2778
+ }
2779
+ case OP_PUSH_REF_DYNAMIC:
2780
+ {
2781
+ const ref = asFullRef(refs[numAt$1(bytecode[++i])]);
2782
+ stack$1[++stackTop$1] = resolveDynamic(ref.k, ref.t, ctx);
2783
+ break;
2784
+ }
2785
+ case OP_MAKE_COLLECTION:
2786
+ {
2787
+ const n = numAt$1(bytecode[++i]);
2788
+ const arr = new Array(n);
2789
+ for (let j = n - 1; j >= 0; j--) {
2790
+ arr[j] = stack$1[stackTop$1--];
2791
+ }
2792
+ stack$1[++stackTop$1] = arr;
2793
+ break;
2794
+ }
2795
+ case OP_PUSH_CONST:
2796
+ stack$1[++stackTop$1] = consts[numAt$1(bytecode[++i])];
2797
+ break;
2798
+ case OP_OVERLAP_CONST:
2799
+ {
2800
+ const constIdx = numAt$1(bytecode[++i]);
2801
+ const constArr = consts[constIdx];
2802
+ const dynamic = stack$1[stackTop$1--];
2803
+ if (!Array.isArray(dynamic)) {
2804
+ stack$1[++stackTop$1] = false;
2805
+ break;
2806
+ }
2807
+ const dLen = dynamic.length;
2808
+ const cLen = constArr.length;
2809
+ if (cLen === 0 && dLen === 0) {
2810
+ stack$1[++stackTop$1] = true;
2811
+ break;
2812
+ }
2813
+ let found = false;
2814
+ if (cLen === 1) {
2815
+ const target = constArr[0];
2816
+ for (let j = 0; j < dLen; j++) {
2817
+ if (dynamic[j] === target) {
2818
+ found = true;
2819
+ break;
2820
+ }
2821
+ }
2822
+ } else {
2823
+ const s = constSets[constIdx];
2824
+ for (let j = 0; j < dLen; j++) {
2825
+ if (s.has(dynamic[j])) {
2826
+ found = true;
2827
+ break;
2828
+ }
2829
+ }
2830
+ }
2831
+ stack$1[++stackTop$1] = found;
2832
+ break;
2833
+ }
2834
+ case OP_STORE_LOCAL:
2835
+ // Peek top (don't pop) and store into locals slot
2836
+ locals$1[numAt$1(bytecode[++i])] = stack$1[stackTop$1];
2837
+ break;
2838
+ case OP_LOAD_LOCAL:
2839
+ stack$1[++stackTop$1] = locals$1[numAt$1(bytecode[++i])];
2840
+ break;
2841
+
2842
+ // -----------------------------------------------------------------------
2843
+ // Equality
2844
+ // -----------------------------------------------------------------------
2845
+ case OP_EQ:
2846
+ {
2847
+ const right = stack$1[stackTop$1--];
2848
+ const left = stack$1[stackTop$1--];
2849
+ stack$1[++stackTop$1] = left === right;
2850
+ break;
2851
+ }
2852
+ case OP_NE:
2853
+ {
2854
+ const right = stack$1[stackTop$1--];
2855
+ const left = stack$1[stackTop$1--];
2856
+ stack$1[++stackTop$1] = left !== right;
2857
+ break;
2858
+ }
2859
+
2860
+ // -----------------------------------------------------------------------
2861
+ // Relational
2862
+ // -----------------------------------------------------------------------
2863
+ case OP_GT:
2864
+ case OP_GE:
2865
+ case OP_LT:
2866
+ case OP_LE:
2867
+ {
2868
+ const right = stack$1[stackTop$1--];
2869
+ const left = stack$1[stackTop$1--];
2870
+ stack$1[++stackTop$1] = relationalCompare$1(left, right, op);
2871
+ break;
2872
+ }
2873
+
2874
+ // -----------------------------------------------------------------------
2875
+ // Containment
2876
+ // -----------------------------------------------------------------------
2877
+ case OP_IN:
2878
+ {
2879
+ const right = stack$1[stackTop$1--];
2880
+ const left = stack$1[stackTop$1--];
2881
+ if (left === null || left === undefined || right === null || right === undefined) {
2882
+ stack$1[++stackTop$1] = false;
2883
+ break;
2884
+ }
2885
+ if (Array.isArray(left) && Array.isArray(right)) {
2886
+ throw new Error('IN: both operands are arrays');
2887
+ }
2888
+ if (!Array.isArray(left) && !Array.isArray(right)) {
2889
+ throw new Error('IN: neither operand is an array');
2890
+ }
2891
+ if (Array.isArray(left)) {
2892
+ stack$1[++stackTop$1] = left.indexOf(right) > -1;
2893
+ } else if (Array.isArray(right)) {
2894
+ stack$1[++stackTop$1] = right.indexOf(left) > -1;
2895
+ }
2896
+ break;
2897
+ }
2898
+ case OP_NOT_IN:
2899
+ {
2900
+ const right = stack$1[stackTop$1--];
2901
+ const left = stack$1[stackTop$1--];
2902
+ if (left === null || left === undefined || right === null || right === undefined) {
2903
+ stack$1[++stackTop$1] = true;
2904
+ break;
2905
+ }
2906
+ if (Array.isArray(left) && Array.isArray(right)) {
2907
+ throw new Error('NOT IN: both operands are arrays');
2908
+ }
2909
+ if (!Array.isArray(left) && !Array.isArray(right)) {
2910
+ throw new Error('NOT IN: neither operand is an array');
2911
+ }
2912
+ if (Array.isArray(left)) {
2913
+ stack$1[++stackTop$1] = left.indexOf(right) === -1;
2914
+ } else if (Array.isArray(right)) {
2915
+ stack$1[++stackTop$1] = right.indexOf(left) === -1;
2916
+ }
2917
+ break;
2918
+ }
2919
+
2920
+ // Inline collection scan — no array allocation.
2921
+ // Stack layout: [item0, item1, ..., itemN-1, scalar]
2922
+ // The compiler always emits collection items first, scalar last.
2923
+ case OP_IN_COLLECTION:
2924
+ {
2925
+ const n = numAt$1(bytecode[++i]);
2926
+ const scalar = stack$1[stackTop$1--];
2927
+ let found = false;
2928
+ if (scalar !== null && scalar !== undefined) {
2929
+ for (let j = 0; j < n; j++) {
2930
+ if (stack$1[stackTop$1 - j] === scalar) {
2931
+ found = true;
2932
+ break;
2933
+ }
2934
+ }
2935
+ }
2936
+ stackTop$1 -= n;
2937
+ stack$1[++stackTop$1] = found;
2938
+ break;
2939
+ }
2940
+ case OP_NOT_IN_COLLECTION:
2941
+ {
2942
+ const n = numAt$1(bytecode[++i]);
2943
+ const scalar = stack$1[stackTop$1--];
2944
+ let found = false;
2945
+ if (scalar !== null && scalar !== undefined) {
2946
+ for (let j = 0; j < n; j++) {
2947
+ if (stack$1[stackTop$1 - j] === scalar) {
2948
+ found = true;
2949
+ break;
2950
+ }
2951
+ }
2952
+ }
2953
+ stackTop$1 -= n;
2954
+ stack$1[++stackTop$1] = !found;
2955
+ break;
2956
+ }
2957
+ case OP_IN_CONST:
2958
+ {
2959
+ const constIdx = numAt$1(bytecode[++i]);
2960
+ const scalar = stack$1[stackTop$1--];
2961
+ if (scalar === null || scalar === undefined) {
2962
+ stack$1[++stackTop$1] = false;
2963
+ break;
2964
+ }
2965
+ stack$1[++stackTop$1] = constSets[constIdx].has(scalar);
2966
+ break;
2967
+ }
2968
+ case OP_NOT_IN_CONST:
2969
+ {
2970
+ const constIdx = numAt$1(bytecode[++i]);
2971
+ const scalar = stack$1[stackTop$1--];
2972
+ if (scalar === null || scalar === undefined) {
2973
+ stack$1[++stackTop$1] = true;
2974
+ break;
2975
+ }
2976
+ stack$1[++stackTop$1] = !constSets[constIdx].has(scalar);
2977
+ break;
2978
+ }
2979
+ case OP_OVERLAP_SCAN_REFS_CONST:
2980
+ {
2981
+ // bytecode layout: n, ref0, ref1, ..., refN-1, constIdx
2982
+ const n = numAt$1(bytecode[++i]);
2983
+ const refStart = i + 1;
2984
+ i += n;
2985
+ const constIdx = numAt$1(bytecode[++i]);
2986
+ const constArr = consts[constIdx];
2987
+ const cLen = constArr.length;
2988
+ let found = false;
2989
+ if (cLen === 0) {
2990
+ // n > 0 here, so cannot be two empty arrays
2991
+ found = false;
2992
+ } else if (cLen === 1) {
2993
+ const target = constArr[0];
2994
+ for (let j = 0; j < n; j++) {
2995
+ const v = resolveCompactRef(refs[numAt$1(bytecode[refStart + j])], ctx);
2996
+ if (v === target) {
2997
+ found = true;
2998
+ break;
2999
+ }
3000
+ }
3001
+ } else {
3002
+ const s = constSets[constIdx];
3003
+ const hasUndefined = s.has(undefined);
3004
+ const hasNull = s.has(null);
3005
+ for (let j = 0; j < n; j++) {
3006
+ const v = resolveCompactRef(refs[numAt$1(bytecode[refStart + j])], ctx);
3007
+ if (v === undefined) {
3008
+ if (hasUndefined) {
3009
+ found = true;
3010
+ break;
3011
+ }
3012
+ continue;
3013
+ }
3014
+ if (v === null) {
3015
+ if (hasNull) {
3016
+ found = true;
3017
+ break;
3018
+ }
3019
+ continue;
3020
+ }
3021
+ if (s.has(v)) {
3022
+ found = true;
3023
+ break;
3024
+ }
3025
+ }
3026
+ }
3027
+ stack$1[++stackTop$1] = found;
3028
+ break;
3029
+ }
3030
+ case OP_IN_SCAN_REFS_CONST:
3031
+ case OP_NOT_IN_SCAN_REFS_CONST:
3032
+ {
3033
+ // bytecode layout: n, ref0, ref1, ..., refN-1, constIdx (always 1-element const)
3034
+ const n = numAt$1(bytecode[++i]);
3035
+ const refStart = i + 1;
3036
+ i += n;
3037
+ const constIdx = numAt$1(bytecode[++i]);
3038
+ const target = consts[constIdx][0]; // always a 1-element set: the scalar operand
3039
+ let found = false;
3040
+ if (target !== null && target !== undefined) {
3041
+ for (let j = 0; j < n; j++) {
3042
+ const v = resolveCompactRef(refs[numAt$1(bytecode[refStart + j])], ctx);
3043
+ if (v === target) {
3044
+ found = true;
3045
+ break;
3046
+ }
3047
+ }
3048
+ }
3049
+ stack$1[++stackTop$1] = op === OP_IN_SCAN_REFS_CONST ? found : !found;
3050
+ break;
3051
+ }
3052
+ case OP_OR_AND_IN_CONST_2:
3053
+ {
3054
+ // bytecode layout: ref1Idx, ref2Idx, M, v0, setBIdx0, v1, setBIdx1, ..., vM-1, setBIdxM-1
3055
+ // constSets[setBIdx] is pre-built at first interpret() call — plain Set.has lookup.
3056
+ const ref1Idx = numAt$1(bytecode[++i]);
3057
+ const ref2Idx = numAt$1(bytecode[++i]);
3058
+ const m = numAt$1(bytecode[++i]);
3059
+ const entriesStart = i + 1;
3060
+ i += m * 2;
3061
+ const v1 = resolveCompactRef(refs[ref1Idx], ctx);
3062
+ const v2 = resolveCompactRef(refs[ref2Idx], ctx);
3063
+ let found = false;
3064
+ if (v1 !== undefined && v1 !== null && v2 !== undefined && v2 !== null) {
3065
+ for (let j = 0; j < m; j++) {
3066
+ if (bytecode[entriesStart + j * 2] === v1) {
3067
+ found = constSets[numAt$1(bytecode[entriesStart + j * 2 + 1])].has(v2);
3068
+ break;
3069
+ }
3070
+ }
3071
+ }
3072
+ stack$1[++stackTop$1] = found;
3073
+ break;
3074
+ }
3075
+
3076
+ // -----------------------------------------------------------------------
3077
+ // String
3078
+ // -----------------------------------------------------------------------
3079
+ case OP_PREFIX:
3080
+ {
3081
+ const right = stack$1[stackTop$1--];
3082
+ const left = stack$1[stackTop$1--];
3083
+ stack$1[++stackTop$1] = isString(left) && isString(right) ? right.startsWith(left) : false;
3084
+ break;
3085
+ }
3086
+ case OP_SUFFIX:
3087
+ {
3088
+ const right = stack$1[stackTop$1--];
3089
+ const left = stack$1[stackTop$1--];
3090
+ stack$1[++stackTop$1] = isString(left) && isString(right) ? left.endsWith(right) : false;
3091
+ break;
3092
+ }
3093
+
3094
+ // -----------------------------------------------------------------------
3095
+ // Array
3096
+ // -----------------------------------------------------------------------
3097
+ case OP_OVERLAP:
3098
+ {
3099
+ const right = stack$1[stackTop$1--];
3100
+ const left = stack$1[stackTop$1--];
3101
+ if (left === null || left === undefined || right === null || right === undefined) {
3102
+ stack$1[++stackTop$1] = false;
3103
+ break;
3104
+ }
3105
+ if (!Array.isArray(left) || !Array.isArray(right)) {
3106
+ throw new Error('OVERLAP: both operands must be arrays');
3107
+ }
3108
+ if (left.length === 0 && right.length === 0) {
3109
+ stack$1[++stackTop$1] = true;
3110
+ break;
3111
+ }
3112
+ stack$1[++stackTop$1] = left.some(el => right.includes(el));
3113
+ break;
3114
+ }
3115
+
3116
+ // -----------------------------------------------------------------------
3117
+ // Presence
3118
+ // -----------------------------------------------------------------------
3119
+ case OP_PRESENT:
3120
+ stack$1[stackTop$1] = stack$1[stackTop$1] !== undefined && stack$1[stackTop$1] !== null;
3121
+ break;
3122
+ case OP_UNDEFINED:
3123
+ stack$1[stackTop$1] = stack$1[stackTop$1] === undefined;
3124
+ break;
3125
+
3126
+ // -----------------------------------------------------------------------
3127
+ // Arithmetic
3128
+ // -----------------------------------------------------------------------
3129
+ case OP_SUM:
3130
+ case OP_SUBTRACT:
3131
+ case OP_MULTIPLY:
3132
+ case OP_DIVIDE:
3133
+ {
3134
+ const n = numAt$1(bytecode[++i]);
3135
+ // Fast path for the common 2-operand case — no array allocation
3136
+ if (n === 2) {
3137
+ const b = stack$1[stackTop$1--];
3138
+ const a = stack$1[stackTop$1--];
3139
+ if (a === null || a === undefined || b === null || b === undefined) {
3140
+ stack$1[++stackTop$1] = false;
3141
+ break;
3142
+ }
3143
+ if (!isNumber(a) || !isNumber(b)) {
3144
+ throw new Error(`arithmetic operand is not a number: ${!isNumber(a) ? a : b}`);
3145
+ }
3146
+ if (op === OP_SUM) {
3147
+ stack$1[++stackTop$1] = addDecimals$1(a, b);
3148
+ } else if (op === OP_SUBTRACT) {
3149
+ stack$1[++stackTop$1] = subtractDecimals$1(a, b);
3150
+ } else if (op === OP_MULTIPLY) {
3151
+ stack$1[++stackTop$1] = multiplyDecimals$1(a, b);
3152
+ } else {
3153
+ stack$1[++stackTop$1] = divideDecimals$1(a, b);
3154
+ }
3155
+ break;
3156
+ }
3157
+ const values = new Array(n);
3158
+ let hasNull = false;
3159
+ for (let j = n - 1; j >= 0; j--) {
3160
+ const v = stack$1[stackTop$1--];
3161
+ if (v === null || v === undefined) {
3162
+ hasNull = true;
3163
+ break;
3164
+ }
3165
+ if (!isNumber(v)) {
3166
+ throw new Error(`arithmetic operand is not a number: ${v}`);
3167
+ }
3168
+ values[j] = v;
3169
+ }
3170
+ stack$1[++stackTop$1] = hasNull ? false : arithmeticReduce$1(values, op);
3171
+ break;
3172
+ }
3173
+
3174
+ // -----------------------------------------------------------------------
3175
+ // Logical
3176
+ // -----------------------------------------------------------------------
3177
+ case OP_NOT:
3178
+ {
3179
+ const val = stack$1[stackTop$1];
3180
+ if (typeof val !== 'boolean') {
3181
+ throw new Error('NOT: operand must be boolean');
3182
+ }
3183
+ stack$1[stackTop$1] = !val;
3184
+ break;
3185
+ }
3186
+ case OP_XOR:
3187
+ {
3188
+ const b = stack$1[stackTop$1--];
3189
+ const a = stack$1[stackTop$1--];
3190
+ if (typeof a !== 'boolean' || typeof b !== 'boolean') {
3191
+ throw new Error('XOR: operands must be boolean');
3192
+ }
3193
+ stack$1[++stackTop$1] = (a || b) && !(a && b);
3194
+ break;
3195
+ }
3196
+ case OP_JUMP_IF_FALSE:
3197
+ {
3198
+ const offset = numAt$1(bytecode[++i]);
3199
+ if (stack$1[stackTop$1] === false) {
3200
+ i += offset;
3201
+ }
3202
+ break;
3203
+ }
3204
+ case OP_JUMP_IF_TRUE:
3205
+ {
3206
+ const offset = numAt$1(bytecode[++i]);
3207
+ if (stack$1[stackTop$1] === true) {
3208
+ i += offset;
3209
+ }
3210
+ break;
3211
+ }
3212
+ case OP_POP:
3213
+ stackTop$1--;
3214
+ break;
3215
+ case OP_AND:
3216
+ case OP_OR:
3217
+ case OP_NOR:
3218
+ i++; // skip operand count
3219
+ break;
3220
+ }
3221
+ i++;
3222
+ }
3223
+ return stack$1[stackTop$1];
3224
+ }
3225
+
3226
+ /**
3227
+ * Bytecode simplify interpreter.
3228
+ *
3229
+ * Runs the same bytecode as the evaluate interpreter but supports partial
3230
+ * evaluation. Stack slots hold either a Result (fully resolved) or an Input
3231
+ * fragment (residual — a ref string or a sub-expression array). When an
3232
+ * operator receives any residual operand it reconstructs the sub-expression
3233
+ * as an Input array instead of computing a value.
3234
+ *
3235
+ * Short-circuit logic still applies: AND with a false short-circuits even if
3236
+ * other operands are unknown; OR with a true short-circuits likewise.
3237
+ */
3238
+
3239
+
3240
+ // Detect Infinity and NaN — these should not be used as concrete values in
3241
+ // comparisons when the other operand is residual, matching the OOP simplifier's
3242
+ // isInfinite guard in isSimplifiedArithmeticExpression.
3243
+ function isUnusableResult(v) {
3244
+ return typeof v === 'number' && !isFinite(v);
3245
+ }
3246
+ const addDecimals = operateWithExpectedDecimals('sum');
3247
+ const subtractDecimals = operateWithExpectedDecimals('subtract');
3248
+ const multiplyDecimals = operateWithExpectedDecimals('multiply');
3249
+ const divideDecimals = (a, b) => a / b;
3250
+
3251
+ // WeakMap Set cache for OP_OVERLAP_CONST, OP_OVERLAP_SCAN_REFS_CONST, and OP_IN_CONST —
3252
+ // same pattern as the evaluate interpreter.
3253
+ // Keyed on the const array identity so Sets are released when the CompiledExpression is GC'd.
3254
+ const overlapSetCache = new WeakMap();
3255
+
3256
+ // Per-compiled-expression Map caches — built lazily from the serializable tuple arrays on the
3257
+ // CompiledExpression. Same WeakMap pattern as constSetsCache in the evaluate interpreter so
3258
+ // the Maps are released when the CompiledExpression is GC'd.
3259
+ const overlapRefsResidualsCache = new WeakMap();
3260
+ const directionMapCache = new WeakMap();
3261
+
3262
+ // Read a numeric operand from a bytecode slot — opcodes and index operands are always numbers.
3263
+ // Throws if the slot contains a non-number (guards against compiler bugs).
3264
+ function numAt(v) {
3265
+ if (typeof v !== 'number') {
3266
+ throw new Error(`bytecode integrity error: expected number, got ${typeof v}`);
3267
+ }
3268
+ return v;
3269
+ }
3270
+
3271
+ // Read a literal value from a bytecode slot — stored literals are string|number|boolean|null.
3272
+ // Throws if the slot contains undefined, an array, or an object (guards against compiler bugs).
3273
+ // Returns string|number|boolean|null, which is a subtype of Input.
3274
+ function literalAt(v) {
3275
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) {
3276
+ return v;
3277
+ }
3278
+ throw new Error(`bytecode integrity error: expected literal, got ${typeof v}`);
3279
+ }
3280
+
3281
+ // Retrieve a required entry from a map — throws if the key is missing.
3282
+ // Eliminates the Map.get() undefined return in contexts where the entry is compiler-guaranteed.
3283
+ function requireMapEntry(map, key) {
3284
+ const v = map.get(key);
3285
+ if (v === undefined) {
3286
+ throw new Error(`bytecode integrity error: missing required map entry for key ${String(key)}`);
3287
+ }
3288
+ return v;
3289
+ }
3290
+
3291
+ // A resolved ref carries its computed value and original serialized form.
3292
+ // Used so that when a comparison partially resolves, we reconstruct using
3293
+ // the original ref key (e.g. '$a') rather than the resolved value (e.g. 10).
3294
+ // Numeric tag _r used for all three wrapper types so V8 can use hidden-class
3295
+ // fixed-offset reads instead of the slower `'key' in obj` property-existence check.
3296
+
3297
+ // A residual sub-expression — a reconstructed Input fragment.
3298
+ // Wrapped in an object so we can distinguish it from concrete Result[] arrays.
3299
+
3300
+ // Accumulated XOR state during chained binary XOR evaluation.
3301
+ // Tracks residual operands and how many concrete-true values were seen.
3302
+
3303
+ // Union of all slot object wrapper types (distinguishable via _r discriminant).
3304
+
3305
+ // Arrays on the stack carry no _r property. Declaring _r?: undefined here exposes
3306
+ // the discriminant on the full "non-null object Slot" union so that needsReconstruct
3307
+ // and slotVal can read ._r directly — without Array.isArray — in their hot paths.
3308
+ // For arrays, ._r resolves to undefined, which naturally fails the === 2/3/1 checks.
3309
+
3310
+ // A stack slot is a concrete value (primitives, arrays, SlotObject wrappers).
3311
+ // Record<string,unknown> values can be pushed directly from OP_PUSH_VALUE
3312
+ // (object literals in expressions), and are returned as-is by slotVal.
3313
+
3314
+ // Type guard: checks if a slot is a SlotObject (has _r as an own property).
3315
+ // This distinguishes SlotObject types from plain Record<string,unknown> objects.
3316
+ function isSlotObject(v) {
3317
+ return typeof v === 'object' && v !== null && Object.prototype.hasOwnProperty.call(v, '_r');
3318
+ }
3319
+ function isXorState(v) {
3320
+ return isSlotObject(v) && v._r === 3;
3321
+ }
3322
+ function isResidual(v) {
3323
+ return isSlotObject(v) && v._r === 2;
3324
+ }
3325
+ function isDivByZeroMarker(v) {
3326
+ return isSlotObject(v) && v._r === 4;
3327
+ }
3328
+
3329
+ // True if the slot needs to be reconstructed rather than computed.
3330
+ // Hot path — booleans/numbers/strings short-circuit at the first typeof check.
3331
+ // Unknown refs are always wrapped in Residual (_r === 2), never pushed as raw strings,
3332
+ // so no reference-predicate check is needed here.
3333
+ // No Array.isArray needed: arrays have _r === undefined, failing the 2/3/4 check.
3334
+ function needsReconstruct(v) {
3335
+ if (typeof v !== 'object' || v === null) {
3336
+ return false;
3337
+ }
3338
+ // v is ArraySlot | SlotObject | Record<string, unknown>; _r is undefined|1|2|3|4
3339
+ return v._r === 2 || v._r === 3 || v._r === 4;
3340
+ }
3341
+
3342
+ // Extract the concrete Result from a slot (unwrap Resolved if needed).
3343
+ // Hot path — no Array.isArray needed: for non-Resolved objects (arrays, Residual,
3344
+ // XorState, DivByZeroMarker), the _r === 1 check is false and they
3345
+ // fall through to the primitive branch or return the value as appropriate.
3346
+ function slotVal(v) {
3347
+ if (typeof v !== 'object' || v === null) {
3348
+ return v; // primitives: boolean, number, string, null, undefined
3349
+ }
3350
+ // v is ArraySlot | SlotObject | Record<string,unknown>
3351
+ if (isSlotObject(v)) {
3352
+ // v is a SlotObject — discriminate via _r
3353
+ if (v._r === 1) {
3354
+ return v.val; // Resolved — unwrap the concrete value
3355
+ }
3356
+ if (v._r === 4) {
3357
+ // DivByZeroMarker — unwrap as Infinity
3358
+ return v._val;
3359
+ }
3360
+ // v._r is 2 or 3 (Residual/XorState) — no concrete value to extract
3361
+ return undefined;
3362
+ }
3363
+ // v is ArraySlot or Record<string,unknown> — both are valid Results
3364
+ if (Array.isArray(v)) {
3365
+ return v; // ArraySlot — the array is itself a Result
3366
+ }
3367
+ return v; // Plain object literal — Record<string,unknown> is a valid Result
3368
+ }
3369
+
3370
+ // Module-level op name references for XorState finalization.
3371
+ // Set at the start of each interpretSimplify call.
3372
+ let _xorOpName = 'XOR';
3373
+ let _notOpName = 'NOT';
3374
+ let _norOpName = 'NOR';
3375
+
3376
+ // Type guard: checks whether a Result value is also a valid Input.
3377
+ // Input = string | number | boolean | null | Input[] | Record<string, unknown>.
3378
+ function isInput(v) {
3379
+ if (v === undefined) {
3380
+ return false;
3381
+ }
3382
+ if (v === null) {
3383
+ return true;
3384
+ }
3385
+ if (Array.isArray(v)) {
3386
+ return v.every(isInput);
3387
+ }
3388
+ if (typeof v === 'object') {
3389
+ return Object.values(v).every(isInput);
3390
+ }
3391
+ return true;
3392
+ }
3393
+
3394
+ // Extract the serialized Input form of a slot for residual reconstruction.
3395
+ function slotSrc(v) {
3396
+ if (typeof v !== 'object' || v === null) {
3397
+ // v is a primitive: undefined | null | string | number | boolean
3398
+ // In residual paths this should always be a valid Input — guard against null/undefined.
3399
+ if (!isInput(v)) {
3400
+ throw new Error(`slotSrc: invariant violated — non-Input value in residual path: ${typeof v}`);
3401
+ }
3402
+ return v; // v narrowed to Input by the type guard above
3403
+ }
3404
+ // v is ArraySlot | SlotObject | Record<string,unknown>
3405
+ if (Array.isArray(v)) {
3406
+ // v is ArraySlot — a concrete collection used as an operand
3407
+ if (!isInput(v)) {
3408
+ throw new Error(`slotSrc: invariant violated — non-Input array in residual path`);
3409
+ }
3410
+ return v;
3411
+ }
3412
+ // v is a plain object — use isSlotObject to distinguish SlotObject types
3413
+ // (which have _r as an own property) from plain Record<string,unknown> objects.
3414
+ if (isSlotObject(v)) {
3415
+ // v is a SlotObject — discriminate via _r
3416
+ if (v._r === 3) {
3417
+ // XorState — finalize accumulated XOR state into an expression
3418
+ const {
3419
+ xorResiduals: residuals,
3420
+ xorTrueCount: trueCount
3421
+ } = v;
3422
+ // "One-hot" XOR: if more than one true was seen, result is false
3423
+ if (trueCount > 1) {
3424
+ return false;
3425
+ }
3426
+ const effectiveTrueCount = trueCount % 2;
3427
+ if (residuals.length === 1) {
3428
+ return effectiveTrueCount === 1 ? [_notOpName, residuals[0]] : residuals[0];
3429
+ }
3430
+ return effectiveTrueCount === 1 ? [_norOpName, ...residuals] : [_xorOpName, ...residuals];
3431
+ }
3432
+ if (v._r === 2) {
3433
+ // Residual — return the reconstructed expression
3434
+ return v.expr;
3435
+ }
3436
+ if (v._r === 4) {
3437
+ // DivByZeroMarker — reconstruct as a DIVIDE expression
3438
+ return ['/', v.left, v.right];
3439
+ }
3440
+ if (v._r === 1) {
3441
+ // Resolved — return original ref key
3442
+ return v.src;
3443
+ }
3444
+ }
3445
+ // Plain object literal — return as-is (valid Input)
3446
+ return v;
3447
+ }
3448
+
3449
+ // Wrap a reconstructed expression as a Residual slot.
3450
+ // expr should be an Input array (sub-expression) like ['EQ', '$ref', 5].
3451
+ function makeResidual(expr) {
3452
+ return {
3453
+ _r: 2,
3454
+ expr
3455
+ };
3456
+ }
3457
+
3458
+ // Create a Resolved slot wrapping a known ref value.
3459
+ function makeResolved(val, src) {
3460
+ return {
3461
+ _r: 1,
3462
+ val,
3463
+ src
3464
+ };
3465
+ }
3466
+
3467
+ // Create a XorState slot accumulating XOR operands.
3468
+ function makeXorState(xorResiduals, xorTrueCount) {
3469
+ return {
3470
+ _r: 3,
3471
+ xorResiduals,
3472
+ xorTrueCount
3473
+ };
3474
+ }
3475
+
3476
+ // Pre-allocated stack — same as evaluate interpreter
3477
+ const MAX_STACK = 512;
3478
+ const stack = new Array(MAX_STACK);
3479
+ let stackTop = -1;
3480
+
3481
+ // Pre-allocated locals for CSE collection caching
3482
+ const MAX_LOCALS = 64;
3483
+ const locals = new Array(MAX_LOCALS);
3484
+
3485
+ // Pre-resolved ref cache — populated lazily per interpretSimplify call.
3486
+ // Indexed by ref index; avoids repeated resolveCompactRef() calls when the same
3487
+ // ref appears in multiple opcodes (e.g. multiple OVERLAP_SCAN_REFS_CONST in one expression).
3488
+ // resolvedRefDirty[i] = true means resolvedRefCache[i] holds a valid (possibly undefined) result.
3489
+ const MAX_REFS = 512;
3490
+ const resolvedRefCache = new Array(MAX_REFS);
3491
+ const resolvedRefDirty = new Array(MAX_REFS).fill(false);
3492
+ // Tracks which indices were populated this call so we can reset only those.
3493
+ const resolvedRefUsed = new Array(MAX_REFS);
3494
+ let resolvedRefUsedCount = 0;
3495
+
3496
+ // Residual spill buffer: when OP_POP discards a residual/unknown-ref slot that
3497
+ // is part of a short-circuit AND/OR sequence, we save it here so OP_AND/OR/NOR
3498
+ // can include it in the reconstructed expression.
3499
+ const spillBuf = new Array(MAX_STACK);
3500
+ let spillTop = -1;
3501
+ // Track the last jump opcode type to detect transitions between short-circuit
3502
+ // sequences. Different jump opcodes (41=JUMP_IF_FALSE vs 42=JUMP_IF_TRUE) indicate
3503
+ // different short-circuit sequences (AND vs OR/NOR).
3504
+ let lastJumpOp = 0;
3505
+ function relationalCompare(left, right, op) {
3506
+ if (isNumber(left) && isNumber(right)) {
3507
+ if (op === OP_GT) {
3508
+ return left > right;
3509
+ }
3510
+ if (op === OP_GE) {
3511
+ return left >= right;
3512
+ }
3513
+ if (op === OP_LT) {
3514
+ return left < right;
3515
+ }
3516
+ return left <= right;
3517
+ }
3518
+ const ld = toDateNumber(left);
3519
+ const rd = toDateNumber(right);
3520
+ if (!isNaN(ld) && !isNaN(rd)) {
3521
+ if (op === OP_GT) {
3522
+ return ld > rd;
3523
+ }
3524
+ if (op === OP_GE) {
3525
+ return ld >= rd;
3526
+ }
3527
+ if (op === OP_LT) {
3528
+ return ld < rd;
3529
+ }
3530
+ return ld <= rd;
3531
+ }
3532
+ return false;
3533
+ }
3534
+ function arithmeticReduce(values, op) {
3535
+ if (op === OP_SUM) {
3536
+ return values.reduce(addDecimals);
3537
+ }
3538
+ if (op === OP_SUBTRACT) {
3539
+ return values.reduce(subtractDecimals);
3540
+ }
3541
+ if (op === OP_MULTIPLY) {
3542
+ return values.reduce(multiplyDecimals);
3543
+ }
3544
+ return values.reduce(divideDecimals);
3545
+ }
3546
+ function interpretSimplify(compiled, ctx, strictKeys, optionalKeys) {
3547
+ const {
3548
+ bytecode,
3549
+ refs,
3550
+ opNames,
3551
+ refKeys,
3552
+ refRawKeys,
3553
+ refFirstCtxKeys
3554
+ } = compiled;
3555
+ stackTop = -1;
3556
+ spillTop = -1;
3557
+ lastJumpOp = 0;
3558
+ let overlapRefsResiduals = overlapRefsResidualsCache.get(compiled);
3559
+ if (overlapRefsResiduals === undefined) {
3560
+ overlapRefsResiduals = new Map(compiled.overlapRefsResiduals);
3561
+ overlapRefsResidualsCache.set(compiled, overlapRefsResiduals);
3562
+ }
3563
+ let directionMap = directionMapCache.get(compiled);
3564
+ if (directionMap === undefined) {
3565
+ directionMap = new Map(compiled.directionMap);
3566
+ directionMapCache.set(compiled, directionMap);
3567
+ }
3568
+
3569
+ // Reset the ref cache (only clear slots used in the previous call)
3570
+ for (let r = 0; r < resolvedRefUsedCount; r++) {
3571
+ resolvedRefDirty[resolvedRefUsed[r]] = false;
3572
+ }
3573
+ resolvedRefUsedCount = 0;
3574
+
3575
+ // Set module-level op names for XorState finalization
3576
+ _xorOpName = opNames[OP_XOR] ?? 'XOR';
3577
+ _notOpName = opNames[OP_NOT] ?? 'NOT';
3578
+ _norOpName = opNames[OP_NOR] ?? 'NOR';
3579
+ let i = 0;
3580
+ const len = bytecode.length;
3581
+
3582
+ // Normalise key sets for O(1) lookup
3583
+ const strictSet = strictKeys instanceof Set ? strictKeys : strictKeys ? new Set(strictKeys) : undefined;
3584
+ const optionalSet = optionalKeys instanceof Set ? optionalKeys : optionalKeys ? new Set(optionalKeys) : undefined;
3585
+ while (i < len) {
3586
+ const op = numAt(bytecode[i++]);
3587
+ switch (op) {
3588
+ // ---------------------------------------------------------------------
3589
+ // Push
3590
+ // ---------------------------------------------------------------------
3591
+ case OP_PUSH_VALUE:
3592
+ {
3593
+ const lit = bytecode[i++];
3594
+ // OP_PUSH_VALUE stores parsed Input literals, including object literals.
3595
+ // No guard needed — the compiler guarantees valid Input values.
3596
+ stack[++stackTop] = lit;
3597
+ break;
3598
+ }
3599
+ case OP_PUSH_REF_KEY:
3600
+ case OP_PUSH_REF_KEYS:
3601
+ case OP_PUSH_REF_TOKENS:
3602
+ case OP_PUSH_REF_DYNAMIC:
3603
+ {
3604
+ const idx = numAt(bytecode[i++]);
3605
+ const rawKey = refRawKeys[idx];
3606
+ let val;
3607
+ if (resolvedRefDirty[idx]) {
3608
+ val = resolvedRefCache[idx];
3609
+ } else {
3610
+ val = resolveCompactRef(refs[idx], ctx);
3611
+ resolvedRefCache[idx] = val;
3612
+ resolvedRefDirty[idx] = true;
3613
+ resolvedRefUsed[resolvedRefUsedCount++] = idx;
3614
+ }
3615
+ if (val !== undefined) {
3616
+ // Ref is in context — always resolve (strictKeys/optionalKeys only affect absent keys)
3617
+ stack[++stackTop] = makeResolved(val, refKeys[idx]);
3618
+ break;
3619
+ }
3620
+
3621
+ // Ref is absent from context.
3622
+ // Check if it should be treated as a concrete undefined (evaluated as undefined)
3623
+ // or as a residual expression (preserved for later simplification).
3624
+ if (strictSet?.has(rawKey)) {
3625
+ // strictKeys: force-evaluate as undefined (not a residual)
3626
+ stack[++stackTop] = undefined;
3627
+ break;
3628
+ }
3629
+ if (optionalSet && !optionalSet.has(rawKey)) {
3630
+ // Key not in optionalKeys: treat as definitely-present but absent → undefined
3631
+ stack[++stackTop] = undefined;
3632
+ break;
3633
+ }
3634
+
3635
+ // First-key heuristic: match OOP Reference.simplify() behavior.
3636
+ // If the top-level context key exists, the ref's parent object is known — treat the
3637
+ // (absent) sub-field as concrete undefined rather than preserving it as an unknown.
3638
+ // This only applies to multi-key refs (refFirstCtxKeys[idx] is undefined for single-key).
3639
+ const firstCtxKey = refFirstCtxKeys[idx];
3640
+ if (firstCtxKey !== undefined && ctx[firstCtxKey] !== undefined) {
3641
+ stack[++stackTop] = undefined;
3642
+ break;
3643
+ }
3644
+
3645
+ // Key is genuinely unknown — wrap as Residual so detection does not depend
3646
+ // on the reference character (respects custom referencePredicate/referenceSerialization).
3647
+ stack[++stackTop] = makeResidual(refKeys[idx]);
3648
+ break;
3649
+ }
3650
+ case OP_MAKE_COLLECTION:
3651
+ {
3652
+ const n = numAt(bytecode[i++]);
3653
+ // Check for unknown items first
3654
+ let hasUnknown = false;
3655
+ for (let j = 0; j < n; j++) {
3656
+ if (needsReconstruct(stack[stackTop - j])) {
3657
+ hasUnknown = true;
3658
+ break;
3659
+ }
3660
+ }
3661
+ if (hasUnknown) {
3662
+ // Keep serialized form (ref keys or sub-expressions) for residual reconstruction
3663
+ const items = new Array(n);
3664
+ for (let j = n - 1; j >= 0; j--) {
3665
+ items[j] = slotSrc(stack[stackTop--]);
3666
+ }
3667
+ stack[++stackTop] = makeResidual(items);
3668
+ } else {
3669
+ // All concrete — use actual values
3670
+ const items = new Array(n);
3671
+ for (let j = n - 1; j >= 0; j--) {
3672
+ items[j] = slotVal(stack[stackTop--]);
3673
+ }
3674
+ stack[++stackTop] = items;
3675
+ }
3676
+ break;
3677
+ }
3678
+ case OP_PUSH_CONST:
3679
+ stack[++stackTop] = compiled.consts[numAt(bytecode[i++])];
3680
+ break;
3681
+ case OP_OVERLAP_CONST:
3682
+ {
3683
+ const opcodePos = i - 1; // position of OP_OVERLAP_CONST in bytecode
3684
+ const constArr = compiled.consts[numAt(bytecode[i++])];
3685
+ const constOnLeft = directionMap.get(opcodePos) === 0;
3686
+ const dynamic = stack[stackTop--];
3687
+ if (needsReconstruct(dynamic)) {
3688
+ // Dynamic side is unknown — reconstruct as OVERLAP expression preserving original order
3689
+ const constInput = constArr;
3690
+ const dynamicInput = slotSrc(dynamic);
3691
+ stack[++stackTop] = makeResidual([opNames[OP_OVERLAP], constOnLeft ? constInput : dynamicInput, constOnLeft ? dynamicInput : constInput]);
3692
+ break;
3693
+ }
3694
+ const dynamicVal = slotVal(dynamic);
3695
+ if (dynamicVal === null || dynamicVal === undefined || !Array.isArray(dynamicVal)) {
3696
+ stack[++stackTop] = false;
3697
+ break;
3698
+ }
3699
+ if (constArr.length === 0 && dynamicVal.length === 0) {
3700
+ stack[++stackTop] = true;
3701
+ break;
3702
+ }
3703
+ let found = false;
3704
+ if (constArr.length === 1) {
3705
+ const constVal = constArr[0];
3706
+ for (let j = 0; j < dynamicVal.length; j++) {
3707
+ if (dynamicVal[j] === constVal) {
3708
+ found = true;
3709
+ break;
3710
+ }
3711
+ }
3712
+ } else {
3713
+ let s = overlapSetCache.get(constArr);
3714
+ if (s === undefined) {
3715
+ s = new Set(constArr);
3716
+ overlapSetCache.set(constArr, s);
3717
+ }
3718
+ for (let j = 0; j < dynamicVal.length; j++) {
3719
+ if (s.has(dynamicVal[j])) {
3720
+ found = true;
3721
+ break;
3722
+ }
3723
+ }
3724
+ }
3725
+ stack[++stackTop] = found;
3726
+ break;
3727
+ }
3728
+ case OP_OVERLAP_SCAN_REFS_CONST:
3729
+ {
3730
+ // bytecode layout: N, ref0..refN-1, constIdx
3731
+ const opcodePos = i - 1; // position of OP_OVERLAP_SCAN_REFS_CONST in bytecode
3732
+ const n = numAt(bytecode[i++]);
3733
+ const refStart = i;
3734
+ i += n; // advance past all ref indices
3735
+ const constIdx = numAt(bytecode[i++]);
3736
+ const constArr = compiled.consts[constIdx];
3737
+ const constOnLeft = directionMap.get(opcodePos) === 0;
3738
+
3739
+ // First pass: check whether any ref is genuinely unknown.
3740
+ // Uses the per-call ref cache to avoid redundant resolveCompactRef calls.
3741
+ let hasUnknown = false;
3742
+ for (let j = 0; j < n; j++) {
3743
+ const refIdx = numAt(bytecode[refStart + j]);
3744
+ const rawKey = refRawKeys[refIdx];
3745
+ let val;
3746
+ if (resolvedRefDirty[refIdx]) {
3747
+ val = resolvedRefCache[refIdx];
3748
+ } else {
3749
+ val = resolveCompactRef(refs[refIdx], ctx);
3750
+ resolvedRefCache[refIdx] = val;
3751
+ resolvedRefDirty[refIdx] = true;
3752
+ resolvedRefUsed[resolvedRefUsedCount++] = refIdx;
3753
+ }
3754
+ if (val === undefined) {
3755
+ if (strictSet?.has(rawKey)) {
3756
+ continue;
3757
+ }
3758
+ if (optionalSet && !optionalSet.has(rawKey)) {
3759
+ continue;
3760
+ }
3761
+ // First-key heuristic: if parent object is in context, treat undefined sub-field as concrete
3762
+ const firstCtxKey = refFirstCtxKeys[refIdx];
3763
+ if (firstCtxKey !== undefined && ctx[firstCtxKey] !== undefined) {
3764
+ continue;
3765
+ }
3766
+ hasUnknown = true;
3767
+ break;
3768
+ }
3769
+ }
3770
+ if (hasUnknown) {
3771
+ // Use pre-built residual array from compile time — no allocation here
3772
+ const refInputs = requireMapEntry(overlapRefsResiduals, opcodePos);
3773
+ const constInput = constArr;
3774
+ const dynamicInput = refInputs;
3775
+ stack[++stackTop] = makeResidual([opNames[OP_OVERLAP], constOnLeft ? constInput : dynamicInput, constOnLeft ? dynamicInput : constInput]);
3776
+ break;
3777
+ }
3778
+ let found = false;
3779
+ if (constArr.length === 1) {
3780
+ // Fast path: single-element const — direct equality, no Set needed
3781
+ const constVal = constArr[0];
3782
+ for (let j = 0; j < n; j++) {
3783
+ const val = resolvedRefCache[numAt(bytecode[refStart + j])];
3784
+ if (val !== undefined && val === constVal) {
3785
+ found = true;
3786
+ break;
3787
+ }
3788
+ }
3789
+ } else {
3790
+ let s = overlapSetCache.get(constArr);
3791
+ if (s === undefined) {
3792
+ s = new Set(constArr);
3793
+ overlapSetCache.set(constArr, s);
3794
+ }
3795
+ for (let j = 0; j < n; j++) {
3796
+ const val = resolvedRefCache[numAt(bytecode[refStart + j])];
3797
+ if (val !== undefined && s.has(val)) {
3798
+ found = true;
3799
+ break;
3800
+ }
3801
+ }
3802
+ }
3803
+ stack[++stackTop] = found;
3804
+ break;
3805
+ }
3806
+ case OP_IN_SCAN_REFS_CONST:
3807
+ case OP_NOT_IN_SCAN_REFS_CONST:
3808
+ {
3809
+ // bytecode layout: N, ref0..refN-1, constIdx
3810
+ // const at constIdx is a 1-element array [scalar]
3811
+ const opcodePos = i - 1;
3812
+ const n = numAt(bytecode[i++]);
3813
+ const refStart = i;
3814
+ i += n;
3815
+ const constIdx = numAt(bytecode[i++]);
3816
+ const constArr = compiled.consts[constIdx];
3817
+ // dir=0: refs on left, scalar on right → scalar (constInput) is on right
3818
+ // dir=1: scalar on left, refs on right → scalar (constInput) is on left
3819
+ const constOnLeft = directionMap.get(opcodePos) === 1;
3820
+ let hasUnknown = false;
3821
+ for (let j = 0; j < n; j++) {
3822
+ const refIdx = numAt(bytecode[refStart + j]);
3823
+ const rawKey = refRawKeys[refIdx];
3824
+ let val;
3825
+ if (resolvedRefDirty[refIdx]) {
3826
+ val = resolvedRefCache[refIdx];
3827
+ } else {
3828
+ val = resolveCompactRef(refs[refIdx], ctx);
3829
+ resolvedRefCache[refIdx] = val;
3830
+ resolvedRefDirty[refIdx] = true;
3831
+ resolvedRefUsed[resolvedRefUsedCount++] = refIdx;
3832
+ }
3833
+ if (val === undefined) {
3834
+ if (strictSet?.has(rawKey)) {
3835
+ continue;
3836
+ }
3837
+ if (optionalSet && !optionalSet.has(rawKey)) {
3838
+ continue;
3839
+ }
3840
+ // First-key heuristic: if parent object is in context, treat undefined sub-field as concrete
3841
+ const firstCtxKey = refFirstCtxKeys[refIdx];
3842
+ if (firstCtxKey !== undefined && ctx[firstCtxKey] !== undefined) {
3843
+ continue;
3844
+ }
3845
+ hasUnknown = true;
3846
+ break;
3847
+ }
3848
+ }
3849
+ if (hasUnknown) {
3850
+ const refInputs = requireMapEntry(overlapRefsResiduals, opcodePos);
3851
+ // constArr is a 1-element array [scalar]; use the scalar as the const operand
3852
+ const constInput = constArr[0];
3853
+ const dynamicInput = refInputs;
3854
+ stack[++stackTop] = makeResidual([opNames[op], constOnLeft ? constInput : dynamicInput, constOnLeft ? dynamicInput : constInput]);
3855
+ break;
3856
+ }
3857
+ const target = constArr[0];
3858
+ let found = false;
3859
+ if (target !== null && target !== undefined) {
3860
+ for (let j = 0; j < n; j++) {
3861
+ const val = resolvedRefCache[numAt(bytecode[refStart + j])];
3862
+ if (val === target) {
3863
+ found = true;
3864
+ break;
3865
+ }
3866
+ }
3867
+ }
3868
+ stack[++stackTop] = op === OP_IN_SCAN_REFS_CONST ? found : !found;
3869
+ break;
3870
+ }
3871
+ case OP_STORE_LOCAL:
3872
+ // Peek top (don't pop) and store into locals slot
3873
+ locals[numAt(bytecode[i++])] = stack[stackTop];
3874
+ break;
3875
+ case OP_LOAD_LOCAL:
3876
+ stack[++stackTop] = locals[numAt(bytecode[i++])];
3877
+ break;
3878
+
3879
+ // ---------------------------------------------------------------------
3880
+ // Equality
3881
+ // ---------------------------------------------------------------------
3882
+ case OP_EQ:
3883
+ case OP_NE:
3884
+ {
3885
+ const right = stack[stackTop--];
3886
+ const left = stack[stackTop--];
3887
+ if (needsReconstruct(left) || needsReconstruct(right)) {
3888
+ stack[++stackTop] = makeResidual([opNames[op], slotSrc(left), slotSrc(right)]);
3889
+ } else {
3890
+ const lv = slotVal(left);
3891
+ const rv = slotVal(right);
3892
+ stack[++stackTop] = op === OP_EQ ? lv === rv : lv !== rv;
3893
+ }
3894
+ break;
3895
+ }
3896
+
3897
+ // ---------------------------------------------------------------------
3898
+ // Relational
3899
+ // ---------------------------------------------------------------------
3900
+ case OP_GT:
3901
+ case OP_GE:
3902
+ case OP_LT:
3903
+ case OP_LE:
3904
+ {
3905
+ const right = stack[stackTop--];
3906
+ const left = stack[stackTop--];
3907
+ // Check for DivByZeroMarker on either side
3908
+ const leftIsDivZero = isDivByZeroMarker(left);
3909
+ const rightIsDivZero = isDivByZeroMarker(right);
3910
+ if (leftIsDivZero) {
3911
+ // Left is a division-by-zero result.
3912
+ // Match OOP isInfinite guard: preserve expression only if right
3913
+ // is a residual. If right is concrete, evaluate directly.
3914
+ if (needsReconstruct(right) && !rightIsDivZero) {
3915
+ stack[++stackTop] = makeResidual([opNames[op], ['/', left.left, left.right], slotSrc(right)]);
3916
+ } else {
3917
+ // Both concrete — evaluate directly (OOP: 10000 > Infinity = false)
3918
+ stack[++stackTop] = relationalCompare(left._val, slotVal(right), op);
3919
+ }
3920
+ } else if (rightIsDivZero) {
3921
+ // Right is a division-by-zero result.
3922
+ // If left is a residual, preserve expression. Otherwise evaluate directly.
3923
+ if (needsReconstruct(left)) {
3924
+ stack[++stackTop] = makeResidual([opNames[op], slotSrc(left), ['/', right.left, right.right]]);
3925
+ } else {
3926
+ // Both concrete — evaluate directly (OOP: 10000 > Infinity = false)
3927
+ stack[++stackTop] = relationalCompare(slotVal(left), right._val, op);
3928
+ }
3929
+ } else if (needsReconstruct(left) || needsReconstruct(right)) {
3930
+ stack[++stackTop] = makeResidual([opNames[op], slotSrc(left), slotSrc(right)]);
3931
+ } else {
3932
+ stack[++stackTop] = relationalCompare(slotVal(left), slotVal(right), op);
3933
+ }
3934
+ break;
3935
+ }
3936
+
3937
+ // ---------------------------------------------------------------------
3938
+ // Containment — dynamic fallback (both sides are refs)
3939
+ // ---------------------------------------------------------------------
3940
+ case OP_IN:
3941
+ case OP_NOT_IN:
3942
+ {
3943
+ const right = stack[stackTop--];
3944
+ const left = stack[stackTop--];
3945
+ if (needsReconstruct(left) || needsReconstruct(right)) {
3946
+ stack[++stackTop] = makeResidual([opNames[op], slotSrc(left), slotSrc(right)]);
3947
+ } else {
3948
+ const l = slotVal(left);
3949
+ const r = slotVal(right);
3950
+ if (l === null || l === undefined || r === null || r === undefined) {
3951
+ stack[++stackTop] = op === OP_IN ? false : true;
3952
+ } else if (Array.isArray(l)) {
3953
+ if (Array.isArray(r)) {
3954
+ throw new Error(op === OP_IN ? 'IN: both operands are arrays' : 'NOT IN: both operands are arrays');
3955
+ }
3956
+ const found = l.indexOf(r) > -1;
3957
+ stack[++stackTop] = op === OP_IN ? found : !found;
3958
+ } else if (Array.isArray(r)) {
3959
+ const found = r.indexOf(l) > -1;
3960
+ stack[++stackTop] = op === OP_IN ? found : !found;
3961
+ } else {
3962
+ throw new Error(op === OP_IN ? 'IN: neither operand is an array' : 'NOT IN: neither operand is an array');
3963
+ }
3964
+ }
3965
+ break;
3966
+ }
3967
+
3968
+ // ---------------------------------------------------------------------
3969
+ // Inline collection scan
3970
+ // ---------------------------------------------------------------------
3971
+ case OP_IN_COLLECTION:
3972
+ case OP_NOT_IN_COLLECTION:
3973
+ {
3974
+ const opcodePos = i - 1; // position of the opcode in bytecode
3975
+ const n = numAt(bytecode[i++]);
3976
+ const collectionOnLeft = directionMap.get(opcodePos) === 0;
3977
+ const scalarSlot = stack[stackTop--];
3978
+ const scalarIsUnknown = needsReconstruct(scalarSlot);
3979
+ // Check if any collection item needs reconstruction
3980
+ let hasUnknownItem = false;
3981
+ for (let j = 0; j < n; j++) {
3982
+ if (needsReconstruct(stack[stackTop - j])) {
3983
+ hasUnknownItem = true;
3984
+ break;
3985
+ }
3986
+ }
3987
+ if (scalarIsUnknown || hasUnknownItem) {
3988
+ const items = new Array(n);
3989
+ for (let j = 0; j < n; j++) {
3990
+ items[j] = slotSrc(stack[stackTop - (n - 1 - j)]);
3991
+ }
3992
+ stackTop -= n;
3993
+ // Reconstruct preserving original operand order
3994
+ const itemsInput = items;
3995
+ const reconstructed = collectionOnLeft ? [opNames[op], itemsInput, slotSrc(scalarSlot)] : [opNames[op], slotSrc(scalarSlot), itemsInput];
3996
+ stack[++stackTop] = makeResidual(reconstructed);
3997
+ break;
3998
+ }
3999
+ // All concrete — inline scan using slotVal to unwrap Resolved
4000
+ const scalar = slotVal(scalarSlot);
4001
+ let found = false;
4002
+ if (scalar !== null && scalar !== undefined) {
4003
+ for (let j = 0; j < n; j++) {
4004
+ if (slotVal(stack[stackTop - j]) === scalar) {
4005
+ found = true;
4006
+ break;
4007
+ }
4008
+ }
4009
+ }
4010
+ stackTop -= n;
4011
+ stack[++stackTop] = op === OP_IN_COLLECTION ? found : !found;
4012
+ break;
4013
+ }
4014
+ case OP_IN_CONST:
4015
+ case OP_NOT_IN_CONST:
4016
+ {
4017
+ const opcodePos = i - 1; // position of the opcode in bytecode
4018
+ const constArr = compiled.consts[numAt(bytecode[i++])];
4019
+ const collectionOnLeft = directionMap.get(opcodePos) === 0;
4020
+ const scalarSlot = stack[stackTop--];
4021
+ if (needsReconstruct(scalarSlot)) {
4022
+ const scalarInput = slotSrc(scalarSlot);
4023
+ const constInput = constArr;
4024
+ stack[++stackTop] = makeResidual([opNames[op], collectionOnLeft ? constInput : scalarInput, collectionOnLeft ? scalarInput : constInput]);
4025
+ break;
4026
+ }
4027
+ const scalar = slotVal(scalarSlot);
4028
+ if (scalar === null || scalar === undefined) {
4029
+ stack[++stackTop] = op === OP_IN_CONST ? false : true;
4030
+ break;
4031
+ }
4032
+ let s = overlapSetCache.get(constArr);
4033
+ if (s === undefined) {
4034
+ s = new Set(constArr);
4035
+ overlapSetCache.set(constArr, s);
4036
+ }
4037
+ const found = s.has(scalar);
4038
+ stack[++stackTop] = op === OP_IN_CONST ? found : !found;
4039
+ break;
4040
+ }
4041
+ case OP_OR_AND_IN_CONST_2:
4042
+ {
4043
+ // bytecode layout: ref1Idx, ref2Idx, M, aVal0, setBIdx0, aVal1, setBIdx1, ..., aValM-1, setBIdxM-1
4044
+ // aVal_j is a literal value; setBIdx_j is a constIdx for the merged setB.
4045
+ const ref1Idx = numAt(bytecode[i++]);
4046
+ const ref2Idx = numAt(bytecode[i++]);
4047
+ const n = numAt(bytecode[i++]);
4048
+ const pairsStart = i;
4049
+ i += n * 2;
4050
+ const rawKey1 = refRawKeys[ref1Idx];
4051
+ const rawKey2 = refRawKeys[ref2Idx];
4052
+ const v1 = resolveCompactRef(refs[ref1Idx], ctx);
4053
+ const v2 = resolveCompactRef(refs[ref2Idx], ctx);
4054
+ const unknown1 = v1 === undefined && !strictSet?.has(rawKey1) && (!optionalSet || optionalSet.has(rawKey1));
4055
+ const unknown2 = v2 === undefined && !strictSet?.has(rawKey2) && (!optionalSet || optionalSet.has(rawKey2));
4056
+ if (unknown1 || unknown2) {
4057
+ // Reconstruct the original complex expression tree
4058
+ const branches = [opNames[OP_OR]];
4059
+ const andOp = opNames[OP_AND];
4060
+ const eqOp = opNames[OP_EQ];
4061
+ const inOp = opNames[OP_IN];
4062
+ const r1 = refKeys[ref1Idx];
4063
+ const r2 = refKeys[ref2Idx];
4064
+ for (let j = 0; j < n; j++) {
4065
+ const aVal = literalAt(bytecode[pairsStart + j * 2]);
4066
+ const setB = compiled.consts[numAt(bytecode[pairsStart + j * 2 + 1])];
4067
+ const setInput = setB;
4068
+ branches.push([andOp, [eqOp, r1, aVal], [inOp, r2, setInput]]);
4069
+ }
4070
+ stack[++stackTop] = makeResidual(branches);
4071
+ break;
4072
+ }
4073
+
4074
+ // Both refs known — evaluate normally
4075
+ let found = false;
4076
+ if (v1 !== null && v1 !== undefined && v2 !== null && v2 !== undefined) {
4077
+ for (let j = 0; j < n; j++) {
4078
+ if (bytecode[pairsStart + j * 2] === v1) {
4079
+ const setB = compiled.consts[numAt(bytecode[pairsStart + j * 2 + 1])];
4080
+ let s = overlapSetCache.get(setB);
4081
+ if (s === undefined) {
4082
+ s = new Set(setB);
4083
+ overlapSetCache.set(setB, s);
4084
+ }
4085
+ found = s.has(v2);
4086
+ break;
4087
+ }
4088
+ }
4089
+ }
4090
+ stack[++stackTop] = found;
4091
+ break;
4092
+ }
4093
+
4094
+ // ---------------------------------------------------------------------
4095
+ // String
4096
+ // ---------------------------------------------------------------------
4097
+ case OP_PREFIX:
4098
+ case OP_SUFFIX:
4099
+ {
4100
+ const right = stack[stackTop--];
4101
+ const left = stack[stackTop--];
4102
+ if (needsReconstruct(left) || needsReconstruct(right)) {
4103
+ stack[++stackTop] = makeResidual([opNames[op], slotSrc(left), slotSrc(right)]);
4104
+ } else {
4105
+ const lv = slotVal(left);
4106
+ const rv = slotVal(right);
4107
+ stack[++stackTop] = op === OP_PREFIX ? isString(lv) && isString(rv) ? rv.startsWith(lv) : false : isString(lv) && isString(rv) ? lv.endsWith(rv) : false;
4108
+ }
4109
+ break;
4110
+ }
4111
+
4112
+ // ---------------------------------------------------------------------
4113
+ // Array
4114
+ // ---------------------------------------------------------------------
4115
+ case OP_OVERLAP:
4116
+ {
4117
+ const right = stack[stackTop--];
4118
+ const left = stack[stackTop--];
4119
+ if (needsReconstruct(left) || needsReconstruct(right)) {
4120
+ stack[++stackTop] = makeResidual([opNames[op], slotSrc(left), slotSrc(right)]);
4121
+ } else {
4122
+ const l = slotVal(left);
4123
+ const r = slotVal(right);
4124
+ if (l === null || l === undefined || r === null || r === undefined) {
4125
+ stack[++stackTop] = false;
4126
+ } else if (!Array.isArray(l) || !Array.isArray(r)) {
4127
+ throw new Error('OVERLAP: both operands must be arrays');
4128
+ } else if (l.length === 0 && r.length === 0) {
4129
+ stack[++stackTop] = true;
4130
+ } else {
4131
+ stack[++stackTop] = l.some(el => r.includes(el));
4132
+ }
4133
+ }
4134
+ break;
4135
+ }
4136
+
4137
+ // ---------------------------------------------------------------------
4138
+ // Presence
4139
+ // ---------------------------------------------------------------------
4140
+ case OP_PRESENT:
4141
+ {
4142
+ const val = stack[stackTop];
4143
+ if (needsReconstruct(val)) {
4144
+ stack[stackTop] = makeResidual([opNames[op], slotSrc(val)]);
4145
+ } else {
4146
+ const v = slotVal(val);
4147
+ stack[stackTop] = v !== undefined && v !== null;
4148
+ }
4149
+ break;
4150
+ }
4151
+ case OP_UNDEFINED:
4152
+ {
4153
+ const val = stack[stackTop];
4154
+ if (needsReconstruct(val)) {
4155
+ stack[stackTop] = makeResidual([opNames[op], slotSrc(val)]);
4156
+ } else {
4157
+ const v = slotVal(val);
4158
+ stack[stackTop] = v === undefined;
4159
+ }
4160
+ break;
4161
+ }
4162
+
4163
+ // ---------------------------------------------------------------------
4164
+ // Arithmetic
4165
+ // ---------------------------------------------------------------------
4166
+ case OP_SUM:
4167
+ case OP_SUBTRACT:
4168
+ case OP_MULTIPLY:
4169
+ case OP_DIVIDE:
4170
+ {
4171
+ const n = numAt(bytecode[i++]);
4172
+ // Check for any unknown operand
4173
+ let hasUnknown = false;
4174
+ for (let j = 0; j < n; j++) {
4175
+ if (needsReconstruct(stack[stackTop - j])) {
4176
+ hasUnknown = true;
4177
+ break;
4178
+ }
4179
+ }
4180
+ if (hasUnknown) {
4181
+ const items = new Array(n);
4182
+ for (let j = n - 1; j >= 0; j--) {
4183
+ items[j] = slotSrc(stack[stackTop--]);
4184
+ }
4185
+ stack[++stackTop] = makeResidual([opNames[op], ...items]);
4186
+ break;
4187
+ }
4188
+ // Fast path: 2 operands, all concrete
4189
+ if (n === 2) {
4190
+ const bVal = slotVal(stack[stackTop--]);
4191
+ const aVal = slotVal(stack[stackTop--]);
4192
+ if (aVal === null || aVal === undefined || bVal === null || bVal === undefined) {
4193
+ stack[++stackTop] = false;
4194
+ break;
4195
+ }
4196
+ if (!isNumber(aVal) || !isNumber(bVal)) {
4197
+ throw new Error(`arithmetic operand is not a number: ${!isNumber(aVal) ? aVal : bVal}`);
4198
+ }
4199
+ // After the throw above, aVal and bVal are narrowed to number
4200
+ if (op === OP_SUM) {
4201
+ stack[++stackTop] = addDecimals(aVal, bVal);
4202
+ } else if (op === OP_SUBTRACT) {
4203
+ stack[++stackTop] = subtractDecimals(aVal, bVal);
4204
+ } else if (op === OP_MULTIPLY) {
4205
+ stack[++stackTop] = multiplyDecimals(aVal, bVal);
4206
+ } else {
4207
+ // Division — match OOP isInfinite guard: use a marker so
4208
+ // comparisons can decide whether to preserve the expression.
4209
+ const result = divideDecimals(aVal, bVal);
4210
+ if (isUnusableResult(result)) {
4211
+ // Push marker with original operands for reconstruction
4212
+ const marker = {
4213
+ _r: 4,
4214
+ _val: result,
4215
+ left: aVal,
4216
+ right: bVal
4217
+ };
4218
+ stack[++stackTop] = marker;
4219
+ } else {
4220
+ stack[++stackTop] = result;
4221
+ }
4222
+ }
4223
+ break;
4224
+ }
4225
+ // N-operand path
4226
+ const values = new Array(n);
4227
+ let hasNull = false;
4228
+ for (let j = n - 1; j >= 0; j--) {
4229
+ const v = slotVal(stack[stackTop--]);
4230
+ if (v === null || v === undefined) {
4231
+ hasNull = true;
4232
+ break;
4233
+ }
4234
+ if (!isNumber(v)) {
4235
+ throw new Error(`arithmetic operand is not a number: ${v}`);
4236
+ }
4237
+ // After the throw above, v is narrowed to number
4238
+ values[j] = v;
4239
+ }
4240
+ const reduced = hasNull ? false : arithmeticReduce(values, op);
4241
+ if (hasNull) {
4242
+ stack[++stackTop] = false;
4243
+ } else if (op === OP_DIVIDE && reduced !== false && isUnusableResult(reduced)) {
4244
+ // N-operand division producing Infinity/NaN — create marker
4245
+ const result = reduced;
4246
+ const marker = {
4247
+ _r: 4,
4248
+ _val: result,
4249
+ left: values[0],
4250
+ right: values[1]
4251
+ };
4252
+ stack[++stackTop] = marker;
4253
+ } else if (reduced !== false && isUnusableResult(reduced)) {
4254
+ // Other arithmetic producing Infinity/NaN — preserve expression
4255
+ stack[++stackTop] = makeResidual([opNames[op], ...values]);
4256
+ } else {
4257
+ stack[++stackTop] = reduced;
4258
+ }
4259
+ break;
4260
+ }
4261
+
4262
+ // ---------------------------------------------------------------------
4263
+ // Logical
4264
+ // ---------------------------------------------------------------------
4265
+ case OP_NOT:
4266
+ {
4267
+ const val = stack[stackTop];
4268
+ if (needsReconstruct(val)) {
4269
+ const src = slotSrc(val);
4270
+ // If this NOT follows a NOR that already applied its simplification
4271
+ // (multi-residual NOR pushes a NOR expression), pass it through unchanged.
4272
+ if (Array.isArray(src) && src[0] === opNames[OP_NOR]) {
4273
+ // Already a NOR expression — leave it as-is
4274
+ break;
4275
+ }
4276
+ stack[stackTop] = makeResidual([opNames[op], src]);
4277
+ } else {
4278
+ const v = slotVal(val);
4279
+ if (typeof v !== 'boolean') {
4280
+ throw new Error('NOT: operand must be boolean');
4281
+ }
4282
+ stack[stackTop] = !v;
4283
+ }
4284
+ break;
4285
+ }
4286
+ case OP_JUMP_IF_FALSE:
4287
+ {
4288
+ const offset = numAt(bytecode[i++]);
4289
+ const top = stack[stackTop];
4290
+ if (!needsReconstruct(top) && slotVal(top) === false) {
4291
+ i += offset;
4292
+ }
4293
+ // Clear spill buffer when transitioning between short-circuit sequences.
4294
+ // Different jump opcodes (41=JUMP_IF_FALSE for AND vs 42=JUMP_IF_TRUE for OR/NOR)
4295
+ // indicate different short-circuit sequences.
4296
+ if (lastJumpOp !== 41) {
4297
+ spillTop = -1;
4298
+ }
4299
+ lastJumpOp = 41;
4300
+ break;
4301
+ }
4302
+ case OP_JUMP_IF_TRUE:
4303
+ {
4304
+ const offset = numAt(bytecode[i++]);
4305
+ const top = stack[stackTop];
4306
+ if (!needsReconstruct(top) && slotVal(top) === true) {
4307
+ i += offset;
4308
+ }
4309
+ // Clear spill buffer when transitioning between short-circuit sequences.
4310
+ if (lastJumpOp !== 42) {
4311
+ spillTop = -1;
4312
+ }
4313
+ lastJumpOp = 42;
4314
+ break;
4315
+ }
4316
+ case OP_POP:
4317
+ {
4318
+ const popped = stack[stackTop--];
4319
+ // If this residual is being discarded in a short-circuit sequence,
4320
+ // save it so OP_AND/OR/NOR can include it in the reconstructed expression.
4321
+ if (needsReconstruct(popped)) {
4322
+ spillBuf[++spillTop] = popped;
4323
+ }
4324
+ break;
4325
+ }
4326
+
4327
+ // AND/OR/NOR markers — collect the current stack top plus any residuals
4328
+ // that were spilled by OP_POP during the short-circuit sequence, then
4329
+ // apply the simplification logic.
4330
+ case OP_AND:
4331
+ {
4332
+ i++; // consume the operand count byte (unused — we use the spill buffer)
4333
+ const top = stack[stackTop--];
4334
+ // Fast path: nothing was spilled — all non-top operands were concrete.
4335
+ // The top is either a short-circuit false, the last true, or a lone residual.
4336
+ // Push top directly — slotVal unwrapping happens at the final return point.
4337
+ if (spillTop < 0) {
4338
+ spillTop = -1;
4339
+ if (!needsReconstruct(top)) {
4340
+ stack[++stackTop] = top;
4341
+ } else {
4342
+ stack[++stackTop] = makeResidual(slotSrc(top));
4343
+ }
4344
+ break;
4345
+ }
4346
+ const residuals = [];
4347
+ // Drain spill buffer (residuals from earlier operands that were POP'd)
4348
+ // Check if any spilled operand was false (dominates AND)
4349
+ let andDominated = false;
4350
+ for (let j = 0; j <= spillTop; j++) {
4351
+ const v = spillBuf[j];
4352
+ if (!needsReconstruct(v) && slotVal(v) === false) {
4353
+ andDominated = true;
4354
+ break;
4355
+ }
4356
+ if (needsReconstruct(v)) {
4357
+ residuals.push(slotSrc(v));
4358
+ }
4359
+ }
4360
+ spillTop = -1; // clear spill buffer
4361
+ // Include the stack top (last operand result)
4362
+ if (!andDominated) {
4363
+ if (!needsReconstruct(top) && slotVal(top) === false) {
4364
+ andDominated = true;
4365
+ } else if (needsReconstruct(top)) {
4366
+ residuals.push(slotSrc(top));
4367
+ }
4368
+ }
4369
+ if (andDominated) {
4370
+ stack[++stackTop] = false;
4371
+ } else if (residuals.length === 0) {
4372
+ stack[++stackTop] = true;
4373
+ } else if (residuals.length === 1) {
4374
+ stack[++stackTop] = makeResidual(residuals[0]);
4375
+ } else {
4376
+ stack[++stackTop] = makeResidual([opNames[op], ...residuals]);
4377
+ }
4378
+ break;
4379
+ }
4380
+ case OP_OR:
4381
+ {
4382
+ i++; // consume the operand count byte
4383
+ const top = stack[stackTop--];
4384
+ // Fast path: nothing was spilled — all non-top operands were concrete.
4385
+ // Push top directly — slotVal unwrapping happens at the final return point.
4386
+ if (spillTop < 0) {
4387
+ spillTop = -1;
4388
+ if (!needsReconstruct(top)) {
4389
+ stack[++stackTop] = top;
4390
+ } else {
4391
+ stack[++stackTop] = makeResidual(slotSrc(top));
4392
+ }
4393
+ break;
4394
+ }
4395
+ const residuals = [];
4396
+ let orDominated = false;
4397
+ for (let j = 0; j <= spillTop; j++) {
4398
+ const v = spillBuf[j];
4399
+ if (!needsReconstruct(v) && slotVal(v) === true) {
4400
+ orDominated = true;
4401
+ break;
4402
+ }
4403
+ if (needsReconstruct(v)) {
4404
+ residuals.push(slotSrc(v));
4405
+ }
4406
+ }
4407
+ spillTop = -1;
4408
+ if (!orDominated) {
4409
+ if (!needsReconstruct(top) && slotVal(top) === true) {
4410
+ orDominated = true;
4411
+ } else if (needsReconstruct(top)) {
4412
+ residuals.push(slotSrc(top));
4413
+ }
4414
+ }
4415
+ if (orDominated) {
4416
+ stack[++stackTop] = true;
4417
+ } else if (residuals.length === 0) {
4418
+ stack[++stackTop] = false;
4419
+ } else if (residuals.length === 1) {
4420
+ stack[++stackTop] = makeResidual(residuals[0]);
4421
+ } else {
4422
+ stack[++stackTop] = makeResidual([opNames[op], ...residuals]);
4423
+ }
4424
+ break;
4425
+ }
4426
+ case OP_NOR:
4427
+ {
4428
+ // Semantics: NOR = NOT OR. OP_NOT follows in bytecode.
4429
+ // For concrete booleans, we push the OR result so OP_NOT negates it.
4430
+ // For residuals with >1 terms, we apply NOR simplification directly
4431
+ // (returning a NOR expression) and push a "NOR_DONE" residual that
4432
+ // OP_NOT will pass through unchanged.
4433
+ i++; // consume the operand count byte
4434
+ const top = stack[stackTop--];
4435
+ const residuals = [];
4436
+ let dominated = false;
4437
+ for (let j = 0; j <= spillTop; j++) {
4438
+ const v = spillBuf[j];
4439
+ if (!needsReconstruct(v) && slotVal(v) === true) {
4440
+ dominated = true;
4441
+ break;
4442
+ }
4443
+ if (needsReconstruct(v)) {
4444
+ residuals.push(slotSrc(v));
4445
+ }
4446
+ }
4447
+ spillTop = -1;
4448
+ if (!dominated) {
4449
+ if (!needsReconstruct(top) && slotVal(top) === true) {
4450
+ dominated = true;
4451
+ } else if (needsReconstruct(top)) {
4452
+ residuals.push(slotSrc(top));
4453
+ }
4454
+ }
4455
+ if (dominated) {
4456
+ // OR was true → push true so OP_NOT yields false (= NOR false)
4457
+ stack[++stackTop] = true;
4458
+ } else if (residuals.length === 0) {
4459
+ // All false → push false so OP_NOT yields true (= NOR true)
4460
+ stack[++stackTop] = false;
4461
+ } else if (residuals.length === 1) {
4462
+ // Single residual — OP_NOT will wrap in NOT(residual) ✓
4463
+ stack[++stackTop] = makeResidual(residuals[0]);
4464
+ } else {
4465
+ // Multiple residuals — push NOR expression directly.
4466
+ // OP_NOT must pass it through unchanged (handled in OP_NOT case).
4467
+ stack[++stackTop] = makeResidual([opNames[op], ...residuals]);
4468
+ }
4469
+ break;
4470
+ }
4471
+ case OP_XOR:
4472
+ {
4473
+ // XOR is compiled as chained binary: (((A XOR B) XOR C) XOR D).
4474
+ // We accumulate residuals + trueCount into a XorState to defer finalization
4475
+ // until we know all operands. The XorState is finalized when used by another
4476
+ // operator or at the return point.
4477
+ const b = stack[stackTop--];
4478
+ const a = stack[stackTop--];
4479
+
4480
+ // If neither has unknowns, compute the binary XOR directly (no state needed)
4481
+ // But for "one-hot" XOR semantics, if both are true, we need XorState(trueCount=2)
4482
+ // so subsequent chained XORs also see trueCount > 1.
4483
+ if (!needsReconstruct(a) && !needsReconstruct(b)) {
4484
+ const av = slotVal(a) === true;
4485
+ const bv = slotVal(b) === true;
4486
+ const trueCount = (av ? 1 : 0) + (bv ? 1 : 0);
4487
+ if (trueCount > 1) {
4488
+ // Both true → "one-hot" XOR is false, but track trueCount for chained XORs
4489
+ stack[++stackTop] = makeXorState([], trueCount);
4490
+ } else {
4491
+ stack[++stackTop] = (av || bv) && !(av && bv);
4492
+ }
4493
+ break;
4494
+ }
4495
+
4496
+ // Accumulate into a XorState
4497
+ let residuals;
4498
+ let trueCount;
4499
+ if (isXorState(a)) {
4500
+ residuals = a.xorResiduals.slice();
4501
+ trueCount = a.xorTrueCount;
4502
+ } else if (!needsReconstruct(a)) {
4503
+ residuals = [];
4504
+ trueCount = slotVal(a) ? 1 : 0;
4505
+ } else {
4506
+ residuals = [slotSrc(a)];
4507
+ trueCount = 0;
4508
+ }
4509
+ if (isXorState(b)) {
4510
+ for (const r of b.xorResiduals) {
4511
+ residuals.push(r);
4512
+ }
4513
+ trueCount += b.xorTrueCount;
4514
+ } else if (!needsReconstruct(b)) {
4515
+ if (slotVal(b)) {
4516
+ trueCount++;
4517
+ }
4518
+ } else {
4519
+ residuals.push(slotSrc(b));
4520
+ }
4521
+
4522
+ // If no residuals, resolve immediately
4523
+ // "One-hot" XOR: exactly one true → true, otherwise false
4524
+ // This matches the OOP evaluator's behavior.
4525
+ // Use XorState so subsequent chained XORs also see trueCount > 1.
4526
+ if (trueCount > 1) {
4527
+ stack[++stackTop] = makeXorState([], trueCount);
4528
+ break;
4529
+ }
4530
+ if (residuals.length === 0) {
4531
+ stack[++stackTop] = trueCount % 2 === 1;
4532
+ break;
4533
+ }
4534
+
4535
+ // Push accumulated state — finalized by slotSrc() when consumed by another op
4536
+ stack[++stackTop] = makeXorState(residuals, trueCount);
4537
+ break;
4538
+ }
4539
+ default:
4540
+ throw new Error(`unknown opcode: ${op}`);
4541
+ }
4542
+ }
4543
+
4544
+ // Unwrap the top slot to a plain Result | Input
4545
+ const top = stack[stackTop];
4546
+ if (isXorState(top) || isResidual(top)) {
4547
+ return slotSrc(top);
4548
+ }
4549
+ const result = slotVal(top);
4550
+ if (result === undefined) {
4551
+ throw new Error('simplify: unexpected undefined top-level result');
4552
+ }
4553
+ if (!isInput(result)) {
4554
+ throw new Error('simplify: unexpected non-Input result');
4555
+ }
4556
+ return result;
4557
+ }
4558
+
4559
+ class BytecodeEvaluable {
4560
+ constructor(compiled, delegate) {
4561
+ this.compiled = compiled;
4562
+ this.delegate = delegate;
4563
+ _defineProperty(this, "type", EvaluableType.Expression);
4564
+ }
4565
+ evaluate(ctx) {
4566
+ return interpret(this.compiled, ctx);
4567
+ }
4568
+ simplify(ctx, strictKeys, optionalKeys) {
4569
+ return interpretSimplify(this.compiled, ctx, strictKeys, optionalKeys);
4570
+ }
4571
+ serialize(options) {
4572
+ return this.delegate.serialize(options);
4573
+ }
4574
+ toString() {
4575
+ return this.delegate.toString();
4576
+ }
4577
+ }
4578
+
4579
+ /**
4580
+ * Collection operand resolved containing mixture of value and references.
4581
+ */
4582
+ class Collection extends Operand {
4583
+ /**
4584
+ * Get the items in the collection.
4585
+ * @returns {Array<Value | Reference>}
4586
+ */
4587
+ getItems() {
4588
+ return this.items;
4589
+ }
4590
+
4591
+ /**
4592
+ * @constructor
4593
+ * @param {Operand[]} items Collection of operands.
4594
+ */
4595
+ constructor(items) {
4596
+ super();
4597
+ _defineProperty(this, "items", void 0);
4598
+ this.items = items;
4599
+ }
4600
+
4601
+ /**
4602
+ * Evaluate in the given context.
4603
+ * @param {Context} ctx
4604
+ * @return {boolean}
4605
+ */
4606
+ evaluate(ctx) {
4607
+ return this.items.map(item => item.evaluate(ctx));
4608
+ }
4609
+
4610
+ /**
4611
+ * {@link Evaluable.simplify}
4612
+ */
4613
+ simplify(...args) {
4614
+ const values = [];
4615
+ for (const item of this.items) {
4616
+ const simplifiedItem = item.simplify(...args);
4617
+ if (isEvaluable(simplifiedItem)) {
4618
+ return this;
4619
+ }
4620
+ values.push(simplifiedItem);
4621
+ }
4622
+ return values;
4623
+ }
4624
+
4625
+ /**
4626
+ * {@link Evaluable.serialize}
4627
+ */
4628
+ serialize(options) {
4629
+ return this.items.map(item => isEvaluable(item) ? item.serialize(options) : item);
4630
+ }
4631
+
4632
+ /**
4633
+ * Get the strict representation of the operand.
4634
+ * @return {string}
4635
+ */
4636
+ toString() {
4637
+ return '[' + this.items.map(item => item.toString()).join(', ') + ']';
4638
+ }
4639
+ }
4640
+
4641
+ // Option value whitelist
4642
+
4643
+ /**
4644
+ * Engine evaluator mode.
4645
+ * - `'oop'` (default): evaluates expressions using the classic OOP evaluable tree.
4646
+ * - `'bytecode'`: compiles expressions to bytecode and interprets them.
4647
+ */
4648
+
4649
+ // Parser options
4650
+
4651
+ /**
4652
+ * Default reference predicate.
4653
+ * The "$" symbol at the begging of the operand is used
4654
+ * to predicate the reference type.
4655
+ * E.g. "$State", "$Country"
4656
+ * @param {string} key
4657
+ * @return {boolean}
4658
+ */
4659
+ function defaultReferencePredicate(key) {
4660
+ return typeof key === 'string' && key[0] === '$';
4661
+ }
4662
+
4663
+ /**
4664
+ * Default reference transform.
4665
+ * It removes the "$" symbol at the begging of the operand name.
4666
+ * @param {string} key
4667
+ * @return {string}
4668
+ */
4669
+ function defaultReferenceTransform(key) {
4670
+ return key.slice(1);
4671
+ }
4672
+ function defaultReferenceSerialization(key) {
4673
+ return `$${key}`;
4674
+ }
4675
+
4676
+ // Default operator mapping
4677
+ // Unique operator key <-> raw expression key
4678
+ const defaultOperatorMapping = new Map([
4679
+ // Comparison
4680
+ [OPERATOR$h, '=='], [OPERATOR$b, '!='], [OPERATOR$f, '>'], [OPERATOR$g, '>='], [OPERATOR$c, '<'], [OPERATOR$d, '<='], [OPERATOR$e, 'IN'], [OPERATOR$a, 'NOT IN'], [OPERATOR$8, 'PREFIX'], [OPERATOR$6, 'SUFFIX'], [OPERATOR$9, 'OVERLAP'], [OPERATOR$5, 'UNDEFINED'], [OPERATOR$7, 'PRESENT'],
4681
+ // Logical
4682
+ [OPERATOR$4, 'AND'], [OPERATOR$1, 'OR'], [OPERATOR$2, 'NOR'], [OPERATOR, 'XOR'], [OPERATOR$3, 'NOT'],
4683
+ // Arithmetic
4684
+ [OPERATOR$i, '+'], [OPERATOR$j, '-'], [OPERATOR$k, '*'], [OPERATOR$l, '/']]);
4685
+
4686
+ /**
4687
+ * Default parser options
4688
+ */
4689
+ const defaultOptions = {
4690
+ referencePredicate: defaultReferencePredicate,
4691
+ referenceTransform: defaultReferenceTransform,
4692
+ referenceSerialization: defaultReferenceSerialization,
4693
+ operatorMapping: defaultOperatorMapping
4694
+ };
4695
+
4696
+ // Input types
4697
+
4698
+ const invalidExpression = 'invalid expression';
4699
+ const logicalIfValidOperands = (operands, logical) => {
4700
+ if (operands.every(operand => operand instanceof Logical || operand instanceof Comparison)) {
4701
+ return logical;
4702
+ }
4703
+ throw new Error(invalidExpression);
4704
+ };
4705
+
4706
+ /**
4707
+ * Parser of raw expressions into Evaluable expression
4708
+ */
4709
+ class Parser {
4710
+ /**
4711
+ * @constructor
4712
+ * @param {Options?} options Parser options.
4713
+ */
4714
+ constructor(options) {
4715
+ _defineProperty(this, "opts", void 0);
4716
+ _defineProperty(this, "expectedRootOperators", void 0);
4717
+ _defineProperty(this, "unexpectedRootSymbols", new Set([OPERATOR$i, OPERATOR$j, OPERATOR$k, OPERATOR$l]));
4718
+ _defineProperty(this, "referenceCache", new Map());
4719
+ this.opts = {
4720
+ ...defaultOptions
4721
+ };
4722
+ // Apply exclusive options overrides
4723
+ if (options) {
4724
+ for (const key of Object.keys(options)) {
4725
+ if (key in this.opts) {
4726
+ Reflect.set(this.opts, key, Reflect.get(options, key));
1758
4727
  }
1759
4728
  }
1760
4729
  }
@@ -1809,6 +4778,9 @@ class Parser {
1809
4778
  let expression;
1810
4779
  let operandParser = this.getOperand;
1811
4780
  const operator = raw[0];
4781
+ if (typeof operator !== 'string') {
4782
+ return this.getOperand(raw);
4783
+ }
1812
4784
  const operands = raw.slice(1);
1813
4785
 
1814
4786
  /**
@@ -1961,7 +4933,19 @@ class Engine {
1961
4933
  */
1962
4934
  constructor(options) {
1963
4935
  _defineProperty(this, "parser", void 0);
4936
+ _defineProperty(this, "evaluator", void 0);
4937
+ _defineProperty(this, "bytecodeCache", new WeakMap());
1964
4938
  this.parser = new Parser(options);
4939
+ this.evaluator = options?.evaluator ?? 'oop';
4940
+ }
4941
+ getCompiled(exp) {
4942
+ let compiled = this.bytecodeCache.get(exp);
4943
+ if (compiled === undefined) {
4944
+ this.parser.parse(exp); // validates root operator and expression structure
4945
+ compiled = compile(exp, this.parser.options);
4946
+ this.bytecodeCache.set(exp, compiled);
4947
+ }
4948
+ return compiled;
1965
4949
  }
1966
4950
 
1967
4951
  /**
@@ -1971,7 +4955,7 @@ class Engine {
1971
4955
  * @return {boolean}
1972
4956
  */
1973
4957
  evaluate(exp, ctx) {
1974
- const result = this.parse(exp).evaluate(ctx);
4958
+ const result = this.evaluator === 'oop' ? this.parser.parse(exp).evaluate(ctx) : interpret(this.getCompiled(exp), ctx);
1975
4959
  if (isBoolean(result)) {
1976
4960
  return result;
1977
4961
  }
@@ -1993,7 +4977,10 @@ class Engine {
1993
4977
  * @return {Evaluable}
1994
4978
  */
1995
4979
  parse(exp) {
1996
- return this.parser.parse(exp);
4980
+ if (this.evaluator === 'oop') {
4981
+ return this.parser.parse(exp);
4982
+ }
4983
+ return new BytecodeEvaluable(this.getCompiled(exp), this.parser.parse(exp));
1997
4984
  }
1998
4985
 
1999
4986
  /**
@@ -2014,7 +5001,10 @@ class Engine {
2014
5001
  * @returns {Inpunt | boolean}
2015
5002
  */
2016
5003
  simplify(exp, context, strictKeys, optionalKeys) {
2017
- const result = this.parse(exp).simplify(context, strictKeys, optionalKeys);
5004
+ if (this.evaluator === 'bytecode') {
5005
+ return interpretSimplify(this.getCompiled(exp), context, strictKeys, optionalKeys);
5006
+ }
5007
+ const result = this.parser.parse(exp).simplify(context, strictKeys, optionalKeys);
2018
5008
  if (isEvaluable(result)) {
2019
5009
  return result.serialize(this.parser.options);
2020
5010
  }