Skip to main content

bynk_check/
checker.rs

1//! Type checker and refinement validator (spec §§5–6, v0.1 §4.2, v0.2 §4.2).
2//!
3//! Operates on a [`ResolvedCommons`]. Walks declarations, validates each
4//! refinement against the spec's predicate-base compatibility and combination
5//! rules, then type-checks every function and method body.
6//!
7//! v0.2 extensions:
8//! - Record types (compatibility, field access, construction).
9//! - Sum types and variant construction (qualified and unqualified).
10//! - Methods (instance and static) with UFCS-style call resolution.
11//! - Pattern matching with exhaustiveness checking.
12//! - The `is` operator with binding flow into truthy contexts.
13//! - The built-in generic `Option[T]`.
14
15use std::collections::{BTreeSet, HashMap, HashSet};
16#[cfg(debug_assertions)]
17use std::sync::atomic::{AtomicU32, Ordering};
18use std::sync::{Arc, Mutex};
19
20use crate::actors::{BadCredential, CallSitePrincipal};
21use crate::builtin_names::map_query;
22use crate::builtin_names::methods::*;
23use crate::builtin_names::types::*;
24use crate::hints::HintSink;
25use crate::index::{RefSink, SymbolKind};
26use crate::kernel_op::{
27    BytesOp, ConnectionOp, DecimalOp, DurationOp, EffectOp, EffectResultOp, FloatOp, HttpResultOp,
28    InstantOp, IntOp, KernelOp, ListOp, MapOp, OptionOp, QueryOp, RequestCookiesOp,
29    RequestHeadersOp, RequestQueryOp, ResultOp, SetOp, StreamOp, StringOp, TestConnectionOp,
30    TokenClaimsOp,
31};
32use crate::kernel_op::{
33    CellStoreOp, IntrinsicNs, LogStoreOp, LogWindowOp, MapStoreOp, SetStoreOp, StaticOp,
34    StoreEntryOp, StoreQueryOp, TestConnectionStatic, TestRunStatic,
35};
36use crate::locals::LocalsSink;
37use crate::requirements::{
38    Materialize, Requirement, RequirementSink, RequirementSource, StoreKind,
39};
40use crate::resolver::{MethodTable, ResolvedCommons};
41use bynk_syntax::ast::*;
42use bynk_syntax::error::{Applicability, CompileError};
43use bynk_syntax::span::Span;
44
45/// P6.27 (design/tracks/the-ir.md §6a): re-exported so a checker consumer keying
46/// off `expr_types`/`Callee` (both `HashMap<ExprId, _>`, Q2's own settled totality
47/// story) can name `ExprId` through `bynk-check` alone, without also depending on
48/// `bynk_syntax::ast` directly just to spell this one identity type — the same
49/// public-dependency-already-exists shape as `Ty`/`TyId` below.
50pub use bynk_syntax::ast::ExprId;
51
52mod calls;
53pub mod codable;
54mod collections;
55mod cookie_lints;
56mod d1;
57mod events_emit;
58pub mod peek;
59pub use d1::{BatchPosition, D1DecodeSite, D1SqlSite, RowLink};
60pub(crate) mod equality;
61pub mod keying;
62pub mod ordering;
63use equality::EqScope;
64mod expressions;
65mod kernels;
66mod linearity;
67mod list_basics;
68mod list_par;
69mod par;
70mod refinements;
71pub(crate) use expressions::empty_range_error;
72pub use refinements::refinement_example;
73pub use refinements::split_regex_flags;
74pub(crate) use refinements::{refinement_needs_pin, refinement_needs_pin_without_example};
75
76/// #2869: the first predicate of a refined or opaque `String` type that `value`
77/// fails, in the order the emitted boundary checks them (`None` when it holds
78/// every one, or when the type carries no refinement). `bynk token` validates a
79/// `--sub` against a Bearer actor's identity type with it, so the token it signs
80/// is one the seam's own refinement check accepts.
81pub fn string_refinement_violation<'a>(
82    decl: &'a bynk_syntax::ast::TypeDecl,
83    value: &str,
84) -> Option<&'a bynk_syntax::ast::PredKind> {
85    let refinement = refinements::type_decl_refinement(decl)?;
86    refinements::first_failed_predicate(refinement, &ConstLit::Str(value.to_string()))
87}
88mod regex_ambiguity;
89mod usefulness;
90
91use calls::*;
92use expressions::*;
93use kernels::*;
94use refinements::*;
95
96pub(crate) use calls::extra_headers_authorization_errors;
97pub use calls::{
98    BYNK_LIST_DEPRECATED, FnCaps, check_const_decl, check_context_fn, check_event_field_default,
99    check_state_initialiser, check_suite_fn,
100};
101pub use collections::BYNK_COLLECTION_DEPRECATED;
102pub(crate) use d1::{is_sql_statement_type, statement_at_boundary};
103pub use d1::{row_base_fields, row_bool_fields};
104pub use refinements::{ZeroValue, is_zeroable, locale_tag_accepts, locale_tag_pattern, zero_value};
105
106// ==== Type representation ====
107
108/// T3.6b (R4.1): the intern table `TyId` is minted from. Owned per
109/// `check_record` invocation (design settled in the identity-and-totality
110/// track doc §9 before this slice started): created fresh at `check_record`'s
111/// entry, threaded through `Ctx`, carried out on `TypedCommons`/`RecordCheck`
112/// alongside `expr_types`, and forwarded across the `bynk-check`→`bynk-emit`
113/// boundary on `CheckedProgram` (T3.7a/T3.7b already built that seam).
114/// Confirmed safe by checking how cross-unit type references actually flow:
115/// `compose_unit_symbols` merges `TypeDecl` (immutable AST declarations)
116/// across units, never an already-interned `Ty`/`TyId` — every unit
117/// re-interns its own `Ty` graph from shared declarations, so `TyId`s are
118/// never compared across two different `check_record` invocations.
119///
120/// **Why [`intern`](Self::intern) takes `&self`, not `&mut self`.** The table
121/// is reached from `Ctx`, whose other fields (`expr_types`, `errors`, the
122/// sinks) are themselves `&mut` and are routinely live across an interning
123/// call — `ctx.tys.intern(…)` inside a loop over `ctx.scopes` is the common
124/// shape, not the exception. A `&mut Types` would make the borrow checker,
125/// not the type system, the thing every one of the ~200 minting sites is
126/// written around. Interior mutability keeps `&'a Types` `Copy`, so a
127/// function that needs the table just reads `ctx.tys` once and is done.
128///
129/// **Why a `Mutex` and `Arc`, not a `RefCell` and `Rc`.** The compiler itself
130/// is single-threaded, so a cell would do for `bynk-check` and `bynk-emit` —
131/// but the table rides out on `TypedCommons`/`ProjectAnalysis` into
132/// `bynk-lsp`, whose `tower-lsp` handlers are `async` and therefore require
133/// `Send`. A non-atomic refcount is exactly what `Send` forbids, so the
134/// choice is made by the consumer, not by the compiler's own threading. The
135/// lock is uncontended in every current caller.
136pub struct Types {
137    inner: Mutex<TypesInner>,
138    /// Which table this is, so [`Types::get`] can reject a foreign `TyId`
139    /// whose index happens to be in range — see [`TyId`]'s own note.
140    #[cfg(debug_assertions)]
141    tag: u32,
142}
143
144/// Hands each [`Types`] a distinct [`Types::tag`]. Wrapping is not a
145/// correctness problem: it would take 2^32 tables in one process for two to
146/// collide, and the guard is a debug-build aid, not a soundness argument.
147#[cfg(debug_assertions)]
148static NEXT_TABLE_TAG: AtomicU32 = AtomicU32::new(0);
149
150impl Default for Types {
151    fn default() -> Self {
152        Self {
153            inner: Mutex::default(),
154            #[cfg(debug_assertions)]
155            tag: NEXT_TABLE_TAG.fetch_add(1, Ordering::Relaxed),
156        }
157    }
158}
159
160#[derive(Debug, Default)]
161struct TypesInner {
162    /// `TyId(i)` resolves to `table[i]`. `Arc` so [`Types::get`] hands back a
163    /// handle by refcount bump rather than cloning the node, and so the same
164    /// allocation backs both `table` and `index` without storing it twice.
165    table: Vec<Arc<Ty>>,
166    index: HashMap<Arc<Ty>, TyId>,
167}
168
169impl Types {
170    pub fn new() -> Self {
171        Self::default()
172    }
173
174    /// Intern `ty`, returning its `TyId`. The same `Ty` value (by `Eq`)
175    /// always yields the same `TyId` — the property `ty_hash_eq_ord_tests`
176    /// (T3.6b's own settling-review prerequisite) pins directly. Dedup is by
177    /// the *shallow* `Ty`, which is sound precisely because every recursive
178    /// field is already a `TyId`: two structurally-equal types have equal
179    /// children ids by induction, so they hash and compare equal here.
180    pub fn intern(&self, ty: Ty) -> TyId {
181        let mut inner = self.lock();
182        if let Some(&id) = inner.index.get(&ty) {
183            return id;
184        }
185        let node = Arc::new(ty);
186        let id = TyId {
187            idx: inner.table.len() as u32,
188            #[cfg(debug_assertions)]
189            tag: self.tag,
190        };
191        inner.table.push(Arc::clone(&node));
192        inner.index.insert(node, id);
193        id
194    }
195
196    /// The node `id` was interned from.
197    ///
198    /// Panics on a `TyId` minted by a *different* table. That is the one new
199    /// failure mode interning introduces, and it is a wiring bug in the
200    /// compiler, never something a Bynk program can provoke — so it fails
201    /// loudly and by name rather than as a bare index-out-of-bounds. It was
202    /// worth the message: this fired twice while T3.6b was being built, both
203    /// times a synthesised `TypedCommons` that had been given a table of its
204    /// own while its `expr_types` was filled in from another.
205    ///
206    /// Both of those were the *shorter*-table shape, where a bounds check
207    /// alone catches it. The dangerous shape is the other one: a foreign id
208    /// that happens to be in range resolves to an unrelated `Ty` and the
209    /// caller mis-diagnoses or mis-emits in silence. So in debug builds the
210    /// check is identity, not length — [`TyId`] carries its table's tag and
211    /// this compares it. Release builds keep the bounds check only, which is
212    /// what indexing would have cost anyway.
213    pub fn get(&self, id: TyId) -> Arc<Ty> {
214        #[cfg(debug_assertions)]
215        assert!(
216            id.tag == self.tag,
217            "bynk internal error (T3.6b, R4.1): {id:?} resolved against a table it was not \
218             interned into (this is table {}). A `TyId` is only meaningful in its own `Types` — \
219             check that whatever produced this id and whatever is reading it share one table",
220            self.tag
221        );
222        let inner = self.lock();
223        match inner.table.get(id.idx as usize) {
224            Some(node) => Arc::clone(node),
225            None => panic!(
226                "bynk internal error (T3.6b, R4.1): {id:?} resolved against a table it was not \
227                 interned into (this table holds {}). A `TyId` is only meaningful in its own \
228                 `Types` — check that whatever produced this id and whatever is reading it share \
229                 one table",
230                inner.table.len()
231            ),
232        }
233    }
234
235    /// [`Ty::display`] for an already-interned type.
236    pub fn display(&self, id: TyId) -> String {
237        self.get(id).display(self)
238    }
239
240    /// Number of distinct types interned so far. Exposed for the interner's
241    /// own tests (dedup is observable only as "the table did not grow").
242    pub fn len(&self) -> usize {
243        self.lock().table.len()
244    }
245
246    /// The lock, recovered from poisoning. `intern` never panics while
247    /// holding it (it only pushes to a `Vec` and a `HashMap`), so a poisoned
248    /// lock can only mean an unrelated panic unwound past a live guard —
249    /// where the table is still structurally sound.
250    fn lock(&self) -> std::sync::MutexGuard<'_, TypesInner> {
251        self.inner.lock().unwrap_or_else(|e| e.into_inner())
252    }
253
254    pub fn is_empty(&self) -> bool {
255        self.len() == 0
256    }
257}
258
259impl std::fmt::Debug for Types {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        f.debug_struct("Types")
262            .field("len", &self.len())
263            .finish_non_exhaustive()
264    }
265}
266
267/// T3.6b (R4.1/R4.2): a `Ty`'s identity above the intern table — `Copy`,
268/// `Hash`, `Ord`, cheap to pass and compare. Resolved back to a `Ty` only
269/// via the [`Types`] table it was interned into (see that type's own doc).
270///
271/// In debug builds it also carries the tag of the table it came from, so
272/// [`Types::get`] can make good on its "interned into another table" promise
273/// for a foreign id whose index is merely *in range* — the case a bounds
274/// check cannot see, and the one that would otherwise resolve to an
275/// unrelated `Ty` in silence. `idx` is declared first so the derived `Ord`
276/// still orders by insertion within a table, exactly as it does in release.
277#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
278pub struct TyId {
279    idx: u32,
280    #[cfg(debug_assertions)]
281    tag: u32,
282}
283
284impl std::fmt::Debug for TyId {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        #[cfg(debug_assertions)]
287        return write!(f, "TyId({} of table {})", self.idx, self.tag);
288        #[cfg(not(debug_assertions))]
289        return write!(f, "TyId({})", self.idx);
290    }
291}
292
293impl TyId {
294    /// The interned node, for the (many) sites that need to look at the
295    /// type's shape. Sugar for [`Types::get`], so a `TyId` reads like the
296    /// `&Ty` it replaced.
297    pub fn get(self, tys: &Types) -> Arc<Ty> {
298        tys.get(self)
299    }
300
301    /// [`Ty::display`] for this id — the form nearly every diagnostic uses.
302    pub fn display(self, tys: &Types) -> String {
303        tys.display(self)
304    }
305
306    /// True if this is [`Ty::Error`] — the type T3.3b records for an
307    /// expression whose typing failed. An editor reading `expr_types` treats
308    /// it as "no type" and shows nothing, rather than displaying it — its
309    /// display string is a diagnostic placeholder, not a Bynk type.
310    pub fn is_error(self, tys: &Types) -> bool {
311        matches!(*tys.get(self), Ty::Error)
312    }
313
314    /// True if this type is `Effect[_]` (v0.5).
315    pub fn is_effect(self, tys: &Types) -> bool {
316        tys.get(self).is_effect()
317    }
318
319    /// v0.102: true if this type belongs to the closed `Held` kind.
320    pub fn is_held(self, tys: &Types) -> bool {
321        tys.get(self).is_held()
322    }
323
324    /// The underlying base type, if this type widens to one.
325    pub fn base(self, tys: &Types) -> Option<BaseType> {
326        tys.get(self).base()
327    }
328}
329
330/// A resolved type.
331#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
332pub enum Ty {
333    /// R4.3 measurement probe (not shipped): a real Error variant.
334    Error,
335    /// #2620 (DECISION A): the bottom type of `unreachable(…)` / `todo(…)` —
336    /// an expression that never produces a value. Assignable to every type
337    /// and absorbed by every join; never nameable in source.
338    Never,
339    /// A base type (`Int`, `String`, `Bool`).
340    Base(BaseType),
341    /// A user-declared named type. `kind` records the declaration's shape
342    /// for compatibility / dispatch decisions. `args` holds the applied type
343    /// arguments of a generic type (`Paginated[String]` → `args = [String]`);
344    /// it is empty for a non-generic type (v0.157, ADR 0183). Substitution,
345    /// unification, and display recurse into `args`.
346    Named {
347        name: String,
348        kind: NamedKind,
349        args: Vec<TyId>,
350    },
351    /// `Result[T, E]`.
352    Result(TyId, TyId),
353    /// `Option[T]`.
354    Option(TyId),
355    /// `Effect[T]` (v0.5).
356    Effect(TyId),
357    /// `HttpResult[T]` (v0.9).
358    HttpResult(TyId),
359    /// `QueueResult` — the built-in queue verdict sum (v0.44). Non-generic.
360    QueueResult,
361    /// `HttpOutcome[T]` — what a `system`-tier case observes when it drives an
362    /// http address past the handler's types (#1934): a `Wire(…)` argument, `by
363    /// Nobody`, or a method the path declares no handler for. `Rejected(
364    /// BoundaryRejection)` when the router or the auth seam refused the request
365    /// before the handler ran, `Handled(HttpResult[T])` when it ran. Produced
366    /// only by a test-service address; it cannot be written in source.
367    HttpOutcome(TyId),
368    /// `BoundaryRejection` — why the boundary refused a request before the
369    /// handler (#1934), the payload of `HttpOutcome.Rejected`. Non-generic.
370    BoundaryRejection,
371    /// `Asset` — a static file declared by `asset name = "path"` (#1883,
372    /// slice 1a, [DECISION H]). Non-generic; its one field is `.url : String`.
373    Asset,
374    /// `RequestHeaders` — an HTTP handler's read-only view of the request's
375    /// headers (#2341, decision A). Non-generic and opaque, with no wire form.
376    RequestHeaders,
377    /// `RequestQuery` (#2854) — an HTTP handler's read-only view of the
378    /// request's query string.
379    RequestQuery,
380    /// `RequestCookies` (#3277) — an HTTP handler's read-only view of the
381    /// request's `Cookie` header.
382    RequestCookies,
383    /// `TokenClaims` (#2380, L5) — an `Oidc` actor's verified token claims,
384    /// read through its binder's `.claims`.
385    TokenClaims,
386    /// `List[T]` — built-in immutable list (v0.20b).
387    List(TyId),
388    /// `Map[K, V]` — built-in immutable map (v0.20b). The key type is
389    /// confined to value-keyable types at TypeRef resolution.
390    Map(TyId, TyId),
391    /// `Set[T]` — built-in immutable set (K6a, #2596). The element type is
392    /// confined to the `Map`-key rule at TypeRef resolution.
393    Set(TyId),
394    /// `Query[T]` — a lazy, by-reference description of a read over agent-local
395    /// storage (v0.91, ADR 0115). The inner type is the element a terminal
396    /// yields. Built by the lazy combinator vocabulary over a `store` field,
397    /// executed by a terminal (`-> Effect[…]`). Non-storable, non-boundary, and
398    /// not value-comparable — like `Effect`/`Fn` (ADRs 0031/0030).
399    Query(TyId),
400    /// `Stream[T]` — a lazy, pull-shaped sequence of values produced over time
401    /// (v0.100, real-time track slice 0). The inner type is the element a
402    /// terminal yields. Built from a runtime source (`Stream.of` at v1),
403    /// transformed by lazy builders (`map`/`take`), drained by a terminal
404    /// (`collect -> Effect[List[T]]`). Non-storable, non-boundary, and not
405    /// value-comparable — like `Query`/`Effect`/`Fn` (ADRs 0031/0030).
406    Stream(TyId),
407    /// `Connection[F]` — a held WebSocket connection (v0.102, real-time track
408    /// slice 2). `F` is the server→client frame type. The one concrete instance
409    /// of the closed `Held` kind (`is_held`). Governed by the linearity
410    /// discipline (§2.9): single-owner, mandatory disposal. Non-serialisable,
411    /// non-boundary, non-comparable; storable only in `Cell[Option[Connection]]`
412    /// / `Map[K, Connection]`.
413    Connection(TyId),
414    /// `TestConnection[F]` (#3051) — a case-scoped recording handle for a
415    /// `from websocket` service's connection. Not held: a case reads what the
416    /// server sent (`.sent()`, `.closed()`) and mints the owned `Connection[F]`
417    /// an agent receives (`.connection()`). Suite-only; nameable only by the
418    /// `TestConnection[F]()` constructor call.
419    TestConnection(TyId),
420    /// `ValidationError` — built-in error type.
421    ValidationError,
422    /// `DecodeError` — built-in JSON-decode error type (v0.22b). A uniform
423    /// record: `kind`/`path`/`message`, all `String`.
424    DecodeError,
425    /// `()` — the unit type (v0.5).
426    Unit,
427    /// v0.45: a verified actor binding (`by name: Actor`). The inner type is
428    /// the actor's identity, read as `name.identity`. A boundary-minted, sealed
429    /// value — only ever `.identity`-accessed, never constructed or passed.
430    Actor(TyId),
431    /// v0.52: a resolved multi-actor binding (`by who: A | B`) — an ordered sum
432    /// of peer actors. Each member is `(actor name, identity ty)`; the body
433    /// `match`es on the resolved actor, each non-unit member binding its
434    /// identity directly. Like `Actor`, a sealed boundary value — only ever
435    /// matched, never constructed or passed.
436    ActorSum(Vec<(String, TyId)>),
437    /// `A -> B` — a function type (v0.20a). Effectful iff `ret` is
438    /// `Effect[_]` (the structural rule); no separate flag, so there is a
439    /// single source of truth.
440    Fn { params: Vec<TyId>, ret: TyId },
441    /// A function type parameter (v0.20a). Two lives: *rigid* while checking
442    /// a generic function's own body (name-equality in `compatible`), and
443    /// *flexible* during call-site instantiation, where it is matched by
444    /// `unify` and fully eliminated by `substitute` before any `compatible`
445    /// runs against argument types. Vars never escape call checking into the
446    /// caller's expression types.
447    Var(String),
448}
449
450/// The shape of a named type — what its declaration looks like.
451///
452/// `Refined` widens to its base type when used in arithmetic, comparisons,
453/// and other operations on the base. `Opaque` does NOT widen — its identity
454/// is nominal and the base type is hidden outside the defining commons.
455#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
456pub enum NamedKind {
457    /// Refined-base type: widens to the recorded base.
458    Refined(BaseType),
459    /// Record type.
460    Record,
461    /// Sum type.
462    Sum,
463    /// Opaque base type. The base is hidden; identity is purely nominal.
464    /// The recorded base is used by the type checker (for `.raw`, `.of`,
465    /// `.unsafe`) and by the emitter, but not for compatibility widening.
466    Opaque(BaseType),
467}
468
469impl Ty {
470    /// Display name for diagnostics. Takes the table the type was interned
471    /// into (T3.6b): every recursive field is a `TyId` now, so rendering a
472    /// nested type is a table read rather than a pointer chase.
473    pub fn display(&self, types: &Types) -> String {
474        match self {
475            // R4.3: a resolution failure already has its own diagnostic at the
476            // site that produced this; this string exists only so a *second*
477            // diagnostic that happens to mention the type (e.g. a mismatch one
478            // level up) reads as "type error" rather than a blank or `unknown`.
479            Ty::Error => "<type error>".to_string(),
480            Ty::Never => NEVER_DISPLAY.to_string(),
481            Ty::Base(b) => b.name().to_string(),
482            // #2087: a qualified key reads as the declaration's own name.
483            Ty::Named { name, args, .. } if args.is_empty() => {
484                crate::symbols::display_type_name(name).to_string()
485            }
486            Ty::Named { name, args, .. } => format!(
487                "{}[{}]",
488                crate::symbols::display_type_name(name),
489                args.iter()
490                    .map(|a| types.display(*a))
491                    .collect::<Vec<_>>()
492                    .join(", ")
493            ),
494            Ty::Result(t, e) => {
495                format!("Result[{}, {}]", types.display(*t), types.display(*e))
496            }
497            Ty::Option(t) => format!("Option[{}]", types.display(*t)),
498            Ty::Effect(t) => format!("Effect[{}]", types.display(*t)),
499            Ty::HttpResult(t) => format!("HttpResult[{}]", types.display(*t)),
500            Ty::QueueResult => "QueueResult".to_string(),
501            Ty::HttpOutcome(t) => format!("HttpOutcome[{}]", types.display(*t)),
502            Ty::BoundaryRejection => "BoundaryRejection".to_string(),
503            Ty::Asset => "Asset".to_string(),
504            Ty::RequestHeaders => "RequestHeaders".to_string(),
505            Ty::RequestQuery => "RequestQuery".to_string(),
506            Ty::RequestCookies => "RequestCookies".to_string(),
507            Ty::TokenClaims => "TokenClaims".to_string(),
508            Ty::List(t) => format!("List[{}]", types.display(*t)),
509            Ty::Set(t) => format!("Set[{}]", types.display(*t)),
510            Ty::Map(k, v) => format!("Map[{}, {}]", types.display(*k), types.display(*v)),
511            Ty::Query(t) => format!("Query[{}]", types.display(*t)),
512            Ty::Stream(t) => format!("Stream[{}]", types.display(*t)),
513            Ty::Connection(t) => format!("Connection[{}]", types.display(*t)),
514            Ty::TestConnection(t) => format!("TestConnection[{}]", types.display(*t)),
515            Ty::ValidationError => "ValidationError".to_string(),
516            Ty::DecodeError => "DecodeError".to_string(),
517            Ty::Unit => "()".to_string(),
518            Ty::Actor(id) => format!("actor[{}]", types.display(*id)),
519            Ty::ActorSum(members) => members
520                .iter()
521                .map(|(name, _)| name.clone())
522                .collect::<Vec<_>>()
523                .join(" | "),
524            Ty::Fn { params, ret } => {
525                let params = match params.len() {
526                    0 => "()".to_string(),
527                    // A single Fn-typed param needs parens to stay readable
528                    // under right-associativity.
529                    1 if !matches!(&*types.get(params[0]), Ty::Fn { .. }) => {
530                        types.display(params[0])
531                    }
532                    _ => format!(
533                        "({})",
534                        params
535                            .iter()
536                            .map(|p| types.display(*p))
537                            .collect::<Vec<_>>()
538                            .join(", ")
539                    ),
540                };
541                format!("{params} -> {}", types.display(*ret))
542            }
543            Ty::Var(name) => name.clone(),
544        }
545    }
546
547    /// True if this type is `Effect[_]`.
548    pub fn is_effect(&self) -> bool {
549        matches!(self, Ty::Effect(_))
550    }
551
552    /// v0.102: true if this type belongs to the closed `Held` kind — a
553    /// runtime-managed resource governed by the linearity discipline (§2.9).
554    /// The one instance at v1 is `Connection[F]`; the single extension point
555    /// for future held types (file handles, DB connections).
556    pub fn is_held(&self) -> bool {
557        matches!(self, Ty::Connection(_))
558    }
559
560    /// v0.102: for a `Held` type, the held element it wraps (the frame type of a
561    /// `Connection[F]`). Used by the storage-admission rules to look through an
562    /// `Option[Connection]` value.
563    pub fn held_inner(&self) -> Option<TyId> {
564        match self {
565            Ty::Connection(t) => Some(*t),
566            _ => None,
567        }
568    }
569
570    /// The underlying base type, if this type widens to a base type.
571    /// Opaque types deliberately do NOT widen — that's the whole point of
572    /// the opacity — so `Ty::Named { kind: Opaque(_), .. }` returns None.
573    pub fn base(&self) -> Option<BaseType> {
574        match self {
575            Ty::Base(b) => Some(*b),
576            Ty::Named {
577                kind: NamedKind::Refined(b),
578                ..
579            } => Some(*b),
580            _ => None,
581        }
582    }
583
584    /// The payload `T` of an `Option[T]`, or `None` for any other type.
585    pub fn as_option(&self) -> Option<TyId> {
586        match self {
587            Ty::Option(t) => Some(*t),
588            Ty::Error
589            | Ty::Never
590            | Ty::Base(..)
591            | Ty::Named { .. }
592            | Ty::Result(..)
593            | Ty::Effect(..)
594            | Ty::HttpResult(..)
595            | Ty::QueueResult
596            | Ty::HttpOutcome(..)
597            | Ty::BoundaryRejection
598            | Ty::Asset
599            | Ty::RequestHeaders
600            | Ty::RequestQuery
601            | Ty::RequestCookies
602            | Ty::TokenClaims
603            | Ty::List(..)
604            | Ty::Map(..)
605            | Ty::Set(..)
606            | Ty::Query(..)
607            | Ty::Stream(..)
608            | Ty::Connection(..)
609            | Ty::TestConnection(..)
610            | Ty::ValidationError
611            | Ty::DecodeError
612            | Ty::Unit
613            | Ty::Actor(..)
614            | Ty::ActorSum(..)
615            | Ty::Fn { .. }
616            | Ty::Var(..) => None,
617        }
618    }
619
620    /// The element `T` of a `List[T]`, or `None` for any other type.
621    pub fn as_list(&self) -> Option<TyId> {
622        match self {
623            Ty::List(t) => Some(*t),
624            Ty::Error
625            | Ty::Never
626            | Ty::Base(..)
627            | Ty::Named { .. }
628            | Ty::Result(..)
629            | Ty::Option(..)
630            | Ty::Effect(..)
631            | Ty::HttpResult(..)
632            | Ty::QueueResult
633            | Ty::HttpOutcome(..)
634            | Ty::BoundaryRejection
635            | Ty::Asset
636            | Ty::RequestHeaders
637            | Ty::RequestQuery
638            | Ty::RequestCookies
639            | Ty::TokenClaims
640            | Ty::Map(..)
641            | Ty::Set(..)
642            | Ty::Query(..)
643            | Ty::Stream(..)
644            | Ty::Connection(..)
645            | Ty::TestConnection(..)
646            | Ty::ValidationError
647            | Ty::DecodeError
648            | Ty::Unit
649            | Ty::Actor(..)
650            | Ty::ActorSum(..)
651            | Ty::Fn { .. }
652            | Ty::Var(..) => None,
653        }
654    }
655
656    /// The payload `T` of an `Effect[T]`, or `None` for any other type.
657    pub fn as_effect(&self) -> Option<TyId> {
658        match self {
659            Ty::Effect(t) => Some(*t),
660            Ty::Error
661            | Ty::Never
662            | Ty::Base(..)
663            | Ty::Named { .. }
664            | Ty::Result(..)
665            | Ty::Option(..)
666            | Ty::HttpResult(..)
667            | Ty::QueueResult
668            | Ty::HttpOutcome(..)
669            | Ty::BoundaryRejection
670            | Ty::Asset
671            | Ty::RequestHeaders
672            | Ty::RequestQuery
673            | Ty::RequestCookies
674            | Ty::TokenClaims
675            | Ty::List(..)
676            | Ty::Map(..)
677            | Ty::Set(..)
678            | Ty::Query(..)
679            | Ty::Stream(..)
680            | Ty::Connection(..)
681            | Ty::TestConnection(..)
682            | Ty::ValidationError
683            | Ty::DecodeError
684            | Ty::Unit
685            | Ty::Actor(..)
686            | Ty::ActorSum(..)
687            | Ty::Fn { .. }
688            | Ty::Var(..) => None,
689        }
690    }
691
692    /// The `(T, E)` of a `Result[T, E]`, or `None` for any other type.
693    pub fn as_result(&self) -> Option<(TyId, TyId)> {
694        match self {
695            Ty::Result(ok, err) => Some((*ok, *err)),
696            Ty::Error
697            | Ty::Never
698            | Ty::Base(..)
699            | Ty::Named { .. }
700            | Ty::Option(..)
701            | Ty::Effect(..)
702            | Ty::HttpResult(..)
703            | Ty::QueueResult
704            | Ty::HttpOutcome(..)
705            | Ty::BoundaryRejection
706            | Ty::Asset
707            | Ty::RequestHeaders
708            | Ty::RequestQuery
709            | Ty::RequestCookies
710            | Ty::TokenClaims
711            | Ty::List(..)
712            | Ty::Map(..)
713            | Ty::Set(..)
714            | Ty::Query(..)
715            | Ty::Stream(..)
716            | Ty::Connection(..)
717            | Ty::TestConnection(..)
718            | Ty::ValidationError
719            | Ty::DecodeError
720            | Ty::Unit
721            | Ty::Actor(..)
722            | Ty::ActorSum(..)
723            | Ty::Fn { .. }
724            | Ty::Var(..) => None,
725        }
726    }
727
728    /// The base type a scalar-shaped type is made of: a base type itself, or a
729    /// refined or opaque named type over one. [`Ty::base`] is the same question
730    /// minus the opaque case, which does not widen.
731    pub fn scalar_base(&self) -> Option<BaseType> {
732        match self {
733            Ty::Base(b) => Some(*b),
734            Ty::Named {
735                kind: NamedKind::Refined(b) | NamedKind::Opaque(b),
736                ..
737            } => Some(*b),
738            Ty::Named {
739                kind: NamedKind::Record | NamedKind::Sum,
740                ..
741            }
742            | Ty::Error
743            | Ty::Never
744            | Ty::Result(..)
745            | Ty::Option(..)
746            | Ty::Effect(..)
747            | Ty::HttpResult(..)
748            | Ty::QueueResult
749            | Ty::HttpOutcome(..)
750            | Ty::BoundaryRejection
751            | Ty::Asset
752            | Ty::RequestHeaders
753            | Ty::RequestQuery
754            | Ty::RequestCookies
755            | Ty::TokenClaims
756            | Ty::List(..)
757            | Ty::Map(..)
758            | Ty::Set(..)
759            | Ty::Query(..)
760            | Ty::Stream(..)
761            | Ty::Connection(..)
762            | Ty::TestConnection(..)
763            | Ty::ValidationError
764            | Ty::DecodeError
765            | Ty::Unit
766            | Ty::Actor(..)
767            | Ty::ActorSum(..)
768            | Ty::Fn { .. }
769            | Ty::Var(..) => None,
770        }
771    }
772}
773
774/// P6.0 (design/tracks/the-ir.md §6, #1139): a resolved classification of a
775/// call-shaped expression, recorded once by the checker's own dispatch
776/// (`checker::calls`) rather than re-derived by each later consumer —
777/// closing R6.10's duplicated-classification gap between `bynk-check` and
778/// `bynk-emit`'s `lower_method_call`/`lower_call`.
779///
780/// Adapted to the identity handles this checker already has (Decision A,
781/// ADR 0333, `the-ir-callee-in-bynk-check`) rather than the reference
782/// document's `DefId`/`LocalId`/`VariantId`/`OpId` arena — none of which
783/// exists here, since the `Resolve` phase that would mint them was never
784/// built (`project-model.md` §3.4 deferred it to phase 8).
785/// `Arc<FnDecl>`/`Arc<TypeDecl>` are already-cheap resolved handles
786/// (`ResolvedCommons::fns`/`types`); every other variant's identity is a
787/// name, exactly as the checker already keys capabilities, store fields,
788/// units, and agents.
789///
790/// Recorded at each dispatch decision as soon as it is known — including on
791/// an error sub-branch (an arity mismatch, an undeclared capability) — since
792/// the *kind* of call is fixed by dispatch, not by whether it went on to
793/// type-check cleanly.
794#[derive(Debug, Clone)]
795pub enum Callee {
796    /// A free function call. The `Vec<TyId>` is the call's comparator witnesses
797    /// (constrained-generics slice 1): the type argument of each `Ord`-bounded
798    /// type parameter of the callee, in [`codable::witness_list`] order.
799    /// Empty for a callee with no `Ord` bound, which is almost every call.
800    Fn(Arc<FnDecl>, Vec<TyId>),
801    /// A generic function with `Ord` bounds named as a value (`xs.map(max)`),
802    /// instantiated at the reference: its witnesses, as for [`Callee::Fn`].
803    FnValue(Arc<FnDecl>, Vec<TyId>),
804    /// Applying a function-typed local or parameter (`f(x)` where `f` is in
805    /// scope, not declared). No stable id exists for a local beyond its
806    /// name — the reference's `LocalId` presumes the same `Resolve` phase
807    /// Decision A declines to build here.
808    Value(String),
809    /// Sum-variant construction, bare (`Some(x)`) or qualified
810    /// (`Opt.Some(x)`).
811    Ctor { sum: Arc<TypeDecl>, tag: String },
812    /// `T.of(value)` — the refined/opaque runtime constructor.
813    Refine(Arc<TypeDecl>),
814    /// `T.unsafe(value)` — the opaque constructor, defining-unit only.
815    Unsafe(Arc<TypeDecl>),
816    /// A user-declared static method (`Type.method(...)`). The `Vec<TyId>` is
817    /// the call's witnesses, as for [`Callee::Fn`] (constrained generics
818    /// slice 4); empty for a static on a non-generic type.
819    Static(Arc<FnDecl>, Vec<TyId>),
820    /// A user-declared instance method (UFCS), generic or not. The `Vec<TyId>`
821    /// is the call's comparator witnesses, as for [`Callee::Fn`].
822    Method(Arc<FnDecl>, Vec<TyId>),
823    /// A built-in method on a value — the collection/query/stream/
824    /// connection/numeric/duration/instant/bytes/string/option/result/
825    /// effect kernels, including the refined-receiver fallback (ADR 0168).
826    /// `recv` is the receiver's own checked type; `op` is the resolved
827    /// operation on it (#3164), so a consumer matches on the enum rather than
828    /// on the method's spelling.
829    Kernel { recv: TyId, op: KernelOp },
830    /// #3386: `Actor.issue(identity)` / `Actor.expire()` on a local `SignedCookie`
831    /// actor: the session cookie the actor mints, or its matching deletion.
832    /// `issue` reads the `Clock` and is an `Effect`; `expire` is pure.
833    SignedCookie { actor: String, issue: bool },
834    /// #3446: `Record.field.cookie(value)` / `Record.field.expire()` on a cookie record: the
835    /// `Cookie` the field's decoder reads back (named by its wire name, valued by the decoder's
836    /// leaf rules), or its matching deletion.
837    CookieField {
838        record: String,
839        field: String,
840        expire: bool,
841    },
842    /// A built-in static constructor with no declaring type — `List.empty`,
843    /// `Map.empty`, `Int.parse`/`Float.parse`, `Duration.millis`,
844    /// `Instant.fromEpochMillis`, `Bytes.fromUtf8`/`fromBase64`/`empty`,
845    /// `Json.decode`/`encode`, `Stream.of`.
846    ///
847    /// `ns` and `op` (1A.33, Decision B) are closed: built only for a method the namespace
848    /// has, so an unknown method gets no callee. Build one with [`Callee::intrinsic`].
849    Intrinsic {
850        ns: crate::kernel_op::IntrinsicNs,
851        op: crate::kernel_op::StaticOp,
852    },
853    /// #2620: `unreachable(msg)` / `todo(msg)` — the ambient built-ins that
854    /// fault when evaluated. `kind` is the runtime fault kind (`Unreachable` /
855    /// `Todo`); the call's type is [`Ty::Never`].
856    Fault { kind: &'static str },
857    /// A same-context capability operation call (`Cap.op(...)`). `wire` is set
858    /// for an operation with `Codable` parameters: how the call encodes them.
859    Capability {
860        cap: String,
861        op: String,
862        wire: Option<Arc<codable::CapEncoding>>,
863        /// 1A.33 (Decision A): which first-party capability this is, when it is
864        /// bynk's own ([`crate::firstparty::resolve`]); `None` for any other
865        /// capability, including a same-named one from another unit (#934).
866        first_party: Option<crate::firstparty::FirstPartyCap>,
867        /// #4113: for bynk's own `Events.emit`, the event the call emits: its type argument,
868        /// written or inferred from the argument, once the owner check has accepted it. The one
869        /// place the emitter and the architecture model read the emitted event from.
870        event: Option<String>,
871    },
872    /// #2865: `Cap.select[T](tail, params)` / `Cap.firstAs[T](tail, params)` on
873    /// a derived `D1` instance. Not a declared operation: the compiler writes
874    /// `sql` (the column list from the row `T`, then the literal tail) and
875    /// lowers over `all`/`first` and the `decodeSql` codec.
876    D1Select {
877        cap: String,
878        row: TyId,
879        sql: String,
880        first: bool,
881        /// Hyperdrive H3 (#3320): the instance is a `Postgres` one, so the
882        /// read decodes with Postgres' rules and fails as a `PgReadError`.
883        pg: bool,
884        /// Hyperdrive H5 (#3322): the instance is a `MySql` one: the read
885        /// quotes columns with backticks, decodes MySQL's text forms (the
886        /// Postgres pass over `Int` fields) and fails as a `MySqlReadError`.
887        mysql: bool,
888    },
889    /// #3070: a literal SQL statement of a derived `D1` instance, recorded under
890    /// the *SQL argument's* id (not the call's, which keeps its own entry), so
891    /// the project phase can prepare it against the binding's migrations.
892    D1Sql(d1::D1SqlSite),
893    /// #3147: `D1.peek(<participant>.<Cap>)`. The case holds a capability over
894    /// the participant's test database, on the `binding` of its `env`, as
895    /// `deps.<local>`; calls on the handle are capability calls on `local`.
896    D1Peek {
897        participant: String,
898        binding: String,
899        local: String,
900    },
901    /// #3139: a `Json.decodeSql[T](x)` whose `x` is the rows of a literal D1 read,
902    /// recorded under the argument's id, so the project phase can check `T`'s
903    /// fields against the statement's result columns.
904    D1Decode(d1::D1DecodeSite),
905    /// A cross-context capability operation call (`B.Cap.op(...)` /
906    /// `Alias.Cap.op(...)`).
907    CrossCap {
908        unit: String,
909        cap: String,
910        op: String,
911        wire: Option<Arc<codable::CapEncoding>>,
912        /// 1A.33 (Decision A): which first-party capability `unit.cap` is, when it is
913        /// bynk's own.
914        first_party: Option<crate::firstparty::FirstPartyCap>,
915    },
916    /// A cross-context service call (`B.service(...)` / `Alias.service(...)`).
917    Cross { unit: String, service: String },
918    /// `AgentName(key)` — agent instance construction. No slot exists for
919    /// this in the reference's own `Callee` taxonomy (Part 6.5 only names
920    /// handler dispatch); added here since this slice covers every call
921    /// shape `check_call` dispatches, not only the ones the reference
922    /// anticipated.
923    AgentInit(String),
924    /// `agent.handler(args)` — agent handler dispatch.
925    Agent { agent: String, handler: String },
926    /// A test-body service address (`svc.call`/`svc.<VERB>("/path", …)`/
927    /// `svc.schedule(...)`/`svc.message(...)`). `check_test_service_address`
928    /// always returns `None` by design (the runner recovers the outcome
929    /// type at runtime) — this classification exists purely for a later
930    /// consumer (e.g. go-to-definition on the address), not typing.
931    /// `extra_headers` (#2910): a trailing `RequestHeaders` argument sent to a
932    /// route that declares no `headers:` parameter — a `system`-tier-only form.
933    ///
934    /// `address` (1A.33, Decision D) is typed: where the address is aimed.
935    TestService {
936        service: String,
937        address: HandlerAddress,
938        extra_headers: bool,
939    },
940    /// #1883, slice 3: `svc.GET(asset)` in a test body — an asset fetch,
941    /// answered by the asset tier rather than a handler. Its own variant
942    /// (review of #1922) so no route address can be mistaken for it.
943    TestAssetFetch { service: String },
944    /// An effectful `<field>.<op>(…)` storage operation on a `store`
945    /// `Map`/`Set`/`Cache`/`Log`/`Cell` field — R6.5's own named target
946    /// (P6.2, #1143): a mutation detector keyed on this variant, not a
947    /// receiver's bare name, cannot miss a mutation reached through a
948    /// non-`Ident` receiver or false-negative on a shadowed local, the
949    /// defect class `block_writes_state`'s `mutating_op` still carries.
950    /// `field` is the store field's own name (no `FieldId` arena exists —
951    /// same adaptation `check_store_*_op`'s own lookups already use). Note
952    /// this is recorded *outside* `calls.rs`'s six functions — the
953    /// store-field ladder lives directly in `checker.rs`'s own `type_of`,
954    /// never reaching any of them — extending P6.0's own recording surface
955    /// past the boundary its "Done when" deliberately drew.
956    ///
957    /// `op` (1A.33, Decision C) is typed, built only for an operation the field's kind has.
958    Store {
959        field: String,
960        op: crate::kernel_op::StoreEntryOp,
961    },
962    /// A query builder/terminal call that *lifts* a bare `store` `Map`/`Log`
963    /// field into a lazy `Query[V]` (`is_query_op`'s own gate,
964    /// `checker.rs`'s `type_of`) — R6.12's own named target (P6.2, #1143).
965    /// `field` names the store field being lifted — without it, a chain
966    /// rooted at this call (`orders.filter(p).count()`) would carry no
967    /// identity for `orders` anywhere in the classification, the same
968    /// information loss R6.5 exists to close on the write side. `role` is
969    /// read back from the checker's own typing decision for this exact call
970    /// (`Ty::Query(_)` result ⇒ `Builder`, anything else ⇒ `Terminal`), not
971    /// a second name-list classifier alongside `is_query_op`'s. A *chained*
972    /// builder/terminal call on an already-`Query`-typed receiver
973    /// (`.filter(p).count()`'s own `.count()`) is not this variant — it
974    /// reaches `check_method_call`'s ordinary kernel dispatch and is
975    /// `Callee::Kernel` already (P6.0); `Query` here exists only because the
976    /// lift call's own outer expression never passes through any of
977    /// `calls.rs`'s six functions to get one.
978    ///
979    /// `op` (1A.33, Decision C) is typed.
980    Query {
981        field: String,
982        op: crate::kernel_op::StoreQueryOp,
983        role: QueryRole,
984    },
985    /// #2617: a bare name that resolves to a `const` (one of this unit's, a
986    /// sibling file's or a `uses`d commons'), not a local of the same name.
987    /// Not call-shaped in the source, but emitted as one: each constant is a
988    /// hoisted, cached function (`Name()`), so the lowering must know which
989    /// idents name a constant, and only the checker's scope walk can tell a
990    /// constant from a local that shadows it. Recorded like the bare
991    /// `HttpResult` variant reference (`Callee::Intrinsic`).
992    ///
993    /// #3108: when the name is a D1 call's SQL argument, the second field keeps
994    /// that statement's [`Callee::D1Sql`] site, which this entry would
995    /// otherwise replace (one id, one entry), so the constant's SQL is still
996    /// prepared.
997    Const(String, Option<Box<d1::D1SqlSite>>),
998    /// 1A.33: what a call-site principal clause (`by Nobody`, `by Forged`, `by User("bob")`)
999    /// is, recorded under the clause's own [`CallSiteActor::id`]. Not call-shaped: it is the
1000    /// one place the reserved principal names are classified, for the checker's own rules
1001    /// and the emitter alike.
1002    Principal(crate::actors::CallSitePrincipal),
1003}
1004
1005impl Callee {
1006    /// A static-intrinsic callee for the resolved operation `op`.
1007    pub fn intrinsic(op: crate::kernel_op::StaticOp) -> Callee {
1008        Callee::Intrinsic { ns: op.ns(), op }
1009    }
1010}
1011
1012/// Where a test-body service address (`svc.call(…)`, `svc.GET("/p")`,
1013/// `svc.schedule("*/5 * * * *")`, `ws.open(…)`) is aimed: the typed form of
1014/// [`Callee::TestService`]'s `address` string (1A.33, Decision D).
1015///
1016/// The checker first records the kind of address as soon as the method is known
1017/// (a verb with no path yet, a schedule with no expression yet) and then enriches
1018/// it once the route or expression is read, so those fields are optional.
1019#[derive(Debug, Clone, PartialEq, Eq)]
1020pub enum HandlerAddress {
1021    /// `svc.call(…)`: the `on call` handler.
1022    Call,
1023    /// `svc.<VERB>(path, …)`: an `on http` handler, matched by its route once `path` is known.
1024    Http {
1025        verb: bynk_syntax::ast::HttpMethod,
1026        path: Option<String>,
1027    },
1028    /// `svc.schedule(expr, …)`: a cron handler, matched by its schedule once `expr` is known.
1029    Schedule { expr: Option<String> },
1030    /// `svc.message(msg)`: the queue `on message` handler.
1031    Message,
1032    /// `svc.event(payload, …)`: the `on event` handler.
1033    Event,
1034    /// A WebSocket lifecycle address on a `TestConnection`.
1035    Ws(WsAddress),
1036}
1037
1038impl HandlerAddress {
1039    /// A `schedule` address once its cron expression is read.
1040    pub fn schedule(expr: &str) -> HandlerAddress {
1041        HandlerAddress::Schedule {
1042            expr: Some(expr.to_string()),
1043        }
1044    }
1045
1046    /// A `ws message` address once its handler is matched.
1047    pub fn ws_message(frame_index: usize, params: usize) -> HandlerAddress {
1048        HandlerAddress::Ws(WsAddress::Message {
1049            frame: Some(WsMessageShape {
1050                frame_index,
1051                params,
1052            }),
1053        })
1054    }
1055
1056    /// A `ws close` address once its handler is matched.
1057    pub fn ws_close(params: usize) -> HandlerAddress {
1058        HandlerAddress::Ws(WsAddress::Close {
1059            params: Some(params),
1060        })
1061    }
1062
1063    /// The address as the diagnostics write it (`POST /orders`, `call`, `ws open`).
1064    pub fn describe(&self) -> String {
1065        match self {
1066            HandlerAddress::Call => "call".to_string(),
1067            HandlerAddress::Http { verb, path: None } => verb.as_str().to_string(),
1068            HandlerAddress::Http {
1069                verb,
1070                path: Some(path),
1071            } => format!("{} {path}", verb.as_str()),
1072            HandlerAddress::Schedule { expr: None } => "schedule".to_string(),
1073            HandlerAddress::Schedule { expr: Some(expr) } => format!("schedule {expr}"),
1074            HandlerAddress::Message => "message".to_string(),
1075            HandlerAddress::Event => "event".to_string(),
1076            HandlerAddress::Ws(WsAddress::Open) => "ws open".to_string(),
1077            HandlerAddress::Ws(WsAddress::Message { .. }) => "ws message".to_string(),
1078            HandlerAddress::Ws(WsAddress::Close { .. }) => "ws close".to_string(),
1079        }
1080    }
1081}
1082
1083/// The WebSocket lifecycle step of a [`HandlerAddress::Ws`]. `Message` and `Close`
1084/// carry what the emitter needs once the handler is matched: the index of the
1085/// inbound-frame parameter and the parameter count, and the count for `close`.
1086#[derive(Debug, Clone, PartialEq, Eq)]
1087pub enum WsAddress {
1088    Open,
1089    Message { frame: Option<WsMessageShape> },
1090    Close { params: Option<usize> },
1091}
1092
1093/// The shape of a `ws message` handler: which parameter takes the inbound frame
1094/// and how many parameters it has.
1095#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1096pub struct WsMessageShape {
1097    pub frame_index: usize,
1098    pub params: usize,
1099}
1100
1101/// Whether a [`Callee::Query`] call returns another `Query[T]` (chainable)
1102/// or executes and returns `Effect[T]` — R6.12: "the builder/terminal split
1103/// is a field on the callee, not a name list." Primarily read back from
1104/// `check_query_kernel_method`'s own return type at the recording site
1105/// (`query_role`, below) — falling back to `is_query_builder_name` only
1106/// when the call didn't type at all (an arity mismatch, or a type error
1107/// deeper inside the call — `map`'s own lambda body, say — both return
1108/// `None` too, not just an arity failure), so a best-effort reader of an
1109/// uncertified/erroring unit still gets the right role.
1110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1111pub enum QueryRole {
1112    Builder,
1113    Terminal,
1114}
1115
1116/// The fallback `Callee::Query::role` classifier for when
1117/// `check_query_kernel_method`'s own return type doesn't settle it (see
1118/// `QueryRole`'s doc comment). Kept in sync by hand with
1119/// `check_query_kernel_method`'s own match arms
1120/// (`bynk-check/src/checker/kernels.rs:861-1118`) — the same "kept in sync
1121/// by hand" risk R6.11 already names for `kernel_methods.rs`'s own
1122/// registries, not a new class of drift this slice introduces.
1123fn is_query_builder_name(name: &str) -> bool {
1124    matches!(
1125        name,
1126        "map"
1127            | "filter"
1128            | "flatMap"
1129            | "sortBy"
1130            | "sortByDescending"
1131            | "take"
1132            | "skip"
1133            | "distinct"
1134            | "distinctBy"
1135            | "joinOn"
1136            | "leftJoin"
1137            | "join"
1138            | "groupBy"
1139    )
1140}
1141
1142/// P6.2 (#1143): `Callee::Query`'s `role` for a call whose op name is `op`
1143/// and whose checked result (from `check_query_kernel_method`/
1144/// `check_store_log_op`) is `result`.
1145fn query_role(result: Option<TyId>, op: &str, tys: &Types) -> QueryRole {
1146    match result.map(|t| tys.get(t)).as_deref() {
1147        Some(Ty::Query(_)) => QueryRole::Builder,
1148        Some(_) => QueryRole::Terminal,
1149        None if is_query_builder_name(op) => QueryRole::Builder,
1150        None => QueryRole::Terminal,
1151    }
1152}
1153
1154/// Output of type checking.
1155pub struct TypedCommons {
1156    pub commons: Arc<Commons>,
1157    pub types: HashMap<String, Arc<TypeDecl>>,
1158    pub fns: HashMap<String, Arc<FnDecl>>,
1159    pub methods: HashMap<String, MethodTable>,
1160    /// T3.4 (R2.4/R2.5): keyed by [`ExprId`] — a node's identity, not its
1161    /// position. The value carries its own `span` alongside `ty`, so
1162    /// LSP-facing consumers that need "type at this cursor offset" (a
1163    /// position-shaped question, asked at the editor boundary, not the
1164    /// checker's own identity) can still answer it without a second map.
1165    pub expr_types: HashMap<ExprId, TypedExpr>,
1166    /// P6.0 (#1139): the call-shaped expressions this unit's checker
1167    /// dispatched, classified once here rather than re-derived by
1168    /// `bynk-emit`'s lowering (P6.2) or any other later consumer. Mirrors
1169    /// `expr_types` exactly — same key, same "recorded during checking, read
1170    /// afterward" shape.
1171    pub callees: HashMap<ExprId, Callee>,
1172    /// v0.89 (ADR 0117): non-failing warnings produced while checking this unit
1173    /// — surfaced but not gating. Empty unless a warning-category diagnostic
1174    /// (e.g. `bynk.given.unused_capability`) fired on an otherwise-clean check.
1175    pub warnings: Vec<CompileError>,
1176    /// T3.6b (R4.1): the intern table every `TyId` on this unit — in
1177    /// `expr_types`, in a `Ty` node's own recursive fields — was minted from.
1178    /// Named `ty_intern` rather than `types` only because `types` above is
1179    /// already this struct's *declaration* table (`TypeDecl` by name); the two
1180    /// are unrelated. `Rc` so [`RecordCheck`] can hand the same table out
1181    /// beside its `result` whichever way the check went.
1182    pub ty_intern: Arc<Types>,
1183    /// #1170: a service handler's own resolved `by <binder>: <Actor>` actor
1184    /// binding — `handler_actor_binding`'s own return value
1185    /// (`context_checks.rs`), persisted here rather than discarded once
1186    /// `check_service_decls`'s own per-handler loop moves on, the same
1187    /// "recorded during checking, read afterward" shape `callees` (above)
1188    /// already established. Keyed by the handler's own `span`: a `Handler`
1189    /// has no arena identity of its own (no `DefId`/`ExprId` — it is a
1190    /// declaration, not an expression), and `Span` is already this
1191    /// codebase's established "no arena" substitute for exactly this kind
1192    /// of identity (`Copy`/`Eq`/`Hash`, already used as a diagnostic anchor
1193    /// throughout `context_checks.rs`). No entry for a handler
1194    /// `handler_actor_binding` itself resolves to `None` for: a
1195    /// binder-less `by <Actor>` clause, or no `by` clause at all —
1196    /// including every agent handler, which cannot carry one
1197    /// (`bynk.actor.by_on_agent`). Read back through [`Self::actor_binding`];
1198    /// its one IR-side consumer (P6.11, #1171, the service-handler
1199    /// actor-binder constructor in `bynk-lower`) was deleted by Slice D1 of
1200    /// #1542, so as of that slice the only readers are this crate's own
1201    /// `context_checks` tests — the table is kept because the binding is a
1202    /// checked fact about the handler, not because of who reads it.
1203    ///
1204    /// **Unit-wide, not per-file** (review of #1170, unlike `callees`/
1205    /// `expr_types`, which are genuinely per-file — keyed by `ExprId`s this
1206    /// file's own checking pass minted): `check_service_decls` walks
1207    /// `table.services`, the whole unit's own `UnitTable`, not just this
1208    /// file's declarations, so every file of a multi-file `context` ends up
1209    /// with the *entire unit's* bindings in its own `TypedCommons`. Harmless
1210    /// for a by-span lookup (a span is only ever looked up in the file that
1211    /// actually owns it), but a future consumer that *iterates* this map
1212    /// rather than looking up one known `span` would see sibling files'
1213    /// handlers too — worth knowing before writing that consumer, not
1214    /// discovering it by surprise.
1215    pub actor_bindings: HashMap<Span, (String, TyId)>,
1216    /// #1883, slice 1a: the assets visible in this unit, carried from
1217    /// [`ResolvedCommons::assets`] so a per-handler check built from this
1218    /// program (`context_checks`) still sees them.
1219    pub assets: HashMap<String, AssetDecl>,
1220    /// #2387, slice 1: the embeds visible in this unit, carried from
1221    /// [`ResolvedCommons::embeds`] for the same per-handler checks.
1222    pub embeds: HashMap<String, EmbedDecl>,
1223    /// #2617: the constants visible in this unit, carried from
1224    /// [`ResolvedCommons::consts`] for the same per-handler checks and for
1225    /// emission.
1226    pub consts: HashMap<String, ConstDecl>,
1227    /// #1925: the imports this unit's own declarations shadow, carried from
1228    /// [`ResolvedCommons::shadowed_imports`] for the same per-handler checks.
1229    pub shadowed_imports: HashMap<String, crate::resolver::ShadowedImport>,
1230    /// S3 (#1963): the extensible first-party enums in scope, carried from
1231    /// [`ResolvedCommons::extensible_enums`] for the same per-handler checks.
1232    pub extensible_enums: HashSet<String>,
1233    /// #3536: carried from [`ResolvedCommons::unselected_types`] for the same
1234    /// per-handler checks.
1235    pub unselected_types: HashSet<String>,
1236    /// S3 (#1963): carried from [`ResolvedCommons::stability`] for the same
1237    /// per-handler checks.
1238    pub stability: crate::stability::UnitStability,
1239    /// #2719: the needs-context set as of this unit — the functions that take
1240    /// the hidden execution-context parameter, and the handlers whose `deps`
1241    /// carry it. Empty until the unit's files are all checked and
1242    /// [`ExecPlan::extend`](crate::exec_plan::ExecPlan::extend) has run.
1243    pub exec_plan: Arc<crate::exec_plan::ExecPlan>,
1244}
1245
1246impl TypedCommons {
1247    /// A `TypedCommons` with no declarations — a pure-data test fixture, so a
1248    /// consuming crate's own test exercising only the `TypedCommons`-shaped
1249    /// part of some function doesn't need to hand-construct a
1250    /// `Commons`/`QualifiedName` itself (`bynk_syntax::ast` types, invisible
1251    /// to `bynk-check` but not to a consumer whose own probe tracks that
1252    /// dependency — P6.38, `design/tracks/the-ir.md` §6a).
1253    pub fn empty() -> Self {
1254        TypedCommons {
1255            commons: Arc::new(Commons {
1256                name: QualifiedName {
1257                    parts: Vec::new(),
1258                    span: Default::default(),
1259                },
1260                items: Vec::new(),
1261                uses: Vec::new(),
1262                documentation: None,
1263                form: CommonsForm::Fragment,
1264                span: Default::default(),
1265                trivia: Default::default(),
1266                trailing_comments: Vec::new(),
1267            }),
1268            types: HashMap::new(),
1269            fns: HashMap::new(),
1270            methods: HashMap::new(),
1271            expr_types: HashMap::new(),
1272            callees: HashMap::new(),
1273            warnings: Vec::new(),
1274            ty_intern: Arc::new(Types::new()),
1275            actor_bindings: HashMap::new(),
1276            assets: HashMap::new(),
1277            embeds: HashMap::new(),
1278            consts: HashMap::new(),
1279            shadowed_imports: HashMap::new(),
1280            extensible_enums: HashSet::new(),
1281            unselected_types: HashSet::new(),
1282            stability: Default::default(),
1283            exec_plan: Default::default(),
1284        }
1285    }
1286
1287    /// T3.6b (R4.1): this unit's intern table — what every `TyId` reachable
1288    /// from `expr_types` resolves against.
1289    /// Returns the `Rc` handle rather than a bare `&Types` so a caller that
1290    /// needs to *share* the table (the project path, which checks many units
1291    /// into one `ExprTypeSink`) can clone it; `&Arc<Types>` deref-coerces to
1292    /// `&Types` everywhere a plain borrow is wanted.
1293    pub fn tys(&self) -> &Arc<Types> {
1294        &self.ty_intern
1295    }
1296
1297    /// The interned node an expression was typed to, resolved in one step.
1298    /// The reader-side shape `bynk-emit`/the LSP want: they ask "what shape is
1299    /// this expression?", never "which id is it?". `Rc` so the resolve is a
1300    /// refcount bump, and `.as_deref()` gives back the `&Ty` these call sites
1301    /// read before T3.6b.
1302    pub fn expr_ty(&self, id: ExprId) -> Option<Arc<Ty>> {
1303        self.expr_types.get(&id).map(|te| self.ty_intern.get(te.ty))
1304    }
1305
1306    /// P6.0 (#1139): the resolved [`Callee`] classification for a
1307    /// call-shaped expression, if this unit's checker dispatched one at
1308    /// `id`. Mirrors [`Self::expr_ty`]'s shape.
1309    pub fn callee(&self, id: ExprId) -> Option<&Callee> {
1310        self.callees.get(&id)
1311    }
1312
1313    /// #1170: a service handler's own resolved actor binding, if
1314    /// `handler_actor_binding` (`context_checks.rs`) resolved one for the
1315    /// handler at `span`. Mirrors [`Self::callee`]'s shape — the single
1316    /// documented read point for `actor_bindings`, kept symmetric with
1317    /// `expr_ty`/`callee` rather than leaving every future consumer to
1318    /// reach into the `HashMap` directly. Its IR-side reader (P6.11, #1171)
1319    /// went with Slice D1 of #1542; see `actor_bindings`'s own doc comment.
1320    pub fn actor_binding(&self, span: Span) -> Option<&(String, TyId)> {
1321        self.actor_bindings.get(&span)
1322    }
1323}
1324
1325/// T3.4: an `expr_types` entry — the checked type, plus the span of the node
1326/// it was computed for. `Deref`-free by design (`.ty`/`.span`, not `.0`/`.1`)
1327/// so call sites read the same as they did against a bare `Ty` before this.
1328///
1329/// T3.6b (R4.1/R4.2): `ty` is a `TyId`, not a `Ty` — the whole entry is
1330/// `Copy`-cheap, and resolving it needs the unit's `ty_intern` table.
1331#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1332pub struct TypedExpr {
1333    pub span: Span,
1334    pub ty: TyId,
1335}
1336
1337/// The outcome of [`check_record`]: the typed model (`Err` if the file had any
1338/// error) and, on the error path, the program as checked so far
1339/// (`typed_despite_errors`), whose `expr_types` are the best-effort types the
1340/// checker computed. Analyse mode surfaces those for `.`-member completion and
1341/// signature help even on a broken buffer (ADR 0094).
1342pub struct RecordCheck {
1343    pub result: Result<TypedCommons, Vec<CompileError>>,
1344    /// T3.6b (R4.1): the table every `TyId` in `result` or
1345    /// `typed_despite_errors` resolves against — the same `Rc` either
1346    /// `TypedCommons::ty_intern` carries.
1347    pub ty_intern: Arc<Types>,
1348    /// #1663 (Decision A): on the `Err` path, the program as checked so far —
1349    /// every declaration was still checked, so a later stage (context
1350    /// declarations, handler bodies) can go on checking the *other*
1351    /// declarations. Never certifiable: the errors in `result` still fail
1352    /// the unit. `None` on the `Ok` path.
1353    pub typed_despite_errors: Option<TypedCommons>,
1354}
1355
1356/// T3.7 (R3.10): the gate between analysis and emission, as a type rather
1357/// than a control-flow decision — constructible only by [`certify`], so no
1358/// unchecked or error-carrying `TypedCommons` can reach the emitter by
1359/// construction (previously enforced only by every caller happening to check
1360/// a `Result` first). `certify` rejects on any error-severity diagnostic;
1361/// T3.3a's `Ty::Error` is what a diagnosed checker failure records into
1362/// `expr_types`, so in practice a `Ty::Error` never reaches a `CheckedProgram`
1363/// either — R4.3's "rejected by certify" already holds today via the same
1364/// diagnostic-severity gate `certify` makes structural.
1365///
1366/// Scoped to the single-file compile path for now (`bynk-emit`'s
1367/// `compile_with_warnings`). The project/batch path's per-unit `emit_project`
1368/// call happens *before* that unit's build-wide gate is finally decided
1369/// (cross-unit validation can still fail the whole build afterward), so
1370/// wrapping it in `CheckedProgram` at today's call site would misrepresent an
1371/// unfinished decision as a certified one — that path needs its own slice,
1372/// not forced into this one.
1373pub struct CheckedProgram(TypedCommons);
1374
1375impl CheckedProgram {
1376    /// The certified program. No accessor exists that goes the other
1377    /// direction — a `TypedCommons` is never recoverable-then-rewrapped
1378    /// without going through `certify` again.
1379    pub fn program(&self) -> &TypedCommons {
1380        &self.0
1381    }
1382}
1383
1384/// The single place "may we emit?" is asked (R3.10). Rejects — returning
1385/// every diagnostic, not just the error-severity ones, matching
1386/// `check_record`'s own error-path convention — if `diagnostics` contains an
1387/// error-severity entry; otherwise wraps `program` as certified.
1388pub fn certify(
1389    program: TypedCommons,
1390    diagnostics: Vec<CompileError>,
1391) -> Result<CheckedProgram, Vec<CompileError>> {
1392    let (hard_errors, warnings) = bynk_syntax::partition_by_severity(diagnostics);
1393    if hard_errors.is_empty() {
1394        Ok(CheckedProgram(program))
1395    } else {
1396        let mut all = hard_errors;
1397        all.extend(warnings);
1398        Err(all)
1399    }
1400}
1401
1402// ==== Entry points ====
1403
1404/// #2607 (Decisions B and I): validate each default a record type's fields
1405/// declare (`field: T = expr`). It must be a static value of the field's type,
1406/// the rule an event field's default follows, and it must have a wire form,
1407/// since a body that lacks the key decodes to it. In a generic record, a
1408/// default must hold for every instantiation: a field whose type is a bare
1409/// type parameter has none.
1410#[allow(clippy::too_many_arguments)]
1411fn check_record_field_defaults(
1412    t: &TypeDecl,
1413    input: &ResolvedCommons,
1414    tys: &Types,
1415    expr_types: &mut HashMap<ExprId, TypedExpr>,
1416    callees: &mut HashMap<ExprId, Callee>,
1417    errors: &mut Vec<CompileError>,
1418    refs: &mut RefSink,
1419    hints: &mut HintSink,
1420    locals: &mut LocalsSink,
1421) {
1422    let TypeBody::Record(r) = &t.body else {
1423        return;
1424    };
1425    for field in &r.fields {
1426        let Some(init) = &field.init else {
1427            continue;
1428        };
1429        if let TypeRef::Named(id) = &field.type_ref
1430            && t.type_params.iter().any(|p| p.name.name == id.name)
1431        {
1432            errors.push(
1433                CompileError::new(
1434                    "bynk.types.bad_field_default",
1435                    init.span,
1436                    format!(
1437                        "field `{}` has the type parameter `{}`, so it cannot have a default",
1438                        field.name.name, id.name
1439                    ),
1440                )
1441                .with_note(
1442                    "no single value has every type; a default must hold for every \
1443                     instantiation of the record, as `None`, `[]` or `Map.empty()` do",
1444                ),
1445            );
1446            continue;
1447        }
1448        let before = errors.len();
1449        check_event_field_default(
1450            init,
1451            &field.type_ref,
1452            "record field default",
1453            input,
1454            tys,
1455            expr_types,
1456            callees,
1457            errors,
1458            refs,
1459            hints,
1460            locals,
1461        );
1462        if errors.len() > before {
1463            continue;
1464        }
1465        let params: Vec<String> = t.type_params.iter().map(|p| p.name.name.clone()).collect();
1466        if let Err(reason) = crate::wire_default::lower_field_default_wire_in(
1467            init,
1468            &field.type_ref,
1469            &input.types,
1470            &params,
1471        ) {
1472            // A default that reaches a type parameter (`Option[T] = Some(1)`)
1473            // holds for one instantiation at most.
1474            if let crate::wire_default::DefaultReason::UnresolvedType(name) = &reason
1475                && let Some(p) = t.type_params.iter().find(|p| &p.name.name == name)
1476            {
1477                errors.push(
1478                    CompileError::new(
1479                        "bynk.types.bad_field_default",
1480                        init.span,
1481                        format!(
1482                            "field `{}`'s default does not hold for every `{}`",
1483                            field.name.name, p.name.name
1484                        ),
1485                    )
1486                    .with_note(
1487                        "a generic record's default must hold for every instantiation, as \
1488                         `None`, `[]` or `Map.empty()` do",
1489                    ),
1490                );
1491                continue;
1492            }
1493            errors.push(
1494                CompileError::new(
1495                    "bynk.types.bad_field_default",
1496                    init.span,
1497                    format!(
1498                        "field `{}`'s default cannot be represented on the wire: {reason}",
1499                        field.name.name
1500                    ),
1501                )
1502                .with_note(
1503                    "a body without this field decodes to its default, so the default needs a \
1504                     wire form: a literal, a variant, `Some`/`None`/`Ok`/`Err`, a record, a \
1505                     list literal, or `Map.empty()`/`Set.empty()`",
1506                ),
1507            );
1508        }
1509    }
1510}
1511
1512/// #1688: clear the cache of generic functions' compared type parameters.
1513/// A project check calls this once before its per-unit loop; a single-file
1514/// [`check`] calls it itself.
1515pub fn reset_compared_cache() {
1516    equality::reset_compared_cache();
1517}
1518
1519pub fn check(input: ResolvedCommons) -> Result<TypedCommons, Vec<CompileError>> {
1520    reset_compared_cache();
1521    check_record(
1522        input,
1523        &mut RefSink::new(),
1524        &mut HintSink::new(),
1525        &mut LocalsSink::new(),
1526        &mut RequirementSink::new(),
1527    )
1528    .result
1529}
1530
1531/// [`check`], recording binding edges into `refs` at the checker's
1532/// resolution sites (v0.25). A fresh sink records nothing.
1533pub fn check_record(
1534    input: ResolvedCommons,
1535    refs: &mut RefSink,
1536    hints: &mut HintSink,
1537    locals: &mut LocalsSink,
1538    requirements: &mut RequirementSink,
1539) -> RecordCheck {
1540    check_record_in(
1541        input,
1542        &Arc::new(Types::new()),
1543        refs,
1544        hints,
1545        locals,
1546        requirements,
1547    )
1548}
1549
1550/// [`check_record`] against a **caller-supplied** intern table (T3.6b, R4.1).
1551///
1552/// The per-invocation table `check_record` mints is the right default: one
1553/// unit, one table, ids that never escape it. A *project* check is the case
1554/// that needs more — it runs `check_record` once per unit but funnels every
1555/// unit's `expr_types` into one `ExprTypeSink`, so a `TyId` recorded there
1556/// would be ambiguous if each unit interned into a table of its own. Sharing
1557/// one table across the whole analysis makes those ids mean one thing, and is
1558/// strictly safer than the per-unit case the track doc argued for: ids are
1559/// still only ever compared against ids from the same table.
1560pub fn check_record_in(
1561    input: ResolvedCommons,
1562    ty_intern: &Arc<Types>,
1563    refs: &mut RefSink,
1564    hints: &mut HintSink,
1565    locals: &mut LocalsSink,
1566    requirements: &mut RequirementSink,
1567) -> RecordCheck {
1568    let ty_intern = Arc::clone(ty_intern);
1569    let mut errors = Vec::new();
1570    let mut expr_types: HashMap<ExprId, TypedExpr> = HashMap::new();
1571    let mut callees: HashMap<ExprId, Callee> = HashMap::new();
1572    // 1. Validate each type declaration. State-migrations S2 (#2224): a record
1573    // naming a `migrate` step's old shape may declare field defaults — they
1574    // stand in for an initialiser a field had at that version (Decision C).
1575    let migrate_old_types: HashSet<&str> = input
1576        .commons
1577        .items
1578        .iter()
1579        .filter_map(|i| match i {
1580            CommonsItem::Agent(a) => Some(a),
1581            _ => None,
1582        })
1583        .flat_map(|a| a.migrations.iter())
1584        .filter_map(|m| match m.old.as_ref().map(|o| &o.type_ref) {
1585            Some(TypeRef::Named(id)) => Some(id.name.as_str()),
1586            _ => None,
1587        })
1588        .collect();
1589    for item in &input.commons.items {
1590        if let CommonsItem::Type(t) = item {
1591            check_type_decl(t, &input.types, &ty_intern, &mut errors);
1592            // #2607: a record field's default. A `migrate` step's old shape
1593            // is validated by its agent's own check, against the types the
1594            // agent sees, so it is skipped here rather than reported twice.
1595            if !migrate_old_types.contains(t.name.name.as_str()) {
1596                check_record_field_defaults(
1597                    t,
1598                    &input,
1599                    &ty_intern,
1600                    &mut expr_types,
1601                    &mut callees,
1602                    &mut errors,
1603                    refs,
1604                    hints,
1605                    locals,
1606                );
1607            }
1608        }
1609    }
1610
1611    // 1b. #2617: check each constant declared in this file — its name, its
1612    // initialiser's static-ness and type — and the cycles through it.
1613    let local_consts: Vec<&ConstDecl> = input
1614        .commons
1615        .items
1616        .iter()
1617        .filter_map(|i| match i {
1618            CommonsItem::Const(c) => Some(c),
1619            _ => None,
1620        })
1621        .collect();
1622    for c in &local_consts {
1623        check_const_decl(
1624            c,
1625            &input,
1626            &ty_intern,
1627            &mut expr_types,
1628            &mut callees,
1629            &mut errors,
1630            refs,
1631            hints,
1632            locals,
1633        );
1634    }
1635    // A cycle can only run through this unit's own constants (`uses` is
1636    // acyclic), so the walk follows only them and treats an imported
1637    // constant as a leaf. Following an imported constant's initialiser here
1638    // would resolve its names in this unit's scope, where a local constant of
1639    // the same name would be taken for the one it actually names.
1640    let own_consts: HashMap<String, ConstDecl> = local_consts
1641        .iter()
1642        .map(|c| (c.name.name.clone(), (*c).clone()))
1643        .collect();
1644    errors.extend(crate::consts::cycle_errors(&local_consts, &own_consts));
1645
1646    // 2. Type-check each function and method body.
1647    for item in &input.commons.items {
1648        if let CommonsItem::Fn(f) = item {
1649            // #2868: `given` on a function. A refused declaration is reported
1650            // and its body is not checked; a context function's is checked with
1651            // the context's declarations (`check_given_fns`).
1652            if !f.given.is_empty() {
1653                if let Some(err) = given_fn_refusal(f, input.is_context) {
1654                    errors.push(err);
1655                }
1656                continue;
1657            }
1658            refs.set_owner(f.name.display());
1659            check_fn(
1660                f,
1661                &input,
1662                &mut expr_types,
1663                &mut callees,
1664                &mut errors,
1665                refs,
1666                hints,
1667                locals,
1668                requirements,
1669                &ty_intern,
1670            );
1671            refs.clear_owner();
1672        }
1673    }
1674    // #1688: record this unit's generics' compared type parameters, in this
1675    // unit's environment, for the units that import them.
1676    equality::scan_local_generics(&input, &ty_intern);
1677
1678    // v0.89 (ADR 0117): split diagnostics by severity. A unit with no
1679    // error-severity diagnostic *checks* — its warnings ride on `TypedCommons`,
1680    // surfaced but non-gating. Only error-severity diagnostics fail the check;
1681    // on that path the warnings are appended so a failed build still renders
1682    // them.
1683    // Finding #28 (debug-only): `Span` is `expr_types`'s key, but nothing
1684    // enforces that no two AST nodes needing a type share one — bug #844 and
1685    // the else-less-`if` synthesis both did, silently, before either was
1686    // caught. Walk every checked function/method body with the total child
1687    // iterator `ast::expr_children` and assert no two nodes recorded here
1688    // collide; a release build doesn't pay for the walk. Scoped per item,
1689    // not across the whole commons: a multi-file commons's merged item list
1690    // legitimately re-walks the same function more than once (its own,
1691    // separate redundancy, outside this finding's scope), and both known
1692    // collisions (#844, the else-less-`if` synthesis) are contained within a
1693    // single function/handler body regardless.
1694    #[cfg(debug_assertions)]
1695    for item in &input.commons.items {
1696        if let CommonsItem::Fn(f) = item {
1697            let mut seen: HashSet<ExprId> = HashSet::new();
1698            assert_expr_types_disjoint_in_block(&f.body, &expr_types, &mut seen);
1699        }
1700    }
1701
1702    let (hard_errors, warnings) = bynk_syntax::partition_by_severity(errors);
1703    if hard_errors.is_empty() {
1704        RecordCheck {
1705            result: Ok(TypedCommons {
1706                commons: input.commons,
1707                types: input.types,
1708                fns: input.fns,
1709                methods: input.methods,
1710                expr_types,
1711                callees,
1712                warnings,
1713                ty_intern: Arc::clone(&ty_intern),
1714                actor_bindings: HashMap::new(),
1715                assets: input.assets,
1716                embeds: input.embeds,
1717                consts: input.consts,
1718                shadowed_imports: input.shadowed_imports,
1719                extensible_enums: input.extensible_enums,
1720                unselected_types: input.unselected_types,
1721                stability: input.stability,
1722                exec_plan: Default::default(),
1723            }),
1724            ty_intern,
1725            typed_despite_errors: None,
1726        }
1727    } else {
1728        // Keep the best-effort types the checker already computed; Analyse mode
1729        // surfaces them for `.`-member completion on a broken buffer (ADR 0094).
1730        let mut all = hard_errors;
1731        all.extend(warnings);
1732        RecordCheck {
1733            result: Err(all),
1734            typed_despite_errors: Some(TypedCommons {
1735                commons: input.commons,
1736                types: input.types,
1737                fns: input.fns,
1738                methods: input.methods,
1739                expr_types,
1740                callees,
1741                warnings: Vec::new(),
1742                ty_intern: Arc::clone(&ty_intern),
1743                actor_bindings: HashMap::new(),
1744                assets: input.assets,
1745                embeds: input.embeds,
1746                consts: input.consts,
1747                shadowed_imports: input.shadowed_imports,
1748                extensible_enums: input.extensible_enums,
1749                unselected_types: input.unselected_types,
1750                stability: input.stability,
1751                exec_plan: Default::default(),
1752            }),
1753            ty_intern,
1754        }
1755    }
1756}
1757
1758/// #3066: check the `type` and `const` declarations of a suite, already added to
1759/// `input` (the suite's view). They are checked as a unit's own are:
1760/// `check_type_decl`, a record's field defaults, `check_const_decl` and the
1761/// cycles through the suite's constants. Returns the initialisers' expression
1762/// types and callee classifications for the emitter.
1763#[allow(clippy::too_many_arguments)]
1764pub fn check_suite_decls(
1765    types: &[TypeDecl],
1766    consts: &[ConstDecl],
1767    input: &ResolvedCommons,
1768    tys: &Arc<Types>,
1769    errors: &mut Vec<CompileError>,
1770    refs: &mut RefSink,
1771    locals: &mut LocalsSink,
1772) -> (HashMap<ExprId, TypedExpr>, HashMap<ExprId, Callee>) {
1773    let mut expr_types = HashMap::new();
1774    let mut callees = HashMap::new();
1775    let mut hints = HintSink::new();
1776    for t in types {
1777        check_type_decl(t, &input.types, tys, errors);
1778        check_record_field_defaults(
1779            t,
1780            input,
1781            tys,
1782            &mut expr_types,
1783            &mut callees,
1784            errors,
1785            refs,
1786            &mut hints,
1787            locals,
1788        );
1789    }
1790    let local: Vec<&ConstDecl> = consts.iter().collect();
1791    for c in &local {
1792        check_const_decl(
1793            c,
1794            input,
1795            tys,
1796            &mut expr_types,
1797            &mut callees,
1798            errors,
1799            refs,
1800            &mut hints,
1801            locals,
1802        );
1803    }
1804    let own: HashMap<String, ConstDecl> = consts
1805        .iter()
1806        .map(|c| (c.name.name.clone(), c.clone()))
1807        .collect();
1808    errors.extend(crate::consts::cycle_errors(&local, &own));
1809    (expr_types, callees)
1810}
1811
1812/// #2868: why a `given` clause on this function is refused, if it is. Only a
1813/// free, effectful function in a context may declare `given`: a context knows
1814/// which capabilities it consumes, where a commons is shared by contexts that
1815/// may consume different ones (so its functions keep the function-value style,
1816/// `(m) => Logger.error(m)` passed in), and a method call has no place to carry
1817/// the capabilities.
1818pub(crate) fn given_fn_refusal(f: &FnDecl, is_context: bool) -> Option<CompileError> {
1819    let span = f.given.first().map(|g| g.span)?;
1820    let span = span.merge(f.given.last().map_or(span, |g| g.span));
1821    if !is_context {
1822        return Some(
1823            CompileError::new(
1824                "bynk.given.fn_outside_context",
1825                span,
1826                format!(
1827                    "function `{}` cannot declare `given`: only a function in a context can",
1828                    f.name.display()
1829                ),
1830            )
1831            .with_note(
1832                "a commons is shared by every context that uses it, and those contexts may consume different capabilities, so a commons function reaches a capability only through a function value its caller passes in",
1833            )
1834            .with_note(
1835                "take the operation as a parameter instead, `log: (String) -> Effect[()]`, and pass `(m) => Logger.error(m)` from the handler; or move the function into the context that consumes the capability",
1836            ),
1837        );
1838    }
1839    if matches!(f.name, FnName::Method { .. }) {
1840        return Some(
1841            CompileError::new(
1842                "bynk.given.fn_unsupported",
1843                span,
1844                format!(
1845                    "method `{}` cannot declare `given`",
1846                    f.name.display()
1847                ),
1848            )
1849            .with_note("only a free function in a context can declare `given`; take the operation as a function-value parameter, or make this a free function"),
1850        );
1851    }
1852    if !matches!(f.return_type, TypeRef::Effect(..)) {
1853        return Some(
1854            CompileError::new(
1855                "bynk.given.fn_unsupported",
1856                span,
1857                format!(
1858                    "function `{}` declares `given` but does not return `Effect[T]`",
1859                    f.name.display()
1860                ),
1861            )
1862            .with_note("a capability operation is an effect, so a function that uses one returns `Effect[T]`"),
1863        );
1864    }
1865    if let Some(ev) = f.given.iter().find(|g| g.key() == "Events") {
1866        return Some(
1867            CompileError::new(
1868                "bynk.given.fn_unsupported",
1869                ev.span,
1870                format!(
1871                    "function `{}` cannot declare `given Events`",
1872                    f.name.display()
1873                ),
1874            )
1875            .with_note("`Events.emit` buffers until its handler commits, so it belongs in the handler: emit there, or pass the event back to the caller"),
1876        );
1877    }
1878    None
1879}
1880
1881/// Finding #28 (debug-only), T3.4: the block-level half of the `expr_types`
1882/// identity-uniqueness walk — visits every statement expression and the tail.
1883/// `ExprId` uniqueness is guaranteed by construction (`Parser::alloc_expr_id`
1884/// is the sole allocation point), so this can no longer catch a *parser*
1885/// collision the way it caught #844 on `Span`; it stays as the loud check
1886/// that a synthetic node (`ExprId::SYNTHETIC`) never reaches the checker's
1887/// own `expr_types` — the one way two entries could still collide.
1888#[cfg(debug_assertions)]
1889fn assert_expr_types_disjoint_in_block(
1890    block: &Block,
1891    expr_types: &HashMap<ExprId, TypedExpr>,
1892    seen: &mut HashSet<ExprId>,
1893) {
1894    let mut roots: Vec<&Expr> = Vec::new();
1895    for s in &block.statements {
1896        bynk_syntax::ast::statement_exprs(s, &mut roots);
1897    }
1898    roots.push(&block.tail);
1899    for e in roots {
1900        assert_expr_types_disjoint(e, expr_types, seen);
1901    }
1902}
1903
1904/// Finding #28 (debug-only), T3.4: recurses over an expression with the
1905/// total child iterator `ast::expr_children`, asserting no two nodes
1906/// recorded into `expr_types` share an [`ExprId`] — a collision means one
1907/// node's recorded type silently clobbered another's (bug #844's class of
1908/// bug, before `ExprId` made position-derived collisions structurally
1909/// impossible for parser-allocated nodes).
1910#[cfg(debug_assertions)]
1911fn assert_expr_types_disjoint(
1912    e: &Expr,
1913    expr_types: &HashMap<ExprId, TypedExpr>,
1914    seen: &mut HashSet<ExprId>,
1915) {
1916    assert!(
1917        e.id != ExprId::SYNTHETIC || !expr_types.contains_key(&e.id),
1918        "bynk internal error (finding #28): a synthetic node (ExprId::SYNTHETIC) reached the \
1919         checker's own `expr_types` at {:?} — synthetic nodes are built after checking and must \
1920         never be inserted here",
1921        e.span
1922    );
1923    if expr_types.contains_key(&e.id) {
1924        assert!(
1925            seen.insert(e.id),
1926            "bynk internal error (finding #28): two typed AST nodes share id {:?} (span {:?}) in \
1927             `expr_types` — one node's recorded type silently clobbered another's",
1928            e.id,
1929            e.span
1930        );
1931    }
1932    for child in bynk_syntax::ast::expr_children(e) {
1933        assert_expr_types_disjoint(child, expr_types, seen);
1934    }
1935}
1936
1937/// #522: the six output sinks a handler-body check writes into. One struct at
1938/// each call site instead of six positional `&mut` arguments.
1939pub struct CheckSinks<'a> {
1940    /// T3.6b (R4.1): the intern table the `TyId`s written into `expr_types`
1941    /// (and carried on [`HandlerBodyCheck`]) resolve against. Belongs with the
1942    /// sinks rather than the signature: it is the thing a body check *writes*
1943    /// types into, and a caller holding a `TypedCommons` passes its
1944    /// `ty_intern` straight through.
1945    pub tys: &'a Types,
1946    pub expr_types: &'a mut HashMap<ExprId, TypedExpr>,
1947    pub errors: &'a mut Vec<CompileError>,
1948    pub refs: &'a mut RefSink,
1949    pub hints: &'a mut HintSink,
1950    pub locals: &'a mut LocalsSink,
1951    pub requirements: &'a mut RequirementSink,
1952    /// P6.0 (#1139): the `Callee` classification sink — see [`Callee`].
1953    pub callees: &'a mut HashMap<ExprId, Callee>,
1954}
1955
1956/// #522: everything [`check_handler_body`] needs to know about the handler —
1957/// signature, capability scope, agent state, and held bindings. Replaces what
1958/// was 17 positional parameters (of a 24-parameter signature); [`Self::new`]
1959/// fills the agent/actor/store extras with empties, so a simple site
1960/// (provider op, test body) sets only the fields it actually uses.
1961pub struct HandlerBodyCheck<'a> {
1962    pub body: &'a Block,
1963    pub return_type: &'a TypeRef,
1964    pub params: &'a [Param],
1965    /// The capabilities the body may call (the handler's resolved `given`).
1966    pub capabilities: HashMap<String, CapabilityInfo>,
1967    /// Every declared capability, for "declared but not given" diagnostics.
1968    pub declared_capabilities: HashMap<String, CapabilityInfo>,
1969    pub given: &'a [CapRef],
1970    pub given_anchor: Option<Span>,
1971    pub report_unused: bool,
1972    /// An agent handler's synthetic state-record type, when one is in scope.
1973    pub agent_state_ty: Option<TyId>,
1974    pub agent_self_scope: Option<HashMap<String, TyId>>,
1975    /// v0.45/v0.52: the `by <binder>: <Actor(s)>` binding — the binder name and
1976    /// its fully-formed sealed type: `Ty::Actor(identity)` for a single actor
1977    /// (so `binder.identity` type-checks), or `Ty::ActorSum(members)` for a sum
1978    /// (so the body `match`es on it). `None` for handlers without a `by` binder.
1979    pub actor_binding: Option<(String, TyId)>,
1980    /// The agent's `store` fields, by name (finding #36 — see [`StoreField`]),
1981    /// so the `:=` write form, `<field>.<op>(…)`, and the map query accessors
1982    /// can resolve their target. Empty for service/test bodies and `state {
1983    /// }` agents.
1984    pub store_fields: HashMap<String, StoreField>,
1985    /// v0.106 (slice 3b-iii): held params that are **borrowed**, not owned —
1986    /// the firing `connection` of a `from websocket` `on message`/`on close`.
1987    /// Borrowed bindings admit non-consuming ops (`send`) but carry no disposal
1988    /// obligation. Empty for every other handler (including `on open`, whose
1989    /// connection is owned).
1990    pub borrowed_held: HashSet<String>,
1991    /// #2380 (L5): the binder name when the `by` actor is an `Oidc` one.
1992    pub oidc_binder: Option<String>,
1993    /// #2683: the body is a service handler's, whose `deps` carry the
1994    /// execution context `e.within(d)` needs.
1995    pub service_handler: bool,
1996}
1997
1998impl<'a> HandlerBodyCheck<'a> {
1999    /// A check of `body` against `return_type` with everything optional empty:
2000    /// no capabilities, no agent state, no actor binding, no store fields.
2001    pub fn new(
2002        body: &'a Block,
2003        return_type: &'a TypeRef,
2004        params: &'a [Param],
2005        given: &'a [CapRef],
2006    ) -> Self {
2007        Self {
2008            body,
2009            return_type,
2010            params,
2011            capabilities: HashMap::new(),
2012            declared_capabilities: HashMap::new(),
2013            given,
2014            given_anchor: None,
2015            report_unused: false,
2016            agent_state_ty: None,
2017            agent_self_scope: None,
2018            actor_binding: None,
2019            store_fields: HashMap::new(),
2020            borrowed_held: HashSet::new(),
2021            oidc_binder: None,
2022            service_handler: false,
2023        }
2024    }
2025}
2026
2027/// Check a single handler body (used for service and agent handlers).
2028pub fn check_handler_body(
2029    input: &ResolvedCommons,
2030    check: HandlerBodyCheck<'_>,
2031    sinks: CheckSinks<'_>,
2032) {
2033    let HandlerBodyCheck {
2034        body,
2035        return_type,
2036        params,
2037        capabilities,
2038        declared_capabilities,
2039        given,
2040        given_anchor,
2041        report_unused,
2042        agent_state_ty,
2043        agent_self_scope,
2044        actor_binding,
2045        store_fields,
2046        borrowed_held,
2047        oidc_binder,
2048        service_handler: in_service_handler,
2049    } = check;
2050    let CheckSinks {
2051        tys,
2052        expr_types,
2053        errors,
2054        refs,
2055        hints,
2056        locals,
2057        requirements,
2058        callees,
2059    } = sinks;
2060    let return_ty_span = return_type.span();
2061    let Some(return_ty) = resolve_type_ref(return_type, &input.types, tys) else {
2062        return;
2063    };
2064    let no_vars = HashSet::new();
2065    record_type_refs(return_type, &input.types, &no_vars, refs);
2066    // Build the parameter scope.
2067    let mut param_scope: HashMap<String, TyId> = HashMap::new();
2068    for p in params {
2069        if let Some(t) = resolve_type_ref(&p.type_ref, &input.types, tys) {
2070            record_type_refs(&p.type_ref, &input.types, &no_vars, refs);
2071            // v0.31: a handler/op parameter is in scope over the whole body.
2072            if p.name.name != "_" {
2073                locals.record(
2074                    p.name.name.clone(),
2075                    p.name.span,
2076                    crate::locals::LocalKind::Param,
2077                    t.display(tys),
2078                    body.span,
2079                );
2080            }
2081            param_scope.insert(p.name.name.clone(), t);
2082        }
2083    }
2084    if let Some((binder, binder_ty)) = actor_binding {
2085        if binder != "_" {
2086            locals.record(
2087                binder.clone(),
2088                body.span,
2089                crate::locals::LocalKind::Param,
2090                "actor".to_string(),
2091                body.span,
2092            );
2093        }
2094        param_scope.insert(binder, binder_ty);
2095    }
2096    if let Some(self_scope) = agent_self_scope {
2097        param_scope.extend(self_scope);
2098    }
2099    let effectful = return_ty.is_effect(tys);
2100    let given_entries: Vec<(String, Span)> = given
2101        .iter()
2102        .map(|c| (c.key().to_string(), c.span))
2103        .collect();
2104    let given_remaining: HashSet<String> = given_entries.iter().map(|(k, _)| k.clone()).collect();
2105    let mut ctx = Ctx {
2106        input,
2107        tys,
2108        expr_types,
2109        errors,
2110        refs,
2111        hints,
2112        locals,
2113        requirements,
2114        callees,
2115        scopes: vec![param_scope],
2116        list_lens: HashMap::new(),
2117        row_links: HashMap::new(),
2118        is_binding_cache: HashMap::new(),
2119        admitted_literals: HashMap::new(),
2120        pattern_binding_types: HashMap::new(),
2121        let_else_removals: HashMap::new(),
2122        store_writing_lambdas: HashMap::new(),
2123        question_let_binders: HashMap::new(),
2124        return_ty,
2125        return_ty_span,
2126        effectful,
2127        agent_state_ty,
2128        commit_seen: false,
2129        caps: CapabilityCtx {
2130            capabilities,
2131            declared_capabilities,
2132            given_remaining,
2133            given_used: HashSet::new(),
2134            given_entries: given_entries.clone(),
2135            given_anchor,
2136            ..Default::default()
2137        },
2138        in_test_body: false,
2139        oidc_binder,
2140        test_services: HashMap::new(),
2141        test_actors: HashMap::new(),
2142        type_vars: HashSet::new(),
2143        eq: EqScope::default(),
2144        last_witness: None,
2145        store_fields,
2146        in_agent_handler: agent_state_ty.is_some(),
2147        in_service_handler,
2148        in_fn_body: false,
2149        test_values: false,
2150    };
2151    // Check the body and validate it matches the return type.
2152    let Some(body_ty) = type_of_block(body, Some(return_ty), &mut ctx) else {
2153        return;
2154    };
2155    // v0.102 (§3 step 11): the held-resource linearity pass, now that
2156    // `expr_types` is fully populated by the body walk above.
2157    linearity::check(
2158        body,
2159        params,
2160        &input.types,
2161        ctx.expr_types,
2162        &ctx.pattern_binding_types,
2163        &borrowed_held,
2164        ctx.errors,
2165        tys,
2166    );
2167    // Finding #28 (debug-only), extended: `check_record`'s per-function walk
2168    // (43abc242) never reaches a handler body — `check_handler_body` is
2169    // `bynk-emit`'s own entry point for service/agent handlers, called
2170    // directly from `validate.rs`, not from `check_record`'s
2171    // `CommonsItem::Fn` loop. A fresh `seen` set per call, matching the
2172    // per-item (not per-commons) granularity 43abc242 chose, so a
2173    // multi-file commons re-checking the same handler doesn't false-positive.
2174    #[cfg(debug_assertions)]
2175    {
2176        let mut seen: HashSet<ExprId> = HashSet::new();
2177        assert_expr_types_disjoint_in_block(body, ctx.expr_types, &mut seen);
2178    }
2179    if !compatible(body_ty, return_ty, tys) {
2180        let err = CompileError::new(
2181            "bynk.types.return_mismatch",
2182            body.tail.span,
2183            format!(
2184                "handler body has type `{}`, but the declared return type is `{}`",
2185                body_ty.display(tys),
2186                return_ty.display(tys)
2187            ),
2188        )
2189        .with_label(return_ty_span, "declared return type");
2190        ctx.errors
2191            .push(calls::with_of_hint(err, body_ty, return_ty, &ctx));
2192    }
2193    if report_unused {
2194        let given_removal_anchor = ctx.caps.given_anchor.unwrap_or(return_ty_span);
2195        report_unused_given(
2196            &mut ctx,
2197            &given_entries,
2198            return_ty_span,
2199            given_removal_anchor,
2200        );
2201    }
2202}
2203
2204/// Bidirectional `given` check, second half: every declared capability is used.
2205/// Entries are walked in declaration order (deduplicated by key) so diagnostics
2206/// and their fixes are stable. Shared by handlers and (#2868) `given` functions,
2207/// whose clause follows the return type just as a handler's does.
2208pub(crate) fn report_unused_given(
2209    ctx: &mut Ctx,
2210    given_entries: &[(String, Span)],
2211    return_ty_span: Span,
2212    removal_anchor: Span,
2213) {
2214    // Bidirectional `given` check.
2215    // 1) Every used capability is declared. (Handled in capability-call site.)
2216    // 2) Every declared capability is used — anything left in given_remaining
2217    //    minus given_used is unused. Emit as a warning-category error so the
2218    //    test harness can match it. Entries are walked in declaration order
2219    //    (deduplicated by key) so diagnostics and their fixes are stable.
2220    let mut reported: HashSet<&str> = HashSet::new();
2221    for (i, (c, _)) in given_entries.iter().enumerate() {
2222        if ctx.caps.given_used.contains(c) || !reported.insert(c) {
2223            continue;
2224        }
2225        ctx.errors.push(
2226            CompileError::new(
2227                "bynk.given.unused_capability",
2228                return_ty_span,
2229                format!("capability `{c}` is declared in `given` but never used in the body"),
2230            )
2231            // Finding #49: the CLI now renders `.with_suggestion` below, so
2232            // this note carries only the alternative fix the suggestion
2233            // doesn't (removing the capability from `given`).
2234            .with_note("alternatively, use the capability in the body")
2235            // v0.26 (ADR 0054): the removal is list-aware — only `report_unused`
2236            // sites are handlers, where the clause follows the return type, so
2237            // `return_ty_span` anchors the only-entry case.
2238            .with_suggestion(
2239                format!("remove `{c}` from the `given` clause"),
2240                vec![(
2241                    given_removal_span(given_entries, i, removal_anchor),
2242                    String::new(),
2243                )],
2244                Applicability::MachineApplicable,
2245            ),
2246        );
2247    }
2248}
2249
2250/// Type-check a bare body against `return_ty` in `scope`, with `caps`
2251/// available as both in-scope and declared capabilities and (if non-empty)
2252/// `test_services`/`test_actors` in scope for a test-case body's `svc.call`/
2253/// `by <Actor>(...)` resolution (§32/#33: the one shape every hand-rolled
2254/// `Ctx` outside this crate needed, letting `Ctx` itself stay `pub(crate)`).
2255/// `where_pred`, if present, is checked first against `Bool` (a property's
2256/// optional `for all ... where` filter — `bynk.property.where_not_bool` on
2257/// mismatch), sharing `ctx` with the main body so both populate the same
2258/// `expr_types`/`errors` sinks. Unlike [`check_handler_body`], this skips
2259/// the linearity pass, the return-type-mismatch diagnostic, and the
2260/// unused-`given` diagnostic — nothing outside this crate that built its
2261/// own `Ctx` ran those either, and adding them here would be a behaviour
2262/// change, not a refactor.
2263#[allow(clippy::too_many_arguments)]
2264pub fn check_body(
2265    input: &ResolvedCommons,
2266    body: &Block,
2267    return_ty: TyId,
2268    return_ty_span: Span,
2269    scope: HashMap<String, TyId>,
2270    caps: CapabilityCtx,
2271    test_services: HashMap<String, TestServiceSig>,
2272    test_actors: HashMap<String, bynk_syntax::ast::ActorDecl>,
2273    where_pred: Option<&Expr>,
2274    sinks: CheckSinks<'_>,
2275) -> Option<TyId> {
2276    let CheckSinks {
2277        tys,
2278        expr_types,
2279        errors,
2280        refs,
2281        hints,
2282        locals,
2283        requirements,
2284        callees,
2285    } = sinks;
2286    let mut ctx = Ctx {
2287        input,
2288        tys,
2289        expr_types,
2290        errors,
2291        refs,
2292        hints,
2293        locals,
2294        requirements,
2295        callees,
2296        scopes: vec![scope],
2297        list_lens: HashMap::new(),
2298        row_links: HashMap::new(),
2299        is_binding_cache: HashMap::new(),
2300        admitted_literals: HashMap::new(),
2301        pattern_binding_types: HashMap::new(),
2302        let_else_removals: HashMap::new(),
2303        store_writing_lambdas: HashMap::new(),
2304        question_let_binders: HashMap::new(),
2305        return_ty,
2306        return_ty_span,
2307        effectful: return_ty.is_effect(tys),
2308        agent_state_ty: None,
2309        commit_seen: false,
2310        caps,
2311        in_test_body: true,
2312        oidc_binder: None,
2313        test_services,
2314        test_actors,
2315        type_vars: HashSet::new(),
2316        eq: EqScope::default(),
2317        last_witness: None,
2318        store_fields: HashMap::new(),
2319        in_agent_handler: false,
2320        in_service_handler: false,
2321        in_fn_body: false,
2322        test_values: false,
2323    };
2324    if let Some(w) = where_pred {
2325        let bool_ty = tys.intern(Ty::Base(BaseType::Bool));
2326        if let Some(actual) = type_of(w, Some(bool_ty), &mut ctx)
2327            && actual.base(tys) != Some(BaseType::Bool)
2328        {
2329            ctx.errors.push(CompileError::new(
2330                "bynk.property.where_not_bool",
2331                w.span,
2332                format!(
2333                    "a `for all ... where` filter has type `{}`, but a `Bool` is required",
2334                    actual.display(tys)
2335                ),
2336            ));
2337        }
2338    }
2339    let result = type_of_block(body, Some(return_ty), &mut ctx);
2340    // Finding #28 (debug-only), extended: see the identical note in
2341    // `check_handler_body` — `check_body`'s test-case/property callers bypass
2342    // `check_record`'s walk the same way handler bodies do.
2343    #[cfg(debug_assertions)]
2344    {
2345        let mut seen: HashSet<ExprId> = HashSet::new();
2346        assert_expr_types_disjoint_in_block(body, ctx.expr_types, &mut seen);
2347    }
2348    result
2349}
2350
2351/// Check an agent's invariant declarations (v0.80 §14). Each predicate is a pure
2352/// `Bool`-typed expression over the agent's state fields (referenced by bare
2353/// name), plus `implies`/`is`. The pass enforces:
2354///
2355/// - `bynk.invariant.duplicate_name` — two invariants share a name.
2356/// - `bynk.invariant.cross_agent_reference` — a predicate names another agent
2357///   (§14 closes that door; sagas/scenarios are the cross-agent tools).
2358/// - `bynk.invariant.impure_predicate` — a predicate uses an effectful or
2359///   test-only construct (Effect, `?` propagation, `expect`, `Val`).
2360/// - `bynk.invariant.not_bool` — the predicate does not type to `Bool`.
2361///
2362/// Store `Cell` fields are placed in scope as the predicate's locals; invariants
2363/// read fields directly by bare name, mirroring the design-notes worked examples.
2364#[allow(clippy::too_many_arguments)]
2365pub fn check_invariants(
2366    invariants: &[Invariant],
2367    // A `store`-bearing agent's invariants reference its `Cell` fields by bare
2368    // name (a pure read of the staged value), so they form the predicate scope.
2369    store_cells: &HashMap<String, TyId>,
2370    agent_name: &str,
2371    input: &ResolvedCommons,
2372    tys: &Types,
2373    expr_types: &mut HashMap<ExprId, TypedExpr>,
2374    errors: &mut Vec<CompileError>,
2375    refs: &mut RefSink,
2376    hints: &mut HintSink,
2377    locals: &mut LocalsSink,
2378    requirements: &mut RequirementSink,
2379    callees: &mut HashMap<ExprId, Callee>,
2380) {
2381    // Duplicate-name check across the agent's invariants.
2382    let mut seen: HashMap<&str, ()> = HashMap::new();
2383    for inv in invariants {
2384        if seen.insert(inv.name.name.as_str(), ()).is_some() {
2385            errors.push(
2386                CompileError::new(
2387                    "bynk.invariant.duplicate_name",
2388                    inv.name.span,
2389                    format!(
2390                        "agent `{agent_name}` declares more than one invariant named `{}`",
2391                        inv.name.name
2392                    ),
2393                )
2394                .with_note("give each invariant a distinct name"),
2395            );
2396        }
2397    }
2398
2399    // Build the predicate scope once: each `store` `Cell` is in scope by bare
2400    // name (a `Cell` reads as its element type).
2401    let mut field_scope: HashMap<String, TyId> = HashMap::new();
2402    for (name, ty) in store_cells {
2403        field_scope.insert(name.clone(), *ty);
2404    }
2405
2406    for inv in invariants {
2407        // Reject cross-agent references and impure/effectful constructs before
2408        // type-checking, so the bespoke diagnostics win over any cascade.
2409        if let Some(span) = predicate_cross_agent_ref(&inv.predicate, input) {
2410            errors.push(
2411                CompileError::new(
2412                    "bynk.invariant.cross_agent_reference",
2413                    span,
2414                    format!(
2415                        "invariant `{}` references another agent; invariants constrain a \
2416                         single agent's reachable states",
2417                        inv.name.name
2418                    ),
2419                )
2420                .with_note(
2421                    "a property that genuinely spans agents belongs in a saga or a scenario, \
2422                     not an invariant — see §14",
2423                ),
2424            );
2425            continue;
2426        }
2427        if let Some(span) = predicate_impure_construct(&inv.predicate) {
2428            errors.push(
2429                CompileError::new(
2430                    "bynk.invariant.impure_predicate",
2431                    span,
2432                    format!(
2433                        "invariant `{}` uses an effectful or test-only construct; invariant \
2434                         predicates must be pure",
2435                        inv.name.name
2436                    ),
2437                )
2438                .with_note(
2439                    "an invariant predicate may read state fields and call pure value methods, \
2440                     but not perform effects",
2441                ),
2442            );
2443            continue;
2444        }
2445
2446        let bool_ty = tys.intern(Ty::Base(BaseType::Bool));
2447        let mut ctx = Ctx {
2448            input,
2449            tys,
2450            expr_types,
2451            errors,
2452            refs,
2453            hints,
2454            locals,
2455            requirements,
2456            callees,
2457            scopes: vec![field_scope.clone()],
2458            list_lens: HashMap::new(),
2459            row_links: HashMap::new(),
2460            is_binding_cache: HashMap::new(),
2461            admitted_literals: HashMap::new(),
2462            pattern_binding_types: HashMap::new(),
2463            let_else_removals: HashMap::new(),
2464            store_writing_lambdas: HashMap::new(),
2465            question_let_binders: HashMap::new(),
2466            return_ty: bool_ty,
2467            return_ty_span: inv.predicate.span,
2468            // A predicate is a pure expression — effectful operations (capability
2469            // calls, `<-`) are not permitted and are rejected as type errors.
2470            effectful: false,
2471            agent_state_ty: None,
2472            commit_seen: false,
2473            caps: CapabilityCtx {
2474                capabilities: HashMap::new(),
2475                declared_capabilities: HashMap::new(),
2476                given_remaining: HashSet::new(),
2477                given_used: HashSet::new(),
2478                given_entries: Vec::new(),
2479                given_anchor: None,
2480                ..Default::default()
2481            },
2482            in_test_body: false,
2483            oidc_binder: None,
2484            test_services: HashMap::new(),
2485            test_actors: HashMap::new(),
2486            type_vars: HashSet::new(),
2487            eq: EqScope::default(),
2488            last_witness: None,
2489            store_fields: HashMap::new(),
2490            in_agent_handler: false,
2491            in_service_handler: false,
2492            in_fn_body: false,
2493            test_values: false,
2494        };
2495        let pred_ty = type_of(&inv.predicate, Some(bool_ty), &mut ctx);
2496        if let Some(t) = pred_ty
2497            && t.base(tys) != Some(BaseType::Bool)
2498        {
2499            ctx.errors.push(
2500                CompileError::new(
2501                    "bynk.invariant.not_bool",
2502                    inv.predicate.span,
2503                    format!(
2504                        "invariant `{}` predicate has type `{}`, but an invariant must be `Bool`",
2505                        inv.name.name,
2506                        t.display(tys)
2507                    ),
2508                )
2509                .with_note("an invariant predicate is a `Bool`-valued property of the state"),
2510            );
2511        }
2512    }
2513}
2514
2515/// Check a function's contract clauses (v0.115 §, testing track slice 3). A
2516/// contract is the invariant predicate attached to a function (ADR 0144 — one
2517/// predicate surface): each `requires`/`ensures` is a pure `Bool`-typed
2518/// expression, `requires` over the parameters and `ensures` over the parameters
2519/// plus `result` (the return value; the awaited element for an `Effect`). The
2520/// pass enforces, mirroring [`check_invariants`]:
2521///
2522/// - `bynk.contract.duplicate_name` — two clauses (across `requires`/`ensures`)
2523///   share a name; the name rides the failure report and dedup.
2524/// - `bynk.contract.result_in_requires` — a precondition references `result`
2525///   (the return value is not yet bound on entry).
2526/// - `bynk.contract.impure_predicate` — a clause uses an effectful or test-only
2527///   construct (Effect, `?` propagation, `expect`, `Val`).
2528/// - `bynk.contract.not_bool` — a clause does not type to `Bool`.
2529///
2530/// Distinct from ADR 0127's capability `@requires` annotation.
2531#[allow(clippy::too_many_arguments)]
2532pub(crate) fn check_contracts(
2533    requires: &[Contract],
2534    ensures: &[Contract],
2535    // The function's parameters in scope by bare name (plus `self` for a
2536    // method), the shared predicate scope for both clause kinds.
2537    param_scope: &HashMap<String, TyId>,
2538    // The declared return type, awaited for an `Effect` — the type of `result`
2539    // inside an `ensures` predicate.
2540    result_ty: TyId,
2541    // True when a parameter is literally named `result`; then `result` in a
2542    // `requires` is that parameter, not the (unbound) return value.
2543    has_result_param: bool,
2544    fn_label: &str,
2545    input: &ResolvedCommons,
2546    expr_types: &mut HashMap<ExprId, TypedExpr>,
2547    errors: &mut Vec<CompileError>,
2548    refs: &mut RefSink,
2549    hints: &mut HintSink,
2550    locals: &mut LocalsSink,
2551    requirements: &mut RequirementSink,
2552    callees: &mut HashMap<ExprId, Callee>,
2553    type_vars: &HashSet<String>,
2554    eq: &EqScope,
2555    tys: &Types,
2556) {
2557    // Duplicate-name check across *all* clauses — the name is the dedup key for
2558    // the failure report and the redundant-test flag, so it is unique per fn.
2559    let mut seen: HashMap<&str, ()> = HashMap::new();
2560    for c in requires.iter().chain(ensures.iter()) {
2561        if seen.insert(c.name.name.as_str(), ()).is_some() {
2562            errors.push(
2563                CompileError::new(
2564                    "bynk.contract.duplicate_name",
2565                    c.name.span,
2566                    format!(
2567                        "{fn_label} declares more than one contract clause named `{}`",
2568                        c.name.name
2569                    ),
2570                )
2571                .with_note("give each `requires`/`ensures` clause a distinct name"),
2572            );
2573        }
2574    }
2575
2576    // Type-check one clause predicate in the given scope, emitting the shared
2577    // impurity / non-`Bool` diagnostics.
2578    let check_clause = |c: &Contract,
2579                        scope: HashMap<String, TyId>,
2580                        expr_types: &mut HashMap<ExprId, TypedExpr>,
2581                        errors: &mut Vec<CompileError>,
2582                        refs: &mut RefSink,
2583                        hints: &mut HintSink,
2584                        locals: &mut LocalsSink,
2585                        requirements: &mut RequirementSink,
2586                        callees: &mut HashMap<ExprId, Callee>| {
2587        if let Some(span) = predicate_impure_construct(&c.predicate) {
2588            errors.push(
2589                CompileError::new(
2590                    "bynk.contract.impure_predicate",
2591                    span,
2592                    format!(
2593                        "contract clause `{}` uses an effectful or test-only construct; a \
2594                             contract predicate must be pure",
2595                        c.name.name
2596                    ),
2597                )
2598                .with_note(
2599                    "a contract predicate may read the parameters (and `result`) and call \
2600                         pure value methods, but not perform effects",
2601                ),
2602            );
2603            return;
2604        }
2605        let bool_ty = tys.intern(Ty::Base(BaseType::Bool));
2606        let mut ctx = Ctx {
2607            input,
2608            tys,
2609            expr_types,
2610            errors,
2611            refs,
2612            hints,
2613            locals,
2614            requirements,
2615            callees,
2616            scopes: vec![scope],
2617            list_lens: HashMap::new(),
2618            row_links: HashMap::new(),
2619            is_binding_cache: HashMap::new(),
2620            admitted_literals: HashMap::new(),
2621            pattern_binding_types: HashMap::new(),
2622            let_else_removals: HashMap::new(),
2623            store_writing_lambdas: HashMap::new(),
2624            question_let_binders: HashMap::new(),
2625            return_ty: bool_ty,
2626            return_ty_span: c.predicate.span,
2627            effectful: false,
2628            agent_state_ty: None,
2629            commit_seen: false,
2630            caps: CapabilityCtx {
2631                capabilities: HashMap::new(),
2632                declared_capabilities: HashMap::new(),
2633                given_remaining: HashSet::new(),
2634                given_used: HashSet::new(),
2635                given_entries: Vec::new(),
2636                given_anchor: None,
2637                ..Default::default()
2638            },
2639            in_test_body: false,
2640            oidc_binder: None,
2641            test_services: HashMap::new(),
2642            test_actors: HashMap::new(),
2643            type_vars: type_vars.clone(),
2644            eq: eq.clone(),
2645            last_witness: None,
2646            store_fields: HashMap::new(),
2647            in_agent_handler: false,
2648            in_service_handler: false,
2649            in_fn_body: false,
2650            test_values: false,
2651        };
2652        let pred_ty = type_of(&c.predicate, Some(bool_ty), &mut ctx);
2653        if let Some(t) = pred_ty
2654            && t.base(tys) != Some(BaseType::Bool)
2655        {
2656            ctx.errors.push(
2657                CompileError::new(
2658                    "bynk.contract.not_bool",
2659                    c.predicate.span,
2660                    format!(
2661                        "contract clause `{}` predicate has type `{}`, but a contract clause \
2662                             must be `Bool`",
2663                        c.name.name,
2664                        t.display(tys)
2665                    ),
2666                )
2667                .with_note("a contract predicate is a `Bool`-valued claim over the arguments"),
2668            );
2669        }
2670    };
2671
2672    for c in requires {
2673        // `result` is the *return value* — not in scope on entry. A `requires`
2674        // that names it is a scope error with a bespoke diagnostic (unless a
2675        // parameter is literally named `result`, in which case it is that param).
2676        if !has_result_param && let Some(span) = predicate_references_result(&c.predicate) {
2677            errors.push(
2678                CompileError::new(
2679                    "bynk.contract.result_in_requires",
2680                    span,
2681                    format!(
2682                        "precondition `{}` references `result`, but the return value is not bound \
2683                         until the function returns",
2684                        c.name.name
2685                    ),
2686                )
2687                .with_note("`result` is only in scope inside an `ensures` clause"),
2688            );
2689            continue;
2690        }
2691        check_clause(
2692            c,
2693            param_scope.clone(),
2694            expr_types,
2695            errors,
2696            refs,
2697            hints,
2698            locals,
2699            requirements,
2700            callees,
2701        );
2702    }
2703
2704    for c in ensures {
2705        // `ensures` scope = parameters + `result` (the return value; awaited for
2706        // an `Effect`). A parameter named `result` is shadowed by the binding.
2707        let mut scope = param_scope.clone();
2708        scope.insert("result".to_string(), result_ty);
2709        check_clause(
2710            c,
2711            scope,
2712            expr_types,
2713            errors,
2714            refs,
2715            hints,
2716            locals,
2717            requirements,
2718            callees,
2719        );
2720    }
2721}
2722
2723/// Check an agent's step invariants (v0.116 §, testing track slice 4). A
2724/// `transition` is the invariant predicate widened to the *step* (ADR 0144 — one
2725/// predicate surface): a pure `Bool` predicate over the `old`/`new` state pair,
2726/// each bound to the agent's synthetic state record (`state_ty`), so `old.status`
2727/// / `new.status` resolve like any record field. The pass enforces, mirroring
2728/// [`check_invariants`]:
2729///
2730/// - `bynk.transition.duplicate_name` — two transitions share a name (the name
2731///   rides the `InvariantViolation` failure report).
2732/// - `bynk.transition.impure_predicate` — a predicate uses an effectful or
2733///   test-only construct.
2734/// - `bynk.transition.no_step_reference` — a predicate references neither `old`
2735///   nor `new`; it is a snapshot claim misfiled as a step (use `invariant`).
2736/// - `bynk.transition.not_bool` — a predicate does not type to `Bool`.
2737///
2738/// Placement is enforced structurally by the grammar (a `transition` is an
2739/// agent-body-only declaration), so there is no "transition on a non-agent"
2740/// diagnostic to raise here.
2741#[allow(clippy::too_many_arguments)]
2742pub fn check_transitions(
2743    transitions: &[Transition],
2744    // The agent's synthetic state record type — both `old` and `new` are bound to
2745    // it, so `old.field` / `new.field` read as the field's element type.
2746    state_ty: TyId,
2747    agent_name: &str,
2748    // Resolved commons carrying the synthetic `<Agent>State` record so field
2749    // access on `old`/`new` resolves.
2750    input: &ResolvedCommons,
2751    expr_types: &mut HashMap<ExprId, TypedExpr>,
2752    errors: &mut Vec<CompileError>,
2753    refs: &mut RefSink,
2754    hints: &mut HintSink,
2755    locals: &mut LocalsSink,
2756    requirements: &mut RequirementSink,
2757    callees: &mut HashMap<ExprId, Callee>,
2758    tys: &Types,
2759) {
2760    // Duplicate-name check across the agent's transitions.
2761    let mut seen: HashMap<&str, ()> = HashMap::new();
2762    for tr in transitions {
2763        if seen.insert(tr.name.name.as_str(), ()).is_some() {
2764            errors.push(
2765                CompileError::new(
2766                    "bynk.transition.duplicate_name",
2767                    tr.name.span,
2768                    format!(
2769                        "agent `{agent_name}` declares more than one transition named `{}`",
2770                        tr.name.name
2771                    ),
2772                )
2773                .with_note("give each transition a distinct name"),
2774            );
2775        }
2776    }
2777
2778    // Both `old` and `new` are in scope as the state record.
2779    let mut scope: HashMap<String, TyId> = HashMap::new();
2780    scope.insert("old".to_string(), state_ty);
2781    scope.insert("new".to_string(), state_ty);
2782
2783    for tr in transitions {
2784        // Reject cross-agent references and impure constructs before type-checking,
2785        // so the bespoke diagnostics win over any cascade.
2786        if let Some(span) = predicate_cross_agent_ref(&tr.predicate, input) {
2787            errors.push(
2788                CompileError::new(
2789                    "bynk.transition.cross_agent_reference",
2790                    span,
2791                    format!(
2792                        "transition `{}` references another agent; a step invariant \
2793                         constrains a single agent's own state move",
2794                        tr.name.name
2795                    ),
2796                )
2797                .with_note(
2798                    "a property that genuinely spans agents belongs in a saga or a scenario, \
2799                     not a transition",
2800                ),
2801            );
2802            continue;
2803        }
2804        if let Some(span) = predicate_impure_construct(&tr.predicate) {
2805            errors.push(
2806                CompileError::new(
2807                    "bynk.transition.impure_predicate",
2808                    span,
2809                    format!(
2810                        "transition `{}` uses an effectful or test-only construct; a step \
2811                         invariant predicate must be pure",
2812                        tr.name.name
2813                    ),
2814                )
2815                .with_note(
2816                    "a transition predicate may read the `old`/`new` state and call pure value \
2817                     methods, but not perform effects",
2818                ),
2819            );
2820            continue;
2821        }
2822        // A transition that mentions neither `old` nor `new` is not a step claim —
2823        // it is a snapshot invariant misfiled. Flag it conservatively.
2824        if predicate_references_old_or_new(&tr.predicate).is_none() {
2825            errors.push(
2826                CompileError::new(
2827                    "bynk.transition.no_step_reference",
2828                    tr.predicate.span,
2829                    format!(
2830                        "transition `{}` references neither `old` nor `new`, so it constrains a \
2831                         single state, not a step",
2832                        tr.name.name
2833                    ),
2834                )
2835                .with_note(
2836                    "a claim about one committed state is an `invariant`, not a `transition`",
2837                ),
2838            );
2839            continue;
2840        }
2841
2842        let bool_ty = tys.intern(Ty::Base(BaseType::Bool));
2843        let mut ctx = Ctx {
2844            input,
2845            tys,
2846            expr_types,
2847            errors,
2848            refs,
2849            hints,
2850            locals,
2851            requirements,
2852            callees,
2853            scopes: vec![scope.clone()],
2854            list_lens: HashMap::new(),
2855            row_links: HashMap::new(),
2856            is_binding_cache: HashMap::new(),
2857            admitted_literals: HashMap::new(),
2858            pattern_binding_types: HashMap::new(),
2859            let_else_removals: HashMap::new(),
2860            store_writing_lambdas: HashMap::new(),
2861            question_let_binders: HashMap::new(),
2862            return_ty: bool_ty,
2863            return_ty_span: tr.predicate.span,
2864            effectful: false,
2865            agent_state_ty: None,
2866            commit_seen: false,
2867            caps: CapabilityCtx {
2868                capabilities: HashMap::new(),
2869                declared_capabilities: HashMap::new(),
2870                given_remaining: HashSet::new(),
2871                given_used: HashSet::new(),
2872                given_entries: Vec::new(),
2873                given_anchor: None,
2874                ..Default::default()
2875            },
2876            in_test_body: false,
2877            oidc_binder: None,
2878            test_services: HashMap::new(),
2879            test_actors: HashMap::new(),
2880            type_vars: HashSet::new(),
2881            eq: EqScope::default(),
2882            last_witness: None,
2883            store_fields: HashMap::new(),
2884            in_agent_handler: false,
2885            in_service_handler: false,
2886            in_fn_body: false,
2887            test_values: false,
2888        };
2889        let pred_ty = type_of(&tr.predicate, Some(bool_ty), &mut ctx);
2890        if let Some(t) = pred_ty
2891            && t.base(tys) != Some(BaseType::Bool)
2892        {
2893            ctx.errors.push(
2894                CompileError::new(
2895                    "bynk.transition.not_bool",
2896                    tr.predicate.span,
2897                    format!(
2898                        "transition `{}` predicate has type `{}`, but a transition must be `Bool`",
2899                        tr.name.name,
2900                        t.display(tys)
2901                    ),
2902                )
2903                .with_note("a transition predicate is a `Bool`-valued property of the state move"),
2904            );
2905        }
2906    }
2907}
2908
2909/// If the predicate references `old` or `new` (a bare identifier) anywhere,
2910/// return the span of the first such reference. Used to flag a `transition` that
2911/// makes no step claim.
2912fn predicate_references_old_or_new(e: &Expr) -> Option<Span> {
2913    match &e.kind {
2914        ExprKind::Ident(id) if id.name == "old" || id.name == "new" => Some(id.span),
2915        _ => bynk_syntax::ast::expr_children(e)
2916            .into_iter()
2917            .find_map(predicate_references_old_or_new),
2918    }
2919}
2920
2921/// If the predicate references `result` (a bare identifier) anywhere, return the
2922/// span of the first such reference. Used to reject `result` in a `requires`.
2923fn predicate_references_result(e: &Expr) -> Option<Span> {
2924    match &e.kind {
2925        ExprKind::Ident(id) if id.name == "result" => Some(id.span),
2926        _ => bynk_syntax::ast::expr_children(e)
2927            .into_iter()
2928            .find_map(predicate_references_result),
2929    }
2930}
2931
2932/// If the predicate references another agent (by bare name, call, or qualified
2933/// constructor), return the span of the first such reference. Used by the
2934/// invariant well-formedness pass to forbid cross-agent predicates.
2935fn predicate_cross_agent_ref(e: &Expr, input: &ResolvedCommons) -> Option<Span> {
2936    let is_agent = |name: &str| input.agents.contains_key(name);
2937    match &e.kind {
2938        ExprKind::Ident(id) if is_agent(&id.name) => Some(id.span),
2939        ExprKind::Call { name, .. } if is_agent(&name.name) => Some(name.span),
2940        ExprKind::RecordConstruction { type_name, .. } if is_agent(&type_name.name) => {
2941            Some(type_name.span)
2942        }
2943        _ => bynk_syntax::ast::expr_children(e)
2944            .into_iter()
2945            .find_map(|c| predicate_cross_agent_ref(c, input)),
2946    }
2947}
2948
2949/// State-migrations S2 (#2224, track §3.3): check each `migrate` step's body
2950/// on its own terms, with no lock: the old parameter names a record type, the
2951/// body is pure and key-free, each `:=` targets a `Cell` or `Map` field with a
2952/// value of that field's type, and no field is assigned twice (record-literal
2953/// semantics). What the lock alone can check (the old shape against the
2954/// recorded version, and which changes the step covers) is
2955/// `schema_registry::reconcile_agents`'s.
2956///
2957/// A bare current field reads its *carried* value, so the scope is the agent's
2958/// `Cell` fields (as for invariants) plus `old` and each `let` in order.
2959#[allow(clippy::too_many_arguments)]
2960pub fn check_migrations(
2961    agent: &AgentDecl,
2962    store_cells: &HashMap<String, TyId>,
2963    types: &HashMap<String, Arc<TypeDecl>>,
2964    input: &ResolvedCommons,
2965    tys: &Types,
2966    expr_types: &mut HashMap<ExprId, TypedExpr>,
2967    errors: &mut Vec<CompileError>,
2968    refs: &mut RefSink,
2969    hints: &mut HintSink,
2970    locals: &mut LocalsSink,
2971    requirements: &mut RequirementSink,
2972    callees: &mut HashMap<ExprId, Callee>,
2973) {
2974    let key = agent.key_name.name.as_str();
2975    let mut seen_from: HashMap<i64, ()> = HashMap::new();
2976    for step in &agent.migrations {
2977        if seen_from.insert(step.from, ()).is_some() {
2978            errors.push(
2979                CompileError::new(
2980                    "bynk.agent.migrate_duplicate",
2981                    step.from_span,
2982                    format!(
2983                        "agent `{}` declares more than one `migrate from {}` step",
2984                        agent.name.name, step.from
2985                    ),
2986                )
2987                .with_note("merge them into one step: a stored version runs exactly one step"),
2988            );
2989        }
2990        let mut scope: HashMap<String, TyId> = store_cells.clone();
2991        if let Some(old) = &step.old {
2992            let is_record = match &old.type_ref {
2993                TypeRef::Named(id) => types
2994                    .get(&id.name)
2995                    .is_some_and(|d| matches!(d.body, TypeBody::Record(_))),
2996                _ => false,
2997            };
2998            if !is_record {
2999                errors.push(
3000                    CompileError::new(
3001                        "bynk.agent.migrate_shape_mismatch",
3002                        old.name.span.merge(old.type_ref.span()),
3003                        format!(
3004                            "`migrate from {}`'s `{}` must name a record type declaring the \
3005                             version-{} fields the step reads",
3006                            step.from, old.name.name, step.from
3007                        ),
3008                    )
3009                    .with_note(
3010                        "declare the old shape as a type, e.g. `type CartV1 = { owner: String }`",
3011                    ),
3012                );
3013            } else if let Some(ty) = resolve_type_ref(&old.type_ref, types, tys) {
3014                record_type_refs(&old.type_ref, types, &HashSet::new(), refs);
3015                scope.insert(old.name.name.clone(), ty);
3016            }
3017        }
3018        // The value type a `:=` to each assignable field takes.
3019        let assignable: HashMap<&str, Option<TyId>> = agent
3020            .store_fields
3021            .iter()
3022            .filter_map(|f| {
3023                let value = match (f.kind.head.name.as_str(), f.kind.args.as_slice()) {
3024                    ("Cell", [t]) => resolve_type_ref(t, types, tys),
3025                    ("Map", [k, v]) => resolve_type_ref(
3026                        &TypeRef::Map(Box::new(k.clone()), Box::new(v.clone()), f.kind.span),
3027                        types,
3028                        tys,
3029                    ),
3030                    _ => return None,
3031                };
3032                Some((f.name.name.as_str(), value))
3033            })
3034            .collect();
3035        let mut assigned: HashMap<String, ()> = HashMap::new();
3036        let mut ctx = Ctx {
3037            input,
3038            tys,
3039            expr_types: &mut *expr_types,
3040            errors: &mut *errors,
3041            refs: &mut *refs,
3042            hints: &mut *hints,
3043            locals: &mut *locals,
3044            requirements: &mut *requirements,
3045            callees: &mut *callees,
3046            scopes: vec![scope],
3047            list_lens: HashMap::new(),
3048            row_links: HashMap::new(),
3049            is_binding_cache: HashMap::new(),
3050            admitted_literals: HashMap::new(),
3051            pattern_binding_types: HashMap::new(),
3052            let_else_removals: HashMap::new(),
3053            store_writing_lambdas: HashMap::new(),
3054            question_let_binders: HashMap::new(),
3055            return_ty: tys.intern(Ty::Unit),
3056            return_ty_span: step.span,
3057            // A step is pure: no capability calls, no `<-` (track §3.3).
3058            effectful: false,
3059            agent_state_ty: None,
3060            commit_seen: false,
3061            caps: CapabilityCtx {
3062                capabilities: HashMap::new(),
3063                declared_capabilities: HashMap::new(),
3064                given_remaining: HashSet::new(),
3065                given_used: HashSet::new(),
3066                given_entries: Vec::new(),
3067                given_anchor: None,
3068                ..Default::default()
3069            },
3070            in_test_body: false,
3071            oidc_binder: None,
3072            test_services: HashMap::new(),
3073            test_actors: HashMap::new(),
3074            type_vars: HashSet::new(),
3075            eq: EqScope::default(),
3076            last_witness: None,
3077            store_fields: HashMap::new(),
3078            in_agent_handler: false,
3079            in_service_handler: false,
3080            in_fn_body: false,
3081            test_values: false,
3082        };
3083        for item in &step.items {
3084            let value = match item {
3085                MigrateItem::Let(l) => Some(&l.value),
3086                MigrateItem::Assign(a) => Some(&a.value),
3087                MigrateItem::Drop(_) => None,
3088            };
3089            // A `let` rejected below still binds its name (to its annotation,
3090            // or the error type), so later items that use it report nothing
3091            // further (#2243 review).
3092            let bind_rejected_let = |ctx: &mut Ctx| {
3093                if let MigrateItem::Let(l) = item {
3094                    let ty = l
3095                        .type_annot
3096                        .as_ref()
3097                        .and_then(|t| resolve_type_ref(t, types, tys))
3098                        .unwrap_or_else(|| tys.intern(Ty::Error));
3099                    if let Some(top) = ctx.scopes.last_mut() {
3100                        top.insert(l.name.name.clone(), ty);
3101                    }
3102                }
3103            };
3104            if let Some(v) = value {
3105                if let Some(span) = predicate_impure_construct(v) {
3106                    ctx.errors.push(
3107                        CompileError::new(
3108                            "bynk.agent.migrate_impure",
3109                            span,
3110                            format!(
3111                                "`migrate from {}` uses an effectful or test-only construct; a \
3112                                 migration step must be pure",
3113                                step.from
3114                            ),
3115                        )
3116                        .with_note("a step may read `old` and the carried fields and call pure value methods"),
3117                    );
3118                    bind_rejected_let(&mut ctx);
3119                    continue;
3120                }
3121                if expr_reads_ident(v, key) && !ctx.scopes.iter().any(|s| s.contains_key(key)) {
3122                    ctx.errors.push(
3123                        CompileError::new(
3124                            "bynk.agent.migrate_impure",
3125                            v.span,
3126                            format!(
3127                                "`migrate from {}` reads the agent's key `{key}`; a migration \
3128                                 step is key-free",
3129                                step.from
3130                            ),
3131                        )
3132                        .with_note(
3133                            "a migration sweep wakes an instance by its object ID, which does not \
3134                             recover the key (track §3.6)",
3135                        ),
3136                    );
3137                    bind_rejected_let(&mut ctx);
3138                    continue;
3139                }
3140            }
3141            match item {
3142                MigrateItem::Let(l) => {
3143                    let annot = l
3144                        .type_annot
3145                        .as_ref()
3146                        .and_then(|t| resolve_type_ref(t, types, tys));
3147                    let ty = type_of(&l.value, annot, &mut ctx);
3148                    if let Some(ty) = annot.or(ty)
3149                        && let Some(top) = ctx.scopes.last_mut()
3150                    {
3151                        top.insert(l.name.name.clone(), ty);
3152                    }
3153                }
3154                MigrateItem::Assign(a) => {
3155                    let target = a.target.name.as_str();
3156                    if assigned.insert(target.to_string(), ()).is_some() {
3157                        ctx.errors.push(
3158                            CompileError::new(
3159                                "bynk.agent.migrate_duplicate_assignment",
3160                                a.target.span,
3161                                format!(
3162                                    "`migrate from {}` assigns `{target}` more than once",
3163                                    step.from
3164                                ),
3165                            )
3166                            .with_note(
3167                                "a step gives each field at most one value; a bare field reads \
3168                                 its carried value, never an earlier assignment",
3169                            ),
3170                        );
3171                    }
3172                    match assignable.get(target) {
3173                        Some(expected) => {
3174                            let _ = type_of(&a.value, *expected, &mut ctx);
3175                        }
3176                        None => {
3177                            let why = if agent.store_fields.iter().any(|f| f.name.name == target) {
3178                                "a `Set`, `Log` or `Cache` field has no value type to assign; \
3179                                 `drop` it to start it afresh"
3180                            } else {
3181                                "it is not one of the agent's `store` fields"
3182                            };
3183                            ctx.errors.push(CompileError::new(
3184                                "bynk.cell.invalid_target",
3185                                a.target.span,
3186                                format!(
3187                                    "`migrate from {}` cannot assign `{target}`: {why}",
3188                                    step.from
3189                                ),
3190                            ));
3191                        }
3192                    }
3193                }
3194                MigrateItem::Drop(_) => {}
3195            }
3196        }
3197    }
3198}
3199
3200/// If the predicate contains an effectful or test-only construct, return its
3201/// span. Capability misuse (an effect operation in a pure context) is left to
3202/// the type checker; this catches the syntactically-impure surface.
3203pub(crate) fn predicate_impure_construct(e: &Expr) -> Option<Span> {
3204    match &e.kind {
3205        ExprKind::EffectPure(_)
3206        | ExprKind::Question(_)
3207        | ExprKind::Expect(_)
3208        | ExprKind::Val { .. }
3209        | ExprKind::Observation(_)
3210        | ExprKind::Faults(_)
3211        | ExprKind::Trace { .. } => Some(e.span),
3212        _ => bynk_syntax::ast::expr_children(e)
3213            .into_iter()
3214            .find_map(predicate_impure_construct),
3215    }
3216}
3217
3218/// #3774 (ADR 0144 D3): the first sub-expression of a test predicate (an
3219/// `expect`, or an observation's `with`) whose checked type is `Effect[_]`.
3220///
3221/// Typing already refuses an `Effect` where a value is compared, matched or
3222/// unwrapped, but not one held inside a pure expression
3223/// (`[Logger.log("x")].length() == 1`). A capability call lowers to an eager
3224/// call on the case's recording `deps`, so such a predicate would run the
3225/// effect and corrupt the observation counts (#3768). Run after the predicate
3226/// is typed: the rule reads `expr_types`, not call shapes.
3227///
3228/// `expect`'s own constructs are not walked: a `faults` claim awaits its call
3229/// by design (#1706), an observation's subject is named rather than called, and
3230/// `trace(Cap.op)` reads the recording. An observation's `with` predicate is
3231/// checked where the observation is, under its own code.
3232pub(crate) fn effect_in_predicate(
3233    e: &Expr,
3234    expr_types: &HashMap<ExprId, TypedExpr>,
3235    tys: &Types,
3236) -> Option<Span> {
3237    match &e.kind {
3238        ExprKind::Faults(_) | ExprKind::Observation(_) | ExprKind::Trace { .. } => None,
3239        _ if expr_types.get(&e.id).is_some_and(|t| t.ty.is_effect(tys)) => Some(e.span),
3240        _ => bynk_syntax::ast::expr_children(e)
3241            .into_iter()
3242            .find_map(|c| effect_in_predicate(c, expr_types, tys)),
3243    }
3244}
3245
3246/// Whether a test predicate typed to `Bool` with no new error since
3247/// `errors_before`: the purity walk runs only then, so a predicate typing has
3248/// already refused (`bynk.expect.not_bool`, `bynk.types.not_comparable`) is not
3249/// reported a second time at the same span.
3250pub(crate) fn predicate_typed_clean(ty: Option<TyId>, errors_before: usize, ctx: &Ctx) -> bool {
3251    ctx.errors.len() == errors_before
3252        && ty.is_some_and(|t| compatible(t, ctx.tys.intern(Ty::Base(BaseType::Bool)), ctx.tys))
3253}
3254
3255/// `bynk.expect.impure_predicate` at the effectful sub-expression `span`.
3256pub(crate) fn expect_impure_error(span: Span) -> CompileError {
3257    CompileError::new(
3258        "bynk.expect.impure_predicate",
3259        span,
3260        "an `expect` predicate performs an effect; a predicate must be pure",
3261    )
3262    .with_note("run the call before the `expect` with `let x <- …`, then state the claim about `x`")
3263}
3264
3265/// Whether `e` reads the identifier `name` anywhere — used by the `:=`
3266/// read-modify-write rule (a cell write whose RHS reads its own LHS).
3267pub(crate) fn expr_reads_ident(e: &Expr, name: &str) -> bool {
3268    match &e.kind {
3269        ExprKind::Ident(id) => id.name == name,
3270        _ => bynk_syntax::ast::expr_children(e)
3271            .into_iter()
3272            .any(|c| expr_reads_ident(c, name)),
3273    }
3274}
3275
3276// ==== Checking context and capability metadata ====
3277
3278/// v0.9.4: a compile-time-constant literal usable for static refinement
3279/// discharge during `T.of(...)` construction.
3280enum ConstLit {
3281    Int(i64),
3282    Float(f64),
3283    /// #2622: a decimal literal's coefficient (with any `-`) and scale.
3284    Decimal(String, u32),
3285    Str(String),
3286    Bool(bool),
3287    Unit,
3288}
3289
3290impl ConstLit {
3291    fn display(&self) -> String {
3292        match self {
3293            ConstLit::Int(n) => n.to_string(),
3294            ConstLit::Float(v) => v.to_string(),
3295            ConstLit::Decimal(coef, scale) => bynk_syntax::decimal::render(coef, *scale),
3296            ConstLit::Str(s) => format!("{s:?}"),
3297            ConstLit::Bool(b) => b.to_string(),
3298            ConstLit::Unit => "()".to_string(),
3299        }
3300    }
3301}
3302
3303/// Mutable per-function context.
3304/// Capability bookkeeping for the checker — the `given`-clause lifecycle and
3305/// capability dispatch, grouped out of the checker's working context
3306/// (v0.29.10). Empty (`Default`) for pure functions / non-context code.
3307#[derive(Default)]
3308pub struct CapabilityCtx {
3309    /// Capabilities in scope for the current handler, as a name → CapabilityInfo
3310    /// map. Empty for pure functions and non-context code.
3311    pub capabilities: HashMap<String, CapabilityInfo>,
3312    /// All capabilities declared in the surrounding context (for diagnostic
3313    /// purposes — used to detect `<Cap>.op(...)` calls where the capability is
3314    /// declared in the context but not listed in `given`).
3315    pub declared_capabilities: HashMap<String, CapabilityInfo>,
3316    /// Names of capabilities the user listed in `given`, but haven't yet
3317    /// observed used. After checking the body, anything left here is
3318    /// unused — a warning.
3319    pub given_remaining: HashSet<String>,
3320    /// Names of capabilities actually used in the body so far.
3321    pub given_used: HashSet<String>,
3322    /// v0.26 (ADR 0054): the `given` clause's entries in declaration order —
3323    /// (deps key, source span) — so the `given` quick-fixes can author
3324    /// list-aware edits at the diagnosis site. Empty where no `given` clause
3325    /// applies (fns, mock ops, state initialisers).
3326    pub given_entries: Vec<(String, Span)>,
3327    /// v0.26: where the add-capability fix synthesises an *absent* `given`
3328    /// clause — the handler's return type (the clause follows it). `None`
3329    /// where the clause lives elsewhere (a provider's `provides … given`
3330    /// line); the fix is then offered only when entries already exist.
3331    pub given_anchor: Option<Span>,
3332    /// #3147: the participants' D1 capabilities a case may `D1.peek`. `Some`
3333    /// only while checking an `integration` or `system` case.
3334    pub peek_env: Option<Arc<peek::PeekEnv>>,
3335    /// #3147: the value of the `let` being checked, the one place a
3336    /// `D1.peek` may stand.
3337    pub peek_let_value: Option<ExprId>,
3338}
3339
3340/// v0.178 (Slice 0, #662) / v0.182 (Slice A, #664): the shape a test body needs
3341/// to resolve a service invocation. Built by the project test pass from the
3342/// target unit's service declarations, so the checker can resolve the addressed
3343/// handler (`svc.call(...)` on an `on call` service, or — Slice A —
3344/// `svc.GET("/x")` / `svc.schedule("…")` / `svc.message(m)` on a `from http` /
3345/// `cron` / `queue` service) and check its arity, argument types, and principal.
3346#[derive(Debug, Clone)]
3347pub struct TestServiceSig {
3348    /// The service's protocol as an author-facing word (`"http"`, `"cron"`,
3349    /// `"queue"`, `"websocket"`), or `None` for a plain `service X { on call }`.
3350    pub protocol: Option<String>,
3351    /// Every handler the service declares, so the branch can resolve any address
3352    /// form. Slice 0 only reads the `on call` entry.
3353    pub handlers: Vec<TestHandler>,
3354    /// #2052: for a `from Events(E)` service, every event the project
3355    /// declares, so `svc.event(f)` with some other event `f` is reported as an
3356    /// event the service does not subscribe to. Empty for any other protocol.
3357    pub known_events: std::collections::BTreeSet<String>,
3358    /// #2052 review: for a `from Events(E)` service, the context that
3359    /// publishes `E` to it ([`crate::test_suites::event_publisher`]), which a
3360    /// default envelope names; `Err` lists the candidates when there is no
3361    /// unique one. `None` for any other protocol.
3362    pub event_publisher: Option<Result<String, Vec<String>>>,
3363    /// #3051: for a `from websocket(in: I, out: O)` service, `(I, O)`, so the
3364    /// `open`/`message`/`close` addresses type a frame and the `TestConnection`.
3365    pub ws_frames: Option<(bynk_syntax::ast::TypeRef, bynk_syntax::ast::TypeRef)>,
3366}
3367
3368/// One service handler, as a test body sees it (v0.178 / v0.182).
3369#[derive(Debug, Clone)]
3370pub struct TestHandler {
3371    pub kind: bynk_syntax::ast::HandlerKind,
3372    pub params: Vec<bynk_syntax::ast::Param>,
3373    /// The handler's declared `by <Actor>` clause, if any — the actor a call-site
3374    /// principal is checked against. `None` inherits the protocol default actor.
3375    pub by_clause: Option<bynk_syntax::ast::ByClause>,
3376    /// #1979, #1934: the handler's declared return type — what a case's
3377    /// call to it yields.
3378    pub return_type: bynk_syntax::ast::TypeRef,
3379    pub span: Span,
3380}
3381
3382impl TestServiceSig {
3383    /// The `on call` handler, if the service declares one.
3384    pub fn call_handler(&self) -> Option<&TestHandler> {
3385        self.handlers
3386            .iter()
3387            .find(|h| matches!(h.kind, bynk_syntax::ast::HandlerKind::Call))
3388    }
3389}
3390
3391/// One agent `store` field's kind and shape (finding #36) — the checker's
3392/// dispatch keys off this instead of five separate per-kind maps, so a new
3393/// storage kind is one new variant rather than a sixth map threaded through
3394/// every constructor and lookup site.
3395#[derive(Debug, Clone, Copy)]
3396pub enum StoreField {
3397    /// `store <name>: Cell[T]` — element type.
3398    Cell(TyId),
3399    /// `store <name>: Map[K, V]` — key, value.
3400    Map(TyId, TyId),
3401    /// `store <name>: Set[T]` — element type.
3402    Set(TyId),
3403    /// `store <name>: Cache[K, V] @ttl(...)` — key, value, TTL in milliseconds.
3404    Cache(TyId, TyId, i64),
3405    /// `store <name>: Log[T]` — element type.
3406    Log(TyId),
3407}
3408
3409/// The checker's working context. `pub(crate)`: every caller outside this
3410/// crate goes through [`check_handler_body`] or [`check_body`] instead of
3411/// hand-building one — adding a field no longer needs auditing every
3412/// external construction site.
3413pub(crate) struct Ctx<'a> {
3414    pub input: &'a ResolvedCommons,
3415    /// T3.6b (R4.1): the unit's intern table. A shared `&` (the table is
3416    /// interior-mutable, see [`Types`]) so it stays `Copy` — a function that
3417    /// needs it reads `ctx.tys` once and is then free of the `ctx` borrow.
3418    /// Spelled `tys`, not `types`, because `input.types` next door is the
3419    /// unrelated `TypeDecl`-by-name declaration map.
3420    pub tys: &'a Types,
3421    pub expr_types: &'a mut HashMap<ExprId, TypedExpr>,
3422    pub errors: &'a mut Vec<CompileError>,
3423    /// v0.25 (ADR 0053): binding edges recorded at the checker's own
3424    /// resolution sites — capability/service dispatch, typed call dispatch,
3425    /// annotation resolution. Handler/test/provider bodies never pass
3426    /// through the resolver's reference walk, so the checker is their only
3427    /// recording point.
3428    pub refs: &'a mut RefSink,
3429    /// v0.27 (ADR 0056): inferred-type inlay hints recorded at the
3430    /// annotation-absent binding sites (`let` / `let <-` / lambda params)
3431    /// as the binding's final type is computed.
3432    pub hints: &'a mut HintSink,
3433    /// v0.31 (ADR 0064): local bindings recorded with their scope ranges at
3434    /// every binding site (`let`/`let <-`, params, match patterns), for the
3435    /// LSP's scope-at-offset query.
3436    pub locals: &'a mut LocalsSink,
3437    /// v0.99: the capability-requirement ledger — every capability-consuming
3438    /// site (direct call, store op), covered or not, recorded so the editor
3439    /// surfaces (the ghost `given` inlay hint, hover) can read it.
3440    pub requirements: &'a mut RequirementSink,
3441    /// P6.0 (#1139): the `Callee` classification sink — see [`Callee`].
3442    pub callees: &'a mut HashMap<ExprId, Callee>,
3443    /// Stack of in-scope name → type frames.
3444    pub scopes: Vec<HashMap<String, TyId>>,
3445    /// #3108: the fixed length of a `let` bound to a list literal, keyed by the
3446    /// scope frame's depth and the name, so a D1 call's `params` can be a name.
3447    /// [`bind`](Self::bind) and a new frame drop what they shadow or outlive.
3448    pub list_lens: HashMap<(usize, String), usize>,
3449    /// #3139: names that hold the rows of a literal D1 read (`let r <- Cap.all(…)`, or
3450    /// the payload a `match r { Ok(x) => … }` binds), keyed like `list_lens`, so a
3451    /// `Json.decodeSql[T](x)` can be checked against the statement's columns.
3452    pub row_links: HashMap<(usize, String), d1::RowLink>,
3453    /// Memoised `is`-pattern bindings, keyed by the condition sub-expression's
3454    /// span. `collect_is_bindings` runs at every `&&`/`implies` node and, for a
3455    /// left-nested `&&` chain, would otherwise re-walk each lhs subtree once per
3456    /// enclosing node — O(N²) for an N-term chain. Because the collector is a
3457    /// pure read over `expr_types` (already populated by the time it runs) and
3458    /// spans are unique per body, caching each node's result collapses the walk
3459    /// to a single pass.
3460    pub is_binding_cache: HashMap<(ExprId, bool), Vec<(String, TyId)>>,
3461    /// #2039: literals inside a cross-context argument already admitted to
3462    /// the refined type at their position in the callee's parameter type,
3463    /// against the callee's declaration. `type_of` takes a literal's type
3464    /// from here before trying admission in the caller's own scope.
3465    pub admitted_literals: HashMap<ExprId, TyId>,
3466    /// T3.4: a pattern-bound name's resolved type, keyed by the binding
3467    /// `Ident`'s own span. Deliberately **not** `ExprId`-keyed and not
3468    /// folded into `expr_types` — a `Pattern::Binding` is not an `Expr` and
3469    /// giving `Ident` an id of its own would touch every identifier
3470    /// construction site in the workspace (field names, type names, params,
3471    /// …), not just the handful that bind. This is exactly the `PatId`
3472    /// reference draws as a *separate* identity from `ExprId` (Part 2) —
3473    /// out of this slice's scope on purpose, not overlooked.
3474    pub pattern_binding_types: HashMap<Span, TyId>,
3475    /// #2654: for each hidden `let … else` binder seen so far (by name), the
3476    /// source ranges to delete to drop its `else` — what the
3477    /// "remove the `else`" fix of an `else` that can never run applies.
3478    pub let_else_removals: HashMap<String, Vec<Span>>,
3479    /// #3298: a `let`-bound lambda whose body writes a store (field, op), by name,
3480    /// so `xs.parTraverse(f)` is checked like the closure written in place.
3481    pub store_writing_lambdas: HashMap<String, (String, String)>,
3482    /// #2839: a plain `let name = <e>?` statement's `?` expression span →
3483    /// the binder's span and name, so the header-`?` lint can offer the
3484    /// `let … else` rewrite. Only `let`s with no annotation are recorded.
3485    pub question_let_binders: HashMap<Span, (Span, String)>,
3486    pub return_ty: TyId,
3487    pub return_ty_span: Span,
3488    /// True if the enclosing function/handler returns `Effect[T]` (v0.5).
3489    /// Determines whether `<-` and capability calls are permitted.
3490    pub effectful: bool,
3491    /// If inside an agent handler, the agent's state type and the agent's
3492    /// name. Used to validate `commit` statements.
3493    pub agent_state_ty: Option<TyId>,
3494    /// True if a `commit` has been seen on the current control-flow path.
3495    /// Used to detect "two reachable commits".
3496    pub commit_seen: bool,
3497    /// Capability bookkeeping — the `given`-clause lifecycle + dispatch,
3498    /// grouped (v0.29.10). Empty for pure functions / non-context code.
3499    pub caps: CapabilityCtx,
3500    /// True when the body being checked is a test case body. Permits
3501    /// `expect` statements (v0.7; renamed from `assert` in v0.112).
3502    pub in_test_body: bool,
3503    /// #2380 (L5): the binder of an `Oidc` actor (`by who: Workload`), whose
3504    /// `.claims` reads the verified token's claims. `None` elsewhere.
3505    pub oidc_binder: Option<String>,
3506    /// The target unit's services, populated for test case bodies (v0.25).
3507    /// `svc.call(args)` in a test invokes the target's service; the checker
3508    /// resolves the service's `on call` handler here to check the call's
3509    /// arity and argument types, and records the binding edge so test-file
3510    /// references index. A service with no `on call` handler (a `from http`
3511    /// / `cron` / `queue` service) carries `None` for `call_handler`, which
3512    /// makes `svc.call(...)` a diagnostic rather than a silent runtime crash.
3513    pub test_services: HashMap<String, TestServiceSig>,
3514    /// v0.182 (Slice A, #664): the target unit's actor declarations, so a
3515    /// call-site `by <Actor>(<identity>)` can resolve the actor and type the
3516    /// identity value against its declared identity type. Prelude actors
3517    /// (`Visitor`, `Caller`, …) are resolved separately. Empty outside test
3518    /// bodies.
3519    pub test_actors: HashMap<String, bynk_syntax::ast::ActorDecl>,
3520    /// v0.20a: the enclosing function's type parameters (rigid vars), so
3521    /// nested explicit type arguments (`identity[A](x)` inside a generic
3522    /// body) resolve. Empty outside generic fn bodies.
3523    pub type_vars: HashSet<String>,
3524    /// Constrained generics slice 0: the `Eq` bounds declared in scope.
3525    pub eq: EqScope,
3526    /// Slice 1: the comparator witnesses of the generic call just checked, left
3527    /// by the generic-call path for the caller that holds the call's `ExprId` to
3528    /// take ([`Ctx::take_witnesses`]) and record on its [`Callee`].
3529    pub last_witness: Option<Vec<TyId>>,
3530    /// The agent's `store` fields, by name (finding #36: collapses the five
3531    /// former per-kind maps — `store_cells`/`store_maps`/`store_sets`/
3532    /// `store_caches`/`store_logs` — into one, since a field name can only
3533    /// ever be one kind). A `:=` write, a `<field>.<op>(…)` call, and the
3534    /// `.entries`/`.keys`/`.values` map accessors all resolve their target
3535    /// here, by receiver provenance. Empty outside `store`-bearing agent
3536    /// handlers.
3537    pub store_fields: HashMap<String, StoreField>,
3538    /// #2017: true while checking an agent handler body, lambdas included.
3539    /// Unlike [`agent_state_ty`](Self::agent_state_ty), a lambda frame does
3540    /// not clear it: a `detach` inside a closure still runs in the agent's
3541    /// handler, which carries no execution context, so the gate must
3542    /// see through the frame swap.
3543    pub in_agent_handler: bool,
3544    /// #2683: true while checking a service handler body, lambdas included
3545    /// (a lambda frame does not clear it, as with
3546    /// [`in_agent_handler`](Self::in_agent_handler)). `e.within(d)` hands its
3547    /// abandoned effect to the execution context, which only a service
3548    /// handler's `deps` carry.
3549    pub in_service_handler: bool,
3550    /// #2719: true while checking the body of a `fn` or a method, lambdas
3551    /// included. A function takes the execution context as a hidden trailing
3552    /// parameter when its body (or a function it calls) hands work to it, so
3553    /// `detach`, `within` and `race` are legal here; whether a *caller* has a
3554    /// context to pass is the needs-context analysis's question
3555    /// ([`crate::exec_plan`]), not this body's.
3556    pub in_fn_body: bool,
3557    /// #2834: a suite-local helper `fn` body, which is not a `case` but may
3558    /// use test-only values (`Val[T]`).
3559    pub test_values: bool,
3560}
3561
3562/// Per-capability info for checker dispatch within a handler body.
3563#[derive(Debug, Clone)]
3564pub struct CapabilityInfo {
3565    pub name: String,
3566    pub ops: Vec<CapabilityOpInfo>,
3567    /// S4a (#1966): for a derived capability (`capability Sessions = Kv`),
3568    /// its base as `(unit, capability)`. An operation call on the instance
3569    /// references the base's operation, where it is declared.
3570    pub derived_from: Option<(String, String)>,
3571}
3572
3573#[derive(Debug, Clone)]
3574pub struct CapabilityOpInfo {
3575    pub name: String,
3576    /// #926: the op's own type parameters (empty for a non-generic op).
3577    /// `params`/`return_ty` below are *pattern* types resolved with these in
3578    /// scope, so a declared `T` survives as `Ty::Var("T")` rather than
3579    /// collapsing to `Ty::Unit` — a call site substitutes a concrete `Ty` for
3580    /// each before checking arguments/return.
3581    pub type_params: Vec<String>,
3582    pub params: Vec<TyId>,
3583    /// The operation's parameter names, positionally aligned with `params`
3584    /// (v0.117). Needed for observation: the `with <pred>` scope binds them by
3585    /// name and `trace(Cap.op)` yields records with these fields.
3586    pub param_names: Vec<String>,
3587    pub return_ty: TyId,
3588    /// Slice 3: the op's type parameters declared `Codable`.
3589    pub codable_params: Vec<String>,
3590    /// #3458: what an undecodable reply means for a typed read, as declared.
3591    pub reply_policy: codable::ReplyPolicy,
3592    /// #2634: for a flattened cross-unit operation, `(unit, type name, in a
3593    /// parameter)` of the
3594    /// first type in its signature that the consumer binds to a structurally
3595    /// different declaration. Reported only when the op is called, as the
3596    /// qualified `U.Cap.op` call does.
3597    pub boundary_conflict: Option<(String, String, bool)>,
3598}
3599
3600/// The synthetic record type name for `trace(Cap.op)`'s call records (v0.117):
3601/// one record per capability operation, its fields the operation's parameters.
3602pub fn call_record_type_name(cap: &str, op: &str) -> String {
3603    format!("__{cap}_{op}_Call")
3604}
3605
3606impl<'a> Ctx<'a> {
3607    pub fn lookup(&self, name: &str) -> Option<TyId> {
3608        for scope in self.scopes.iter().rev() {
3609            if let Some(t) = scope.get(name) {
3610                return Some(*t);
3611            }
3612        }
3613        None
3614    }
3615
3616    /// Returns the type of an expression's "root identifier" — for `a.b.c`
3617    /// that's `a`; for a bare `a` it's `a`. Used to detect whether a chain's
3618    /// outermost name shadows an alias / consumed-context prefix.
3619    pub fn lookup_root_ident(&self, expr: &Expr) -> Option<TyId> {
3620        match &expr.kind {
3621            ExprKind::Ident(id) => self.lookup(&id.name),
3622            ExprKind::FieldAccess { receiver, .. } => self.lookup_root_ident(receiver),
3623            ExprKind::MethodCall { receiver, .. } => self.lookup_root_ident(receiver),
3624            _ => None,
3625        }
3626    }
3627
3628    /// #1930: whether an expression's root ident names an asset in scope
3629    /// (`sheet` in `sheet.url.startsWith(…)`). An asset is a value, but not a
3630    /// local binding, so [`lookup_root_ident`](Self::lookup_root_ident) returns
3631    /// `None` for it, and its chain would otherwise read as a dotted context
3632    /// prefix (`sheet.url` as a context, `startsWith` as its service). Like
3633    /// [`root_ident_is_store_field`](Self::root_ident_is_store_field), it is
3634    /// asked only once the root has no local binding.
3635    pub fn root_ident_is_asset(&self, expr: &Expr) -> bool {
3636        match &expr.kind {
3637            // #2387: an embed is a value of the same kind (`shell.replace(…)`).
3638            ExprKind::Ident(id) => {
3639                self.input.assets.contains_key(&id.name) || self.input.embeds.contains_key(&id.name)
3640            }
3641            ExprKind::FieldAccess { receiver, .. } | ExprKind::MethodCall { receiver, .. } => {
3642                self.root_ident_is_asset(receiver)
3643            }
3644            _ => false,
3645        }
3646    }
3647
3648    /// v0.158 (ADR 0184): whether an expression's root ident names an agent
3649    /// `store` field. A store field is not in the value scope (so
3650    /// [`lookup_root_ident`](Self::lookup_root_ident) returns `None` for it),
3651    /// yet `<map>.entries.…` / `<map>.values.…` chains root in one — this
3652    /// distinguishes them from an un-consumed cross-context prefix so the
3653    /// `map.entries` query accessor is not mistaken for a service call.
3654    pub fn root_ident_is_store_field(&self, expr: &Expr) -> bool {
3655        match &expr.kind {
3656            ExprKind::Ident(id) => self.store_fields.contains_key(&id.name),
3657            ExprKind::FieldAccess { receiver, .. } | ExprKind::MethodCall { receiver, .. } => {
3658                self.root_ident_is_store_field(receiver)
3659            }
3660            _ => false,
3661        }
3662    }
3663
3664    pub fn push_scope(&mut self) {
3665        self.scopes.push(HashMap::new());
3666        self.drop_list_lens_from(self.scopes.len() - 1);
3667    }
3668    /// Push a frame already holding `scope`'s bindings.
3669    pub fn push_scope_with(&mut self, scope: HashMap<String, TyId>) {
3670        self.scopes.push(scope);
3671        self.drop_list_lens_from(self.scopes.len() - 1);
3672    }
3673    fn drop_list_lens_from(&mut self, depth: usize) {
3674        self.list_lens.retain(|(d, _), _| *d < depth);
3675        self.row_links.retain(|(d, _), _| *d < depth);
3676    }
3677    /// #3108: the length of the list literal a `let` named `name` is bound to,
3678    /// when the innermost binding of that name is such a `let`.
3679    pub fn let_list_len(&self, name: &str) -> Option<usize> {
3680        let depth = self.scopes.iter().rposition(|s| s.contains_key(name))?;
3681        self.list_lens.get(&(depth, name.to_string())).copied()
3682    }
3683    /// #3139: the D1 read the innermost binding of `name` holds the rows of.
3684    pub fn row_link(&self, name: &str) -> Option<&d1::RowLink> {
3685        let depth = self.scopes.iter().rposition(|s| s.contains_key(name))?;
3686        self.row_links.get(&(depth, name.to_string()))
3687    }
3688    pub fn pop_scope(&mut self) {
3689        self.scopes.pop();
3690    }
3691    pub fn bind(&mut self, name: String, ty: TyId) {
3692        self.list_lens
3693            .remove(&(self.scopes.len() - 1, name.clone()));
3694        self.row_links
3695            .remove(&(self.scopes.len() - 1, name.clone()));
3696        self.scopes.last_mut().unwrap().insert(name, ty);
3697    }
3698}
3699
3700// ==== Type-system core (resolution, unification, compatibility, inference) ====
3701
3702/// Build a `Ty` from a TypeDecl name reference.
3703pub fn type_from_decl(
3704    id: &Ident,
3705    types: &HashMap<String, Arc<TypeDecl>>,
3706    tys: &Types,
3707) -> Option<TyId> {
3708    let decl = types.get(&id.name)?;
3709    Some(named_ty(decl, tys))
3710}
3711
3712/// Build a `Ty::Named` for the given declaration with the given applied type
3713/// arguments (empty for a non-generic reference).
3714pub fn named_ty_with_args(decl: &TypeDecl, args: Vec<TyId>, tys: &Types) -> TyId {
3715    let kind = match &decl.body {
3716        TypeBody::Refined { base, .. } => NamedKind::Refined(*base),
3717        TypeBody::Record(_) => NamedKind::Record,
3718        TypeBody::Sum(_) => NamedKind::Sum,
3719        TypeBody::Opaque { base, .. } => NamedKind::Opaque(*base),
3720    };
3721    tys.intern(Ty::Named {
3722        name: decl.name.name.clone(),
3723        kind,
3724        args,
3725    })
3726}
3727
3728/// Build a `Ty::Named` for the given declaration (no applied type arguments).
3729pub fn named_ty(decl: &TypeDecl, tys: &Types) -> TyId {
3730    named_ty_with_args(decl, Vec::new(), tys)
3731}
3732
3733/// #2863: the note on `bynk.types.interpolation_non_scalar`. A `DecodeError`
3734/// has fields that interpolate, so its note points at them; any other type gets the
3735/// list of scalar types and how to stringify `Bytes`, `Duration` and `Instant`.
3736fn interpolation_non_scalar_note(ty: TyId, tys: &Types) -> &'static str {
3737    match &*tys.get(ty) {
3738        Ty::DecodeError => {
3739            "a `DecodeError` has no string form; interpolate its fields, e.g. `\"\\(e.kind) at \\(e.path): \\(e.message)\"`"
3740        }
3741        Ty::ValidationError => {
3742            "a `ValidationError` has no string form; interpolate its fields, e.g. `\"\\(e.field): \\(e.message)\"`"
3743        }
3744        _ => {
3745            "interpolation holes accept the base scalar types (String, Int, Float, Bool, Decimal) or a refinement of one; map other values to a String first — `Bytes` via `toHex()`/`toBase64()`, `Duration` via `toString()`, `Instant` via `toIso()`/`toString()`"
3746        }
3747    }
3748}
3749
3750/// v0.158 (ADR 0184): the compiler-known `MapEntry[K, V]` record — the element
3751/// a `store Map[K, V]`'s `.entries` query yields. A nominal generic record
3752/// (`{ key: K, value: V }`), so it flows through `unify`/`compatible`/`display`
3753/// and the ADR 0183 non-boundary rule like any generic-record instantiation;
3754/// its fields are resolved by name in `check_field_access` (it has no
3755/// user-visible `TypeDecl`, like `DecodeError`).
3756pub fn map_entry_ty(k: TyId, v: TyId, tys: &Types) -> TyId {
3757    tys.intern(Ty::Named {
3758        name: MAP_ENTRY.to_string(),
3759        kind: NamedKind::Record,
3760        args: vec![k, v],
3761    })
3762}
3763
3764/// v0.157 (ADR 0183): the substitution mapping a generic record's declared
3765/// type parameters onto a concrete instantiation's arguments. Empty when the
3766/// type is non-generic or `args` is empty (an under-applied reference — the
3767/// resolver reports that separately).
3768pub fn type_param_subst(decl: &TypeDecl, args: &[TyId]) -> HashMap<String, TyId> {
3769    decl.type_params
3770        .iter()
3771        .map(|p| p.name.name.clone())
3772        .zip(args.iter().copied())
3773        .collect()
3774}
3775
3776/// v0.157 (ADR 0183): the type of a generic record's field at a concrete
3777/// instantiation. The field's declared type is resolved with the declaration's
3778/// type parameters in scope as rigid vars, then those vars are replaced by the
3779/// instantiation's `args`. For a non-generic record this is a plain resolve.
3780pub fn instantiate_field_ty(
3781    decl: &TypeDecl,
3782    args: &[TyId],
3783    field_ref: &TypeRef,
3784    types: &HashMap<String, Arc<TypeDecl>>,
3785    tys: &Types,
3786) -> Option<TyId> {
3787    if decl.type_params.is_empty() {
3788        return resolve_type_ref(field_ref, types, tys);
3789    }
3790    // Without a full argument set the substitution is partial and would leave a
3791    // rigid `Ty::Var` in the field type; an under-/over-applied reference is an
3792    // error the resolver reports, so field access yields no type here.
3793    if decl.type_params.len() != args.len() {
3794        return None;
3795    }
3796    let vars: HashSet<String> = decl
3797        .type_params
3798        .iter()
3799        .map(|p| p.name.name.clone())
3800        .collect();
3801    let field_ty = resolve_type_ref_in(field_ref, types, &vars, tys)?;
3802    Some(substitute(field_ty, &type_param_subst(decl, args), tys))
3803}
3804
3805/// v0.20a: like [`resolve_type_ref`], with a set of in-scope **type
3806/// parameters**: a `Named` reference matching one resolves to [`Ty::Var`]
3807/// (checked before the type-table lookup — a type parameter shadows a
3808/// same-named declaration; the collision is diagnosed at the declaration).
3809pub fn resolve_type_ref_in(
3810    r: &TypeRef,
3811    types: &HashMap<String, Arc<TypeDecl>>,
3812    vars: &HashSet<String>,
3813    tys: &Types,
3814) -> Option<TyId> {
3815    let ty = match r {
3816        TypeRef::Named(id) if vars.contains(&id.name) => Ty::Var(id.name.clone()),
3817        TypeRef::Result(t, e, _) => Ty::Result(
3818            resolve_type_ref_in(t, types, vars, tys)?,
3819            resolve_type_ref_in(e, types, vars, tys)?,
3820        ),
3821        TypeRef::Option(t, _) => Ty::Option(resolve_type_ref_in(t, types, vars, tys)?),
3822        TypeRef::Effect(t, _) => Ty::Effect(resolve_type_ref_in(t, types, vars, tys)?),
3823        TypeRef::HttpResult(t, _) => Ty::HttpResult(resolve_type_ref_in(t, types, vars, tys)?),
3824        TypeRef::List(t, _) => Ty::List(resolve_type_ref_in(t, types, vars, tys)?),
3825        TypeRef::Set(t, _) => Ty::Set(resolve_type_ref_in(t, types, vars, tys)?),
3826        TypeRef::Query(t, _) => Ty::Query(resolve_type_ref_in(t, types, vars, tys)?),
3827        TypeRef::Stream(t, _) => Ty::Stream(resolve_type_ref_in(t, types, vars, tys)?),
3828        TypeRef::Connection(t, _) => Ty::Connection(resolve_type_ref_in(t, types, vars, tys)?),
3829        TypeRef::Map(k, v, _) => Ty::Map(
3830            resolve_type_ref_in(k, types, vars, tys)?,
3831            resolve_type_ref_in(v, types, vars, tys)?,
3832        ),
3833        TypeRef::Fn(params, ret, _) => {
3834            let params: Option<Vec<TyId>> = params
3835                .iter()
3836                .map(|p| resolve_type_ref_in(p, types, vars, tys))
3837                .collect();
3838            Ty::Fn {
3839                params: params?,
3840                ret: resolve_type_ref_in(ret, types, vars, tys)?,
3841            }
3842        }
3843        // v0.157 (ADR 0183): `Name[Arg, …]` — application of a user generic
3844        // type. Arguments resolve with the enclosing type parameters in scope;
3845        // existence/arity are validated in the resolver, so an unknown or
3846        // mis-applied name simply produces no type here.
3847        TypeRef::App { name, args, .. } => {
3848            let decl = types.get(&name.name)?;
3849            let args: Option<Vec<TyId>> = args
3850                .iter()
3851                .map(|a| resolve_type_ref_in(a, types, vars, tys))
3852                .collect();
3853            return Some(named_ty_with_args(decl, args?, tys));
3854        }
3855        _ => return resolve_type_ref(r, types, tys),
3856    };
3857    Some(tys.intern(ty))
3858}
3859
3860/// v0.20a: substitute type variables in `t` per `subst`. Must be total when
3861/// instantiating a call (the uninferable check runs first); an unbound Var
3862/// passes through unchanged for partial substitution during inference.
3863pub(crate) fn substitute(t: TyId, subst: &HashMap<String, TyId>, tys: &Types) -> TyId {
3864    let node = tys.get(t);
3865    let substituted = match &*node {
3866        Ty::Var(n) => return subst.get(n).copied().unwrap_or(t),
3867        Ty::Result(a, b) => Ty::Result(substitute(*a, subst, tys), substitute(*b, subst, tys)),
3868        Ty::Option(a) => Ty::Option(substitute(*a, subst, tys)),
3869        Ty::Effect(a) => Ty::Effect(substitute(*a, subst, tys)),
3870        Ty::HttpResult(a) => Ty::HttpResult(substitute(*a, subst, tys)),
3871        Ty::HttpOutcome(a) => Ty::HttpOutcome(substitute(*a, subst, tys)),
3872        Ty::List(a) => Ty::List(substitute(*a, subst, tys)),
3873        Ty::Set(a) => Ty::Set(substitute(*a, subst, tys)),
3874        Ty::Query(a) => Ty::Query(substitute(*a, subst, tys)),
3875        Ty::Stream(a) => Ty::Stream(substitute(*a, subst, tys)),
3876        Ty::Connection(a) => Ty::Connection(substitute(*a, subst, tys)),
3877        Ty::TestConnection(a) => Ty::TestConnection(substitute(*a, subst, tys)),
3878        Ty::Map(k, v) => Ty::Map(substitute(*k, subst, tys), substitute(*v, subst, tys)),
3879        Ty::Fn { params, ret } => Ty::Fn {
3880            params: params.iter().map(|p| substitute(*p, subst, tys)).collect(),
3881            ret: substitute(*ret, subst, tys),
3882        },
3883        // v0.157 (ADR 0183): a generic named type's arguments may carry vars —
3884        // substitution recurses into them (an under-applied bare reference has
3885        // empty `args`, so this is a no-op there).
3886        Ty::Named { name, kind, args } => Ty::Named {
3887            name: name.clone(),
3888            kind: kind.clone(),
3889            args: args.iter().map(|a| substitute(*a, subst, tys)).collect(),
3890        },
3891        // Leaves (no inner type to ground) and the sealed actor bindings
3892        // (boundary-minted, never Var-bearing). Enumerated — no `_` — so a
3893        // new `Ty` variant must state whether substitution recurses into it.
3894        // `Ty::Error` is a leaf by construction (R4.3): it never carries a
3895        // `Var` to ground. T3.6b: a leaf substitutes to itself, and its `TyId`
3896        // is already that value — return it rather than re-interning.
3897        Ty::Error
3898        | Ty::Never
3899        | Ty::Base(_)
3900        | Ty::QueueResult
3901        | Ty::BoundaryRejection
3902        | Ty::Asset
3903        | Ty::RequestHeaders
3904        | Ty::RequestQuery
3905        | Ty::RequestCookies
3906        | Ty::TokenClaims
3907        | Ty::ValidationError
3908        | Ty::DecodeError
3909        | Ty::Unit
3910        | Ty::Actor(_)
3911        | Ty::ActorSum(_) => return t,
3912    };
3913    tys.intern(substituted)
3914}
3915
3916/// v0.20a: does `t` still contain a type variable?
3917pub(crate) fn contains_var(t: TyId, tys: &Types) -> bool {
3918    match &*tys.get(t) {
3919        Ty::Var(_) => true,
3920        // R4.3: `Ty::Error` is a leaf; it never carries a `Var`.
3921        Ty::Error | Ty::Never => false,
3922        Ty::Result(a, b) | Ty::Map(a, b) => contains_var(*a, tys) || contains_var(*b, tys),
3923        Ty::Option(a)
3924        | Ty::Effect(a)
3925        | Ty::HttpResult(a)
3926        | Ty::HttpOutcome(a)
3927        | Ty::List(a)
3928        | Ty::Set(a)
3929        | Ty::Query(a)
3930        | Ty::Stream(a)
3931        | Ty::TestConnection(a)
3932        | Ty::Connection(a) => contains_var(*a, tys),
3933        Ty::Fn { params, ret } => {
3934            params.iter().any(|p| contains_var(*p, tys)) || contains_var(*ret, tys)
3935        }
3936        // v0.157 (ADR 0183): a generic named type's arguments may carry vars.
3937        Ty::Named { args, .. } => args.iter().any(|a| contains_var(*a, tys)),
3938        Ty::Base(_)
3939        | Ty::QueueResult
3940        | Ty::BoundaryRejection
3941        | Ty::Asset
3942        | Ty::RequestHeaders
3943        | Ty::RequestQuery
3944        | Ty::RequestCookies
3945        | Ty::TokenClaims
3946        | Ty::ValidationError
3947        | Ty::DecodeError
3948        | Ty::Unit
3949        | Ty::Actor(_)
3950        | Ty::ActorSum(_) => false,
3951    }
3952}
3953
3954/// Merge two list element types that may still mention flexible variables of
3955/// an enclosing generic call (`Result[Int, E]` and `Result[Int, String]` give
3956/// `Result[Int, String]`). `None` when their concrete parts disagree.
3957fn merge_open(a: TyId, b: TyId, rigid: &HashSet<String>, tys: &Types) -> Option<TyId> {
3958    if a == b {
3959        return Some(a);
3960    }
3961    let flex = |t: TyId| matches!(&*tys.get(t), Ty::Var(n) if !rigid.contains(n));
3962    if flex(a) {
3963        return Some(b);
3964    }
3965    if flex(b) {
3966        return Some(a);
3967    }
3968    let (ta, tb) = ((*tys.get(a)).clone(), (*tys.get(b)).clone());
3969    let merged = match (ta, tb) {
3970        (Ty::Option(x), Ty::Option(y)) => Ty::Option(merge_open(x, y, rigid, tys)?),
3971        (Ty::List(x), Ty::List(y)) => Ty::List(merge_open(x, y, rigid, tys)?),
3972        (Ty::Set(x), Ty::Set(y)) => Ty::Set(merge_open(x, y, rigid, tys)?),
3973        (Ty::HttpResult(x), Ty::HttpResult(y)) => Ty::HttpResult(merge_open(x, y, rigid, tys)?),
3974        (Ty::Effect(x), Ty::Effect(y)) => Ty::Effect(merge_open(x, y, rigid, tys)?),
3975        (Ty::Stream(x), Ty::Stream(y)) => Ty::Stream(merge_open(x, y, rigid, tys)?),
3976        (Ty::Query(x), Ty::Query(y)) => Ty::Query(merge_open(x, y, rigid, tys)?),
3977        (Ty::Connection(x), Ty::Connection(y)) => Ty::Connection(merge_open(x, y, rigid, tys)?),
3978        (Ty::TestConnection(x), Ty::TestConnection(y)) => {
3979            Ty::TestConnection(merge_open(x, y, rigid, tys)?)
3980        }
3981        (Ty::HttpOutcome(x), Ty::HttpOutcome(y)) => Ty::HttpOutcome(merge_open(x, y, rigid, tys)?),
3982        (
3983            Ty::Fn {
3984                params: p1,
3985                ret: r1,
3986            },
3987            Ty::Fn {
3988                params: p2,
3989                ret: r2,
3990            },
3991        ) if p1.len() == p2.len() => Ty::Fn {
3992            params: p1
3993                .iter()
3994                .zip(&p2)
3995                .map(|(x, y)| merge_open(*x, *y, rigid, tys))
3996                .collect::<Option<Vec<_>>>()?,
3997            ret: merge_open(r1, r2, rigid, tys)?,
3998        },
3999        (Ty::Result(x1, e1), Ty::Result(x2, e2)) => Ty::Result(
4000            merge_open(x1, x2, rigid, tys)?,
4001            merge_open(e1, e2, rigid, tys)?,
4002        ),
4003        (Ty::Map(k1, v1), Ty::Map(k2, v2)) => Ty::Map(
4004            merge_open(k1, k2, rigid, tys)?,
4005            merge_open(v1, v2, rigid, tys)?,
4006        ),
4007        (
4008            Ty::Named {
4009                name: n1,
4010                kind,
4011                args: a1,
4012            },
4013            Ty::Named {
4014                name: n2,
4015                kind: k2,
4016                args: a2,
4017            },
4018        ) if n1 == n2 && kind == k2 && a1.len() == a2.len() => Ty::Named {
4019            name: n1,
4020            kind,
4021            args: a1
4022                .iter()
4023                .zip(&a2)
4024                .map(|(x, y)| merge_open(*x, *y, rigid, tys))
4025                .collect::<Option<Vec<_>>>()?,
4026        },
4027        _ => return compatible(a, b, tys).then_some(a),
4028    };
4029    Some(tys.intern(merged))
4030}
4031
4032/// v0.20b: does `t` contain a type variable that is NOT one of the enclosing
4033/// function's rigid type parameters? Rigid vars are fully constrained inside
4034/// the body; only flexible (call-site instantiation) vars mean "still being
4035/// inferred".
4036fn contains_flexible_var(t: TyId, rigid: &HashSet<String>, tys: &Types) -> bool {
4037    match &*tys.get(t) {
4038        Ty::Var(n) => !rigid.contains(n),
4039        // R4.3: `Ty::Error` is a leaf; it never carries a `Var`.
4040        Ty::Error | Ty::Never => false,
4041        Ty::Result(a, b) | Ty::Map(a, b) => {
4042            contains_flexible_var(*a, rigid, tys) || contains_flexible_var(*b, rigid, tys)
4043        }
4044        Ty::Option(a)
4045        | Ty::Effect(a)
4046        | Ty::HttpResult(a)
4047        | Ty::HttpOutcome(a)
4048        | Ty::List(a)
4049        | Ty::Set(a)
4050        | Ty::Query(a)
4051        | Ty::Stream(a)
4052        | Ty::TestConnection(a)
4053        | Ty::Connection(a) => contains_flexible_var(*a, rigid, tys),
4054        Ty::Fn { params, ret } => {
4055            params.iter().any(|p| contains_flexible_var(*p, rigid, tys))
4056                || contains_flexible_var(*ret, rigid, tys)
4057        }
4058        // v0.157 (ADR 0183): a generic named type's arguments may carry vars.
4059        Ty::Named { args, .. } => args.iter().any(|a| contains_flexible_var(*a, rigid, tys)),
4060        Ty::Base(_)
4061        | Ty::QueueResult
4062        | Ty::BoundaryRejection
4063        | Ty::Asset
4064        | Ty::RequestHeaders
4065        | Ty::RequestQuery
4066        | Ty::RequestCookies
4067        | Ty::TokenClaims
4068        | Ty::ValidationError
4069        | Ty::DecodeError
4070        | Ty::Unit
4071        | Ty::Actor(_)
4072        | Ty::ActorSum(_) => false,
4073    }
4074}
4075
4076/// v0.20a: argument-directed unification. Walks `pattern` (possibly
4077/// Var-bearing) against the ground `actual`; a Var binds on first sight and
4078/// must match its prior binding **exactly** afterwards (keep inference dumb
4079/// and predictable — the explicit `name[T](…)` form is the pressure valve).
4080/// Returns false on a conflict; structural mismatches are NOT reported here —
4081/// the post-substitution `compatible` check owns those diagnostics.
4082pub(crate) fn unify(
4083    pattern: TyId,
4084    actual: TyId,
4085    subst: &mut HashMap<String, TyId>,
4086    tys: &Types,
4087) -> bool {
4088    // T3.6b: bind the two nodes first — the `Rc`s must outlive the `match`
4089    // they are destructured by, and a `TyId` pair is not itself matchable.
4090    let (p_node, a_node) = (tys.get(pattern), tys.get(actual));
4091    match (&*p_node, &*a_node) {
4092        // #2620: the bottom type fits any pattern and constrains nothing, so a
4093        // fault call never binds a type variable — the other arguments or the
4094        // expected type resolve it (`pick(unreachable("x"), n)`).
4095        (_, Ty::Never) => true,
4096        (Ty::Var(n), _) => match subst.get(n) {
4097            // T3.6b (R4.1): "matches its prior binding exactly" is now a
4098            // `TyId` comparison — one `u32` equality, where it used to be a
4099            // recursive structural walk. Interning is what makes the two
4100            // equivalent.
4101            Some(bound) => *bound == actual,
4102            None => {
4103                subst.insert(n.clone(), actual);
4104                true
4105            }
4106        },
4107        (Ty::Result(a1, b1), Ty::Result(a2, b2)) | (Ty::Map(a1, b1), Ty::Map(a2, b2)) => {
4108            unify(*a1, *a2, subst, tys) && unify(*b1, *b2, subst, tys)
4109        }
4110        (Ty::Option(a1), Ty::Option(a2))
4111        | (Ty::Effect(a1), Ty::Effect(a2))
4112        | (Ty::HttpResult(a1), Ty::HttpResult(a2))
4113        | (Ty::HttpOutcome(a1), Ty::HttpOutcome(a2))
4114        | (Ty::List(a1), Ty::List(a2))
4115        | (Ty::Set(a1), Ty::Set(a2))
4116        | (Ty::Query(a1), Ty::Query(a2))
4117        | (Ty::Stream(a1), Ty::Stream(a2))
4118        | (Ty::Connection(a1), Ty::Connection(a2))
4119        | (Ty::TestConnection(a1), Ty::TestConnection(a2)) => unify(*a1, *a2, subst, tys),
4120        (
4121            Ty::Fn {
4122                params: p1,
4123                ret: r1,
4124            },
4125            Ty::Fn {
4126                params: p2,
4127                ret: r2,
4128            },
4129        ) => {
4130            p1.len() == p2.len()
4131                && p1
4132                    .iter()
4133                    .zip(p2)
4134                    .all(|(a, b)| unify(*a, *b, subst, tys))
4135                && unify(*r1, *r2, subst, tys)
4136        }
4137        // v0.157 (ADR 0183): a generic named type binds vars through its
4138        // arguments — `Paginated[T]` against `Paginated[User]` binds `T=User`.
4139        (
4140            Ty::Named {
4141                name: n1, args: a1, ..
4142            },
4143            Ty::Named {
4144                name: n2, args: a2, ..
4145            },
4146        ) if n1 == n2 && a1.len() == a2.len() && !a1.is_empty() => {
4147            a1.iter().zip(a2).all(|(x, y)| unify(*x, *y, subst, tys))
4148        }
4149        // Ground-vs-ground: any pair is fine here; `compatible` owns the
4150        // real check after substitution. The left side is enumerated — no
4151        // `_` — so a new inner-type-bearing `Ty` variant must add its
4152        // recursion arm above instead of silently skipping unification.
4153        (
4154            Ty::Base(_)
4155            | Ty::Named { .. }
4156            | Ty::Result(..)
4157            | Ty::Option(_)
4158            | Ty::Effect(_)
4159            | Ty::HttpResult(_)
4160            | Ty::HttpOutcome(_)
4161            | Ty::QueueResult
4162            | Ty::BoundaryRejection
4163            | Ty::Asset
4164            | Ty::RequestHeaders
4165            | Ty::RequestQuery
4166            | Ty::RequestCookies
4167
4168            | Ty::TokenClaims
4169            | Ty::List(_)
4170            | Ty::Set(_)
4171            | Ty::Map(..)
4172            | Ty::Query(_)
4173            | Ty::Stream(_)
4174            | Ty::TestConnection(_)
4175            | Ty::Connection(_)
4176            | Ty::ValidationError
4177            | Ty::DecodeError
4178            | Ty::Unit
4179            | Ty::Actor(_)
4180            | Ty::ActorSum(_)
4181            | Ty::Fn { .. }
4182            // R4.3: an already-diagnosed subtree unifies with anything —
4183            // the failure was reported once, at the site that produced
4184            // `Ty::Error`; unification is not where a second one belongs.
4185            | Ty::Error
4186            | Ty::Never,
4187            _,
4188        ) => true,
4189    }
4190}
4191
4192/// v0.25 (ADR 0053): record a binding edge for every `Named` reference
4193/// inside a type-ref that resolved. Called alongside the `resolve_type_ref*`
4194/// annotation sites; `skip` holds the enclosing fn's type parameters (rigid
4195/// vars are not type symbols). Handler signatures and body annotations never
4196/// pass through the resolver's reference walk, so these sites are their only
4197/// recording point; where both passes run, assembly dedupes.
4198pub fn record_type_refs(
4199    r: &TypeRef,
4200    types: &HashMap<String, Arc<TypeDecl>>,
4201    skip: &HashSet<String>,
4202    refs: &mut RefSink,
4203) {
4204    match r {
4205        TypeRef::Named(id) => {
4206            if types.contains_key(&id.name) && !skip.contains(&id.name) {
4207                refs.record(id.span, SymbolKind::Type, &id.name);
4208            }
4209        }
4210        TypeRef::Fn(params, ret, _) => {
4211            for p in params {
4212                record_type_refs(p, types, skip, refs);
4213            }
4214            record_type_refs(ret, types, skip, refs);
4215        }
4216        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
4217            record_type_refs(a, types, skip, refs);
4218            record_type_refs(b, types, skip, refs);
4219        }
4220        TypeRef::Option(t, _)
4221        | TypeRef::Effect(t, _)
4222        | TypeRef::HttpResult(t, _)
4223        | TypeRef::Query(t, _)
4224        | TypeRef::Stream(t, _)
4225        | TypeRef::Connection(t, _)
4226        | TypeRef::History(t, _)
4227        | TypeRef::List(t, _)
4228        | TypeRef::Set(t, _) => record_type_refs(t, types, skip, refs),
4229        // v0.157 (ADR 0183): a `Name[Arg, …]` application records the generic
4230        // type's name plus every argument.
4231        TypeRef::App { name, args, .. } => {
4232            if types.contains_key(&name.name) && !skip.contains(&name.name) {
4233                refs.record(name.span, SymbolKind::Type, &name.name);
4234            }
4235            for a in args {
4236                record_type_refs(a, types, skip, refs);
4237            }
4238        }
4239        TypeRef::Base(..)
4240        | TypeRef::QueueResult(_)
4241        | TypeRef::Asset(_)
4242        | TypeRef::RequestHeaders(_)
4243        | TypeRef::RequestQuery(_)
4244        | TypeRef::RequestCookies(_)
4245        | TypeRef::TokenClaims(_)
4246        | TypeRef::BoundaryRejection(_)
4247        | TypeRef::ValidationError(_)
4248        | TypeRef::DecodeError(_)
4249        | TypeRef::Unit(_) => {}
4250    }
4251}
4252
4253/// #712: resolve a type reference that appears in an *expression* position the
4254/// resolver does not walk for handler bodies — explicit call type arguments
4255/// (`identity[T](x)`), `Json.decode[T]`, and lambda parameter annotations
4256/// (`(x: T) => …`). On failure the reference is silently dropped by the bare
4257/// `resolve_type_ref_in`, so an unknown type in a handler body would compile
4258/// clean; this reports `bynk.resolve.unknown_type` instead, and records the
4259/// resolved type's references for the IDE on success. The resolver still covers
4260/// `fn`/method bodies, and the checker runs only after the resolver returns Ok
4261/// (`bynk-emit`'s pipeline sequences `resolve(..)?` then `check(..)`), so this
4262/// never double-reports.
4263pub(crate) fn resolve_expr_type_ref(r: &TypeRef, ctx: &mut Ctx) -> Option<TyId> {
4264    let tys = ctx.tys;
4265    match resolve_type_ref_in(r, &ctx.input.types, &ctx.type_vars, tys) {
4266        Some(ty) => {
4267            record_type_refs(r, &ctx.input.types, &ctx.type_vars, ctx.refs);
4268            Some(ty)
4269        }
4270        None => {
4271            ctx.errors.push(unresolved_type_ref_error(
4272                r,
4273                &ctx.input.types,
4274                &ctx.type_vars,
4275            ));
4276            None
4277        }
4278    }
4279}
4280
4281/// #712: the diagnostic for a type reference that fails to resolve. Points at
4282/// the exact offending name when one can be identified (`identity[Missing](5)`
4283/// → the `Missing` span), falling back to the whole reference otherwise.
4284fn unresolved_type_ref_error(
4285    r: &TypeRef,
4286    types: &HashMap<String, Arc<TypeDecl>>,
4287    vars: &HashSet<String>,
4288) -> CompileError {
4289    match first_unresolved_type_name(r, types, vars) {
4290        Some(id) => CompileError::new(
4291            "bynk.resolve.unknown_type",
4292            id.span,
4293            format!("unknown type `{}`", id.name),
4294        )
4295        .with_note(
4296            "in scope are the base types (`Int`, `Float`, `String`, `Bool`, `Duration`, \
4297             `Instant`, `Bytes`), the built-in generics (`List`, `Map`, `Option`, `Result`, …), \
4298             `ValidationError`, and the types this unit declares or imports",
4299        ),
4300        None => CompileError::new(
4301            "bynk.resolve.unknown_type",
4302            r.span(),
4303            "this type does not resolve",
4304        ),
4305    }
4306}
4307
4308/// #712: the first type name in `r` that names neither a declared type nor an
4309/// in-scope type variable — the reason `resolve_type_ref_in` returned `None`.
4310fn first_unresolved_type_name<'a>(
4311    r: &'a TypeRef,
4312    types: &HashMap<String, Arc<TypeDecl>>,
4313    vars: &HashSet<String>,
4314) -> Option<&'a Ident> {
4315    match r {
4316        TypeRef::Named(id) => {
4317            (!types.contains_key(&id.name) && !vars.contains(&id.name)).then_some(id)
4318        }
4319        TypeRef::App { name, args, .. } => {
4320            if !types.contains_key(&name.name) && !vars.contains(&name.name) {
4321                return Some(name);
4322            }
4323            args.iter()
4324                .find_map(|a| first_unresolved_type_name(a, types, vars))
4325        }
4326        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
4327            first_unresolved_type_name(a, types, vars)
4328                .or_else(|| first_unresolved_type_name(b, types, vars))
4329        }
4330        TypeRef::Option(t, _)
4331        | TypeRef::Effect(t, _)
4332        | TypeRef::HttpResult(t, _)
4333        | TypeRef::List(t, _)
4334        | TypeRef::Set(t, _)
4335        | TypeRef::Query(t, _)
4336        | TypeRef::Stream(t, _)
4337        | TypeRef::Connection(t, _)
4338        | TypeRef::History(t, _) => first_unresolved_type_name(t, types, vars),
4339        TypeRef::Fn(params, ret, _) => params
4340            .iter()
4341            .find_map(|p| first_unresolved_type_name(p, types, vars))
4342            .or_else(|| first_unresolved_type_name(ret, types, vars)),
4343        TypeRef::Base(..)
4344        | TypeRef::QueueResult(_)
4345        | TypeRef::Asset(_)
4346        | TypeRef::RequestHeaders(_)
4347        | TypeRef::RequestQuery(_)
4348        | TypeRef::RequestCookies(_)
4349        | TypeRef::TokenClaims(_)
4350        | TypeRef::BoundaryRejection(_)
4351        | TypeRef::ValidationError(_)
4352        | TypeRef::DecodeError(_)
4353        | TypeRef::Unit(_) => None,
4354    }
4355}
4356
4357/// v0.154 (ADR 0178): the declared error embedding that converts `source_err`
4358/// into `target_err`, if one exists. When `target_err` is a sum declaring
4359/// `embeds E as V` with `E` compatible with `source_err`, returns
4360/// `(sum_type_name, variant_name)` — the variant a value of `source_err`
4361/// auto-wraps into. One level only: the source must match a declared embedding
4362/// directly. Used by `?` in the checker (to accept the conversion) and the
4363/// emitter (to lower the `Err`-wrap) from the **same** rule, so the two cannot
4364/// diverge.
4365pub fn embedding_for(
4366    target_err: TyId,
4367    source_err: TyId,
4368    types: &HashMap<String, Arc<TypeDecl>>,
4369    tys: &Types,
4370) -> Option<(String, String)> {
4371    let target_node = tys.get(target_err);
4372    let Ty::Named { name, .. } = &*target_node else {
4373        return None;
4374    };
4375    let decl = types.get(name)?;
4376    let TypeBody::Sum(sum) = &decl.body else {
4377        return None;
4378    };
4379    for clause in &sum.embeds {
4380        if let Some(src) = resolve_type_ref(&clause.source_type, types, tys)
4381            && compatible(source_err, src, tys)
4382        {
4383            return Some((name.clone(), clause.variant.name.clone()));
4384        }
4385    }
4386    None
4387}
4388
4389pub fn resolve_type_ref(
4390    r: &TypeRef,
4391    types: &HashMap<String, Arc<TypeDecl>>,
4392    tys: &Types,
4393) -> Option<TyId> {
4394    let ty = match r {
4395        TypeRef::Base(b, _) => Ty::Base(*b),
4396        TypeRef::Named(id) => return type_from_decl(id, types, tys),
4397        // v0.20a: a function type. Effectfulness is structural (ret is
4398        // Effect[_]); nothing extra to record.
4399        TypeRef::Fn(params, ret, _) => {
4400            let params: Option<Vec<TyId>> = params
4401                .iter()
4402                .map(|p| resolve_type_ref(p, types, tys))
4403                .collect();
4404            Ty::Fn {
4405                params: params?,
4406                ret: resolve_type_ref(ret, types, tys)?,
4407            }
4408        }
4409        TypeRef::Result(t, e, _) => Ty::Result(
4410            resolve_type_ref(t, types, tys)?,
4411            resolve_type_ref(e, types, tys)?,
4412        ),
4413        TypeRef::Option(t, _) => Ty::Option(resolve_type_ref(t, types, tys)?),
4414        TypeRef::Effect(t, _) => Ty::Effect(resolve_type_ref(t, types, tys)?),
4415        TypeRef::HttpResult(t, _) => Ty::HttpResult(resolve_type_ref(t, types, tys)?),
4416        TypeRef::List(t, _) => Ty::List(resolve_type_ref(t, types, tys)?),
4417        TypeRef::Set(t, _) => Ty::Set(resolve_type_ref(t, types, tys)?),
4418        TypeRef::Query(t, _) => Ty::Query(resolve_type_ref(t, types, tys)?),
4419        TypeRef::Stream(t, _) => Ty::Stream(resolve_type_ref(t, types, tys)?),
4420        TypeRef::Connection(t, _) => Ty::Connection(resolve_type_ref(t, types, tys)?),
4421        TypeRef::Map(k, v, _) => Ty::Map(
4422            resolve_type_ref(k, types, tys)?,
4423            resolve_type_ref(v, types, tys)?,
4424        ),
4425        TypeRef::QueueResult(_) => Ty::QueueResult,
4426        TypeRef::Asset(_) => Ty::Asset,
4427        TypeRef::RequestHeaders(_) => Ty::RequestHeaders,
4428        TypeRef::RequestQuery(_) => Ty::RequestQuery,
4429        TypeRef::RequestCookies(_) => Ty::RequestCookies,
4430        TypeRef::TokenClaims(_) => Ty::TokenClaims,
4431        TypeRef::BoundaryRejection(_) => Ty::BoundaryRejection,
4432        // v0.119 (ADR 0155): `History[Agent]` is not a value type — it is a
4433        // test-only generator handled directly in `check_property_body`. It never
4434        // resolves as an ordinary type, so a stray `History[…]` in a value
4435        // position fails to resolve (the resolver reports `outside_property`).
4436        TypeRef::History(_, _) => return None,
4437        // v0.157 (ADR 0183): `Name[Arg, …]` — a user generic-type application.
4438        TypeRef::App { name, args, .. } => {
4439            let decl = types.get(&name.name)?;
4440            let args: Option<Vec<TyId>> = args
4441                .iter()
4442                .map(|a| resolve_type_ref(a, types, tys))
4443                .collect();
4444            return Some(named_ty_with_args(decl, args?, tys));
4445        }
4446        TypeRef::ValidationError(_) => Ty::ValidationError,
4447        TypeRef::DecodeError(_) => Ty::DecodeError,
4448        TypeRef::Unit(_) => Ty::Unit,
4449    };
4450    Some(tys.intern(ty))
4451}
4452
4453/// `t` is usable where `u` is expected.
4454///
4455/// T3.6b: deliberately **no** `t == u` fast path, tempting as interning makes
4456/// one. `compatible` is not reflexive — `Actor`/`ActorSum` are sealed boundary
4457/// values that fall through to the `false` arm below even against themselves
4458/// (they are matched, never assigned), so short-circuiting on id equality
4459/// would silently make them assignable.
4460pub fn compatible(t: TyId, u: TyId, tys: &Types) -> bool {
4461    let (t_node, u_node) = (tys.get(t), tys.get(u));
4462    match (&*t_node, &*u_node) {
4463        // R4.3: `Ty::Error` is compatible with everything, in both positions
4464        // — the failure that produced it was already diagnosed at its own
4465        // site, and a mismatch diagnostic naming it here would be a second
4466        // report of the same failure, not a new one. Ordered first so it
4467        // takes priority over the more specific arms below.
4468        (Ty::Error, _) | (_, Ty::Error) => true,
4469        // #2620: the bottom type is usable wherever any type is expected, and
4470        // nothing but `Never` itself (or the error type, above) is usable
4471        // where `Never` is expected.
4472        (Ty::Never, _) => true,
4473        (_, Ty::Never) => false,
4474        (Ty::Base(a), Ty::Base(b)) => a == b,
4475        // v0.157 (ADR 0183): two named types are compatible when they share a
4476        // name and kind and their applied type arguments are pairwise
4477        // compatible. Records are immutable (`readonly` fields), so the
4478        // arguments are covariant — like `List`/`Option`.
4479        (
4480            Ty::Named {
4481                name: a,
4482                kind: ka,
4483                args: aa,
4484            },
4485            Ty::Named {
4486                name: b,
4487                kind: kb,
4488                args: ba,
4489            },
4490        ) => {
4491            a == b
4492                && ka == kb
4493                && aa.len() == ba.len()
4494                && aa.iter().zip(ba).all(|(x, y)| compatible(*x, *y, tys))
4495        }
4496        // Refined → base (widening).
4497        (
4498            Ty::Named {
4499                kind: NamedKind::Refined(b),
4500                ..
4501            },
4502            Ty::Base(target),
4503        ) => b == target,
4504        (Ty::Base(_), Ty::Named { .. }) => false,
4505        (Ty::Result(t1, e1), Ty::Result(t2, e2)) => {
4506            compatible(*t1, *t2, tys) && compatible(*e1, *e2, tys)
4507        }
4508        (Ty::Option(a), Ty::Option(b)) => compatible(*a, *b, tys),
4509        (Ty::Effect(a), Ty::Effect(b)) => compatible(*a, *b, tys),
4510        (Ty::HttpResult(a), Ty::HttpResult(b)) | (Ty::HttpOutcome(a), Ty::HttpOutcome(b)) => {
4511            compatible(*a, *b, tys)
4512        }
4513        // v0.20b: collections are covariant in their element/value types;
4514        // Map keys must match exactly — key-position widening would split a
4515        // map's keys across refined/base identities at lookup time.
4516        (Ty::List(a), Ty::List(b)) => compatible(*a, *b, tys),
4517        // K6a (#2596): a `Set`'s element must match exactly, as a `Map` key must.
4518        (Ty::Set(a), Ty::Set(b)) => a == b,
4519        // v0.100: `Stream[T]` is covariant in its element, like `List`/`Effect`.
4520        // (Assignability only — streams are not value-comparable for `==`.)
4521        (Ty::Stream(a), Ty::Stream(b)) => compatible(*a, *b, tys),
4522        // v0.91: `Query[T]` is covariant in its element, like `List`/`Stream`.
4523        // (Assignability only — queries are not value-comparable for `==`.)
4524        (Ty::Query(a), Ty::Query(b)) => compatible(*a, *b, tys),
4525        // v0.102: a `Connection[F]` is assignable to itself (the linearity pass
4526        // governs the move). Held values have identity, not value-equality, so
4527        // they are not `==`-comparable (guarded in the `Eq`/`NotEq` arm).
4528        (Ty::Connection(a), Ty::Connection(b)) => compatible(*a, *b, tys),
4529        (Ty::TestConnection(a), Ty::TestConnection(b)) => compatible(*a, *b, tys),
4530        (Ty::Map(k1, v1), Ty::Map(k2, v2)) => k1 == k2 && compatible(*v1, *v2, tys),
4531        (Ty::QueueResult, Ty::QueueResult) | (Ty::BoundaryRejection, Ty::BoundaryRejection) => true,
4532        (Ty::Asset, Ty::Asset) => true,
4533        (Ty::RequestHeaders, Ty::RequestHeaders) => true,
4534        (Ty::RequestQuery, Ty::RequestQuery) => true,
4535        (Ty::RequestCookies, Ty::RequestCookies) => true,
4536        (Ty::TokenClaims, Ty::TokenClaims) => true,
4537        (Ty::ValidationError, Ty::ValidationError) => true,
4538        (Ty::DecodeError, Ty::DecodeError) => true,
4539        (Ty::Unit, Ty::Unit) => true,
4540        // v0.20a: function types — **contravariant** in parameters, covariant
4541        // in the return type. `compatible(t, u, tys)` is "t usable where u is
4542        // expected" and is already asymmetric (refined → base widening), so
4543        // the per-position argument order flips for params: a function
4544        // expecting the *wider* param type is usable where one expecting the
4545        // narrower is required — and crucially, the covariant direction would
4546        // let unvalidated base values flow into a refined-typed body.
4547        (Ty::Fn { params: p, ret: r }, Ty::Fn { params: q, ret: s }) => {
4548            p.len() == q.len()
4549                && p.iter().zip(q).all(|(a, b)| compatible(*b, *a, tys))
4550                && compatible(*r, *s, tys)
4551        }
4552        // v0.20a: rigid type variables (a generic fn's own body) match by
4553        // name. Flexible vars never reach `compatible` — they are eliminated
4554        // by substitution during call-site instantiation.
4555        (Ty::Var(a), Ty::Var(b)) => a == b,
4556        // Everything else is incompatible: cross-variant pairs, and the
4557        // sealed boundary values (`Actor`/`ActorSum` are only ever matched,
4558        // never assigned). The left side is enumerated — no `_` — so adding
4559        // a `Ty` variant fails to compile here instead of silently making
4560        // the new type incompatible with itself (the trap `Query` fell into).
4561        (
4562            Ty::Base(_)
4563            | Ty::Named { .. }
4564            | Ty::Result(..)
4565            | Ty::Option(_)
4566            | Ty::Effect(_)
4567            | Ty::HttpResult(_)
4568            | Ty::HttpOutcome(_)
4569            | Ty::QueueResult
4570            | Ty::BoundaryRejection
4571            | Ty::Asset
4572            | Ty::RequestHeaders
4573            | Ty::RequestQuery
4574            | Ty::RequestCookies
4575            | Ty::TokenClaims
4576            | Ty::List(_)
4577            | Ty::Set(_)
4578            | Ty::Map(..)
4579            | Ty::Query(_)
4580            | Ty::Stream(_)
4581            | Ty::TestConnection(_)
4582            | Ty::Connection(_)
4583            | Ty::ValidationError
4584            | Ty::DecodeError
4585            | Ty::Unit
4586            | Ty::Actor(_)
4587            | Ty::ActorSum(_)
4588            | Ty::Fn { .. }
4589            | Ty::Var(_),
4590            _,
4591        ) => false,
4592    }
4593}
4594
4595/// Check a `do e` statement: the effect-context requirement (when
4596/// `check_context`) and that the operand is an `Effect[T]` whose `T` is not a `Result`
4597/// (ADR 0170 B, amended).
4598pub(super) fn check_do(d: &DoStmt, check_context: bool, ctx: &mut Ctx) {
4599    let tys = ctx.tys;
4600    // v0.146 (ADR 0170): `do e` — perform a unit effect as a
4601    // statement. Effectful context only, like `<-`; nothing is bound.
4602    // Any `Effect[T]` is accepted except a `Result` payload
4603    // (`bynk.effect.do_discards_result`): dropping an `Err` stays explicit
4604    // with `let _ <- e`. Aliases are already resolved in the interned type;
4605    // an opaque `T` in a generic body is accepted.
4606    if check_context && !ctx.effectful {
4607        ctx.errors.push(
4608                        CompileError::new(
4609                            "bynk.effect.do_in_pure_context",
4610                            d.span,
4611                            "the `do` statement can only be used inside an effectful body (one returning `Effect[T]`)",
4612                        )
4613                        .with_label(
4614                            ctx.return_ty_span,
4615                            format!("enclosing return type is `{}`", ctx.return_ty.display(tys)),
4616                        )
4617                        .with_note(
4618                            "change the enclosing function/handler's return type to `Effect[...]`",
4619                        ),
4620                    );
4621    }
4622    let rhs_ty = type_of(&d.value, None, ctx);
4623    check_unbound_effects(&d.value, true, ctx);
4624    match rhs_ty.map(|t| tys.get(t)).as_deref() {
4625        Some(Ty::Effect(inner)) if matches!(*tys.get(*inner), Ty::Result(..)) => {
4626            // The `do` keyword is `d.span.start..d.value.span.start`; the
4627            // quick-fix swaps it for `let _ <- `. Not machine-applicable:
4628            // it silently chooses to discard an `Err`.
4629            let head = Span {
4630                file: d.span.file,
4631                start: d.span.start,
4632                end: d.value.span.start,
4633            };
4634            ctx.errors.push(
4635                CompileError::new(
4636                    "bynk.effect.do_discards_result",
4637                    d.value.span,
4638                    format!(
4639                        "a `do` statement would drop a `Result`: `Effect[{}]`. An `Err` here would be lost without a trace",
4640                        inner.display(tys)
4641                    ),
4642                )
4643                .with_note(
4644                    "bind it and handle the error with `let r <- e` and a `match` (or `?`); to discard it deliberately, write `let _ <- e`, or `do e.detach()` to stop waiting for it and have a failure reported",
4645                )
4646                .with_suggestion(
4647                    "discard the result deliberately with `let _ <- e`",
4648                    vec![(head, "let _ <- ".to_string())],
4649                    Applicability::MaybeIncorrect,
4650                ),
4651            );
4652        }
4653        Some(Ty::Effect(_)) => {}
4654        Some(other) => {
4655            ctx.errors.push(
4656                CompileError::new(
4657                    "bynk.effect.do_on_non_effect",
4658                    d.value.span,
4659                    format!(
4660                        "a `do` statement requires an `Effect[T]` value, but got `{}`",
4661                        other.display(tys)
4662                    ),
4663                )
4664                .with_note(
4665                    "`do` performs an effect; its operand must be a call returning `Effect[T]`",
4666                ),
4667            );
4668        }
4669        None => {}
4670    }
4671}
4672
4673/// How [`Ty::Never`] reads in a message or hover. It is not source syntax, so
4674/// no inlay hint or inserted annotation may carry it (#2727).
4675pub const NEVER_DISPLAY: &str = "never returns";
4676
4677/// #2727: the diagnostic for an unannotated binding or lambda result whose
4678/// inferred type is the bottom type, which would otherwise stand in for any type.
4679pub(super) fn never_inferred(span: Span, what: &str, ty: &str, hint: &str) -> CompileError {
4680    CompileError::new(
4681        "bynk.types.never_inferred",
4682        span,
4683        format!("{what} would have the type `{ty}`, which cannot be named in source"),
4684    )
4685    .with_note(hint)
4686}
4687
4688/// #2727: whether `t` is, or is built from, the bottom type, so a binding of it
4689/// would stand in for any type.
4690pub(crate) fn contains_never(t: TyId, tys: &Types) -> bool {
4691    match &*tys.get(t) {
4692        Ty::Never => true,
4693        Ty::Result(a, b) | Ty::Map(a, b) => contains_never(*a, tys) || contains_never(*b, tys),
4694        Ty::Option(a)
4695        | Ty::Effect(a)
4696        | Ty::HttpResult(a)
4697        | Ty::HttpOutcome(a)
4698        | Ty::List(a)
4699        | Ty::Set(a)
4700        | Ty::Query(a)
4701        | Ty::Stream(a)
4702        | Ty::TestConnection(a)
4703        | Ty::Connection(a) => contains_never(*a, tys),
4704        Ty::Fn { params, ret } => {
4705            params.iter().any(|p| contains_never(*p, tys)) || contains_never(*ret, tys)
4706        }
4707        Ty::Named { args, .. } => args.iter().any(|a| contains_never(*a, tys)),
4708        _ => false,
4709    }
4710}
4711
4712/// Check one `let x <- e` binding: the effect-context requirement (when
4713/// `check_context`), the annotation, the `Effect[T]` payload and the call-site
4714/// principal. Returns the bound type, or `None` when the value failed to type
4715/// (already reported). Binding the name is the caller's job, so a `par` block can
4716/// bind its names only after every binding is checked.
4717pub(super) fn check_effect_let(l: &LetStmt, check_context: bool, ctx: &mut Ctx) -> Option<TyId> {
4718    let tys = ctx.tys;
4719    if check_context && !ctx.effectful {
4720        ctx.errors.push(
4721                CompileError::new(
4722                    "bynk.effect.bind_in_pure_context",
4723                    l.span,
4724                    "the `<-` operator can only be used inside an effectful body (one returning `Effect[T]`)",
4725                )
4726                .with_label(
4727                    ctx.return_ty_span,
4728                    format!("enclosing return type is `{}`", ctx.return_ty.display(tys)),
4729                )
4730                .with_note(
4731                    "change the enclosing function/handler's return type to `Effect[...]`, or use `let ... =` for a pure binding",
4732                ),
4733            );
4734    }
4735    // Determine the inner Effect[T] payload type for the binding.
4736    let annot_ty = l.type_annot.as_ref().and_then(|a| {
4737        // v0.20b: the enclosing fn's type parameters are legal
4738        // in body annotations (`let init: List[B] = …`).
4739        let r = resolve_type_ref_in(a, &ctx.input.types, &ctx.type_vars, tys);
4740        if r.is_none() {
4741            ctx.errors.push(CompileError::new(
4742                "bynk.resolve.unknown_type",
4743                a.span(),
4744                "type in `let` annotation does not resolve",
4745            ));
4746        } else {
4747            record_type_refs(a, &ctx.input.types, &ctx.type_vars, ctx.refs);
4748        }
4749        r
4750    });
4751    // The expected type for the RHS is `Effect[annot]` if annot present.
4752    let rhs_expected = annot_ty.map(|t| tys.intern(Ty::Effect(t)));
4753    let mut rhs_ty = type_of(&l.value, rhs_expected, ctx);
4754    // #1934: a test-service address driven `by Nobody` observes the
4755    // auth seam, so it yields an `HttpOutcome`. The principal is on
4756    // the statement, so the call alone cannot say so.
4757    if l.principal
4758        .as_ref()
4759        .is_some_and(|p| calls::record_principal(p, ctx).is_reserved())
4760        && let Some(t) = rhs_ty
4761    {
4762        let t = calls::nobody_outcome(&l.value, t, ctx);
4763        if let Some(te) = ctx.expr_types.get_mut(&l.value.id) {
4764            te.ty = t;
4765        }
4766        rhs_ty = Some(t);
4767    }
4768    check_unbound_effects(&l.value, true, ctx);
4769    // v0.182 (#664): validate the call-site principal against the
4770    // addressed handler — including the *absent* case, where an
4771    // identity-carrying handler driven with no `by` would silently
4772    // drop the identity.
4773    calls::check_effect_let_principal(&l.value, l.principal.as_ref(), ctx);
4774    let inner_ty = match rhs_ty.map(|t| tys.get(t)).as_deref() {
4775        Some(Ty::Effect(t)) => Some(*t),
4776        // #2620 (DECISION F): `x <- todo(…)` — the bottom type is usable where an
4777        // `Effect[T]` is, and the bind faults when it runs; `x` is `Never` too.
4778        Some(Ty::Never) => rhs_ty,
4779        Some(_) => {
4780            ctx.errors.push(
4781                CompileError::new(
4782                    "bynk.effect.bind_on_non_effect",
4783                    l.value.span,
4784                    format!(
4785                        "the `<-` operator requires an `Effect[T]` value, but got `{}`",
4786                        rhs_ty.expect("matched Some").display(tys)
4787                    ),
4788                )
4789                .with_note(
4790                    "use `let ... =` for a pure binding, or wrap the value with `Effect.pure(...)`",
4791                ),
4792            );
4793            None
4794        }
4795        None => None,
4796    };
4797    let final_ty = match (annot_ty, inner_ty) {
4798        (Some(annot), Some(rhs)) => {
4799            if !compatible(rhs, annot, tys) {
4800                ctx.errors.push(CompileError::new(
4801                        "bynk.types.let_annotation_mismatch",
4802                        l.value.span,
4803                        format!(
4804                            "let-binding's value has type `Effect[{}]`, but the annotation declares `Effect[{}]`",
4805                            rhs.display(tys),
4806                            annot.display(tys)
4807                        ),
4808                    ));
4809            }
4810            annot
4811        }
4812        (Some(annot), None) => annot,
4813        (None, Some(rhs)) if contains_never(rhs, tys) && l.name.name != "_" => {
4814            ctx.errors.push(never_inferred(
4815                l.value.span,
4816                &format!("`{}`", l.name.name),
4817                &rhs.display(tys),
4818                "annotate the binding (`let x: T <- …`); for a lambda, annotate it with a function type (`let f: (Int) -> T = …`)",
4819            ));
4820            return None;
4821        }
4822        (None, Some(rhs)) => rhs,
4823        // #1663: the value failed to type (already reported).
4824        // Bind the name to the error type anyway, so its uses
4825        // absorb instead of echoing as unknown names.
4826        (None, None) => return None,
4827    };
4828    Some(final_ty)
4829}
4830
4831/// Bind a checked `let x <- e`'s name in the innermost scope and record its inlay
4832/// hint and local, visible from `scope_start` to `scope_end`.
4833pub(super) fn bind_effect_let(
4834    l: &LetStmt,
4835    final_ty: TyId,
4836    scope_start: usize,
4837    scope_end: usize,
4838    ctx: &mut Ctx,
4839) {
4840    let tys = ctx.tys;
4841    if l.name.name != "_" {
4842        // v0.27 (ADR 0056): as for `let =`, but `final_ty` here
4843        // is the peeled `Effect[T]` payload — the binding's
4844        // actual type, which is what the hint must show.
4845        // #2010: a `let … else`'s hidden binder is not the author's
4846        // name, so it gets no inlay hint and no entry in the locals.
4847        if !is_generated_binding(&l.name.name) {
4848            if l.type_annot.is_none() {
4849                ctx.hints
4850                    .record(l.name.span, format!(": {}", final_ty.display(tys)));
4851            }
4852            ctx.locals.record(
4853                l.name.name.clone(),
4854                l.name.span,
4855                crate::locals::LocalKind::Let,
4856                final_ty.display(tys),
4857                Span {
4858                    file: l.span.file,
4859                    start: scope_start,
4860                    end: scope_end,
4861                },
4862            );
4863        }
4864        ctx.bind(l.name.name.clone(), final_ty);
4865        d1::link_effect_let(l, ctx);
4866    }
4867}
4868
4869pub(crate) fn type_of_block(block: &Block, expected: Option<TyId>, ctx: &mut Ctx) -> Option<TyId> {
4870    let tys = ctx.tys;
4871    ctx.push_scope();
4872    for stmt in &block.statements {
4873        if let Statement::Let(l) | Statement::EffectLet(l) = stmt
4874            && let Some(le) = &l.let_else
4875            && !le.remove_else.is_empty()
4876        {
4877            ctx.let_else_removals
4878                .insert(l.name.name.clone(), le.remove_else.clone());
4879        }
4880        match stmt {
4881            Statement::Let(l) => {
4882                if l.type_annot.is_none()
4883                    && l.let_else.is_none()
4884                    && matches!(l.value.kind, ExprKind::Question(_))
4885                {
4886                    ctx.question_let_binders
4887                        .insert(l.value.span, (l.name.span, l.name.name.clone()));
4888                }
4889                let annot_ty = l.type_annot.as_ref().and_then(|a| {
4890                    // v0.20b: the enclosing fn's type parameters are legal
4891                    // in body annotations (`let init: List[B] = …`).
4892                    let r = resolve_type_ref_in(a, &ctx.input.types, &ctx.type_vars, tys);
4893                    if r.is_none() {
4894                        ctx.errors.push(CompileError::new(
4895                            "bynk.resolve.unknown_type",
4896                            a.span(),
4897                            "type in `let` annotation does not resolve",
4898                        ));
4899                    } else {
4900                        record_type_refs(a, &ctx.input.types, &ctx.type_vars, ctx.refs);
4901                    }
4902                    r
4903                });
4904                peek::expect_let(&l.value, ctx);
4905                let rhs_ty = type_of(&l.value, annot_ty, ctx);
4906                par::note_let_lambda(l, ctx);
4907                check_unbound_effects(&l.value, false, ctx);
4908                let final_ty = match (annot_ty, rhs_ty) {
4909                    (Some(annot), Some(rhs)) => {
4910                        if !compatible(rhs, annot, tys) {
4911                            ctx.errors.push(
4912                                CompileError::new(
4913                                    "bynk.types.let_annotation_mismatch",
4914                                    l.value.span,
4915                                    format!(
4916                                        "let binding's value has type `{}`, but the annotation declares `{}`",
4917                                        rhs.display(tys),
4918                                        annot.display(tys)
4919                                    ),
4920                                )
4921                                .with_label(
4922                                    l.type_annot.as_ref().unwrap().span(),
4923                                    "declared type annotation",
4924                                ),
4925                            );
4926                        }
4927                        annot
4928                    }
4929                    (Some(annot), None) => annot,
4930                    // #2727: with no annotation the binding would be `Never`,
4931                    // assignable anywhere. Bind it to the error type instead.
4932                    (None, Some(rhs)) if contains_never(rhs, tys) && l.name.name != "_" => {
4933                        ctx.errors.push(never_inferred(
4934                            l.value.span,
4935                            &format!("`{}`", l.name.name),
4936                            &rhs.display(tys),
4937                            "annotate the binding (`let x: T = …`); for a lambda, annotate it with a function type (`let f: (Int) -> T = …`)",
4938                        ));
4939                        ctx.bind(l.name.name.clone(), tys.intern(Ty::Error));
4940                        continue;
4941                    }
4942                    (None, Some(rhs)) => rhs,
4943                    // #1663: the value failed to type (already reported).
4944                    // Bind the name to the error type anyway, so its uses
4945                    // absorb instead of echoing as unknown names.
4946                    (None, None) => {
4947                        if l.name.name != "_" {
4948                            ctx.bind(l.name.name.clone(), tys.intern(Ty::Error));
4949                        }
4950                        continue;
4951                    }
4952                };
4953                if l.name.name != "_" {
4954                    // #2010: a `let … else`'s hidden binder is not the author's
4955                    // name, so it gets no inlay hint and no entry in the locals.
4956                    if !is_generated_binding(&l.name.name) {
4957                        // v0.27 (ADR 0056): an annotation-absent binding gets an
4958                        // inferred-type inlay hint at the binding name.
4959                        if l.type_annot.is_none() {
4960                            ctx.hints
4961                                .record(l.name.span, format!(": {}", final_ty.display(tys)));
4962                        }
4963                        // v0.31: in scope from after this statement to block end.
4964                        ctx.locals.record(
4965                            l.name.name.clone(),
4966                            l.name.span,
4967                            crate::locals::LocalKind::Let,
4968                            final_ty.display(tys),
4969                            Span {
4970                                file: l.span.file,
4971                                start: l.span.end,
4972                                end: block.span.end,
4973                            },
4974                        );
4975                    }
4976                    ctx.bind(l.name.name.clone(), final_ty);
4977                    if l.let_else.is_none()
4978                        && let ExprKind::ListLit(items, ..) = &l.value.kind
4979                    {
4980                        let depth = ctx.scopes.len() - 1;
4981                        ctx.list_lens
4982                            .insert((depth, l.name.name.clone()), items.len());
4983                    }
4984                }
4985            }
4986            Statement::EffectLet(l) => {
4987                let Some(final_ty) = check_effect_let(l, true, ctx) else {
4988                    // #1663: the value failed to type (already reported).
4989                    // Bind the name to the error type anyway, so its uses
4990                    // absorb instead of echoing as unknown names.
4991                    if l.name.name != "_" {
4992                        ctx.bind(l.name.name.clone(), tys.intern(Ty::Error));
4993                    }
4994                    continue;
4995                };
4996                bind_effect_let(l, final_ty, l.span.end, block.span.end, ctx);
4997            }
4998            Statement::Expect(a) => {
4999                if !ctx.in_test_body {
5000                    ctx.errors.push(
5001                        CompileError::new(
5002                            "bynk.expect.outside_case",
5003                            a.span,
5004                            "`expect` is only valid inside a `case` body",
5005                        )
5006                        .with_note(
5007                            "expectations verify predicates at test runtime; use them only inside `case \"...\" { ... }` blocks",
5008                        ),
5009                    );
5010                }
5011                if let Some(clause) = &a.snapshot {
5012                    // #2842: a snapshot compares the value's canonical JSON, so
5013                    // the value need only be `Codable` (the domain `Json.encode`
5014                    // accepts), not a `Bool`.
5015                    if let Some(actual) = type_of(&a.value, None, ctx)
5016                        && (!codable::json_codable(actual, &ctx.input.types, tys, &ctx.type_vars)
5017                            || actual == tys.intern(Ty::Unit))
5018                    {
5019                        let mut err = CompileError::new(
5020                            "bynk.test.snapshot_not_codable",
5021                            a.value.span,
5022                            format!(
5023                                "a snapshot stores the value as JSON, but `{}` is not `Codable`",
5024                                actual.display(tys),
5025                            ),
5026                        )
5027                        .with_label(clause.span, "snapshotted here")
5028                        .with_note(
5029                            "`Codable` types are the ones `Json.encode` accepts: base types, named types, and the built-in containers over them — not `()`, functions, effects, streams, or `bynk.crypto` keys",
5030                        );
5031                        if let Some(n) = codable::key_note(actual, &ctx.input.types, tys) {
5032                            err = err.with_note(n);
5033                        }
5034                        ctx.errors.push(err);
5035                    }
5036                    continue;
5037                }
5038                let typed_errors = ctx.errors.len();
5039                let val_ty = type_of(&a.value, Some(tys.intern(Ty::Base(BaseType::Bool))), ctx);
5040                if predicate_typed_clean(val_ty, typed_errors, ctx)
5041                    && let Some(span) = effect_in_predicate(&a.value, ctx.expr_types, tys)
5042                {
5043                    ctx.errors.push(expect_impure_error(span));
5044                }
5045                if let Some(actual) = val_ty
5046                    && !compatible(actual, tys.intern(Ty::Base(BaseType::Bool)), tys)
5047                {
5048                    ctx.errors.push(CompileError::new(
5049                        "bynk.expect.not_bool",
5050                        a.value.span,
5051                        format!(
5052                            "`expect` predicate has type `{}`, but a `Bool` is required",
5053                            actual.display(tys),
5054                        ),
5055                    ));
5056                }
5057            }
5058            Statement::Advance(a) => check_advance(a, ctx),
5059            Statement::Par(p) => par::check_par(p, block.span.end, ctx),
5060            Statement::Do(d) => check_do(d, true, ctx),
5061            Statement::Assign(a) => {
5062                // v0.81 (storage track): `cell := expr` — the unconditional `Cell`
5063                // write. The target must be a `store Cell` field; the value must
5064                // match the cell's element type; and (the §10 read-modify-write
5065                // rule) the RHS must not read the cell being written.
5066                match ctx.store_fields.get(&a.target.name).cloned() {
5067                    // A name that isn't a store field at all, or is one of a
5068                    // different kind, is the same "not a Cell" diagnostic.
5069                    None
5070                    | Some(
5071                        StoreField::Map(..)
5072                        | StoreField::Set(_)
5073                        | StoreField::Cache(..)
5074                        | StoreField::Log(_),
5075                    ) => {
5076                        ctx.errors.push(
5077                            CompileError::new(
5078                                "bynk.cell.invalid_target",
5079                                a.target.span,
5080                                format!(
5081                                    "`:=` writes a `Cell` store field, but `{}` is not one",
5082                                    a.target.name
5083                                ),
5084                            )
5085                            .with_note(
5086                                "the `:=` write form applies only to a `store <name>: Cell[T]` field",
5087                            ),
5088                        );
5089                        type_of(&a.value, None, ctx);
5090                    }
5091                    Some(StoreField::Cell(elem_ty)) => {
5092                        // §10: a `:=` whose RHS reads its own LHS is a hidden
5093                        // read-modify-write — require `.update(fn)` instead, so the
5094                        // dependency is visible (and retry-safe).
5095                        if expr_reads_ident(&a.value, &a.target.name) {
5096                            ctx.errors.push(
5097                                CompileError::new(
5098                                    "bynk.cell.self_reference",
5099                                    a.span,
5100                                    format!(
5101                                        "the `:=` right-hand side reads `{0}`, the cell being \
5102                                         written — this is a read-modify-write",
5103                                        a.target.name
5104                                    ),
5105                                )
5106                                .with_note(
5107                                    "use `<cell>.update(fn)` for a read-modify-write so the \
5108                                     dependency on the prior value is explicit",
5109                                ),
5110                            );
5111                        }
5112                        if let Some(vt) = type_of(&a.value, Some(elem_ty), ctx)
5113                            && !compatible(vt, elem_ty, tys)
5114                        {
5115                            ctx.errors.push(CompileError::new(
5116                                "bynk.types.type_mismatch",
5117                                a.value.span,
5118                                format!(
5119                                    "this `:=` writes `{}`, but the cell `{}` holds `{}`",
5120                                    vt.display(tys),
5121                                    a.target.name,
5122                                    elem_ty.display(tys)
5123                                ),
5124                            ));
5125                        }
5126                    }
5127                }
5128            }
5129        }
5130    }
5131    let ty = type_of(&block.tail, expected, ctx);
5132    check_unbound_effects(&block.tail, true, ctx);
5133    let ty = maybe_auto_lift(ty, expected, tys);
5134    // T3.4: this block previously wrote its own auto-lifted type into
5135    // `expr_types` at `block.span` (bug #844's era — recording it only when
5136    // `block.span != block.tail.span`, to avoid clobbering a synthetic
5137    // single-expression block's more specific tail entry). `Block` has no
5138    // `ExprId` of its own to key that write with now, and — checked, not
5139    // assumed — nothing in the workspace ever read it: the only caller that
5140    // has a real enclosing expression to attribute it to (`ExprKind::Block`,
5141    // `checker.rs`'s own `type_of` dispatch) already gets an identical entry
5142    // for free from `type_of`'s own choke-point write on the way back out,
5143    // since the parser sets that expression's span to `block.span` exactly.
5144    // The other eight callers (function/handler bodies, `if` branches,
5145    // `match` arm bodies) never had a real position to attribute it to
5146    // either, span-keyed or not. Dropped rather than worked around.
5147    ctx.pop_scope();
5148    ty
5149}
5150
5151/// v0.7.1 tail-position auto-lift. If the expected type is `Effect[T]` and
5152/// the computed type is `T` (not itself an `Effect[_]`), lift it to
5153/// `Effect[T]`. Otherwise leave the type alone — the surrounding compatibility
5154/// check will report any genuine mismatch.
5155fn maybe_auto_lift(ty: Option<TyId>, expected: Option<TyId>, tys: &Types) -> Option<TyId> {
5156    if let Some(actual) = ty
5157        && let Some(exp) = expected
5158        && let Ty::Effect(et) = &*tys.get(exp)
5159        && !actual.is_effect(tys)
5160        && compatible(actual, *et, tys)
5161    {
5162        return Some(tys.intern(Ty::Effect(actual)));
5163    }
5164    ty
5165}
5166
5167/// Whether a value of type `ty` may fill an interpolation hole (v0.43, ADR
5168/// 0075): a scalar base — `String`/`Int`/`Float`/`Bool`, or `Decimal` (ADR
5169/// 0698: its canonical text) — or a refinement of one (which widens to its base
5170/// for display). `Bytes`, `Duration` and `Instant` have no implicit string form
5171/// — each has an explicit rendering method — and opaque types are excluded,
5172/// their base being hidden (`.raw` it first).
5173fn interpolable(ty: TyId, tys: &Types) -> bool {
5174    let scalar = |b: BaseType| {
5175        matches!(
5176            b,
5177            BaseType::String | BaseType::Int | BaseType::Float | BaseType::Bool | BaseType::Decimal
5178        )
5179    };
5180    match &*tys.get(ty) {
5181        Ty::Base(b) => scalar(*b),
5182        Ty::Named {
5183            kind: NamedKind::Refined(b),
5184            ..
5185        } => scalar(*b),
5186        _ => false,
5187    }
5188}
5189
5190pub(crate) fn type_of(expr: &Expr, expected: Option<TyId>, ctx: &mut Ctx) -> Option<TyId> {
5191    let tys = ctx.tys;
5192    let admitted = ctx.admitted_literals.get(&expr.id).copied();
5193    let ty = match &expr.kind {
5194        // #2039: a literal a cross-context argument already admitted to the
5195        // callee's refined type at its position.
5196        _ if admitted.is_some() => admitted,
5197        // v0.9.4: a literal in a refined-expected position takes the refined
5198        // type (validated now); otherwise it keeps its base type.
5199        // v0.20a: a lambda. With an expected function type, params type
5200        // contextually and the body checks against the expected return; in an
5201        // unconstrained position, every param must be annotated and
5202        // effectfulness is inferred bottom-up by a syntactic pre-scan.
5203        ExprKind::Lambda(lambda) => check_lambda(lambda, expected, ctx),
5204        ExprKind::IntLit { .. } => {
5205            admit_refined_literal(expr, expected, ctx).or(Some(tys.intern(Ty::Base(BaseType::Int))))
5206        }
5207        ExprKind::FloatLit { .. } => admit_refined_literal(expr, expected, ctx)
5208            .or(Some(tys.intern(Ty::Base(BaseType::Float)))),
5209        // #2622: a `Decimal` literal, admitted into a refined `Decimal` type
5210        // like any other literal.
5211        ExprKind::DecimalLit { .. } => admit_refined_literal(expr, expected, ctx)
5212            .or(Some(tys.intern(Ty::Base(BaseType::Decimal)))),
5213        // v0.86 (ADR 0112): a `Duration` literal always takes the base
5214        // `Duration` (no refined `Duration` types exist).
5215        ExprKind::DurationLit { .. } => Some(tys.intern(Ty::Base(BaseType::Duration))),
5216        ExprKind::StrLit(_) => admit_refined_literal(expr, expected, ctx)
5217            .or(Some(tys.intern(Ty::Base(BaseType::String)))),
5218        // An interpolated string (v0.43, ADR 0075). Each hole must type to a
5219        // base scalar (String/Int/Float/Bool) or a *refinement* of one — those
5220        // have a well-defined display form (Int/Float via the ADR 0074
5221        // `toString` contract, Bool as `true`/`false`; a refined value widens
5222        // to its base, e.g. `Subject` displays as its `String`). Records,
5223        // sums, opaque types (whose base is deliberately hidden — `.raw` it
5224        // first), and other types are rejected, foreclosing JS's
5225        // `[object Object]` footgun. The result is always a `String`.
5226        ExprKind::InterpStr(parts) => {
5227            for part in parts {
5228                let InterpPart::Hole(hole) = part else {
5229                    continue;
5230                };
5231                match type_of(hole, None, ctx) {
5232                    Some(ty) if interpolable(ty, tys) => {}
5233                    Some(other) => ctx.errors.push(
5234                        CompileError::new(
5235                            "bynk.types.interpolation_non_scalar",
5236                            hole.span,
5237                            format!("type `{}` has no string form here", other.display(tys)),
5238                        )
5239                        .with_note(interpolation_non_scalar_note(other, tys)),
5240                    ),
5241                    // The hole already produced its own error — don't pile on.
5242                    None => {}
5243                }
5244            }
5245            Some(tys.intern(Ty::Base(BaseType::String)))
5246        }
5247        ExprKind::BoolLit(_) => Some(tys.intern(Ty::Base(BaseType::Bool))),
5248        // v0.20b: a list literal. Elements check against the expected
5249        // element type when one is supplied (so refined literals admit,
5250        // v0.9.4); an empty `[]` has no inferable element type without one.
5251        ExprKind::ListLit(elems, ..) => {
5252            let expected_elem = expected.and_then(|t| peel_to_list(t, tys));
5253            if elems.is_empty() {
5254                match expected_elem {
5255                    Some(t) => Some(tys.intern(Ty::List(t))),
5256                    None => {
5257                        ctx.errors.push(
5258                            CompileError::new(
5259                                "bynk.types.uninferable_element_type",
5260                                expr.span,
5261                                "an empty `[]` has no inferable element type",
5262                            )
5263                            .with_note(
5264                                "annotate the binding (`let xs: List[T] = []`) or use the empty list where a `List[T]` is expected",
5265                            ),
5266                        );
5267                        None
5268                    }
5269                }
5270            } else {
5271                // An expected element type still mentioning a flexible
5272                // variable of an enclosing generic call (`size([1, 2])` against
5273                // `List[T]`) carries nothing yet: type the elements bottom-up
5274                // and let the call unify `T` from the result.
5275                let flexible =
5276                    expected_elem.is_some_and(|t| contains_flexible_var(t, &ctx.type_vars, tys));
5277                let mut elem_ty: Option<TyId> = expected_elem.filter(|_| !flexible);
5278                // Elements that only take their type from context (`None`,
5279                // `[]`, ...) wait for a sibling to supply it (`[None, Some(1)]`).
5280                let mut deferred: Vec<&Expr> = Vec::new();
5281                for e in elems {
5282                    if flexible && elem_ty.is_none() && needs_expected_type(e) {
5283                        deferred.push(e);
5284                        continue;
5285                    }
5286                    let Some(t) = type_of(e, elem_ty, ctx) else {
5287                        continue;
5288                    };
5289                    match &elem_ty {
5290                        Some(et) => {
5291                            if !compatible(t, *et, tys) {
5292                                ctx.errors.push(CompileError::new(
5293                                    "bynk.types.list_element_mismatch",
5294                                    e.span,
5295                                    format!(
5296                                        "list element has type `{}`, but the list's element type is `{}`",
5297                                        t.display(tys),
5298                                        et.display(tys)
5299                                    ),
5300                                ));
5301                            }
5302                        }
5303                        None => elem_ty = Some(t),
5304                    }
5305                }
5306                for e in deferred {
5307                    // No sibling supplied a type: the first deferred element
5308                    // falls back to the flexible expected one, which the call
5309                    // then unifies (or reports as uninferable).
5310                    let want = elem_ty.or(expected_elem);
5311                    let Some(t) = type_of(e, want, ctx) else {
5312                        continue;
5313                    };
5314                    match elem_ty {
5315                        Some(et) => {
5316                            // A sibling still mentioning a flexible variable
5317                            // (`Result[Int, E]`) is merged rather than
5318                            // compared by name; the call unifies the result.
5319                            match merge_open(et, t, &ctx.type_vars, tys) {
5320                                Some(m) => elem_ty = Some(m),
5321                                None => ctx.errors.push(CompileError::new(
5322                                    "bynk.types.list_element_mismatch",
5323                                    e.span,
5324                                    format!(
5325                                        "list element has type `{}`, but the list's element type is `{}`",
5326                                        t.display(tys),
5327                                        et.display(tys)
5328                                    ),
5329                                )),
5330                            }
5331                        }
5332                        None => elem_ty = Some(t),
5333                    }
5334                }
5335                elem_ty.map(|t| tys.intern(Ty::List(t)))
5336            }
5337        }
5338        ExprKind::Ident(id) => {
5339            // v0.94 (ADR 0120): a bare `store Map` ident used as a **value** — not
5340            // a method receiver, which the `MethodCall` arm dispatches — is a lazy
5341            // `Query[V]` over the whole map (e.g. the `other` side of a join). It
5342            // is not in the value scope, so it never shadows a local.
5343            if ctx.lookup(id.name.as_str()).is_none()
5344                && let Some(StoreField::Map(_, v)) = ctx.store_fields.get(&id.name).cloned()
5345            {
5346                Some(tys.intern(Ty::Query(v)))
5347            }
5348            // v0.9: a bare ident may name an HttpResult variant. Resolve to
5349            // HttpResult only when (a) the surrounding type implies it, or
5350            // (b) no user sum-type variant of the same name exists. This
5351            // keeps `NotFound` resolving to a user `StockError` variant
5352            // when the caller expects a domain Result.
5353            else if ctx.lookup(id.name.as_str()).is_none()
5354                && let Some(v) = http_variant(&id.name)
5355            {
5356                let user_owns = user_sum_owns_variant(ctx, &id.name);
5357                if http_variant_applies(user_owns, expected, ctx) {
5358                    // P6.21/P6.23 (review of #1244/#1247): `Callee::Intrinsic`
5359                    // recorded here — a namespace-qualified built-in-sum
5360                    // variant reference, the shape P6.1's Decision C had
5361                    // excluded from bare-global resolution until a sink like
5362                    // this existed for it.
5363                    ctx.callees
5364                        .insert(expr.id, Callee::intrinsic(StaticOp::HttpResult(v)));
5365                    check_http_variant(id.span, v, &[], expected, ctx)
5366                } else {
5367                    check_ident_at(expr.id, id, expected, ctx)
5368                }
5369            } else if ctx.lookup(id.name.as_str()).is_none()
5370                && let Some(qv) = queue_variant(&id.name)
5371                && (expected.is_some_and(|t| peel_to_queue_result(t, tys))
5372                    || peel_to_queue_result(ctx.return_ty, tys))
5373            {
5374                // v0.44: a bare QueueResult variant (`Ack`) in a queue handler.
5375                ctx.callees
5376                    .insert(expr.id, Callee::intrinsic(StaticOp::QueueResult(qv)));
5377                check_queue_variant(id.span, qv, &[], ctx)
5378            } else {
5379                check_ident_at(expr.id, id, expected, ctx)
5380            }
5381        }
5382        ExprKind::Paren(inner) => type_of(inner, expected, ctx),
5383        ExprKind::Call {
5384            name,
5385            type_args,
5386            args,
5387            ..
5388        } => {
5389            // v0.9: HttpResult variant call. Prefer HttpResult when the
5390            // surrounding type implies it; otherwise defer to fn/user-variant
5391            // resolution and only fall back to HttpResult when nothing else
5392            // owns the name.
5393            //
5394            // `http_variant`/`queue_variant` are cheap keyword lookups; gate
5395            // the expensive context peel and — above all — the O(types×variants)
5396            // scan for user sum-variant owners behind them. The common case is
5397            // an ordinary function call whose name is neither keyword, so it
5398            // must not pay for either. The owner scan is further deferred behind
5399            // `http_variant_applies`, since ownership only matters when the surrounding
5400            // type does not already imply HttpResult.
5401            if let Some(v) = http_variant(&name.name) {
5402                let owned_elsewhere = ctx.input.fns.contains_key(&name.name)
5403                    || user_sum_owns_variant(ctx, &name.name);
5404                if http_variant_applies(owned_elsewhere, expected, ctx) {
5405                    ctx.callees
5406                        .insert(expr.id, Callee::intrinsic(StaticOp::HttpResult(v)));
5407                    check_http_variant(expr.span, v, args, expected, ctx)
5408                } else {
5409                    // Falling straight to `check_call` (rather than the
5410                    // `queue_variant` else-if below) relies on the http and
5411                    // queue variant keyword sets being disjoint, so an http
5412                    // name could never have taken the queue branch anyway.
5413                    check_call(name, type_args, args, expr.span, expected, expr.id, ctx)
5414                }
5415            } else if let Some(qv) = queue_variant(&name.name)
5416                && (expected.is_some_and(|t| peel_to_queue_result(t, tys))
5417                    || peel_to_queue_result(ctx.return_ty, tys))
5418            {
5419                // v0.44: a QueueResult variant call (`Retry(reason)`).
5420                ctx.callees
5421                    .insert(expr.id, Callee::intrinsic(StaticOp::QueueResult(qv)));
5422                check_queue_variant(expr.span, qv, args, ctx)
5423            } else {
5424                check_call(name, type_args, args, expr.span, expected, expr.id, ctx)
5425            }
5426        }
5427        ExprKind::UnaryOp(op, inner) => check_unary(*op, inner, expr.span, ctx),
5428        ExprKind::BinOp(op, lhs, rhs) => check_binop(*op, lhs, rhs, ctx),
5429        ExprKind::Block(b) => type_of_block(b, expected, ctx),
5430        ExprKind::If {
5431            cond,
5432            then_block,
5433            else_block,
5434        } => check_if(cond, then_block, else_block, expr.span, expected, ctx),
5435        ExprKind::Ok(inner) => check_ok(inner, expr.span, expected, ctx),
5436        ExprKind::Err(inner) => check_err(inner, expr.span, expected, ctx),
5437        ExprKind::Some(inner) => check_some(inner, expr.span, expected, ctx),
5438        ExprKind::None => check_none(expr.span, expected, ctx),
5439        ExprKind::Question(inner) => check_question(inner, expr.span, ctx),
5440        ExprKind::RecordConstruction {
5441            type_name, fields, ..
5442        } => {
5443            let ty = check_record_construction(type_name, fields, expected, expr.span, ctx)?;
5444            // P4c (#2628): a `SqlStatement`'s `sql` is a literal.
5445            d1::check_statement_fields(ty, fields, ctx);
5446            Some(ty)
5447        }
5448        ExprKind::FieldAccess { receiver, field } if is_run_id(receiver, field, ctx) => {
5449            // #2138 (track §3.7): `run.id`, the test run's identity, in a test
5450            // body where nothing else is named `run`.
5451            ctx.callees.insert(
5452                expr.id,
5453                Callee::intrinsic(StaticOp::TestRun(TestRunStatic::Id)),
5454            );
5455            Some(tys.intern(Ty::Base(BaseType::String)))
5456        }
5457        ExprKind::FieldAccess { receiver, field } => {
5458            // #2622: `RoundingMode.X` names a mode only as the mode argument of
5459            // a `Decimal` `round`/`div`; anywhere else it has no value.
5460            if let ExprKind::Ident(id) = &receiver.kind
5461                && id.name == "RoundingMode"
5462                && ctx.lookup(id.name.as_str()).is_none()
5463                && !ctx.input.types.contains_key(id.name.as_str())
5464            {
5465                ctx.errors.push(
5466                    CompileError::new(
5467                        "bynk.types.rounding_mode_position",
5468                        expr.span,
5469                        format!(
5470                            "`RoundingMode.{}` names a mode only as the mode argument of a `Decimal`'s `round` or `div`",
5471                            field.name
5472                        ),
5473                    )
5474                    .with_note("write the mode where the rounding happens: `price.round(2, RoundingMode.HalfEven)`"),
5475                );
5476                return None;
5477            }
5478            // #2341 (L4): `ErrorStatus.X` is a `RawError` status, read
5479            // syntactically at that argument; anywhere else it has no value.
5480            if let ExprKind::Ident(id) = &receiver.kind
5481                && id.name == "ErrorStatus"
5482                && ctx.lookup(id.name.as_str()).is_none()
5483                && !ctx.input.types.contains_key(id.name.as_str())
5484            {
5485                ctx.errors.push(
5486                    CompileError::new(
5487                        "bynk.http.error_status_position",
5488                        expr.span,
5489                        format!(
5490                            "`ErrorStatus.{}` names a status only as `RawError`'s first argument",
5491                            field.name
5492                        ),
5493                    )
5494                    .with_note("write the status where the response is built: `RawError(ErrorStatus.Forbidden, body, contentType)`; a helper can build the body"),
5495                );
5496                return None;
5497            }
5498            // v0.9: `HttpResult.Variant` qualified nullary variant access.
5499            if let ExprKind::Ident(id) = &receiver.kind
5500                && ctx.lookup(id.name.as_str()).is_none()
5501                && id.name == HTTP_RESULT
5502            {
5503                if let Some(v) = http_variant(&field.name) {
5504                    if !matches!(v.payload, HttpVariantPayload::None) {
5505                        ctx.errors.push(CompileError::new(
5506                            "bynk.types.variant_missing_payload",
5507                            field.span,
5508                            format!(
5509                                "`HttpResult.{}` has a payload — call it with an argument",
5510                                v.name
5511                            ),
5512                        ));
5513                        return None;
5514                    }
5515                    ctx.callees
5516                        .insert(expr.id, Callee::intrinsic(StaticOp::HttpResult(v)));
5517                    check_http_variant(field.span, v, &[], expected, ctx)
5518                } else {
5519                    ctx.errors.push(CompileError::new(
5520                        "bynk.types.unknown_static_member",
5521                        field.span,
5522                        format!("`HttpResult` has no variant named `{}`", field.name),
5523                    ));
5524                    None
5525                }
5526            } else {
5527                check_field_access(receiver, field, expected, ctx)
5528            }
5529        }
5530        ExprKind::MethodCall {
5531            receiver,
5532            method,
5533            type_args,
5534            args,
5535            ..
5536        } => {
5537            // `<field>.<op>(…)` on a `store` field — effectful storage
5538            // operations, dispatched by receiver provenance (a bare ident
5539            // naming a store field). Finding #36: one lookup into the unified
5540            // `store_fields` map, then dispatch by kind, instead of five
5541            // sequential per-kind lookups.
5542            //
5543            // Note: unlike the other store kinds, a `Cell` field is
5544            // deliberately bound into scope by `self_scope` (v0.81: "each
5545            // `Cell` store field is a bare local of its element type") so a
5546            // bare read derefs it — so `ctx.lookup` legitimately finds it and
5547            // no `is_none()` guard belongs there; a local sharing a cell's
5548            // name is a scope-construction question, not a dispatch-order
5549            // one. Every other kind requires `ctx.lookup(...).is_none()` so a
5550            // local that happens to share a store field's name is not
5551            // shadowed by the store dispatch.
5552            if let ExprKind::Ident(id) = &receiver.kind
5553                && let Some(field) = ctx.store_fields.get(&id.name).cloned()
5554                && (matches!(field, StoreField::Cell(_)) || ctx.lookup(id.name.as_str()).is_none())
5555            {
5556                match field {
5557                    // v0.82 (ADR 0110): `<map>.<op>(…)` on a `store Map[K, V]`
5558                    // field — effectful storage-map operations.
5559                    StoreField::Map(k, v) => {
5560                        // v0.91 (ADR 0115): a query builder/terminal lifts the
5561                        // store map into a lazy `Query[V]` over its values; an
5562                        // entry op (`put`/`get`/…) stays the effectful map
5563                        // operation.
5564                        if is_query_op(&method.name) {
5565                            // v0.107 (slice 4): record the receiver's lifted
5566                            // `Query[V]` type (otherwise unrecorded — the
5567                            // dispatch keys off the store field, not a typed
5568                            // receiver). This is the receiver's true type for
5569                            // any query op; its load-bearing use is the
5570                            // linearity pass, which now sees a held-bearing
5571                            // collection and lends the closure parameter of
5572                            // `forEach`/`parTraverse` as borrowed —
5573                            // otherwise `ty_of(receiver)` is `None` and the
5574                            // no-consume-in-a-broadcast rule is silently
5575                            // unenforced.
5576                            ctx.expr_types.insert(
5577                                receiver.id,
5578                                TypedExpr {
5579                                    span: receiver.span,
5580                                    ty: tys.intern(Ty::Query(v)),
5581                                },
5582                            );
5583                            let result = check_query_kernel_method(
5584                                method,
5585                                QueryOp::from_name(&method.name),
5586                                args,
5587                                v,
5588                                expr.span,
5589                                ctx,
5590                            );
5591                            par::reject_store_write_in_closure(method, args, ctx);
5592                            // P6.2 (#1143, R6.12): role is read back from
5593                            // this call's own resolved type where possible —
5594                            // `is_query_op` above only decides "lift or
5595                            // not", never "builder or terminal" (`query_role`
5596                            // itself, not this call site).
5597                            let role = query_role(result, &method.name, tys);
5598                            if let Some(op) = QueryOp::from_name(&method.name) {
5599                                ctx.callees.insert(
5600                                    expr.id,
5601                                    Callee::Query {
5602                                        field: id.name.clone(),
5603                                        op: StoreQueryOp::Query(op),
5604                                        role,
5605                                    },
5606                                );
5607                            }
5608                            result
5609                        } else {
5610                            if let Some(op) = MapStoreOp::from_name(&method.name) {
5611                                ctx.callees.insert(
5612                                    expr.id,
5613                                    Callee::Store {
5614                                        field: id.name.clone(),
5615                                        op: StoreEntryOp::Map(op),
5616                                    },
5617                                );
5618                            }
5619                            check_store_map_op(method, args, k, v, expr.span, ctx)
5620                        }
5621                    }
5622                    // v0.83: `<set>.<op>(…)` on a `store Set[T]` field —
5623                    // effectful storage-set ops.
5624                    StoreField::Set(t) => {
5625                        if let Some(op) = SetStoreOp::from_name(&method.name) {
5626                            ctx.callees.insert(
5627                                expr.id,
5628                                Callee::Store {
5629                                    field: id.name.clone(),
5630                                    op: StoreEntryOp::Set(op),
5631                                },
5632                            );
5633                        }
5634                        check_store_set_op(method, args, t, expr.span, ctx)
5635                    }
5636                    // v0.87 (ADR 0113): `<cache>.<op>(…)` on a `store
5637                    // Cache[K, V]` field — the storage-map ops plus a `given
5638                    // Clock` requirement (eviction).
5639                    StoreField::Cache(k, v, _ttl) => {
5640                        if let Some(op) = MapStoreOp::from_name(&method.name) {
5641                            ctx.callees.insert(
5642                                expr.id,
5643                                Callee::Store {
5644                                    field: id.name.clone(),
5645                                    op: StoreEntryOp::Cache(op),
5646                                },
5647                            );
5648                        }
5649                        check_store_cache_op(method, args, k, v, expr.span, ctx)
5650                    }
5651                    // v0.95 (ADR 0121): `<log>.<op>(…)` on a `store Log[T]`
5652                    // field — `append` is the effectful non-idempotent write
5653                    // (`given Clock`); the time-window roots and general
5654                    // builders lift the log into a lazy `Query[T]` over its
5655                    // entry values. Unlike `Map`, the store-vs-query split
5656                    // lives *inside* `check_store_log_op` itself (the
5657                    // window-root vocabulary `since`/`before`/`between`/
5658                    // `recent`/`reversed` plus its own `is_query_op`
5659                    // fallthrough, `calls.rs:1879-1913`) — mirrored here by
5660                    // name so `Callee::Query` is recorded only for the same
5661                    // vocabulary `check_store_log_op` itself treats as a
5662                    // query op, not for every non-`append` name (an unknown
5663                    // op — `check_store_log_op`'s own `other =>` arm reports
5664                    // `bynk.store.unknown_op` — gets neither `Callee`, since
5665                    // dispatch's own conclusion is that it is not a valid
5666                    // call at all).
5667                    StoreField::Log(t) => match method.name.as_str() {
5668                        "append" => {
5669                            ctx.callees.insert(
5670                                expr.id,
5671                                Callee::Store {
5672                                    field: id.name.clone(),
5673                                    op: StoreEntryOp::Log(LogStoreOp::Append),
5674                                },
5675                            );
5676                            check_store_log_op(method, args, t, expr.span, ctx)
5677                        }
5678                        name if matches!(
5679                            name,
5680                            "since" | "before" | "between" | "recent" | "reversed"
5681                        ) || is_query_op(name) =>
5682                        {
5683                            let result = check_store_log_op(method, args, t, expr.span, ctx);
5684                            let role = query_role(result, &method.name, tys);
5685                            let op = LogWindowOp::from_name(&method.name)
5686                                .map(StoreQueryOp::LogWindow)
5687                                .or_else(|| {
5688                                    QueryOp::from_name(&method.name).map(StoreQueryOp::Query)
5689                                });
5690                            if let Some(op) = op {
5691                                ctx.callees.insert(
5692                                    expr.id,
5693                                    Callee::Query {
5694                                        field: id.name.clone(),
5695                                        op,
5696                                        role,
5697                                    },
5698                                );
5699                            }
5700                            result
5701                        }
5702                        _ => check_store_log_op(method, args, t, expr.span, ctx),
5703                    },
5704                    // v0.98 (ADR 0125): `<cell>.update(f)` on a `store
5705                    // Cell[T]` field — the one method-shaped cell op (read is
5706                    // the bare name, write is `:=`).
5707                    StoreField::Cell(t) => {
5708                        if let Some(op) = CellStoreOp::from_name(&method.name) {
5709                            ctx.callees.insert(
5710                                expr.id,
5711                                Callee::Store {
5712                                    field: id.name.clone(),
5713                                    op: StoreEntryOp::Cell(op),
5714                                },
5715                            );
5716                        }
5717                        check_store_cell_op(method, args, t, expr.span, ctx)
5718                    }
5719                }
5720            }
5721            // v0.9: `HttpResult.Variant(args)` — explicit HttpResult construction.
5722            else if let ExprKind::Ident(id) = &receiver.kind
5723                && ctx.lookup(id.name.as_str()).is_none()
5724                && id.name == HTTP_RESULT
5725            {
5726                if let Some(v) = http_variant(&method.name) {
5727                    ctx.callees
5728                        .insert(expr.id, Callee::intrinsic(StaticOp::HttpResult(v)));
5729                    check_http_variant(expr.span, v, args, expected, ctx)
5730                } else {
5731                    ctx.errors.push(CompileError::new(
5732                        "bynk.types.unknown_static_member",
5733                        method.span,
5734                        format!("`HttpResult` has no variant named `{}`", method.name),
5735                    ));
5736                    None
5737                }
5738            } else {
5739                check_method_call(
5740                    receiver, method, type_args, args, expr.span, expected, expr.id, ctx,
5741                )
5742            }
5743        }
5744        ExprKind::Match { discriminant, arms } => {
5745            check_match(discriminant, arms, expr.span, expected, ctx)
5746        }
5747        ExprKind::Is { value, pattern } => check_is(value, pattern, expr.span, ctx),
5748        ExprKind::UnitLit => Some(tys.intern(Ty::Unit)),
5749        ExprKind::EffectPure(inner) => {
5750            let expected_inner = match expected.map(|e| tys.get(e)).as_deref() {
5751                Some(Ty::Effect(t)) => Some(*t),
5752                _ => None,
5753            };
5754            let inner_ty = type_of(inner, expected_inner, ctx)?;
5755            Some(tys.intern(Ty::Effect(inner_ty)))
5756        }
5757        ExprKind::RecordSpread {
5758            type_name,
5759            base,
5760            overrides,
5761            ..
5762        } => {
5763            let ty = check_record_spread(
5764                type_name.as_ref(),
5765                base,
5766                overrides,
5767                expr.span,
5768                expected,
5769                ctx,
5770            )?;
5771            d1::check_statement_fields(ty, overrides, ctx);
5772            Some(ty)
5773        }
5774        ExprKind::Expect(inner) => check_expect(inner, expr.span, ctx),
5775        ExprKind::Val { type_ref, args, .. } => check_val(type_ref, args, expr.span, ctx),
5776        ExprKind::Observation(o) => check_observation(o, expr.span, ctx),
5777        ExprKind::Faults(f) => check_faults(f, expr.span, ctx),
5778        ExprKind::Trace { cap, op } => check_trace(cap, op, expr.span, ctx),
5779        // Slice C: a `Wire(<String>)` reached through the ordinary expression
5780        // checker is *misplaced* — a valid `Wire` is intercepted by the service-
5781        // address argument checker (`check_address_args`), which validates the
5782        // inner and the `system` tier. Anywhere else it is an error. The inner is
5783        // still typed so a mistake inside it is reported too.
5784        ExprKind::Wire(inner) => {
5785            let _ = type_of(inner, Some(tys.intern(Ty::Base(BaseType::String))), ctx);
5786            ctx.errors.push(
5787                CompileError::new(
5788                    "bynk.test.wire_needs_system",
5789                    expr.span,
5790                    "`Wire(...)` may only be passed as an argument to a service address in a `system`-tier case",
5791                )
5792                .with_note(
5793                    "`Wire` hands raw, pre-validation input to the boundary; there is no wire to be raw about at `unit`, and it is meaningless outside a service address",
5794                ),
5795            );
5796            None
5797        }
5798    };
5799    // T3.3b (R4.3, R2.5, R4.9): `expr_types` is total for every expression
5800    // `type_of` is called on — a `None` result (whether from a diagnosed
5801    // failure or a deliberate, undiagnosed non-type such as an untyped
5802    // test-body binding) records `Ty::Error` rather than leaving the span
5803    // unrecorded. This changes only what gets *written*; every caller of
5804    // `type_of` still sees its actual `Option<TyId>` return value and every
5805    // existing `?`/`.or(...)` control-flow site is unaffected — `Ty::Error`
5806    // only becomes observable to an external reader of `expr_types` (the
5807    // emitter, the LSP), never to internal checker logic.
5808    ctx.expr_types.insert(
5809        expr.id,
5810        TypedExpr {
5811            span: expr.span,
5812            ty: ty.unwrap_or_else(|| tys.intern(Ty::Error)),
5813        },
5814    );
5815    ty
5816}
5817
5818/// Whether a user sum type declared in this unit has a variant `name`.
5819fn user_sum_owns_variant(ctx: &Ctx, name: &str) -> bool {
5820    ctx.input.types.values().any(|t| {
5821        matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|var| var.name.name == name))
5822    })
5823}
5824
5825/// #3631: whether a bare name or call that is spelled like an `HttpResult`
5826/// variant (`Found`, `Gone`, `Ok`, ...) is that variant rather than something
5827/// the user declared under the same name (a sum variant or a `fn`).
5828///
5829/// An expected type that is `HttpResult` settles it. A name nothing else owns
5830/// is the `HttpResult` variant. A name the user owns goes to the user whenever
5831/// the context supplies a concrete expected type that is not `HttpResult`
5832/// (`Ok(Found(item))` in a handler returning `HttpResult[Outcome]` expects an
5833/// `Outcome`), and only with no informative expected type (none at all, an error type, or
5834/// a type variable still being inferred, as for `id(Found("/x"))`) does the
5835/// enclosing handler's `HttpResult` return type tip it back to the variant. Reading the
5836/// return type alone, as this once did, claimed every user variant sharing an
5837/// `HttpResult` variant's name for HTTP, whatever type the context asked for.
5838fn http_variant_applies(owned_by_user: bool, expected: Option<TyId>, ctx: &Ctx) -> bool {
5839    let tys = ctx.tys;
5840    // An unsolved variable (`id(Found("/x"))`: the argument's `T` is still being
5841    // inferred) or an error type says nothing about what the value is, so it is
5842    // no more informative than no expected type.
5843    let informative = |t: TyId| {
5844        !matches!(&*tys.get(t), Ty::Error) && !contains_flexible_var(t, &ctx.type_vars, tys)
5845    };
5846    match expected {
5847        Some(t) if peel_to_http_result(t, tys).is_some() => true,
5848        Some(t) if informative(t) => !owned_by_user,
5849        _ => !owned_by_user || peel_to_http_result(ctx.return_ty, tys).is_some(),
5850    }
5851}
5852
5853/// #1658 (runtime-semantics track S9): an `Effect[T]` value in an effectful
5854/// body must be bound (`<-`), sequenced (`do`), returned (the block's tail),
5855/// or handed to something that takes an `Effect`. The emitter translates an
5856/// effectful call to an eager `Promise`, so a call that is *built* but not
5857/// bound still runs, unawaited, racing everything after it: `let e =
5858/// Counter("k").bump()` performed the write with no diagnostic. This flags the
5859/// value positions where an `Effect` can only be built and abandoned:
5860/// - the right-hand side of a plain `let` (`allowed == false` at the root),
5861///   including `let _ = …`;
5862/// - a list literal's element. No API takes a `List[Effect[T]]`, and a list's
5863///   element type is inferred from its elements, so it cannot vouch for them;
5864/// - the payload of `Some`/`Ok`/`Err`, a sum-variant constructor, or a record
5865///   field.
5866///
5867/// It does not descend into call arguments, receivers, lambdas or nested
5868/// blocks: an argument is the higher-order use the language keeps (its
5869/// parameter decides), and nested blocks are checked as blocks. Pure bodies
5870/// are untouched: effectful calls are already rejected there.
5871fn check_unbound_effects(e: &Expr, allowed: bool, ctx: &mut Ctx) {
5872    if !ctx.effectful {
5873        return;
5874    }
5875    let tys = ctx.tys;
5876    let ty_of = |e: &Expr, ctx: &Ctx| ctx.expr_types.get(&e.id).map(|t| t.ty);
5877    let is_effect = |t: Option<TyId>| t.is_some_and(|t| matches!(&*tys.get(t), Ty::Effect(_)));
5878    if !allowed && is_effect(ty_of(e, ctx)) {
5879        ctx.errors.push(
5880            CompileError::new(
5881                "bynk.effect.unbound_effect",
5882                e.span,
5883                "this `Effect` is started here and never awaited — it runs eagerly, out of order with everything after it",
5884            )
5885            .with_note(
5886                "bind its result with `let x <- …`, run it for its effect with `do …`, or return it as the body's value",
5887            ),
5888        );
5889        return;
5890    }
5891    match &e.kind {
5892        ExprKind::Paren(inner) => check_unbound_effects(inner, allowed, ctx),
5893        ExprKind::Some(x) | ExprKind::Ok(x) | ExprKind::Err(x) => {
5894            check_unbound_effects(x, false, ctx);
5895        }
5896        ExprKind::ListLit(args, ..) => {
5897            for a in args {
5898                check_unbound_effects(a, false, ctx);
5899            }
5900        }
5901        // A variant constructor in every spelling: `Loaded(x)` is a `Call`;
5902        // the qualified `ApiResult.Loaded(x)` parses as a `MethodCall` on the
5903        // type name. Both resolve to `Callee::Ctor` on their own expression
5904        // (review of #1694).
5905        ExprKind::Call { args, .. } | ExprKind::MethodCall { args, .. }
5906            if matches!(ctx.callees.get(&e.id), Some(Callee::Ctor { .. })) =>
5907        {
5908            for a in args {
5909                check_unbound_effects(a, false, ctx);
5910            }
5911        }
5912        ExprKind::RecordConstruction { fields, .. }
5913        | ExprKind::RecordSpread {
5914            overrides: fields, ..
5915        } => {
5916            for f in fields {
5917                if let Some(v) = &f.value {
5918                    check_unbound_effects(v, false, ctx);
5919                }
5920            }
5921        }
5922        _ => {}
5923    }
5924}
5925
5926// ==== Peel helpers (unwrap Effect / Result / Option / List / Map) ====
5927
5928/// Peel one optional `Effect[_]` wrapper to expose an underlying `HttpResult[T]`.
5929pub(crate) fn peel_to_http_result(ty: TyId, tys: &Types) -> Option<TyId> {
5930    match &*tys.get(ty) {
5931        Ty::HttpResult(inner) => Some(*inner),
5932        Ty::Effect(inner) => peel_to_http_result(*inner, tys),
5933        _ => None,
5934    }
5935}
5936
5937/// v0.44: peel an optional `Effect[_]` to detect an underlying `QueueResult`.
5938fn peel_to_queue_result(ty: TyId, tys: &Types) -> bool {
5939    match &*tys.get(ty) {
5940        Ty::QueueResult => true,
5941        Ty::Effect(inner) => peel_to_queue_result(*inner, tys),
5942        _ => false,
5943    }
5944}
5945
5946fn surrounding_result(
5947    expected: Option<TyId>,
5948    return_ty: TyId,
5949    tys: &Types,
5950) -> Option<(TyId, TyId)> {
5951    if let Some(t) = expected
5952        && let Some(pair) = peel_to_result(t, tys)
5953    {
5954        return Some(pair);
5955    }
5956    peel_to_result(return_ty, tys)
5957}
5958
5959/// Peel one optional `Effect[_]` wrapper to expose an underlying `Result[T, E]`.
5960/// Used by `Ok` / `Err` checking in v0.7.1 so that bare constructors in
5961/// `Effect[Result[T, E]]` tail positions can pick up the surrounding type's
5962/// parameters via the auto-lift propagation.
5963fn peel_to_result(ty: TyId, tys: &Types) -> Option<(TyId, TyId)> {
5964    match &*tys.get(ty) {
5965        Ty::Result(t, e) => Some((*t, *e)),
5966        Ty::Effect(inner) => peel_to_result(*inner, tys),
5967        _ => None,
5968    }
5969}
5970
5971/// Companion to `peel_to_result` for `Option[T]`.
5972fn peel_to_option(ty: TyId, tys: &Types) -> Option<TyId> {
5973    match &*tys.get(ty) {
5974        Ty::Option(t) => Some(*t),
5975        Ty::Effect(inner) => peel_to_option(*inner, tys),
5976        _ => None,
5977    }
5978}
5979
5980/// Companion to `peel_to_result` for `List[T]` (v0.20b) — the expected
5981/// element type of a list literal, looking through `Effect[_]` so tail
5982/// auto-lift positions still propagate it.
5983fn peel_to_list(ty: TyId, tys: &Types) -> Option<TyId> {
5984    match &*tys.get(ty) {
5985        Ty::List(t) => Some(*t),
5986        Ty::Effect(inner) => peel_to_list(*inner, tys),
5987        _ => None,
5988    }
5989}
5990
5991/// K6a (#2596): companion to `peel_to_list` for `Set[T]`.
5992fn peel_to_set(ty: TyId, tys: &Types) -> Option<TyId> {
5993    match &*tys.get(ty) {
5994        Ty::Set(t) => Some(*t),
5995        Ty::Effect(inner) => peel_to_set(*inner, tys),
5996        _ => None,
5997    }
5998}
5999
6000/// Companion to `peel_to_list` for `Map[K, V]` (v0.20b).
6001fn peel_to_map(ty: TyId, tys: &Types) -> Option<(TyId, TyId)> {
6002    match &*tys.get(ty) {
6003        Ty::Map(k, v) => Some((*k, *v)),
6004        Ty::Effect(inner) => peel_to_map(*inner, tys),
6005        _ => None,
6006    }
6007}
6008
6009// ==== Structural compatibility and variant introspection ====
6010
6011/// A flattened view of a type's variants (name + payload types).
6012///
6013/// `pub` since P6.4 (design/tracks/the-ir.md §6, #1157, Decision A):
6014/// `bynk-emit::ir::lower`'s pattern-lowering needs the exact same uniform
6015/// view this function already gives the checker — a user sum, `Result`,
6016/// `Option`, `ActorSum` and `HttpResult` all flattened into one `name` +
6017/// `payload` shape, with no `Arc<TypeDecl>` required (`Callee::Ctor`'s own
6018/// identity scheme never fires for `Ok`/`Err`/`Some`/`None`, ADR 0333's
6019/// `#1145` Decision B). No behaviour change — a reachability change only,
6020/// the same shape ADR 0333 already gave `Callee`.
6021pub struct VariantInfo {
6022    pub name: String,
6023    pub payload: Vec<(String, TyId)>,
6024}
6025
6026/// Project a return type produced in the consumed context's namespace into
6027/// the caller's namespace by re-resolving named types that exist on both
6028/// sides. The structural shape stays the same; the brand changes.
6029pub(crate) fn rebrand_return_type(
6030    t: TyId,
6031    caller_types: &HashMap<String, Arc<TypeDecl>>,
6032    tys: &Types,
6033) -> TyId {
6034    let node = tys.get(t);
6035    match &*node {
6036        Ty::Named { name, kind, args } => {
6037            // If the caller's namespace has the same name, prefer the caller's
6038            // view (it carries the caller's brand at emission time). Otherwise
6039            // keep the consumed-context name; the caller can hold it opaquely.
6040            // Applied type arguments (a generic record) are preserved either
6041            // way — though a generic record is non-boundary, so this path only
6042            // ever sees the empty-args non-generic case in practice.
6043            if let Some(decl) = caller_types.get(name) {
6044                named_ty_with_args(decl, args.clone(), tys)
6045            } else {
6046                tys.intern(Ty::Named {
6047                    name: name.clone(),
6048                    kind: kind.clone(),
6049                    args: args.clone(),
6050                })
6051            }
6052        }
6053        Ty::Result(t, e) => tys.intern(Ty::Result(
6054            rebrand_return_type(*t, caller_types, tys),
6055            rebrand_return_type(*e, caller_types, tys),
6056        )),
6057        Ty::Option(t) => tys.intern(Ty::Option(rebrand_return_type(*t, caller_types, tys))),
6058        Ty::Effect(t) => tys.intern(Ty::Effect(rebrand_return_type(*t, caller_types, tys))),
6059        Ty::HttpResult(t) => tys.intern(Ty::HttpResult(rebrand_return_type(*t, caller_types, tys))),
6060        Ty::HttpOutcome(t) => {
6061            tys.intern(Ty::HttpOutcome(rebrand_return_type(*t, caller_types, tys)))
6062        }
6063        Ty::List(t) => tys.intern(Ty::List(rebrand_return_type(*t, caller_types, tys))),
6064        Ty::Set(t) => tys.intern(Ty::Set(rebrand_return_type(*t, caller_types, tys))),
6065        Ty::Query(t) => tys.intern(Ty::Query(rebrand_return_type(*t, caller_types, tys))),
6066        Ty::Stream(t) => tys.intern(Ty::Stream(rebrand_return_type(*t, caller_types, tys))),
6067        Ty::Connection(t) => tys.intern(Ty::Connection(rebrand_return_type(*t, caller_types, tys))),
6068        Ty::TestConnection(t) => tys.intern(Ty::TestConnection(rebrand_return_type(
6069            *t,
6070            caller_types,
6071            tys,
6072        ))),
6073        Ty::Map(k, v) => tys.intern(Ty::Map(
6074            rebrand_return_type(*k, caller_types, tys),
6075            rebrand_return_type(*v, caller_types, tys),
6076        )),
6077        // R4.3: `Ty::Error` carries no name to rebrand — pass it through.
6078        Ty::Error
6079        | Ty::Never
6080        | Ty::Base(_)
6081        | Ty::QueueResult
6082        | Ty::BoundaryRejection
6083        | Ty::Asset
6084        | Ty::RequestHeaders
6085        | Ty::RequestQuery
6086        | Ty::RequestCookies
6087        | Ty::TokenClaims
6088        | Ty::ValidationError
6089        | Ty::DecodeError
6090        | Ty::Unit
6091        | Ty::Actor(_)
6092        | Ty::ActorSum(_) => t,
6093        // v0.20a: function types are confined to non-boundary positions
6094        // (`bynk.types.function_at_boundary`), so a cross-context return can
6095        // never carry one; Vars never escape call checking.
6096        Ty::Fn { .. } | Ty::Var(_) => t,
6097    }
6098}
6099
6100/// #2901: the caller's type table with the provider's qualified keys
6101/// (`lib__Code`, #2087) that the caller names by the declaration's own name
6102/// added. A provider that has a type of its own named like one it borrows
6103/// files the borrowed one under a qualified key; a caller holding that same
6104/// declaration under the bare name takes the value as its own type, as it
6105/// would a provider's `Code` by name.
6106pub(crate) fn rebrand_table(
6107    caller_types: &HashMap<String, Arc<TypeDecl>>,
6108    provider_types: &HashMap<String, Arc<TypeDecl>>,
6109) -> HashMap<String, Arc<TypeDecl>> {
6110    let mut out = caller_types.clone();
6111    for (key, decl) in provider_types {
6112        let bare = crate::symbols::display_type_name(key);
6113        if bare == key || caller_types.contains_key(key) {
6114            continue;
6115        }
6116        if let Some(own) = caller_types
6117            .get(bare)
6118            .filter(|c| Arc::ptr_eq(c, decl) || c.span == decl.span)
6119        {
6120            out.insert(key.clone(), own.clone());
6121        }
6122    }
6123    out
6124}
6125
6126/// #1941: the first type name [`rebrand_return_type`] would swap for the
6127/// caller's declaration of a different shape. A returned value takes the
6128/// caller's type of the same name (§6.5), so that swap would type the
6129/// provider's value as an unrelated type: the caller's `Box` reading fields
6130/// the provider's `Box` lacks. Names the caller does not bind keep the
6131/// provider's declaration and need no check.
6132///
6133/// `caller_types` is the table the rebrand uses, so this check and the
6134/// rebrand agree on which names are swapped. `receiving` is the caller's
6135/// [`projected_types`], which resolves the names the caller's declaration
6136/// reaches but does not bind (an export's unexported field type).
6137pub(crate) fn rebrand_conflict(
6138    t: TyId,
6139    provider_types: &HashMap<String, Arc<TypeDecl>>,
6140    caller_types: &HashMap<String, Arc<TypeDecl>>,
6141    receiving: &HashMap<String, Arc<TypeDecl>>,
6142    tys: &Types,
6143) -> Option<String> {
6144    let walk = |inner: TyId| rebrand_conflict(inner, provider_types, caller_types, receiving, tys);
6145    let node = tys.get(t);
6146    match &*node {
6147        Ty::Named { name, .. } => {
6148            let (Some(caller_decl), Some(provider_decl)) =
6149                (caller_types.get(name), provider_types.get(name))
6150            else {
6151                return None;
6152            };
6153            if Arc::ptr_eq(caller_decl, provider_decl) {
6154                return None;
6155            }
6156            let rebranded = rebrand_return_type(t, caller_types, tys);
6157            (!structurally_compatible(t, rebranded, provider_types, receiving, tys))
6158                .then(|| name.clone())
6159        }
6160        Ty::Result(a, b) | Ty::Map(a, b) => walk(*a).or_else(|| walk(*b)),
6161        Ty::Option(a) | Ty::Effect(a) | Ty::HttpResult(a) | Ty::List(a) | Ty::Set(a) => walk(*a),
6162        // `Query`, `Stream` and `Connection` are non-boundary, so a
6163        // cross-context return never carries one.
6164        _ => None,
6165    }
6166}
6167
6168/// Structural compatibility check for values crossing a context boundary
6169/// (v0.6 §4.3). The two types may be expressed in different namespaces
6170/// (caller-side / callee-side type tables), so we walk them in parallel
6171/// against their respective tables.
6172fn structurally_compatible(
6173    arg: TyId,
6174    param: TyId,
6175    arg_types: &HashMap<String, Arc<TypeDecl>>,
6176    param_types: &HashMap<String, Arc<TypeDecl>>,
6177    tys: &Types,
6178) -> bool {
6179    structurally_compatible_inner(arg, param, arg_types, param_types, tys, &mut HashSet::new())
6180}
6181
6182/// [`projected_types`]' result: the projected table, and the names it leaves
6183/// out as ambiguous.
6184pub(crate) type Projection = (HashMap<String, Arc<TypeDecl>>, BTreeSet<String>);
6185
6186/// #1941: the caller's type table, extended with the types a value from a
6187/// consumed context can carry here without the caller naming them. A
6188/// consumed service may return a type its context does not export (§6.5:
6189/// a value crosses whether or not its type is exported), and the caller's
6190/// table lacks it, so comparing that value on its way back used to find
6191/// nothing and reject it against its own declaration.
6192///
6193/// A `Ty::Named` keeps only the bare name, not the context it came from. A
6194/// name the caller does not bind is therefore resolved only when every
6195/// consumed context that declares it declares a structurally compatible
6196/// type, so whichever one the value came from compares the same. Otherwise
6197/// the name is left out, and a value of it is rejected rather than compared
6198/// against the wrong declaration. The names left out are returned too, for
6199/// the rejection to explain.
6200pub(crate) fn projected_types(
6201    caller_types: &HashMap<String, Arc<TypeDecl>>,
6202    consumed_types: &HashMap<String, HashMap<String, Arc<TypeDecl>>>,
6203    tys: &Types,
6204) -> Projection {
6205    type Table = HashMap<String, Arc<TypeDecl>>;
6206    let mut candidates: HashMap<&String, Vec<(&Arc<TypeDecl>, &Table)>> = HashMap::new();
6207    // Consumed contexts in name order, so when several agree on a name the
6208    // same declaration is projected on every run.
6209    let mut tables: Vec<(&String, &Table)> = consumed_types.iter().collect();
6210    tables.sort_by_key(|(context, _)| *context);
6211    for (_, table) in tables {
6212        for (name, decl) in table {
6213            if !caller_types.contains_key(name) {
6214                candidates.entry(name).or_default().push((decl, table));
6215            }
6216        }
6217    }
6218    let mut projected = caller_types.clone();
6219    let mut ambiguous = BTreeSet::new();
6220    for (name, decls) in candidates {
6221        let (first, first_table) = decls[0];
6222        let agree = decls[1..].iter().all(|&(decl, table)| {
6223            Arc::ptr_eq(first, decl)
6224                || (first.type_params.is_empty()
6225                    && decl.type_params.is_empty()
6226                    && structural_compare_named(
6227                        (name, &[]),
6228                        (name, &[]),
6229                        first_table,
6230                        table,
6231                        tys,
6232                        &mut HashSet::new(),
6233                    )
6234                    && structural_compare_named(
6235                        (name, &[]),
6236                        (name, &[]),
6237                        table,
6238                        first_table,
6239                        tys,
6240                        &mut HashSet::new(),
6241                    ))
6242        });
6243        if agree {
6244            projected.insert(name.clone(), first.clone());
6245        } else {
6246            ambiguous.insert(name.clone());
6247        }
6248    }
6249    (projected, ambiguous)
6250}
6251
6252/// #1948: the caller's [`projected_types`], when it consumes a context, for
6253/// reading a value of a type the caller does not name: a consumed service's
6254/// unexported return type, or an export's unexported field type. `None` for
6255/// a unit that consumes nothing, whose own table is all there is. Projecting
6256/// clones the caller's table, so call it only once that table has missed.
6257pub(crate) fn consumer_projection(ctx: &Ctx) -> Option<Projection> {
6258    let consumed = &ctx.input.cross_context.consumed_types;
6259    (!consumed.is_empty()).then(|| projected_types(&ctx.input.types, consumed, ctx.tys))
6260}
6261
6262/// #1948: a type's declaration by name: the caller's own, else the one
6263/// [`consumer_projection`] resolves. `None` for a name neither binds,
6264/// including one the projection leaves ambiguous.
6265pub(crate) fn lookup_type_decl(name: &str, ctx: &Ctx) -> Option<Arc<TypeDecl>> {
6266    if let Some(decl) = ctx.input.types.get(name) {
6267        return Some(decl.clone());
6268    }
6269    consumer_projection(ctx)?.0.get(name).cloned()
6270}
6271
6272/// #1941: a note for a cross-context argument whose type names one of
6273/// [`projected_types`]' ambiguous names, which no declaration resolves.
6274pub(crate) fn ambiguous_projection_note(
6275    t: TyId,
6276    ambiguous: &BTreeSet<String>,
6277    tys: &Types,
6278) -> Option<String> {
6279    let node = tys.get(t);
6280    match &*node {
6281        Ty::Named { name, args, .. } => {
6282            if ambiguous.contains(name) {
6283                return Some(format!(
6284                    "more than one consumed context declares a type `{name}`, with different \
6285                     shapes, so a value of it cannot be traced to one of them; rename one"
6286                ));
6287            }
6288            args.iter()
6289                .find_map(|a| ambiguous_projection_note(*a, ambiguous, tys))
6290        }
6291        Ty::Result(a, b) | Ty::Map(a, b) => ambiguous_projection_note(*a, ambiguous, tys)
6292            .or_else(|| ambiguous_projection_note(*b, ambiguous, tys)),
6293        Ty::Option(a) | Ty::Effect(a) | Ty::HttpResult(a) | Ty::List(a) | Ty::Set(a) => {
6294            ambiguous_projection_note(*a, ambiguous, tys)
6295        }
6296        _ => None,
6297    }
6298}
6299
6300fn structurally_compatible_inner(
6301    arg: TyId,
6302    param: TyId,
6303    arg_types: &HashMap<String, Arc<TypeDecl>>,
6304    param_types: &HashMap<String, Arc<TypeDecl>>,
6305    tys: &Types,
6306    visited: &mut HashSet<(String, String)>,
6307) -> bool {
6308    let (arg_node, param_node) = (tys.get(arg), tys.get(param));
6309    match (&*arg_node, &*param_node) {
6310        // R4.3: as in `compatible` — an already-diagnosed side is compatible
6311        // with anything, so a cross-context signature check doesn't report
6312        // the same failure a second time as a signature mismatch.
6313        (Ty::Error, _) | (_, Ty::Error) => true,
6314        (Ty::Never, _) => true,
6315        (Ty::Base(a), Ty::Base(b)) => a == b,
6316        (Ty::ValidationError, Ty::ValidationError) => true,
6317        (Ty::DecodeError, Ty::DecodeError) => true,
6318        (Ty::Unit, Ty::Unit) => true,
6319        (Ty::Result(t1, e1), Ty::Result(t2, e2)) => {
6320            structurally_compatible_inner(*t1, *t2, arg_types, param_types, tys, visited)
6321                && structurally_compatible_inner(*e1, *e2, arg_types, param_types, tys, visited)
6322        }
6323        (Ty::Option(a), Ty::Option(b)) => {
6324            structurally_compatible_inner(*a, *b, arg_types, param_types, tys, visited)
6325        }
6326        (Ty::Effect(a), Ty::Effect(b)) => {
6327            structurally_compatible_inner(*a, *b, arg_types, param_types, tys, visited)
6328        }
6329        (Ty::HttpResult(a), Ty::HttpResult(b)) | (Ty::HttpOutcome(a), Ty::HttpOutcome(b)) => {
6330            structurally_compatible_inner(*a, *b, arg_types, param_types, tys, visited)
6331        }
6332        // The boundary-crossing collections walk their element types like
6333        // `Result`/`Option` — without these arms an identical `List[Int]`
6334        // was rejected against itself at a context boundary.
6335        (Ty::List(a), Ty::List(b)) | (Ty::Set(a), Ty::Set(b)) => {
6336            structurally_compatible_inner(*a, *b, arg_types, param_types, tys, visited)
6337        }
6338        (Ty::Map(k1, v1), Ty::Map(k2, v2)) => {
6339            structurally_compatible_inner(*k1, *k2, arg_types, param_types, tys, visited)
6340                && structurally_compatible_inner(*v1, *v2, arg_types, param_types, tys, visited)
6341        }
6342        (Ty::QueueResult, Ty::QueueResult) | (Ty::BoundaryRejection, Ty::BoundaryRejection) => true,
6343        (Ty::Asset, Ty::Asset) => true,
6344        (Ty::RequestHeaders, Ty::RequestHeaders) => true,
6345        (Ty::RequestQuery, Ty::RequestQuery) => true,
6346        (Ty::RequestCookies, Ty::RequestCookies) => true,
6347        (Ty::TokenClaims, Ty::TokenClaims) => true,
6348        (
6349            Ty::Named {
6350                name: an, args: aa, ..
6351            },
6352            Ty::Named {
6353                name: bn, args: ba, ..
6354            },
6355        ) => {
6356            // v0.157 (ADR 0183): applied type arguments must match structurally
6357            // too — `Paginated[String]` and `Paginated[Int]` are not the same
6358            // brand. (#1736: live now that a generic type's fields compare at
6359            // these arguments, in `structural_compare_named`.)
6360            if aa.len() != ba.len()
6361                || !aa.iter().zip(ba).all(|(x, y)| {
6362                    structurally_compatible_inner(*x, *y, arg_types, param_types, tys, visited)
6363                })
6364            {
6365                return false;
6366            }
6367            // Cycle break: once we've started comparing (an, bn) we trust
6368            // the recursive case to succeed.
6369            let key = (an.clone(), bn.clone());
6370            if !visited.insert(key.clone()) {
6371                return true;
6372            }
6373            let ok =
6374                structural_compare_named((an, aa), (bn, ba), arg_types, param_types, tys, visited);
6375            visited.remove(&key);
6376            ok
6377        }
6378        // Refined-named widens to its base; tolerate one-sided widening only
6379        // when comparing within the same nominal name (handled above) or when
6380        // the param accepts a plain base.
6381        (
6382            Ty::Named {
6383                kind: NamedKind::Refined(b),
6384                ..
6385            },
6386            Ty::Base(target),
6387        ) => b == target,
6388        // Everything else cannot cross a context boundary: cross-variant
6389        // pairs, and the non-boundary types (`Effect` payloads are unwrapped
6390        // before this check; `Query`/`Stream`/`Connection`/`Fn`/`Var` and the
6391        // sealed actor bindings never cross). The left side is enumerated —
6392        // no `_` — so adding a `Ty` variant fails to compile here instead of
6393        // silently rejecting the new type against itself (the trap the
6394        // collections fell into).
6395        (
6396            Ty::Base(_)
6397            | Ty::Named { .. }
6398            | Ty::Result(..)
6399            | Ty::Option(_)
6400            | Ty::Effect(_)
6401            | Ty::HttpResult(_)
6402            | Ty::HttpOutcome(_)
6403            | Ty::QueueResult
6404            | Ty::BoundaryRejection
6405            | Ty::Asset
6406            | Ty::RequestHeaders
6407            | Ty::RequestQuery
6408            | Ty::RequestCookies
6409            | Ty::TokenClaims
6410            | Ty::List(_)
6411            | Ty::Set(_)
6412            | Ty::Map(..)
6413            | Ty::Query(_)
6414            | Ty::Stream(_)
6415            | Ty::TestConnection(_)
6416            | Ty::Connection(_)
6417            | Ty::ValidationError
6418            | Ty::DecodeError
6419            | Ty::Unit
6420            | Ty::Actor(_)
6421            | Ty::ActorSum(_)
6422            | Ty::Fn { .. }
6423            | Ty::Var(_),
6424            _,
6425        ) => false,
6426    }
6427}
6428
6429/// #2087: whether two declarations have the same members by name: the
6430/// fields of a record, or the variants (and their payload fields) of a sum,
6431/// in order. With the name and span, this tells one declaration (or a copy of
6432/// it with its references renamed) from another at the same byte range of a
6433/// different file.
6434fn same_members(a: &TypeDecl, b: &TypeDecl) -> bool {
6435    let fields = |fs: &[RecordField]| fs.iter().map(|f| f.name.name.clone()).collect::<Vec<_>>();
6436    match (&a.body, &b.body) {
6437        (TypeBody::Record(x), TypeBody::Record(y)) => fields(&x.fields) == fields(&y.fields),
6438        (TypeBody::Sum(x), TypeBody::Sum(y)) => {
6439            x.variants.len() == y.variants.len()
6440                && x.variants.iter().zip(&y.variants).all(|(v, w)| {
6441                    v.name.name == w.name.name
6442                        && v.payload
6443                            .iter()
6444                            .map(|f| &f.name.name)
6445                            .eq(w.payload.iter().map(|f| &f.name.name))
6446                })
6447        }
6448        (TypeBody::Refined { base: x, .. }, TypeBody::Refined { base: y, .. })
6449        | (TypeBody::Opaque { base: x, .. }, TypeBody::Opaque { base: y, .. }) => x == y,
6450        _ => false,
6451    }
6452}
6453
6454fn structural_compare_named(
6455    (arg_name, arg_args): (&str, &[TyId]),
6456    (param_name, param_args): (&str, &[TyId]),
6457    arg_types: &HashMap<String, Arc<TypeDecl>>,
6458    param_types: &HashMap<String, Arc<TypeDecl>>,
6459    tys: &Types,
6460    visited: &mut HashSet<(String, String)>,
6461) -> bool {
6462    // The "same nominal name" case is the most common: both sides derive
6463    // the same commons type. Compare their structural shapes.
6464    let Some(arg_decl) = arg_types.get(arg_name) else {
6465        return false;
6466    };
6467    let Some(param_decl) = param_types.get(param_name) else {
6468        return false;
6469    };
6470    // #2087: one declaration on both sides (its applied arguments already
6471    // compared) is the same type, field for field. Its fields' types need not
6472    // resolve in the caller's table: a borrowed type's field may name a type
6473    // the caller cannot bind unambiguously (#1941), which the callee's table
6474    // holds under a qualified key (`shop_order__Code`).
6475    //
6476    // The name stays in the test: most spans carry `FileId::UNKNOWN` (they
6477    // come from the lexer), so two declarations in different files at the
6478    // same byte range have equal spans. The name, the span and the members'
6479    // names together identify one declaration; a copy `contract_types_for`
6480    // made (its references renamed) keeps all three.
6481    if arg_name == param_name
6482        && (Arc::ptr_eq(arg_decl, param_decl)
6483            || (arg_decl.span == param_decl.span && same_members(arg_decl, param_decl)))
6484    {
6485        return true;
6486    }
6487    // #1736: a generic declaration's fields name its type parameters
6488    // (`item: T`), which resolve against neither side's type table, so every
6489    // generic record or sum used to compare as incompatible, even against
6490    // itself. Each side's fields are resolved at that side's *applied*
6491    // arguments (`Envelope[Int]` → `item: Int`) with [`instantiate_field_ty`],
6492    // whose arity guard turns a mis-applied reference into `None` (rejected),
6493    // so the bodies compare as instantiated. The arguments were already
6494    // compared pairwise by the caller.
6495    match (&arg_decl.body, &param_decl.body) {
6496        (
6497            TypeBody::Refined {
6498                base: ab,
6499                refinement: ar,
6500                ..
6501            },
6502            TypeBody::Refined {
6503                base: bb,
6504                refinement: br,
6505                ..
6506            },
6507        ) => {
6508            if ab != bb {
6509                return false;
6510            }
6511            refinements_match(*ab, ar.as_ref(), br.as_ref())
6512        }
6513        (
6514            TypeBody::Opaque {
6515                base: ab,
6516                refinement: ar,
6517                ..
6518            },
6519            TypeBody::Opaque {
6520                base: bb,
6521                refinement: br,
6522                ..
6523            },
6524        ) => {
6525            // Opaque types must share a name to be compatible (a context's
6526            // opaque cannot be reinterpreted as a different context's opaque).
6527            if arg_name != param_name {
6528                return false;
6529            }
6530            if ab != bb {
6531                return false;
6532            }
6533            refinements_match(*ab, ar.as_ref(), br.as_ref())
6534        }
6535        (TypeBody::Record(a), TypeBody::Record(b)) => {
6536            if a.fields.len() != b.fields.len() {
6537                return false;
6538            }
6539            for af in &a.fields {
6540                let Some(bf) = b.fields.iter().find(|f| f.name.name == af.name.name) else {
6541                    return false;
6542                };
6543                let at = instantiate_field_ty(arg_decl, arg_args, &af.type_ref, arg_types, tys);
6544                let bt =
6545                    instantiate_field_ty(param_decl, param_args, &bf.type_ref, param_types, tys);
6546                let (Some(at), Some(bt)) = (at, bt) else {
6547                    return false;
6548                };
6549                if !structurally_compatible_inner(at, bt, arg_types, param_types, tys, visited) {
6550                    return false;
6551                }
6552            }
6553            true
6554        }
6555        (TypeBody::Sum(a), TypeBody::Sum(b)) => {
6556            if a.variants.len() != b.variants.len() {
6557                return false;
6558            }
6559            for av in &a.variants {
6560                let Some(bv) = b.variants.iter().find(|v| v.name.name == av.name.name) else {
6561                    return false;
6562                };
6563                if av.payload.len() != bv.payload.len() {
6564                    return false;
6565                }
6566                for (af, bf) in av.payload.iter().zip(bv.payload.iter()) {
6567                    if af.name.name != bf.name.name {
6568                        return false;
6569                    }
6570                    let at = instantiate_field_ty(arg_decl, arg_args, &af.type_ref, arg_types, tys);
6571                    let bt = instantiate_field_ty(
6572                        param_decl,
6573                        param_args,
6574                        &bf.type_ref,
6575                        param_types,
6576                        tys,
6577                    );
6578                    let (Some(at), Some(bt)) = (at, bt) else {
6579                        return false;
6580                    };
6581                    if !structurally_compatible_inner(at, bt, arg_types, param_types, tys, visited)
6582                    {
6583                        return false;
6584                    }
6585                }
6586            }
6587            true
6588        }
6589        _ => false,
6590    }
6591}
6592
6593/// #2802 (supersedes the v0.177 set-equality of #643): a refinement on the
6594/// sending side is admitted where the receiving side expects another when it
6595/// **entails** it — every predicate of the receiver follows from the
6596/// conjunction of the sender's ([`crate::entailment`]). Equal predicate sets are
6597/// the degenerate case, so `String where NonEmpty && MaxLength(10)` and
6598/// `String where MaxLength(10) && NonEmpty` still match, and so do `NonEmpty`
6599/// and `MinLength(1)`; `MaxLength(4)` now also satisfies `MaxLength(8)`.
6600///
6601/// The asymmetry is unchanged and now follows from the rule: an unrefined
6602/// receiver is the empty conjunction, which anything entails; an unrefined
6603/// sender entails no predicate, so a refined receiver rejects it.
6604///
6605/// Both sides still go through `contract::canon_pred_set`, the form that feeds
6606/// the cross-context contract hash, so the matcher, the hash and the deploy
6607/// gate's classifier read one normal form. The hash covers the *callee's* own
6608/// contract, not the caller's argument type, so admitting a stronger sender
6609/// does not change it. `Matches` is entailed only by an identical `Matches`.
6610fn refinements_match(base: BaseType, a: Option<&Refinement>, b: Option<&Refinement>) -> bool {
6611    match (a, b) {
6612        (_, None) => true,
6613        (None, Some(_)) => false,
6614        (Some(a), Some(b)) => crate::entailment::unmet(
6615            base.name(),
6616            &crate::contract::canon_pred_set(a),
6617            &crate::contract::canon_pred_set(b),
6618        )
6619        .is_empty(),
6620    }
6621}
6622
6623/// `pub` since P6.4 (#1157, Decision A) — see [`VariantInfo`]'s own doc
6624/// comment for why `bynk-emit` needs this exact function rather than a
6625/// re-derived copy (R5.11, for the IR side).
6626pub fn variants_of(
6627    ty: TyId,
6628    types: &HashMap<String, Arc<TypeDecl>>,
6629    tys: &Types,
6630) -> Option<Vec<VariantInfo>> {
6631    match &*tys.get(ty) {
6632        Ty::Named {
6633            kind: NamedKind::Sum,
6634            name,
6635            args,
6636        } => {
6637            let decl = types.get(name)?;
6638            if let TypeBody::Sum(s) = &decl.body {
6639                Some(
6640                    s.variants
6641                        .iter()
6642                        .map(|v| VariantInfo {
6643                            name: v.name.name.clone(),
6644                            payload: v
6645                                .payload
6646                                .iter()
6647                                .map(|f| {
6648                                    // #593: for a generic sum, substitute the
6649                                    // instantiation's arguments into each payload
6650                                    // type (`Some(v: T)` over `Opt[Int]` ⇒ `Int`),
6651                                    // exactly as a generic record's fields are read
6652                                    // at an instantiation. `instantiate_field_ty`
6653                                    // degrades to a plain resolve for a non-generic
6654                                    // sum (empty `args`).
6655                                    let t =
6656                                        instantiate_field_ty(decl, args, &f.type_ref, types, tys)
6657                                            .unwrap_or_else(|| tys.intern(Ty::Base(BaseType::Int)));
6658                                    (f.name.name.clone(), t)
6659                                })
6660                                .collect(),
6661                        })
6662                        .collect(),
6663                )
6664            } else {
6665                None
6666            }
6667        }
6668        Ty::Result(t, e) => Some(vec![
6669            VariantInfo {
6670                name: "Ok".to_string(),
6671                payload: vec![("value".to_string(), *t)],
6672            },
6673            VariantInfo {
6674                name: "Err".to_string(),
6675                payload: vec![("error".to_string(), *e)],
6676            },
6677        ]),
6678        Ty::Option(t) => Some(vec![
6679            VariantInfo {
6680                name: "Some".to_string(),
6681                payload: vec![("value".to_string(), *t)],
6682            },
6683            VariantInfo {
6684                name: "None".to_string(),
6685                payload: vec![],
6686            },
6687        ]),
6688        // v0.52: a multi-actor sum matches on the resolved actor. Each member's
6689        // variant is named by the actor and binds that actor's identity
6690        // *directly* (`User(u)` ⇒ `u : UserId` — the arm already names the
6691        // actor, so no `.identity` indirection). A unit-identity member
6692        // (`Visitor`, `Webhook`) binds nothing.
6693        Ty::ActorSum(members) => Some(
6694            members
6695                .iter()
6696                .map(|(name, id)| VariantInfo {
6697                    name: name.clone(),
6698                    payload: match &*tys.get(*id) {
6699                        Ty::Unit => vec![],
6700                        _ => vec![("identity".to_string(), *id)],
6701                    },
6702                })
6703                .collect(),
6704        ),
6705        Ty::HttpResult(t) => Some(
6706            HTTP_VARIANTS
6707                .iter()
6708                .map(|v| VariantInfo {
6709                    name: v.name.to_string(),
6710                    payload: match v.payload {
6711                        HttpVariantPayload::None => vec![],
6712                        HttpVariantPayload::Value => vec![("value".to_string(), *t)],
6713                        HttpVariantPayload::Message => {
6714                            vec![(
6715                                "message".to_string(),
6716                                tys.intern(Ty::Base(BaseType::String)),
6717                            )]
6718                        }
6719                        HttpVariantPayload::Location => {
6720                            vec![(
6721                                "location".to_string(),
6722                                tys.intern(Ty::Base(BaseType::String)),
6723                            )]
6724                        }
6725                        HttpVariantPayload::Streamed => {
6726                            let elem = tys.intern(Ty::Base(BaseType::String));
6727                            vec![("stream".to_string(), tys.intern(Ty::Stream(elem)))]
6728                        }
6729                        // v0.111: the first two-field payload. Field names are
6730                        // kept byte-identical to the runtime union in
6731                        // `bynk-emit/runtime/src/http.ts`. An `HttpResult` is
6732                        // construct-only in handler position (never scrutinised),
6733                        // so this binding exists for exhaustiveness, not a path.
6734                        HttpVariantPayload::Raw => vec![
6735                            ("body".to_string(), tys.intern(Ty::Base(BaseType::Bytes))),
6736                            (
6737                                "contentType".to_string(),
6738                                tys.intern(Ty::Base(BaseType::String)),
6739                            ),
6740                        ],
6741                        HttpVariantPayload::RawTagged => vec![
6742                            ("body".to_string(), tys.intern(Ty::Base(BaseType::Bytes))),
6743                            (
6744                                "contentType".to_string(),
6745                                tys.intern(Ty::Base(BaseType::String)),
6746                            ),
6747                            ("etag".to_string(), tys.intern(Ty::Base(BaseType::String))),
6748                        ],
6749                        // K-streams (#2623): a test drains the bound body.
6750                        HttpVariantPayload::RawStreamed => {
6751                            let bytes = tys.intern(Ty::Base(BaseType::Bytes));
6752                            vec![
6753                                ("body".to_string(), tys.intern(Ty::Stream(bytes))),
6754                                (
6755                                    "contentType".to_string(),
6756                                    tys.intern(Ty::Base(BaseType::String)),
6757                                ),
6758                            ]
6759                        }
6760                        // #2341 (L4): the status matches as its number
6761                        // (`RawError(403, _, _)`); `ErrorStatus` names are a
6762                        // construction-site vocabulary, not a type.
6763                        HttpVariantPayload::RawError => vec![
6764                            ("status".to_string(), tys.intern(Ty::Base(BaseType::Int))),
6765                            ("body".to_string(), tys.intern(Ty::Base(BaseType::Bytes))),
6766                            (
6767                                "contentType".to_string(),
6768                                tys.intern(Ty::Base(BaseType::String)),
6769                            ),
6770                        ],
6771                    },
6772                })
6773                .collect(),
6774        ),
6775        // #1934: a case matches a queue handler's verdict (`expect r is Ack`).
6776        // Field names are the runtime union's in `bynk-emit/runtime/src/queue.ts`.
6777        Ty::QueueResult => Some(
6778            QUEUE_VARIANTS
6779                .iter()
6780                .map(|v| VariantInfo {
6781                    name: v.name.to_string(),
6782                    payload: match v.payload {
6783                        QueueVariantPayload::None => vec![],
6784                        QueueVariantPayload::Message => {
6785                            vec![("reason".to_string(), tys.intern(Ty::Base(BaseType::String)))]
6786                        }
6787                    },
6788                })
6789                .collect(),
6790        ),
6791        // #1934: the `system`-tier wire outcome. Field names are the runtime
6792        // union's in `bynk-emit/runtime/src/http.ts` (`HttpOutcome<T>`).
6793        Ty::HttpOutcome(t) => Some(vec![
6794            VariantInfo {
6795                name: "Rejected".to_string(),
6796                payload: vec![("value".to_string(), tys.intern(Ty::BoundaryRejection))],
6797            },
6798            VariantInfo {
6799                name: "Handled".to_string(),
6800                payload: vec![("value".to_string(), tys.intern(Ty::HttpResult(*t)))],
6801            },
6802        ]),
6803        Ty::BoundaryRejection => Some(
6804            BOUNDARY_REJECTIONS
6805                .iter()
6806                .map(|(name, has_detail)| VariantInfo {
6807                    name: (*name).to_string(),
6808                    payload: if *has_detail {
6809                        vec![("detail".to_string(), tys.intern(Ty::Base(BaseType::String)))]
6810                    } else {
6811                        vec![]
6812                    },
6813                })
6814                .collect(),
6815        ),
6816        _ => None,
6817    }
6818}
6819
6820/// #1934: the variants of `BoundaryRejection`, each with whether it carries a
6821/// `detail: String` (the router's description of a refused body or path). The
6822/// first three are the router's `BoundaryError` kinds; `Unauthorized` is the
6823/// auth seam's `401` to a request with no credential, and `MethodNotAllowed`
6824/// the router's `405` to a method the path declares no handler for. The last two
6825/// are the router's `413` (a capped body over its cap) and `415` (a `@raw` route's
6826/// other `Content-Type`). Kept in
6827/// sync with `responseToHttpOutcome` in `bynk-emit/runtime/src/http.ts`.
6828pub const BOUNDARY_REJECTIONS: &[(&str, bool)] = &[
6829    ("RefinementViolation", true),
6830    ("MalformedJson", true),
6831    ("StructuralMismatch", true),
6832    ("Unauthorized", false),
6833    ("MethodNotAllowed", false),
6834    ("PayloadTooLarge", true),
6835    ("UnsupportedMediaType", true),
6836    // #3276: the router's `400` to a `multipart/form-data` body that is not one
6837    // (no boundary, never closed). A breaking addition to a closed sum, as ADR 0586's.
6838    ("MalformedForm", true),
6839];
6840
6841// ── v0.9.2: agent state-field zeroability ──────────────────────────────────
6842//
6843// Fresh agent state is the zero-value record (finding #10): a never-seen key
6844// reads `0` / `false` / `""` / `None` rather than `undefined`. A type is
6845// *zeroable* when it has a defined zero; agent state fields must be zeroable,
6846// since a fresh key has no committed value to load. Non-zeroable fields (a
6847// non-Option sum, an opaque type, or a refined type whose refinement excludes
6848// the underlying zero) are a compile error until explicit-initialiser syntax
6849// lands.
6850
6851/// #2137: `advance <Cap> by <amount>` — only in a test `case` body
6852/// (`bynk.test.advance_outside_case`), only on `Clock`
6853/// (`bynk.test.advance_not_clock`), and by a `Duration`
6854/// (`bynk.test.advance_not_duration`). A `Duration` literal can't be negated,
6855/// so a negative amount is always computed, and faults at run time.
6856fn check_advance(a: &AdvanceStmt, ctx: &mut Ctx) {
6857    let tys = ctx.tys;
6858    if !ctx.in_test_body {
6859        ctx.errors.push(
6860            CompileError::new(
6861                "bynk.test.advance_outside_case",
6862                a.keyword.merge(a.cap.span),
6863                "`advance` is only valid inside a `case` body",
6864            )
6865            .with_note(
6866                "`advance Clock by <Duration>` moves the test harness's clock; production code reads real time",
6867            ),
6868        );
6869    }
6870    if a.cap.name != "Clock" {
6871        ctx.errors.push(
6872            CompileError::new(
6873                "bynk.test.advance_not_clock",
6874                a.cap.span,
6875                format!(
6876                    "`advance` moves only `Clock`, but names `{}`",
6877                    a.cap.name
6878                ),
6879            )
6880            .with_note("the harness owns one time source, the first-party `Clock`; write `advance Clock by <Duration>`"),
6881        );
6882    }
6883    let duration = tys.intern(Ty::Base(BaseType::Duration));
6884    let ty = type_of(&a.amount, Some(duration), ctx);
6885    if let Some(actual) = ty
6886        && !compatible(actual, duration, tys)
6887    {
6888        ctx.errors.push(
6889            CompileError::new(
6890                "bynk.test.advance_not_duration",
6891                a.amount.span,
6892                format!(
6893                    "`advance Clock by` takes a `Duration`, but this is `{}`",
6894                    actual.display(tys)
6895                ),
6896            )
6897            .with_note("write a duration literal such as `15.minutes`"),
6898        );
6899    }
6900}
6901
6902/// #2138: the [`Callee::Intrinsic`] namespace of `run.id`.
6903pub const RUN_ID_NS: &str = "test.run";
6904
6905/// #2138 (track §3.7): whether `receiver.field` is `run.id` — a test body's
6906/// per-run identity, a `String` — rather than a field of something named
6907/// `run`. A fixed value in process; a fresh one for each `bynk test
6908/// --against` run, so ids built from it don't collide between runs.
6909fn is_run_id(receiver: &Expr, field: &Ident, ctx: &Ctx) -> bool {
6910    ctx.in_test_body
6911        && field.name == "id"
6912        && matches!(&receiver.kind, ExprKind::Ident(id) if id.name == "run" && ctx.lookup("run").is_none())
6913}
6914
6915#[cfg(test)]
6916mod generics_tests {
6917    use super::*;
6918
6919    fn var(tys: &Types, n: &str) -> TyId {
6920        tys.intern(Ty::Var(n.to_string()))
6921    }
6922    fn int(tys: &Types) -> TyId {
6923        tys.intern(Ty::Base(BaseType::Int))
6924    }
6925    fn string(tys: &Types) -> TyId {
6926        tys.intern(Ty::Base(BaseType::String))
6927    }
6928
6929    #[test]
6930    fn unify_binds_and_holds() {
6931        let tys = &Types::new();
6932        let mut s = HashMap::new();
6933        assert!(unify(var(tys, "A"), int(tys), &mut s, tys));
6934        assert_eq!(s.get("A"), Some(&int(tys)));
6935        // Same binding again: fine. A different one: conflict.
6936        assert!(unify(var(tys, "A"), int(tys), &mut s, tys));
6937        assert!(!unify(var(tys, "A"), string(tys), &mut s, tys));
6938    }
6939
6940    #[test]
6941    fn unify_walks_structure() {
6942        let tys = &Types::new();
6943        let mut s = HashMap::new();
6944        let pattern = tys.intern(Ty::Fn {
6945            params: vec![var(tys, "A")],
6946            ret: tys.intern(Ty::Effect(var(tys, "B"))),
6947        });
6948        let actual = tys.intern(Ty::Fn {
6949            params: vec![int(tys)],
6950            ret: tys.intern(Ty::Effect(string(tys))),
6951        });
6952        assert!(unify(pattern, actual, &mut s, tys));
6953        assert_eq!(s.get("A"), Some(&int(tys)));
6954        assert_eq!(s.get("B"), Some(&string(tys)));
6955    }
6956
6957    #[test]
6958    fn substitute_grounds_fully() {
6959        let tys = &Types::new();
6960        let mut s = HashMap::new();
6961        s.insert("A".to_string(), int(tys));
6962        let inner = tys.intern(Ty::Fn {
6963            params: vec![var(tys, "A")],
6964            ret: var(tys, "A"),
6965        });
6966        let t = tys.intern(Ty::Option(inner));
6967        let g = substitute(t, &s, tys);
6968        assert!(!contains_var(g, tys));
6969    }
6970
6971    /// The §2 invariant (pinned per the plan): every expected-driven feature
6972    /// in `type_of` matches *concrete* `Ty` variants, so a Var-bearing
6973    /// expected imposes no constraint — `compatible` must simply reject
6974    /// Var-vs-ground pairs rather than panic or accept.
6975    #[test]
6976    fn var_bearing_expected_is_benign() {
6977        let tys = &Types::new();
6978        assert!(!compatible(int(tys), var(tys, "A"), tys));
6979        assert!(!compatible(var(tys, "A"), int(tys), tys));
6980        // Rigid vars: name equality only.
6981        assert!(compatible(var(tys, "A"), var(tys, "A"), tys));
6982        assert!(!compatible(var(tys, "A"), var(tys, "B"), tys));
6983    }
6984}
6985
6986/// T3.6b (R4.1/R4.2): the interner's dedup property, and the `Hash`/`Eq`/`Ord`
6987/// it rests on.
6988///
6989/// T3.6a shipped the derives; these tests (added while scoping T3.6b, see the
6990/// identity-and-totality track doc §9) pinned the property `intern` would
6991/// depend on before it existed. Now that it does, they pin it directly: two
6992/// types built through *different construction paths* but structurally
6993/// identical must intern to the **same** `TyId` (or the checker's `TyId`
6994/// equality — which `unify` and `Ty::Map`'s key comparison now rely on —
6995/// would be unsound), and structurally different types must never collide.
6996///
6997/// Dedup being by the *shallow* `Ty` is exactly what makes this work: every
6998/// recursive field is already a `TyId`, so equal children imply equal parents
6999/// by induction. The nested cases below are what test that induction.
7000#[cfg(test)]
7001mod ty_hash_eq_ord_tests {
7002    use super::*;
7003    use std::collections::HashSet;
7004    use std::collections::hash_map::DefaultHasher;
7005    use std::hash::{Hash, Hasher};
7006
7007    fn hash_of(ty: &Ty) -> u64 {
7008        let mut h = DefaultHasher::new();
7009        ty.hash(&mut h);
7010        h.finish()
7011    }
7012
7013    /// `map_entry_ty` (a real constructor) vs. the raw `Ty::Named` literal it
7014    /// builds — two different construction paths for the same type.
7015    #[test]
7016    fn map_entry_ty_matches_its_own_raw_literal() {
7017        let tys = &Types::new();
7018        let int = tys.intern(Ty::Base(BaseType::Int));
7019        let string = tys.intern(Ty::Base(BaseType::String));
7020        let via_constructor = map_entry_ty(int, string, tys);
7021        let via_literal = tys.intern(Ty::Named {
7022            name: MAP_ENTRY.to_string(),
7023            kind: NamedKind::Record,
7024            args: vec![int, string],
7025        });
7026        assert_eq!(via_constructor, via_literal);
7027        assert_eq!(
7028            hash_of(&tys.get(via_constructor)),
7029            hash_of(&tys.get(via_literal))
7030        );
7031    }
7032
7033    /// A deeply nested type built two separate times interns to one `TyId` —
7034    /// the property `unify`'s "matches its prior binding exactly" now rests on.
7035    #[test]
7036    fn structurally_identical_nested_types_intern_to_one_id() {
7037        let tys = &Types::new();
7038        let build = || {
7039            let int = tys.intern(Ty::Base(BaseType::Int));
7040            let opt = tys.intern(Ty::Option(int));
7041            let list = tys.intern(Ty::List(opt));
7042            let string = tys.intern(Ty::Base(BaseType::String));
7043            tys.intern(Ty::Map(string, list))
7044        };
7045        let a = build();
7046        let before = tys.len();
7047        let b = build();
7048        assert_eq!(a, b);
7049        // Re-building it added nothing: every node was already interned.
7050        assert_eq!(tys.len(), before);
7051        assert_eq!(hash_of(&tys.get(a)), hash_of(&tys.get(b)));
7052    }
7053
7054    /// Structurally different types must get distinct ids — the flip side of
7055    /// the dedup property above.
7056    #[test]
7057    fn structurally_different_types_get_distinct_ids() {
7058        let tys = &Types::new();
7059        let int = tys.intern(Ty::Base(BaseType::Int));
7060        let string = tys.intern(Ty::Base(BaseType::String));
7061        let ids = HashSet::from([
7062            tys.intern(Ty::List(int)),
7063            tys.intern(Ty::List(string)),
7064            tys.intern(Ty::Option(int)),
7065        ]);
7066        assert_eq!(ids.len(), 3);
7067    }
7068
7069    /// Interning the same type repeatedly grows the table exactly once.
7070    #[test]
7071    fn repeated_interning_grows_the_table_once() {
7072        let tys = &Types::new();
7073        let int = tys.intern(Ty::Base(BaseType::Int));
7074        let bool_ = tys.intern(Ty::Base(BaseType::Bool));
7075        let before = tys.len();
7076        let ids: HashSet<TyId> = (0..3).map(|_| map_entry_ty(int, bool_, tys)).collect();
7077        assert_eq!(ids.len(), 1);
7078        assert_eq!(tys.len(), before + 1);
7079    }
7080
7081    /// `resolve`-round-trip: an id resolves to the node it was minted from.
7082    #[test]
7083    fn an_id_resolves_to_the_node_it_was_interned_from() {
7084        let tys = &Types::new();
7085        let int = tys.intern(Ty::Base(BaseType::Int));
7086        assert_eq!(&*tys.get(int), &Ty::Base(BaseType::Int));
7087        let list = tys.intern(Ty::List(int));
7088        assert_eq!(&*tys.get(list), &Ty::List(int));
7089    }
7090
7091    /// A `TyId` is only meaningful in the table it was minted from — the one
7092    /// new failure mode interning introduces. It fails loudly and by name;
7093    /// pinned so the diagnosis stays cheap for the next reader who wires two
7094    /// tables together by accident.
7095    ///
7096    /// This is the *shorter*-table shape, which both migration bugs had and
7097    /// which a bounds check alone catches. Its sibling below is the shape
7098    /// that actually needs the tag.
7099    #[test]
7100    #[should_panic(expected = "resolved against a table it was not interned into")]
7101    fn an_id_from_another_table_is_a_named_panic_not_a_silent_wrong_answer() {
7102        let a = Types::new();
7103        let b = Types::new();
7104        let id = a.intern(Ty::Base(BaseType::Int));
7105        let _ = b.get(id);
7106    }
7107
7108    /// The sharp edge of the same guard: a foreign id whose index is merely
7109    /// *in range*. Before `TyId` carried its table's tag this returned an
7110    /// unrelated `Ty` — here, `Bool` for an id minted from `Int` — and the
7111    /// caller went on to mis-diagnose or mis-emit with no panic at all. The
7112    /// bounds check cannot see this one, so it is the case worth pinning.
7113    ///
7114    /// Debug-only, because that is where the tag exists; a release build
7115    /// still has the length check the sibling above covers.
7116    #[cfg(debug_assertions)]
7117    #[test]
7118    #[should_panic(expected = "resolved against a table it was not interned into")]
7119    fn an_in_range_id_from_another_table_panics_rather_than_resolving_wrongly() {
7120        let a = Types::new();
7121        let b = Types::new();
7122        let id = a.intern(Ty::Base(BaseType::Int));
7123        b.intern(Ty::Base(BaseType::Bool));
7124        assert_eq!(a.len(), b.len(), "the index must be in range for b");
7125        let _ = b.get(id);
7126    }
7127
7128    /// T3.6b's own soundness guard: `compatible` is deliberately **not**
7129    /// reflexive for the sealed boundary values, so interning must not be
7130    /// short-circuited on id equality. Pinned here because the fast path is
7131    /// the obvious "optimisation" a later reader would add.
7132    #[test]
7133    fn compatible_is_not_reflexive_for_sealed_actor_types() {
7134        let tys = &Types::new();
7135        let id_ty = tys.intern(Ty::Base(BaseType::String));
7136        let actor = tys.intern(Ty::Actor(id_ty));
7137        assert!(!compatible(actor, actor, tys));
7138        let sum = tys.intern(Ty::ActorSum(vec![("User".to_string(), id_ty)]));
7139        assert!(!compatible(sum, sum, tys));
7140        // …while an ordinary type still is.
7141        assert!(compatible(id_ty, id_ty, tys));
7142    }
7143}
7144
7145/// Characterization pins for `checker.rs`'s pure free functions (v0.29.10
7146/// slice 0). These pin *current* behaviour ahead of the upcoming module split
7147/// so the verbatim moves are verifiable. Any surprising behaviour is pinned
7148/// as-is, flagged with a comment — these are not specifications.
7149#[cfg(test)]
7150mod pure_helper_pins {
7151    use super::*;
7152    use bynk_syntax::ast::{FloatBound, RefinementPred};
7153
7154    // -- small constructors ------------------------------------------------
7155
7156    fn sp() -> Span {
7157        Span::new(0, 0)
7158    }
7159    fn ident(n: &str) -> Ident {
7160        Ident {
7161            name: n.to_string(),
7162            span: sp(),
7163        }
7164    }
7165    fn var(tys: &Types, n: &str) -> TyId {
7166        tys.intern(Ty::Var(n.to_string()))
7167    }
7168    fn int(tys: &Types) -> TyId {
7169        tys.intern(Ty::Base(BaseType::Int))
7170    }
7171    fn string(tys: &Types) -> TyId {
7172        tys.intern(Ty::Base(BaseType::String))
7173    }
7174    fn expr(kind: ExprKind) -> Expr {
7175        Expr {
7176            id: ExprId::SYNTHETIC,
7177            kind,
7178            span: sp(),
7179        }
7180    }
7181    fn pred(kind: PredKind) -> RefinementPred {
7182        RefinementPred {
7183            kind,
7184            arg_text: None,
7185            span: sp(),
7186        }
7187    }
7188    fn refinement(preds: Vec<PredKind>) -> Refinement {
7189        Refinement {
7190            annotations: Vec::new(),
7191            predicates: preds.into_iter().map(pred).collect(),
7192            span: sp(),
7193        }
7194    }
7195    fn fbound(value: f64) -> FloatBound {
7196        FloatBound {
7197            value,
7198            lexeme: value.to_string(),
7199            span: Span::new(0, 0),
7200        }
7201    }
7202    fn ibound(value: i64) -> IntBound {
7203        IntBound {
7204            value,
7205            lexeme: value.to_string(),
7206            span: Span::new(0, 0),
7207        }
7208    }
7209    /// An `InRange` predicate from two int values (test convenience).
7210    fn in_range(lo: i64, hi: i64) -> PredKind {
7211        PredKind::InRange(ibound(lo), ibound(hi))
7212    }
7213    fn refined_decl(name: &str, base: BaseType, refinement: Option<Refinement>) -> TypeDecl {
7214        TypeDecl {
7215            derives: Vec::new(),
7216            derives_kw: None,
7217            name: ident(name),
7218            type_params: Vec::new(),
7219            body: TypeBody::Refined {
7220                base,
7221                base_span: sp(),
7222                refinement,
7223            },
7224            documentation: None,
7225            span: sp(),
7226            trivia: bynk_syntax::ast::Trivia::default(),
7227            private: None,
7228        }
7229    }
7230    fn record_decl(name: &str) -> TypeDecl {
7231        TypeDecl {
7232            derives: Vec::new(),
7233            derives_kw: None,
7234            name: ident(name),
7235            type_params: Vec::new(),
7236            body: TypeBody::Record(bynk_syntax::ast::RecordBody {
7237                trailing_comments: Default::default(),
7238                fields: vec![],
7239                span: sp(),
7240            }),
7241            documentation: None,
7242            span: sp(),
7243            trivia: bynk_syntax::ast::Trivia::default(),
7244            private: None,
7245        }
7246    }
7247
7248    // -- unify -------------------------------------------------------------
7249
7250    #[test]
7251    fn unify_identical_concrete_types() {
7252        let tys = &Types::new();
7253        let mut s = HashMap::new();
7254        assert!(unify(int(tys), int(tys), &mut s, tys));
7255        assert!(s.is_empty());
7256    }
7257
7258    #[test]
7259    fn unify_var_binds_in_subst() {
7260        let tys = &Types::new();
7261        let mut s = HashMap::new();
7262        assert!(unify(var(tys, "A"), string(tys), &mut s, tys));
7263        assert_eq!(s.get("A"), Some(&string(tys)));
7264    }
7265
7266    #[test]
7267    fn unify_nested_generic_binds() {
7268        let tys = &Types::new();
7269        // List[A] vs List[Int] binds A := Int.
7270        let mut s = HashMap::new();
7271        let pat = tys.intern(Ty::List(var(tys, "A")));
7272        let act = tys.intern(Ty::List(int(tys)));
7273        assert!(unify(pat, act, &mut s, tys));
7274        assert_eq!(s.get("A"), Some(&int(tys)));
7275    }
7276
7277    #[test]
7278    fn unify_surprise_concrete_mismatch_returns_true() {
7279        let tys = &Types::new();
7280        // SURPRISING (pinned as-is): `unify`'s catch-all is `_ => true`, so a
7281        // ground-vs-ground mismatch (Int vs String) and a constructor mismatch
7282        // (List vs Option) both *succeed* here — `compatible` owns those
7283        // diagnostics post-substitution, not `unify`.
7284        let mut s = HashMap::new();
7285        assert!(unify(int(tys), string(tys), &mut s, tys));
7286        assert!(unify(
7287            tys.intern(Ty::List(int(tys))),
7288            tys.intern(Ty::Option(int(tys))),
7289            &mut s,
7290            tys
7291        ));
7292        // The only false paths: a Var rebind conflict and an Fn arity mismatch.
7293        let mut s2 = HashMap::new();
7294        assert!(unify(var(tys, "A"), int(tys), &mut s2, tys));
7295        assert!(!unify(var(tys, "A"), string(tys), &mut s2, tys));
7296        let mut s3 = HashMap::new();
7297        let f1 = tys.intern(Ty::Fn {
7298            params: vec![int(tys)],
7299            ret: int(tys),
7300        });
7301        let f2 = tys.intern(Ty::Fn {
7302            params: vec![int(tys), int(tys)],
7303            ret: int(tys),
7304        });
7305        assert!(!unify(f1, f2, &mut s3, tys));
7306    }
7307
7308    // -- substitute --------------------------------------------------------
7309
7310    #[test]
7311    fn substitute_replaces_bound_var() {
7312        let tys = &Types::new();
7313        let mut s = HashMap::new();
7314        s.insert("A".to_string(), int(tys));
7315        assert_eq!(substitute(var(tys, "A"), &s, tys), int(tys));
7316    }
7317
7318    #[test]
7319    fn substitute_recurses_into_nested() {
7320        let tys = &Types::new();
7321        let mut s = HashMap::new();
7322        s.insert("A".to_string(), string(tys));
7323        let t = tys.intern(Ty::Map(var(tys, "A"), int(tys)));
7324        assert_eq!(
7325            substitute(t, &s, tys),
7326            tys.intern(Ty::Map(string(tys), int(tys))),
7327        );
7328    }
7329
7330    #[test]
7331    fn substitute_leaves_unbound_var_alone() {
7332        let tys = &Types::new();
7333        let s = HashMap::new();
7334        assert_eq!(substitute(var(tys, "Z"), &s, tys), var(tys, "Z"));
7335    }
7336
7337    // -- contains_var / contains_flexible_var ------------------------------
7338
7339    #[test]
7340    fn contains_var_positive_and_negative() {
7341        let tys = &Types::new();
7342        assert!(contains_var(tys.intern(Ty::Option(var(tys, "A"))), tys));
7343        assert!(!contains_var(tys.intern(Ty::Option(int(tys))), tys));
7344        assert!(!contains_var(int(tys), tys));
7345    }
7346
7347    #[test]
7348    fn contains_flexible_var_respects_rigid_set() {
7349        let tys = &Types::new();
7350        let mut rigid = HashSet::new();
7351        rigid.insert("A".to_string());
7352        // A is rigid → not flexible.
7353        assert!(!contains_flexible_var(var(tys, "A"), &rigid, tys));
7354        // B is not rigid → flexible.
7355        assert!(contains_flexible_var(var(tys, "B"), &rigid, tys));
7356        // No vars at all → not flexible.
7357        assert!(!contains_flexible_var(int(tys), &rigid, tys));
7358    }
7359
7360    // -- peel_to_* ---------------------------------------------------------
7361
7362    #[test]
7363    fn peel_to_result_matches_and_misses() {
7364        let tys = &Types::new();
7365        let r = tys.intern(Ty::Result(int(tys), string(tys)));
7366        assert_eq!(peel_to_result(r, tys), Some((int(tys), string(tys))));
7367        assert_eq!(peel_to_result(int(tys), tys), None);
7368        // Pinned: peels through Effect[_].
7369        assert_eq!(
7370            peel_to_result(tys.intern(Ty::Effect(r)), tys),
7371            Some((int(tys), string(tys)))
7372        );
7373    }
7374
7375    #[test]
7376    fn peel_to_option_matches_and_misses() {
7377        let tys = &Types::new();
7378        assert_eq!(
7379            peel_to_option(tys.intern(Ty::Option(int(tys))), tys),
7380            Some(int(tys))
7381        );
7382        assert_eq!(peel_to_option(int(tys), tys), None);
7383    }
7384
7385    #[test]
7386    fn peel_to_list_matches_and_misses() {
7387        let tys = &Types::new();
7388        assert_eq!(
7389            peel_to_list(tys.intern(Ty::List(string(tys))), tys),
7390            Some(string(tys))
7391        );
7392        assert_eq!(peel_to_list(int(tys), tys), None);
7393    }
7394
7395    #[test]
7396    fn peel_to_map_matches_and_misses() {
7397        let tys = &Types::new();
7398        let m = tys.intern(Ty::Map(string(tys), int(tys)));
7399        assert_eq!(peel_to_map(m, tys), Some((string(tys), int(tys))));
7400        assert_eq!(peel_to_map(int(tys), tys), None);
7401    }
7402
7403    #[test]
7404    fn peel_to_http_result_matches_and_misses() {
7405        let tys = &Types::new();
7406        assert_eq!(
7407            peel_to_http_result(tys.intern(Ty::HttpResult(int(tys))), tys),
7408            Some(int(tys)),
7409        );
7410        assert_eq!(peel_to_http_result(int(tys), tys), None);
7411    }
7412
7413    // -- maybe_auto_lift ---------------------------------------------------
7414
7415    #[test]
7416    fn maybe_auto_lift_lifts_into_expected_effect() {
7417        let tys = &Types::new();
7418        // T lifts to Effect[T] when expected is Effect[T] and T is not effectful.
7419        let expected = tys.intern(Ty::Effect(int(tys)));
7420        let lifted = maybe_auto_lift(Some(int(tys)), Some(expected), tys);
7421        assert_eq!(lifted, Some(tys.intern(Ty::Effect(int(tys)))));
7422    }
7423
7424    #[test]
7425    fn maybe_auto_lift_leaves_non_matching_alone() {
7426        let tys = &Types::new();
7427        // Already Effect[_]: untouched.
7428        let expected = tys.intern(Ty::Effect(int(tys)));
7429        assert_eq!(
7430            maybe_auto_lift(Some(tys.intern(Ty::Effect(int(tys)))), Some(expected), tys),
7431            Some(tys.intern(Ty::Effect(int(tys)))),
7432        );
7433        // Expected not an Effect: untouched.
7434        assert_eq!(
7435            maybe_auto_lift(Some(int(tys)), Some(int(tys)), tys),
7436            Some(int(tys))
7437        );
7438        // None type: untouched.
7439        assert_eq!(maybe_auto_lift(None, Some(expected), tys), None);
7440    }
7441
7442    // -- const_literal -----------------------------------------------------
7443
7444    #[test]
7445    fn const_literal_extracts_literals() {
7446        assert!(matches!(
7447            const_literal(&expr(ExprKind::int_lit(7))),
7448            Some(ConstLit::Int(7)),
7449        ));
7450        assert!(matches!(
7451            const_literal(&expr(ExprKind::BoolLit(true))),
7452            Some(ConstLit::Bool(true)),
7453        ));
7454        assert!(matches!(
7455            const_literal(&expr(ExprKind::StrLit("hi".into()))),
7456            Some(ConstLit::Str(s)) if s == "hi",
7457        ));
7458        assert!(matches!(
7459            const_literal(&expr(ExprKind::FloatLit {
7460                value: 1.5,
7461                lexeme: "1.5".into(),
7462            })),
7463            Some(ConstLit::Float(_)),
7464        ));
7465        // Unary-neg on an int literal folds.
7466        let neg = expr(ExprKind::UnaryOp(
7467            UnaryOp::Neg,
7468            Box::new(expr(ExprKind::int_lit(3))),
7469        ));
7470        assert!(matches!(const_literal(&neg), Some(ConstLit::Int(-3))));
7471    }
7472
7473    #[test]
7474    fn const_literal_rejects_non_literals() {
7475        assert!(const_literal(&expr(ExprKind::Ident(ident("x")))).is_none());
7476    }
7477
7478    // -- eval_predicate ----------------------------------------------------
7479
7480    #[test]
7481    fn eval_predicate_int_and_float() {
7482        assert!(eval_predicate(&PredKind::NonNegative, &ConstLit::Int(0)));
7483        assert!(!eval_predicate(&PredKind::NonNegative, &ConstLit::Int(-1)));
7484        assert!(eval_predicate(&PredKind::Positive, &ConstLit::Int(1)));
7485        assert!(!eval_predicate(&PredKind::Positive, &ConstLit::Int(0)));
7486        assert!(eval_predicate(&in_range(1, 10), &ConstLit::Int(5),));
7487        assert!(!eval_predicate(&in_range(1, 10), &ConstLit::Int(11),));
7488    }
7489
7490    #[test]
7491    fn eval_predicate_string() {
7492        assert!(eval_predicate(
7493            &PredKind::MinLength(2),
7494            &ConstLit::Str("ab".into()),
7495        ));
7496        assert!(!eval_predicate(
7497            &PredKind::MinLength(3),
7498            &ConstLit::Str("ab".into()),
7499        ));
7500        assert!(eval_predicate(
7501            &PredKind::NonEmpty,
7502            &ConstLit::Str("x".into()),
7503        ));
7504        assert!(!eval_predicate(
7505            &PredKind::NonEmpty,
7506            &ConstLit::Str(String::new()),
7507        ));
7508        assert!(eval_predicate(
7509            &PredKind::Matches("[a-z]+".into()),
7510            &ConstLit::Str("abc".into()),
7511        ));
7512        assert!(!eval_predicate(
7513            &PredKind::Matches("[a-z]+".into()),
7514            &ConstLit::Str("ABC".into()),
7515        ));
7516    }
7517
7518    #[test]
7519    fn eval_predicate_base_mismatch_is_vacuously_true() {
7520        // SURPRISING (pinned as-is): a predicate/literal base mismatch returns
7521        // `true` — base/predicate mismatch is a declaration-time error reported
7522        // elsewhere, not by construction-time eval.
7523        assert!(eval_predicate(&PredKind::MinLength(5), &ConstLit::Int(0),));
7524    }
7525
7526    // -- literal_matches_base ----------------------------------------------
7527
7528    #[test]
7529    fn literal_matches_base_pairs() {
7530        assert!(literal_matches_base(&ConstLit::Int(1), BaseType::Int));
7531        assert!(literal_matches_base(
7532            &ConstLit::Str("x".into()),
7533            BaseType::String,
7534        ));
7535        assert!(!literal_matches_base(&ConstLit::Int(1), BaseType::String));
7536        assert!(!literal_matches_base(&ConstLit::Unit, BaseType::Int));
7537    }
7538
7539    // -- type_decl_base / type_decl_refinement -----------------------------
7540
7541    #[test]
7542    fn type_decl_base_refined_vs_record() {
7543        let refined = refined_decl("Age", BaseType::Int, None);
7544        assert_eq!(type_decl_base(&refined), Some(BaseType::Int));
7545        assert_eq!(type_decl_base(&record_decl("Pt")), None);
7546    }
7547
7548    #[test]
7549    fn type_decl_refinement_present_vs_absent() {
7550        let with = refined_decl(
7551            "Age",
7552            BaseType::Int,
7553            Some(refinement(vec![PredKind::Positive])),
7554        );
7555        assert!(type_decl_refinement(&with).is_some());
7556        let without = refined_decl("Raw", BaseType::Int, None);
7557        assert!(type_decl_refinement(&without).is_none());
7558        assert!(type_decl_refinement(&record_decl("Pt")).is_none());
7559    }
7560
7561    // -- check_*_refinement_consistency ------------------------------------
7562
7563    #[test]
7564    fn int_refinement_consistency() {
7565        // Consistent: 1..=10 with Positive — no error.
7566        let mut errs = vec![];
7567        check_int_refinement_consistency(
7568            &refinement(vec![PredKind::Positive, in_range(1, 10)]),
7569            &mut errs,
7570        );
7571        assert!(errs.is_empty());
7572        // Inconsistent: InRange(10, 1) is empty → exactly one error.
7573        let mut errs = vec![];
7574        check_int_refinement_consistency(&refinement(vec![in_range(10, 1)]), &mut errs);
7575        assert_eq!(errs.len(), 1);
7576        assert_eq!(errs[0].category, "bynk.types.empty_refinement");
7577    }
7578
7579    #[test]
7580    fn float_refinement_consistency() {
7581        // Consistent range.
7582        let mut errs = vec![];
7583        check_float_refinement_consistency(
7584            &refinement(vec![PredKind::InRangeF(fbound(0.0), fbound(1.0))]),
7585            &mut errs,
7586        );
7587        assert!(errs.is_empty());
7588        // Empty: 5.0..=1.0 → one error.
7589        let mut errs = vec![];
7590        check_float_refinement_consistency(
7591            &refinement(vec![PredKind::InRangeF(fbound(5.0), fbound(1.0))]),
7592            &mut errs,
7593        );
7594        assert_eq!(errs.len(), 1);
7595        assert_eq!(errs[0].category, "bynk.types.empty_refinement");
7596        // Degenerate-but-exclusive: Positive with InRangeF(0.0, 0.0) → lo==hi
7597        // and lo_exclusive → one error.
7598        let mut errs = vec![];
7599        check_float_refinement_consistency(
7600            &refinement(vec![
7601                PredKind::Positive,
7602                PredKind::InRangeF(fbound(0.0), fbound(0.0)),
7603            ]),
7604            &mut errs,
7605        );
7606        assert_eq!(errs.len(), 1);
7607    }
7608
7609    #[test]
7610    fn string_refinement_consistency() {
7611        // Consistent: MinLength(1), MaxLength(10).
7612        let mut errs = vec![];
7613        check_string_refinement_consistency(
7614            &refinement(vec![PredKind::MinLength(1), PredKind::MaxLength(10)]),
7615            &mut errs,
7616        );
7617        assert!(errs.is_empty());
7618        // min > max → one error.
7619        let mut errs = vec![];
7620        check_string_refinement_consistency(
7621            &refinement(vec![PredKind::MinLength(10), PredKind::MaxLength(2)]),
7622            &mut errs,
7623        );
7624        assert_eq!(errs.len(), 1);
7625        assert_eq!(errs[0].category, "bynk.types.empty_refinement");
7626        // Conflicting exact lengths → TWO errors (pinned as-is): the explicit
7627        // `Length(3)`/`Length(5)` conflict push, *plus* the subsequent
7628        // min_len(5) > max_len(3) empty-range push (each `Length` clamps both
7629        // bounds to itself).
7630        let mut errs = vec![];
7631        check_string_refinement_consistency(
7632            &refinement(vec![PredKind::Length(3), PredKind::Length(5)]),
7633            &mut errs,
7634        );
7635        assert_eq!(errs.len(), 2);
7636        assert!(
7637            errs.iter()
7638                .all(|e| e.category == "bynk.types.empty_refinement")
7639        );
7640    }
7641
7642    /// R12.2/T1.8: `NonEmpty` folds to `MinLength(1)` in `contract::canon_predicate`,
7643    /// so the two spellings are the same refinement. A strictly *tighter* receiver
7644    /// still fails (T1.8's `1021_refined_boundary_mismatch`); since #2802 a
7645    /// strictly tighter *sender* is admitted.
7646    #[test]
7647    fn refinements_match_treats_non_empty_and_min_length_one_as_equal() {
7648        let s = BaseType::String;
7649        let a = refinement(vec![PredKind::NonEmpty]);
7650        let b = refinement(vec![PredKind::MinLength(1)]);
7651        assert!(refinements_match(s, Some(&a), Some(&b)));
7652        let c = refinement(vec![PredKind::MinLength(2)]);
7653        assert!(!refinements_match(s, Some(&a), Some(&c)));
7654        assert!(refinements_match(s, Some(&c), Some(&a)));
7655    }
7656
7657    /// #2802: one row of the entailment table per assertion.
7658    #[test]
7659    fn refinements_match_admits_a_stronger_sender() {
7660        let s = BaseType::String;
7661        let max = |n| refinement(vec![PredKind::MaxLength(n)]);
7662        assert!(refinements_match(s, Some(&max(4)), Some(&max(8))));
7663        assert!(!refinements_match(s, Some(&max(8)), Some(&max(4))));
7664        let len3 = refinement(vec![PredKind::Length(3)]);
7665        let both = refinement(vec![PredKind::MinLength(1), PredKind::MaxLength(8)]);
7666        assert!(refinements_match(s, Some(&len3), Some(&both)));
7667        // Unrefined: anything entails the empty conjunction, nothing entails a refinement.
7668        assert!(refinements_match(s, Some(&max(4)), None));
7669        assert!(!refinements_match(s, None, Some(&max(4))));
7670        let i = BaseType::Int;
7671        let pos = refinement(vec![PredKind::Positive]);
7672        let nn = refinement(vec![PredKind::NonNegative]);
7673        assert!(refinements_match(i, Some(&pos), Some(&nn)));
7674        assert!(!refinements_match(i, Some(&nn), Some(&pos)));
7675    }
7676
7677    // -- numeric_mix -------------------------------------------------------
7678
7679    #[test]
7680    fn numeric_mix_int_float_pairs() {
7681        assert!(numeric_mix(Some(BaseType::Int), Some(BaseType::Float)));
7682        assert!(numeric_mix(Some(BaseType::Float), Some(BaseType::Int)));
7683        assert!(!numeric_mix(Some(BaseType::Int), Some(BaseType::Int)));
7684        assert!(!numeric_mix(Some(BaseType::Float), Some(BaseType::Float)));
7685        assert!(!numeric_mix(None, Some(BaseType::Int)));
7686    }
7687}
7688
7689/// The shape accessors on [`Ty`] (`as_option`, `as_list`, `as_effect`, `as_result`,
7690/// `scalar_base`): each answers for the variant it names and `None` for every other.
7691#[cfg(test)]
7692mod ty_accessor_tests {
7693    use super::*;
7694
7695    #[test]
7696    fn each_shape_accessor_answers_only_for_its_own_variant() {
7697        let tys = Types::new();
7698        let int = tys.intern(Ty::Base(BaseType::Int));
7699        let string = tys.intern(Ty::Base(BaseType::String));
7700        let option = Ty::Option(int);
7701        let list = Ty::List(int);
7702        let effect = Ty::Effect(int);
7703        let result = Ty::Result(int, string);
7704
7705        assert_eq!(option.as_option(), Some(int));
7706        assert_eq!(list.as_list(), Some(int));
7707        assert_eq!(effect.as_effect(), Some(int));
7708        assert_eq!(result.as_result(), Some((int, string)));
7709
7710        for other in [&list, &effect, &result, &Ty::Unit, &Ty::Base(BaseType::Int)] {
7711            assert_eq!(other.as_option(), None);
7712        }
7713        for other in [&option, &effect, &result, &Ty::Set(int), &Ty::Unit] {
7714            assert_eq!(other.as_list(), None);
7715        }
7716        for other in [&option, &list, &result, &Ty::Query(int), &Ty::Unit] {
7717            assert_eq!(other.as_effect(), None);
7718        }
7719        for other in [&option, &list, &effect, &Ty::Map(int, string), &Ty::Unit] {
7720            assert_eq!(other.as_result(), None);
7721        }
7722    }
7723
7724    #[test]
7725    fn scalar_base_reads_base_refined_and_opaque_but_not_records_or_sums() {
7726        let named = |kind| Ty::Named {
7727            name: "T".to_string(),
7728            kind,
7729            args: vec![],
7730        };
7731        assert_eq!(
7732            Ty::Base(BaseType::String).scalar_base(),
7733            Some(BaseType::String)
7734        );
7735        assert_eq!(
7736            named(NamedKind::Refined(BaseType::Int)).scalar_base(),
7737            Some(BaseType::Int)
7738        );
7739        assert_eq!(
7740            named(NamedKind::Opaque(BaseType::Bytes)).scalar_base(),
7741            Some(BaseType::Bytes)
7742        );
7743        assert_eq!(named(NamedKind::Record).scalar_base(), None);
7744        assert_eq!(named(NamedKind::Sum).scalar_base(), None);
7745        assert_eq!(Ty::Unit.scalar_base(), None);
7746        // `base` is the same question minus the opaque case, which does not widen.
7747        assert_eq!(named(NamedKind::Opaque(BaseType::Bytes)).base(), None);
7748    }
7749}