@telorun/templating 0.20.0 → 0.21.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 (40) hide show
  1. package/dist/cel/analyze.d.ts +26 -0
  2. package/dist/cel/analyze.d.ts.map +1 -1
  3. package/dist/cel/analyze.js +114 -8
  4. package/dist/cel/catalog.d.ts.map +1 -1
  5. package/dist/cel/catalog.js +10 -0
  6. package/dist/cel/compile.d.ts +9 -3
  7. package/dist/cel/compile.d.ts.map +1 -1
  8. package/dist/cel/compile.js +25 -11
  9. package/dist/cel/diagnose.d.ts +10 -1
  10. package/dist/cel/diagnose.d.ts.map +1 -1
  11. package/dist/cel/diagnose.js +42 -6
  12. package/dist/cel/environment.d.ts.map +1 -1
  13. package/dist/cel/environment.js +2 -0
  14. package/dist/cel/module-call.d.ts +108 -0
  15. package/dist/cel/module-call.d.ts.map +1 -0
  16. package/dist/cel/module-call.js +245 -0
  17. package/dist/cel/value-identity.d.ts +18 -0
  18. package/dist/cel/value-identity.d.ts.map +1 -0
  19. package/dist/cel/value-identity.js +25 -0
  20. package/dist/engine.d.ts +66 -0
  21. package/dist/engine.d.ts.map +1 -1
  22. package/dist/engines/cel.d.ts.map +1 -1
  23. package/dist/engines/cel.js +87 -6
  24. package/dist/engines/sql.d.ts.map +1 -1
  25. package/dist/engines/sql.js +5 -1
  26. package/dist/index.d.ts +3 -2
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +7 -1
  29. package/package.json +3 -3
  30. package/src/cel/analyze.ts +131 -9
  31. package/src/cel/catalog.ts +10 -0
  32. package/src/cel/compile.ts +32 -12
  33. package/src/cel/diagnose.ts +56 -6
  34. package/src/cel/environment.ts +3 -0
  35. package/src/cel/module-call.ts +369 -0
  36. package/src/cel/value-identity.ts +34 -0
  37. package/src/engine.ts +72 -0
  38. package/src/engines/cel.ts +104 -6
  39. package/src/engines/sql.ts +5 -1
  40. package/src/index.ts +20 -1
@@ -0,0 +1,369 @@
1
+ /**
2
+ * **A call whose receiver is one of the declaring module's names.**
3
+ *
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.
9
+ *
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.
16
+ *
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.
38
+ */
39
+ import type { ASTNode } from "@marcbachmann/cel-js";
40
+
41
+ /**
42
+ * Activation key the per-scope dispatch table is read from.
43
+ *
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.
48
+ */
49
+ export const MODULE_CALL_DISPATCH_KEY = "@telo:module-functions";
50
+
51
+ /** Per-scope binding table: qualified name → the callable's `call`. */
52
+ export type ModuleCallDispatch = ReadonlyMap<string, (args: readonly unknown[]) => unknown>;
53
+
54
+ /**
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.
63
+ */
64
+ export type ModuleCallTypeResolver = (qualified: string) => string | undefined;
65
+
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. */
108
+ export interface ModuleCall {
109
+ readonly qualified: string;
110
+ readonly args: readonly ASTNode[];
111
+ readonly argumentTypes?: readonly string[];
112
+ }
113
+
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;
123
+ }
124
+
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. */
128
+ export function unboundModuleCallMessage(qualified: string): string {
129
+ const dot = qualified.indexOf(".");
130
+ const receiver = qualified.slice(0, dot);
131
+ const fn = qualified.slice(dot + 1);
132
+ return (
133
+ `unbound function '${qualified}' — nothing is bound under that name in this scope. ` +
134
+ `'${receiver}' must be an imports: alias (or Self, or this module's own name) whose ` +
135
+ `module declares a callable named '${fn}' and exports it.`
136
+ );
137
+ }
138
+
139
+ const NO_NAMES: ReadonlySet<string> = new Set();
140
+
141
+ /**
142
+ * Rewrite every module call in `ast` in place and report them in source order.
143
+ *
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.
148
+ */
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;
185
+ }
186
+ descend(node, (child) => visit(child, moduleNames, typeOf, calls));
187
+ }
188
+
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
+ }
253
+
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);
258
+ return out;
259
+
260
+ function walk(node: ASTNode): void {
261
+ 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);
268
+ }
269
+ }
270
+
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";
276
+ }
277
+
278
+ /**
279
+ * Bare identifiers used as a call receiver that resolved to NO module name.
280
+ *
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.
284
+ */
285
+ export function unresolvedCallReceivers(
286
+ ast: ASTNode | undefined,
287
+ moduleNames: ReadonlySet<string> = NO_NAMES,
288
+ ): Set<string> {
289
+ const out = new Set<string>();
290
+ if (ast) walk(ast);
291
+ return out;
292
+
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
+ }
303
+ }
304
+ descend(node, walk);
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Names bound INSIDE the expression — a comprehension variable, a `cel.bind`
310
+ * name — that collide with one of the module's names.
311
+ *
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.
316
+ */
317
+ export function moduleNameBindings(
318
+ ast: ASTNode | undefined,
319
+ moduleNames: ReadonlySet<string> = NO_NAMES,
320
+ ): string[] {
321
+ const out: string[] = [];
322
+ if (ast && moduleNames.size > 0) walk(ast);
323
+ return [...new Set(out)];
324
+
325
+ function walk(node: ASTNode): void {
326
+ const bound = boundNameOf(node);
327
+ 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;
345
+ }
346
+ return COMPREHENSION_METHODS.has(method as string) ? (first.args as string) : undefined;
347
+ }
348
+
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>);
369
+ }
@@ -0,0 +1,34 @@
1
+ import { Environment } from "@marcbachmann/cel-js";
2
+ import { Duration, UnsignedInt } from "@telorun/sdk";
3
+
4
+ /** The classes the CEL value domain is typed by. */
5
+ export interface CelValueClasses {
6
+ readonly Duration: abstract new (...args: never[]) => unknown;
7
+ readonly UnsignedInt: abstract new (...args: never[]) => unknown;
8
+ }
9
+
10
+ /**
11
+ * Refuse to run with a CEL engine whose values are not the SDK's.
12
+ *
13
+ * cel-js dispatches by constructor, so a second installed copy of it gives the
14
+ * engine a `Duration` / `UnsignedInt` no controller can construct: every value a
15
+ * controller builds from `@telorun/sdk` would fail `+`, `type()` and every
16
+ * overload, at the first expression that meets one. Checked once, where the
17
+ * engine is loaded, so the cause is named before anything evaluates.
18
+ */
19
+ export function assertCelValueIdentity(classes: CelValueClasses): void {
20
+ const probe = new Environment();
21
+ const duration = probe.evaluate("duration('1s')");
22
+ const uint = probe.evaluate("1u");
23
+ if (duration instanceof classes.Duration && uint instanceof classes.UnsignedInt) return;
24
+ throw new Error(
25
+ "@telorun/templating's CEL engine is a different copy of @marcbachmann/cel-js than the one " +
26
+ "@telorun/sdk exports Duration and UnsignedInt from, so a duration or uint a controller " +
27
+ "builds would be rejected by every CEL expression. Two copies of @marcbachmann/cel-js are " +
28
+ "installed: every Telo package pins the same exact version, so deduplicate the install " +
29
+ "(`pnpm dedupe` / `npm dedupe`) until one remains.",
30
+ );
31
+ }
32
+
33
+ /** The SDK's classes — the identity every Telo package and controller shares. */
34
+ export const SDK_CEL_VALUE_CLASSES: CelValueClasses = { Duration, UnsignedInt };
package/src/engine.ts CHANGED
@@ -1,11 +1,25 @@
1
1
  import type { Environment } from "@marcbachmann/cel-js";
2
2
  import type { CompiledValue } from "@telorun/sdk";
3
+ import type { ModuleCallFlags } from "./cel/diagnose.js";
4
+ import type { ModuleCallTypeResolver } from "./cel/module-call.js";
3
5
 
4
6
  /** Compile-time environment passed to `engine.compile`. Engines that need to
5
7
  * parse against a CEL environment (the `cel` engine) read it from `celEnv`;
6
8
  * engines that resolve fully at compile time (`literal`) ignore it. */
7
9
  export interface CompileEnv {
8
10
  readonly celEnv: Environment;
11
+ /**
12
+ * The names a call's receiver may be for the call to resolve as a MODULE
13
+ * call — the declaring module's `imports:` keys, `Self`, its `metadata.name`
14
+ * and `Telo`.
15
+ *
16
+ * An INPUT, not something an engine derives: they are known from the module's
17
+ * own file before any import resolves, and a partial compiles with the names
18
+ * of the module that includes it. Absent means "no module names here", which
19
+ * leaves every call an ordinary catalog call — the reading every caller had
20
+ * before module functions existed.
21
+ */
22
+ readonly moduleNames?: ReadonlySet<string>;
9
23
  }
10
24
 
11
25
  /** Analyze-time environment passed to `engine.analyze`. The walker resolves
@@ -33,6 +47,38 @@ export interface AnalyzeEnv {
33
47
  * did before it existed.
34
48
  */
35
49
  readonly rootsDeclared?: boolean;
50
+
51
+ /** The declaring module's names — see {@link CompileEnv.moduleNames}. An
52
+ * analysis that does not supply them reads a module call as an ordinary
53
+ * method call, so the compile and analyze halves must be given the same set
54
+ * or they disagree about what the expression says. */
55
+ readonly moduleNames?: ReadonlySet<string>;
56
+
57
+ /** The type a module call yields, when the caller can resolve one. Absent
58
+ * leaves every module call `dyn` — its arguments are still checked where
59
+ * they are written, and nothing is claimed about its result. */
60
+ readonly moduleCallType?: ModuleCallTypeResolver;
61
+
62
+ /** The JSON Schema a module call's RESULT carries, when the caller can resolve
63
+ * one — what member access on the result (`Billing.total(xs).amont`) is
64
+ * checked against. Absent leaves such access unchecked. */
65
+ readonly moduleCallResult?: (qualified: string) => Record<string, unknown> | undefined;
66
+
67
+ /** The derived flags of the module function a qualified call reaches, carried
68
+ * onto its {@link CallSite} — boolean wherever the call resolves, so a
69
+ * consumer reading `deterministic === false` sees every impure one. */
70
+ readonly moduleCallFlags?: ModuleCallFlags;
71
+
72
+ /**
73
+ * Whether a bare identifier could denote a MODULE at all.
74
+ *
75
+ * The host's naming rule, which this package does not own: an unknown call
76
+ * receiver is repaired by an `imports:` alias only where the name could be
77
+ * one, and telling the author of `dbb.query(1)` to add an import is advice
78
+ * for a different mistake. Absent leaves the unknown-identifier message
79
+ * unqualified, which is what it says with no host rule to consult.
80
+ */
81
+ readonly couldNameModule?: (name: string) => boolean;
36
82
  }
37
83
 
38
84
  /** A mechanically applicable repair for a diagnostic. `replacement` is the
@@ -68,11 +114,26 @@ export interface EngineDiagnostic {
68
114
  * call), and policy that depends on manifest context does not belong in a
69
115
  * templating engine. */
70
116
  export interface CallSite {
117
+ /** The name called. For a module call this is the QUALIFIED name as written
118
+ * (`Billing.format`), which is what keeps a module function and a catalog
119
+ * function of the same bare name apart in every consumer that keys on it. */
71
120
  readonly name: string;
72
121
  /** How it was written — `f(x)` vs `x.f()`. */
73
122
  readonly form: "global" | "receiver";
123
+ /** Set when the receiver is one of the declaring module's names, so the call
124
+ * resolved to a module function rather than to the catalog. Its determinism
125
+ * and host-backedness are not this engine's to know — they follow from the
126
+ * callable the name resolves to — so they are carried only as the host's
127
+ * {@link AnalyzeEnv.moduleCallFlags} reports them. */
128
+ readonly moduleCall?: true;
74
129
  /** Argument count as written; excludes the receiver. */
75
130
  readonly arity: number;
131
+ /** For a module call, each argument as the analysis saw it: the type the
132
+ * checker gave it (absent when the expression did not type-check) and, when
133
+ * the argument is a plain member chain (`variables.price`), that chain — so a
134
+ * caller holding the callee's signature can compare a declared shape rather
135
+ * than a CEL type alone. */
136
+ readonly arguments?: readonly CallArgument[];
76
137
  /** Offsets of the whole call within the analyzed source. */
77
138
  readonly start: number;
78
139
  readonly end: number;
@@ -80,6 +141,17 @@ export interface CallSite {
80
141
  * name resolves to nothing, or to a function carrying no determinism
81
142
  * metadata — absent is not "deterministic". */
82
143
  readonly deterministic?: boolean;
144
+ /** Whether the resolved function is supplied by the host rather than written
145
+ * in CEL — a catalog function the kernel implements natively, or a module
146
+ * function reaching native code — so nothing without that host can run it.
147
+ * `undefined` under the same rule as {@link CallSite.deterministic}. */
148
+ readonly hostBacked?: boolean;
149
+ }
150
+
151
+ /** One argument of a module call. */
152
+ export interface CallArgument {
153
+ readonly type?: string;
154
+ readonly chain?: readonly string[];
83
155
  }
84
156
 
85
157
  /** What one `analyze` call establishes about one source. Everything derivable
@@ -1,11 +1,28 @@
1
+ import type { ASTNode } from "@marcbachmann/cel-js";
1
2
  import {
2
3
  extractAccessChains,
4
+ extractCallResultAccesses,
3
5
  findNullableAccessIssues,
6
+ INDEX_SEGMENT,
7
+ moduleCallArgumentChains,
4
8
  validateChainAgainstSchema,
5
9
  } from "../cel/analyze.js";
6
10
  import { compileExpression } from "../cel/compile.js";
7
11
  import { auditCalls, explainUnresolved } from "../cel/diagnose.js";
8
- import type { AnalyzeEnv, AnalyzeResult, EngineDiagnostic, TemplatingEngine } from "../engine.js";
12
+ import {
13
+ moduleCallNodes,
14
+ moduleNameBindings,
15
+ resolveModuleCalls,
16
+ unresolvedCallReceivers,
17
+ type ModuleCall,
18
+ } from "../cel/module-call.js";
19
+ import type {
20
+ AnalyzeEnv,
21
+ AnalyzeResult,
22
+ CallSite,
23
+ EngineDiagnostic,
24
+ TemplatingEngine,
25
+ } from "../engine.js";
9
26
 
10
27
  /** Statically analyze one CEL expression against the effective context schema:
11
28
  * parse → classify every call → type-check → validate member-access chains →
@@ -31,7 +48,27 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
31
48
  };
32
49
  }
33
50
 
34
- const audit = auditCalls(source, parsed.ast, env.celEnv);
51
+ // Resolution, before anything reads the tree — the audit, the type check and
52
+ // every chain walk below all see the resolved shape, so none of them has to
53
+ // know a module name from a variable.
54
+ // The walks that read resolved calls below are skipped when there are none.
55
+ const resolvedCalls = resolveModuleCalls(parsed.ast, env.moduleNames, env.moduleCallType).length > 0;
56
+
57
+ // A name bound inside the expression can never be read once a module owns it:
58
+ // `Billing.f(x)` under a comprehension variable named `Billing` resolves to
59
+ // the module. Reported rather than silently shadowed, the rule every other
60
+ // name in CEL scope follows.
61
+ for (const name of moduleNameBindings(parsed.ast, env.moduleNames)) {
62
+ out.push({
63
+ code: "BINDING_NAME_RESERVED",
64
+ message:
65
+ `'${name}' names a module here (an imports: alias, Self, or this module's own name), ` +
66
+ `so a call written '${name}.f(…)' resolves to that module and this binding could never ` +
67
+ `be read. Rename the bound variable.`,
68
+ });
69
+ }
70
+
71
+ const audit = auditCalls(source, parsed.ast, env.celEnv, env.moduleCallFlags);
35
72
 
36
73
  // Reported whatever the type-checker concludes. A literal argument a guard
37
74
  // will refuse is a defect the manifest states outright, and leaving it to the
@@ -42,7 +79,10 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
42
79
  let type: string | undefined;
43
80
  let checkError: string | undefined;
44
81
  try {
45
- const result = env.celEnv.check(source);
82
+ // `parsed.check()`, never `celEnv.check(source)`: the latter RE-PARSES, so
83
+ // it would type a tree in which no module call was ever resolved — every
84
+ // one of them reported as a missing method on an unknown receiver.
85
+ const result = parsed.check();
46
86
  if (result.valid) type = result.type;
47
87
  else if (result.error) {
48
88
  checkError = String((result.error as { message?: string }).message ?? result.error)
@@ -94,18 +134,46 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
94
134
  // Comprehension variables are not roots: `extractAccessChains` drops the
95
135
  // names a `.all(x, …)` binds, so the check never sees them.
96
136
  if (env.rootsDeclared) {
137
+ // A receiver that resolved to no module name AND could be one — the host
138
+ // decides the second half, since a name's level is its naming rule, not
139
+ // this engine's. `Foo.bar()` is an unknown identifier like any other, but
140
+ // its repair is an `imports:` alias rather than a different spelling, so it
141
+ // says so; `dbb.query(1)` is a misspelled value and gets no such advice.
142
+ // Walked only once a root is unknown, which a correct expression never has.
143
+ let callReceivers: Set<string> | undefined;
97
144
  const reported = new Set<string>();
98
145
  for (const chain of extractAccessChains(parsed.ast)) {
99
146
  const root = chain[0];
100
147
  if (!root || reported.has(root) || env.celEnv.hasVariable(root)) continue;
101
148
  reported.add(root);
149
+ callReceivers ??= unresolvedCallReceivers(parsed.ast, env.moduleNames);
102
150
  out.push({
103
151
  code: "CEL_UNKNOWN_IDENTIFIER",
104
- message: `unknown identifier '${root}' — nothing by that name is in scope here.`,
152
+ message:
153
+ `unknown identifier '${root}' — nothing by that name is in scope here.` +
154
+ (callReceivers.has(root) && env.couldNameModule?.(root) === true
155
+ ? ` To call a function another module declares, '${root}' must be one of this module's names — an 'imports:' alias, 'Self', or the module's own metadata.name.`
156
+ : ""),
105
157
  });
106
158
  }
107
159
  }
108
160
 
161
+ // A module call's result is typed by the callee's declared `returns`, which the
162
+ // caller resolves: member access on it is checked exactly as a read off the
163
+ // context would be, under the call as written.
164
+ if (resolvedCalls && env.moduleCallResult) {
165
+ for (const access of extractCallResultAccesses(parsed.ast)) {
166
+ const schema = env.moduleCallResult(access.qualified);
167
+ if (!schema) continue;
168
+ const label = `${access.qualified}(…)`;
169
+ const err = validateChainAgainstSchema([label, ...access.members], {
170
+ type: "object",
171
+ properties: { [label]: schema },
172
+ });
173
+ if (err) out.push({ code: "CEL_UNKNOWN_FIELD", message: err });
174
+ }
175
+ }
176
+
109
177
  if (env.contextSchema) {
110
178
  const contextSchema = env.contextSchema as Record<string, any>;
111
179
  for (const chain of extractAccessChains(parsed.ast)) {
@@ -124,7 +192,37 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
124
192
  }
125
193
  }
126
194
 
127
- return { diagnostics: out, calls: audit.calls, ...(type === undefined ? {} : { type }) };
195
+ return {
196
+ diagnostics: out,
197
+ calls: resolvedCalls ? withCallArguments(audit.calls, parsed.ast) : audit.calls,
198
+ ...(type === undefined ? {} : { type }),
199
+ };
200
+ }
201
+
202
+ /** The audited call sites, each module call carrying its arguments as the type
203
+ * check saw them. Matched by position, which is what identifies one call among
204
+ * several of the same name. */
205
+ function withCallArguments(calls: readonly CallSite[], ast: ASTNode): CallSite[] {
206
+ const byStart = new Map<number, ModuleCall>();
207
+ for (const { node, call } of moduleCallNodes(ast)) byStart.set(node.start, call);
208
+ const chainsByStart = new Map<number, Array<string[] | null>>();
209
+ for (const [node, chains] of moduleCallArgumentChains(ast)) chainsByStart.set(node.start, chains);
210
+ return calls.map((site) => {
211
+ const call = site.moduleCall ? byStart.get(site.start) : undefined;
212
+ if (!call) return site;
213
+ const chains = chainsByStart.get(site.start);
214
+ return {
215
+ ...site,
216
+ arguments: call.args.map((arg, index) => {
217
+ const type = call.argumentTypes?.[index];
218
+ const chain = chains?.[index] ?? null;
219
+ return {
220
+ ...(type !== undefined ? { type } : {}),
221
+ ...(chain && !chain.includes(INDEX_SEGMENT) ? { chain } : {}),
222
+ };
223
+ }),
224
+ };
225
+ });
128
226
  }
129
227
 
130
228
  /** `dyn` in a checker message means an operand whose type is unknown here —
@@ -144,7 +242,7 @@ export const celEngine: TemplatingEngine = {
144
242
  language: "cel",
145
243
 
146
244
  compile(source, env) {
147
- return compileExpression(source, env.celEnv);
245
+ return compileExpression(source, env.celEnv, env.moduleNames);
148
246
  },
149
247
 
150
248
  analyze(source, env) {