Skip to main content

bynk_emit/emitter/
project.rs

1//! The project-mode module builder (2.5b, #4090): `emit_project` and the helpers the
2//! driver, `compose/` and the emitters read (`call_handler_needs_exec`,
3//! `walk_unit_table_bodies`, `agent_cross_context_targets`, the agent registry and
4//! factory names). `emitter` re-exports the public ones.
5
6use std::path::Path;
7
8use bynk_ts::TsType;
9
10use super::boundary::emit_boundary_helpers;
11use super::ctx::UnitFacts;
12use super::ts_types::asset_ts_type;
13use super::{InternalFault, emit, ts_ident};
14use super::{
15    emit_agent, emit_capability, emit_consts, emit_consumed_type_reexports, emit_context_rebrands,
16    emit_cross_context_namespace_imports, emit_derived_capability, emit_free_fn,
17    emit_json_codec_helpers, emit_make_surface, emit_messages_bundle, emit_project_imports,
18    emit_provider, emit_service, emit_type, external_references_of, extra_import_stmts,
19    type_shape_for, used_external_names, write_commons_doc, write_header,
20};
21use crate::emit_model::EmitProjectCtx;
22use bynk_check::checker::CheckedProgram;
23use bynk_check::project_model::BuildTarget;
24use bynk_check::symbols::UnitTable;
25use bynk_model::walk_block_exprs;
26use bynk_model::{lower_capability_ops_ir, lower_protocol_ir, lower_service_handler_signature_ir};
27use bynk_project::UnitKind;
28use bynk_syntax::ast::{CommonsItem, Expr, ExprKind, FnName, MessagesDecl};
29
30/// Append one item's statements to `body`, giving the first the item's span: the checkpoint
31/// every line up to the next span maps back to.
32fn extend_with_span(
33    body: &mut Vec<bynk_ts::TsStmt>,
34    mut stmts: Vec<bynk_ts::TsStmt>,
35    span: bynk_syntax::span::Span,
36) {
37    if let Some(first) = stmts.first_mut() {
38        first.span = Some(span);
39    }
40    body.extend(stmts);
41}
42
43/// Emit TypeScript source for a single file inside a multi-file project,
44/// including cross-file and cross-commons imports computed from
45/// [`EmitProjectCtx`].
46/// Emit one unit's TypeScript, plus its source map (slice 1, ADR 0103).
47///
48/// `source_text` is the originating `.bynk` file's text and `source_name` its
49/// project-root-relative path; together they let the source-map builder resolve
50/// each recorded span to a `(line, col)` and embed `sourcesContent`. Returns the
51/// generated TS and the serialised source-map v3 JSON (`None` when nothing
52/// mapped — e.g. a unit whose items all came from sibling files).
53///
54/// 1A.34: a checker fact the emitter needed and did not find is an
55/// [`InternalFault`], not an `any`, an `undefined` or a panic. Lowering carries
56/// on past each, so the `Err` holds every fault of the unit; the program built
57/// alongside is then never used.
58pub fn emit_project(
59    program: &CheckedProgram,
60    ctx: &EmitProjectCtx,
61    source_text: &str,
62    source_name: &str,
63) -> Result<(bynk_ts::TsProgram, Option<String>), Vec<InternalFault>> {
64    let commons = program.program();
65    // #1486: no more `RefCell<SourceMapBuilder>` — every top-level item's
66    // own checkpoint is `stmt.span` on the first statement its own emitter
67    // returns, and `bynk_ts::print`'s own top-level loop (per #1477's own
68    // extension) records it, and merges any `nested_map` (body-bearing
69    // statements — service/agent handler bodies, `emit_free_fn`'s own body,
70    // …) at its real print-time offset, automatically. This replaces the
71    // old `smb.borrow_mut().record(out.len(), item.span)` + `print_stmt_
72    // and_merge`/`extend_printed_and_merged` dance below with the printer
73    // doing the same work at the one place (R7.4) it always should have.
74    let mut stmts: Vec<bynk_ts::TsStmt> = Vec::new();
75    // The body first: the names this file imports from elsewhere (a sibling file, a
76    // used commons, a consumed context) are the ones the body uses and does not
77    // declare, read off the tree below (1A.36b-2, #3737 Decision A).
78    let mut body: Vec<bynk_ts::TsStmt> = Vec::new();
79    body.extend(write_commons_doc(commons));
80    for item in &commons.commons.items {
81        if let CommonsItem::Type(t) = item {
82            let shape = type_shape_for(t, program);
83            let mut item_stmts = emit_type(t, &shape, commons, ctx);
84            if let Some(first) = item_stmts.first_mut() {
85                first.span = Some(t.span);
86            }
87            body.extend(item_stmts);
88        }
89    }
90    // Events track, slice 0 (spine #936): an `event` is checker-visible as
91    // a type (via `EventDecl::as_type_decl`, so exports/consumes/
92    // construction all worked from day one), but nothing emitted its actual
93    // TS declaration — this loop only ever matched `CommonsItem::Type`, so
94    // a subscriber importing an event type across contexts (`from
95    // Events(E)`, or `E` named in a cross-context signature) got a real
96    // `tsc` "has no exported member" error. Reuses the identical synthetic
97    // `TypeDecl` the checker already builds.
98    for item in &commons.commons.items {
99        if let CommonsItem::Event(e) = item {
100            let t = e.as_type_decl();
101            let shape = type_shape_for(&t, program);
102            let mut item_stmts = emit_type(&t, &shape, commons, ctx);
103            if let Some(first) = item_stmts.first_mut() {
104                first.span = Some(t.span);
105            }
106            body.extend(item_stmts);
107        }
108    }
109    // #1883, slice 1b: each asset is an exported constant holding its served
110    // URL, emitted before the functions so no top-level initializer can reach
111    // it before it is defined. It is typed with the structural `Asset` shape,
112    // so it reads the same as any other `Asset` value. A unit that `uses` this one imports it like a
113    // function (`record_name_ref`).
114    for item in &commons.commons.items {
115        if let CommonsItem::Asset(a) = item {
116            let url = ctx
117                .asset_served
118                .get(&bynk_check::assets::asset_key(a))
119                .cloned()
120                .unwrap_or_else(|| {
121                    panic!(
122                        "bynk internal error: asset `{}` reached emission without a served path",
123                        a.name.name
124                    )
125                });
126            body.push(bynk_ts::TsStmt::decl(
127                bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::ConstDecl {
128                    name: ts_ident(&a.name.name),
129                    ty: Some(asset_ts_type()),
130                    init: bynk_ts::TsExpr::object(vec![(
131                        "url".to_string(),
132                        bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Str(url)),
133                    )]),
134                })),
135                Some(a.span),
136            ));
137        }
138    }
139    // #2387, slice 2: each embed is an exported `string` constant holding its
140    // file's text, emitted before the functions for the same reason as an
141    // asset. A unit that `uses` this one imports it like a function
142    // (`record_name_ref`); the bundler drops one nothing references.
143    for item in &commons.commons.items {
144        if let CommonsItem::Embed(e) = item {
145            let key = bynk_project::assets::normalise_asset_path(&e.path);
146            let text = ctx.embed_text.get(&key).cloned().unwrap_or_else(|| {
147                panic!(
148                    "bynk internal error: embed `{}` reached emission without its text",
149                    e.name.name
150                )
151            });
152            body.push(bynk_ts::TsStmt::decl(
153                bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::ConstDecl {
154                    name: ts_ident(&e.name.name),
155                    ty: Some(TsType::named("string")),
156                    init: bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Str(text)),
157                })),
158                Some(e.span),
159            ));
160        }
161    }
162    // #2617: each constant is an exported, hoisted function, after the types
163    // and before the functions. A unit that `uses` this one, or a sibling
164    // file, imports it like a function (`record_name_ref`).
165    body.extend(emit_consts(commons, ctx));
166    for item in &commons.commons.items {
167        if let CommonsItem::Fn(f) = item
168            && let FnName::Free(_) = &f.name
169        {
170            let mut item_stmts = emit_free_fn(
171                f,
172                commons,
173                ctx.contracts,
174                &ctx.runtime_use,
175                &ctx.cross_context,
176                UnitFacts::of(ctx),
177            );
178            if let Some(first) = item_stmts.first_mut() {
179                first.span = Some(f.span);
180            }
181            body.extend(item_stmts);
182        }
183    }
184    // message-bundles slice 2 (#874): every `messages` block in the commons
185    // is emitted together, once, as a single multi-locale bundle — not
186    // per-item like the other behavioural kinds below — so the generated
187    // `render` can dispatch across every declared locale's own table rather
188    // than reading only the `@reference` one (slice 1's scope). Recorded at
189    // the `@reference` block's own span, matching how a single-item emission
190    // records at that item's span elsewhere in this loop.
191    let messages_blocks: Vec<&MessagesDecl> = commons
192        .commons
193        .items
194        .iter()
195        .filter_map(CommonsItem::as_messages)
196        .collect();
197    if let Some(reference) = messages_blocks
198        .iter()
199        .find(|m| m.annotations.iter().any(|a| a.name.name == "reference"))
200    {
201        let mut item_stmts = emit_messages_bundle(&messages_blocks, reference);
202        if let Some(first) = item_stmts.first_mut() {
203            first.span = Some(reference.span);
204        }
205        body.extend(item_stmts);
206    }
207    // v0.5: behavioural items follow the type/fn declarations.
208    for item in &commons.commons.items {
209        match item {
210            CommonsItem::Capability(c) if c.derived.is_some() => {
211                let mut item_stmts = emit_derived_capability(c, ctx);
212                if let Some(first) = item_stmts.first_mut() {
213                    first.span = Some(c.span);
214                }
215                body.extend(item_stmts);
216            }
217            CommonsItem::Capability(c) => {
218                // P6.x (#1193, slice 3 of #1187): `emit_capability` reads
219                // each op's resolved types off `ops`, not `c`'s own raw
220                // `TypeRef`s (Decision B, #1193) — no separate helper, this
221                // is `emit_capability`'s one and only call site.
222                let ops = lower_capability_ops_ir(c, program);
223                let mut item_stmts = emit_capability(c, &ops, commons, UnitFacts::of(ctx));
224                if let Some(first) = item_stmts.first_mut() {
225                    first.span = Some(c.span);
226                }
227                body.extend(item_stmts);
228            }
229            CommonsItem::Provider(p) => {
230                if let Some(item_stmts) = emit_provider(p, commons, ctx) {
231                    extend_with_span(&mut body, item_stmts, p.span);
232                }
233            }
234            CommonsItem::Service(s) => {
235                // #1187's slice 5: `emit_service` reads the protocol's own
236                // resolved data (`ProtocolIr`) and each handler's resolved
237                // signature (params/ret/effectful) instead of `s`'s own raw
238                // `ServiceProtocol`/`TypeRef`s — shape readers only, never
239                // a handler body (the full service/handler IR constructors
240                // that lowered bodies were deleted by Slices D1/D2 of
241                // #1542). No separate helper, this is `emit_service`'s one
242                // and only call site.
243                let protocol = lower_protocol_ir(&s.protocol, program);
244                let signatures: Vec<_> = s
245                    .handlers
246                    .iter()
247                    .map(|h| lower_service_handler_signature_ir(h, program))
248                    .collect();
249                let item_stmts = emit_service(s, &protocol, &signatures, commons, ctx);
250                extend_with_span(&mut body, item_stmts, s.span);
251            }
252            CommonsItem::Agent(a) => {
253                let state = emit::agent_state_ir(a, program);
254                let mut item_stmts = emit_agent(a, &state, commons, ctx, source_text);
255                if let Some(first) = item_stmts.first_mut() {
256                    first.span = Some(a.span);
257                }
258                body.extend(item_stmts);
259            }
260            CommonsItem::Type(_)
261            | CommonsItem::Fn(_)
262            | CommonsItem::Actor(_)
263            | CommonsItem::Messages(_)
264            | CommonsItem::Event(_)
265            | CommonsItem::Asset(_)
266            | CommonsItem::Embed(_)
267            | CommonsItem::Const(_) => {}
268        }
269    }
270    // v0.9.2: per-test registry reset. The test runner calls this before each
271    // test so a fresh test sees clean agent state (finding #10's "fresh per
272    // test" half).
273    let agent_names: Vec<&str> = commons
274        .commons
275        .items
276        .iter()
277        .filter_map(|i| match i {
278            CommonsItem::Agent(a) => Some(a.name.name.as_str()),
279            CommonsItem::Type(_)
280            | CommonsItem::Fn(_)
281            | CommonsItem::Capability(_)
282            | CommonsItem::Provider(_)
283            | CommonsItem::Service(_)
284            | CommonsItem::Actor(_)
285            | CommonsItem::Messages(_)
286            | CommonsItem::Event(_)
287            | CommonsItem::Asset(_)
288            | CommonsItem::Embed(_)
289            | CommonsItem::Const(_) => None,
290        })
291        .collect();
292    if !agent_names.is_empty() {
293        // Arc C, slice 30 (#1392): a real `TsDecl::Function`.
294        let reset_fn = bynk_ts::TsStmt::decl(
295            bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::Function {
296                name: "__resetAgents".to_string(),
297                generics: Vec::new(),
298                params: Vec::new(),
299                return_type: Some(bynk_ts::TsType::named("void")),
300                body: agent_names
301                    .iter()
302                    .map(|name| {
303                        bynk_ts::TsStmt::expr_stmt(
304                            bynk_ts::TsExpr::Call {
305                                callee: Box::new(bynk_ts::TsExpr::Member {
306                                    object: Box::new(bynk_ts::TsExpr::Ident(agent_registry_name(
307                                        name,
308                                    ))),
309                                    property: "reset".to_string(),
310                                }),
311                                args: Vec::new(),
312                            },
313                            None,
314                        )
315                    })
316                    .collect(),
317                is_async: false,
318                inline: false,
319            })),
320            None,
321        );
322        body.push(reset_fn);
323    }
324    // v0.6: cross-context surface assembly. Emit `__makeSurface` for any
325    // context that declares services — the composition root references it
326    // for every such context, not just those consumed by others. Skipped
327    // in workers mode where each Worker has its own `compose(env)` root.
328    if ctx.unit_kind == UnitKind::Context && matches!(ctx.target, BuildTarget::Bundle) {
329        let has_services = commons
330            .commons
331            .items
332            .iter()
333            .any(|i| matches!(i, CommonsItem::Service(_)));
334        if has_services {
335            body.extend(emit_make_surface(commons, ctx));
336        }
337    }
338    // v0.8: in workers mode, the context module also exports per-type
339    // serialise/deserialise helpers for every type that crosses a
340    // boundary. The commons modules likewise carry helpers for their
341    // own commons-declared boundary types.
342    // v0.96 (ADR 0124): runs on both targets — workers emits service-call +
343    // agent-rehydration boundary helpers; bundle emits only the agent-rehydration
344    // ones (the gate's deserialisers), since in-process calls need no wire codec.
345    let (boundary_stmts, boundary_names, boundary_insts) = emit_boundary_helpers(program, ctx);
346    // #1817: a boundary helper's `import` goes in the module's import block,
347    // not where the helpers are. A top-level use above the helpers (an agent's
348    // wire table names its codecs) otherwise ran before the import bound them
349    // once compiled to CommonJS: `ReferenceError: Cannot access … before
350    // initialization`.
351    let (mut boundary_imports, boundary_stmts): (Vec<_>, Vec<_>) = boundary_stmts
352        .into_iter()
353        .partition(|s| s.is_named_import());
354    body.extend(boundary_stmts);
355    // v0.22b: module-local codec helpers for this file's Json.encode/decode
356    // targets, deduped against the workers boundary helpers above.
357    let json_stmts = emit_json_codec_helpers(commons, ctx, &boundary_names, &boundary_insts);
358    body.extend(json_stmts);
359    // 1A.36b-2: what the module uses and does not declare, over the whole of it: the
360    // imports the driver adds for the Durable Object deps (`ctx.extra_imports`) and the
361    // boundary helpers' own imports bind names the body spells.
362    let used = {
363        let mut imports = extra_import_stmts(ctx);
364        imports.extend(boundary_imports.iter().cloned());
365        let bound = bynk_ts::TsProgram { stmts: imports }.imported_names();
366        used_external_names(commons, ctx, &body, &bound)
367    };
368    let references = external_references_of(&used, commons, ctx);
369    let mut project_imports = emit_project_imports(commons, ctx, &references);
370    let mut cross_context_imports = emit_cross_context_namespace_imports(commons, ctx, &used);
371    // #1486: the boundary between `emit_project_imports`'s own last
372    // statement and `emit_cross_context_namespace_imports`'s own first
373    // (when non-empty) must reproduce the pre-#1486 code's own unconditional
374    // rule exactly — no blank, *except* when `references` is non-empty,
375    // which wants exactly one separating "this file's own sibling imports"
376    // from "this file's cross-context namespace imports" — regardless of
377    // either side's real `TsStmtKind`, which the printer's automatic
378    // "no blank between adjacent imports" exemption cannot see through:
379    // `emit_project_imports`'s own last statement is not always a real
380    // import decl, and the printer's "no blank between adjacent imports"
381    // exemption only applies when both sides are. (Its `extra_imports` tail was
382    // pre-formatted `Raw` text until 1A.38a; it is import nodes now.)
383    if !cross_context_imports.is_empty() {
384        if references.is_empty() {
385            // Force the "no blank" default explicitly — the automatic
386            // exemption only reliably suppresses it when *both* sides are a
387            // real import decl, which is not guaranteed here.
388            cross_context_imports[0].no_blank_before = true;
389        } else {
390            // Force exactly one blank regardless of whether the automatic
391            // exemption would otherwise suppress it (both sides real import
392            // decls) or already supply it for free (either side `Raw`) —
393            // `no_blank_before` on both the spacer and the statement right
394            // after it suppresses the automatic policy on both sides,
395            // leaving only the spacer's own single rendered blank line.
396            let mut spacer = bynk_ts::TsStmt::blank(None);
397            spacer.no_blank_before = true;
398            project_imports.push(spacer);
399            cross_context_imports[0].no_blank_before = true;
400        }
401    }
402    stmts.extend(project_imports);
403    stmts.extend(cross_context_imports);
404    if let Some(first) = boundary_imports.first_mut() {
405        first.no_blank_before = true;
406    }
407    stmts.extend(boundary_imports);
408    // For contexts: emit per-context nominal rebrand aliases for each type
409    // imported via `uses` that this file references. The structural shape is
410    // inherited from the original commons type; the brand makes the
411    // rebranded type nominally distinct (v0.4 §6.2).
412    if ctx.unit_kind == UnitKind::Context {
413        stmts.extend(emit_context_rebrands(&references, commons, ctx));
414        stmts.extend(emit_consumed_type_reexports(&references, commons, ctx));
415    }
416    stmts.append(&mut body);
417    // #1476: `ctx.runtime_use` is fully populated now — every producer above has
418    // had its chance to note `bytes()`/`icu()` (`emitter::runtime_use`'s own doc:
419    // this used to key on `out.contains("<helper name>")`, wrong in both
420    // directions — a user string literal/doc comment false-positive, or an
421    // unrelated formatting change silently dropping a *required* import). Build
422    // the header — including its own runtime-import line, `bytes()`/`icu()`
423    // folded in directly rather than spliced in afterward — then prepend it.
424    // #1486: no more `shift_checkpoints` — every item's own checkpoint lives
425    // on `stmt.span`/`stmt.nested_map`, which travel with the statement
426    // itself; prepending the header is now ordinary `Vec` splicing, nothing
427    // to rebase.
428    let mut program_stmts = write_header(commons, ctx, &stmts);
429    // #1486: `write_header`'s own last statement (the runtime import, when
430    // the file has any commons items) sits directly adjacent to whatever
431    // `stmts` starts with — genuinely import-kind itself whenever
432    // `emit_project_imports` contributed any sibling/cross-unit imports,
433    // which exempts this boundary from the printer's automatic "no blank
434    // between adjacent imports" policy. This boundary always wants exactly
435    // one blank regardless (the pre-#1486 code's own unconditional-when-
436    // items-non-empty blank, replicated exactly), so it's forced the same
437    // way the project/cross-context import boundary above is, rather than
438    // relying on the automatic policy.
439    if !commons.commons.items.is_empty() {
440        let mut spacer = bynk_ts::TsStmt::blank(None);
441        spacer.no_blank_before = true;
442        program_stmts.push(spacer);
443        if let Some(first) = stmts.first_mut() {
444            first.no_blank_before = true;
445        }
446    } else if stmts.is_empty() {
447        // Review of #1486, finding 2: pre-conversion, `write_header`
448        // unconditionally seeded a trailing blank line after the banner
449        // regardless of whether the file had any commons items — the
450        // automatic policy alone reproduces that gap everywhere else (it
451        // fires between the banner and whatever `stmts` starts with), but
452        // not in this fully-degenerate case, where there is no later
453        // statement left for it to fire before. Restores the old trailing
454        // blank line this module's own output would otherwise lose.
455        program_stmts.push(bynk_ts::TsStmt::blank(None));
456    }
457    program_stmts.append(&mut stmts);
458    let mut program = bynk_ts::TsProgram {
459        stmts: program_stmts,
460    };
461    // 1A.36b-2: what the driver adds (`extra_imports`) and the boundary helpers bring in is
462    // there for a body that may never reach it, so each import is kept only if the tree uses it.
463    program.prune_unused_imports();
464    // The generated `file` name: the source basename with `.bynk` → `.ts`.
465    let generated_file = Path::new(source_name)
466        .file_stem()
467        .map(|s| format!("{}.ts", s.to_string_lossy()))
468        .unwrap_or_else(|| "module.ts".to_string());
469    let printed = bynk_ts::print(&program, source_name, source_text, &generated_file);
470    let faults = ctx.runtime_use.take_faults();
471    if faults.is_empty() {
472        Ok((program, printed.source_map))
473    } else {
474        Err(faults)
475    }
476}
477
478/// Whether a service's `on call` handler hands work to the execution context
479/// (`detach`, `within` or `race`, directly or through the functions it calls or
480/// names, #2719), so the Bundle target's `__makeSurface` deps must carry the
481/// execution context (`deps.__exec`) it forwards to the handler. The set is the
482/// checker's ([`bynk_check::exec_plan::ExecPlan`]), computed from what it
483/// resolved rather than by walking the syntax for method names.
484pub fn call_handler_needs_exec(
485    plan: &bynk_check::exec_plan::ExecPlan,
486    h: &bynk_syntax::ast::Handler,
487) -> bool {
488    matches!(h.kind, bynk_syntax::ast::HandlerKind::Call) && plan.handler_needs(h)
489}
490
491/// P6.48 (design/tracks/the-ir.md §6b): every handler/op body in `table` —
492/// every service handler, every agent handler, every provider op — visited
493/// via [`walk_block_exprs`]. The shared walk `project::unit_table_uses_emit`'s
494/// own `body_uses_emit` and `project::called_cross_context_services` each
495/// hand-rolled a separate copy of, over exactly the same three `UnitTable`
496/// collections in the same order. Lives here (already counted regardless by
497/// [`ast_importers`]) so those two `project.rs` callers need only a `&Expr`
498/// closure parameter, never a `&Block` or `&bynk_syntax::ast::Expr` of their
499/// own.
500pub(crate) fn walk_unit_table_bodies(table: &UnitTable, f: &mut impl FnMut(&Expr)) {
501    for service in table.services.values() {
502        for h in &service.handlers {
503            walk_block_exprs(&h.body, f);
504        }
505    }
506    for agent in table.agents.values() {
507        for h in &agent.handlers {
508            walk_block_exprs(&h.body, f);
509        }
510    }
511    for provider in table.providers.values() {
512        for op in &provider.ops {
513            walk_block_exprs(&op.body, f);
514        }
515    }
516}
517
518/// #1961: the consumed contexts an agent handler body calls a service of,
519/// read from the receivers' syntax (`B.svc(…)` / `Alias.svc(…)`) through
520/// `resolve` — `CrossContextInfo::resolve_prefix`, or its equivalent over the
521/// unit's `consumes`. A handler that constructs an agent hands its own `deps`
522/// to the agent's methods (#1960), so its `deps.env` type must name these, and
523/// the Worker must bind them. Syntactic because a file's `handlers.ts` is
524/// emitted before the unit's other files are checked; it over-counts only a
525/// local that shadows a consumed alias, which costs an unused binding.
526pub fn agent_cross_context_targets(
527    table: &UnitTable,
528    resolve: impl Fn(&str) -> Option<String>,
529) -> std::collections::BTreeSet<String> {
530    let mut out = std::collections::BTreeSet::new();
531    for agent in table.agents.values() {
532        for h in &agent.handlers {
533            walk_block_exprs(&h.body, &mut |e| {
534                if let ExprKind::MethodCall { receiver, .. } = &e.kind
535                    && let Some(chain) = emit::flatten_emit_ident_chain(receiver)
536                    && let Some(consumed) = resolve(&chain)
537                {
538                    out.insert(consumed);
539                }
540            });
541        }
542    }
543    out
544}
545
546/// The module-level state-registry constant name for an agent class.
547pub(super) fn agent_registry_name(agent: &str) -> String {
548    format!("__{agent}Registry")
549}
550
551/// The exported agent-construction factory name for an agent class.
552pub fn agent_factory_name(agent: &str) -> String {
553    format!("__make{agent}")
554}