@telorun/templating 0.107.0 → 0.109.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 (60) hide show
  1. package/dist/builtins.d.ts +2 -2
  2. package/dist/builtins.d.ts.map +1 -1
  3. package/dist/cel/analyze.d.ts +6 -6
  4. package/dist/cel/analyze.d.ts.map +1 -1
  5. package/dist/cel/analyze.js +138 -183
  6. package/dist/cel/compile.d.ts +47 -17
  7. package/dist/cel/compile.d.ts.map +1 -1
  8. package/dist/cel/compile.js +135 -83
  9. package/dist/cel/diagnose.d.ts +52 -57
  10. package/dist/cel/diagnose.d.ts.map +1 -1
  11. package/dist/cel/diagnose.js +69 -291
  12. package/dist/cel/environment.d.ts +33 -37
  13. package/dist/cel/environment.d.ts.map +1 -1
  14. package/dist/cel/environment.js +54 -86
  15. package/dist/cel/module-call.d.ts +68 -79
  16. package/dist/cel/module-call.d.ts.map +1 -1
  17. package/dist/cel/module-call.js +118 -194
  18. package/dist/cel/value-brands.d.ts +14 -12
  19. package/dist/cel/value-brands.d.ts.map +1 -1
  20. package/dist/cel/value-brands.js +26 -24
  21. package/dist/cel/verdict-codes.d.ts +13 -2
  22. package/dist/cel/verdict-codes.d.ts.map +1 -1
  23. package/dist/cel/verdict-codes.js +20 -1
  24. package/dist/engine.d.ts +4 -4
  25. package/dist/engine.d.ts.map +1 -1
  26. package/dist/engines/cel.d.ts +2 -2
  27. package/dist/engines/cel.d.ts.map +1 -1
  28. package/dist/engines/cel.js +53 -81
  29. package/dist/engines/hole-analysis.d.ts +3 -3
  30. package/dist/engines/hole-analysis.d.ts.map +1 -1
  31. package/dist/engines/interpolate.js +11 -8
  32. package/dist/index.d.ts +4 -5
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +8 -5
  35. package/package.json +4 -4
  36. package/src/builtins.ts +2 -2
  37. package/src/cel/analyze.ts +152 -193
  38. package/src/cel/compile.ts +160 -77
  39. package/src/cel/diagnose.ts +115 -370
  40. package/src/cel/environment.ts +64 -87
  41. package/src/cel/module-call.ts +129 -292
  42. package/src/cel/value-brands.ts +26 -25
  43. package/src/cel/verdict-codes.ts +20 -1
  44. package/src/engine.ts +4 -4
  45. package/src/engines/cel.ts +52 -84
  46. package/src/engines/hole-analysis.ts +3 -3
  47. package/src/engines/interpolate.ts +16 -13
  48. package/src/index.ts +8 -11
  49. package/dist/cel/catalog.d.ts +0 -70
  50. package/dist/cel/catalog.d.ts.map +0 -1
  51. package/dist/cel/catalog.js +0 -1320
  52. package/dist/cel/json-prefix-scan.d.ts +0 -17
  53. package/dist/cel/json-prefix-scan.d.ts.map +0 -1
  54. package/dist/cel/json-prefix-scan.js +0 -160
  55. package/dist/cel/value-identity.d.ts +0 -18
  56. package/dist/cel/value-identity.d.ts.map +0 -1
  57. package/dist/cel/value-identity.js +0 -25
  58. package/src/cel/catalog.ts +0 -1455
  59. package/src/cel/json-prefix-scan.ts +0 -152
  60. package/src/cel/value-identity.ts +0 -34
@@ -1,130 +1,71 @@
1
1
  /**
2
- * **A call whose receiver is one of the declaring module's names.**
2
+ * Module calls: what a resolved one says, where the dispatch table hangs, and the two walks
3
+ * the analyzer asks of an expression's own names.
3
4
  *
4
- * `Billing.format(x)`, `Self.y(1)`, `<ModuleName>.y(1)` — CEL's own
5
- * qualified-function rule, the one `cel.bind` and cel-go's `math.greatest`
6
- * already follow. Resolution happens on the PARSED TREE, right after
7
- * `env.parse` and before any check: the author's text, spans and the expression
8
- * a trace shows stay exactly as written, which rewriting the source would move.
5
+ * **The rewrite is gone.** `Alias.fn(x)` and `obj.method(x)` are the same syntax and only a
6
+ * set of names distinguishes them, so this package used to rewrite the parsed tree itself,
7
+ * through internals the previous engine did not expose: a `setMeta('macro', …)` redirect
8
+ * that made a qualified call check and evaluate as something else, with a comprehension
9
+ * macro's `alternate` winning over `macro` unless cleared, and an rcall's asyncness derived
10
+ * from state the replaced checker filled in. Three facts about a dependency's internals,
11
+ * each pinned by a test, and the reason it was pinned to an exact version.
9
12
  *
10
- * A module's names are known from its own file before any import resolves — its
11
- * `imports:` keys, `Self`, its `metadata.name` and `Telo` — so the set is an
12
- * INPUT here rather than something this module derives. A call on a bare
13
- * identifier outside the set stays an ordinary method call, which is what keeps
14
- * the catalog's `format` and `Billing.format` from ever colliding, with one
15
- * catalog environment compiling both.
13
+ * `@telorun/cel` has **`qcall` as a node of its own**, produced by a total tree-to-tree pass
14
+ * over the name set — never by the parser, because the set is the host's — and a
15
+ * `CelExpression` records the set it was resolved under, so an environment refuses a tree
16
+ * resolved for a different site instead of answering a different question about it. So
17
+ * reading a module call is reading a node kind, and there is nothing to rewrite and nothing
18
+ * to pin.
16
19
  *
17
- * Two engine internals carry it, neither exposed by cel-js's typings — hence
18
- * the exact version pin and `tests/module-call.test.ts`, which fails the moment
19
- * an upgrade moves either:
20
- *
21
- * - `ASTNode.setMeta('macro', …)` redirects a node's check and evaluation. A
22
- * comprehension macro (`map`, `filter`, …) sets `alternate` instead, and
23
- * `alternate` WINS over `macro`, so a call the parser expanded as a macro
24
- * needs it cleared or the rewrite is silently ignored. The parser expands
25
- * those names BEFORE this rewrite and refuses any call whose arguments do not
26
- * fit the macro, so no function may take a macro's name
27
- * (`FUNCTION_NAME_RESERVED`); clearing keeps a call that did parse reported
28
- * as the module call it names.
29
- * - `async` must be set explicitly: cel-js derives it for an `rcall` from
30
- * `receiverWithArgs`, which only the rcall's own checker fills in — and ours
31
- * replaces it.
32
- *
33
- * The dispatch table is read from the activation under a key no CEL source can
34
- * spell, so nothing an author can write reaches the mechanism past the export
35
- * gate or the dependency edge. Binding the table is the kernel's, per scope;
36
- * until something binds one, evaluating a module call throws naming the
37
- * function.
20
+ * What is left here is Telo's half: the activation key the kernel binds a scope's table
21
+ * under, the unbound message, and the two questions the analyzer asks about a module's own
22
+ * names colliding with the expression's.
38
23
  */
39
- import type { ASTNode } from "@marcbachmann/cel-js";
24
+ import {
25
+ childNodes,
26
+ isIdentifierSpelling,
27
+ isReservedWord,
28
+ namespaceMacroBinding,
29
+ qualifiedCalls,
30
+ receiverMacroBinding,
31
+ RESERVED_NAMESPACES,
32
+ type CelNode,
33
+ } from "@telorun/cel";
40
34
 
41
35
  /**
42
- * Activation key the per-scope dispatch table is read from.
36
+ * Where a scope's dispatch table hangs on the activation.
43
37
  *
44
- * `@` and `:` are outside CEL's identifier grammar and there is no other way to
45
- * reach the activation, so no expression can name this — a spellable dispatcher
46
- * would let an author call past the export gate and past the dependency edge
47
- * that orders the callee before its caller.
38
+ * `@` and `:` are outside CEL's identifier grammar and the activation is reachable no other
39
+ * way, so no author can call past the export gate or the dependency edge. Binding the table
40
+ * is the kernel's, per owning scope; with none, evaluating a module call is refused.
48
41
  */
49
42
  export const MODULE_CALL_DISPATCH_KEY = "@telo:module-functions";
50
43
 
51
- /** Per-scope binding table: qualified name → the callable's `call`. */
44
+ /** A scope's module functions, keyed by qualified name. */
52
45
  export type ModuleCallDispatch = ReadonlyMap<string, (args: readonly unknown[]) => unknown>;
53
46
 
54
47
  /**
55
- * The CEL type a qualified call yields, as a type name (`"string"`,
56
- * `"list<int>"`), or undefined for "not known here".
57
- *
58
- * A hook rather than a table because the answer belongs to the analysis, not to
59
- * the expression: a signature is declared on a resource in the module the call
60
- * resolves through. With no resolver — every compile, and every analysis until
61
- * signatures are typed — a module call is `dyn`, which types its arguments and
62
- * claims nothing about its result.
48
+ * What the host says a module call's RESULT is, as a CEL type expression. The engine types
49
+ * the call node from it, so an operator over the call checks; absent, the call is `dyn`.
63
50
  */
64
51
  export type ModuleCallTypeResolver = (qualified: string) => string | undefined;
65
52
 
66
- /** cel-js internals this module drives. Structural, because the package's
67
- * typings expose neither `meta` nor `setMeta`. */
68
- interface MetaNode {
69
- readonly meta?: Record<string, unknown>;
70
- setMeta(key: string, value: unknown): MetaNode;
71
- }
72
-
73
- /** cel-js's `ASTNode` is a union over its operators, so it has no statically
74
- * known members to extend — the internals are read through this cast, in one
75
- * place. */
76
- const metaOf = (node: ASTNode): MetaNode => node as unknown as MetaNode;
77
-
78
- /** The macro record a resolved node carries. `teloModuleCall` is the brand every
79
- * reader tests — cel-js puts its own macros under the same key. */
80
- interface ModuleCallMacro {
81
- readonly teloModuleCall: true;
82
- readonly qualified: string;
83
- readonly args: readonly ASTNode[];
84
- /** Each argument's checked type name, recorded by the last type check. */
85
- argumentTypes?: readonly string[];
86
- typeCheck(chk: TypeCheckerLike, macro: ModuleCallMacro, ctx: unknown): unknown;
87
- evaluate(ev: EvaluatorLike, macro: ModuleCallMacro, ctx: ActivationLike): unknown;
88
- }
89
-
90
- interface TypeCheckerLike {
91
- readonly dynType: unknown;
92
- check(node: ASTNode, ctx: unknown): unknown;
93
- getType(name: string): unknown;
94
- }
95
-
96
- interface EvaluatorLike {
97
- eval(node: ASTNode, ctx: unknown): unknown;
98
- }
99
-
100
- interface ActivationLike {
101
- getValue(key: string): unknown;
102
- }
103
-
104
- /** What a resolved module call says about itself: the qualified name as
105
- * written, the argument nodes, and — once the tree has been type-checked — the
106
- * type the checker gave each argument. The single reader — no other surface
107
- * pattern-matches the macro's shape. */
53
+ /** What a resolved module call says about itself. */
108
54
  export interface ModuleCall {
109
55
  readonly qualified: string;
110
- readonly args: readonly ASTNode[];
111
- readonly argumentTypes?: readonly string[];
56
+ readonly args: readonly CelNode[];
112
57
  }
113
58
 
114
- export function moduleCallOf(node: ASTNode): ModuleCall | undefined {
115
- const macro = metaOf(node).meta?.macro as ModuleCallMacro | undefined;
116
- return macro?.teloModuleCall === true
117
- ? {
118
- qualified: macro.qualified,
119
- args: macro.args,
120
- ...(macro.argumentTypes ? { argumentTypes: macro.argumentTypes } : {}),
121
- }
122
- : undefined;
59
+ /** The module call this node IS, or nothing. One node kind, no pattern-matching. */
60
+ export function moduleCallOf(node: CelNode): ModuleCall | undefined {
61
+ if (node.kind !== "qcall") return undefined;
62
+ return { qualified: `${node.namespace}.${node.name}`, args: node.args };
123
63
  }
124
64
 
125
- /** Message for a call nothing has bound. Not a fallback value: a call that
126
- * cannot reach its function has no result, and inventing one would make a
127
- * missing export read as a null. */
65
+ /**
66
+ * Message for a call nothing has bound. Not a fallback value: a call that cannot reach its
67
+ * function has no result, and inventing one would make a missing export read as a null.
68
+ */
128
69
  export function unboundModuleCallMessage(qualified: string): string {
129
70
  const dot = qualified.indexOf(".");
130
71
  const receiver = qualified.slice(0, dot);
@@ -136,234 +77,130 @@ export function unboundModuleCallMessage(qualified: string): string {
136
77
  );
137
78
  }
138
79
 
139
- const NO_NAMES: ReadonlySet<string> = new Set();
140
-
141
80
  /**
142
- * Rewrite every module call in `ast` in place and report them in source order.
81
+ * Which of a module's own names CEL can read as a namespace.
82
+ *
83
+ * **A module name and an import alias are YAML scalars nothing lexes where they are
84
+ * written** — `my-module`, `test-run` and `cel` all reach a name set, and the naming
85
+ * diagnostics (`INVALID_NAME`, `INVALID_TYPE_NAME`) are what report them. The engine refuses
86
+ * such a name at registration and refuses the SET WHOLE, so handing one over unfiltered
87
+ * turns a reportable name into a crash that loses every other diagnostic in the file. A name
88
+ * CEL cannot read as a namespace resolves no call, which is exactly what the naming
89
+ * diagnostic says is wrong with it.
143
90
  *
144
- * Returns the qualified names as written (`["Billing.format", "Self.y"]`), which
145
- * is what a compiled value carries so no consumer has to re-parse to learn what
146
- * an expression calls. Idempotent: a node already resolved is rewritten once and
147
- * reported again, so two passes over one tree agree about what it calls.
91
+ * It is here rather than in a consumer because the module-name set is this package's concept
92
+ * — `CompileEnv.moduleNames` — and three callers need the same answer: compiling an
93
+ * expression, the analyzer's typed site environments, and the kernel's type-rule conditions.
148
94
  */
149
- export function resolveModuleCalls(
150
- ast: ASTNode | undefined,
151
- moduleNames: ReadonlySet<string> = NO_NAMES,
152
- typeOf?: ModuleCallTypeResolver,
153
- ): string[] {
154
- const calls: string[] = [];
155
- if (ast && moduleNames.size > 0) visit(ast, moduleNames, typeOf, calls);
156
- return calls;
157
- }
158
-
159
- function visit(
160
- node: ASTNode,
161
- moduleNames: ReadonlySet<string>,
162
- typeOf: ModuleCallTypeResolver | undefined,
163
- calls: string[],
164
- ): void {
165
- // Already resolved: rewritten once, reported every time, so the return value
166
- // is what the TREE calls rather than what this pass happened to change.
167
- const resolved = moduleCallOf(node);
168
- if (resolved) {
169
- calls.push(resolved.qualified);
170
- for (const arg of resolved.args) visit(arg, moduleNames, typeOf, calls);
171
- return;
172
- }
173
-
174
- const receiver = moduleCallReceiver(node, moduleNames);
175
- if (receiver) {
176
- const [method, , args] = node.args as [string, ASTNode, ASTNode[]];
177
- const qualified = `${receiver}.${method}`;
178
- calls.push(qualified);
179
- rewrite(node, qualified, args, typeOf);
180
- // The receiver names a MODULE, not a value, so it is not descended into:
181
- // that is what keeps it out of every access chain, out of `refs`, and out
182
- // of the undeclared-root check.
183
- for (const arg of args) visit(arg, moduleNames, typeOf, calls);
184
- return;
95
+ export function celNamespaceNames(moduleNames: Iterable<string>): ReadonlySet<string> {
96
+ const usable = new Set<string>();
97
+ for (const name of moduleNames) {
98
+ if (!isIdentifierSpelling(name) || isReservedWord(name)) continue;
99
+ if (RESERVED_NAMESPACES.includes(name)) continue;
100
+ usable.add(name);
185
101
  }
186
- descend(node, (child) => visit(child, moduleNames, typeOf, calls));
102
+ return usable;
187
103
  }
188
104
 
189
- /** The module name a node's receiver is, or undefined when the node is not a
190
- * module call. `a.b.c(x)` is not one — its receiver is a member access, not a
191
- * bare identifier. */
192
- function moduleCallReceiver(
193
- node: ASTNode,
194
- moduleNames: ReadonlySet<string>,
195
- ): string | undefined {
196
- if (node.op !== "rcall" || !Array.isArray(node.args)) return undefined;
197
- const [method, receiver, args] = node.args as [unknown, unknown, unknown];
198
- if (typeof method !== "string" || !Array.isArray(args)) return undefined;
199
- if (!isNode(receiver) || receiver.op !== "id") return undefined;
200
- const name = receiver.args as string;
201
- return moduleNames.has(name) ? name : undefined;
202
- }
203
-
204
- function rewrite(
205
- node: ASTNode,
206
- qualified: string,
207
- args: readonly ASTNode[],
208
- typeOf: ModuleCallTypeResolver | undefined,
209
- ): void {
210
- const macro: ModuleCallMacro = {
211
- teloModuleCall: true,
212
- qualified,
213
- args,
214
- typeCheck(chk, m, ctx) {
215
- // The arguments are checked in the CURRENT context, so a mistake inside
216
- // one is reported where it is written — and each argument's type is kept,
217
- // so whoever knows the callee's signature can compare against it.
218
- m.argumentTypes = m.args.map((arg) => typeNameOf(chk.check(arg, ctx)));
219
- // cel-js derives an rcall's asyncness from `receiverWithArgs`, which only
220
- // the rcall checker this macro replaces fills in — so it is stated: the
221
- // dispatch is synchronous, so the node is async exactly when one of its
222
- // arguments is. Asked only now, once each argument is checked: an
223
- // argument's answer is cached on first reading, and read before its own
224
- // check it is the conservative `true` for every operator and call.
225
- metaOf(node).setMeta(
226
- "async",
227
- m.args.some((arg) => (arg as { maybeAsync?: boolean }).maybeAsync === true),
228
- );
229
- const declared = typeOf?.(m.qualified);
230
- return declared === undefined ? chk.dynType : chk.getType(declared);
231
- },
232
- evaluate(ev, m, ctx) {
233
- const table = ctx.getValue(MODULE_CALL_DISPATCH_KEY) as ModuleCallDispatch | undefined;
234
- const fn = table?.get(m.qualified);
235
- if (!fn) throw new Error(unboundModuleCallMessage(m.qualified));
236
- const values = m.args.map((arg) => ev.eval(arg, ctx));
237
- // A callable's `call` is synchronous; an ARGUMENT need not be, and every
238
- // other dispatch in cel-js settles its operands first. Handing a pending
239
- // Promise to the function instead would pass it a value of the wrong type
240
- // with nothing reported.
241
- return values.some((value) => value instanceof Promise)
242
- ? Promise.all(values).then((settled) => fn(settled))
243
- : fn(values);
244
- },
245
- };
246
- metaOf(node)
247
- // A comprehension macro expands into an `alternate`, which cel-js consults
248
- // BEFORE `macro`. Left in place, `Billing.map(i, i)` would evaluate as a
249
- // comprehension over an identifier rather than as the module call it names.
250
- .setMeta("alternate", undefined)
251
- .setMeta("macro", macro);
252
- }
105
+ const NO_NAMES: ReadonlySet<string> = new Set();
253
106
 
254
- /** Every resolved module call in `ast` with its node, outermost first. */
255
- export function moduleCallNodes(ast: ASTNode | undefined): Array<{ node: ASTNode; call: ModuleCall }> {
256
- const out: Array<{ node: ASTNode; call: ModuleCall }> = [];
257
- if (ast) walk(ast);
107
+ /** Every resolved module call in the tree with its node, outermost first. */
108
+ export function moduleCallNodes(
109
+ root: CelNode | undefined,
110
+ ): Array<{ node: CelNode; call: ModuleCall }> {
111
+ const out: Array<{ node: CelNode; call: ModuleCall }> = [];
112
+ if (root) walk(root);
258
113
  return out;
259
114
 
260
- function walk(node: ASTNode): void {
115
+ function walk(node: CelNode): void {
261
116
  const call = moduleCallOf(node);
262
- if (call) {
263
- out.push({ node, call });
264
- for (const arg of call.args) walk(arg);
265
- return;
266
- }
267
- descend(node, walk);
117
+ if (call) out.push({ node, call });
118
+ for (const child of childNodes(node)) walk(child);
268
119
  }
269
120
  }
270
121
 
271
- /** The name of a checker type object (`int`, `list<string>`), or `dyn` for one
272
- * that carries none. */
273
- function typeNameOf(type: unknown): string {
274
- const name = (type as { name?: unknown } | null | undefined)?.name;
275
- return typeof name === "string" ? name : "dyn";
122
+ /** Every qualified call's name, as written. */
123
+ export function moduleCallNames(root: CelNode | undefined): readonly string[] {
124
+ return root ? qualifiedCalls(root).map((call) => call.qualifiedName) : [];
276
125
  }
277
126
 
278
127
  /**
279
- * Bare identifiers used as a call receiver that resolved to NO module name.
128
+ * Bare identifiers that are the RECEIVER of an unresolved call (`dbb.query(1)`), so the
129
+ * caller reporting the root can ask whether such a name could denote a module at all rather
130
+ * than telling an author to add an `imports:` alias for a typo.
280
131
  *
281
- * `Foo.bar()` with no `Foo` import is an unknown identifier like any other, but
282
- * the repair is not the usual one — it needs an `imports:` alias, not a
283
- * different spelling — so the caller that reports the root says so.
132
+ * A call the name set resolved is a `qcall` and is not here — it names a module, so reading
133
+ * its receiver as a root would invent a dependency the expression never states.
284
134
  */
285
135
  export function unresolvedCallReceivers(
286
- ast: ASTNode | undefined,
136
+ root: CelNode | undefined,
287
137
  moduleNames: ReadonlySet<string> = NO_NAMES,
288
138
  ): Set<string> {
289
139
  const out = new Set<string>();
290
- if (ast) walk(ast);
140
+ if (root) walk(root);
291
141
  return out;
292
142
 
293
- function walk(node: ASTNode): void {
294
- if (moduleCallOf(node)) {
295
- for (const arg of (node.args as [string, ASTNode, ASTNode[]])[2]) walk(arg);
296
- return;
297
- }
298
- if (node.op === "rcall" && Array.isArray(node.args)) {
299
- const receiver = (node.args as [unknown, unknown, unknown])[1];
300
- if (isNode(receiver) && receiver.op === "id" && !moduleNames.has(receiver.args as string)) {
301
- out.add(receiver.args as string);
302
- }
143
+ function walk(node: CelNode): void {
144
+ if (
145
+ node.kind === "receiverCall" &&
146
+ node.receiver.kind === "ident" &&
147
+ !moduleNames.has(node.receiver.name)
148
+ ) {
149
+ out.add(node.receiver.name);
303
150
  }
304
- descend(node, walk);
151
+ for (const child of childNodes(node)) walk(child);
305
152
  }
306
153
  }
307
154
 
308
155
  /**
309
- * Names bound INSIDE the expression — a comprehension variable, a `cel.bind`
310
- * name — that collide with one of the module's names.
156
+ * Names bound INSIDE the expression — a comprehension variable, a `cel.bind` name — that
157
+ * collide with one of the module's names.
311
158
  *
312
- * Such a binding is unreachable through a call: `Billing.f(x)` inside it
313
- * resolves to the module, never to the bound value. Reported as a reserved name
314
- * rather than silently shadowed, which is the rule every other name in CEL
315
- * scope already follows.
159
+ * Such a binding is unreachable through a call: `Billing.f(x)` inside it resolves to the
160
+ * module, never to the bound value. Reported as a reserved name rather than silently
161
+ * shadowed, which is the rule every other name in CEL scope already follows.
162
+ *
163
+ * The binding forms come from the engine's own enumeration (`BINDING_FORMS`) rather than a
164
+ * list kept in step with it here — the previous spelling carried a hand-written set of
165
+ * comprehension method names, mirrored in a second file.
316
166
  */
317
167
  export function moduleNameBindings(
318
- ast: ASTNode | undefined,
168
+ root: CelNode | undefined,
319
169
  moduleNames: ReadonlySet<string> = NO_NAMES,
320
170
  ): string[] {
321
171
  const out: string[] = [];
322
- if (ast && moduleNames.size > 0) walk(ast);
172
+ if (root && moduleNames.size > 0) walk(root);
323
173
  return [...new Set(out)];
324
174
 
325
- function walk(node: ASTNode): void {
175
+ function walk(node: CelNode): void {
326
176
  const bound = boundNameOf(node);
327
177
  if (bound !== undefined && moduleNames.has(bound)) out.push(bound);
328
- descend(node, walk);
329
- }
330
- }
331
-
332
- /** The name a binding form introduces: `cel.bind(<name>, …)`'s first argument,
333
- * or a comprehension macro's iteration variable. */
334
- function boundNameOf(node: ASTNode): string | undefined {
335
- if (node.op !== "rcall" || !Array.isArray(node.args)) return undefined;
336
- if (moduleCallOf(node)) return undefined;
337
- const [method, receiver, args] = node.args as [unknown, unknown, unknown];
338
- if (!Array.isArray(args) || args.length === 0) return undefined;
339
- const first = args[0];
340
- if (!isNode(first) || first.op !== "id") return undefined;
341
- if (method === "bind") {
342
- return isNode(receiver) && receiver.op === "id" && receiver.args === "cel"
343
- ? (first.args as string)
344
- : undefined;
178
+ for (const child of childNodes(node)) walk(child);
345
179
  }
346
- return COMPREHENSION_METHODS.has(method as string) ? (first.args as string) : undefined;
347
180
  }
348
181
 
349
- /** cel-js's comprehension macros, which bind their first argument as the
350
- * iteration variable. Mirrors the set `analyze.ts` walks with. */
351
- const COMPREHENSION_METHODS = new Set(["filter", "map", "exists", "all", "exists_one"]);
352
-
353
- /** Generic descent over a node's operands — an array, a single node, or an
354
- * array of arrays (a map literal's entries). */
355
- function descend(node: ASTNode, fn: (child: ASTNode) => void): void {
356
- const args = node.args as unknown;
357
- if (Array.isArray(args)) {
358
- for (const arg of args) {
359
- if (isNode(arg)) fn(arg);
360
- else if (Array.isArray(arg)) for (const item of arg) if (isNode(item)) fn(item);
361
- }
362
- return;
363
- }
364
- if (isNode(args)) fn(args);
365
- }
366
-
367
- function isNode(v: unknown): v is ASTNode {
368
- return v !== null && typeof v === "object" && "op" in (v as Record<string, unknown>);
182
+ /**
183
+ * The name a binding form introduces: a comprehension macro's iteration variable, or
184
+ * `cel.bind(<name>, …)`'s first argument.
185
+ *
186
+ * **The binding is asked of the engine by NAME AND ARITY.** `BINDING_FORMS` is a list of
187
+ * `"map/2"`, `"map/3"`, `"cel.bind/3"` — a bare `"map"` matches none of them, so a set over
188
+ * the list and a `.has(node.name)` test silently never fires.
189
+ *
190
+ * **And `cel` is a RESERVED namespace** (`cel`, `optional`), which a host can never claim —
191
+ * so `cel.bind(c, …)` is not a qualified call at all: it reads as a receiver call on the
192
+ * ident `cel`, which is in no scope and never will be. Reading it as a `qcall` matches
193
+ * nothing, and the cost is not just a missed binding: the bound name and the bare `cel` then
194
+ * leak out as member-access chains, so a comprehension variable is reported as an undeclared
195
+ * field and `cel` itself as an unknown identifier.
196
+ */
197
+ function boundNameOf(node: CelNode): string | undefined {
198
+ if (node.kind !== "receiverCall") return undefined;
199
+ const binding =
200
+ node.receiver.kind === "ident" && node.receiver.name === "cel"
201
+ ? namespaceMacroBinding("cel", node.name, node.args.length)
202
+ : receiverMacroBinding(node.name, node.args.length);
203
+ if (!binding) return undefined;
204
+ const held = node.args[binding.variableArgument];
205
+ return held?.kind === "ident" ? held.name : undefined;
369
206
  }
@@ -1,33 +1,34 @@
1
- import type { Environment } from "@marcbachmann/cel-js";
1
+ import type { CelEnvironment } from "@telorun/cel";
2
2
  import { VALUE_TYPES, valueBrandBases } from "@telorun/sdk";
3
3
 
4
4
  /**
5
- * Register every nominal value brand on an analysis environment, with what a
6
- * brand may do: convert to its base with the base's own conversion
7
- * (`int(ports.http)`, `string(variables.dataDir)`), render as text
8
- * (`string(ports.http)`), and — for a host path — be
9
- * extended with `.joinPath(relative)` and stay one.
5
+ * Register every nominal value brand on an analysis environment, with what a brand may do:
6
+ * convert to its base with the base's own conversion (`int(ports.http)`,
7
+ * `string(variables.dataDir)`), render as text (`string(ports.http)`), and — for a host
8
+ * path — be extended with `.joinPath(relative)` and stay one.
10
9
  *
11
- * Static only: at runtime a branded value IS its base (an int, a string), so the
12
- * catalog's own overloads — `string.joinPath` among them — are what evaluate. The
13
- * implementations below exist because registration requires one; a brand's
14
- * values never reach them. `buildCelEnvironment` registers none of this: a
15
- * caller typing a site registers the brands on its own clone.
10
+ * **Declared, not implemented.** A nominal type is a checking concept: the engine takes the
11
+ * conversions and members as signatures over `Self` and needs no function body for any of
12
+ * them, because at runtime a branded value IS its base (an int, a string) and the standard
13
+ * library's own overloads are what evaluate. The previous engine required an implementation
14
+ * per registration, so this file carried three stubs a brand's values never reached.
15
+ *
16
+ * `buildCelEnvironment` registers none of it: a caller typing a site registers the brands on
17
+ * its own clone.
16
18
  */
17
- export function registerValueBrands(env: Environment): void {
19
+ export function registerValueBrands(environment: CelEnvironment): void {
18
20
  for (const [brand, base] of Object.entries(valueBrandBases())) {
19
- (env as any).registerType(brand, { fields: {} });
20
- (env as any).registerFunction(`${base}(${brand}): ${base}`, (value: unknown) => value);
21
- // Every base CEL can render as text renders its brand too — the runtime
22
- // value IS the base — so `string(ports.http)` and a port in an
23
- // `!interpolate` hole convert as the integer they are.
24
- if (base !== "string") {
25
- (env as any).registerFunction(`string(${brand}): string`, (value: unknown) => String(value));
26
- }
27
- if (VALUE_TYPES.get(brand)?.fromHost !== undefined) {
28
- (env as any).registerFunction(`${brand}.joinPath(string): ${brand}`, () => {
29
- throw new Error("joinPath() is evaluated by the runtime, not the analyzer.");
30
- });
31
- }
21
+ const conversions = [`${base}(Self): ${base}`];
22
+ // Every base CEL can render as text renders its brand too — the runtime value IS the
23
+ // base — so `string(ports.http)` and a port in an `!interpolate` hole convert as the
24
+ // integer they are.
25
+ if (base !== "string") conversions.push("string(Self): string");
26
+ const fromHost = VALUE_TYPES.get(brand)?.fromHost !== undefined;
27
+ environment.registerType({
28
+ name: brand,
29
+ base,
30
+ conversions,
31
+ ...(fromHost ? { members: ["Self.joinPath(string): Self"] } : {}),
32
+ });
32
33
  }
33
34
  }
@@ -5,18 +5,37 @@ import type { CallAudit } from "./diagnose.js";
5
5
  /** Every code the `!cel`, `!interpolate` and `!sql` engines emit: `diagnostics`
6
6
  * from `analyze`, `errors` thrown by compiling or evaluating. Stated once here;
7
7
  * the types below hold every emit site to it, and the conformance runner
8
- * requires a `verdicts.json` row for each. */
8
+ * requires a `verdicts.json` row for each.
9
+ *
10
+ * **Four codes the ENGINE decides are deliberately absent**, because these engines cannot
11
+ * reach them and a code no row can pin is a claim the gate can never satisfy:
12
+ * `FUNCTION_UNRESOLVED`, `FUNCTION_ARITY_MISMATCH` and `FUNCTION_ARGUMENT_MISMATCH` need a
13
+ * namespace declared CLOSED and with a parameter list, and a module's names are registered
14
+ * open and withhold their parameters on purpose — whether a call reaches a function, and
15
+ * whether its arity and arguments fit, rest on the export gate, the dependency edge and a
16
+ * JSON Schema per parameter, which are the analyzer's verdicts. `CEL_TYPE_ARGUMENT_MISMATCH`
17
+ * needs a parameterized value type on both sides, and the brands registered here are
18
+ * nominal with a base and no parameters. Each is still reported where it IS decided — by
19
+ * the analyzer, against its own environment. */
9
20
  export const CEL_VERDICT_CODES = {
10
21
  diagnostics: [
11
22
  "BINDING_NAME_RESERVED",
12
23
  "CEL_INVALID_ARGUMENT",
13
24
  "CEL_NULLABLE_ACCESS",
14
25
  "CEL_SYNTAX_ERROR",
26
+ "CEL_TYPE_ARGUMENT_MISMATCH",
15
27
  "CEL_TYPE_ERROR",
16
28
  "CEL_UNKNOWN_FIELD",
17
29
  "CEL_UNKNOWN_FUNCTION",
18
30
  "CEL_UNKNOWN_IDENTIFIER",
19
31
  "CEL_WRONG_CALL_FORM",
32
+ // Forwarded from the engine's checker, which decides them. Whether a module call
33
+ // REACHES a function, and whether its arity and arguments fit, is still the analyzer's
34
+ // verdict against its own environment — these engines register a module's names open and
35
+ // withhold their parameters, so they pass the engine's codes through rather than deciding.
36
+ "FUNCTION_ARGUMENT_MISMATCH",
37
+ "FUNCTION_ARITY_MISMATCH",
38
+ "FUNCTION_UNRESOLVED",
20
39
  "INTERPOLATION_HOLE_NOT_CONVERTIBLE",
21
40
  ],
22
41
  errors: ["ERR_INTERPOLATION_HOLE_NOT_CONVERTIBLE"],
package/src/engine.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Environment } from "@marcbachmann/cel-js";
1
+ import type { CelEnvironment } from "@telorun/cel";
2
2
  import type { CompiledValue } from "@telorun/sdk";
3
3
  import type { ModuleCallFlags } from "./cel/diagnose.js";
4
4
  import type { ModuleCallTypeResolver } from "./cel/module-call.js";
@@ -7,7 +7,7 @@ import type { ModuleCallTypeResolver } from "./cel/module-call.js";
7
7
  * parse against a CEL environment (the `cel` engine) read it from `celEnv`;
8
8
  * engines that resolve fully at compile time (`literal`) ignore it. */
9
9
  export interface CompileEnv {
10
- readonly celEnv: Environment;
10
+ readonly celEnv: CelEnvironment;
11
11
  /**
12
12
  * The names a call's receiver may be for the call to resolve as a MODULE
13
13
  * call — the declaring module's `imports:` keys, `Self`, its `metadata.name`
@@ -33,7 +33,7 @@ export interface CompileEnv {
33
33
  * expression again against a different environment. One expression, one
34
34
  * verdict. */
35
35
  export interface AnalyzeEnv {
36
- readonly celEnv: Environment;
36
+ readonly celEnv: CelEnvironment;
37
37
  readonly contextSchema: Record<string, unknown> | null;
38
38
  /**
39
39
  * The caller vouches that `celEnv` declares EVERY name legal at this site, so
@@ -298,5 +298,5 @@ export interface TemplatingEngine {
298
298
  * they are equal without evaluating either. Absent on an engine that gives no
299
299
  * such verdict, which reads as "not repeatable". A source the engine cannot
300
300
  * read is not repeatable; `analyze` is what reports why. */
301
- repeatable?(source: string, celEnv: Environment): boolean;
301
+ repeatable?(source: string, celEnv: CelEnvironment): boolean;
302
302
  }