@briza/illogical 2.0.2 → 2.2.0

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