@cobol-ts/cel-implementation 0.0.30 → 0.0.32

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 (105) hide show
  1. package/README.md +76 -5
  2. package/dist/src/cel.access.d.ts +12 -0
  3. package/dist/src/cel.access.js +281 -0
  4. package/dist/src/cel.access.js.map +1 -0
  5. package/dist/src/cel.access.spec.d.ts +1 -0
  6. package/dist/src/cel.access.spec.js +30 -0
  7. package/dist/src/cel.access.spec.js.map +1 -0
  8. package/dist/src/cel.collection.d.ts +12 -0
  9. package/dist/src/cel.collection.index.d.ts +8 -0
  10. package/dist/src/cel.collection.index.js +59 -0
  11. package/dist/src/cel.collection.index.js.map +1 -0
  12. package/dist/src/cel.collection.index.spec.d.ts +1 -0
  13. package/dist/src/cel.collection.index.spec.js +47 -0
  14. package/dist/src/cel.collection.index.spec.js.map +1 -0
  15. package/dist/src/cel.collection.js +273 -0
  16. package/dist/src/cel.collection.js.map +1 -0
  17. package/dist/src/cel.collection.spec.d.ts +1 -0
  18. package/dist/src/cel.collection.spec.js +78 -0
  19. package/dist/src/cel.collection.spec.js.map +1 -0
  20. package/dist/src/cel.compile.d.ts +5 -16
  21. package/dist/src/cel.compile.diagnostics.spec.d.ts +1 -0
  22. package/dist/src/cel.compile.diagnostics.spec.js +60 -0
  23. package/dist/src/cel.compile.diagnostics.spec.js.map +1 -0
  24. package/dist/src/cel.compile.js +17 -1056
  25. package/dist/src/cel.compile.js.map +1 -1
  26. package/dist/src/cel.compile.spec.js +1 -35
  27. package/dist/src/cel.compile.spec.js.map +1 -1
  28. package/dist/src/cel.compile.types.d.ts +64 -0
  29. package/dist/src/cel.compile.types.js +3 -0
  30. package/dist/src/cel.compile.types.js.map +1 -0
  31. package/dist/src/cel.evaluate.d.ts +3 -0
  32. package/dist/src/cel.evaluate.js +23 -0
  33. package/dist/src/cel.evaluate.js.map +1 -0
  34. package/dist/src/cel.evaluate.spec.d.ts +1 -0
  35. package/dist/src/cel.evaluate.spec.js +52 -0
  36. package/dist/src/cel.evaluate.spec.js.map +1 -0
  37. package/dist/src/cel.frame.d.ts +18 -0
  38. package/dist/src/cel.frame.js +48 -0
  39. package/dist/src/cel.frame.js.map +1 -0
  40. package/dist/src/cel.frame.spec.d.ts +1 -0
  41. package/dist/src/cel.frame.spec.js +53 -0
  42. package/dist/src/cel.frame.spec.js.map +1 -0
  43. package/dist/src/cel.interpreter.d.ts +15 -0
  44. package/dist/src/cel.interpreter.js +82 -0
  45. package/dist/src/cel.interpreter.js.map +1 -0
  46. package/dist/src/cel.interpreter.spec.d.ts +1 -0
  47. package/dist/src/cel.interpreter.spec.js +26 -0
  48. package/dist/src/cel.interpreter.spec.js.map +1 -0
  49. package/dist/src/cel.literal.types.d.ts +26 -0
  50. package/dist/src/cel.literal.types.js +80 -0
  51. package/dist/src/cel.literal.types.js.map +1 -0
  52. package/dist/src/cel.literal.types.spec.d.ts +1 -0
  53. package/dist/src/cel.literal.types.spec.js +41 -0
  54. package/dist/src/cel.literal.types.spec.js.map +1 -0
  55. package/dist/src/cel.literals.d.ts +6 -0
  56. package/dist/src/cel.literals.js +284 -0
  57. package/dist/src/cel.literals.js.map +1 -0
  58. package/dist/src/cel.literals.spec.d.ts +1 -0
  59. package/dist/src/cel.literals.spec.js +289 -0
  60. package/dist/src/cel.literals.spec.js.map +1 -0
  61. package/dist/src/cel.materialise.d.ts +9 -0
  62. package/dist/src/cel.materialise.js +44 -0
  63. package/dist/src/cel.materialise.js.map +1 -0
  64. package/dist/src/cel.materialise.spec.d.ts +1 -0
  65. package/dist/src/cel.materialise.spec.js +21 -0
  66. package/dist/src/cel.materialise.spec.js.map +1 -0
  67. package/dist/src/cel.node.d.ts +18 -0
  68. package/dist/src/cel.node.js +64 -0
  69. package/dist/src/cel.node.js.map +1 -0
  70. package/dist/src/cel.numeric.d.ts +12 -0
  71. package/dist/src/cel.numeric.js +86 -0
  72. package/dist/src/cel.numeric.js.map +1 -0
  73. package/dist/src/cel.numeric.spec.d.ts +1 -0
  74. package/dist/src/cel.numeric.spec.js +37 -0
  75. package/dist/src/cel.numeric.spec.js.map +1 -0
  76. package/dist/src/cel.operations.js +9 -19
  77. package/dist/src/cel.operations.js.map +1 -1
  78. package/dist/src/cel.projection.d.ts +5 -0
  79. package/dist/src/cel.projection.js +56 -0
  80. package/dist/src/cel.projection.js.map +1 -0
  81. package/dist/src/cel.projection.spec.d.ts +1 -0
  82. package/dist/src/cel.projection.spec.js +37 -0
  83. package/dist/src/cel.projection.spec.js.map +1 -0
  84. package/dist/src/cel.root.types.d.ts +14 -0
  85. package/dist/src/cel.root.types.js +3 -0
  86. package/dist/src/cel.root.types.js.map +1 -0
  87. package/dist/src/cel.runner.d.ts +7 -0
  88. package/dist/src/cel.runner.js +77 -0
  89. package/dist/src/cel.runner.js.map +1 -0
  90. package/dist/src/cel.runner.spec.d.ts +1 -0
  91. package/dist/src/cel.runner.spec.js +56 -0
  92. package/dist/src/cel.runner.spec.js.map +1 -0
  93. package/dist/src/cel.scalar.d.ts +10 -0
  94. package/dist/src/cel.scalar.js +120 -0
  95. package/dist/src/cel.scalar.js.map +1 -0
  96. package/dist/src/cel.scalar.spec.d.ts +1 -0
  97. package/dist/src/cel.scalar.spec.js +25 -0
  98. package/dist/src/cel.scalar.spec.js.map +1 -0
  99. package/dist/src/cel.scope.d.ts +14 -0
  100. package/dist/src/cel.scope.js +88 -0
  101. package/dist/src/cel.scope.js.map +1 -0
  102. package/dist/src/cel.scope.spec.d.ts +1 -0
  103. package/dist/src/cel.scope.spec.js +47 -0
  104. package/dist/src/cel.scope.spec.js.map +1 -0
  105. package/package.json +9 -9
@@ -1,1003 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.evaluateCompiled = void 0;
3
4
  exports.compileCelExpression = compileCelExpression;
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");
8
6
  const errors_1 = require("@cobol-ts/errors");
9
7
  const cel_1 = require("@cobol-ts/cel");
10
8
  const cel_operations_1 = require("./cel.operations");
11
- const INT_MIN = -(1n << 63n);
12
- const INT_MAX = (1n << 63n) - 1n;
13
- const UINT_MAX = (1n << 64n) - 1n;
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. */
35
- function windowAt(frame, depth) {
36
- let window = frame.windows[depth];
37
- if (window === undefined) {
38
- window = [];
39
- frame.windows[depth] = window;
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();
46
- return window;
47
- }
48
- function setOccurrence(frame, depth, index) {
49
- frame.indices[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;
108
- }
109
- const failed = (message) => (0, errors_1.errors)(message);
110
- const message = (error) => error instanceof Error ? error.message : String(error);
111
- const typeOf = (t) => t === 'integer' ? 'int' : t === 'float' ? 'double' : 'string';
112
- function checkInt(n, kind) {
113
- if (kind === 'int' ? (n < INT_MIN || n > INT_MAX) : (n < 0n || n > UINT_MAX))
114
- throw new RangeError(`${kind} overflow: ${n}`);
115
- return n;
116
- }
117
- function ensureValue(kind, v, allowNumber = false) {
118
- if (kind === 'null')
119
- return v === null;
120
- if (kind === 'int' || kind === 'uint')
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);
125
- return typeof v === (kind === 'double' ? 'number' : kind === 'bool' ? 'boolean' : 'string');
126
- }
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;
142
- if (!Number.isSafeInteger(n))
143
- throw new RangeError(`Projection integer is not a safe integer: ${n}`);
144
- return checkInt(BigInt(n), 'int');
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
- }
186
- function resolveNode(definition, path) {
187
- let fields = definition;
188
- let node;
189
- for (let i = 0; i < path.length; i++) {
190
- node = fields[path[i]];
191
- if (node === undefined)
192
- return undefined;
193
- if (i + 1 < path.length) {
194
- if (node.type === 'object')
195
- fields = node.fields;
196
- else if (node.type === 'array')
197
- fields = node.element;
198
- else
199
- return undefined;
200
- }
201
- }
202
- return node;
203
- }
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 };
209
- }
210
- function concrete(node) {
211
- return node.kind !== 'object' && node.kind !== 'collection';
212
- }
213
- function arrayDepth(projection, path) {
214
- let fields = projection, depth = 0;
215
- for (const part of path) {
216
- const node = fields[part];
217
- if (!node)
218
- throw new Error('Unknown collection path ' + path.join('.'));
219
- if (node.type === 'array') {
220
- depth++;
221
- fields = node.element;
222
- }
223
- else if (node.type === 'object')
224
- fields = node.fields;
225
- }
226
- return depth;
227
- }
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.
239
- const 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
- }));
333
- }
334
- /** Builds executable closures through the existing tagless CEL parser. */
335
- class CompilingInterpreter {
336
- projection;
337
- accesses;
338
- functions;
339
- 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 = {}) {
346
- this.projection = projection;
347
- this.accesses = accesses;
348
- this.functions = functions;
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);
357
- }
358
- projectionTypes;
359
- preferNumberIntegers;
360
- get fastNumbers() { return this.preferNumberIntegers; }
361
- scopes = [];
362
- nextSlot = 0;
363
- nextVisitorSlot = 0;
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
- }
371
- isScopedCall(name) {
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
- }));
451
- }
452
- enterScope(target, _operation, name) {
453
- if (target.kind !== 'collection')
454
- return failed('Collection operation requires an array receiver');
455
- if (elementKind(target.type.element) === 'object') {
456
- if (!target.sourcePath)
457
- return failed('Collection object has no projection path');
458
- this.scopes.push({ name, type: target.type.element, sourcePath: target.sourcePath });
459
- }
460
- else {
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++ });
464
- }
465
- this.needsFrame = true;
466
- return (0, errors_1.value)(undefined);
467
- }
468
- leaveScope() { this.scopes.pop(); }
469
- scopedCall(target, operation, _variable, body) {
470
- if (target.kind !== 'collection')
471
- return failed('Collection operation requires an array receiver');
472
- const binding = this.scopes[this.scopes.length - 1];
473
- if (binding === undefined)
474
- return failed('Missing collection lexical binding');
475
- if (operation === 'filter' || operation === 'exists' || operation === 'all') {
476
- if (!concrete(body) || body.kind !== 'bool')
477
- return failed(`${operation} requires a Boolean predicate`);
478
- }
479
- else if (operation === 'map') {
480
- if (body.kind === 'object')
481
- return failed('map body must return a value');
482
- if (body.kind === 'collection' && body.sourcePath)
483
- return failed('map cannot directly return source-backed objects; select fields using map');
484
- }
485
- else
486
- return failed('Unknown collection operation ' + operation);
487
- if (operation === 'exists' || operation === 'all') {
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
- };
509
- return (0, errors_1.value)(scalar('bool', (r, i, frame) => {
510
- if (!frame)
511
- throw new Error('Missing collection evaluation frame');
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
- }
526
- }));
527
- }
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;
560
- }
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 },
566
- sourcePath: operation === 'filter' ? target.sourcePath : undefined,
567
- iterate });
568
- }
569
- identifier(name) {
570
- for (let n = this.scopes.length - 1; n >= 0; n--) {
571
- const binding = this.scopes[n];
572
- if (binding.name !== name)
573
- continue;
574
- if (binding.sourcePath)
575
- return (0, errors_1.value)({ kind: 'object', root: 'source', path: binding.sourcePath });
576
- if (binding.slot === undefined || binding.type.kind !== 'scalar')
577
- return failed('Unsupported computed collection element');
578
- const slot = binding.slot;
579
- return (0, errors_1.value)(scalarWithType(binding.type, (_r, _i, frame) => {
580
- if (!frame)
581
- throw new Error('Missing collection evaluation frame');
582
- return frame.values[slot];
583
- }));
584
- }
585
- if (name === 'input')
586
- return (0, errors_1.value)({ kind: 'object', root: 'input', path: [] });
587
- if (name === 'acc' || name === 'now' || name === 'prev' || name === 'variables')
588
- return (0, errors_1.value)({ kind: 'object', root: name, path: [] });
589
- return failed(`Unknown CEL identifier ${name}`);
590
- }
591
- literal(literal) {
592
- if (literal.type === 'null')
593
- return (0, errors_1.value)(scalar('null', () => null));
594
- const kind = literal.type === 'bool' ? 'bool' : literal.type;
595
- const v = literal.value;
596
- if ((kind === 'int' || kind === 'uint') && typeof v === 'bigint') {
597
- try {
598
- checkInt(v, kind);
599
- }
600
- catch (e) {
601
- return failed(message(e));
602
- }
603
- }
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
- }
629
- }
630
- member(target, name) {
631
- if (target.kind !== 'object')
632
- return failed(`Cannot select ${name} from ${target.kind}`);
633
- if (target.root !== 'input' && target.root !== 'source') {
634
- const path = [...target.path, name];
635
- if (path.length !== 1)
636
- return failed(`Nested ${target.root} property ${path.join('.')} requires declared object types`);
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);
698
- if (kind === undefined)
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;
727
- return (0, errors_1.value)(scalar(kind, (record) => {
728
- const raw = record[storageRoot]?.[name];
729
- if (!ensureRepresentedValue(kind, representation, raw))
730
- throw new TypeError(`CEL ${root}.${name} expected ${kind}`);
731
- return raw;
732
- }, representation));
733
- }
734
- const path = [...target.path, name];
735
- const defined = resolveNode(this.projection, path);
736
- if (defined === undefined)
737
- return failed(`Unknown CEL projected field input.${path.join('.')}`);
738
- if (defined.type === 'object')
739
- return (0, errors_1.value)({ kind: 'object', root: 'input', path, selection: target.selection });
740
- if (defined.type === 'array') {
741
- if (this.accesses.compileArray === undefined)
742
- return failed('Array accessor required to compile a collection');
743
- const result = this.accesses.compileArray(path);
744
- if ((0, errors_1.isErrors)(result))
745
- return result;
746
- this.needsFrame = true;
747
- const dimension = arrayDepth(this.projection, path) - 1;
748
- const compiled = result.value;
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);
784
- try {
785
- return plainIterate(record, indices, frame, visit);
786
- }
787
- finally {
788
- frame.activeLength = originalLength;
789
- if (selection.depth < originalLength)
790
- frame.indices[selection.depth] = previous;
791
- }
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 });
799
- }
800
- const access = this.accesses.compileScalar(path);
801
- if ((0, errors_1.isErrors)(access))
802
- return access;
803
- const compiled = access.value;
804
- const kind = typeOf(defined.type);
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';
815
- return (0, errors_1.value)(scalar(kind, (record, indices, frame) => {
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));
826
- }
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 } });
857
- }
858
- call(target, name, args) {
859
- if (target !== undefined)
860
- return compileCollectionAggregate(target, name, args, this.fastNumbers, this.nextVisitorSlot++);
861
- const fn = this.functions[name];
862
- if (fn === undefined)
863
- return failed(`Unknown CEL function ${name}`);
864
- if (fn.args.length !== args.length)
865
- return failed(`Function ${name} expects ${fn.args.length} arguments, got ${args.length}`);
866
- for (let i = 0; i < args.length; i++) {
867
- if (args[i].kind !== fn.args[i])
868
- return failed(`Function ${name} argument ${i + 1}: expected ${fn.args[i]}, got ${args[i].kind}`);
869
- }
870
- const all = args;
871
- // Close over compiled operands once. Avoid allocating a values array for
872
- // the common 0–3 argument functions on every record.
873
- let invoke;
874
- switch (all.length) {
875
- case 0:
876
- invoke = () => fn.invoke();
877
- break;
878
- case 1:
879
- invoke = (r, i, frame) => fn.invoke(all[0].run(r, i, frame));
880
- break;
881
- case 2:
882
- invoke = (r, i, frame) => fn.invoke(all[0].run(r, i, frame), all[1].run(r, i, frame));
883
- break;
884
- case 3:
885
- invoke = (r, i, frame) => fn.invoke(all[0].run(r, i, frame), all[1].run(r, i, frame), all[2].run(r, i, frame));
886
- break;
887
- default: invoke = (r, i, frame) => fn.invoke(...all.map(a => a.run(r, i, frame)));
888
- }
889
- return (0, errors_1.value)(scalar(fn.returns, (record, indices, frame) => {
890
- const result = invoke(record, indices, frame);
891
- if (!ensureValue(fn.returns, result, this.fastNumbers))
892
- throw new TypeError(`Function ${name} returned an invalid ${fn.returns}`);
893
- return result;
894
- }, fn.returns === 'int' || fn.returns === 'uint' ? 'dynamic' : undefined));
895
- }
896
- unary(operator, operand) {
897
- if (!concrete(operand))
898
- return failed(`Unary ${operator} requires a scalar`);
899
- if (operator === '!') {
900
- if (operand.kind !== 'bool')
901
- return failed(`Unary ! requires bool, got ${operand.kind}`);
902
- return (0, errors_1.value)(scalar('bool', (r, i, frame) => !operand.run(r, i, frame)));
903
- }
904
- if (operator === '+' && (operand.kind === 'int' || operand.kind === 'uint' || operand.kind === 'double'))
905
- return (0, errors_1.value)(operand);
906
- if (operator === '-' && (operand.kind === 'int' || operand.kind === 'double')) {
907
- const k = operand.kind;
908
- return (0, errors_1.value)(scalar(k, (r, i, frame) => {
909
- const v = operand.run(r, i, frame);
910
- return k === 'int' ? typeof v === 'number' ? safeNumberInteger(-v) : checkInt(-v, 'int') : -v;
911
- }, operand.type.javascriptType));
912
- }
913
- return failed(`Unsupported unary ${operator} for ${operand.kind}`);
914
- }
915
- binary(operator, left, right) {
916
- if (!concrete(left) || !concrete(right))
917
- return failed(`Binary ${operator} requires scalar operands`);
918
- if ((operator === '&&' || operator === '||') && (left.kind !== 'bool' || right.kind !== 'bool'))
919
- return failed(`${operator} requires bool operands`);
920
- if (left.kind !== right.kind)
921
- return failed(`Operator ${operator} requires matching types; got ${left.kind} and ${right.kind}`);
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));
929
- }
930
- conditional(condition, whenTrue, whenFalse) {
931
- if (!concrete(condition) || condition.kind !== 'bool')
932
- return failed(`Conditional requires bool, got ${condition.kind}`);
933
- if (!concrete(whenTrue) || !concrete(whenFalse))
934
- return failed('Conditional branches must be scalar');
935
- if (whenTrue.kind !== whenFalse.kind)
936
- return failed(`Conditional branches differ: ${whenTrue.kind} and ${whenFalse.kind}`);
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));
941
- }
942
- list(_elements) { return failed('List literals require the collection compilation phase'); }
943
- map(_entries) {
944
- return failed('Map literals require the collection compilation phase');
945
- }
946
- }
9
+ const cel_node_1 = require("./cel.node");
10
+ const cel_interpreter_1 = require("./cel.interpreter");
11
+ const cel_runner_1 = require("./cel.runner");
12
+ const cel_materialise_1 = require("./cel.materialise");
13
+ var cel_evaluate_1 = require("./cel.evaluate");
14
+ Object.defineProperty(exports, "evaluateCompiled", { enumerable: true, get: function () { return cel_evaluate_1.evaluateCompiled; } });
947
15
  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);
16
+ const compiler = (0, cel_interpreter_1.createCompilingInterpreter)(projection, access, functions, roots, readers, operations, representations, conditionals, rootValueTypes);
949
17
  const result = (0, cel_1.parseCel)(expression, compiler);
950
18
  if ((0, errors_1.isErrors)(result))
951
19
  return result;
952
20
  const node = result.value;
953
- if (!concrete(node))
954
- return failed('CEL expression returns a collection or object; scalar expected');
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 });
983
- }
984
- /** Error policy is applied once, at the evaluator boundary. */
985
- function evaluateCompiled(expression, record, indices, policy = { mode: 'throw' }) {
986
- if (policy.mode === 'throw')
987
- return { value: expression.run(record, indices), errors: [] };
988
- try {
989
- return { value: expression.run(record, indices), errors: [] };
990
- }
991
- catch (e) {
992
- const err = e instanceof Error ? e : new Error(String(e));
993
- const prefix = `CEL ${expression.type} evaluation: ${err.message}`;
994
- if (policy.fallback === undefined)
995
- return { errors: [prefix] };
996
- const recovered = policy.fallback(err, expression.type);
997
- if (!ensureRepresentedValue(expression.type, expression.valueType.javascriptType, recovered))
998
- return { errors: [prefix, `Fallback must have type ${expression.type}`] };
999
- return { value: recovered, errors: [prefix] };
1000
- }
21
+ if (!(0, cel_node_1.concrete)(node))
22
+ return (0, errors_1.errors)('CEL expression returns a collection or object; scalar expected');
23
+ return (0, errors_1.value)((0, cel_runner_1.createScalarExpression)(node, compiler.needsFrame, compiler.preferNumberIntegers));
1001
24
  }
1002
25
  /**
1003
26
  * Compile a collection, preserving source-backed traversal until the value is
@@ -1005,78 +28,16 @@ function evaluateCompiled(expression, record, indices, policy = { mode: 'throw'
1005
28
  * elements; map/filter chains over those elements do not.
1006
29
  */
1007
30
  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);
31
+ const compiler = (0, cel_interpreter_1.createCompilingInterpreter)(projection, access, functions, roots, readers, cel_operations_1.defaultBinaryOperations, {}, cel_operations_1.defaultConditionalOperations, rootValueTypes);
1009
32
  const parsed = (0, cel_1.parseCel)(expression, compiler);
1010
33
  if ((0, errors_1.isErrors)(parsed))
1011
34
  return parsed;
1012
35
  const node = parsed.value;
1013
36
  if (node.kind !== 'collection')
1014
- return failed('CEL expression is not a collection');
1015
- let render;
1016
- if (elementKind(node.type.element) === 'object') {
1017
- const path = node.sourcePath;
1018
- if (!path)
1019
- return failed('Cannot materialise a computed object collection');
1020
- const definition = resolveNode(projection, path);
1021
- if (!definition || definition.type !== 'array')
1022
- return failed('Unknown source collection ' + path.join('.'));
1023
- const readers = [];
1024
- for (const [name, field] of Object.entries(definition.element)) {
1025
- if (field.type === 'object' || field.type === 'array')
1026
- return failed('Materialising nested source objects requires an explicit map');
1027
- const resolved = access.compileScalar([...path, name]);
1028
- if ((0, errors_1.isErrors)(resolved))
1029
- return resolved;
1030
- const reader = resolved.value;
1031
- const depth = arrayDepth(projection, [...path, name]);
1032
- readers.push([name, (r, _i, frame) => {
1033
- const raw = reader.read(r, windowAt(frame, depth));
1034
- return field.type === 'integer' ? readProjectionInteger(raw, reader.integerStorage === 'number') : raw;
1035
- }]);
1036
- }
1037
- render = (r, i, frame) => {
1038
- const object = {};
1039
- for (const [name, read] of readers)
1040
- object[name] = read(r, i, frame);
1041
- return object;
1042
- };
1043
- }
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);
1048
- return true;
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);
1063
- return result;
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
- }
1080
- });
37
+ return (0, errors_1.errors)('CEL expression is not a collection');
38
+ const render = (0, cel_materialise_1.compileItemRenderer)(node, projection, access);
39
+ if ((0, errors_1.isErrors)(render))
40
+ return render;
41
+ return (0, errors_1.value)((0, cel_runner_1.createCollectionExpression)(node, compiler.allocateVisitorSlot(), render.value));
1081
42
  }
1082
43
  //# sourceMappingURL=cel.compile.js.map