@cobol-ts/cel-implementation 0.0.13 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +68 -6
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +1 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/src/cel.aggregates.benchmark.d.ts +15 -0
  6. package/dist/src/cel.aggregates.benchmark.js +75 -0
  7. package/dist/src/cel.aggregates.benchmark.js.map +1 -0
  8. package/dist/src/cel.collections.spec.js +262 -2
  9. package/dist/src/cel.collections.spec.js.map +1 -1
  10. package/dist/src/cel.compile.d.ts +15 -4
  11. package/dist/src/cel.compile.js +740 -179
  12. package/dist/src/cel.compile.js.map +1 -1
  13. package/dist/src/cel.compile.spec.js +3 -2
  14. package/dist/src/cel.compile.spec.js.map +1 -1
  15. package/dist/src/cel.indexed.slot.spec.d.ts +1 -0
  16. package/dist/src/cel.indexed.slot.spec.js +58 -0
  17. package/dist/src/cel.indexed.slot.spec.js.map +1 -0
  18. package/dist/src/cel.numeric.pic.spec.d.ts +1 -0
  19. package/dist/src/cel.numeric.pic.spec.js +72 -0
  20. package/dist/src/cel.numeric.pic.spec.js.map +1 -0
  21. package/dist/src/cel.operations.d.ts +45 -0
  22. package/dist/src/cel.operations.js +225 -0
  23. package/dist/src/cel.operations.js.map +1 -0
  24. package/dist/src/cel.operations.spec.d.ts +1 -0
  25. package/dist/src/cel.operations.spec.js +193 -0
  26. package/dist/src/cel.operations.spec.js.map +1 -0
  27. package/dist/src/cel.rolling.window.spec.d.ts +1 -0
  28. package/dist/src/cel.rolling.window.spec.js +151 -0
  29. package/dist/src/cel.rolling.window.spec.js.map +1 -0
  30. package/dist/src/cel.type.algebra.spec.d.ts +1 -0
  31. package/dist/src/cel.type.algebra.spec.js +65 -0
  32. package/dist/src/cel.type.algebra.spec.js.map +1 -0
  33. package/package.json +9 -6
@@ -3,25 +3,108 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.compileCelExpression = compileCelExpression;
4
4
  exports.evaluateCompiled = evaluateCompiled;
5
5
  exports.compileCelCollectionExpression = compileCelCollectionExpression;
6
+ const ring_buffer_1 = require("@cobol-ts/ring-buffer");
7
+ const cursor_loader_types_1 = require("@cobol-ts/cursor-loader-types");
6
8
  const errors_1 = require("@cobol-ts/errors");
7
9
  const cel_1 = require("@cobol-ts/cel");
10
+ const cel_operations_1 = require("./cel.operations");
8
11
  const INT_MIN = -(1n << 63n);
9
12
  const INT_MAX = (1n << 63n) - 1n;
10
13
  const UINT_MAX = (1n << 64n) - 1n;
11
- /** One vector per occurrence depth, allocated at most once per evaluation. */
14
+ function createFrame() { return { indices: [], activeLength: 0, windows: [], values: [], visitors: [] }; }
15
+ /** A distinct visitor slot per compiled collection operation, private to the leased result. */
16
+ function visitorState(frame, slot, factory) {
17
+ let state = frame.visitors[slot];
18
+ if (state === undefined) {
19
+ state = factory();
20
+ frame.visitors[slot] = state;
21
+ }
22
+ return state;
23
+ }
24
+ /** Previous record's lexical values must not survive reuse of a pooled result. */
25
+ function clearFrameValues(frame) {
26
+ for (let n = 0; n < frame.values.length; n++)
27
+ frame.values[n] = undefined;
28
+ }
29
+ function bindFrame(frame, indices) {
30
+ frame.activeLength = indices.length;
31
+ for (let n = 0; n < indices.length; n++)
32
+ frame.indices[n] = indices[n];
33
+ }
34
+ /** One reusable prefix vector per depth. No slice or per-read index array. */
12
35
  function windowAt(frame, depth) {
13
36
  let window = frame.windows[depth];
14
37
  if (window === undefined) {
15
- window = frame.indices.slice(0, depth);
38
+ window = [];
16
39
  frame.windows[depth] = window;
17
40
  }
41
+ const length = Math.min(depth, frame.activeLength);
42
+ for (let n = 0; n < length; n++)
43
+ window[n] = frame.indices[n];
44
+ while (window.length > length)
45
+ window.pop();
18
46
  return window;
19
47
  }
20
48
  function setOccurrence(frame, depth, index) {
21
49
  frame.indices[depth] = index;
22
- for (const vector of frame.windows)
23
- if (vector && vector.length > depth)
24
- vector[depth] = index;
50
+ if (frame.activeLength <= depth)
51
+ frame.activeLength = depth + 1;
52
+ }
53
+ function compiledScalarType(kind, representation) {
54
+ const semanticType = kind === 'int' ? 'integer' : kind === 'uint' ? 'unsignedInteger' :
55
+ kind === 'double' ? 'float' : kind === 'bool' ? 'boolean' : kind === 'null' ? 'null' : 'string';
56
+ return { kind: 'scalar', semanticType, javascriptType: representation };
57
+ }
58
+ function isCelRootScalar(type) {
59
+ return type.semanticType !== 'fixed2' && type.semanticType !== 'fixed3';
60
+ }
61
+ function elementKind(type) {
62
+ if (type.kind === 'object' || type.kind === 'map')
63
+ return 'object';
64
+ if (type.kind === 'array')
65
+ return 'list';
66
+ switch (type.semanticType) {
67
+ case 'integer': return 'int';
68
+ case 'unsignedInteger': return 'uint';
69
+ case 'float': return 'double';
70
+ case 'boolean': return 'bool';
71
+ case 'null': return 'null';
72
+ case 'string': return 'string';
73
+ default: throw new Error(`Unsupported CEL element semantic type`);
74
+ }
75
+ }
76
+ /** The domain algebra permits future fixed-point scalars. CEL currently doesn't;
77
+ * validate this one translation boundary before retaining the descriptor. */
78
+ function supportedCelValueType(type) {
79
+ if (type.kind === 'scalar')
80
+ return type.semanticType !== 'fixed2' && type.semanticType !== 'fixed3';
81
+ if (type.kind === 'array')
82
+ return supportedCelValueType(type.element);
83
+ if (type.kind === 'object')
84
+ return Object.values(type.fields).every(supportedCelValueType);
85
+ if (type.kind === 'rolling-window')
86
+ return false; // Phase 4 adds a non-materialising CEL collection adapter.
87
+ return supportedCelValueType(type.key) && supportedCelValueType(type.value);
88
+ }
89
+ function scalarElement(type) {
90
+ return type.kind === 'scalar' ? type : undefined;
91
+ }
92
+ function projectionValueTypeAt(types, path) {
93
+ let fields = types;
94
+ let found;
95
+ for (const name of path) {
96
+ found = fields[name];
97
+ if (found === undefined)
98
+ throw new Error(`Missing projection value type for ${path.join('.')}`);
99
+ const object = found.kind === 'array' ? found.element : found;
100
+ if (object.kind === 'object')
101
+ fields = object.fields;
102
+ else if (name !== path[path.length - 1])
103
+ throw new Error(`Cannot traverse scalar value type ${path.join('.')}`);
104
+ }
105
+ if (found === undefined)
106
+ throw new Error('Empty projection value type path');
107
+ return found;
25
108
  }
26
109
  const failed = (message) => (0, errors_1.errors)(message);
27
110
  const message = (error) => error instanceof Error ? error.message : String(error);
@@ -31,19 +114,75 @@ function checkInt(n, kind) {
31
114
  throw new RangeError(`${kind} overflow: ${n}`);
32
115
  return n;
33
116
  }
34
- function ensureValue(kind, v) {
117
+ function ensureValue(kind, v, allowNumber = false) {
35
118
  if (kind === 'null')
36
119
  return v === null;
37
120
  if (kind === 'int' || kind === 'uint')
38
- return typeof v === 'bigint' &&
39
- (kind === 'int' ? (v >= INT_MIN && v <= INT_MAX) : (v >= 0n && v <= UINT_MAX));
121
+ return typeof v === 'bigint'
122
+ ? (kind === 'int' ? (v >= INT_MIN && v <= INT_MAX) : (v >= 0n && v <= UINT_MAX))
123
+ : allowNumber && typeof v === 'number' && Number.isSafeInteger(v) &&
124
+ (kind === 'int' || v >= 0);
40
125
  return typeof v === (kind === 'double' ? 'number' : kind === 'bool' ? 'boolean' : 'string');
41
126
  }
42
- function readProjectionInteger(n) {
127
+ /** A root field uses its declared physical representation, never the
128
+ * consumer expression's literal policy. */
129
+ function ensureRepresentedValue(kind, representation, raw) {
130
+ if (kind !== 'int' && kind !== 'uint')
131
+ return ensureValue(kind, raw);
132
+ if (representation === 'number')
133
+ return typeof raw === 'number' && Number.isSafeInteger(raw) && (kind !== 'uint' || raw >= 0);
134
+ if (representation === 'bigint')
135
+ return typeof raw === 'bigint' && ensureValue(kind, raw);
136
+ return ensureValue(kind, raw, true);
137
+ }
138
+ function readProjectionInteger(n, asNumber = false) {
139
+ // A COBOL numeric decoder has already validated its number.
140
+ if (asNumber)
141
+ return n;
43
142
  if (!Number.isSafeInteger(n))
44
143
  throw new RangeError(`Projection integer is not a safe integer: ${n}`);
45
144
  return checkInt(BigInt(n), 'int');
46
145
  }
146
+ /** A numeric operator uses native number arithmetic when both inputs are numbers,
147
+ * preserving bigint arithmetic if either input was selected by a wider PIC. */
148
+ function safeNumberInteger(value) {
149
+ if (!Number.isSafeInteger(value))
150
+ throw new RangeError('Integer arithmetic exceeds the JavaScript safe-integer range');
151
+ return value;
152
+ }
153
+ function integerOperation(operator, a, b, kind) {
154
+ if (typeof a === 'number' && typeof b === 'number') {
155
+ if ((operator === '/' || operator === '%') && b === 0)
156
+ throw new RangeError('Integer division by zero');
157
+ switch (operator) {
158
+ case '+': return safeNumberInteger(a + b);
159
+ case '-': return safeNumberInteger(a - b);
160
+ case '*': return safeNumberInteger(a * b);
161
+ case '/': return safeNumberInteger(Math.trunc(a / b));
162
+ default: return safeNumberInteger(a % b);
163
+ }
164
+ }
165
+ const x = typeof a === 'bigint' ? a : BigInt(a), y = typeof b === 'bigint' ? b : BigInt(b);
166
+ if ((operator === '/' || operator === '%') && y === 0n)
167
+ throw new RangeError('Integer division by zero');
168
+ let result;
169
+ switch (operator) {
170
+ case '+':
171
+ result = x + y;
172
+ break;
173
+ case '-':
174
+ result = x - y;
175
+ break;
176
+ case '*':
177
+ result = x * y;
178
+ break;
179
+ case '/':
180
+ result = x / y;
181
+ break;
182
+ default: result = x % y;
183
+ }
184
+ return checkInt(result, kind);
185
+ }
47
186
  function resolveNode(definition, path) {
48
187
  let fields = definition;
49
188
  let node;
@@ -62,8 +201,11 @@ function resolveNode(definition, path) {
62
201
  }
63
202
  return node;
64
203
  }
65
- function scalar(kind, run) {
66
- return { kind, run };
204
+ function scalar(kind, run, representation = kind === 'int' || kind === 'uint' ? 'bigint' : kind === 'double' ? 'number' : kind === 'bool' ? 'boolean' : kind === 'null' ? 'null' : 'string') {
205
+ return { kind, type: compiledScalarType(kind, representation), run };
206
+ }
207
+ function scalarWithType(type, run) {
208
+ return { kind: elementKind(type), type, run };
67
209
  }
68
210
  function concrete(node) {
69
211
  return node.kind !== 'object' && node.kind !== 'collection';
@@ -83,15 +225,111 @@ function arrayDepth(projection, path) {
83
225
  }
84
226
  return depth;
85
227
  }
86
- function collect(node, r, i, frame) {
228
+ function createCollectorState() {
229
+ const state = { result: undefined, visit: item => {
230
+ if (item === undefined)
231
+ throw new Error('An object collection must be projected before it can be returned');
232
+ state.result.push(item);
233
+ return true;
234
+ } };
235
+ return state;
236
+ }
237
+ function collect(node, r, i, frame, slot) {
238
+ // A nested computed list is a value: unlike scratch, it must not alias future results.
87
239
  const result = [];
88
- node.iterate(r, i, frame, item => {
89
- if (item === undefined)
90
- throw new Error('An object collection must be projected before it can be returned');
91
- result.push(item);
92
- return true;
93
- });
94
- return result;
240
+ const state = visitorState(frame, slot, createCollectorState);
241
+ state.result = result;
242
+ try {
243
+ node.iterate(r, i, frame, state.visit);
244
+ return result;
245
+ }
246
+ finally {
247
+ state.result = undefined;
248
+ }
249
+ }
250
+ /** Compiles numeric aggregation over the same traversal used by map/filter/reduce. */
251
+ function compileCollectionAggregate(target, name, args, preferNumberIntegers = false, slot) {
252
+ if (!['size', 'sum', 'min', 'max', 'avg'].includes(name))
253
+ return failed(`Receiver-style function ${name} is not supported yet`);
254
+ if (target.kind !== 'collection')
255
+ return failed(`${name} requires an array receiver`);
256
+ if (args.length !== 0)
257
+ return failed(`${name} expects 0 arguments, got ${args.length}`);
258
+ const collection = target;
259
+ if (name === 'size') {
260
+ const create = () => {
261
+ const state = { count: 0, visit: () => { state.count++; return true; } };
262
+ return state;
263
+ };
264
+ return (0, errors_1.value)(scalar('int', (r, i, frame) => {
265
+ if (!frame)
266
+ throw new Error('Missing collection evaluation frame');
267
+ if (collection.length !== undefined) {
268
+ const count = collection.length(r, i, frame);
269
+ return preferNumberIntegers ? count : checkInt(BigInt(count), 'int');
270
+ }
271
+ const state = visitorState(frame, slot, create);
272
+ state.count = 0;
273
+ collection.iterate(r, i, frame, state.visit);
274
+ return preferNumberIntegers ? state.count : checkInt(BigInt(state.count), 'int');
275
+ }, preferNumberIntegers ? 'number' : 'bigint'));
276
+ }
277
+ const element = scalarElement(collection.type.element);
278
+ if (element === undefined)
279
+ return failed(`${name} requires a typed scalar collection element`);
280
+ const kind = elementKind(element);
281
+ if (kind !== 'int' && kind !== 'uint' && kind !== 'double')
282
+ return failed(`${name} requires a numeric collection, got ${kind}`);
283
+ const representation = element.javascriptType;
284
+ // Select the accumulator operation once, not per element visited.
285
+ const add = kind === 'double'
286
+ ? (a, b) => a + b
287
+ : representation === 'number'
288
+ ? (a, b) => safeNumberInteger(a + b)
289
+ : representation === 'bigint'
290
+ ? (a, b) => checkInt(a + b, kind)
291
+ : (a, b) => integerOperation('+', a, b, kind);
292
+ const zero = kind === 'double' || representation === 'number' ? 0 : 0n;
293
+ const create = () => {
294
+ const state = { count: 0, total: zero, first: true, best: zero, visit: item => {
295
+ const candidate = item;
296
+ if (name === 'sum' || name === 'avg') {
297
+ state.total = add(state.total, candidate);
298
+ state.count++;
299
+ }
300
+ else if (state.first) {
301
+ state.best = candidate;
302
+ state.first = false;
303
+ }
304
+ else if (kind === 'double' && (Number.isNaN(state.best) || Number.isNaN(candidate)))
305
+ state.best = NaN;
306
+ else if (name === 'min' ? candidate < state.best : candidate > state.best)
307
+ state.best = candidate;
308
+ return true;
309
+ } };
310
+ return state;
311
+ };
312
+ const outputType = name === 'avg' ? compiledScalarType('double', 'number') : element;
313
+ return (0, errors_1.value)(scalarWithType(outputType, (r, i, frame) => {
314
+ if (!frame)
315
+ throw new Error('Missing collection evaluation frame');
316
+ const state = visitorState(frame, slot, create);
317
+ state.count = 0;
318
+ state.total = zero;
319
+ state.first = true;
320
+ state.best = zero;
321
+ collection.iterate(r, i, frame, state.visit);
322
+ if (name === 'sum')
323
+ return state.total;
324
+ if (name === 'avg') {
325
+ if (state.count === 0)
326
+ throw new RangeError('avg of empty collection');
327
+ return Number(state.total) / state.count;
328
+ }
329
+ if (state.first)
330
+ throw new RangeError(`${name} of empty collection`);
331
+ return state.best;
332
+ }));
95
333
  }
96
334
  /** Builds executable closures through the existing tagless CEL parser. */
97
335
  class CompilingInterpreter {
@@ -99,28 +337,130 @@ class CompilingInterpreter {
99
337
  accesses;
100
338
  functions;
101
339
  roots;
102
- constructor(projection, accesses, functions, roots = {}) {
340
+ rootReaders;
341
+ operations;
342
+ rootRepresentations;
343
+ conditionals;
344
+ rootValueTypes;
345
+ constructor(projection, accesses, functions, roots = {}, rootReaders = {}, operations = cel_operations_1.defaultBinaryOperations, rootRepresentations = {}, conditionals = cel_operations_1.defaultConditionalOperations, rootValueTypes = {}) {
103
346
  this.projection = projection;
104
347
  this.accesses = accesses;
105
348
  this.functions = functions;
106
349
  this.roots = roots;
350
+ this.rootReaders = rootReaders;
351
+ this.operations = operations;
352
+ this.rootRepresentations = rootRepresentations;
353
+ this.conditionals = conditionals;
354
+ this.rootValueTypes = rootValueTypes;
355
+ this.preferNumberIntegers = accesses.preferNumberIntegers === true;
356
+ this.projectionTypes = (0, cursor_loader_types_1.projectionValueTypes)(projection);
107
357
  }
358
+ projectionTypes;
359
+ preferNumberIntegers;
360
+ get fastNumbers() { return this.preferNumberIntegers; }
108
361
  scopes = [];
109
362
  nextSlot = 0;
363
+ nextVisitorSlot = 0;
110
364
  needsFrame = false;
365
+ allocateVisitorSlot() { return this.nextVisitorSlot++; }
366
+ rootRepresentation(root, name, kind) {
367
+ return this.rootRepresentations[root]?.[name] ??
368
+ (kind === 'int' || kind === 'uint' ? (['variables', 'acc'].includes(root) ? 'dynamic' : this.fastNumbers ? 'number' : 'bigint') :
369
+ kind === 'double' ? 'number' : kind === 'bool' ? 'boolean' : kind === 'null' ? 'null' : 'string');
370
+ }
111
371
  isScopedCall(name) {
112
- return name === 'map' || name === 'filter' || name === 'exists' || name === 'all';
372
+ return name === 'map' || name === 'filter' || name === 'exists' || name === 'all' || name === 'reduce';
373
+ }
374
+ enterReductionScope(target, accumulator, element, initial) {
375
+ if (target.kind !== 'collection')
376
+ return failed('reduce requires an array receiver');
377
+ if (!concrete(initial))
378
+ return failed('reduce requires a scalar initial value');
379
+ if (accumulator === element)
380
+ return failed('reduce accumulator and element bindings must be distinct');
381
+ const accumulatorSlot = this.nextSlot++;
382
+ this.scopes.push({ name: accumulator, slot: accumulatorSlot, type: initial.type });
383
+ if (elementKind(target.type.element) === 'object') {
384
+ if (!target.sourcePath) {
385
+ this.scopes.pop();
386
+ return failed('Collection object has no projection path');
387
+ }
388
+ this.scopes.push({ name: element, type: target.type.element, sourcePath: target.sourcePath });
389
+ }
390
+ else if (elementKind(target.type.element) === 'list') {
391
+ this.scopes.pop();
392
+ return failed('reduce of computed nested lists is not supported yet');
393
+ }
394
+ else {
395
+ if (!scalarElement(target.type.element)) {
396
+ this.scopes.pop();
397
+ return failed('Missing collection element value type');
398
+ }
399
+ this.scopes.push({ name: element, type: target.type.element, slot: this.nextSlot++ });
400
+ }
401
+ this.needsFrame = true;
402
+ return (0, errors_1.value)(undefined);
403
+ }
404
+ leaveReductionScope() { this.scopes.pop(); this.scopes.pop(); }
405
+ reductionCall(target, _accumulator, _element, initial, body) {
406
+ if (target.kind !== 'collection' || !concrete(initial))
407
+ return failed('reduce requires an array and scalar initial value');
408
+ if (!concrete(body))
409
+ return failed('reduce body must be scalar');
410
+ if (initial.type.semanticType !== body.type.semanticType)
411
+ return failed(`reduce body must return ${initial.kind}, got ${body.kind}`);
412
+ if (initial.type.javascriptType !== body.type.javascriptType)
413
+ return failed(`reduce body must return ${initial.type.javascriptType}, got ${body.type.javascriptType}`);
414
+ const element = this.scopes[this.scopes.length - 1];
415
+ const accumulation = this.scopes[this.scopes.length - 2];
416
+ if (!element || !accumulation || accumulation.slot === undefined)
417
+ return failed('Missing reduce lexical bindings');
418
+ const accumulatorSlot = accumulation.slot, elementSlot = element.slot;
419
+ const visitorSlot = this.nextVisitorSlot++;
420
+ const create = () => {
421
+ const state = { record: undefined, indices: undefined, frame: undefined,
422
+ result: undefined, visit: item => {
423
+ const f = state.frame;
424
+ f.values[accumulatorSlot] = state.result;
425
+ if (elementSlot !== undefined)
426
+ f.values[elementSlot] = item;
427
+ state.result = body.run(state.record, state.indices, f);
428
+ return true;
429
+ } };
430
+ return state;
431
+ };
432
+ return (0, errors_1.value)(scalarWithType(initial.type, (record, indices, frame) => {
433
+ if (!frame)
434
+ throw new Error('Missing collection evaluation frame');
435
+ const result = initial.run(record, indices, frame);
436
+ const state = visitorState(frame, visitorSlot, create);
437
+ state.result = result;
438
+ state.record = record;
439
+ state.indices = indices;
440
+ state.frame = frame;
441
+ try {
442
+ target.iterate(record, indices, frame, state.visit);
443
+ return state.result;
444
+ }
445
+ finally {
446
+ state.record = undefined;
447
+ state.indices = undefined;
448
+ state.frame = undefined;
449
+ }
450
+ }));
113
451
  }
114
452
  enterScope(target, _operation, name) {
115
453
  if (target.kind !== 'collection')
116
454
  return failed('Collection operation requires an array receiver');
117
- if (target.elementKind === 'object') {
455
+ if (elementKind(target.type.element) === 'object') {
118
456
  if (!target.sourcePath)
119
457
  return failed('Collection object has no projection path');
120
- this.scopes.push({ name, kind: 'object', sourcePath: target.sourcePath });
458
+ this.scopes.push({ name, type: target.type.element, sourcePath: target.sourcePath });
121
459
  }
122
460
  else {
123
- this.scopes.push({ name, kind: target.elementKind, slot: this.nextSlot++ });
461
+ if (!scalarElement(target.type.element))
462
+ return failed('Missing collection element value type');
463
+ this.scopes.push({ name, type: target.type.element, slot: this.nextSlot++ });
124
464
  }
125
465
  this.needsFrame = true;
126
466
  return (0, errors_1.value)(undefined);
@@ -146,41 +486,83 @@ class CompilingInterpreter {
146
486
  return failed('Unknown collection operation ' + operation);
147
487
  if (operation === 'exists' || operation === 'all') {
148
488
  const predicate = body;
489
+ const visitorSlot = this.nextVisitorSlot++;
490
+ const create = () => {
491
+ const state = { record: undefined, indices: undefined, frame: undefined, matched: false,
492
+ visit: item => {
493
+ const f = state.frame;
494
+ if (binding.slot !== undefined)
495
+ f.values[binding.slot] = item;
496
+ const test = predicate.run(state.record, state.indices, f);
497
+ if (operation === 'exists' && test) {
498
+ state.matched = true;
499
+ return false;
500
+ }
501
+ if (operation === 'all' && !test) {
502
+ state.matched = false;
503
+ return false;
504
+ }
505
+ return true;
506
+ } };
507
+ return state;
508
+ };
149
509
  return (0, errors_1.value)(scalar('bool', (r, i, frame) => {
150
510
  if (!frame)
151
511
  throw new Error('Missing collection evaluation frame');
152
- let matched = operation === 'all';
153
- target.iterate(r, i, frame, item => {
154
- if (binding.slot !== undefined)
155
- frame.values[binding.slot] = item;
156
- const test = predicate.run(r, i, frame);
157
- if (operation === 'exists' && test) {
158
- matched = true;
159
- return false;
160
- }
161
- if (operation === 'all' && !test) {
162
- matched = false;
163
- return false;
164
- }
165
- return true;
166
- });
167
- return matched;
512
+ const state = visitorState(frame, visitorSlot, create);
513
+ state.record = r;
514
+ state.indices = i;
515
+ state.frame = frame;
516
+ state.matched = operation === 'all';
517
+ try {
518
+ target.iterate(r, i, frame, state.visit);
519
+ return state.matched;
520
+ }
521
+ finally {
522
+ state.record = undefined;
523
+ state.indices = undefined;
524
+ state.frame = undefined;
525
+ }
168
526
  }));
169
527
  }
170
- const iterate = (r, i, frame, visit) => target.iterate(r, i, frame, item => {
171
- if (binding.slot !== undefined)
172
- frame.values[binding.slot] = item;
173
- if (operation === 'filter') {
174
- const matches = body.run(r, i, frame);
175
- return !matches || visit(item);
528
+ const visitorSlot = this.nextVisitorSlot++;
529
+ const collectSlot = body.kind === 'collection' ? this.nextVisitorSlot++ : -1;
530
+ const create = () => {
531
+ const state = { record: undefined, indices: undefined, frame: undefined, next: undefined,
532
+ visit: item => {
533
+ const f = state.frame;
534
+ if (binding.slot !== undefined)
535
+ f.values[binding.slot] = item;
536
+ if (operation === 'filter') {
537
+ const matches = body.run(state.record, state.indices, f);
538
+ return !matches || state.next(item);
539
+ }
540
+ const mapped = body.kind === 'collection' ? collect(body, state.record, state.indices, f, collectSlot) :
541
+ body.run(state.record, state.indices, f);
542
+ return state.next(mapped);
543
+ } };
544
+ return state;
545
+ };
546
+ const iterate = (r, i, frame, visit) => {
547
+ const state = visitorState(frame, visitorSlot, create);
548
+ state.record = r;
549
+ state.indices = i;
550
+ state.frame = frame;
551
+ state.next = visit;
552
+ try {
553
+ return target.iterate(r, i, frame, state.visit);
554
+ }
555
+ finally {
556
+ state.record = undefined;
557
+ state.indices = undefined;
558
+ state.frame = undefined;
559
+ state.next = undefined;
176
560
  }
177
- const mapped = body.kind === 'collection' ? collect(body, r, i, frame) :
178
- body.run(r, i, frame);
179
- return visit(mapped);
180
- });
181
- return (0, errors_1.value)({ kind: 'collection',
182
- elementKind: operation === 'filter' ? target.elementKind :
183
- body.kind === 'collection' ? 'list' : body.kind,
561
+ };
562
+ const resultElement = operation === 'filter' ? target.type.element :
563
+ body.kind === 'collection' ? body.type : concrete(body) ? body.type :
564
+ { kind: 'object', fields: {} };
565
+ return (0, errors_1.value)({ kind: 'collection', type: { kind: 'array', element: resultElement },
184
566
  sourcePath: operation === 'filter' ? target.sourcePath : undefined,
185
567
  iterate });
186
568
  }
@@ -191,10 +573,10 @@ class CompilingInterpreter {
191
573
  continue;
192
574
  if (binding.sourcePath)
193
575
  return (0, errors_1.value)({ kind: 'object', root: 'source', path: binding.sourcePath });
194
- if (binding.slot === undefined || binding.kind === 'object' || binding.kind === 'list')
576
+ if (binding.slot === undefined || binding.type.kind !== 'scalar')
195
577
  return failed('Unsupported computed collection element');
196
- const slot = binding.slot, kind = binding.kind;
197
- return (0, errors_1.value)(scalar(kind, (_r, _i, frame) => {
578
+ const slot = binding.slot;
579
+ return (0, errors_1.value)(scalarWithType(binding.type, (_r, _i, frame) => {
198
580
  if (!frame)
199
581
  throw new Error('Missing collection evaluation frame');
200
582
  return frame.values[slot];
@@ -202,7 +584,7 @@ class CompilingInterpreter {
202
584
  }
203
585
  if (name === 'input')
204
586
  return (0, errors_1.value)({ kind: 'object', root: 'input', path: [] });
205
- if (name === 'current' || name === 'acc' || name === 'variables')
587
+ if (name === 'acc' || name === 'now' || name === 'prev' || name === 'variables')
206
588
  return (0, errors_1.value)({ kind: 'object', root: name, path: [] });
207
589
  return failed(`Unknown CEL identifier ${name}`);
208
590
  }
@@ -219,7 +601,31 @@ class CompilingInterpreter {
219
601
  return failed(message(e));
220
602
  }
221
603
  }
222
- return (0, errors_1.value)(scalar(kind, () => v));
604
+ const primitive = (this.fastNumbers && (kind === 'int' || kind === 'uint') && typeof v === 'bigint' &&
605
+ v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= BigInt(Number.MIN_SAFE_INTEGER)) ? Number(v) : v;
606
+ return (0, errors_1.value)(scalar(kind, () => primitive, typeof primitive === 'bigint' ? 'bigint' : typeof primitive === 'number' ? 'number' : kind === 'bool' ? 'boolean' : 'string'));
607
+ }
608
+ /** Rebind an indexed collection occurrence in an existing reusable frame. */
609
+ withSelection(selection, r, i, frame, run) {
610
+ if (frame === undefined)
611
+ throw new Error('Missing index evaluation frame');
612
+ const raw = selection.index.run(r, i, frame);
613
+ if (typeof raw !== 'number' && typeof raw !== 'bigint')
614
+ throw new RangeError('Array index is not an integer');
615
+ const index = Number(raw);
616
+ const length = selection.length(r, i, frame);
617
+ if (!Number.isSafeInteger(index) || index < 0 || index >= length)
618
+ throw new RangeError('CEL array index out of bounds: ' + String(raw));
619
+ const before = frame.activeLength, old = frame.indices[selection.depth];
620
+ setOccurrence(frame, selection.depth, index);
621
+ try {
622
+ return run(r, i, frame);
623
+ }
624
+ finally {
625
+ frame.activeLength = before;
626
+ if (selection.depth < before)
627
+ frame.indices[selection.depth] = old;
628
+ }
223
629
  }
224
630
  member(target, name) {
225
631
  if (target.kind !== 'object')
@@ -228,23 +634,109 @@ class CompilingInterpreter {
228
634
  const path = [...target.path, name];
229
635
  if (path.length !== 1)
230
636
  return failed(`Nested ${target.root} property ${path.join('.')} requires declared object types`);
231
- const kind = this.roots[target.root]?.[name];
637
+ const declaredType = this.rootValueTypes[target.root]?.[name];
638
+ if (declaredType?.kind === 'rolling-window') {
639
+ const element = declaredType.element;
640
+ if (!isCelRootScalar(element))
641
+ return failed(`CEL ${target.root}.${name}: Fixed-point arithmetic is not supported yet`);
642
+ const elementType = element;
643
+ const kind = elementKind(elementType);
644
+ const root = target.root;
645
+ const binding = this.rootReaders[root]?.(name, kind);
646
+ if (binding !== undefined && typeof binding !== 'function' &&
647
+ (!['now', 'prev'].includes(root) || !Number.isSafeInteger(binding.index) || binding.index < 0))
648
+ return failed(`Invalid indexed accumulator binding for ${root}.${name}`);
649
+ // Both accumulator layouts supply the same ring by reference.
650
+ // Select the reader once; no array projection or copy is required.
651
+ const read = typeof binding === 'function' ? binding :
652
+ binding !== undefined
653
+ ? record => record.acc.values[binding.index]
654
+ : record => record[root === 'now' || root === 'prev' ? 'acc' : root]?.[name];
655
+ const ring = (record) => {
656
+ const raw = read(record);
657
+ if (raw === null || typeof raw !== 'object' || !Array.isArray(raw.values))
658
+ throw new TypeError(`CEL ${root}.${name} expected rolling-window`);
659
+ const buffer = raw;
660
+ if (buffer.size !== declaredType.size || buffer.values.length !== declaredType.size + 1 ||
661
+ !Number.isSafeInteger(buffer.count) || buffer.count < 0 || buffer.count > buffer.size ||
662
+ !Number.isSafeInteger(buffer.excluded) || buffer.excluded < 0 || buffer.excluded > buffer.size ||
663
+ typeof buffer.hasExpired !== 'boolean' ||
664
+ (buffer.hasExpired && buffer.count !== buffer.size) ||
665
+ (!buffer.hasExpired && buffer.excluded !== 0))
666
+ throw new TypeError(`CEL ${root}.${name} has invalid rolling-window state`);
667
+ return buffer;
668
+ };
669
+ this.needsFrame = true;
670
+ const at = (record, _indices, _frame, index) => {
671
+ const item = (0, ring_buffer_1.get)(ring(record), index);
672
+ if (!ensureRepresentedValue(kind, element.javascriptType, item))
673
+ throw new TypeError(`CEL ${root}.${name} expected ${kind} element at index ${index}`);
674
+ return item;
675
+ };
676
+ const iterate = (record, _indices, frame, visit) => {
677
+ const buffer = ring(record);
678
+ const count = (0, ring_buffer_1.length)(buffer);
679
+ for (let n = 0; n < count; n++) {
680
+ const item = (0, ring_buffer_1.get)(buffer, n);
681
+ if (!ensureRepresentedValue(kind, element.javascriptType, item))
682
+ throw new TypeError(`CEL ${root}.${name} expected ${kind} element at index ${n}`);
683
+ if (!visit(item))
684
+ return false;
685
+ }
686
+ return true;
687
+ };
688
+ return (0, errors_1.value)({ kind: 'collection', type: { kind: 'array', element: elementType },
689
+ length: record => (0, ring_buffer_1.length)(ring(record)), at, iterate });
690
+ }
691
+ // Narrow the domain scalar once at the CEL boundary. Fixed-point
692
+ // descriptors cannot enter the CEL operation/representation algebra.
693
+ const celType = declaredType === undefined ? undefined :
694
+ isCelRootScalar(declaredType) ? declaredType : undefined;
695
+ if (declaredType !== undefined && celType === undefined)
696
+ return failed(`CEL ${target.root}.${name}: Fixed-point arithmetic is not supported yet`);
697
+ const kind = celType === undefined ? this.roots[target.root]?.[name] : elementKind(celType);
232
698
  if (kind === undefined)
233
699
  return failed(`Unknown CEL ${target.root} value ${name}`);
700
+ if (kind === 'object' || kind === 'list')
701
+ return failed(`CEL ${target.root}.${name} requires a scalar value type`);
702
+ // Resolve both kind and representation from the same canonical descriptor.
703
+ const representation = celType?.javascriptType ?? this.rootRepresentation(target.root, name, kind);
704
+ const binding = this.rootReaders[target.root]?.(name, kind);
705
+ if (binding !== undefined && typeof binding !== 'function') {
706
+ if (!['now', 'prev'].includes(target.root) || !Number.isSafeInteger(binding.index) || binding.index < 0)
707
+ return failed(`Invalid indexed accumulator binding for ${target.root}.${name}`);
708
+ const position = binding.index;
709
+ return (0, errors_1.value)(scalar(kind, (record) => {
710
+ const raw = record.acc.values[position];
711
+ if (!ensureRepresentedValue(kind, representation, raw))
712
+ throw new TypeError(`CEL ${target.root}.${name} expected ${kind}`);
713
+ return raw;
714
+ }, representation));
715
+ }
716
+ if (typeof binding === 'function') {
717
+ const read = binding;
718
+ return (0, errors_1.value)(scalar(kind, (record) => {
719
+ const raw = read(record);
720
+ if (!ensureRepresentedValue(kind, representation, raw))
721
+ throw new TypeError(`CEL ${target.root}.${name} expected ${kind}`);
722
+ return raw;
723
+ }, representation));
724
+ }
725
+ const root = target.root;
726
+ const storageRoot = root === 'now' || root === 'prev' ? 'acc' : root;
234
727
  return (0, errors_1.value)(scalar(kind, (record) => {
235
- const data = record;
236
- const raw = data[target.root]?.[name];
237
- if (!ensureValue(kind, raw))
238
- throw new TypeError(`CEL ${target.root}.${name} expected ${kind}`);
728
+ const raw = record[storageRoot]?.[name];
729
+ if (!ensureRepresentedValue(kind, representation, raw))
730
+ throw new TypeError(`CEL ${root}.${name} expected ${kind}`);
239
731
  return raw;
240
- }));
732
+ }, representation));
241
733
  }
242
734
  const path = [...target.path, name];
243
735
  const defined = resolveNode(this.projection, path);
244
736
  if (defined === undefined)
245
737
  return failed(`Unknown CEL projected field input.${path.join('.')}`);
246
738
  if (defined.type === 'object')
247
- return (0, errors_1.value)({ kind: 'object', root: 'input', path });
739
+ return (0, errors_1.value)({ kind: 'object', root: 'input', path, selection: target.selection });
248
740
  if (defined.type === 'array') {
249
741
  if (this.accesses.compileArray === undefined)
250
742
  return failed('Array accessor required to compile a collection');
@@ -254,26 +746,56 @@ class CompilingInterpreter {
254
746
  this.needsFrame = true;
255
747
  const dimension = arrayDepth(this.projection, path) - 1;
256
748
  const compiled = result.value;
257
- return (0, errors_1.value)({ kind: 'collection', elementKind: 'object', sourcePath: path,
258
- iterate: (record, indices, frame, visit) => {
259
- const count = compiled.length(record, windowAt(frame, dimension));
260
- const originalLength = frame.indices.length;
261
- const previous = frame.indices[dimension];
749
+ const plainLength = (record, _indices, frame) => compiled.length(record, windowAt(frame, dimension));
750
+ const length = target.selection === undefined ? plainLength :
751
+ (record, indices, frame) => this.withSelection(target.selection, record, indices, frame, plainLength);
752
+ const plainIterate = (record, indices, frame, visit) => {
753
+ const count = plainLength(record, indices, frame);
754
+ const originalLength = frame.activeLength;
755
+ const previous = frame.indices[dimension];
756
+ try {
757
+ for (let n = 0; n < count; n++) {
758
+ setOccurrence(frame, dimension, n);
759
+ if (!visit(undefined))
760
+ return false;
761
+ }
762
+ return true;
763
+ }
764
+ finally {
765
+ frame.activeLength = originalLength;
766
+ if (dimension < originalLength)
767
+ frame.indices[dimension] = previous;
768
+ }
769
+ };
770
+ // A physical array below an indexed joined child must retain that
771
+ // outer occurrence for the entire traversal, not just length().
772
+ const iterate = target.selection === undefined ? plainIterate :
773
+ (record, indices, frame, visit) => {
774
+ const selection = target.selection;
775
+ const raw = selection.index.run(record, indices, frame);
776
+ const index = Number(raw);
777
+ if ((typeof raw !== 'number' && typeof raw !== 'bigint') ||
778
+ !Number.isSafeInteger(index) || index < 0 ||
779
+ index >= selection.length(record, indices, frame))
780
+ throw new RangeError('CEL array index out of bounds: ' + String(raw));
781
+ const originalLength = frame.activeLength;
782
+ const previous = frame.indices[selection.depth];
783
+ setOccurrence(frame, selection.depth, index);
262
784
  try {
263
- for (let n = 0; n < count; n++) {
264
- setOccurrence(frame, dimension, n);
265
- if (!visit(undefined))
266
- return false;
267
- }
268
- return true;
785
+ return plainIterate(record, indices, frame, visit);
269
786
  }
270
787
  finally {
271
- frame.indices.length = originalLength;
272
- if (dimension < originalLength)
273
- setOccurrence(frame, dimension, previous);
788
+ frame.activeLength = originalLength;
789
+ if (selection.depth < originalLength)
790
+ frame.indices[selection.depth] = previous;
274
791
  }
275
- }
276
- });
792
+ };
793
+ const collectionType = projectionValueTypeAt(this.projectionTypes, path);
794
+ if (collectionType.kind !== 'array')
795
+ return failed('Expected an array value type for ' + path.join('.'));
796
+ if (!supportedCelValueType(collectionType))
797
+ return failed('Unsupported CEL collection element type at ' + path.join('.'));
798
+ return (0, errors_1.value)({ kind: 'collection', type: collectionType, sourcePath: path, length, iterate });
277
799
  }
278
800
  const access = this.accesses.compileScalar(path);
279
801
  if ((0, errors_1.isErrors)(access))
@@ -281,18 +803,61 @@ class CompilingInterpreter {
281
803
  const compiled = access.value;
282
804
  const kind = typeOf(defined.type);
283
805
  const dimension = arrayDepth(this.projection, path);
806
+ const plainRead = (record, indices, frame) => compiled.read(record, (frame ? windowAt(frame, dimension) : indices));
807
+ const reader = target.selection === undefined ? plainRead :
808
+ (record, indices, frame) => this.withSelection(target.selection, record, indices, frame, plainRead);
809
+ // Explicit field storage takes precedence over the preference for CEL literals.
810
+ // The preference must not turn a PIC-width-selected bigint into a number.
811
+ const integerStorage = compiled.integerStorage ?? (this.fastNumbers ? 'number' : 'bigint');
812
+ const representation = defined.type === 'integer'
813
+ ? integerStorage
814
+ : kind === 'double' ? 'number' : kind === 'bool' ? 'boolean' : 'string';
284
815
  return (0, errors_1.value)(scalar(kind, (record, indices, frame) => {
285
- const raw = compiled.read(record, (frame ?
286
- windowAt(frame, dimension) : indices));
287
- return defined.type === 'integer' ? readProjectionInteger(raw) : raw;
288
- }));
816
+ const raw = reader(record, indices, frame);
817
+ if (defined.type !== 'integer')
818
+ return raw;
819
+ if (integerStorage === 'number') {
820
+ if (typeof raw === 'bigint')
821
+ return safeNumberInteger(Number(raw));
822
+ return safeNumberInteger(raw);
823
+ }
824
+ return typeof raw === 'bigint' ? checkInt(raw, 'int') : readProjectionInteger(raw);
825
+ }, representation));
289
826
  }
290
- index(_target, _index) {
291
- return failed('Index expressions require the collection compilation phase');
827
+ index(target, index) {
828
+ if (target.kind === 'collection' && target.at !== undefined) {
829
+ if (!concrete(index) || index.kind !== 'int')
830
+ return failed('Array index must be int');
831
+ const element = scalarElement(target.type.element);
832
+ if (element === undefined)
833
+ return failed('Indexing requires a scalar collection element');
834
+ const at = target.at;
835
+ this.needsFrame = true;
836
+ return (0, errors_1.value)(scalarWithType(element, (r, i, frame) => {
837
+ if (!frame)
838
+ throw new Error('Missing collection evaluation frame');
839
+ const raw = index.run(r, i, frame);
840
+ const n = typeof raw === 'number' || typeof raw === 'bigint' ? Number(raw) : NaN;
841
+ if (!Number.isSafeInteger(n))
842
+ throw new RangeError('CEL array index out of bounds: ' + String(raw));
843
+ return at(r, i, frame, n);
844
+ }));
845
+ }
846
+ if (target.kind !== 'collection' || elementKind(target.type.element) !== 'object' || target.sourcePath === undefined)
847
+ return failed('Indexing requires a source-backed object collection');
848
+ if (!concrete(index) || index.kind !== 'int')
849
+ return failed('Array index must be int');
850
+ if (target.length === undefined)
851
+ return failed('Indexed collection has no length reader');
852
+ const path = target.sourcePath;
853
+ const depth = arrayDepth(this.projection, path) - 1;
854
+ this.needsFrame = true;
855
+ return (0, errors_1.value)({ kind: 'object', root: 'source', path,
856
+ selection: { depth, index, length: target.length } });
292
857
  }
293
858
  call(target, name, args) {
294
859
  if (target !== undefined)
295
- return failed(`Receiver-style function ${name} is not supported yet`);
860
+ return compileCollectionAggregate(target, name, args, this.fastNumbers, this.nextVisitorSlot++);
296
861
  const fn = this.functions[name];
297
862
  if (fn === undefined)
298
863
  return failed(`Unknown CEL function ${name}`);
@@ -323,10 +888,10 @@ class CompilingInterpreter {
323
888
  }
324
889
  return (0, errors_1.value)(scalar(fn.returns, (record, indices, frame) => {
325
890
  const result = invoke(record, indices, frame);
326
- if (!ensureValue(fn.returns, result))
891
+ if (!ensureValue(fn.returns, result, this.fastNumbers))
327
892
  throw new TypeError(`Function ${name} returned an invalid ${fn.returns}`);
328
893
  return result;
329
- }));
894
+ }, fn.returns === 'int' || fn.returns === 'uint' ? 'dynamic' : undefined));
330
895
  }
331
896
  unary(operator, operand) {
332
897
  if (!concrete(operand))
@@ -342,108 +907,79 @@ class CompilingInterpreter {
342
907
  const k = operand.kind;
343
908
  return (0, errors_1.value)(scalar(k, (r, i, frame) => {
344
909
  const v = operand.run(r, i, frame);
345
- return k === 'int' ? checkInt(-v, 'int') : -v;
346
- }));
910
+ return k === 'int' ? typeof v === 'number' ? safeNumberInteger(-v) : checkInt(-v, 'int') : -v;
911
+ }, operand.type.javascriptType));
347
912
  }
348
913
  return failed(`Unsupported unary ${operator} for ${operand.kind}`);
349
914
  }
350
915
  binary(operator, left, right) {
351
916
  if (!concrete(left) || !concrete(right))
352
917
  return failed(`Binary ${operator} requires scalar operands`);
353
- if (operator === '&&' || operator === '||') {
354
- if (left.kind !== 'bool' || right.kind !== 'bool')
355
- return failed(`${operator} requires bool operands`);
356
- return (0, errors_1.value)(scalar('bool', (r, i, frame) => {
357
- const a = left.run(r, i, frame);
358
- return operator === '&&' ? (a && right.run(r, i, frame)) : (a || right.run(r, i, frame));
359
- }));
360
- }
918
+ if ((operator === '&&' || operator === '||') && (left.kind !== 'bool' || right.kind !== 'bool'))
919
+ return failed(`${operator} requires bool operands`);
361
920
  if (left.kind !== right.kind)
362
921
  return failed(`Operator ${operator} requires matching types; got ${left.kind} and ${right.kind}`);
363
- const k = left.kind;
364
- if (operator === '==' || operator === '!=') {
365
- return (0, errors_1.value)(scalar('bool', (r, i, frame) => {
366
- const equal = left.run(r, i, frame) === right.run(r, i, frame);
367
- return operator === '==' ? equal : !equal;
368
- }));
369
- }
370
- if (operator === '<' || operator === '>' || operator === '<=' || operator === '>=') {
371
- if (!['int', 'uint', 'double', 'string'].includes(k))
372
- return failed(`Operator ${operator} not supported for ${k}`);
373
- return (0, errors_1.value)(scalar('bool', (r, i, frame) => {
374
- const a = left.run(r, i, frame);
375
- const b = right.run(r, i, frame);
376
- switch (operator) {
377
- case '<': return a < b;
378
- case '<=': return a <= b;
379
- case '>': return a > b;
380
- default: return a >= b;
381
- }
382
- }));
383
- }
384
- if (operator === '+' && k === 'string') {
385
- return (0, errors_1.value)(scalar('string', (r, i, frame) => left.run(r, i, frame) + right.run(r, i, frame)));
386
- }
387
- if (!['int', 'uint', 'double'].includes(k) || !['+', '-', '*', '/', '%'].includes(operator))
388
- return failed(`Operator ${operator} not supported for ${k}`);
389
- return (0, errors_1.value)(scalar(k, (r, i, frame) => {
390
- const a = left.run(r, i, frame);
391
- const b = right.run(r, i, frame);
392
- if (k === 'double') {
393
- const x = a, y = b;
394
- switch (operator) {
395
- case '+': return x + y;
396
- case '-': return x - y;
397
- case '*': return x * y;
398
- case '/': return x / y;
399
- default: return x % y;
400
- }
401
- }
402
- const x = a, y = b;
403
- if ((operator === '/' || operator === '%') && y === 0n)
404
- throw new RangeError('Integer division by zero');
405
- let result;
406
- switch (operator) {
407
- case '+':
408
- result = x + y;
409
- break;
410
- case '-':
411
- result = x - y;
412
- break;
413
- case '*':
414
- result = x * y;
415
- break;
416
- case '/':
417
- result = x / y;
418
- break;
419
- default: result = x % y;
420
- }
421
- return checkInt(result, k);
422
- }));
922
+ const registry = this.operations[operator];
923
+ if (registry === undefined)
924
+ return failed(`Operator ${operator} not supported for ${left.kind}`);
925
+ const operation = registry.resolve({ kind: left.kind, representation: left.type.javascriptType }, { kind: right.kind, representation: right.type.javascriptType });
926
+ if (operation === undefined)
927
+ return failed(`Operator ${operator} not supported for ${left.kind}/${left.type.javascriptType} and ${right.kind}/${right.type.javascriptType}`);
928
+ return (0, errors_1.value)(scalar(operation.result.kind, operation.compile(left.run, right.run), operation.result.representation));
423
929
  }
424
930
  conditional(condition, whenTrue, whenFalse) {
425
- if (condition.kind !== 'bool')
931
+ if (!concrete(condition) || condition.kind !== 'bool')
426
932
  return failed(`Conditional requires bool, got ${condition.kind}`);
427
933
  if (!concrete(whenTrue) || !concrete(whenFalse))
428
934
  return failed('Conditional branches must be scalar');
429
935
  if (whenTrue.kind !== whenFalse.kind)
430
936
  return failed(`Conditional branches differ: ${whenTrue.kind} and ${whenFalse.kind}`);
431
- return (0, errors_1.value)(scalar(whenTrue.kind, (r, i, frame) => condition.run(r, i, frame) ? whenTrue.run(r, i, frame) : whenFalse.run(r, i, frame)));
937
+ const operation = this.conditionals.resolve({ kind: whenTrue.kind, representation: whenTrue.type.javascriptType }, { kind: whenFalse.kind, representation: whenFalse.type.javascriptType });
938
+ if (operation === undefined)
939
+ return failed(`Conditional branches unsupported: ${whenTrue.kind} and ${whenFalse.kind}`);
940
+ return (0, errors_1.value)(scalar(operation.result.kind, operation.compile(condition.run, whenTrue.run, whenFalse.run), operation.result.representation));
432
941
  }
433
942
  list(_elements) { return failed('List literals require the collection compilation phase'); }
434
943
  map(_entries) {
435
944
  return failed('Map literals require the collection compilation phase');
436
945
  }
437
946
  }
438
- function compileCelExpression(expression, projection, access, functions = {}, roots = {}) {
439
- const compiler = new CompilingInterpreter(projection, access, functions, roots);
947
+ function compileCelExpression(expression, projection, access, functions = {}, roots = {}, readers = {}, operations = cel_operations_1.defaultBinaryOperations, representations = {}, conditionals = cel_operations_1.defaultConditionalOperations, rootValueTypes = {}) {
948
+ const compiler = new CompilingInterpreter(projection, access, functions, roots, readers, operations, representations, conditionals, rootValueTypes);
440
949
  const result = (0, cel_1.parseCel)(expression, compiler);
441
950
  if ((0, errors_1.isErrors)(result))
442
951
  return result;
443
952
  const node = result.value;
444
953
  if (!concrete(node))
445
954
  return failed('CEL expression returns a collection or object; scalar expected');
446
- return (0, errors_1.value)({ type: node.kind, run: (record, indices) => node.run(record, indices, compiler.needsFrame ? { indices: [...indices], windows: [], values: [] } : undefined) });
955
+ const createRunner = () => {
956
+ if (!compiler.needsFrame)
957
+ return (record, indices) => node.run(record, indices);
958
+ const frame = createFrame();
959
+ return (record, indices) => {
960
+ bindFrame(frame, indices);
961
+ try {
962
+ return node.run(record, indices, frame);
963
+ }
964
+ finally {
965
+ clearFrameValues(frame);
966
+ }
967
+ };
968
+ };
969
+ // Standalone run() has invocation-local state; a pooled graph result creates its own runner.
970
+ const run = (record, indices) => {
971
+ if (!compiler.needsFrame)
972
+ return node.run(record, indices);
973
+ const frame = createFrame();
974
+ bindFrame(frame, indices);
975
+ try {
976
+ return node.run(record, indices, frame);
977
+ }
978
+ finally {
979
+ clearFrameValues(frame);
980
+ }
981
+ };
982
+ return (0, errors_1.value)({ type: node.kind, valueType: node.type, representation: node.type.javascriptType, acceptNumberIntegers: compiler.preferNumberIntegers, run, createRunner });
447
983
  }
448
984
  /** Error policy is applied once, at the evaluator boundary. */
449
985
  function evaluateCompiled(expression, record, indices, policy = { mode: 'throw' }) {
@@ -458,7 +994,7 @@ function evaluateCompiled(expression, record, indices, policy = { mode: 'throw'
458
994
  if (policy.fallback === undefined)
459
995
  return { errors: [prefix] };
460
996
  const recovered = policy.fallback(err, expression.type);
461
- if (!ensureValue(expression.type, recovered))
997
+ if (!ensureRepresentedValue(expression.type, expression.valueType.javascriptType, recovered))
462
998
  return { errors: [prefix, `Fallback must have type ${expression.type}`] };
463
999
  return { value: recovered, errors: [prefix] };
464
1000
  }
@@ -468,8 +1004,8 @@ function evaluateCompiled(expression, record, indices, policy = { mode: 'throw'
468
1004
  * returned. A terminal source-object filter must materialise its selected
469
1005
  * elements; map/filter chains over those elements do not.
470
1006
  */
471
- function compileCelCollectionExpression(expression, projection, access, functions = {}, roots = {}) {
472
- const compiler = new CompilingInterpreter(projection, access, functions, roots);
1007
+ function compileCelCollectionExpression(expression, projection, access, functions = {}, roots = {}, readers = {}, rootValueTypes = {}) {
1008
+ const compiler = new CompilingInterpreter(projection, access, functions, roots, readers, cel_operations_1.defaultBinaryOperations, {}, cel_operations_1.defaultConditionalOperations, rootValueTypes);
473
1009
  const parsed = (0, cel_1.parseCel)(expression, compiler);
474
1010
  if ((0, errors_1.isErrors)(parsed))
475
1011
  return parsed;
@@ -477,7 +1013,7 @@ function compileCelCollectionExpression(expression, projection, access, function
477
1013
  if (node.kind !== 'collection')
478
1014
  return failed('CEL expression is not a collection');
479
1015
  let render;
480
- if (node.elementKind === 'object') {
1016
+ if (elementKind(node.type.element) === 'object') {
481
1017
  const path = node.sourcePath;
482
1018
  if (!path)
483
1019
  return failed('Cannot materialise a computed object collection');
@@ -493,9 +1029,9 @@ function compileCelCollectionExpression(expression, projection, access, function
493
1029
  return resolved;
494
1030
  const reader = resolved.value;
495
1031
  const depth = arrayDepth(projection, [...path, name]);
496
- readers.push([name, (r, i, frame) => {
1032
+ readers.push([name, (r, _i, frame) => {
497
1033
  const raw = reader.read(r, windowAt(frame, depth));
498
- return field.type === 'integer' ? readProjectionInteger(raw) : raw;
1034
+ return field.type === 'integer' ? readProjectionInteger(raw, reader.integerStorage === 'number') : raw;
499
1035
  }]);
500
1036
  }
501
1037
  render = (r, i, frame) => {
@@ -505,17 +1041,42 @@ function compileCelCollectionExpression(expression, projection, access, function
505
1041
  return object;
506
1042
  };
507
1043
  }
508
- return (0, errors_1.value)({
509
- type: 'list', elementType: node.elementKind,
510
- run: (r, i) => {
511
- const frame = { indices: [...i], windows: [], values: [] };
512
- const result = [];
513
- node.iterate(r, i, frame, item => {
514
- result.push(item === undefined ? render(r, i, frame) : item);
1044
+ const visitorSlot = compiler.allocateVisitorSlot();
1045
+ const create = () => {
1046
+ const state = { record: undefined, indices: undefined, frame: undefined, result: undefined, visit: item => {
1047
+ state.result.push(item === undefined ? render(state.record, state.indices, state.frame) : item);
515
1048
  return true;
516
- });
1049
+ } };
1050
+ return state;
1051
+ };
1052
+ const evaluate = (frame, r, i) => {
1053
+ bindFrame(frame, i);
1054
+ // Materialised values have independent storage; only traversal scratch is reused.
1055
+ const result = [];
1056
+ const state = visitorState(frame, visitorSlot, create);
1057
+ state.record = r;
1058
+ state.indices = i;
1059
+ state.frame = frame;
1060
+ state.result = result;
1061
+ try {
1062
+ node.iterate(r, i, frame, state.visit);
517
1063
  return result;
518
1064
  }
1065
+ finally {
1066
+ state.record = undefined;
1067
+ state.indices = undefined;
1068
+ state.frame = undefined;
1069
+ state.result = undefined;
1070
+ clearFrameValues(frame);
1071
+ }
1072
+ };
1073
+ return (0, errors_1.value)({
1074
+ type: 'list', valueType: node.type, elementType: elementKind(node.type.element),
1075
+ run: (r, i) => evaluate(createFrame(), r, i),
1076
+ createRunner: () => {
1077
+ const frame = createFrame();
1078
+ return (r, i) => evaluate(frame, r, i);
1079
+ }
519
1080
  });
520
1081
  }
521
1082
  //# sourceMappingURL=cel.compile.js.map