@telorun/cel 0.0.0-stage → 0.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +281 -2
  3. package/dist/activation.d.ts +27 -0
  4. package/dist/activation.d.ts.map +1 -0
  5. package/dist/activation.js +24 -0
  6. package/dist/backend-runtime.d.ts +146 -0
  7. package/dist/backend-runtime.d.ts.map +1 -0
  8. package/dist/backend-runtime.js +322 -0
  9. package/dist/bounded-cache.d.ts +21 -0
  10. package/dist/bounded-cache.d.ts.map +1 -0
  11. package/dist/bounded-cache.js +42 -0
  12. package/dist/catalog-runtime.d.ts +59 -0
  13. package/dist/catalog-runtime.d.ts.map +1 -0
  14. package/dist/catalog-runtime.js +785 -0
  15. package/dist/cel-expression.d.ts +32 -0
  16. package/dist/cel-expression.d.ts.map +1 -0
  17. package/dist/cel-expression.js +29 -0
  18. package/dist/cel-map-value.d.ts +34 -0
  19. package/dist/cel-map-value.d.ts.map +1 -0
  20. package/dist/cel-map-value.js +74 -0
  21. package/dist/cel-program.d.ts +44 -0
  22. package/dist/cel-program.d.ts.map +1 -0
  23. package/dist/cel-program.js +72 -0
  24. package/dist/cel-type.d.ts +131 -0
  25. package/dist/cel-type.d.ts.map +1 -0
  26. package/dist/cel-type.js +293 -0
  27. package/dist/cel-value.d.ts +159 -0
  28. package/dist/cel-value.d.ts.map +1 -0
  29. package/dist/cel-value.js +225 -0
  30. package/dist/check-diagnostic.d.ts +53 -0
  31. package/dist/check-diagnostic.d.ts.map +1 -0
  32. package/dist/check-diagnostic.js +66 -0
  33. package/dist/checker.d.ts +77 -0
  34. package/dist/checker.d.ts.map +1 -0
  35. package/dist/checker.js +721 -0
  36. package/dist/closure-backend.d.ts +21 -0
  37. package/dist/closure-backend.d.ts.map +1 -0
  38. package/dist/closure-backend.js +436 -0
  39. package/dist/comprehension-bindings.d.ts +33 -0
  40. package/dist/comprehension-bindings.d.ts.map +1 -0
  41. package/dist/comprehension-bindings.js +50 -0
  42. package/dist/comprehension-runtime.d.ts +44 -0
  43. package/dist/comprehension-runtime.d.ts.map +1 -0
  44. package/dist/comprehension-runtime.js +137 -0
  45. package/dist/declared-chain.d.ts +35 -0
  46. package/dist/declared-chain.d.ts.map +1 -0
  47. package/dist/declared-chain.js +36 -0
  48. package/dist/duration-value.d.ts +59 -0
  49. package/dist/duration-value.d.ts.map +1 -0
  50. package/dist/duration-value.js +135 -0
  51. package/dist/emitted-module.d.ts +207 -0
  52. package/dist/emitted-module.d.ts.map +1 -0
  53. package/dist/emitted-module.js +359 -0
  54. package/dist/engine-version.d.ts +3 -0
  55. package/dist/engine-version.d.ts.map +1 -0
  56. package/dist/engine-version.js +8 -0
  57. package/dist/environment-digest.d.ts +44 -0
  58. package/dist/environment-digest.d.ts.map +1 -0
  59. package/dist/environment-digest.js +98 -0
  60. package/dist/environment.d.ts +283 -0
  61. package/dist/environment.d.ts.map +1 -0
  62. package/dist/environment.js +459 -0
  63. package/dist/function-catalog.d.ts +66 -0
  64. package/dist/function-catalog.d.ts.map +1 -0
  65. package/dist/function-catalog.js +77 -0
  66. package/dist/function-registry.d.ts +78 -0
  67. package/dist/function-registry.d.ts.map +1 -0
  68. package/dist/function-registry.js +189 -0
  69. package/dist/index.d.ts +91 -0
  70. package/dist/index.d.ts.map +1 -0
  71. package/dist/index.js +59 -0
  72. package/dist/integer-arithmetic.d.ts +27 -0
  73. package/dist/integer-arithmetic.d.ts.map +1 -0
  74. package/dist/integer-arithmetic.js +58 -0
  75. package/dist/js-emitter.d.ts +132 -0
  76. package/dist/js-emitter.d.ts.map +1 -0
  77. package/dist/js-emitter.js +562 -0
  78. package/dist/json-schema-type.d.ts +182 -0
  79. package/dist/json-schema-type.d.ts.map +1 -0
  80. package/dist/json-schema-type.js +487 -0
  81. package/dist/json-text-scan.d.ts +28 -0
  82. package/dist/json-text-scan.d.ts.map +1 -0
  83. package/dist/json-text-scan.js +159 -0
  84. package/dist/lexer.d.ts +103 -0
  85. package/dist/lexer.d.ts.map +1 -0
  86. package/dist/lexer.js +458 -0
  87. package/dist/macro-check.d.ts +33 -0
  88. package/dist/macro-check.d.ts.map +1 -0
  89. package/dist/macro-check.js +162 -0
  90. package/dist/macro-shape.d.ts +24 -0
  91. package/dist/macro-shape.d.ts.map +1 -0
  92. package/dist/macro-shape.js +55 -0
  93. package/dist/member-read.d.ts +52 -0
  94. package/dist/member-read.d.ts.map +1 -0
  95. package/dist/member-read.js +125 -0
  96. package/dist/namespace-resolution.d.ts +35 -0
  97. package/dist/namespace-resolution.d.ts.map +1 -0
  98. package/dist/namespace-resolution.js +160 -0
  99. package/dist/nominal-type.d.ts +63 -0
  100. package/dist/nominal-type.d.ts.map +1 -0
  101. package/dist/nominal-type.js +98 -0
  102. package/dist/nullable-access.d.ts +38 -0
  103. package/dist/nullable-access.d.ts.map +1 -0
  104. package/dist/nullable-access.js +93 -0
  105. package/dist/parse-limits.d.ts +26 -0
  106. package/dist/parse-limits.d.ts.map +1 -0
  107. package/dist/parse-limits.js +21 -0
  108. package/dist/parser.d.ts +48 -0
  109. package/dist/parser.d.ts.map +1 -0
  110. package/dist/parser.js +503 -0
  111. package/dist/qualified-calls.d.ts +22 -0
  112. package/dist/qualified-calls.d.ts.map +1 -0
  113. package/dist/qualified-calls.js +27 -0
  114. package/dist/regular-expression.d.ts +48 -0
  115. package/dist/regular-expression.d.ts.map +1 -0
  116. package/dist/regular-expression.js +77 -0
  117. package/dist/reserved-words.d.ts +52 -0
  118. package/dist/reserved-words.d.ts.map +1 -0
  119. package/dist/reserved-words.js +77 -0
  120. package/dist/resolved-call.d.ts +33 -0
  121. package/dist/resolved-call.d.ts.map +1 -0
  122. package/dist/resolved-call.js +15 -0
  123. package/dist/root-references.d.ts +23 -0
  124. package/dist/root-references.d.ts.map +1 -0
  125. package/dist/root-references.js +120 -0
  126. package/dist/runtime-library.d.ts +56 -0
  127. package/dist/runtime-library.d.ts.map +1 -0
  128. package/dist/runtime-library.js +545 -0
  129. package/dist/serializer.d.ts +24 -0
  130. package/dist/serializer.d.ts.map +1 -0
  131. package/dist/serializer.js +240 -0
  132. package/dist/sha256.d.ts +20 -0
  133. package/dist/sha256.d.ts.map +1 -0
  134. package/dist/sha256.js +103 -0
  135. package/dist/signature.d.ts +72 -0
  136. package/dist/signature.d.ts.map +1 -0
  137. package/dist/signature.js +61 -0
  138. package/dist/signatures/function-catalog.json +788 -0
  139. package/dist/signatures/standard-library.json +229 -0
  140. package/dist/standard-library.d.ts +41 -0
  141. package/dist/standard-library.d.ts.map +1 -0
  142. package/dist/standard-library.js +85 -0
  143. package/dist/syntax-diagnostic.d.ts +61 -0
  144. package/dist/syntax-diagnostic.d.ts.map +1 -0
  145. package/dist/syntax-diagnostic.js +28 -0
  146. package/dist/syntax-tree.d.ts +160 -0
  147. package/dist/syntax-tree.d.ts.map +1 -0
  148. package/dist/syntax-tree.js +58 -0
  149. package/dist/timestamp-value.d.ts +53 -0
  150. package/dist/timestamp-value.d.ts.map +1 -0
  151. package/dist/timestamp-value.js +223 -0
  152. package/dist/tree-equality.d.ts +15 -0
  153. package/dist/tree-equality.d.ts.map +1 -0
  154. package/dist/tree-equality.js +105 -0
  155. package/dist/type-expression.d.ts +26 -0
  156. package/dist/type-expression.d.ts.map +1 -0
  157. package/dist/type-expression.js +134 -0
  158. package/dist/value-equality.d.ts +38 -0
  159. package/dist/value-equality.d.ts.map +1 -0
  160. package/dist/value-equality.js +196 -0
  161. package/dist/value-text.d.ts +25 -0
  162. package/dist/value-text.d.ts.map +1 -0
  163. package/dist/value-text.js +44 -0
  164. package/dist/zoned-calendar.d.ts +61 -0
  165. package/dist/zoned-calendar.d.ts.map +1 -0
  166. package/dist/zoned-calendar.js +143 -0
  167. package/package.json +56 -3
  168. package/src/activation.ts +32 -0
  169. package/src/backend-runtime.ts +454 -0
  170. package/src/bounded-cache.ts +45 -0
  171. package/src/catalog-runtime.ts +921 -0
  172. package/src/cel-expression.ts +53 -0
  173. package/src/cel-map-value.ts +86 -0
  174. package/src/cel-program.ts +103 -0
  175. package/src/cel-type.ts +359 -0
  176. package/src/cel-value.ts +353 -0
  177. package/src/check-diagnostic.ts +102 -0
  178. package/src/checker.ts +932 -0
  179. package/src/closure-backend.ts +502 -0
  180. package/src/comprehension-bindings.ts +66 -0
  181. package/src/comprehension-runtime.ts +157 -0
  182. package/src/declared-chain.ts +45 -0
  183. package/src/duration-value.ts +145 -0
  184. package/src/emitted-module.ts +494 -0
  185. package/src/engine-version.ts +9 -0
  186. package/src/environment-digest.ts +111 -0
  187. package/src/environment.ts +740 -0
  188. package/src/function-catalog.ts +140 -0
  189. package/src/function-registry.ts +229 -0
  190. package/src/index.ts +386 -0
  191. package/src/integer-arithmetic.ts +64 -0
  192. package/src/js-emitter.ts +713 -0
  193. package/src/json-schema-type.ts +664 -0
  194. package/src/json-text-scan.ts +163 -0
  195. package/src/lexer.ts +562 -0
  196. package/src/macro-check.ts +191 -0
  197. package/src/macro-shape.ts +66 -0
  198. package/src/member-read.ts +126 -0
  199. package/src/namespace-resolution.ts +167 -0
  200. package/src/nominal-type.ts +149 -0
  201. package/src/nullable-access.ts +95 -0
  202. package/src/parse-limits.ts +36 -0
  203. package/src/parser.ts +554 -0
  204. package/src/qualified-calls.ts +39 -0
  205. package/src/regular-expression.ts +101 -0
  206. package/src/reserved-words.ts +94 -0
  207. package/src/resolved-call.ts +34 -0
  208. package/src/root-references.ts +126 -0
  209. package/src/runtime-library.ts +615 -0
  210. package/src/serializer.ts +246 -0
  211. package/src/sha256.ts +112 -0
  212. package/src/signature.ts +127 -0
  213. package/src/signatures/function-catalog.json +788 -0
  214. package/src/signatures/standard-library.json +235 -0
  215. package/src/standard-library.ts +149 -0
  216. package/src/syntax-diagnostic.ts +72 -0
  217. package/src/syntax-tree.ts +229 -0
  218. package/src/timestamp-value.ts +294 -0
  219. package/src/tree-equality.ts +130 -0
  220. package/src/type-expression.ts +160 -0
  221. package/src/value-equality.ts +201 -0
  222. package/src/value-text.ts +45 -0
  223. package/src/zoned-calendar.ts +178 -0
@@ -0,0 +1,562 @@
1
+ /**
2
+ * The JavaScript emitter: a tree compiled to **source**, not to closures.
3
+ *
4
+ * It decides nothing the closure backend decides differently. Every operator and standard
5
+ * function is the runtime library's, every comprehension is `comprehension-runtime.ts`, and
6
+ * every member read, name read, bool operand and call-site dispatch is `backend-runtime.ts`
7
+ * — so what this file produces is a tree of CALLS into those, in the same order, with the
8
+ * same short-circuit. That is why the two backends can be held to one answer case for case:
9
+ * the only thing that differs is how control gets from one call to the next.
10
+ *
11
+ * Three properties the shape of the output exists for:
12
+ *
13
+ * - **The runtime is a parameter, never an import.** The emitted module's default export is
14
+ * a factory; it names no specifier, so it loads from a `data:` URL, from a cache directory
15
+ * mounted anywhere, and under a host that resolves nothing. A module naming
16
+ * `@telorun/cel` would also silently accept a runtime of another version, which the cache
17
+ * key could not see.
18
+ * - **No bare property access implements a CEL read.** `a.b`, `a['b']`, `a[expr]`, `.?`,
19
+ * `[?]` and `has()` all emit a call to the member-read seam, so no key an author or a
20
+ * request wrote reaches a prototype, a method or a function property. The frame's own
21
+ * fields are the engine's structure and are read directly, as they are in a closure.
22
+ * - **Nothing is asynchronous.** No `async`, no `await`, no promise: a thenable is refused
23
+ * at the same doors, because the doors are the shared runtime's.
24
+ *
25
+ * Emission is **deterministic**: temporaries are numbered per emitted function in tree
26
+ * order, bindings per module in tree order, and every hoisted constant is keyed by its own
27
+ * text, so the same tree against the same environment is the same bytes.
28
+ */
29
+ import { CelCompileError, plainMemberChain, prefixCandidates, } from "./backend-runtime.js";
30
+ import { namespaceMacroBinding, receiverMacroBinding } from "./comprehension-bindings.js";
31
+ import { splitDeclaredChain } from "./declared-chain.js";
32
+ import { isMacroCall } from "./macro-check.js";
33
+ /**
34
+ * The names an emitted module destructures from the runtime it is handed, in the order it
35
+ * destructures them. It is the module's whole contract with the engine: `emitterRuntime`
36
+ * (`emitted-module.ts`) builds an object with exactly these keys, and a module emitted by
37
+ * one engine against another's runtime fails at load rather than running on a missing
38
+ * binding — which is the second reason the key carries the engine version.
39
+ */
40
+ export const RUNTIME_BINDINGS = [
41
+ "asyncValueRefused",
42
+ "boolOperand",
43
+ "callSite",
44
+ "celAll",
45
+ "celError",
46
+ "celExists",
47
+ "celExistsOne",
48
+ "celFilter",
49
+ "celIterable",
50
+ "celMapComprehension",
51
+ "celMapFromEntries",
52
+ "celSome",
53
+ "celUint",
54
+ "constants",
55
+ "hasMember",
56
+ "isCelError",
57
+ "isCelOptional",
58
+ "none",
59
+ "optionalEntry",
60
+ "optionalOfNonZero",
61
+ "readHostValue",
62
+ "readName",
63
+ "readNameChain",
64
+ "readThrough",
65
+ "searchNameChain",
66
+ ];
67
+ function boundName(scope, name) {
68
+ for (let at = scope; at; at = at.outer)
69
+ if (at.name === name)
70
+ return at.js;
71
+ return undefined;
72
+ }
73
+ /**
74
+ * The temporaries one emitted function declares. Each emitted function — the expression's
75
+ * own, and every comprehension or binding body inside it — declares its own, because a
76
+ * body's closure outlives the statement that called it and a name it shares with its caller
77
+ * would clobber a value still in use.
78
+ *
79
+ * **Every name is unique across the MODULE, not within the function**, and that is not
80
+ * tidiness: a body declaring `let t0` would **shadow** the `t0` its caller holds a bound
81
+ * value in, so `cel.bind(n, 2, xs.map(e, e + n))` read the element where it meant the
82
+ * binding and answered `[2, 4, 6]` for `[3, 4, 5]`. Numbering per module makes the shape
83
+ * impossible rather than avoided.
84
+ */
85
+ class Temporaries {
86
+ allocate;
87
+ names = [];
88
+ constructor(allocate) {
89
+ this.allocate = allocate;
90
+ }
91
+ next() {
92
+ const name = this.allocate();
93
+ this.names.push(name);
94
+ return name;
95
+ }
96
+ /** The `let` that declares them, or nothing where the function used none. */
97
+ declaration() {
98
+ return this.names.length === 0 ? "" : `let ${this.names.join(", ")}; `;
99
+ }
100
+ }
101
+ /**
102
+ * One module's worth of emission. The hoist table is shared by every expression in the
103
+ * module, so two expressions reading the same name share one range and one rest-list: a
104
+ * constant allocated per evaluation is the cost the closure backend does not pay, and
105
+ * hoisting is how the emitter does not pay it either.
106
+ */
107
+ export class ModuleEmitter {
108
+ target;
109
+ hoisted = [];
110
+ hoistedByText = new Map();
111
+ locals = 0;
112
+ bindings = 0;
113
+ constructor(target) {
114
+ this.target = target;
115
+ }
116
+ /** The source of one expression's function: a `CelStep` over the evaluation frame. */
117
+ emitFunction(root) {
118
+ const temporaries = this.temporaries();
119
+ const body = this.node(root, undefined, temporaries);
120
+ return `(frame) => { ${temporaries.declaration()}return ${body}; }`;
121
+ }
122
+ /** A fresh function's temporaries, drawing names from the module's own numbering. */
123
+ temporaries() {
124
+ return new Temporaries(() => {
125
+ const name = `t${this.locals}`;
126
+ this.locals += 1;
127
+ return name;
128
+ });
129
+ }
130
+ /** The `const` lines every emitted expression reads, in first-use order. */
131
+ hoistedLines() {
132
+ return this.hoisted;
133
+ }
134
+ hoist(text) {
135
+ const held = this.hoistedByText.get(text);
136
+ if (held !== undefined)
137
+ return held;
138
+ const name = `h${this.hoisted.length}`;
139
+ this.hoisted.push(`const ${name} = ${text};`);
140
+ this.hoistedByText.set(text, name);
141
+ return name;
142
+ }
143
+ range(range) {
144
+ return this.hoist(`[${range[0]}, ${range[1]}]`);
145
+ }
146
+ /**
147
+ * The name a comprehension's element is bound to: a **parameter** of the body function,
148
+ * numbered per module so a nested body can never shadow the one around it.
149
+ */
150
+ elementName() {
151
+ const name = `b${this.bindings}`;
152
+ this.bindings += 1;
153
+ return name;
154
+ }
155
+ // --- the tree -----------------------------------------------------------
156
+ node(node, scope, fn) {
157
+ switch (node.kind) {
158
+ case "literal":
159
+ return this.literal(node.literal);
160
+ case "ident":
161
+ return this.ident(node, scope);
162
+ case "list":
163
+ return this.list(node, scope, fn);
164
+ case "map":
165
+ return this.map(node, scope, fn);
166
+ case "select":
167
+ return this.select(node, scope, fn);
168
+ case "index":
169
+ return this.index(node, scope, fn);
170
+ case "unary":
171
+ return this.call(node.operator, "global", [this.node(node.operand, scope, fn)], node.range, fn);
172
+ case "binary":
173
+ return this.binary(node, scope, fn);
174
+ case "conditional":
175
+ return this.conditional(node, scope, fn);
176
+ case "call":
177
+ case "receiverCall":
178
+ return this.anyCall(node, scope, fn);
179
+ case "qcall":
180
+ return this.qualifiedCall(node, scope, fn);
181
+ case "unparsed":
182
+ throw new CelCompileError("the expression could not be read whole, so it cannot be compiled");
183
+ }
184
+ }
185
+ /**
186
+ * A literal as the source that builds its value. A plain value is written inline; a uint
187
+ * and a bytes literal are **hoisted**, because each is an object and allocating one per
188
+ * evaluation would be work the closure backend does once at compile time.
189
+ */
190
+ literal(literal) {
191
+ switch (literal.type) {
192
+ case "int":
193
+ return integerSource(literal.value);
194
+ case "uint":
195
+ return this.hoist(`celUint(${integerSource(literal.value)})`);
196
+ case "double":
197
+ return doubleSource(literal.value);
198
+ case "string":
199
+ return textSource(literal.value);
200
+ case "bytes":
201
+ return this.hoist(`new Uint8Array([${[...literal.value].join(", ")}])`);
202
+ case "bool":
203
+ return literal.value ? "true" : "false";
204
+ case "null":
205
+ return "null";
206
+ }
207
+ }
208
+ // --- names --------------------------------------------------------------
209
+ ident(node, scope) {
210
+ if (!node.absolute) {
211
+ const held = boundName(scope, node.name);
212
+ if (held !== undefined)
213
+ return held;
214
+ }
215
+ return `readName(frame.activation, constants, ${textSource(node.name)}, ${this.range(node.range)})`;
216
+ }
217
+ /**
218
+ * A chain of plain member names rooted at a free name. The split over the names the host
219
+ * declared happens **here, at emit time**, through the same function the checker and the
220
+ * closure backend split it with — so the emitted code performs one activation read and
221
+ * then member reads, and can never read a different name than the one the check typed.
222
+ */
223
+ chain(segments, range) {
224
+ const declaredSplit = splitDeclaredChain(segments, this.target.declares);
225
+ const at = this.range(range);
226
+ if (declaredSplit) {
227
+ const rest = this.hoist(`[${declaredSplit.rest.map(textSource).join(", ")}]`);
228
+ return `readNameChain(frame.activation, constants, ${textSource(declaredSplit.name)}, ${rest}, ${at})`;
229
+ }
230
+ // Nothing declares a prefix, so the activation is searched longest prefix first — the
231
+ // same fallback, over the same candidate list, that the closure backend builds.
232
+ const candidates = this.hoist(`[${prefixCandidates(segments)
233
+ .map((candidate) => `{ name: ${textSource(candidate.name)}, rest: [${candidate.rest.map(textSource).join(", ")}] }`)
234
+ .join(", ")}]`);
235
+ return `searchNameChain(frame.activation, constants, ${candidates}, ${textSource(segments.join("."))}, ${at})`;
236
+ }
237
+ // --- member reads -------------------------------------------------------
238
+ select(node, scope, fn) {
239
+ const chain = plainMemberChain(node, (name) => boundName(scope, name) !== undefined);
240
+ if (chain)
241
+ return this.chain(chain, node.range);
242
+ const operand = this.node(node.operand, scope, fn);
243
+ const at = this.range(node.range);
244
+ return this.carrying([operand], fn, ([held]) => `readThrough(${held}, ${textSource(node.field)}, ${node.optional}, ${at})`);
245
+ }
246
+ index(node, scope, fn) {
247
+ const operand = this.node(node.operand, scope, fn);
248
+ const key = this.node(node.index, scope, fn);
249
+ const at = this.range(node.range);
250
+ return this.carrying([operand, key], fn, ([held, named]) => `readThrough(${held}, ${named}, ${node.optional}, ${at})`);
251
+ }
252
+ // --- aggregates ---------------------------------------------------------
253
+ list(node, scope, fn) {
254
+ const out = fn.next();
255
+ const at = this.range(node.range);
256
+ const entries = node.elements.map((element) => ({
257
+ value: this.node(element.value, scope, fn),
258
+ optional: element.optional,
259
+ }));
260
+ let body = out;
261
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
262
+ const entry = entries[index];
263
+ const value = fn.next();
264
+ if (!entry.optional) {
265
+ body = `(${value} = ${entry.value}, isCelError(${value}) ? ${value} : (${out}.push(${value}), ${body}))`;
266
+ continue;
267
+ }
268
+ // An absent optional entry leaves no element: the aggregate shrinks, which is the
269
+ // whole reason to write one.
270
+ const held = fn.next();
271
+ body =
272
+ `(${value} = ${entry.value}, isCelError(${value}) ? ${value} : ` +
273
+ `(${held} = optionalEntry(${value}, ${at}), isCelError(${held}) ? ${held} : ` +
274
+ `(${held}.present && ${out}.push(${held}.held), ${body})))`;
275
+ }
276
+ return `(${out} = [], ${body})`;
277
+ }
278
+ map(node, scope, fn) {
279
+ const out = fn.next();
280
+ const at = this.range(node.range);
281
+ const entries = node.entries.map((entry) => ({
282
+ key: this.node(entry.key, scope, fn),
283
+ value: this.node(entry.value, scope, fn),
284
+ optional: entry.optional,
285
+ }));
286
+ let body = `celMapFromEntries(${out}, ${at})`;
287
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
288
+ const entry = entries[index];
289
+ const key = fn.next();
290
+ const value = fn.next();
291
+ const kept = entry.optional ? fn.next() : undefined;
292
+ const written = kept
293
+ ? `(${kept} = optionalEntry(${value}, ${at}), isCelError(${kept}) ? ${kept} : ` +
294
+ `(${kept}.present && ${out}.push([${key}, ${kept}.held]), ${body}))`
295
+ : `(${out}.push([${key}, ${value}]), ${body})`;
296
+ body =
297
+ `(${key} = ${entry.key}, isCelError(${key}) ? ${key} : ` +
298
+ `(${value} = ${entry.value}, isCelError(${value}) ? ${value} : ${written}))`;
299
+ }
300
+ return `(${out} = [], ${body})`;
301
+ }
302
+ // --- operators ----------------------------------------------------------
303
+ /**
304
+ * `&&` and `||` carry an error-valued operand through: `false && <error>` is `false` and
305
+ * `true || <error>` is `true`, whichever side the error is on. The emitted form is the
306
+ * closure backend's branch order written out, so an error on one side and a non-bool on
307
+ * the other decide the same way.
308
+ */
309
+ binary(node, scope, fn) {
310
+ if (node.operator !== "&&" && node.operator !== "||") {
311
+ return this.call(node.operator, "global", [this.node(node.left, scope, fn), this.node(node.right, scope, fn)], node.range, fn);
312
+ }
313
+ const left = this.node(node.left, scope, fn);
314
+ const right = this.node(node.right, scope, fn);
315
+ const at = this.range(node.range);
316
+ const decided = node.operator === "&&" ? "false" : "true";
317
+ const undecided = node.operator === "&&" ? "true" : "false";
318
+ const a = fn.next();
319
+ const b = fn.next();
320
+ return (`(${a} = boolOperand(${left}, ${at}), ${a} === ${decided} ? ${decided} : ` +
321
+ `(${b} = boolOperand(${right}, ${at}), ${b} === ${decided} ? ${decided} : ` +
322
+ `isCelError(${a}) ? ${a} : isCelError(${b}) ? ${b} : ${undecided}))`);
323
+ }
324
+ conditional(node, scope, fn) {
325
+ const condition = this.node(node.condition, scope, fn);
326
+ const whenTrue = this.node(node.whenTrue, scope, fn);
327
+ const whenFalse = this.node(node.whenFalse, scope, fn);
328
+ const at = this.range(node.range);
329
+ const held = fn.next();
330
+ return (`(${held} = boolOperand(${condition}, ${at}), isCelError(${held}) ? ${held} : ` +
331
+ `${held} ? ${whenTrue} : ${whenFalse})`);
332
+ }
333
+ // --- calls --------------------------------------------------------------
334
+ anyCall(node, scope, fn) {
335
+ // The same question the checker asks, in the same place: a macro is not a function, and
336
+ // it is recognised before any overload is looked for.
337
+ if (isMacroCall(node))
338
+ return this.macro(node, scope, fn);
339
+ const args = [
340
+ ...(node.kind === "receiverCall" ? [this.node(node.receiver, scope, fn)] : []),
341
+ ...node.args.map((argument) => this.node(argument, scope, fn)),
342
+ ];
343
+ return this.call(node.name, node.kind === "call" ? "global" : "receiver", args, node.range, fn);
344
+ }
345
+ /**
346
+ * One dispatch: evaluate the arguments, carry the first error out, then hand the values to
347
+ * the site. The site is hoisted, so it is built once per loaded module and holds the
348
+ * overloads it resolved — exactly as a compiled closure's does.
349
+ */
350
+ call(name, form, args, range, fn) {
351
+ const site = this.hoist(`callSite(${textSource(name)}, ${textSource(form)}, ${this.range(range)})`);
352
+ return this.carrying(args, fn, (values) => `${site}.call([${values.join(", ")}])`);
353
+ }
354
+ qualifiedCall(node, scope, fn) {
355
+ const args = node.args.map((argument) => this.node(argument, scope, fn));
356
+ const at = this.range(node.range);
357
+ const context = this.hoist(`{ range: ${at} }`);
358
+ const bound = fn.next();
359
+ // The arguments are evaluated only once something IS bound, which is the closure
360
+ // backend's order: a call nothing bound is `unbound_function` even where an argument
361
+ // would have failed.
362
+ const dispatched = this.carrying(args, fn, (values) => `readHostValue(${bound}([${values.join(", ")}], ${context}), ${at})`);
363
+ const refusal = `celError("unbound_function", ${textSource(`unbound function '${node.namespace}.${node.name}' — nothing is bound under that name here`)}, ${at})`;
364
+ return (`(${bound} = frame.namespaceFunction ? frame.namespaceFunction(${textSource(node.namespace)}, ` +
365
+ `${textSource(node.name)}) : undefined, !${bound} ? ${refusal} : ${dispatched})`);
366
+ }
367
+ // --- macros -------------------------------------------------------------
368
+ macro(node, scope, fn) {
369
+ if (node.kind === "call")
370
+ return this.has(node, scope, fn);
371
+ const receiver = node.receiver;
372
+ if (receiver.kind === "ident" && receiver.name === "cel" && node.name === "bind") {
373
+ return this.celBind(node, scope, fn);
374
+ }
375
+ if (receiver.kind === "ident" && receiver.name === "optional") {
376
+ return this.optionalNamespace(node, scope, fn);
377
+ }
378
+ if ((node.name === "optMap" || node.name === "optFlatMap") && node.args.length === 2) {
379
+ return this.optionalBinding(node, scope, fn);
380
+ }
381
+ return this.comprehension(node, scope, fn);
382
+ }
383
+ /** `has(a.b)` — presence, which a missing key answers `false` rather than erroring. */
384
+ has(node, scope, fn) {
385
+ const argument = node.args[0];
386
+ if (argument.kind !== "select") {
387
+ throw new CelCompileError("has() asks about a member, so its argument ends in a select");
388
+ }
389
+ const operand = this.node(argument.operand, scope, fn);
390
+ const at = this.range(node.range);
391
+ return this.carrying([operand], fn, ([held]) => `hasMember(${held}, ${textSource(argument.field)}, ${at})`);
392
+ }
393
+ celBind(node, scope, fn) {
394
+ const binding = namespaceMacroBinding("cel", node.name, node.args.length);
395
+ if (!binding) {
396
+ throw new CelCompileError("cel.bind(name, value, body) takes a name, its value and a body");
397
+ }
398
+ const name = node.args[binding.variableArgument];
399
+ if (name.kind !== "ident")
400
+ throw new CelCompileError("cel.bind binds a name");
401
+ const value = this.node(node.args[1], scope, fn);
402
+ // The bound value lives in a temporary of the enclosing function, so it is DECLARED
403
+ // there: a body nested inside this one captures it as a closure captures any `let`.
404
+ const held = fn.next();
405
+ const body = this.node(node.args[2], { name: name.name, js: held, outer: scope }, fn);
406
+ const at = this.range(node.range);
407
+ const refused = fn.next();
408
+ // A name is bound to a VALUE, so a value that must be awaited is refused here rather
409
+ // than inside the body, where every read of the name would meet it again.
410
+ return (`(${held} = ${value}, isCelError(${held}) ? ${held} : ` +
411
+ `(${refused} = asyncValueRefused(${held}, ${at}), ${refused} ? ${refused} : ${body}))`);
412
+ }
413
+ /** `optional.of(v)`, `optional.ofNonZeroValue(v)` and `optional.none()`. */
414
+ optionalNamespace(node, scope, fn) {
415
+ if (node.name === "none")
416
+ return "none";
417
+ if (node.args.length !== 1) {
418
+ throw new CelCompileError(`optional.${node.name}(value) takes one argument`);
419
+ }
420
+ const value = this.node(node.args[0], scope, fn);
421
+ const wrap = node.name === "ofNonZeroValue" ? "optionalOfNonZero" : "celSome";
422
+ return this.carrying([value], fn, ([held]) => `${wrap}(${held})`);
423
+ }
424
+ /** `opt.optMap(v, body)` wraps what the body answers; `optFlatMap` does not. */
425
+ optionalBinding(node, scope, fn) {
426
+ const name = node.args[0];
427
+ if (name.kind !== "ident")
428
+ throw new CelCompileError(`${node.name} binds a name`);
429
+ const receiver = this.node(node.receiver, scope, fn);
430
+ const at = this.range(node.range);
431
+ const optional = fn.next();
432
+ const refused = fn.next();
433
+ const answered = fn.next();
434
+ const held = fn.next();
435
+ const body = this.node(node.args[1], { name: name.name, js: held, outer: scope }, fn);
436
+ const wrong = `celError("no_matching_overload", ${textSource(`${JSON.stringify(node.name)} reads an optional`)}, ${at})`;
437
+ const result = node.name === "optMap"
438
+ ? `celSome(${answered})`
439
+ : `isCelOptional(${answered}) ? ${answered} : celError("no_matching_overload", ` +
440
+ `${textSource("optFlatMap's body answers an optional")}, ${at})`;
441
+ // A host may hand over the optional itself, so what it HOLDS is a door of its own.
442
+ return (`(${optional} = ${receiver}, isCelError(${optional}) ? ${optional} : ` +
443
+ `!isCelOptional(${optional}) ? ${wrong} : ` +
444
+ `!${optional}.present ? none : ` +
445
+ `(${refused} = asyncValueRefused(${optional}.held, ${at}), ${refused} ? ${refused} : ` +
446
+ `(${held} = ${optional}.held, ${answered} = ${body}, isCelError(${answered}) ? ${answered} : ${result})))`);
447
+ }
448
+ /**
449
+ * A comprehension. The body becomes a function of the element, exactly as the closure
450
+ * backend passes one, so the macro's meaning — including which error outranks which
451
+ * decided answer — stays `comprehension-runtime.ts`'s alone.
452
+ */
453
+ comprehension(node, scope, fn) {
454
+ const binding = receiverMacroBinding(node.name, node.args.length);
455
+ if (!binding)
456
+ throw new CelCompileError(`${node.name} is not a comprehension`);
457
+ const name = node.args[binding.variableArgument];
458
+ if (name.kind !== "ident")
459
+ throw new CelCompileError(`${node.name} binds a name`);
460
+ const receiver = this.node(node.receiver, scope, fn);
461
+ const at = this.range(node.range);
462
+ const element = this.elementName();
463
+ const inner = { name: name.name, js: element, outer: scope };
464
+ const bodies = binding.scopedArguments.map((argument) => this.body(node.args[argument], inner, element));
465
+ const elements = fn.next();
466
+ const call = (() => {
467
+ switch (node.name) {
468
+ case "all":
469
+ return `celAll(${elements}, ${bodies[0]}, ${at})`;
470
+ case "exists":
471
+ return `celExists(${elements}, ${bodies[0]}, ${at})`;
472
+ case "exists_one":
473
+ return `celExistsOne(${elements}, ${bodies[0]}, ${at})`;
474
+ case "filter":
475
+ return `celFilter(${elements}, ${bodies[0]}, ${at})`;
476
+ default:
477
+ return bodies.length === 2
478
+ ? `celMapComprehension(${elements}, ${bodies[1]}, ${bodies[0]}, ${at})`
479
+ : `celMapComprehension(${elements}, ${bodies[0]}, undefined, ${at})`;
480
+ }
481
+ })();
482
+ return this.carrying([receiver], fn, ([held]) => `(${elements} = celIterable(${held}, ${at}), isCelError(${elements}) ? ${elements} : ${call})`);
483
+ }
484
+ /** A body a comprehension calls per element: its own function, with its own temporaries. */
485
+ body(node, scope, parameter) {
486
+ const temporaries = this.temporaries();
487
+ const text = this.node(node, scope, temporaries);
488
+ return `(${parameter}) => { ${temporaries.declaration()}return ${text}; }`;
489
+ }
490
+ // --- the one sequencing rule --------------------------------------------
491
+ /**
492
+ * Evaluate each expression in order and carry the first error out, then build the answer
493
+ * from the values. Every form that evaluates more than one thing goes through here, so a
494
+ * later operand is never evaluated after an earlier one failed — which is what makes an
495
+ * error a value that short-circuits rather than an exception.
496
+ */
497
+ carrying(expressions, fn, answer) {
498
+ const values = expressions.map(() => fn.next());
499
+ let out = answer(values);
500
+ for (let at = expressions.length - 1; at >= 0; at -= 1) {
501
+ out = `(${values[at]} = ${expressions[at]}, isCelError(${values[at]}) ? ${values[at]} : ${out})`;
502
+ }
503
+ return out;
504
+ }
505
+ }
506
+ // --- writing a value as source ---------------------------------------------
507
+ /** An int or uint literal as a `bigint`, parenthesized where it is negative. */
508
+ function integerSource(value) {
509
+ return value < 0n ? `(${value}n)` : `${value}n`;
510
+ }
511
+ /**
512
+ * A double as source. `-0` is a value CEL tells apart from `0`, and an overflowing literal
513
+ * reads as an infinity, so neither may go through the shortest decimal form.
514
+ */
515
+ function doubleSource(value) {
516
+ if (Number.isNaN(value))
517
+ return "NaN";
518
+ if (value === Number.POSITIVE_INFINITY)
519
+ return "Infinity";
520
+ if (value === Number.NEGATIVE_INFINITY)
521
+ return "(-Infinity)";
522
+ if (Object.is(value, -0))
523
+ return "(-0)";
524
+ return value < 0 ? `(${value})` : `${value}`;
525
+ }
526
+ const ESCAPES = {
527
+ "\\": "\\\\",
528
+ '"': '\\"',
529
+ "\n": "\\n",
530
+ "\r": "\\r",
531
+ "\t": "\\t",
532
+ "\b": "\\b",
533
+ "\f": "\\f",
534
+ "\v": "\\v",
535
+ };
536
+ /**
537
+ * Text as a JavaScript string literal. Every character outside printable ASCII is written
538
+ * as an escape — a lone surrogate, a line separator and a zero-width joiner all read back
539
+ * as themselves, and the emitted module is pure ASCII however its expressions were written,
540
+ * so no encoding assumption about the file it is stored in can change its meaning.
541
+ */
542
+ export function textSource(text) {
543
+ let out = '"';
544
+ for (const unit of text) {
545
+ const held = ESCAPES[unit];
546
+ if (held !== undefined) {
547
+ out += held;
548
+ continue;
549
+ }
550
+ const code = unit.codePointAt(0);
551
+ if (code >= 0x20 && code <= 0x7e) {
552
+ out += unit;
553
+ continue;
554
+ }
555
+ if (code > 0xffff) {
556
+ out += `\\u{${code.toString(16)}}`;
557
+ continue;
558
+ }
559
+ out += `\\u${code.toString(16).padStart(4, "0")}`;
560
+ }
561
+ return `${out}"`;
562
+ }