Skip to main content

bynk_model/
lower.rs

1//! `bynk_model::lower` (the `bynk-lower` crate until crate-hygiene B1, #2939): the
2//! model's builder, the AST-analysis helpers `bynk-emit` reads resolved
3//! declaration-level facts through — handler kinds and `given` clauses,
4//! service protocols, store-field shapes, capability op and attached-method
5//! signatures, route cache/limit annotations, event-subscriber shapes, and
6//! the store-write walk behind `emit_agent`'s implicit-commit decision. Each
7//! takes a checked program (or its `TypedCommons`) and a syntax-tree node
8//! and returns a [`crate::vocabulary`] value; none lowers an expression body.
9//!
10//! **Reachability, corrected twice and now settled (Slice D0 of `#1542`,
11//! the IR cutover, closing summary in `design/archive/retired-tracks.md`).** Through the crate carve (Arc D,
12//! P7.12) this paragraph claimed nothing here was reached from `bynk-emit`'s
13//! emission path; that was false — `lower_event_subscriber_shapes_ir`
14//! (called from `bynk-emit/src/project.rs`) went through
15//! `lower_service_item_ir`, which lowers every handler's own *body*, so the
16//! whole recursive expression-lowering machinery (`lower_service_handler_ir`
17//! → `lower_service_handler_body_ir` → `lower_block_ir` → `lower_expr_ir`/
18//! `lower_stmt_ir`) ran in production for every `from Events(E)` service and
19//! had its result discarded. Slice D0 repointed that one caller at the
20//! shape-only helpers it actually needs (see its own doc comment), so the
21//! original claim is now *true* by construction rather than false by
22//! oversight: **every item constructor and the expression/statement/body
23//! lowering beneath it — `lower_service_item_ir`, `lower_agent_item_ir`,
24//! `lower_provider_item_ir`, `lower_fn_item_ir`, `lower_type_item_ir`,
25//! `lower_capability_item_ir`, the handler/store-field/commit-shape/
26//! invariant/transition helpers, `lower_fn_body_ir`, `lower_block_ir`,
27//! `lower_expr_ir` and everything they call — has no caller outside this
28//! crate's own test module.** The 30 August 2026 review's "zero callers"
29//! finding was right about the end state and wrong about the path; the
30//! track doc's §10.2 has the trace. Slice D1 of the same track then deleted
31//! that machinery outright — 48 functions, the lowering context's scope
32//! stack/temp counter/return-type/store-queryable fields, and every
33//! `todo!()` this crate ever carried — so `rustc`'s own dead-code analysis,
34//! not this paragraph, is the reachability record from here on. What stays
35//! is the AST-analysis helper vocabulary `bynk-emit` consumes today —
36//! `lower_handler_kind_ir`, `lower_handler_given_ir`,
37//! `lower_protocol_ir{,_from_commons}`, `lower_type_shape_ir`,
38//! `lower_service_handler_signature_ir`, `body_writes_state`, and their
39//! siblings — each with a production call site.
40//!
41//! **Totality discipline (ADR 0334, Q2), as it stands after Slice D1:** the
42//! rule was "every entry point takes a certified `&CheckedProgram`, so a
43//! per-expression type lookup that misses is a compiler bug, not a
44//! recoverable state." The per-expression lookup went with the expression
45//! lowering, so what the rule now governs is narrower: a helper that reads
46//! a *declaration's* own type references still takes `&CheckedProgram` by
47//! default (`lower_type_shape_ir`'s doc comment has the full argument — a
48//! bare `TypedCommons` is not certified by construction), and the four that
49//! take a bare `&TypedCommons` instead — `body_writes_state`,
50//! `lower_protocol_ir_from_commons`, `capability_op_sig_from_commons`,
51//! `lower_attached_fn_sig_ir_from_types` — each document why their reads
52//! cannot reach a certification-dependent panic. The same discipline
53//! `bynk-emit/src/emitter/emit.rs`'s `lower_workers_cross_context_call`
54//! applies to its own `bynk.emit.unresolved_cross_context_signature` panic.
55
56use std::collections::{HashMap, HashSet};
57use std::sync::Arc;
58
59use bynk_check::checker::{self, Callee, CheckedProgram, TyId, TypedCommons, Types};
60use bynk_check::resolver::MethodTable;
61use bynk_syntax::ast::{
62    ActorDecl, Block, CapRef, CapabilityDecl, CapabilityOp, CommonsItem, EventPattern,
63    EventPatternValue, Expr, ExprKind, FnDecl, FnName, Handler, HandlerKind, HttpMethod,
64    LiteralValue, MatchBody, ProviderDecl, QualifiedName, ServiceProtocol, Statement, StoreField,
65    TypeBody, TypeDecl, TypeRef, expr_children,
66};
67
68use crate::vocabulary::{
69    ActorSeamIr, CacheIr, CapRefIr, ConstVal, EventPatternIr, EventPatternValueIr,
70    EventSubscriberShape, FnSig, IrHandlerKind, IrHttpMethod, OpSig, ProtocolIr, StoreFieldIr,
71    StoreKindIr, TypeShape,
72};
73
74/// The resolution context the AST-analysis helpers below share: the checked
75/// program's own `TypedCommons` (for type interning and declared-type
76/// lookups) plus the enclosing fn/method's own rigid type variables
77/// (`fn identity[T](x: T)`, and a generic type's own params on one of its
78/// methods), needed by `resolve_type_ref_in` the same way `Ctx::type_vars`
79/// is (`bynk-check/src/checker.rs`); `resolve_type_ref` (no `vars` set)
80/// would otherwise resolve a rigid `T` as an unknown declared type and
81/// silently fail.
82///
83/// Slice D1 of `#1542` (the IR cutover, `design/archive/retired-tracks.md`) slimmed
84/// this from the expression lowerer's full context — the lexical scope
85/// stack, the synthetic-temp counter, the enclosing return type and the
86/// agent handler's store-queryable field set all went with the body
87/// lowering that was their only reader. What remains is exactly what a
88/// signature/shape reader needs.
89pub(crate) struct LowerIrCtx<'a> {
90    program: &'a TypedCommons,
91    type_vars: HashSet<String>,
92}
93
94impl<'a> LowerIrCtx<'a> {
95    fn new(program: &'a CheckedProgram, type_vars: HashSet<String>) -> Self {
96        Self::from_commons(program.program(), type_vars)
97    }
98
99    /// #1187's own closing scoping pass: a `TypedCommons`-only constructor,
100    /// for the call paths (`lower_op_sig_ir_from_commons` and
101    /// `lower_attached_fn_sig_ir_from_types`, below) that never have a
102    /// `&CheckedProgram` to unwrap. See `lower_op_sig_ir_from_commons`'s
103    /// own doc comment for why that is sound.
104    fn from_commons(commons: &'a TypedCommons, type_vars: HashSet<String>) -> Self {
105        Self {
106            program: commons,
107            type_vars,
108        }
109    }
110
111    /// A type reference resolved in this pass's own rigid-variable scope —
112    /// the `resolve_type_ref_in` counterpart to `Ctx::resolve_type_ref_in`
113    /// call sites (e.g. `checker.rs:2816,2897`), not the bare
114    /// `resolve_type_ref` (which has no `vars` set and cannot resolve a
115    /// generic fn/method's own type parameters).
116    fn resolve_type_ref(&self, r: &bynk_syntax::ast::TypeRef) -> Option<TyId> {
117        checker::resolve_type_ref_in(
118            r,
119            &self.program.types,
120            &self.type_vars,
121            &self.program.ty_intern,
122        )
123    }
124
125    /// [`Self::resolve_type_ref`] for a reference the checker has already
126    /// accepted. A miss is a compiler bug, so it stops with an internal error
127    /// naming the declaration and the type (active in release builds) rather
128    /// than substituting `()`, which would let the emitter generate code for a
129    /// declaration that takes or returns the wrong type.
130    ///
131    /// Every caller of the lowering functions that use this runs after
132    /// certification: they are reached only through `bynk-emit`, which the
133    /// driver invokes on a program that checked clean. `bynk-ide` and
134    /// `bynk-lsp` read `lower_handler_kind_ir` and the shape helpers, never these
135    /// signature readers, so a half-typed file cannot reach this path.
136    fn resolve_checked_type_ref(&self, r: &bynk_syntax::ast::TypeRef, what: &str) -> TyId {
137        self.resolve_type_ref(r).unwrap_or_else(|| {
138            panic!(
139                "bynk internal error: {what}: type `{}` does not resolve, but the checker \
140                 already accepted this declaration",
141                bynk_syntax::print::type_ref_to_string(r)
142            )
143        })
144    }
145}
146
147/// `(params, given, ret, effectful)` — [`lower_service_handler_signature_ir`]'s
148/// return shape (#1187's slice 5), a named alias rather than a bare tuple
149/// because its consumer (`emit_service`, `bynk-emit/src/emitter/emit.rs`)
150/// has to spell it out in a function signature. (The agent-handler
151/// signature reader that shared it went with Slice D1 of `#1542`.)
152pub type HandlerSignatureIr = (Vec<(String, TyId)>, Vec<String>, TyId, bool);
153
154/// P6.50 (design/tracks/the-ir.md §6b): a return type's own syntactic
155/// `Effect[...]` wrapper — `TypeRef::Effect(_, _)`, not the *resolved*
156/// `Ty::Effect(_)` shape `lower_handler_signature_ir` reads above via
157/// `cx.program.ty_intern`. Relocated here from `emitter/emit.rs` (its
158/// original home, `#[allow(dead_code)]`-free and with eight call sites
159/// across `emit.rs`/`workers.rs`/`workers_entry.rs`) because
160/// [`lower_service_handler_signature_ir`] below was already calling *up*
161/// into it (`bynk_emit::emitter::is_effectful_return`) — the `Ast → Ir` boundary
162/// running backwards, an `Ir`-side lowering function reaching into the
163/// `emitter` module it should only ever be called *from*. `emit.rs` and
164/// friends now call `bynk_model::is_effectful_return` instead (relocated
165/// again at the P7.12 crate carve — `emitter`/`ir::lower` are now separate
166/// crates, `bynk-emit`/`bynk-lower` respectively).
167pub fn is_effectful_return(r: &TypeRef) -> bool {
168    matches!(r, TypeRef::Effect(_, _))
169}
170
171/// A service handler's resolved *signature* — `params`/`given`/`ret`/
172/// `effectful` — and never its body. This is what `emit_service`
173/// (`bynk-emit/src/emitter/emit.rs`) reads per handler, and what
174/// `lower_event_subscriber_shapes_ir` reads for a subscriber's parameter
175/// count. Mirrors [`body_writes_state`]'s posture (#1196): a narrow,
176/// standalone reader of already-resolved data, applied to signature data
177/// instead of a body walk.
178///
179/// A resolve miss is an internal error (#3166): the resolver rejects an
180/// unknown handler parameter or return type (`bynk.resolve.unknown_type`), and
181/// only `bynk-emit` calls this, after certification.
182pub fn lower_service_handler_signature_ir(
183    h: &Handler,
184    program: &CheckedProgram,
185) -> HandlerSignatureIr {
186    let cx = LowerIrCtx::new(program, HashSet::new());
187    let params: Vec<(String, TyId)> = h
188        .params
189        .iter()
190        .map(|p| {
191            let ty = cx.resolve_checked_type_ref(
192                &p.type_ref,
193                &format!(
194                    "service handler at {:?}, parameter `{}`",
195                    h.span, p.name.name
196                ),
197            );
198            (p.name.name.clone(), ty)
199        })
200        .collect();
201    let given: Vec<String> = h.given.iter().map(|c| c.key().to_string()).collect();
202    let ret = cx.resolve_checked_type_ref(
203        &h.return_type,
204        &format!("service handler at {:?}, return type", h.span),
205    );
206    let effectful = is_effectful_return(&h.return_type);
207    (params, given, ret, effectful)
208}
209
210/// A `type` declaration's resolved structure as a [`TypeShape`] — the
211/// reader `emitter.rs`'s own `type_shape_for` calls directly. (Slice 1 of
212/// `#1542` split this out of a full `IrItem::Type` constructor whose single
213/// field it was, ending a build-then-`unreachable!`-discard round-trip;
214/// Slice D1 then deleted that constructor, leaving this as the type
215/// reader.)
216///
217/// Takes a certified `&CheckedProgram`, matching this module's own
218/// categorical discipline (this file's own header doc: "every entry point
219/// here takes a `&CheckedProgram`"), even though only
220/// `TypedCommons::types`/`ty_intern` are read — no per-expression
221/// `expr_types` lookup is involved (Q2, `design/tracks/the-ir.md` §3.2), but
222/// *which fields are read* isn't the discipline; *which failures are allowed
223/// to `panic!`* is. Every panic below asserts "the checker already accepted
224/// this declaration" — true only once `certify` has run: a bare
225/// `TypedCommons` is not certified by construction (`checker.rs`'s own
226/// `CheckedProgram` doc notes the project/batch path holds per-unit
227/// `TypedCommons` values *before* that unit's build-wide gate is decided),
228/// so accepting one here would make `resolve_type_ref_in` returning `None` a
229/// reachable, not just a buggy, outcome.
230pub fn lower_type_shape_ir(decl: &Arc<TypeDecl>, program: &CheckedProgram) -> TypeShape {
231    lower_type_shape_in(decl, program.program())
232}
233
234/// #3066: [`lower_type_shape_ir`] for a suite's own type, whose `TypedCommons`
235/// is the suite's view (the unit's, plus the suite's declarations) rather than a
236/// certified unit. The suite's declarations were checked by
237/// `test_suites::check_suite_decls` before emission is reached, which is the
238/// guarantee `certify` gives a unit.
239pub fn lower_suite_type_shape_ir(decl: &Arc<TypeDecl>, program: &TypedCommons) -> TypeShape {
240    lower_type_shape_in(decl, program)
241}
242
243fn lower_type_shape_in(decl: &Arc<TypeDecl>, program: &TypedCommons) -> TypeShape {
244    let type_vars: HashSet<String> = decl
245        .type_params
246        .iter()
247        .map(|tp| tp.name.name.clone())
248        .collect();
249    let resolve = |r: &bynk_syntax::ast::TypeRef| {
250        checker::resolve_type_ref_in(r, &program.types, &type_vars, &program.ty_intern)
251    };
252    match &decl.body {
253        TypeBody::Record(r) => TypeShape::Record {
254            fields: r
255                .fields
256                .iter()
257                .map(|f| {
258                    let ty = resolve(&f.type_ref).unwrap_or_else(|| {
259                        panic!(
260                            "bynk internal error (ADR 0334): field `{}` of type `{}` does not \
261                             resolve, but the checker already accepted this declaration",
262                            f.name.name, decl.name.name
263                        )
264                    });
265                    (f.name.name.clone(), ty)
266                })
267                .collect(),
268        },
269        TypeBody::Sum(s) => TypeShape::Sum {
270            variants: s
271                .variants
272                .iter()
273                .map(|v| {
274                    let payload = v
275                        .payload
276                        .iter()
277                        .map(|vf| {
278                            let ty = resolve(&vf.type_ref).unwrap_or_else(|| {
279                                panic!(
280                                    "bynk internal error (ADR 0334): field `{}` of variant `{}` \
281                                     of type `{}` does not resolve, but the checker already \
282                                     accepted this declaration",
283                                    vf.name.name, v.name.name, decl.name.name
284                                )
285                            });
286                            (vf.name.name.clone(), ty)
287                        })
288                        .collect();
289                    (v.name.name.clone(), payload)
290                })
291                .collect(),
292            embeds: s
293                .embeds
294                .iter()
295                .map(|e| {
296                    let source = resolve(&e.source_type).unwrap_or_else(|| {
297                        panic!(
298                            "bynk internal error (ADR 0334): `embeds` clause source type on \
299                             variant `{}` of type `{}` does not resolve, but the checker \
300                             already accepted this declaration",
301                            e.variant.name, decl.name.name
302                        )
303                    });
304                    (source, e.variant.name.clone())
305                })
306                .collect(),
307        },
308        TypeBody::Refined {
309            base, refinement, ..
310        } => TypeShape::Refined {
311            base: *base,
312            refinement: refinement.clone(),
313            opaque: false,
314        },
315        TypeBody::Opaque {
316            base, refinement, ..
317        } => TypeShape::Refined {
318            base: *base,
319            refinement: refinement.clone(),
320            opaque: true,
321        },
322    }
323}
324
325/// A store field's own element/key/value type, resolved with no rigid type
326/// variables in scope — `AgentDecl` carries no `type_params` of its own
327/// (its own struct shape, `bynk-syntax/src/ast.rs:908-934`), so
328/// [`lower_store_field_ir`] never needs the `fn_rigid_type_vars`-shaped
329/// seeding every fn/method-level constructor here does. Shared by every
330/// arm of that function's own kind dispatch, and by [`lower_store_field_shape_ir`].
331///
332/// A resolve miss is an internal error (#3166), not a silent `()`. It used to
333/// degrade, because `store x: Cell[Bogus] = "hello"` once certified (#1187's
334/// Agent state-field slice, step 0); since #1679 the resolver rejects an
335/// unknown store field type (`bynk.resolve.unknown_type`), so a miss now
336/// means the checker let something through.
337fn resolve_store_field_ty(cx: &LowerIrCtx, field: &str, r: &bynk_syntax::ast::TypeRef) -> TyId {
338    cx.resolve_checked_type_ref(r, &format!("store field `{field}`"))
339}
340
341/// A `@name(<duration literal>)` annotation's own millisecond value — the
342/// shared "find the annotation, read its first argument's `DurationLit`"
343/// step both `@ttl` (`Cache`) and `@retain` (`Log`) need, factored out so
344/// the two [`lower_store_field_ir`] arms are one call each rather than two
345/// near-identical inline `find`/`and_then` chains. Mirrors, but does not
346/// call, `cache_ttl_millis` (`bynk-check/src/context_checks.rs`) and the
347/// shipped emitter's own equivalent extraction (`emit.rs`'s
348/// `store_cache_fields`/`store_log_fields`) — those thread a
349/// `&mut Vec<CompileError>` for a missing-`@ttl` diagnostic and are private
350/// to their own module, so reusing them directly here is not architecturally
351/// available; see [`lower_store_field_ir`]'s own doc comment for why this is
352/// an accepted, named duplication rather than a gap this slice closes.
353fn duration_millis_annotation(
354    annotations: &[bynk_syntax::ast::Annotation],
355    name: &str,
356) -> Option<i64> {
357    annotations
358        .iter()
359        .find(|a| a.name.name == name)
360        .and_then(|a| match a.args.first().map(|arg| &arg.value.kind) {
361            Some(ExprKind::DurationLit { millis, .. }) => Some(*millis),
362            _ => None,
363        })
364}
365
366/// The shape half of [`lower_store_field_ir`] — its `kind`/`indexed`
367/// computation, factored out so [`lower_store_field_shape_ir`] can share it
368/// without either duplicating the `Cell`/`Map`/`Set`/`Cache`/`Log` dispatch
369/// or paying for a `&mut LowerIrCtx` it never needs (nothing here lowers an
370/// expression).
371fn store_field_kind_and_indexed(f: &StoreField, cx: &LowerIrCtx) -> (StoreKindIr, Vec<String>) {
372    let head = f.kind.head.name.as_str();
373    let kind = match head {
374        "Cell" => StoreKindIr::Cell(resolve_store_field_ty(cx, &f.name.name, &f.kind.args[0])),
375        "Map" => StoreKindIr::Map(
376            resolve_store_field_ty(cx, &f.name.name, &f.kind.args[0]),
377            resolve_store_field_ty(cx, &f.name.name, &f.kind.args[1]),
378        ),
379        "Set" => StoreKindIr::Set(resolve_store_field_ty(cx, &f.name.name, &f.kind.args[0])),
380        "Cache" => {
381            let k = resolve_store_field_ty(cx, &f.name.name, &f.kind.args[0]);
382            let v = resolve_store_field_ty(cx, &f.name.name, &f.kind.args[1]);
383            let ttl = duration_millis_annotation(&f.annotations, "ttl").unwrap_or_else(|| {
384                panic!(
385                    "bynk internal error (ADR 0334): `Cache` field `{}` has no resolvable \
386                     `@ttl` millis, but the checker already accepted this declaration — \
387                     bynk.store.cache_ttl_required gates a missing or malformed `@ttl` \
388                     before certify",
389                    f.name.name
390                )
391            });
392            StoreKindIr::Cache(k, v, ttl)
393        }
394        "Log" => {
395            let elem = resolve_store_field_ty(cx, &f.name.name, &f.kind.args[0]);
396            let retain = duration_millis_annotation(&f.annotations, "retain");
397            StoreKindIr::Log(elem, retain)
398        }
399        other => panic!(
400            "bynk internal error (ADR 0334): store field `{}` has storage kind `{other}`, which \
401             cannot reach a certified program — only Cell/Map/Set/Cache/Log are functional \
402             (Queue is gated by bynk.store.kind_unsupported before certify)",
403            f.name.name
404        ),
405    };
406    // [DECISION C]/[DECISION E]: one entry per distinct `by:` argument,
407    // declaration order, no sort — legal only on `Map` (`ANNOTATIONS`'s own
408    // registry), so this is empty by construction for every other kind.
409    // Deduplicated: `validate_indexed_keys` (`context_checks.rs`) validates
410    // each `by:` argument independently with no duplicate check, so
411    // `@indexed(by: k, by: k)` certifies — mirrors the shipped emitter's own
412    // `store_map_indexes` guard (`emit.rs`'s `!fields.contains(&k.name)`),
413    // grounded during P6.7's own review (#1163): dropping this would mean a
414    // duplicate `by:` produces the same sibling index table twice.
415    let mut indexed: Vec<String> = Vec::new();
416    for arg in f
417        .annotations
418        .iter()
419        .filter(|a| a.name.name == "indexed")
420        .flat_map(|a| &a.args)
421    {
422        if let (Some(l), ExprKind::Ident(k)) = (&arg.label, &arg.value.kind)
423            && l.name == "by"
424            && !indexed.contains(&k.name)
425        {
426            indexed.push(k.name.clone());
427        }
428    }
429    (kind, indexed)
430}
431
432/// A store field's storage *shape* — its `Cell`/`Map`/`Set`/`Cache`/`Log`
433/// kind and `@indexed` keys (via `store_field_kind_and_indexed`), with
434/// `init` always `None`. This is the entry point `emit_agent`'s own state
435/// section actually needs; a `Cell` field's zero/initial-value expression is
436/// rendered by the emitter from the AST, never lowered here. (An
437/// `init`-lowering sibling existed until Slice D1 of `#1542`; it lowered the
438/// initialiser through the deleted expression lowerer and had no caller.)
439///
440/// The field's own type reference is resolved with an internal error on a
441/// miss (#3166); the resolver rejects an unknown store field type.
442pub fn lower_store_field_shape_ir(f: &StoreField, program: &CheckedProgram) -> StoreFieldIr {
443    let cx = LowerIrCtx::new(program, HashSet::new());
444    let (kind, indexed) = store_field_kind_and_indexed(f, &cx);
445    StoreFieldIr {
446        field: f.name.name.clone(),
447        kind,
448        indexed,
449    }
450}
451
452/// [DECISION B]/[DECISION C] (#1165): does `body` reach a mutating
453/// `Callee::Store` write, or an unconditional `Statement::Assign` (`:=`),
454/// anywhere — including inside a nested `if`/`match`/lambda? Drives, as of
455/// #1196 (the #1187 emitter-cutover track's own R6.5 stake), `emit_agent`'s
456/// (`bynk-emit/src/emitter/emit.rs`) real implicit-commit-wrapper decision
457/// (it also drove the IR-side `CommitShape::Transactional` decision until
458/// Slice D1 of `#1542` deleted that constructor) — its previous own
459/// name-matching `block_writes_state`
460/// (`emitter.rs`) is deleted, this function is its sole, direct
461/// replacement. The walk's own shape is that deleted function's own
462/// already-correct skeleton reused structurally, not re-derived:
463/// `Block`/`If`/`Match` are hand-matched so crossing a nested block
464/// re-enters the statement-aware case (an `expr_children` descent alone
465/// flattens a block straight to its statements' *values*, losing the
466/// `Statement::Assign` tag), everywhere else recurses over
467/// `expr_children`'s total child iterator.
468///
469/// Unlike the deleted function's own name-based `mutating_op`, this walk
470/// needs no per-kind receiver-name set: a `Callee::Store { op, .. }` already
471/// carries the field's own resolved identity (the checker only ever records
472/// one for a method the field's own kind actually declares), so `op`'s
473/// membership in the store-op registry's mutating set
474/// (`bynk_check::store_ops::is_mutating_any`, #2194) is unambiguous checked
475/// flat, across every kind at once — a locally-shadowed name that would false-positive
476/// `mutating_op` cannot false-positive here at all, the exact fix Decision
477/// B's own Risk names, and the exact defect `#1196_agent_write_detection_
478/// via_resolved_callee`'s own fixture pins at the emitted-output level.
479pub fn body_writes_state(body: &Block, program: &TypedCommons) -> bool {
480    fn is_mutating_store_write(e: &Expr, program: &TypedCommons) -> bool {
481        match program.callees.get(&e.id) {
482            // #2194: the mutating set is the store-op registry's own
483            // `mutates` flag. A `Callee::Store` already carries the op
484            // resolved against its field's kind, so the op name alone decides.
485            Some(Callee::Store { op, .. }) => op.mutates(),
486            _ => false,
487        }
488    }
489    fn stmt(s: &Statement, program: &TypedCommons) -> bool {
490        match s {
491            Statement::Assign(_) => true,
492            Statement::Let(l) | Statement::EffectLet(l) => expr(&l.value, program),
493            Statement::Expect(a) => expr(&a.value, program),
494            Statement::Do(d) => expr(&d.value, program),
495            Statement::Advance(a) => expr(&a.amount, program),
496            Statement::Par(p) => p.statements.iter().any(|s| stmt(s, program)),
497        }
498    }
499    fn expr(e: &Expr, program: &TypedCommons) -> bool {
500        if is_mutating_store_write(e, program) {
501            return true;
502        }
503        match &e.kind {
504            ExprKind::Block(b) => body_writes_state(b, program),
505            ExprKind::If {
506                cond,
507                then_block,
508                else_block,
509            } => {
510                expr(cond, program)
511                    || body_writes_state(then_block, program)
512                    || body_writes_state(else_block, program)
513            }
514            // #1800: a guard is evaluated like any other expression, so a
515            // write in one (`Some(x) if if x > 0 { hits := x; true } …`) runs
516            // and must be committed. Skipping it dropped the commit wrapper.
517            ExprKind::Match { discriminant, arms } => {
518                expr(discriminant, program)
519                    || arms.iter().any(|a| {
520                        a.guard.as_ref().is_some_and(|g| expr(g, program))
521                            || match &a.body {
522                                MatchBody::Expr(e) => expr(e, program),
523                                MatchBody::Block(b) => body_writes_state(b, program),
524                            }
525                    })
526            }
527            ExprKind::IntLit { .. }
528            | ExprKind::FloatLit { .. }
529            | ExprKind::DecimalLit { .. }
530            | ExprKind::DurationLit { .. }
531            | ExprKind::StrLit(_)
532            | ExprKind::InterpStr(_)
533            | ExprKind::BoolLit(_)
534            | ExprKind::Ident(_)
535            | ExprKind::Call { .. }
536            | ExprKind::Lambda(_)
537            | ExprKind::BinOp(..)
538            | ExprKind::UnaryOp(..)
539            | ExprKind::Paren(_)
540            | ExprKind::Ok(_)
541            | ExprKind::Err(_)
542            | ExprKind::Question(_)
543            | ExprKind::RecordConstruction { .. }
544            | ExprKind::FieldAccess { .. }
545            | ExprKind::MethodCall { .. }
546            | ExprKind::Is { .. }
547            | ExprKind::Some(_)
548            | ExprKind::None
549            | ExprKind::UnitLit
550            | ExprKind::RecordSpread { .. }
551            | ExprKind::EffectPure(_)
552            | ExprKind::Expect(_)
553            | ExprKind::Val { .. }
554            | ExprKind::Wire(_)
555            | ExprKind::ListLit(..)
556            | ExprKind::Observation(_)
557            | ExprKind::Faults(_)
558            | ExprKind::Trace { .. } => expr_children(e).into_iter().any(|c| expr(c, program)),
559        }
560    }
561    body.statements.iter().any(|s| stmt(s, program)) || expr(&body.tail, program)
562}
563
564/// P6.11 ([DECISION C], #1171): reshape a `from Events(E { … })` pattern
565/// into a real [`EventPatternIr`] — pure structural reshaping, no
566/// `&CheckedProgram` parameter and no resolution: every field's own
567/// matched value is either already a literal or an unresolved variant tag,
568/// neither needing a `TyId`. `EventPatternValue::Literal` lowers through
569/// the same `LiteralValue -> ConstVal` match [`lower_pattern_ir`] already
570/// uses for `Pattern::Literal`'s identical closed set.
571fn lower_event_pattern_ir(pattern: &EventPattern) -> EventPatternIr {
572    EventPatternIr {
573        fields: pattern
574            .fields
575            .iter()
576            .map(|f| {
577                let value = match &f.value {
578                    EventPatternValue::Literal { value, .. } => {
579                        EventPatternValueIr::Const(match value {
580                            LiteralValue::Int(n) => ConstVal::Int(*n),
581                            LiteralValue::Str(s) => ConstVal::Str(s.clone()),
582                            LiteralValue::Bool(b) => ConstVal::Bool(*b),
583                        })
584                    }
585                    EventPatternValue::Variant { variant, .. } => EventPatternValueIr::Variant {
586                        tag: variant.name.clone(),
587                    },
588                };
589                (f.name.name.clone(), value)
590            })
591            .collect(),
592    }
593}
594
595/// P6.11 ([DECISION A], #1171): lower a service's own `from <protocol>`
596/// header into a real [`ProtocolIr`] — standalone, takes the sub-node
597/// rather than the owning `ServiceDecl` (mirrors
598/// [`lower_store_field_shape_ir`]), so a `from websocket`/`from Events`
599/// fixture can pin the descriptor by itself.
600///
601/// `WebSocket`/`Events` type refs are resolved with an internal error on a
602/// miss (#3166): the resolver rejects an unknown protocol type.
603pub fn lower_protocol_ir(protocol: &ServiceProtocol, program: &CheckedProgram) -> ProtocolIr {
604    lower_protocol_ir_from_commons(protocol, program.program())
605}
606
607/// P6.24a: a `TypedCommons`-only sibling of [`lower_protocol_ir`], the same
608/// split `lower_op_sig_ir`/`lower_op_sig_ir_from_commons` already
609/// established — for a call site holding only a unit's own `TypedCommons`,
610/// never a `&CheckedProgram` (`emitter.rs`'s `emit_project_imports`, a
611/// header-import-collection pass that runs well outside the per-declaration
612/// emission loop any `CheckedProgram` is threaded through). Sound for the
613/// identical reason: nothing here reads a per-expression type, the one
614/// lookup whose `.expect()`-panic needed a genuinely certified program.
615pub fn lower_protocol_ir_from_commons(
616    protocol: &ServiceProtocol,
617    commons: &TypedCommons,
618) -> ProtocolIr {
619    let cx = LowerIrCtx::from_commons(commons, HashSet::new());
620    match protocol {
621        ServiceProtocol::Call => ProtocolIr::Call,
622        ServiceProtocol::Http => ProtocolIr::Http,
623        ServiceProtocol::Cron => ProtocolIr::Cron,
624        ServiceProtocol::Queue { name } => ProtocolIr::Queue { name: name.clone() },
625        ServiceProtocol::Email { address } => ProtocolIr::Email {
626            address: address.clone(),
627        },
628        ServiceProtocol::WebSocket { in_type, out_type } => ProtocolIr::WebSocket {
629            in_ty: cx.resolve_checked_type_ref(in_type, "WebSocket service protocol in-type"),
630            out_ty: cx.resolve_checked_type_ref(out_type, "WebSocket service protocol out-type"),
631        },
632        ServiceProtocol::Events {
633            event_type,
634            pattern,
635            schema_dispatch,
636        } => ProtocolIr::Events {
637            event: cx.resolve_checked_type_ref(event_type, "Events service protocol event type"),
638            pattern: pattern.as_ref().map(lower_event_pattern_ir),
639            schema_dispatch: schema_dispatch.as_ref().map(|d| match &d.pattern {
640                bynk_syntax::ast::SchemaVersionPattern::Literal(v) => {
641                    crate::vocabulary::SchemaVersionIr::Exact(*v)
642                }
643                bynk_syntax::ast::SchemaVersionPattern::Range(r) => {
644                    crate::vocabulary::SchemaVersionIr::Range { lo: r.lo, hi: r.hi }
645                }
646                bynk_syntax::ast::SchemaVersionPattern::Wildcard => {
647                    crate::vocabulary::SchemaVersionIr::Any
648                }
649            }),
650        },
651    }
652}
653
654/// #1228: a GET handler's own `@cache(maxAge:, scope:)` freshness policy —
655/// [`crate::vocabulary::CacheIr`]'s own doc comment has the full grounding for why
656/// this is a standalone per-route reader. Field-for-
657/// field the same extraction `emitter/workers_entry.rs`'s own (now
658/// superseded) `cache_policy_for` did: only a `GET` yields a policy;
659/// project validation (`bynk.http.cache_*`) has already rejected a
660/// `@cache` anywhere else, and a malformed `maxAge` there, so a missing or
661/// ill-formed annotation here simply yields `None` — no `&CheckedProgram`
662/// needed, the same posture `lower_policy_ir`'s own doc comment already
663/// argues for: `maxAge`/`scope` are already-resolved syntactic literals
664/// (`ExprKind::DurationLit`/`Ident`), not a type this pass would ever need
665/// to resolve.
666pub fn lower_route_cache_ir(h: &Handler) -> Option<CacheIr> {
667    if !matches!(
668        h.kind,
669        HandlerKind::Http {
670            method: HttpMethod::Get,
671            ..
672        }
673    ) {
674        return None;
675    }
676    let ann = h.annotations.iter().find(|a| a.name.name == "cache")?;
677    let mut max_age_millis: Option<i64> = None;
678    let mut scope = "private";
679    let mut immutable = false;
680    for arg in &ann.args {
681        match arg.label.as_ref().map(|l| l.name.as_str()) {
682            Some("maxAge") => {
683                if let ExprKind::DurationLit { millis, .. } = &arg.value.kind {
684                    max_age_millis = Some(*millis);
685                }
686            }
687            Some("scope") => {
688                if let ExprKind::Ident(id) = &arg.value.kind
689                    && id.name == "public"
690                {
691                    scope = "public";
692                }
693            }
694            Some("immutable") => {
695                if let ExprKind::BoolLit(b) = arg.value.kind {
696                    immutable = b;
697                }
698            }
699            _ => {}
700        }
701    }
702    Some(CacheIr {
703        max_age_secs: max_age_millis? / 1000,
704        scope,
705        immutable,
706    })
707}
708
709/// #1228: a route's own `@limit(maxBody:)` annotation, if present — the
710/// override half of `emitter/workers_entry.rs`'s own (now superseded)
711/// `effective_max_body`; the service-wide `limits { maxBody }` fallback
712/// stays that function's own concern (read from a *service*'s `limits {}`
713/// block, not a per-route `Handler`, so it does not move here). Project validation
714/// (`bynk.http.limit_*`/`limits_*`) has already rejected a malformed or
715/// misplaced `@limit`, so an absent/ill-formed annotation here simply
716/// yields `None` — the caller's own service-default fallback still
717/// applies. No `&CheckedProgram` needed, same reasoning as
718/// [`lower_route_cache_ir`]: `maxBody` is an already-resolved
719/// `ExprKind::IntLit`, not a type.
720pub fn lower_route_limit_ir(h: &Handler) -> Option<i64> {
721    h.limit_max_body()
722}
723
724/// Every `from Events(E)` service in `program`'s own unit, captured as an
725/// [`crate::vocabulary::EventSubscriberShape`] keyed by service name — see that
726/// struct's own doc comment for why this is captured now rather than
727/// re-derived cross-unit at compose time (P6.47, `#1254`).
728///
729/// Slice D0 of `#1542` (the IR cutover, `design/archive/retired-tracks.md`; `#1574`):
730/// reads the two facts it returns from the shape-only helpers that own them —
731/// [`lower_protocol_ir`] for `schema_dispatch`, and [`lower_handler_kind_ir`]
732/// plus [`lower_service_handler_signature_ir`] for the `Event` handler's
733/// parameter count. Before D0 this function went through
734/// `lower_service_item_ir`, which lowers every handler's *body* to `IrExpr`
735/// through the expression lowerer and then discards it — the one production
736/// route into that lowerer, and the detour §10.2 of the track doc names (the
737/// body lowering's own `unreachable!()` safety argument covered
738/// `lower_fn_body_ir`'s callers only, never this path). The values are
739/// identical by construction: `lower_service_handler_ir` itself took its
740/// `params` from [`lower_service_handler_signature_ir`] and its `kind` from
741/// [`lower_handler_kind_ir`], and `lower_service_item_ir` its `protocol` from
742/// [`lower_protocol_ir`] — this function now calls those three directly and
743/// skips the body.
744///
745/// The `ServiceProtocol::Events` pre-filter stays first: a cheap, structural
746/// "which services even have a shape to capture" check (the same match
747/// [`lower_protocol_ir`] performs), not a raw-AST *read* of anything the IR
748/// side owns.
749pub fn lower_event_subscriber_shapes_ir(
750    program: &CheckedProgram,
751) -> HashMap<String, EventSubscriberShape> {
752    let mut out = HashMap::new();
753    for item in &program.program().commons.items {
754        if let CommonsItem::Service(s) = item
755            && matches!(&s.protocol, ServiceProtocol::Events { .. })
756        {
757            let ProtocolIr::Events {
758                schema_dispatch, ..
759            } = lower_protocol_ir(&s.protocol, program)
760            else {
761                panic!(
762                    "bynk internal error: lower_protocol_ir did not return \
763                     ProtocolIr::Events for a service whose own AST protocol is \
764                     ServiceProtocol::Events"
765                )
766            };
767            // A `from Events` service has exactly one `on event` handler (the checker
768            // refuses a second: `bynk.event.duplicate_handler`, #1781, in
769            // `check_service_protocols`), so the first one found is the one.
770            let two_param_handler = s
771                .handlers
772                .iter()
773                .find(|h| matches!(lower_handler_kind_ir(&h.kind), IrHandlerKind::Event))
774                .is_some_and(|h| lower_service_handler_signature_ir(h, program).0.len() == 2);
775            out.insert(
776                s.name.name.clone(),
777                EventSubscriberShape {
778                    two_param_handler,
779                    schema_dispatch: schema_dispatch.is_some(),
780                },
781            );
782        }
783    }
784    out
785}
786
787/// A capability declaration's resolved op signatures, in declaration order
788/// — what `emitter.rs`'s own capability-item loop reads (the caller already
789/// holds the capability's name from the AST declaration). Slice 1 of
790/// `#1542` split this out of a full `IrItem::Capability` constructor to end
791/// a build-then-discard-`def` round-trip; Slice D1 deleted that constructor.
792pub fn lower_capability_ops_ir(cap: &CapabilityDecl, program: &CheckedProgram) -> Vec<OpSig> {
793    cap.ops
794        .iter()
795        .map(|op| lower_op_sig_ir(op, program))
796        .collect()
797}
798
799/// P6.29 (design/tracks/the-ir.md §6a): the `TypedCommons`-only counterpart to
800/// [`lower_capability_ops_ir`], for call sites (`emitter/lower.rs`'s
801/// `cap_op_param_names`) that have a `TypedCommons` in hand but no
802/// `CheckedProgram` — `LowerCtx`/`ModuleCtx` never carry one (see
803/// `lower_op_sig_ir_from_commons`, this function's own single-op sibling,
804/// for the identical reason it exists as a separate entry point rather than a
805/// thin wrapper over the `CheckedProgram`-driven `lower_op_sig_ir`).
806///
807/// Resolves one capability operation's signature by name — "find the op
808/// named `op` on the capability named `cap`" has no IR-native replacement
809/// (nothing indexes capabilities by name once lowered), so this still walks
810/// `TypedCommons::commons.items` the same way the code it replaces did.
811/// First match in item order; `None` on no match, mirroring the caller's own
812/// prior fallthrough-to-empty behaviour exactly.
813pub fn capability_op_sig_from_commons(
814    commons: &TypedCommons,
815    cap: &str,
816    op: &str,
817) -> Option<OpSig> {
818    commons.commons.items.iter().find_map(|item| {
819        let CommonsItem::Capability(c) = item else {
820            return None;
821        };
822        if c.name.name != cap {
823            return None;
824        }
825        c.ops
826            .iter()
827            .find(|o| o.name.name == op)
828            .map(|o| lower_op_sig_ir_from_commons(o, commons))
829    })
830}
831
832/// P6.12 (#1173): lower one capability operation's own signature into a real
833/// [`crate::vocabulary::OpSig`] — the reference's own capability-item sketch
834/// names this type (`ops: Vec<OpSig>`) but never defines it. Resolves
835/// `params`/`return_ty` in the scope `op.type_params` names, the same
836/// per-op rigid-variable seeding `context_checks::build_capability_op_info`
837/// (`bynk-check/src/context_checks.rs`) already gives a generic op for the
838/// checker-facing `CapabilityOpInfo` — an op's own `[T, …]` list is scoped to
839/// the op itself, not the capability (`CapabilityDecl` carries no
840/// `type_params` of its own), so this seeds a fresh [`LowerIrCtx`] per op
841/// rather than reusing `fn_rigid_type_vars`'s fn/method-shaped
842/// receiver-widening, which does not apply here.
843///
844/// A resolve miss is an internal error (#3166): the resolver rejects an
845/// unknown type in a capability op's signature.
846fn lower_op_sig_ir(op: &CapabilityOp, program: &CheckedProgram) -> OpSig {
847    lower_op_sig_ir_from_commons(op, program.program())
848}
849
850/// #1187's own closing scoping pass: a `TypedCommons`-only sibling of
851/// `lower_op_sig_ir`, for the one real call site that never has a
852/// `&CheckedProgram` — `emitter/lower.rs`'s `cap_op_param_names`, feeding
853/// `trace(Cap.op)`/`with`-predicate observation lowering
854/// (`bynk.test`'s DSL). That call path's own `TypedCommons` is a synthetic,
855/// hand-assembled project-wide view (`project/tests_emit.rs`'s
856/// `synthetic_typed_commons_for_target`, merging every consumed unit's own
857/// `capability` declarations into one scratch commons for lookup) — never
858/// itself the output of `certify`, so wrapping it as a `CheckedProgram`
859/// here would misrepresent an uncertified value as certified
860/// (`CheckedProgram`'s own doc comment, `bynk-check/src/checker.rs`, warns
861/// against exactly this). Splitting this out is sound precisely because
862/// this function never reads a per-expression type — the one lookup whose
863/// `.expect()`-panic needed a genuinely certified program, and the reason
864/// this module's own file-level doc comment gives for taking
865/// `&CheckedProgram` by default elsewhere. `resolve_checked_type_ref` (below) reads nothing `TypedCommons` doesn't
866/// already expose directly, and stops with an internal error on a miss.
867fn lower_op_sig_ir_from_commons(op: &CapabilityOp, commons: &TypedCommons) -> OpSig {
868    let type_vars: HashSet<String> = op
869        .type_params
870        .iter()
871        .map(|tp| tp.name.name.clone())
872        .collect();
873    let cx = LowerIrCtx::from_commons(commons, type_vars);
874    let params: Vec<(String, TyId)> = op
875        .params
876        .iter()
877        .map(|p| {
878            let ty = cx.resolve_checked_type_ref(
879                &p.type_ref,
880                &format!(
881                    "capability op `{}`, parameter `{}`",
882                    op.name.name, p.name.name
883                ),
884            );
885            (p.name.name.clone(), ty)
886        })
887        .collect();
888    let return_ty = cx.resolve_checked_type_ref(
889        &op.return_type,
890        &format!("capability op `{}`, return type", op.name.name),
891    );
892    OpSig {
893        name: op.name.name.clone(),
894        type_params: op
895            .type_params
896            .iter()
897            .map(|tp| tp.name.name.clone())
898            .collect(),
899        params,
900        return_ty,
901    }
902}
903
904/// P6.18: [`crate::vocabulary::FnSig`]'s own constructor — a `fn`'s own resolved
905/// signature, for a call site holding only that fn's *declaring* unit's own
906/// combined types (`bynk_check::symbols::combined_types_for`'s return shape),
907/// never a `CheckedProgram`. The one real call site
908/// (`bynk-emit/src/project.rs`'s `build_emit_unit_ctx`) reads a `uses`-
909/// imported *foreign* unit's own attached methods, whose own `CheckedProgram`
910/// does not survive past that unit's own `check_unit_files` iteration — the
911/// same "dropped before any later, project-wide pass runs" shape
912/// `unit_callees` (#1202)/`EventSubscriberShape` (#1232) both work around,
913/// except here no project-wide accumulator is needed at all: unlike a
914/// `Callee`/event-subscriber-shape classification (checker-only facts, never
915/// re-derivable from raw declarations alone), a fn signature's own
916/// `params`/`return_type` are ordinary type references, resolvable from that
917/// unit's own declared types the same way [`lower_op_sig_ir_from_commons`]
918/// already resolves a capability op's — so a bare types map is sufficient,
919/// the same non-`CheckedProgram` scope that function already established.
920///
921/// Only the method's own `[T, …]` list seeds the rigid-variable scope, not
922/// its generic receiver's — the one real caller (`emit_forwarded_methods`)
923/// never renders `self`'s own type through this value at all (it takes the
924/// *consumer* context's own rebranded type name directly), so resolving
925/// `fn_receiver_ty` here would be dead work.
926fn lower_fn_sig_ir_from_types(
927    f: &FnDecl,
928    types: &HashMap<String, Arc<TypeDecl>>,
929    tys: &Types,
930) -> FnSig {
931    // An attached fn of a generic type names the *receiver's* type variables
932    // (`Bag.largest -> Option[A]`) as well as its own, so both are in scope.
933    let receiver_params = match &f.name {
934        FnName::Method { type_name, .. } => types
935            .get(&type_name.name)
936            .map(|d| d.type_params.as_slice())
937            .unwrap_or_default(),
938        FnName::Free(_) => &[],
939    };
940    let type_vars: HashSet<String> = receiver_params
941        .iter()
942        .chain(&f.type_params)
943        .map(|tp| tp.name.name.clone())
944        .collect();
945    let fn_name = f.name.display();
946    let resolve = |r: &bynk_syntax::ast::TypeRef, what: &str| {
947        checker::resolve_type_ref_in(r, types, &type_vars, tys).unwrap_or_else(|| {
948            panic!(
949                "bynk internal error: fn `{fn_name}`, {what}: type `{}` does not resolve, but \
950                 the checker already accepted this declaration",
951                bynk_syntax::print::type_ref_to_string(r)
952            )
953        })
954    };
955    let params: Vec<(String, TyId)> = f
956        .params
957        .iter()
958        .map(|p| {
959            let ty = resolve(&p.type_ref, &format!("parameter `{}`", p.name.name));
960            (p.name.name.clone(), ty)
961        })
962        .collect();
963    let return_ty = resolve(&f.return_type, "return type");
964    let name = match &f.name {
965        FnName::Method { method_name, .. } => method_name.name.clone(),
966        FnName::Free(id) => id.name.clone(),
967    };
968    FnSig {
969        name,
970        has_self: f.has_self,
971        params,
972        return_ty,
973    }
974}
975
976/// P6.x (#1137): `lower_fn_sig_ir_from_types` over an entire
977/// [`MethodTable`]'s own instance + static entries — the attached-method
978/// gathering [`bynk-emit`'s `build_emit_unit_ctx`] needs for a `uses`-imported
979/// type. Filters to [`FnName::Method`] before lowering: `ResolverMethodTable`
980/// only ever collects attached methods in practice (`bynk-check/src/resolver.rs`'s
981/// own doc comment on [`MethodTable`]), but the filter stays as a defensive
982/// match rather than an assumption, matching the caller's own pre-existing
983/// posture one step earlier — this just moves that posture in front of the
984/// lowering call instead of behind it, so the `FnName` read (and the filter
985/// itself) never has to leave this module.
986pub fn lower_attached_fn_sig_ir_from_types(
987    mt: &MethodTable,
988    types: &HashMap<String, Arc<TypeDecl>>,
989    tys: &Types,
990) -> Vec<FnSig> {
991    mt.instance
992        .values()
993        .chain(mt.statics.values())
994        .filter(|f| matches!(f.name, FnName::Method { .. }))
995        .map(|f| lower_fn_sig_ir_from_types(f, types, tys))
996        .collect()
997}
998
999/// P6.24a: pure, unconditional [`HandlerKind`] → [`IrHandlerKind`]
1000/// conversion — every field is already fully resolved at parse time, so
1001/// unlike almost every other function in this module this one takes no
1002/// `&CheckedProgram`/`&TypedCommons` at all and can never miss.
1003pub fn lower_handler_kind_ir(k: &HandlerKind) -> IrHandlerKind {
1004    match k {
1005        HandlerKind::Call => IrHandlerKind::Call,
1006        HandlerKind::Http { method, path } => IrHandlerKind::Http {
1007            method: lower_http_method_ir(*method),
1008            path: path.clone(),
1009        },
1010        HandlerKind::Cron { expr } => IrHandlerKind::Cron { expr: expr.clone() },
1011        HandlerKind::Message => IrHandlerKind::Message,
1012        HandlerKind::Open => IrHandlerKind::Open,
1013        HandlerKind::Close => IrHandlerKind::Close,
1014        HandlerKind::Event => IrHandlerKind::Event,
1015        HandlerKind::Rejected => IrHandlerKind::Rejected,
1016    }
1017}
1018
1019/// [`lower_handler_kind_ir`]'s own `HttpMethod` half.
1020fn lower_http_method_ir(m: HttpMethod) -> IrHttpMethod {
1021    match m {
1022        HttpMethod::Get => IrHttpMethod::Get,
1023        HttpMethod::Post => IrHttpMethod::Post,
1024        HttpMethod::Put => IrHttpMethod::Put,
1025        HttpMethod::Patch => IrHttpMethod::Patch,
1026        HttpMethod::Delete => IrHttpMethod::Delete,
1027    }
1028}
1029
1030/// A provider's own `given` clause, resolved standalone — the entry point
1031/// `bynk-emit/src/project.rs`'s `instantiate_provider_ts_expr` actually
1032/// calls. This never touches the provider's `ops` or their bodies; the
1033/// full-provider assembly that did (and lowered every `Bynk` op body through
1034/// the expression lowerer) had no caller and went with Slice D1 of `#1542`.
1035pub fn lower_provider_given_ir(provider: &ProviderDecl) -> Vec<CapRefIr> {
1036    provider.given.iter().map(lower_cap_ref_ir).collect()
1037}
1038
1039/// #1187's slice 6 plumbing (sibling of [`lower_provider_given_ir`]): a
1040/// handler's own `given` clause, resolved standalone — the entry point for
1041/// `project.rs`'s `plan_agent_given_deps`, `EmitProjectCtx::
1042/// agent_method_givens`, and `emitter/workers.rs`'s own `given` collection.
1043/// Reuses `lower_cap_ref_ir` verbatim; a handler's `given` is syntactically
1044/// identical to a provider's (`bynk_syntax::ast::CapRef`), so this is the
1045/// same one-line adapter, not a new design.
1046pub fn lower_handler_given_ir(h: &Handler) -> Vec<CapRefIr> {
1047    h.given.iter().map(lower_cap_ref_ir).collect()
1048}
1049
1050/// #2912: a context-level function's own `given` clause, resolved standalone —
1051/// the sibling of [`lower_handler_given_ir`] for the `fn … given C` form
1052/// (#2868), so a capability a function alone names is still imported.
1053pub fn lower_fn_given_ir(f: &FnDecl) -> Vec<CapRefIr> {
1054    f.given.iter().map(lower_cap_ref_ir).collect()
1055}
1056
1057/// #1187's slice 3: a handler's resolved actor-verification seam — the same
1058/// "narrow, standalone reader of already-resolved data" precedent
1059/// [`body_writes_state`]/[`lower_service_handler_signature_ir`] established,
1060/// applied to `bynk-check`'s own five actor-seam resolvers
1061/// (`bynk-check/src/actors.rs`) instead of a full handler assembly.
1062/// [`ActorSeamIr`]'s own doc comment has the full grounding for the
1063/// priority order and for the deliberately-missing `Signature` variant.
1064///
1065/// Replaces the hand-duplicated "try N resolvers, branch on which
1066/// returned `Some`" call sites this slice converts: `emit_service`
1067/// (`emitter/emit.rs`) and `emit_worker_compose`'s HTTP-dispatch match
1068/// (`emitter/workers.rs`). Deliberately does **not** yet replace every
1069/// caller of the five resolvers — `secrets.rs`'s `declared_secrets` unions
1070/// *all* matching seams' secrets rather than picking one (a different
1071/// shape this enum doesn't model), and the remaining call sites
1072/// (`emitter/workers_entry.rs`, `emitter/workers.rs`'s other two sites,
1073/// `emitter/emit.rs`'s `any_service_binds_caller`/`emit_make_surface`/
1074/// `ws_open_hosts_for`, `project/tests_emit.rs`) each call exactly one
1075/// resolver with nothing to collapse against — converting them to build a
1076/// five-variant enum just to immediately match out one arm would add
1077/// indirection without removing any real duplication.
1078pub fn lower_actor_seam_ir(handler: &Handler, actors: &HashMap<String, ActorDecl>) -> ActorSeamIr {
1079    if let Some(members) = bynk_check::actors::sum_members_for(handler, actors) {
1080        return ActorSeamIr::Sum(members);
1081    }
1082    if let Some(members) =
1083        bynk_check::actors::call_admission_for(handler, actors).and_then(|a| a.sum)
1084    {
1085        return ActorSeamIr::CallSum(members);
1086    }
1087    if let Some(seam) = bynk_check::actors::bearer_seam_for(handler, actors) {
1088        return ActorSeamIr::Bearer(seam);
1089    }
1090    if let Some(seam) = bynk_check::actors::oidc_seam_for(handler, actors) {
1091        return ActorSeamIr::Oidc(seam);
1092    }
1093    if let Some(seam) = bynk_check::actors::signed_cookie_seam_for(handler, actors) {
1094        return ActorSeamIr::SignedCookie(seam);
1095    }
1096    if let Some(binder) = bynk_check::actors::caller_binder_for(handler, actors) {
1097        return ActorSeamIr::Caller(binder);
1098    }
1099    if let Some(binder) = bynk_check::actors::sender_binder_for(handler, actors) {
1100        return ActorSeamIr::Sender(binder);
1101    }
1102    ActorSeamIr::None
1103}
1104
1105/// P6.14 (#1174, review of #1186): adapt one `given` entry into a real
1106/// [`crate::vocabulary::CapRefIr`] — [`CapRefIr`]'s own doc comment has the full
1107/// grounding for the `QualifiedName -> String` flattening and for why a
1108/// `Some` prefix is preserved unresolved.
1109pub fn lower_cap_ref_ir(cap_ref: &CapRef) -> CapRefIr {
1110    CapRefIr {
1111        context: cap_ref.context.as_ref().map(QualifiedName::joined),
1112        name: cap_ref.name.name.clone(),
1113    }
1114}
1115
1116/// Decision E: targeted minimal fixtures, one per node kind this slice
1117/// covers, staying strictly inside the subset [`lower_expr_ir`]/
1118/// [`lower_stmt_ir`] actually implement — not a walk over the real
1119/// `bynk-tests/tests/fixtures/positive` corpus, which hits an unimplemented
1120/// `Match`/`Call` arm within a few lines of almost any real fixture.
1121#[cfg(test)]
1122mod tests {
1123    use super::*;
1124    use bynk_check::checker::{CheckedProgram, Ty};
1125    use bynk_check::hints::HintSink;
1126    use bynk_check::index::RefSink;
1127    use bynk_check::locals::LocalsSink;
1128    use bynk_check::requirements::RequirementSink;
1129    use bynk_check::{checker, context_checks, resolver, symbols};
1130    use bynk_project::UnitKind;
1131    use bynk_syntax::ast::{AgentDecl, Commons, CommonsItem, HandlerKind, ServiceDecl, SourceUnit};
1132    use bynk_syntax::span::Span;
1133    use bynk_syntax::{lexer, parser};
1134
1135    /// The invariant the internal-error paths rely on (#3166): the resolver
1136    /// rejects an unknown type in a service handler's parameter and in a
1137    /// capability op's signature, so neither reaches lowering on a certified
1138    /// program.
1139    #[test]
1140    fn the_resolver_rejects_unknown_types_before_lowering_can_see_them() {
1141        for source in [
1142            "context demo\n\ncapability Store {\n  fn get(k: Bogus) -> Effect[Int]\n}\n",
1143            "context demo\n\ntype Frame = String\n\nservice Gw from websocket(in: Bogus, out: Frame) {\n  on open() -> Effect[()] {\n    Effect.pure(())\n  }\n}\n",
1144            "context demo\n\nservice Sub from Events(Bogus) {\n  on event(e: Bogus) -> Effect[()] {\n    Effect.pure(())\n  }\n}\n",
1145            "context demo\n\nservice Api from http {\n  on GET(\"/x\") (b: Bogus) -> Effect[HttpResult[String]] {\n    Effect.pure(Ok(\"ok\"))\n  }\n}\n",
1146        ] {
1147            let tokens = lexer::tokenize(source).expect("lex");
1148            let SourceUnit::Context(ctx) = parser::parse_unit(&tokens, source).expect("parse")
1149            else {
1150                panic!("expected a context unit")
1151            };
1152            let commons = Commons {
1153                name: ctx.name,
1154                items: ctx.items,
1155                uses: ctx.uses,
1156                documentation: ctx.documentation,
1157                form: ctx.form,
1158                span: ctx.span,
1159                trivia: ctx.trivia,
1160                trailing_comments: ctx.trailing_comments,
1161            };
1162            let Err(errors) = resolver::resolve(commons) else {
1163                panic!("`Bogus` must not resolve")
1164            };
1165            assert!(
1166                errors
1167                    .iter()
1168                    .any(|e| e.category == "bynk.resolve.unknown_type"),
1169                "{errors:?}"
1170            );
1171        }
1172    }
1173
1174    /// An attached fn of a generic type names the receiver's own type
1175    /// variables as well as its own; both resolve to type variables (#3213), so
1176    /// the reader never meets an unresolved name on a certified program.
1177    #[test]
1178    fn an_attached_fn_of_a_generic_type_resolves_the_receivers_type_variables() {
1179        let program = checked_context_program(
1180            r#"
1181context demo
1182
1183type Bag[A] = { items: List[A] }
1184
1185fn Bag.of(v: A) -> Bag[A] {
1186  Bag { items: [v] }
1187}
1188
1189fn Bag.largest(self) -> Option[A] {
1190  None
1191}
1192
1193fn Bag.pair[B](self, other: B) -> Bag[A] {
1194  self
1195}
1196"#,
1197        );
1198        let commons = program.program();
1199        let sigs = lower_attached_fn_sig_ir_from_types(
1200            &commons.methods["Bag"],
1201            &commons.types,
1202            &commons.ty_intern,
1203        );
1204        assert_eq!(sigs.len(), 3);
1205        let by_name = |n: &str| sigs.iter().find(|s| s.name == n).expect(n);
1206        let var_a = commons.ty_intern.intern(Ty::Var("A".to_string()));
1207        assert_eq!(by_name("of").params[0].1, var_a);
1208        let unit = commons.ty_intern.intern(Ty::Unit);
1209        assert_ne!(by_name("largest").return_ty, unit);
1210        assert_ne!(by_name("pair").return_ty, unit);
1211        assert_ne!(by_name("pair").params[0].1, unit);
1212    }
1213
1214    /// #3166: a type reference the checker accepted but that does not resolve
1215    /// is an internal error naming the declaration and the type, not a silent
1216    /// `()`.
1217    #[test]
1218    #[should_panic(expected = "capability op `get`, return type: type `Bogus` does not resolve")]
1219    fn an_unresolved_type_is_an_internal_error_naming_it() {
1220        let program = checked_context_program("context demo\n");
1221        let cx = LowerIrCtx::new(&program, HashSet::new());
1222        let bogus = bynk_syntax::ast::TypeRef::Named(bynk_syntax::ast::Ident {
1223            name: "Bogus".to_string(),
1224            span: Default::default(),
1225        });
1226        cx.resolve_checked_type_ref(&bogus, "capability op `get`, return type");
1227    }
1228
1229    /// Like [`checked_program`], but for source that declares an `agent`
1230    /// and/or a `service` — both are only legal inside a `context`, not a
1231    /// bare `commons` (`bynk.agent.outside_context`/the service
1232    /// equivalent), so `source` is parsed as a context unit and its items
1233    /// re-wrapped into a [`Commons`] value before re-using the same
1234    /// `resolve`/`check` pipeline `checked_program` does.
1235    /// `resolver::resolve`/`checker::check` both already treat
1236    /// `CommonsItem::Agent`/`Service` as inert (v0.5 declaration kinds "go
1237    /// through the context-level v0.5 path", `resolver.rs`'s own comment)
1238    /// — real agent/service checking (`store` field kinds, handler bodies,
1239    /// `expr_types` for a `Cell` initialiser, actor bindings) only happens
1240    /// via `context_checks::check_context_declarations`, called here by
1241    /// hand with a [`symbols::UnitTable`] built directly from the checked
1242    /// commons' own agent/service/actor and local `capability` items (a
1243    /// handler's `given <Cap>` resolves against `table.capabilities` —
1244    /// populated here so a fixture can declare its own local capability,
1245    /// but still no cross-context `uses`/`consumes` in any fixture this
1246    /// helper is given, so `resolver::CrossContextInfo::default()` is
1247    /// exact, not an approximation — in particular, no `from Events(E)`
1248    /// fixture is possible here, since a real subscription needs
1249    /// `consumes bynk { Events }`).
1250    ///
1251    /// **P6.11 (#1171) adds `services`/`actors` to the table and a
1252    /// pre-`resolve` `inject_service_defaults` pass.** `table.actors`
1253    /// matters even for a fixture using only the prelude (`Caller`,
1254    /// `Visitor`): `actor_identity_ty` resolves a *local* `actor`
1255    /// declaration through `table.actors` and silently falls through to
1256    /// the prelude/`Ty::Unit` otherwise
1257    /// (`context_checks.rs::actor_identity_ty`), so a `by u: Buyer`
1258    /// fixture without this would assert against a wrong `TyId` with no
1259    /// error at all. `inject_service_defaults` stands in for
1260    /// `bynk-check/src/analysis.rs`'s own pipeline-phase-2b call — this
1261    /// reduced harness has no such phase — so a fixture relying on a
1262    /// service-level `by`/`given` default (rather than declaring one per
1263    /// handler) would otherwise silently see it un-inherited, pinning the
1264    /// wrong fact with no failure to signal it.
1265    fn checked_context_program(source: &str) -> CheckedProgram {
1266        let tokens = lexer::tokenize(source).expect("lex");
1267        let unit = parser::parse_unit(&tokens, source).expect("parse");
1268        let SourceUnit::Context(mut ctx) = unit else {
1269            panic!("expected a context unit, got {unit:?}")
1270        };
1271        for item in &mut ctx.items {
1272            if let CommonsItem::Service(svc) = item {
1273                bynk_check::project_model::inject_service_defaults(svc);
1274            }
1275        }
1276        let commons = Commons {
1277            name: ctx.name,
1278            items: ctx.items,
1279            uses: ctx.uses,
1280            documentation: ctx.documentation,
1281            form: ctx.form,
1282            span: ctx.span,
1283            trivia: ctx.trivia,
1284            trailing_comments: ctx.trailing_comments,
1285        };
1286        let resolved = resolver::resolve(commons).expect("resolve");
1287        let mut typed = checker::check(resolved).expect("check");
1288        let agents: HashMap<String, Arc<AgentDecl>> = typed
1289            .commons
1290            .items
1291            .iter()
1292            .filter_map(|item| {
1293                if let CommonsItem::Agent(a) = item {
1294                    Some((a.name.name.clone(), Arc::new(a.clone())))
1295                } else {
1296                    None
1297                }
1298            })
1299            .collect();
1300        let services: HashMap<String, ServiceDecl> = typed
1301            .commons
1302            .items
1303            .iter()
1304            .filter_map(|item| {
1305                if let CommonsItem::Service(s) = item {
1306                    Some((s.name.name.clone(), s.clone()))
1307                } else {
1308                    None
1309                }
1310            })
1311            .collect();
1312        let actors: HashMap<String, bynk_syntax::ast::ActorDecl> = typed
1313            .commons
1314            .items
1315            .iter()
1316            .filter_map(|item| {
1317                if let CommonsItem::Actor(a) = item {
1318                    Some((a.name.name.clone(), a.clone()))
1319                } else {
1320                    None
1321                }
1322            })
1323            .collect();
1324        // A `given <Cap>` clause on a handler resolves against
1325        // `table.capabilities` (`context_checks.rs`'s own `capability_info_map`
1326        // construction) — populated here from this fixture's own local
1327        // `capability` declarations so a handler can legitimately declare one
1328        // (e.g. `Log.append`'s own `given Clock` requirement), the same
1329        // "no cross-context uses/consumes" scope this helper's own doc
1330        // comment already names for `agents`/`types`.
1331        let capabilities: HashMap<String, bynk_syntax::ast::CapabilityDecl> = typed
1332            .commons
1333            .items
1334            .iter()
1335            .filter_map(|item| {
1336                if let CommonsItem::Capability(c) = item {
1337                    Some((c.name.name.clone(), c.clone()))
1338                } else {
1339                    None
1340                }
1341            })
1342            .collect();
1343        // P6.14 (#1174): `check_provider_decls` (the pass that actually
1344        // type-checks a `ProviderOp`'s own body via `check_handler_body`)
1345        // reads `table.providers`, keyed by capability name — same "one
1346        // provider per capability in v0.5" convention
1347        // `symbols::UnitTable::providers`'s own doc comment names. Populated
1348        // here for the same reason `capabilities` is (above): without it, a
1349        // fixture's own `provides` declaration is silently never checked at
1350        // all, not merely under-checked (feedback memory
1351        // "bynk-emit test harness scope").
1352        let providers: HashMap<String, ProviderDecl> = typed
1353            .commons
1354            .items
1355            .iter()
1356            .filter_map(|item| {
1357                if let CommonsItem::Provider(p) = item {
1358                    Some((p.capability.name.clone(), p.clone()))
1359                } else {
1360                    None
1361                }
1362            })
1363            .collect();
1364        let table = symbols::UnitTable {
1365            kind: Some(UnitKind::Context),
1366            types: typed.types.clone(),
1367            agents,
1368            services,
1369            actors,
1370            capabilities,
1371            providers,
1372            ..symbols::UnitTable::default()
1373        };
1374        let tys = typed.ty_intern.clone();
1375        let errors = context_checks::check_context_declarations(
1376            &mut typed,
1377            &table,
1378            &resolver::CrossContextInfo::default(),
1379            true,
1380            &HashSet::new(),
1381            &HashMap::new(),
1382            &mut RefSink::new(),
1383            &mut HintSink::new(),
1384            &mut LocalsSink::new(),
1385            &mut RequirementSink::new(),
1386            &tys,
1387        );
1388        checker::certify(typed, errors).expect("certify")
1389    }
1390
1391    fn find_agent<'a>(program: &'a CheckedProgram, name: &str) -> &'a AgentDecl {
1392        program
1393            .program()
1394            .commons
1395            .items
1396            .iter()
1397            .find_map(|item| {
1398                if let CommonsItem::Agent(a) = item
1399                    && a.name.name == name
1400                {
1401                    Some(a)
1402                } else {
1403                    None
1404                }
1405            })
1406            .unwrap_or_else(|| panic!("no agent named `{name}` in this fixture"))
1407    }
1408
1409    /// `lower_actor_seam_ir`'s own `actors` map — rebuilt the same way
1410    /// `checked_context_program` builds its own throwaway `table.actors`
1411    /// (not itself exposed on `CheckedProgram`), since the resolvers it
1412    /// wraps take the same `HashMap<String, ActorDecl>` shape the real
1413    /// `table.actors`/`ctx.actors` emitter-side callers already carry.
1414    fn actors_map(program: &CheckedProgram) -> HashMap<String, ActorDecl> {
1415        program
1416            .program()
1417            .commons
1418            .items
1419            .iter()
1420            .filter_map(|item| {
1421                if let CommonsItem::Actor(a) = item {
1422                    Some((a.name.name.clone(), a.clone()))
1423                } else {
1424                    None
1425                }
1426            })
1427            .collect()
1428    }
1429
1430    fn find_service<'a>(program: &'a CheckedProgram, name: &str) -> &'a ServiceDecl {
1431        program
1432            .program()
1433            .commons
1434            .items
1435            .iter()
1436            .find_map(|item| {
1437                if let CommonsItem::Service(s) = item
1438                    && s.name.name == name
1439                {
1440                    Some(s)
1441                } else {
1442                    None
1443                }
1444            })
1445            .unwrap_or_else(|| panic!("no service named `{name}` in this fixture"))
1446    }
1447
1448    /// `find_handler` (below) matches on `method_name`, which is always
1449    /// `None` for a service handler — useless here. Matches on
1450    /// `HandlerKind` equality instead; not a unique identity on its own (a
1451    /// service may declare several handlers sharing one `HandlerKind`, all
1452    /// `on call`), so a fixture with more than one same-kind handler must
1453    /// index `service.handlers`/the lowered `handlers` slice directly
1454    /// instead of calling this twice.
1455    fn find_service_handler<'a>(service: &'a ServiceDecl, kind: &HandlerKind) -> &'a Handler {
1456        service
1457            .handlers
1458            .iter()
1459            .find(|h| &h.kind == kind)
1460            .unwrap_or_else(|| {
1461                panic!(
1462                    "no handler of kind {kind:?} on service `{}`",
1463                    service.name.name
1464                )
1465            })
1466    }
1467
1468    fn find_store_field<'a>(agent: &'a AgentDecl, name: &str) -> &'a StoreField {
1469        agent
1470            .store_fields
1471            .iter()
1472            .find(|f| f.name.name == name)
1473            .unwrap_or_else(|| {
1474                panic!(
1475                    "no store field named `{name}` on agent `{}`",
1476                    agent.name.name
1477                )
1478            })
1479    }
1480
1481    /// [`lower_store_field_shape_ir`] reads a store field's shape and never
1482    /// its initialiser — pinned against the two initialiser forms that once
1483    /// tripped the (since deleted) `init`-lowering sibling: `= None`
1484    /// (`223_store_cell_agent`'s `store paymentRef: Cell[Option[AuthId]] =
1485    /// None`) and an `is`-expression (`1029_agent_static_init_hoist`'s
1486    /// `store active: Cell[Bool] = if true { 5 is PositiveInt } else {
1487    /// false }`). Both are real, certified fixtures; the shape reader lowers
1488    /// both fields cleanly because it does not touch `init` at all.
1489    #[test]
1490    fn store_field_shape_ir_does_not_panic_on_none_or_is_initialisers() {
1491        let program = checked_context_program(
1492            r#"
1493context demo
1494
1495type AuthId = String where NonEmpty
1496
1497agent Order {
1498  key id: String
1499  store paymentRef: Cell[Option[AuthId]] = None
1500
1501  on call touch() -> Effect[()] {
1502    Effect.pure(())
1503  }
1504}
1505"#,
1506        );
1507        let agent = find_agent(&program, "Order");
1508        let payment_ref = find_store_field(agent, "paymentRef");
1509        let ir = lower_store_field_shape_ir(payment_ref, &program);
1510        assert_eq!(ir.field, "paymentRef");
1511        assert!(matches!(ir.kind, StoreKindIr::Cell(_)));
1512
1513        let program = checked_context_program(
1514            r#"
1515context demo
1516
1517type PositiveInt = Int where Positive
1518
1519agent Meter {
1520  key id: String
1521  store active: Cell[Bool] = if true { 5 is PositiveInt } else { false }
1522
1523  on call touch() -> Effect[()] {
1524    Effect.pure(())
1525  }
1526}
1527"#,
1528        );
1529        let agent = find_agent(&program, "Meter");
1530        let active = find_store_field(agent, "active");
1531        let ir = lower_store_field_shape_ir(active, &program);
1532        assert_eq!(ir.field, "active");
1533        assert!(matches!(ir.kind, StoreKindIr::Cell(_)));
1534    }
1535
1536    /// Review of #1209: pins the one load-bearing ordering decision
1537    /// `ActorSeamIr`'s own doc comment argues for — `sum_members_for`
1538    /// ahead of `bearer_seam_for` — at `lower_actor_seam_ir` itself, not
1539    /// only four fixture-hops away via a full `emit_service`/`bless` run.
1540    /// `bearer_seam_for` has no `by.is_sum()` guard of its own and resolves
1541    /// off `by.primary()`, so a Bearer-first sum (`by who: User | Visitor`
1542    /// with `User`'s own scheme `Bearer`) would resolve as `ActorSeamIr::
1543    /// Bearer` instead of `ActorSeamIr::Sum` if the two resolvers were ever
1544    /// tried in the other order.
1545    #[test]
1546    fn lower_actor_seam_ir_tries_sum_ahead_of_bearer_for_a_bearer_first_sum() {
1547        let program = checked_context_program(
1548            r#"
1549context demo
1550
1551type UserId = String
1552
1553actor User { auth = Bearer(secret = "AUTH_SECRET"), identity = UserId }
1554
1555service Api from http {
1556  on GET("/whoami") () -> Effect[HttpResult[String]] by who: User | Visitor {
1557    Effect.pure(Ok("ok"))
1558  }
1559}
1560"#,
1561        );
1562        let service = find_service(&program, "Api");
1563        let handler = &service.handlers[0];
1564        let actors = actors_map(&program);
1565        let seam = lower_actor_seam_ir(handler, &actors);
1566        let ActorSeamIr::Sum(members) = &seam else {
1567            panic!("expected ActorSeamIr::Sum for a Bearer-first sum `by` clause, got {seam:?}");
1568        };
1569        assert_eq!(members.len(), 2);
1570        assert_eq!(members[0].actor_name, "User");
1571        assert_eq!(members[1].actor_name, "Visitor");
1572    }
1573
1574    /// [`lower_service_handler_signature_ir`] is `emit_service`'s entry
1575    /// point for a handler's resolved signature (#1187's slice 5, review of
1576    /// #1196) and never reads the body. Pinned against the shape that
1577    /// motivated it: an ordinary `from http` handler body constructing
1578    /// `Ok(...)` directly, not routed through the `fn ok(s) ->
1579    /// HttpResult[String] { Ok(s) }` indirection other fixtures in this
1580    /// module use — historically the body shape a full handler lowering
1581    /// panicked on, and still the clearest demonstration that this reader is
1582    /// signature-only.
1583    #[test]
1584    fn service_handler_signature_lowers_without_touching_a_body_that_constructs_ok() {
1585        let program = checked_context_program(
1586            r#"
1587context demo
1588
1589service Api from http {
1590  on GET("/ping") () -> Effect[HttpResult[String]] by v: Visitor {
1591    Effect.pure(Ok("pong"))
1592  }
1593}
1594"#,
1595        );
1596        let service = find_service(&program, "Api");
1597        let handler = find_service_handler(
1598            service,
1599            &HandlerKind::Http {
1600                method: bynk_syntax::ast::HttpMethod::Get,
1601                path: "/ping".to_string(),
1602            },
1603        );
1604        let (params, _given, ret, effectful) =
1605            lower_service_handler_signature_ir(handler, &program);
1606        assert!(params.is_empty(), "`() -> ...` declares no parameters");
1607        assert!(effectful, "an `Effect[...]` return type");
1608        assert!(matches!(
1609            &*program.program().ty_intern.get(ret),
1610            Ty::Effect(_)
1611        ));
1612    }
1613
1614    /// Mirrors `bynk-tests/tests/fixtures/positive/236_websocket_chatroom` in
1615    /// full — `on open`/`on message`/`on close` all present, the same
1616    /// shape the real fixture uses — so this fixture's own tests can cover
1617    /// both the owned (`on open`) and borrowed (`on message`/`on close`,
1618    /// P6.13, #1179) `connection` cases. A held `Connection` needs real
1619    /// disposal to certify (the linearity pass), so `on open` transfers it
1620    /// into a trivial `Room` agent rather than dropping it.
1621    fn websocket_service_fixture() -> CheckedProgram {
1622        checked_context_program(
1623            r#"
1624context demo
1625
1626type RoomId = String
1627type UserId = String
1628type ServerFrame = { text: String }
1629type ClientFrame = { text: String }
1630
1631actor Participant { auth = Bearer(secret = "AUTH_SECRET"), identity = UserId }
1632
1633service ChatGateway from websocket(in: ClientFrame, out: ServerFrame) {
1634  on open (roomId: RoomId) -> Effect[()] by user: Participant {
1635    let _ <- connection.send(ServerFrame { text: "welcome" })
1636    let _ <- Room(roomId).join(user.identity, connection)
1637    ()
1638  }
1639
1640  on message (roomId: RoomId, frame: ClientFrame) -> Effect[()] by user: Participant {
1641    let _ <- connection.send(ServerFrame { text: frame.text })
1642    let _ <- Room(roomId).post(user.identity, frame.text)
1643    ()
1644  }
1645
1646  on close (roomId: RoomId) -> Effect[()] by user: Participant {
1647    let _ <- Room(roomId).leave(user.identity)
1648    ()
1649  }
1650}
1651
1652agent Room {
1653  key id: RoomId
1654  store members: Set[UserId]
1655  store conns: Map[UserId, Connection[ServerFrame]]
1656
1657  on call join(u: UserId, conn: Connection[ServerFrame]) -> Effect[()] {
1658    let _ <- members.add(u)
1659    let _ <- conns.put(u, conn)
1660    ()
1661  }
1662
1663  on call leave(u: UserId) -> Effect[()] {
1664    let _ <- members.remove(u)
1665    let _ <- conns.remove(u)
1666    ()
1667  }
1668
1669  on call post(sender: UserId, text: String) -> Effect[()] {
1670    let _ <- conns.parTraverse((c: Connection[ServerFrame]) => c.send(ServerFrame { text: text }))
1671    ()
1672  }
1673}
1674"#,
1675        )
1676    }
1677
1678    #[test]
1679    fn websocket_protocol_descriptor_lowers_its_frame_types() {
1680        let program = websocket_service_fixture();
1681        let service = find_service(&program, "ChatGateway");
1682        let ir = lower_protocol_ir(&service.protocol, &program);
1683        let ProtocolIr::WebSocket { in_ty, out_ty } = ir else {
1684            panic!("expected ProtocolIr::WebSocket, got {:?}", ir)
1685        };
1686        let tys = &program.program().ty_intern;
1687        assert_eq!(in_ty.display(tys), "ClientFrame");
1688        assert_eq!(out_ty.display(tys), "ServerFrame");
1689    }
1690
1691    #[test]
1692    fn lower_event_pattern_ir_reshapes_literal_and_variant_fields() {
1693        // Review of #1180: the `Events` protocol path had zero coverage.
1694        // `lower_protocol_ir`'s own `Events` arm genuinely can't be driven
1695        // through `checked_context_program` — a real `from Events(E)`
1696        // subscription needs `consumes bynk { Events }`, which this
1697        // reduced harness's `CrossContextInfo::default()` doesn't support
1698        // (the same limitation named in `checked_context_program`'s own
1699        // doc comment). `lower_event_pattern_ir` itself has no such
1700        // excuse: it takes no `&CheckedProgram`, resolves nothing, and
1701        // cannot panic — pure AST reshaping — so it's pinned directly
1702        // against a parsed (not checked or certified) `EventPattern`.
1703        let source = r#"
1704context demo
1705
1706type Status = | Active | Inactive
1707
1708event OrderPlaced = {
1709  status: Status,
1710  count: Int,
1711}
1712
1713service Subscriber from Events(OrderPlaced { status: Active, count: 3, .. }) {
1714  on event(o: OrderPlaced) -> Effect[()] {
1715    Effect.pure(())
1716  }
1717}
1718"#;
1719        let tokens = lexer::tokenize(source).expect("lex");
1720        let unit = parser::parse_unit(&tokens, source).expect("parse");
1721        let SourceUnit::Context(ctx) = unit else {
1722            panic!("expected a context unit, got {unit:?}")
1723        };
1724        let service = ctx
1725            .items
1726            .iter()
1727            .find_map(|item| {
1728                if let CommonsItem::Service(s) = item
1729                    && s.name.name == "Subscriber"
1730                {
1731                    Some(s)
1732                } else {
1733                    None
1734                }
1735            })
1736            .expect("no service named `Subscriber` in this fixture");
1737        let ServiceProtocol::Events { pattern, .. } = &service.protocol else {
1738            panic!(
1739                "expected ServiceProtocol::Events, got {:?}",
1740                service.protocol
1741            )
1742        };
1743        let pattern = pattern
1744            .as_ref()
1745            .expect("expected a structural pattern on this Events subscription");
1746
1747        let ir = lower_event_pattern_ir(pattern);
1748        assert_eq!(ir.fields.len(), 2, "declaration order preserved");
1749        assert_eq!(ir.fields[0].0, "status");
1750        assert!(
1751            matches!(&ir.fields[0].1, EventPatternValueIr::Variant { tag } if tag == "Active"),
1752            "expected a bare nullary variant tag (the AST's own optional qualifying type_name \
1753             dropped), got {:?}",
1754            ir.fields[0].1
1755        );
1756        assert_eq!(ir.fields[1].0, "count");
1757        assert!(
1758            matches!(
1759                &ir.fields[1].1,
1760                EventPatternValueIr::Const(ConstVal::Int(3))
1761            ),
1762            "expected a literal Int constant, got {:?}",
1763            ir.fields[1].1
1764        );
1765    }
1766
1767    /// P6.29 (design/tracks/the-ir.md §6a): pins `capability_op_sig_from_commons`
1768    /// against the same fixture as its `CheckedProgram`-driven sibling above —
1769    /// same param names/order, found by name alone from `TypedCommons`, no
1770    /// `CheckedProgram` needed at the call site (`emitter/lower.rs`'s
1771    /// `cap_op_param_names` only ever had one).
1772    #[test]
1773    fn capability_op_sig_from_commons_finds_the_named_op() {
1774        let program = checked_context_program(
1775            r#"
1776context demo
1777
1778capability Store {
1779  fn get(key: String) -> Effect[Int]
1780  fn put(key: String, value: Int) -> Effect[()]
1781}
1782"#,
1783        );
1784        let commons = program.program();
1785
1786        let get = capability_op_sig_from_commons(commons, "Store", "get")
1787            .expect("Store.get should resolve");
1788        assert_eq!(get.params.len(), 1);
1789        assert_eq!(get.params[0].0, "key");
1790
1791        let put = capability_op_sig_from_commons(commons, "Store", "put")
1792            .expect("Store.put should resolve");
1793        assert_eq!(put.params.len(), 2);
1794        assert_eq!(put.params[0].0, "key");
1795        assert_eq!(put.params[1].0, "value");
1796
1797        // Same fallthrough-to-`None` behaviour the by-hand AST walk it
1798        // replaces had, for both an unknown capability and a known
1799        // capability's unknown op — mirrors `cap_op_param_names`'s own prior
1800        // fallthrough-to-empty-`Vec` at the caller.
1801        assert!(capability_op_sig_from_commons(commons, "NoSuchCap", "get").is_none());
1802        assert!(capability_op_sig_from_commons(commons, "Store", "no_such_op").is_none());
1803    }
1804
1805    #[test]
1806    fn lower_cap_ref_ir_local_capability_has_no_context() {
1807        let cap_ref = CapRef {
1808            context: None,
1809            name: bynk_syntax::ast::Ident {
1810                name: "Clock".to_string(),
1811                span: Span::default(),
1812            },
1813            span: Span::default(),
1814        };
1815        let ir = lower_cap_ref_ir(&cap_ref);
1816        assert_eq!(ir.context, None);
1817        assert_eq!(ir.name, "Clock");
1818    }
1819
1820    #[test]
1821    fn lower_cap_ref_ir_preserves_a_cross_context_prefix() {
1822        // `given B.Cap` (v0.15) is out of `checked_context_program`'s own
1823        // fixture scope (no cross-context `uses`/`consumes`, feedback
1824        // memory "bynk-emit test harness scope") — pins `lower_cap_ref_ir`'s
1825        // own `QualifiedName -> String` flattening directly against a
1826        // hand-built `CapRef`, the same posture the external-provider test
1827        // above already takes for a branch the fixture cannot reach.
1828        let cap_ref = CapRef {
1829            context: Some(QualifiedName {
1830                parts: vec![bynk_syntax::ast::Ident {
1831                    name: "Billing".to_string(),
1832                    span: Span::default(),
1833                }],
1834                span: Span::default(),
1835            }),
1836            name: bynk_syntax::ast::Ident {
1837                name: "Ledger".to_string(),
1838                span: Span::default(),
1839            },
1840            span: Span::default(),
1841        };
1842        let ir = lower_cap_ref_ir(&cap_ref);
1843        assert_eq!(ir.context.as_deref(), Some("Billing"));
1844        assert_eq!(ir.name, "Ledger");
1845    }
1846
1847    /// Review of #1229 (#1228): `lower_route_cache_ir`/`lower_route_limit_ir`
1848    /// take no `&CheckedProgram`, resolve nothing, and cannot panic — the same
1849    /// posture `lower_event_pattern_ir`'s own test above already established a
1850    /// parsed-not-checked fixture for, and for the identical reason here: their
1851    /// defensive branches (a non-`GET` handler, a `maxAge`-less `@cache`, a
1852    /// non-positive `maxBody`) are exactly the shapes `bynk-check`'s
1853    /// `bynk.http.cache_on_non_get`/`cache_bad_max_age`/`limit_bad_max_body`
1854    /// (`bynk-check/src/context_checks.rs`) already reject, so a real checked
1855    /// program can never reach them and the fixture bless run never exercises
1856    /// them either.
1857    fn parsed_only_context(source: &str) -> bynk_syntax::ast::Context {
1858        let tokens = lexer::tokenize(source).expect("lex");
1859        let unit = parser::parse_unit(&tokens, source).expect("parse");
1860        let SourceUnit::Context(ctx) = unit else {
1861            panic!("expected a context unit, got {unit:?}")
1862        };
1863        ctx
1864    }
1865
1866    fn parsed_handler<'a>(
1867        ctx: &'a bynk_syntax::ast::Context,
1868        service: &str,
1869        index: usize,
1870    ) -> &'a Handler {
1871        let service = ctx
1872            .items
1873            .iter()
1874            .find_map(|item| {
1875                if let CommonsItem::Service(s) = item
1876                    && s.name.name == service
1877                {
1878                    Some(s)
1879                } else {
1880                    None
1881                }
1882            })
1883            .unwrap_or_else(|| panic!("no service named `{service}` in this fixture"));
1884        &service.handlers[index]
1885    }
1886
1887    #[test]
1888    fn lower_route_cache_ir_reads_maxage_and_scope_off_a_get_handler() {
1889        let ctx = parsed_only_context(
1890            r#"
1891context demo
1892
1893service Api from http {
1894  @cache(maxAge: 5.minutes, scope: public)
1895  on GET("/config") () -> Effect[HttpResult[String]] by v: Visitor {
1896    Ok("cfg")
1897  }
1898
1899  @cache(maxAge: 30.seconds)
1900  on GET("/private") () -> Effect[HttpResult[String]] by v: Visitor {
1901    Ok("priv")
1902  }
1903
1904  on GET("/plain") () -> Effect[HttpResult[String]] by v: Visitor {
1905    Ok("plain")
1906  }
1907}
1908"#,
1909        );
1910        let public_cache = lower_route_cache_ir(parsed_handler(&ctx, "Api", 0))
1911            .unwrap_or_else(|| panic!("expected Some(CacheIr) for a well-formed @cache"));
1912        assert_eq!(public_cache.max_age_secs, 300, "5.minutes in whole seconds");
1913        assert_eq!(public_cache.scope, "public");
1914
1915        let default_scope_cache = lower_route_cache_ir(parsed_handler(&ctx, "Api", 1))
1916            .unwrap_or_else(|| panic!("expected Some(CacheIr) with no explicit scope:"));
1917        assert_eq!(default_scope_cache.max_age_secs, 30);
1918        assert_eq!(
1919            default_scope_cache.scope, "private",
1920            "no scope: argument written — must default to private"
1921        );
1922
1923        assert!(
1924            lower_route_cache_ir(parsed_handler(&ctx, "Api", 2)).is_none(),
1925            "no @cache annotation at all must yield None"
1926        );
1927    }
1928
1929    #[test]
1930    fn lower_route_cache_ir_returns_none_for_a_non_get_handler_even_with_a_cache_annotation() {
1931        // `bynk.http.cache_on_non_get` already rejects this at check time — this
1932        // pins the lowering function's own independent guard, not reachable
1933        // through a real certified program.
1934        let ctx = parsed_only_context(
1935            r#"
1936context demo
1937
1938service Api from http {
1939  @cache(maxAge: 5.minutes)
1940  on POST("/items") (body: String) -> Effect[HttpResult[String]] by v: Visitor {
1941    Created(body)
1942  }
1943}
1944"#,
1945        );
1946        assert!(
1947            lower_route_cache_ir(parsed_handler(&ctx, "Api", 0)).is_none(),
1948            "a @cache on a non-GET handler must not construct a CacheIr"
1949        );
1950    }
1951
1952    #[test]
1953    fn lower_route_cache_ir_discards_an_otherwise_well_formed_scope_when_maxage_is_missing() {
1954        // `bynk.http.cache_bad_max_age` already rejects a maxAge-less @cache at
1955        // check time — this pins that `scope`'s own well-formedness does not
1956        // rescue a missing `maxAge` into a partial CacheIr.
1957        let ctx = parsed_only_context(
1958            r#"
1959context demo
1960
1961service Api from http {
1962  @cache(scope: public)
1963  on GET("/broken") () -> Effect[HttpResult[String]] by v: Visitor {
1964    Ok("x")
1965  }
1966}
1967"#,
1968        );
1969        assert!(
1970            lower_route_cache_ir(parsed_handler(&ctx, "Api", 0)).is_none(),
1971            "a well-formed scope: must not survive a missing maxAge:"
1972        );
1973    }
1974
1975    #[test]
1976    fn lower_route_limit_ir_reads_maxbody_off_a_route_annotation() {
1977        let ctx = parsed_only_context(
1978            r#"
1979context demo
1980
1981service Api from http {
1982  @limit(maxBody: 26_214_400)
1983  on POST("/bulk") (body: String) -> Effect[HttpResult[String]] by v: Visitor {
1984    Created(body)
1985  }
1986
1987  on POST("/upload") (body: String) -> Effect[HttpResult[String]] by v: Visitor {
1988    Created(body)
1989  }
1990}
1991"#,
1992        );
1993        assert_eq!(
1994            lower_route_limit_ir(parsed_handler(&ctx, "Api", 0)),
1995            Some(26_214_400)
1996        );
1997        assert!(
1998            lower_route_limit_ir(parsed_handler(&ctx, "Api", 1)).is_none(),
1999            "no @limit annotation at all must yield None — the caller applies the \
2000             service-wide default, this function does not know it"
2001        );
2002    }
2003
2004    #[test]
2005    fn lower_route_limit_ir_returns_none_for_a_non_positive_maxbody() {
2006        // `bynk.http.limit_bad_max_body` already rejects a non-positive maxBody
2007        // at check time — this pins the lowering function's own independent
2008        // guard. `None` here matters specifically because the caller's own
2009        // fallback composition (`effective_max_body`) treats it as "no
2010        // route-level override," falling through to the service-wide default —
2011        // not as "an explicit zero-byte cap."
2012        let ctx = parsed_only_context(
2013            r#"
2014context demo
2015
2016service Api from http {
2017  @limit(maxBody: 0)
2018  on POST("/zero") (body: String) -> Effect[HttpResult[String]] by v: Visitor {
2019    Created(body)
2020  }
2021}
2022"#,
2023        );
2024        assert!(
2025            lower_route_limit_ir(parsed_handler(&ctx, "Api", 0)).is_none(),
2026            "a non-positive maxBody must not construct Some(0)"
2027        );
2028    }
2029
2030    /// Every `body_writes_state` classification (#1165's [DECISION B]/
2031    /// [DECISION C], the shipped `emit_agent` implicit-commit decision) lives
2032    /// on one agent — each handler exercises exactly one case so a failing
2033    /// assertion names its own scenario unambiguously. Until Slice D1 of
2034    /// `#1542` these pinned the same function through the deleted IR-side
2035    /// `CommitShape` constructor; they now pin it directly.
2036    fn store_write_fixture() -> CheckedProgram {
2037        checked_context_program(
2038            r#"
2039context demo
2040
2041type Box = { n: Int }
2042
2043fn Box.put(self, x: Int) -> Effect[()] {
2044  Effect.pure(())
2045}
2046
2047capability Clock {
2048  fn now() -> Effect[Int]
2049}
2050
2051provides Clock = FixedClock {
2052  fn now() -> Effect[Int] {
2053    42
2054  }
2055}
2056
2057agent Widget {
2058  key id: String
2059  store items: Map[String, Int]
2060  store active: Cell[Bool] = true
2061  store tags: Set[String]
2062  store history: Log[String]
2063
2064  on call readOnlyPlain() -> Effect[()] {
2065    Effect.pure(())
2066  }
2067
2068  on call readOnlyQuery() -> Effect[Int] {
2069    items.size()
2070  }
2071
2072  on call nestedMutation(xs: List[String], flag: Bool) -> Effect[()] {
2073    if flag {
2074      match flag {
2075        true => xs.forEach((x) => items.put(x, 1))
2076        false => Effect.pure(())
2077      }
2078    } else {
2079      Effect.pure(())
2080    }
2081  }
2082
2083  on call bareAssign(v: Bool) -> Effect[()] {
2084    active := v
2085    Effect.pure(())
2086  }
2087
2088  on call shadowedName(items: Box, x: Int) -> Effect[()] {
2089    let _ <- items.put(x)
2090    Effect.pure(())
2091  }
2092
2093  on call cellUpdate() -> Effect[()] {
2094    let _ <- active.update((b) => !b)
2095    Effect.pure(())
2096  }
2097
2098  on call setAdd(t: String) -> Effect[()] {
2099    let _ <- tags.add(t)
2100    Effect.pure(())
2101  }
2102
2103  on call logAppend(t: String) -> Effect[()] given Clock {
2104    let _ <- history.append(t)
2105    Effect.pure(())
2106  }
2107}
2108"#,
2109        )
2110    }
2111
2112    /// #2220: the agent state model recomputes the emitter's commit condition
2113    /// syntactically (`bynk_check::agent_state::handler_commits`), because
2114    /// the state view runs on a re-parse with no resolved callees. Pin the two
2115    /// together on every handler of a fixture built to probe where they could
2116    /// part: each store kind's mutating ops, a non-mutating query, writes
2117    /// nested in `if`/`match`/lambdas, a tail write, a query before a write, and a
2118    /// parameter, a `let`,
2119    /// a match binding, a lambda parameter and a `let` in a block-bodied lambda
2120    /// that shadow a store field.
2121    #[test]
2122    fn the_state_models_commit_condition_agrees_with_body_writes_state() {
2123        let extra = checked_context_program(
2124            r#"
2125context demo
2126
2127type Box = { n: Int }
2128
2129fn Box.put(self, x: Int) -> Effect[()] {
2130  Effect.pure(())
2131}
2132
2133agent Gadget {
2134  key id: String
2135  store items: Map[String, Int]
2136  store tags: Set[String]
2137
2138  on call letShadow() -> Effect[()] {
2139    let items = Box { n: 1 }
2140    let _ <- items.put(2)
2141    Effect.pure(())
2142  }
2143
2144  on call matchShadow(b: Option[Box]) -> Effect[()] {
2145    match b {
2146      Some(items) => items.put(1)
2147      None => Effect.pure(())
2148    }
2149  }
2150
2151  on call lambdaShadow(bs: List[Box]) -> Effect[()] {
2152    bs.forEach((items) => items.put(1))
2153  }
2154
2155  on call blockLambdaShadow(bs: List[Box]) -> Effect[()] {
2156    bs.forEach((b) => {
2157      let items = b
2158      items.put(1)
2159    })
2160  }
2161
2162  on call tailWrite(t: String) -> Effect[()] {
2163    tags.add(t)
2164  }
2165
2166  on call queryThenWrite(t: String) -> Effect[Bool] {
2167    let present <- tags.contains(t)
2168    if present { true } else {
2169      let _ <- tags.add(t)
2170      false
2171    }
2172  }
2173}
2174"#,
2175        );
2176        let mut compared = 0;
2177        for (program, agent) in [(store_write_fixture(), "Widget"), (extra, "Gadget")] {
2178            let a = find_agent(&program, agent);
2179            for h in &a.handlers {
2180                let name = h.method_name.as_ref().map_or("call", |m| m.name.as_str());
2181                assert_eq!(
2182                    bynk_check::agent_state::handler_commits(a, h),
2183                    body_writes_state(&h.body, program.program()),
2184                    "`{agent}.{name}`: the state model and the emitter disagree on whether it commits"
2185                );
2186                compared += 1;
2187            }
2188        }
2189        assert_eq!(compared, 14, "every fixture handler was compared");
2190    }
2191
2192    fn find_handler<'a>(agent: &'a AgentDecl, name: &str) -> &'a Handler {
2193        agent
2194            .handlers
2195            .iter()
2196            .find(|h| h.method_name.as_ref().is_some_and(|m| m.name == name))
2197            .unwrap_or_else(|| panic!("no handler named `{name}` on agent `{}`", agent.name.name))
2198    }
2199
2200    /// A queue consumer's own body is the one shape this module's own
2201    /// pre-existing gaps make genuinely unlowerable today, not just
2202    /// awkward to fixture around: `Effect[QueueResult]` is mandatory
2203    /// (`bynk.queue.return_not_https`-adjacent gate, `context_checks.rs:
2204    /// 3730-3744`), and every `QueueResult` value — `Ack`, `NotFound`,
2205    /// `Retry(reason)` — is a bare or qualified built-in-sum variant
2206    /// reference (a contextual, `expected`-type-driven disambiguation).
2207    /// Unlike `HttpResult`'s `Ok`/`Err`, `QueueResult`'s
2208    /// own variants also don't resolve inside an ordinary free `fn` body at
2209    /// all (confirmed empirically: `bynk.resolve.unknown_name`) — the
2210    /// checker's own special-case for them (`checker.rs:3507`) is reached
2211    /// only via a real handler body's own `Ctx::return_ty`, which the
2212    /// resolver's eager pass over an ordinary `fn` never sets up — so the
2213    /// `fn ok(s) -> HttpResult[String] { Ok(s) }` indirection every other
2214    /// HTTP/cron fixture in this module uses has no queue-shaped
2215    /// equivalent. Two tests, not one, cover what's actually true here.
2216    fn queue_service_fixture() -> CheckedProgram {
2217        checked_context_program(
2218            r#"
2219context demo
2220
2221type EmailJob = { to: String }
2222
2223service Outbox from queue("orders") {
2224  on message(m: EmailJob) -> Effect[QueueResult] {
2225    Ack
2226  }
2227}
2228"#,
2229        )
2230    }
2231
2232    #[test]
2233    fn a_queue_services_protocol_and_handler_signature_lower_correctly() {
2234        // The protocol descriptor (standalone, mirroring `lower_protocol_ir`'s
2235        // own precedent for `from websocket`) and the handler's own
2236        // `params`/`given`/`effectful` via `lower_service_handler_signature_ir`
2237        // — the two shape readers `bynk-emit` consumes for a queue service.
2238        let program = queue_service_fixture();
2239        let service = find_service(&program, "Outbox");
2240        assert!(matches!(
2241            lower_protocol_ir(&service.protocol, &program),
2242            ProtocolIr::Queue { name } if name == "orders"
2243        ));
2244        let handler = find_service_handler(service, &HandlerKind::Message);
2245        let (params, given, _ret, effectful) =
2246            lower_service_handler_signature_ir(handler, &program);
2247        assert_eq!(params.len(), 1);
2248        assert_eq!(params[0].0, "m");
2249        assert!(given.is_empty());
2250        assert!(effectful, "every service handler returns Effect[T]");
2251    }
2252
2253    #[test]
2254    fn store_field_with_an_unresolvable_type_is_rejected_before_lowering() {
2255        // #1187's Agent state-field slice, step 0, found that no checker pass
2256        // validated a store field's own type reference, so `store x:
2257        // Cell[Bogus]` certified and reached `resolve_store_field_ty`, whose
2258        // `Ty::Unit` fallback this test used to pin. #1679 closed that gap: the
2259        // resolver now walks agent store field types, so the program is
2260        // rejected with `bynk.resolve.unknown_type` before lowering, and the
2261        // fallback is defensive only.
2262        let source = r#"
2263context demo
2264
2265agent Widget {
2266  key id: String
2267  store x: Cell[Bogus] = "hello"
2268
2269  on call touch() -> Effect[()] {
2270    Effect.pure(())
2271  }
2272}
2273"#;
2274        let tokens = lexer::tokenize(source).expect("lex");
2275        let unit = parser::parse_unit(&tokens, source).expect("parse");
2276        let SourceUnit::Context(ctx) = unit else {
2277            panic!("expected a context unit, got {unit:?}")
2278        };
2279        let commons = Commons {
2280            name: ctx.name,
2281            items: ctx.items,
2282            uses: ctx.uses,
2283            documentation: ctx.documentation,
2284            form: ctx.form,
2285            span: ctx.span,
2286            trivia: ctx.trivia,
2287            trailing_comments: ctx.trailing_comments,
2288        };
2289        let Err(errors) = resolver::resolve(commons) else {
2290            panic!("an unknown store type must be rejected by the resolver")
2291        };
2292        assert!(
2293            errors
2294                .iter()
2295                .any(|e| e.category == "bynk.resolve.unknown_type" && e.message.contains("Bogus")),
2296            "{errors:?}"
2297        );
2298    }
2299
2300    #[test]
2301    fn body_writes_state_is_false_for_a_plain_body() {
2302        let program = store_write_fixture();
2303        let handler = find_handler(find_agent(&program, "Widget"), "readOnlyPlain");
2304        assert!(!body_writes_state(&handler.body, program.program()));
2305    }
2306
2307    #[test]
2308    fn body_writes_state_is_false_for_a_non_mutating_store_read() {
2309        let program = store_write_fixture();
2310        let handler = find_handler(find_agent(&program, "Widget"), "readOnlyQuery");
2311        assert!(!body_writes_state(&handler.body, program.program()));
2312    }
2313
2314    #[test]
2315    fn body_writes_state_is_false_for_a_locally_shadowed_store_field_name() {
2316        let program = store_write_fixture();
2317        let handler = find_handler(find_agent(&program, "Widget"), "shadowedName");
2318        assert!(!body_writes_state(&handler.body, program.program()));
2319    }
2320
2321    #[test]
2322    fn body_writes_state_is_true_for_a_write_nested_in_if_match_lambda() {
2323        let program = store_write_fixture();
2324        let handler = find_handler(find_agent(&program, "Widget"), "nestedMutation");
2325        assert!(body_writes_state(&handler.body, program.program()));
2326    }
2327
2328    #[test]
2329    fn body_writes_state_is_true_for_a_bare_cell_assign() {
2330        let program = store_write_fixture();
2331        let handler = find_handler(find_agent(&program, "Widget"), "bareAssign");
2332        assert!(body_writes_state(&handler.body, program.program()));
2333    }
2334
2335    #[test]
2336    fn body_writes_state_is_true_for_a_cell_update_method_call() {
2337        let program = store_write_fixture();
2338        let handler = find_handler(find_agent(&program, "Widget"), "cellUpdate");
2339        assert!(body_writes_state(&handler.body, program.program()));
2340    }
2341
2342    #[test]
2343    fn body_writes_state_is_true_for_a_set_add_method_call() {
2344        let program = store_write_fixture();
2345        let handler = find_handler(find_agent(&program, "Widget"), "setAdd");
2346        assert!(body_writes_state(&handler.body, program.program()));
2347    }
2348
2349    #[test]
2350    fn body_writes_state_is_true_for_a_log_append_method_call() {
2351        let program = store_write_fixture();
2352        let handler = find_handler(find_agent(&program, "Widget"), "logAppend");
2353        assert!(body_writes_state(&handler.body, program.program()));
2354    }
2355
2356    fn checked_program(source: &str) -> CheckedProgram {
2357        let tokens = lexer::tokenize(source).expect("lex");
2358        let (commons, warnings) = parser::parse_with_warnings(&tokens, source).expect("parse");
2359        let resolved = resolver::resolve(commons).expect("resolve");
2360        let typed = checker::check(resolved).expect("check");
2361        checker::certify(typed, warnings).expect("certify")
2362    }
2363
2364    fn find_type<'a>(program: &'a CheckedProgram, name: &str) -> &'a Arc<TypeDecl> {
2365        program
2366            .program()
2367            .types
2368            .get(name)
2369            .unwrap_or_else(|| panic!("no type named `{name}` in this fixture"))
2370    }
2371
2372    fn find_capability<'a>(program: &'a CheckedProgram, name: &str) -> &'a CapabilityDecl {
2373        program
2374            .program()
2375            .commons
2376            .items
2377            .iter()
2378            .find_map(|item| {
2379                if let CommonsItem::Capability(c) = item
2380                    && c.name.name == name
2381                {
2382                    Some(c)
2383                } else {
2384                    None
2385                }
2386            })
2387            .unwrap_or_else(|| panic!("no capability named `{name}` in this fixture"))
2388    }
2389
2390    fn find_provider<'a>(program: &'a CheckedProgram, name: &str) -> &'a ProviderDecl {
2391        program
2392            .program()
2393            .commons
2394            .items
2395            .iter()
2396            .find_map(|item| {
2397                if let CommonsItem::Provider(p) = item
2398                    && p.provider_name.name == name
2399                {
2400                    Some(p)
2401                } else {
2402                    None
2403                }
2404            })
2405            .unwrap_or_else(|| panic!("no provider named `{name}` in this fixture"))
2406    }
2407
2408    // The six `type_shape_*` tests below, the capability/provider/handler-kind
2409    // tests after them, and the `body_writes_state_*` tests above were all
2410    // re-created by Slice D1 of `#1542`: each pinned a kept helper only
2411    // through a deleted item constructor (`IrItem::Type`/`Capability`/
2412    // `Provider`/`Service`) and now calls the helper directly, asserting the
2413    // same facts minus the constructor's own wrapper field.
2414
2415    #[test]
2416    fn type_shape_record_resolves_fields_and_generic_rigid_vars() {
2417        let program = checked_program(
2418            r#"
2419commons demo {
2420  type Box[T] = { value: T }
2421}
2422"#,
2423        );
2424        let shape = lower_type_shape_ir(find_type(&program, "Box"), &program);
2425        let TypeShape::Record { fields } = &shape else {
2426            panic!("expected TypeShape::Record, got {shape:?}")
2427        };
2428        assert_eq!(fields.len(), 1);
2429        assert_eq!(fields[0].0, "value");
2430        assert!(matches!(
2431            &*program.program().ty_intern.get(fields[0].1),
2432            Ty::Var(name) if name == "T"
2433        ));
2434    }
2435
2436    #[test]
2437    fn type_shape_sum_resolves_variant_payloads_and_embeds() {
2438        let program = checked_program(
2439            r#"
2440commons demo {
2441  type PaymentError = enum { Declined, InsufficientFunds }
2442
2443  type OrderError =
2444    | OutOfStock(sku: String, qty: Int)
2445    | Payment(reason: PaymentError)
2446    embeds PaymentError as Payment
2447}
2448"#,
2449        );
2450        let shape = lower_type_shape_ir(find_type(&program, "OrderError"), &program);
2451        let TypeShape::Sum { variants, embeds } = &shape else {
2452            panic!("expected TypeShape::Sum, got {shape:?}")
2453        };
2454        assert_eq!(variants.len(), 2);
2455        assert_eq!(variants[0].0, "OutOfStock");
2456        assert_eq!(variants[0].1.len(), 2);
2457        assert_eq!(variants[0].1[0].0, "sku");
2458        assert!(matches!(
2459            &*program.program().ty_intern.get(variants[0].1[0].1),
2460            Ty::Base(bynk_syntax::ast::BaseType::String)
2461        ));
2462        assert_eq!(variants[0].1[1].0, "qty");
2463        assert!(matches!(
2464            &*program.program().ty_intern.get(variants[0].1[1].1),
2465            Ty::Base(bynk_syntax::ast::BaseType::Int)
2466        ));
2467        assert_eq!(variants[1].0, "Payment");
2468        assert_eq!(variants[1].1.len(), 1);
2469        assert_eq!(variants[1].1[0].0, "reason");
2470
2471        assert_eq!(embeds.len(), 1);
2472        let (source, tag) = &embeds[0];
2473        assert_eq!(tag, "Payment");
2474        let Ty::Named { name, .. } = &*program.program().ty_intern.get(*source) else {
2475            panic!("expected embeds source to resolve to a named type")
2476        };
2477        assert_eq!(name, "PaymentError");
2478    }
2479
2480    #[test]
2481    fn type_shape_refined_and_opaque_cover_bare_and_predicated_and_opaque_forms() {
2482        let program = checked_program(
2483            r#"
2484commons demo {
2485  type Age = Int where Positive
2486  type UserId = opaque Int
2487  type Bare = Int
2488}
2489"#,
2490        );
2491        let TypeShape::Refined {
2492            base,
2493            refinement,
2494            opaque,
2495        } = lower_type_shape_ir(find_type(&program, "Age"), &program)
2496        else {
2497            panic!("expected TypeShape::Refined for Age")
2498        };
2499        assert_eq!(base, bynk_syntax::ast::BaseType::Int);
2500        assert!(refinement.is_some());
2501        assert!(!opaque);
2502
2503        let TypeShape::Refined {
2504            refinement, opaque, ..
2505        } = lower_type_shape_ir(find_type(&program, "UserId"), &program)
2506        else {
2507            panic!("expected TypeShape::Refined for UserId")
2508        };
2509        assert!(refinement.is_none());
2510        assert!(opaque);
2511
2512        let TypeShape::Refined {
2513            refinement, opaque, ..
2514        } = lower_type_shape_ir(find_type(&program, "Bare"), &program)
2515        else {
2516            panic!("expected TypeShape::Refined for Bare")
2517        };
2518        assert!(refinement.is_none());
2519        assert!(!opaque);
2520    }
2521
2522    #[test]
2523    fn type_shape_sum_covers_a_payload_less_variant() {
2524        let program = checked_program(
2525            r#"
2526commons demo {
2527  type PaymentError = enum { Declined, InsufficientFunds }
2528}
2529"#,
2530        );
2531        let shape = lower_type_shape_ir(find_type(&program, "PaymentError"), &program);
2532        let TypeShape::Sum { variants, embeds } = &shape else {
2533            panic!("expected TypeShape::Sum, got {shape:?}")
2534        };
2535        assert_eq!(variants.len(), 2);
2536        assert_eq!(variants[0].0, "Declined");
2537        assert!(
2538            variants[0].1.is_empty(),
2539            "a bare variant carries no payload"
2540        );
2541        assert_eq!(variants[1].0, "InsufficientFunds");
2542        assert!(variants[1].1.is_empty());
2543        assert!(embeds.is_empty());
2544    }
2545
2546    #[test]
2547    fn type_shape_record_drops_a_fields_own_inline_refinement() {
2548        // Decision B extension, the vocabulary's own `TypeShape::Record` doc
2549        // comment: a field's inline `where` clause is a construction-time
2550        // constraint the checker already enforces, not part of the emitted
2551        // shape — pin that the field still lowers to `(name, ty)` with the
2552        // refinement silently absent, not that lowering rejects it.
2553        let program = checked_program(
2554            r#"
2555commons demo {
2556  type Account = { balance: Int where NonNegative }
2557}
2558"#,
2559        );
2560        let shape = lower_type_shape_ir(find_type(&program, "Account"), &program);
2561        let TypeShape::Record { fields } = &shape else {
2562            panic!("expected TypeShape::Record, got {shape:?}")
2563        };
2564        assert_eq!(fields.len(), 1);
2565        assert_eq!(fields[0].0, "balance");
2566        assert!(matches!(
2567            &*program.program().ty_intern.get(fields[0].1),
2568            Ty::Base(bynk_syntax::ast::BaseType::Int)
2569        ));
2570    }
2571
2572    #[test]
2573    fn type_shape_record_resolves_a_generic_type_application_field() {
2574        // The `TypeRef::App` arm of `resolve_type_ref_in` — the one arm
2575        // that returns `None` for an unknown/unapplied name, and so the one
2576        // most likely to silently hit this pass's own ADR 0334 panic if the
2577        // field's resolution were ever wired up wrong.
2578        let program = checked_program(
2579            r#"
2580commons demo {
2581  type Box[T] = { value: T }
2582  type Wrapper = { boxed: Box[Int] }
2583}
2584"#,
2585        );
2586        let shape = lower_type_shape_ir(find_type(&program, "Wrapper"), &program);
2587        let TypeShape::Record { fields } = &shape else {
2588            panic!("expected TypeShape::Record, got {shape:?}")
2589        };
2590        assert_eq!(fields.len(), 1);
2591        assert_eq!(fields[0].0, "boxed");
2592        let Ty::Named { name, args, .. } = &*program.program().ty_intern.get(fields[0].1) else {
2593            panic!("expected `boxed` to resolve to a named type")
2594        };
2595        assert_eq!(name, "Box");
2596        assert_eq!(args.len(), 1);
2597        assert!(matches!(
2598            &*program.program().ty_intern.get(args[0]),
2599            Ty::Base(bynk_syntax::ast::BaseType::Int)
2600        ));
2601    }
2602
2603    #[test]
2604    fn lower_capability_ops_ir_assembles_ops_in_declaration_order() {
2605        let program = checked_context_program(
2606            r#"
2607context demo
2608
2609capability Store {
2610  fn get(key: String) -> Effect[Int]
2611  fn put(key: String, value: Int) -> Effect[()]
2612}
2613"#,
2614        );
2615        let ops = lower_capability_ops_ir(find_capability(&program, "Store"), &program);
2616        assert_eq!(ops.len(), 2, "declaration order preserved");
2617
2618        assert_eq!(ops[0].name, "get");
2619        assert!(ops[0].type_params.is_empty());
2620        assert_eq!(ops[0].params.len(), 1);
2621        assert_eq!(ops[0].params[0].0, "key");
2622        assert!(matches!(
2623            &*program.program().ty_intern.get(ops[0].params[0].1),
2624            Ty::Base(bynk_syntax::ast::BaseType::String)
2625        ));
2626        // `return_ty` is Effect-wrapped, not peeled — `get`'s declared
2627        // `Effect[Int]` resolves whole, the same convention `FnSig::ret`
2628        // uses.
2629        assert!(matches!(
2630            &*program.program().ty_intern.get(ops[0].return_ty),
2631            Ty::Effect(inner) if matches!(
2632                &*program.program().ty_intern.get(*inner),
2633                Ty::Base(bynk_syntax::ast::BaseType::Int)
2634            )
2635        ));
2636
2637        assert_eq!(ops[1].name, "put");
2638        assert_eq!(ops[1].params.len(), 2);
2639        assert_eq!(ops[1].params[0].0, "key");
2640        assert_eq!(ops[1].params[1].0, "value");
2641        assert!(matches!(
2642            &*program.program().ty_intern.get(ops[1].params[1].1),
2643            Ty::Base(bynk_syntax::ast::BaseType::Int)
2644        ));
2645    }
2646
2647    #[test]
2648    fn lower_provider_given_ir_preserves_declaration_order_including_unused_entries() {
2649        // `given Random, Clock` (reverse-alphabetical, deliberately) pins
2650        // that `given`'s own declaration order survives — neither op body
2651        // below calls either capability, pinning review of #1186's point
2652        // that an *unused* `given` entry must still appear (it feeds R8.1's
2653        // own `deps` constructor, not anything the op bodies reference).
2654        let program = checked_context_program(
2655            r#"
2656context demo
2657
2658capability Clock {
2659  fn now() -> Effect[Int]
2660}
2661
2662capability Random {
2663  fn next() -> Effect[Int]
2664}
2665
2666capability Store {
2667  fn get(key: String) -> Effect[Int]
2668  fn put(key: String, value: Int) -> Effect[()]
2669}
2670
2671provides Store = MemStore given Random, Clock {
2672  fn get(key: String) -> Effect[Int] {
2673    Effect.pure(0)
2674  }
2675  fn put(key: String, value: Int) -> Effect[()] {
2676    Effect.pure(())
2677  }
2678}
2679"#,
2680        );
2681        let given = lower_provider_given_ir(find_provider(&program, "MemStore"));
2682        assert_eq!(
2683            given.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(),
2684            vec!["Random", "Clock"],
2685            "given's own declaration order preserved, unused entries included"
2686        );
2687        assert!(given.iter().all(|g| g.context.is_none()));
2688    }
2689
2690    #[test]
2691    fn lower_provider_given_ir_reads_an_external_providers_given_too() {
2692        // v0.17: an external (bodiless) provider is only legal inside an
2693        // `adapter` unit (`bynk-check/src/symbols.rs`), which this test
2694        // harness's own `checked_context_program` cannot build (it only
2695        // ever parses a `context`). `lower_provider_given_ir` never reads
2696        // `program` at all, so this hand-constructs the `ProviderDecl` the
2697        // parser would produce for `provides Store = ExternalStore given
2698        // Clock` inside an adapter. Nothing in the grammar or checker gates
2699        // `given` on `external`, so an external provider's `given` must come
2700        // through the same way a Bynk one's does (review of #1187's own
2701        // Provider given/deps-wiring slice).
2702        let provider = ProviderDecl {
2703            capability: bynk_syntax::ast::Ident {
2704                name: "Store".to_string(),
2705                span: Span::default(),
2706            },
2707            provider_name: bynk_syntax::ast::Ident {
2708                name: "ExternalStore".to_string(),
2709                span: Span::default(),
2710            },
2711            given: vec![CapRef {
2712                context: None,
2713                name: bynk_syntax::ast::Ident {
2714                    name: "Clock".to_string(),
2715                    span: Span::default(),
2716                },
2717                span: Span::default(),
2718            }],
2719            ops: Vec::new(),
2720            external: true,
2721            documentation: None,
2722            span: Span::default(),
2723            trivia: Default::default(),
2724        };
2725        let given = lower_provider_given_ir(&provider);
2726        assert_eq!(given.len(), 1);
2727        assert_eq!(given[0].context, None);
2728        assert_eq!(given[0].name, "Clock");
2729    }
2730
2731    #[test]
2732    fn an_http_service_lowers_its_protocol_and_per_handler_route_kind() {
2733        let program = checked_context_program(
2734            r#"
2735context demo
2736
2737fn ok(s: String) -> HttpResult[String] { Ok(s) }
2738
2739service Api from http {
2740  on GET("/ping") () -> Effect[HttpResult[String]] by v: Visitor {
2741    Effect.pure(ok("pong"))
2742  }
2743}
2744"#,
2745        );
2746        let service = find_service(&program, "Api");
2747        assert!(matches!(
2748            lower_protocol_ir(&service.protocol, &program),
2749            ProtocolIr::Http
2750        ));
2751        assert_eq!(
2752            lower_handler_kind_ir(&service.handlers[0].kind),
2753            IrHandlerKind::Http {
2754                method: IrHttpMethod::Get,
2755                path: "/ping".to_string(),
2756            },
2757            "the route binding lives per-handler — this is why ProtocolIr::Http itself \
2758             carries no payload"
2759        );
2760    }
2761
2762    #[test]
2763    fn a_cron_service_lowers_its_schedule_from_the_handler_not_the_protocol() {
2764        let program = checked_context_program(
2765            r#"
2766context demo
2767
2768fn done() -> Result[(), String] { Ok(()) }
2769
2770service Sweeper from cron {
2771  on schedule("*/5 * * * *") () -> Effect[Result[(), String]] {
2772    Effect.pure(done())
2773  }
2774}
2775"#,
2776        );
2777        let service = find_service(&program, "Sweeper");
2778        assert!(matches!(
2779            lower_protocol_ir(&service.protocol, &program),
2780            ProtocolIr::Cron
2781        ));
2782        assert_eq!(
2783            lower_handler_kind_ir(&service.handlers[0].kind),
2784            IrHandlerKind::Cron {
2785                expr: "*/5 * * * *".to_string()
2786            }
2787        );
2788    }
2789}