Skip to main content

bynk_check/
resolver.rs

1//! Name resolution (spec §5.1, v0.1 §4.1, v0.2 §4.1).
2//!
3//! Builds symbol tables for the commons and validates that:
4//! - No two top-level items share a name (types, fns, methods are all named).
5//! - Every `TypeRef::Named` resolves to a declared type.
6//! - Every free function call resolves to a function declaration.
7//! - Every identifier in expression position resolves to a parameter, a
8//!   `let` binding, or `self` (inside a method).
9//! - Constructor / static calls (`TypeName.method(args)`) resolve either to
10//!   the built-in `T.of` of a refined type, a static method on `T`, or a
11//!   variant constructor when `T` is a sum type.
12//! - Record construction targets a declared record type and uses only
13//!   declared fields.
14//! - Method calls resolve via the receiver's nominal type (the actual type
15//!   check happens in the type checker).
16//!
17//! On success returns a [`ResolvedCommons`] — the original AST plus
18//! symbol tables the type checker consumes.
19
20use std::collections::{HashMap, HashSet};
21use std::sync::Arc;
22
23use crate::index::{RefSink, SymbolKind};
24use bynk_project::UnitKind;
25use bynk_syntax::ast::*;
26use bynk_syntax::error::{Applicability, CompileError};
27use bynk_syntax::span::Span;
28
29/// Is `name` a type imported via `uses` of a *commons* specifically — the
30/// exact predicate [`ResolvedCommons::is_uses_commons_type`] caches as
31/// `uses_commons_type_names`, and `bynk-emit` needs at *two* real call
32/// sites that must never disagree: `emit_context_rebrands`'s own two steps,
33/// "alias the import" and "rebrand the type" (its own doc comment, step 1
34/// "Done in imports", step 2 the rebrand itself, both in
35/// `bynk-emit/src/emitter.rs`) — an import narrower than the rebrand leaves
36/// an undefined name in the generated module; a rebrand narrower than the
37/// import leaves an alias imported and never used.
38///
39/// R4.10/R8.2 (`design/bynk-greenfield-compiler.md`): before this function
40/// existed, `prepare_unit_check_ctx` (`check_pipeline.rs`) and *both*
41/// `bynk-emit` call sites above each independently inlined this same
42/// two-condition check, linked only by a doc comment promising they all
43/// matched exactly — a real risk ADR 0226 names (#655: "a single named
44/// binder took the entire test run down, pointing at generated code the
45/// author never wrote"). One definition, every caller reads it — an edit to
46/// either condition can no longer silently update only one side.
47pub fn compute_is_uses_commons_type(
48    imported_from_kind: &HashMap<String, UnitKind>,
49    types: &HashMap<String, Arc<TypeDecl>>,
50    name: &str,
51) -> bool {
52    matches!(imported_from_kind.get(name), Some(UnitKind::Commons)) && types.contains_key(name)
53}
54
55#[cfg(test)]
56mod compute_is_uses_commons_type_tests {
57    use super::compute_is_uses_commons_type;
58    use bynk_project::UnitKind;
59    use bynk_syntax::ast::{Ident, RecordBody, Trivia, TypeBody, TypeDecl};
60    use bynk_syntax::span::Span;
61    use std::collections::HashMap;
62    use std::sync::Arc;
63
64    fn bare_record_type(name: &str) -> Arc<TypeDecl> {
65        Arc::new(TypeDecl {
66            derives: Vec::new(),
67            derives_kw: None,
68            type_params: Vec::new(),
69            name: Ident {
70                name: name.to_string(),
71                span: Span::default(),
72            },
73            body: TypeBody::Record(RecordBody {
74                trailing_comments: Default::default(),
75                fields: Vec::new(),
76                span: Span::default(),
77            }),
78            documentation: None,
79            span: Span::default(),
80            trivia: Trivia::default(),
81            private: None,
82        })
83    }
84
85    /// The four combinations the real callers' own doc comments describe:
86    /// a `uses`-imported commons type (the only `true` case), a
87    /// `uses`-imported commons *function* (v0.20b's own carve-out — not
88    /// rebranded, a value not a type), a name imported from a non-commons
89    /// unit kind (a consumed context, say), and a name absent from
90    /// `imported_from_kind` entirely (a local declaration).
91    #[test]
92    fn matches_a_commons_imported_type_only() {
93        let mut kinds = HashMap::new();
94        kinds.insert("Money".to_string(), UnitKind::Commons);
95        kinds.insert("traverse".to_string(), UnitKind::Commons);
96        kinds.insert("Order".to_string(), UnitKind::Context);
97        let mut types = HashMap::new();
98        types.insert("Money".to_string(), bare_record_type("Money"));
99        types.insert("Order".to_string(), bare_record_type("Order"));
100
101        assert!(compute_is_uses_commons_type(&kinds, &types, "Money"));
102        assert!(
103            !compute_is_uses_commons_type(&kinds, &types, "traverse"),
104            "a uses-imported commons function is a value, not a type — v0.20b"
105        );
106        assert!(
107            !compute_is_uses_commons_type(&kinds, &types, "Order"),
108            "imported from a context, not a commons"
109        );
110        assert!(
111            !compute_is_uses_commons_type(&kinds, &types, "Local"),
112            "absent from imported_from_kind entirely — a local declaration"
113        );
114    }
115}
116
117/// The resolver's two collection points, bundled so the reference walk
118/// threads one parameter (v0.25, ADR 0053). `push` forwards to the error
119/// list, keeping the walk's error sites unchanged; binding edges record
120/// via `refs` at the site that resolved them.
121pub(crate) struct Sinks<'a> {
122    errs: &'a mut Vec<CompileError>,
123    pub(crate) refs: &'a mut RefSink,
124}
125
126impl Sinks<'_> {
127    fn push(&mut self, e: CompileError) {
128        self.errs.push(e);
129    }
130}
131
132/// Per-type method table built during resolution: keyed by method name,
133/// values are clones of the [`FnDecl`] for that method.
134#[derive(Debug, Default, Clone)]
135pub struct MethodTable {
136    pub instance: HashMap<String, Arc<FnDecl>>,
137    pub statics: HashMap<String, Arc<FnDecl>>,
138}
139
140/// Output of resolution: the AST plus the symbol tables the checker needs.
141pub struct ResolvedCommons {
142    pub commons: Arc<Commons>,
143    /// Finding #10/#51: `Arc`-wrapped (not owned) so cloning this map — done
144    /// once per synthetic per-handler `ResolvedCommons` during emission — is
145    /// a pointer bump, not a deep copy of every declaration body in the unit.
146    pub types: HashMap<String, Arc<TypeDecl>>,
147    /// Finding #10/#51: `Arc`-wrapped for the same reason as `types`.
148    pub fns: HashMap<String, Arc<FnDecl>>,
149    /// Per-type method tables (instance + static).
150    pub methods: HashMap<String, MethodTable>,
151    /// Names of types declared in *this* commons (as opposed to imported via
152    /// `uses`). Used by the checker to gate access to `.raw` and `.unsafe()`
153    /// on opaque types. Private: this field's contract is specifically
154    /// "declared here, not merely visible here", and a builder outside this
155    /// crate that populates it from the wrong (merged, rather than
156    /// pre-merge) table silently over-widens those gates — read it via
157    /// [`ResolvedCommons::is_local_type`], and build a `ResolvedCommons` via
158    /// [`ResolvedCommons::new`], which derives it correctly by construction.
159    pub(crate) local_type_names: std::collections::HashSet<String>,
160    /// Cross-context call information for v0.6. None for commons and for
161    /// single-file mode. For contexts, supplies the set of consumed contexts
162    /// and any aliases introduced via `consumes ... as Alias`.
163    pub cross_context: CrossContextInfo,
164    /// Agents declared in this context. Used to recognise the `Agent(key)`
165    /// construction shape and the `agent_instance.handler(args)` method-call
166    /// shape in handler bodies that mention other agents.
167    pub agents: HashMap<String, Arc<AgentDecl>>,
168    /// v0.91 (ADR 0116 D6): for each imported function name, the qualified unit
169    /// it came from (`map` → `bynk.list`). Lets the checker flag deprecated
170    /// first-party free functions at their call sites. Empty in single-file
171    /// mode and in synthetic handler-validation resolveds.
172    pub imported_from: HashMap<String, String>,
173    /// True iff this unit is a `context` (as opposed to a commons, adapter, or
174    /// test/integration scaffold). `bynk-check` has no dependency on
175    /// `bynk-emit`'s `UnitKind`, so callers set this directly from their own
176    /// unit-kind knowledge. Used to gate the context-rebrand construction
177    /// check (#907): only a context's emission rebrands a `uses`-sourced
178    /// commons sum type's variant constructors out of value scope.
179    pub is_context: bool,
180    /// Names of types brought into scope via `uses` of a *commons*
181    /// specifically (as opposed to a local declaration, or a type surfaced
182    /// via `consumes`) — every name [`compute_is_uses_commons_type`] accepts
183    /// against this unit's own `imported_from_kind`/`combined_types`, the
184    /// single shared definition both `bynk-emit`'s `emit_context_rebrands`
185    /// (rebrand + its own import-aliasing step) and this crate's own
186    /// `prepare_unit_check_ctx` (which populates this set) read (R4.10/R8.2,
187    /// closing what used to be two independently hand-maintained copies
188    /// linked only by a doc comment promising they matched). A type surfaced
189    /// via `consumes` (a capability signature from an adapter or another
190    /// context) is *not* rebranded and must not be gated by #907's check —
191    /// only this narrower set may be. Private for the same reason as
192    /// `local_type_names`; read via [`ResolvedCommons::is_uses_commons_type`].
193    pub(crate) uses_commons_type_names: std::collections::HashSet<String>,
194    /// #2881: the functions this unit sees through `uses` rather than declares
195    /// (in any of its files). `uses` brings in a commons only, so a `given` on
196    /// one of these is always refused. Empty unless [`ResolvedCommons::with_local_fns`]
197    /// was called.
198    pub(crate) imported_fn_names: std::collections::HashSet<String>,
199    /// Events track, slice 0 (spine #936): names of `event` declarations in
200    /// *this* commons specifically — as opposed to `local_type_names`, which
201    /// answers "declared here" for any type, event-derived or not. Backs the
202    /// `Events.emit[E]` check that `E` names a real event, not merely any
203    /// local type (owner-only emission alone can't tell the two apart, since
204    /// an event's synthetic `TypeDecl` sits in the same `types` table as
205    /// every ordinary type). Private for the same reason as
206    /// `local_type_names`; read via [`ResolvedCommons::is_local_event`].
207    pub(crate) event_type_names: std::collections::HashSet<String>,
208    /// #1883, slice 1a: every `asset` visible in this unit — its own and its
209    /// `uses`d commons' ([`crate::assets::compose_unit_assets`]). An asset
210    /// name is a value of type `Asset`. Empty unless set with
211    /// [`ResolvedCommons::with_assets`].
212    pub assets: HashMap<String, AssetDecl>,
213    /// #2387, slice 1: every `embed` visible in this unit — its own and its
214    /// `uses`d commons' ([`crate::embeds::compose_unit_embeds`]). An embed
215    /// name is a `String` value. Empty unless set with
216    /// [`ResolvedCommons::with_embeds`].
217    pub embeds: HashMap<String, EmbedDecl>,
218    /// #2617: every `const` visible in this unit — its own and its `uses`d
219    /// commons' ([`crate::consts::compose_unit_consts`]). A constant's name
220    /// is a value of its annotated type. Empty unless set with
221    /// [`ResolvedCommons::with_consts`].
222    pub consts: HashMap<String, ConstDecl>,
223    /// #1925: the `uses`-imported values this unit's own declarations of
224    /// another kind shadow, by name. Empty unless set with
225    /// [`ResolvedCommons::with_shadowed_imports`]; read through
226    /// [`ResolvedCommons::shadowed_import_error`].
227    pub shadowed_imports: HashMap<String, ShadowedImport>,
228    /// Standard-library S3 (#1963): the names in scope that are a first-party
229    /// unit's extensible enums (`FetchError`, `Method`), whose `match` needs a
230    /// wildcard. Types carry no owning unit, so this is decided once per unit
231    /// from its provenance (`check_pipeline`) and carried to every check built
232    /// from it. Empty unless set with [`ResolvedCommons::with_extensible_enums`].
233    pub extensible_enums: HashSet<String>,
234    /// #3536: the names of types in scope that a braced `consumes` of a
235    /// first-party unit leaves out (`consumes bynk { Logger }` leaves out
236    /// `Claim`). Still resolvable, so `bynk.consumes.type_not_selected` reports
237    /// it with a fix, but never a name-clash or bare-variant ambiguity candidate: a
238    /// declaration of the unit's own wins. Empty unless set with
239    /// [`ResolvedCommons::with_unselected_types`].
240    pub unselected_types: HashSet<String>,
241    /// Standard-library S3 (#1963): the unit's stability facts — the project's
242    /// `[unstable]` policy and the imports it blocks. Set with
243    /// [`ResolvedCommons::with_stability`]; the default blocks nothing.
244    pub stability: crate::stability::UnitStability,
245}
246
247/// Static information about the consuming context: the set of contexts it
248/// `consumes`, and any aliases introduced via `as Alias` clauses. Used by
249/// the resolver to recognise cross-context service calls and by the checker
250/// to type them (v0.6 §4.2).
251#[derive(Debug, Default, Clone)]
252pub struct CrossContextInfo {
253    /// The qualified name of the consuming context, if this unit is a context.
254    pub self_context: Option<String>,
255    /// Qualified names of every consumed context.
256    pub consumed_contexts: Vec<String>,
257    /// alias → consumed-context qualified name.
258    pub aliases: HashMap<String, String>,
259    /// For each consumed context, its service surface plus the structural
260    /// shapes of each service handler's params and return type (as seen
261    /// from the consumed context's own namespace). Populated by the project
262    /// driver; empty in single-file mode.
263    pub consumed_services: HashMap<String, HashMap<String, CrossContextService>>,
264    /// For each consumed context, its full type table (the consumed
265    /// context's local types, plus the types it brings in via `uses`).
266    /// Used by the checker for structural shape comparisons across the
267    /// boundary (v0.6 §4.3).
268    pub consumed_types: HashMap<String, HashMap<String, Arc<TypeDecl>>>,
269    /// #1932: for each consumed context, the renames (`Box` → `shop__Box`)
270    /// under which the consumer generates codecs for the consumed context's
271    /// types it neither imports nor names (#1846). Set by the emitter, which
272    /// computes them once (`emitter::unexported_type_renames`) so a call site
273    /// names the same codecs the consumer generates. Empty in the checker.
274    pub consumed_type_renames: HashMap<String, HashMap<String, String>>,
275    /// v0.15: for each consumed context, the capabilities it `exports
276    /// capability { … }` — keyed by capability name. Used to resolve and
277    /// type-check `given B.Cap` references and `B.Cap.op(…)` calls, and by
278    /// the emitter to instantiate the provider locally.
279    pub consumed_capabilities: HashMap<String, HashMap<String, CrossContextCapability>>,
280    /// v0.17: `consumes U { Cap, … }` flattens selected capabilities into the
281    /// consumer's local namespace under their bare names (§3.3). Maps each bare
282    /// capability name to the consumed unit (context or adapter) providing it,
283    /// so bare `given Cap` / `Cap.op(…)` resolve, the deps type imports from the
284    /// right module, and compose instantiates the provider.
285    pub flattened_caps: HashMap<String, String>,
286    /// Events track, slice 0 (spine #936): for each consumed context, the
287    /// names of its own `event` declarations. Lets a subscriber's `from
288    /// Events(E)` header be checked against a foreign owner too — `E` is
289    /// legitimate if it's a local event *or* a declared event of some
290    /// consumed context, mirroring how `discover_event_subscribers`
291    /// (`bynk-emit/src/project.rs`) already resolves ownership for wiring.
292    pub consumed_event_names: HashMap<String, HashSet<String>>,
293    /// #2073: for each consumed context, the types in its `consumed_types`
294    /// table that it does not declare but consumes from another context,
295    /// mapped to that declaring context (`Order` → `shop.order` for a consumed
296    /// `shop.ledger`). A boundary cast or codec names such a type through its
297    /// declaring context, not the consumed one.
298    pub consumed_type_owners: HashMap<String, HashMap<String, String>>,
299    /// #2887: for each consumed context, the types this context renames with
300    /// `consumes U { T as Alias }`, alias → the name `U` declares. The checker
301    /// works in the alias; anything the callee also reads (the contract hash,
302    /// the TS names its module exports) is spelled in the declared name.
303    pub consumed_type_aliases: HashMap<String, HashMap<String, String>>,
304    /// #2890: for each consumed context, the types it renames from a context of
305    /// its own (alias → declared name). Its services' signatures name them by
306    /// the alias, and a caller that does not alias them reaches the type
307    /// through the module that declares it, under the declared name.
308    pub callee_type_aliases: HashMap<String, HashMap<String, String>>,
309    /// #2901: for each consumed context, the key a caller names each type it
310    /// renamed by (the declared name, or the qualified key on a clash with a
311    /// type of its own) mapped back to the alias its signatures and contract
312    /// hash spell.
313    pub callee_alias_keys: HashMap<String, HashMap<String, String>>,
314    /// #3446: the records some handler of the unit decodes as its `cookies` parameter (any file
315    /// of the unit): the ones `Record.field.cookie(v)` may write.
316    pub cookie_records: HashSet<String>,
317    /// #3446: the cookie names the unit's `SignedCookie` actors consume (their `cookie` key, else
318    /// the default): the cookies only `Actor.issue`/`expire` may write.
319    pub signed_cookie_names: HashSet<String>,
320}
321
322/// Snapshot of one exported capability in a consumed context, as needed for
323/// v0.15 cross-context capability resolution. Operation signatures are
324/// expressed in the consumed context's own namespace (resolved against
325/// `consumed_types` at the call site, mirroring [`CrossContextService`]).
326#[derive(Debug, Clone)]
327pub struct CrossContextCapability {
328    pub name: String,
329    /// Each operation's parameter type-refs and return type-ref.
330    pub ops: Vec<CrossContextCapabilityOp>,
331    /// The provider that implements this capability in the providing context
332    /// (its generated class name), so the consumer can instantiate it.
333    pub provider_name: String,
334    /// The provider's own `given` capabilities (intra-providing-context),
335    /// needed to wire the provider's constructor when instantiated locally.
336    pub provider_given: Vec<String>,
337    pub span: bynk_syntax::span::Span,
338}
339
340#[derive(Debug, Clone)]
341pub struct CrossContextCapabilityOp {
342    pub name: String,
343    /// #926: the op's own type parameters (empty for a non-generic op),
344    /// spelled the same as the consumed context's own declaration. A cross-
345    /// context call resolves these from an explicit call-site type argument,
346    /// same as the local-capability path.
347    pub type_params: Vec<String>,
348    pub params: Vec<(String, TypeRef)>,
349    pub return_type: TypeRef,
350    /// Slice 3: the op's type parameters declared `Codable`.
351    pub codable_params: Vec<String>,
352    /// #3458: what an undecodable reply means for a typed read, as declared.
353    pub reply_policy: crate::checker::codable::ReplyPolicy,
354}
355
356/// Snapshot of one service in a consumed context, as needed for v0.6
357/// cross-context type checking. The params and return type are expressed
358/// in the consumed context's own namespace.
359#[derive(Debug, Clone)]
360pub struct CrossContextService {
361    pub name: String,
362    /// Surface (parsed) type-refs of the `on call` handler's parameters.
363    pub params: Vec<(String, TypeRef)>,
364    pub return_type: TypeRef,
365    pub span: bynk_syntax::span::Span,
366    /// I3 (#1971): the foreign callers the handler admits, by actor name. A
367    /// system test that calls as one of them signs as that actor. Not part
368    /// of the contract.
369    pub foreign_callers: Vec<String>,
370}
371
372/// Project one local `on call` handler into the [`CrossContextService`] shape
373/// both sides of a cross-context contract check need — a caller resolving a
374/// *consumed* service ([`crate::symbols::build_cross_context_info`]) and a
375/// callee stamping its *own* `X-Bynk-Contract` constant
376/// ([`crate::contract::own_contract_hashes`]). Sharing this one projection is
377/// the whole correctness argument for that symmetry: if the two sides ever
378/// diverged, a working deployment would 409 on every call instead of only on
379/// real skew. `None` when `sdecl` has no `on call` handler (e.g. an
380/// events-only or queue-only service).
381pub fn cross_context_service_for(name: &str, sdecl: &ServiceDecl) -> Option<CrossContextService> {
382    let handler = sdecl
383        .handlers
384        .iter()
385        .find(|h| matches!(h.kind, HandlerKind::Call))?;
386    Some(CrossContextService {
387        name: name.to_string(),
388        params: handler
389            .params
390            .iter()
391            .map(|p| (p.name.name.clone(), p.type_ref.clone()))
392            .collect(),
393        return_type: handler.return_type.clone(),
394        span: sdecl.span,
395        foreign_callers: Vec::new(),
396    })
397}
398
399impl CrossContextInfo {
400    /// Returns the qualified name of the consumed context this prefix refers
401    /// to, treating `prefix` as either an alias or a full qualified name.
402    pub fn resolve_prefix(&self, prefix: &str) -> Option<String> {
403        if let Some(q) = self.aliases.get(prefix) {
404            return Some(q.clone());
405        }
406        if self.consumed_contexts.iter().any(|c| c == prefix) {
407            return Some(prefix.to_string());
408        }
409        None
410    }
411
412    /// v0.15: resolve a dotted receiver chain like `platform.time.Clock` or
413    /// `Time.Clock` to `(consumed_context, capability)` when the leading
414    /// segments name a consumed context (or alias) that exports the trailing
415    /// capability. Returns `None` if the chain is not a cross-context
416    /// capability reference.
417    pub fn resolve_cross_capability(&self, chain: &str) -> Option<(String, String)> {
418        let (prefix, cap) = chain.rsplit_once('.')?;
419        let ctx = self.resolve_prefix(prefix)?;
420        let caps = self.consumed_capabilities.get(&ctx)?;
421        if caps.contains_key(cap) {
422            Some((ctx, cap.to_string()))
423        } else {
424            None
425        }
426    }
427}
428
429impl ResolvedCommons {
430    /// Returns true if `name` is a type declared in the current commons
431    /// (rather than imported via `uses`). Local types alone may reach into
432    /// their opaque representation (`.raw`) or call `.unsafe(value)`.
433    pub fn is_local_type(&self, name: &str) -> bool {
434        self.local_type_names.contains(name)
435    }
436
437    /// Events track, slice 0: is `name` a declared `event` in this commons —
438    /// not merely any local type?
439    pub fn is_local_event(&self, name: &str) -> bool {
440        self.event_type_names.contains(name)
441    }
442
443    /// Is `name` in scope via `uses` of a *commons* specifically? See
444    /// `uses_commons_type_names`'s field doc for the exact predicate.
445    pub fn is_uses_commons_type(&self, name: &str) -> bool {
446        self.uses_commons_type_names.contains(name)
447    }
448
449    /// Build a `ResolvedCommons` from a merged (local + `uses`/`consumes`)
450    /// symbol table, deriving `local_type_names`/`event_type_names` from
451    /// `local_types`/`local_events` — the *pre-merge* tables — rather than
452    /// from `types`/`agents` (already merged). This is the one thing every
453    /// hand-rolled construction outside this crate got a chance to disagree
454    /// on: the pre-merge/merged distinction is exactly what backs
455    /// `.raw`/`.unsafe()`/owner-only-event-emission gating, and reusing the
456    /// merged table there silently widens all three to any consumed/used
457    /// type or event (found during the events track, slice 0, spine #936).
458    #[allow(clippy::too_many_arguments)]
459    pub fn new(
460        commons: Arc<Commons>,
461        types: HashMap<String, Arc<TypeDecl>>,
462        local_types: &HashMap<String, Arc<TypeDecl>>,
463        fns: HashMap<String, Arc<FnDecl>>,
464        methods: HashMap<String, MethodTable>,
465        agents: HashMap<String, Arc<AgentDecl>>,
466        local_events: &HashMap<String, EventDecl>,
467        cross_context: CrossContextInfo,
468        imported_from: HashMap<String, String>,
469        is_context: bool,
470        uses_commons_type_names: HashSet<String>,
471    ) -> Self {
472        Self {
473            commons,
474            local_type_names: local_types.keys().cloned().collect(),
475            event_type_names: local_events.keys().cloned().collect(),
476            types,
477            fns,
478            methods,
479            cross_context,
480            agents,
481            imported_from,
482            is_context,
483            uses_commons_type_names,
484            imported_fn_names: HashSet::new(),
485            assets: HashMap::new(),
486            embeds: HashMap::new(),
487            consts: HashMap::new(),
488            shadowed_imports: HashMap::new(),
489            extensible_enums: HashSet::new(),
490            unselected_types: HashSet::new(),
491            stability: Default::default(),
492        }
493    }
494
495    /// #2881: record which of this unit's functions came in through `uses`
496    /// (those in `fns` that `local_fns`, the unit's own table across all its
497    /// files, lacks). A builder, so constructions with no `uses` need not call it.
498    pub fn with_local_fns<V>(mut self, local_fns: &HashMap<String, V>) -> Self {
499        self.imported_fn_names = self
500            .fns
501            .keys()
502            .filter(|n| !local_fns.contains_key(*n))
503            .cloned()
504            .collect();
505        self
506    }
507
508    /// #1883, slice 1a: the assets visible in this unit. A builder rather
509    /// than a [`ResolvedCommons::new`] parameter, so the constructions that
510    /// can never see an asset (a synthetic test scaffold) need not mention
511    /// them.
512    pub fn with_assets(mut self, assets: HashMap<String, AssetDecl>) -> Self {
513        self.assets = assets;
514        self
515    }
516
517    /// #2387, slice 1: the embeds visible in this unit, a builder like
518    /// [`ResolvedCommons::with_assets`].
519    pub fn with_embeds(mut self, embeds: HashMap<String, EmbedDecl>) -> Self {
520        self.embeds = embeds;
521        self
522    }
523
524    /// #2617: the constants visible in this unit, a builder like
525    /// [`ResolvedCommons::with_embeds`].
526    pub fn with_consts(mut self, consts: HashMap<String, ConstDecl>) -> Self {
527        self.consts = consts;
528        self
529    }
530
531    /// #1925: the `uses`-imported values this unit's own declarations of
532    /// another kind shadow ([`crate::project_model::shadowed_imports`]).
533    pub fn with_shadowed_imports(mut self, shadowed: HashMap<String, ShadowedImport>) -> Self {
534        self.shadowed_imports = shadowed;
535        self
536    }
537
538    /// #3536: set [`ResolvedCommons::unselected_types`].
539    pub fn with_unselected_types(mut self, names: HashSet<String>) -> Self {
540        self.unselected_types = names;
541        self
542    }
543
544    /// Carry the per-unit scope facts of a checked unit
545    /// ([`ResolvedCommons::extensible_enums`], [`ResolvedCommons::unselected_types`])
546    /// onto the rebuilt per-handler view.
547    pub fn with_scope_facts_of(self, typed: &crate::checker::TypedCommons) -> Self {
548        self.with_extensible_enums(typed.extensible_enums.clone())
549            .with_unselected_types(typed.unselected_types.clone())
550    }
551
552    /// S3 (#1963): set [`ResolvedCommons::extensible_enums`].
553    pub fn with_extensible_enums(mut self, names: HashSet<String>) -> Self {
554        self.extensible_enums = names;
555        self
556    }
557
558    /// S3 (#1963): set [`ResolvedCommons::stability`].
559    pub fn with_stability(mut self, stability: crate::stability::UnitStability) -> Self {
560        self.stability = stability;
561        self
562    }
563
564    /// #1925: the conflict to report for a reference to `name` that the
565    /// unit's own declaration could not answer, when `name` is a shadowed
566    /// import — or `None`, and the caller reports its usual diagnostic.
567    pub fn shadowed_import_error(&self, name: &str, span: Span) -> Option<CompileError> {
568        self.shadowed_imports
569            .get(name)
570            .map(|s| shadowed_import_error(name, span, s))
571    }
572}
573
574/// #1925: a `uses`-imported function or asset that the unit hides behind its
575/// own declaration of the same name and another kind. A local declaration
576/// wins, as it does in the emitted module, so the import is out of scope; a
577/// reference the local declaration cannot answer (a call to a type, a bare
578/// service name) is reported as this conflict, not as an unknown name.
579#[derive(Debug, Clone)]
580pub struct ShadowedImport {
581    /// The commons that declares the import.
582    pub unit: String,
583    /// The import's kind: `"function"`, `"asset"`, or `"type"` (#1927).
584    pub imported: &'static str,
585    /// The local declaration's kind, as `symbols::local_value_kind` names it.
586    pub local: &'static str,
587    /// The local declaration's name.
588    pub local_span: Span,
589}
590
591/// `bynk.uses.name_conflict` for a reference to `name`, a shadowed import.
592pub(crate) fn shadowed_import_error(name: &str, span: Span, s: &ShadowedImport) -> CompileError {
593    CompileError::new(
594        "bynk.uses.name_conflict",
595        span,
596        format!(
597            "`{name}` names this unit's {}, which hides the {} `{name}` from `{}`",
598            s.local, s.imported, s.unit
599        ),
600    )
601    .with_label(s.local_span, format!("{} declared here", s.local))
602    .with_note(format!(
603        "a unit's own declaration shadows a `uses`-imported one of the same name; rename one to use the {}",
604        s.imported
605    ))
606}
607
608/// Resolve names in a single-file (or already-merged) commons. Use this
609/// entry point only for self-contained Bynk programs. For multi-file
610/// projects and `uses`-resolving commons, use [`resolve_file`] against a
611/// pre-built combined symbol table.
612pub fn resolve(commons: Commons) -> Result<ResolvedCommons, Vec<CompileError>> {
613    let (resolved, errors) = resolve_recovering(commons);
614    if errors.is_empty() {
615        Ok(resolved)
616    } else {
617        Err(errors)
618    }
619}
620
621/// Single-file mode has no `uses`, so the visible assets (#1883), embeds
622/// (#2387) and constants (#2617) are exactly the ones declared here, the first
623/// declaration of a name winning as in the unit table; a second is reported by
624/// `assets::single_file_asset_errors`, `embeds::single_file_embed_errors` and
625/// `consts::single_file_const_errors`.
626fn single_file_values(
627    commons: &Commons,
628) -> (
629    HashMap<String, AssetDecl>,
630    HashMap<String, EmbedDecl>,
631    HashMap<String, ConstDecl>,
632) {
633    let (mut assets, mut embeds, mut consts) = (HashMap::new(), HashMap::new(), HashMap::new());
634    for item in &commons.items {
635        match item {
636            CommonsItem::Asset(a) => {
637                assets
638                    .entry(a.name.name.clone())
639                    .or_insert_with(|| a.clone());
640            }
641            CommonsItem::Embed(e) => {
642                embeds
643                    .entry(e.name.name.clone())
644                    .or_insert_with(|| e.clone());
645            }
646            CommonsItem::Const(c) => {
647                consts
648                    .entry(c.name.name.clone())
649                    .or_insert_with(|| c.clone());
650            }
651            _ => {}
652        }
653    }
654    (assets, embeds, consts)
655}
656
657/// [`resolve`], returning the symbol table *with* every resolve error rather
658/// than instead of it (#1663, Decision A). A resolve error is local to the
659/// declaration it is in, so the checker can still check every declaration —
660/// an unknown name in `b` no longer hides a type error in `a`. The table is
661/// complete apart from what the errors name (a duplicate keeps its first
662/// declaration). A caller that emits must still refuse on any error.
663pub fn resolve_recovering(commons: Commons) -> (ResolvedCommons, Vec<CompileError>) {
664    let mut errors = Vec::new();
665    let mut types: HashMap<String, Arc<TypeDecl>> = HashMap::new();
666    let mut fns: HashMap<String, Arc<FnDecl>> = HashMap::new();
667    let mut methods: HashMap<String, MethodTable> = HashMap::new();
668
669    // First pass: collect declarations and detect duplicates / name overlap.
670    for item in &commons.items {
671        match item {
672            // v0.5 declaration kinds — these don't introduce types/fns into
673            // the symbol space. They go through the context-level v0.5 path
674            // in project.rs. Skip them at the per-commons level.
675            CommonsItem::Capability(_)
676            | CommonsItem::Provider(_)
677            | CommonsItem::Service(_)
678            | CommonsItem::Agent(_)
679            | CommonsItem::Actor(_)
680            // `messages` entries are plain string literals with no type refs
681            // to resolve here; commons-only legality and the reference/
682            // duplicate-code checks live in bynk-emit's project validation.
683            | CommonsItem::Messages(_)
684            // #1883, slice 1a: an asset's placement, path and name checks
685            // live in `symbols::build_unit_table`; it has no type refs.
686            | CommonsItem::Asset(_)
687            // #2387, slice 1: likewise an embed (`embeds::path_errors`).
688            | CommonsItem::Embed(_)
689            // #2617: a constant's name rules live in `build_unit_table` and
690            // `consts::single_file_const_errors`; its type and initialiser
691            // resolve in the second pass.
692            | CommonsItem::Const(_) => {}
693            CommonsItem::Type(t) => {
694                if let Some(prev) = types.get(&t.name.name) {
695                    errors.push(
696                        CompileError::new(
697                            "bynk.resolve.duplicate_type",
698                            t.name.span,
699                            format!("type `{}` is already declared", t.name.name),
700                        )
701                        .with_label(prev.name.span, "previously declared here"),
702                    );
703                } else if let Some(prev) = fns.get(&t.name.name) {
704                    errors.push(
705                        CompileError::new(
706                            "bynk.resolve.name_conflict",
707                            t.name.span,
708                            format!(
709                                "type `{}` conflicts with a function of the same name",
710                                t.name.name
711                            ),
712                        )
713                        .with_label(prev.name.ident().span, "function declared here"),
714                    );
715                } else {
716                    types.insert(t.name.name.clone(), Arc::new(t.clone()));
717                    methods.insert(t.name.name.clone(), MethodTable::default());
718                }
719            }
720            // Events track, slice 0 (spine #936): an `event` registers into
721            // the same `types` table as an ordinary `type` — via the
722            // synthetic `TypeDecl` `EventDecl::as_type_decl` builds — so it
723            // reuses every existing type-reference/construction check.
724            // Context-only legality (`bynk.event.outside_context`) and
725            // event-vs-plain-type distinctions live in bynk-emit's project
726            // validation, the same split `messages` already uses.
727            CommonsItem::Event(e) => {
728                let t = e.as_type_decl();
729                if let Some(prev) = types.get(&t.name.name) {
730                    errors.push(
731                        CompileError::new(
732                            "bynk.resolve.duplicate_type",
733                            t.name.span,
734                            format!("type `{}` is already declared", t.name.name),
735                        )
736                        .with_label(prev.name.span, "previously declared here"),
737                    );
738                } else if let Some(prev) = fns.get(&t.name.name) {
739                    errors.push(
740                        CompileError::new(
741                            "bynk.resolve.name_conflict",
742                            t.name.span,
743                            format!(
744                                "type `{}` conflicts with a function of the same name",
745                                t.name.name
746                            ),
747                        )
748                        .with_label(prev.name.ident().span, "function declared here"),
749                    );
750                } else {
751                    methods.insert(t.name.name.clone(), MethodTable::default());
752                    types.insert(t.name.name.clone(), Arc::new(t));
753                }
754            }
755            CommonsItem::Fn(f) => match &f.name {
756                FnName::Free(id) => {
757                    if let Some(prev) = fns.get(&id.name) {
758                        errors.push(
759                            CompileError::new(
760                                "bynk.resolve.duplicate_fn",
761                                id.span,
762                                format!("function `{}` is already declared", id.name),
763                            )
764                            .with_label(prev.name.ident().span, "previously declared here"),
765                        );
766                    } else if let Some(prev) = types.get(&id.name) {
767                        errors.push(
768                            CompileError::new(
769                                "bynk.resolve.name_conflict",
770                                id.span,
771                                format!(
772                                    "function `{}` conflicts with a type of the same name",
773                                    id.name
774                                ),
775                            )
776                            .with_label(prev.name.span, "type declared here"),
777                        );
778                    } else {
779                        fns.insert(id.name.clone(), Arc::new(f.clone()));
780                    }
781                }
782                FnName::Method {
783                    type_name,
784                    method_name,
785                } => {
786                    // The type the method is attached to must be declared.
787                    if !types.contains_key(&type_name.name) {
788                        errors.push(
789                            CompileError::new(
790                                "bynk.resolve.method_unknown_type",
791                                type_name.span,
792                                format!(
793                                    "method `{}.{}` attached to an unknown type `{}`",
794                                    type_name.name, method_name.name, type_name.name
795                                ),
796                            )
797                            .with_note(
798                                "methods can only be declared on types defined in the same commons",
799                            ),
800                        );
801                        continue;
802                    }
803                    // #594: an *instance* method on a generic type is a generic
804                    // method — the receiver's type arguments supply the type's
805                    // parameters (`self: Box[A]`), so it resolves and emits as an
806                    // erased TS generic method. Constrained generics slice 4
807                    // (DECISION A): a *static* method is generic over the type's
808                    // parameters too, inferred from its arguments, the expected
809                    // type, or explicit type arguments. DECISION H: one whose
810                    // signature never mentions a type parameter leaves it
811                    // undeterminable at every call, so it is rejected here.
812                    if !f.has_self
813                        && let Some(d) = types.get(&type_name.name)
814                    {
815                        let sig: Vec<&TypeRef> = f
816                            .params
817                            .iter()
818                            .map(|p| &p.type_ref)
819                            .chain(std::iter::once(&f.return_type))
820                            .collect();
821                        let missing = d.type_params.iter().find(|tp| {
822                            !sig.iter().any(|t| {
823                                crate::checker::codable::mentions_any(
824                                    t,
825                                    std::slice::from_ref(&tp.name.name),
826                                )
827                            })
828                        });
829                        if let Some(tp) = missing {
830                            errors.push(
831                                CompileError::new(
832                                    "bynk.generics.method_on_generic_type",
833                                    type_name.span,
834                                    format!(
835                                        "static method `{}.{}` never mentions `{}`, a type parameter of `{}` — no call could determine it",
836                                        type_name.name, method_name.name, tp.name.name, type_name.name
837                                    ),
838                                )
839                                .with_label(tp.span, "type parameter declared here")
840                                .with_note(format!(
841                                    "make it a free function, or mention `{}` in the signature",
842                                    tp.name.name
843                                )),
844                            );
845                            continue;
846                        }
847                    }
848                    let table = methods.entry(type_name.name.clone()).or_default();
849                    let bucket = if f.has_self {
850                        &mut table.instance
851                    } else {
852                        &mut table.statics
853                    };
854                    if let Some(prev) = bucket.get(&method_name.name) {
855                        errors.push(
856                            CompileError::new(
857                                "bynk.resolve.duplicate_method",
858                                method_name.span,
859                                format!(
860                                    "method `{}.{}` is already declared",
861                                    type_name.name, method_name.name
862                                ),
863                            )
864                            .with_label(prev.name.ident().span, "previously declared here"),
865                        );
866                    } else {
867                        bucket.insert(method_name.name.clone(), Arc::new(f.clone()));
868                    }
869                }
870            },
871        }
872    }
873
874    let (local_assets, local_embeds, local_consts) = single_file_values(&commons);
875
876    // Second pass: validate references inside type-refs and function bodies.
877    let mut refs = RefSink::new(); // single-file mode: no recording context.
878    let mut sinks = Sinks {
879        errs: &mut errors,
880        refs: &mut refs,
881    };
882    for item in &commons.items {
883        check_reserved_host_name(item, &mut sinks);
884        match item {
885            CommonsItem::Type(t) => {
886                check_type_decl_refs(t, &types, &mut sinks);
887            }
888            CommonsItem::Event(e) => {
889                check_type_decl_refs(&e.as_type_decl(), &types, &mut sinks);
890            }
891            CommonsItem::Fn(f) => {
892                check_fn_refs(
893                    f,
894                    &types,
895                    &fns,
896                    &methods,
897                    &local_assets,
898                    &local_embeds,
899                    &local_consts,
900                    // A single file has no `uses` imports to shadow.
901                    &HashMap::new(),
902                    &HashSet::new(),
903                    &mut sinks,
904                );
905            }
906            CommonsItem::Const(c) => {
907                check_const_refs(c, &types, &fns, &methods, &local_consts, &mut sinks);
908            }
909            // v0.5 items' bodies are resolved via a separate context-level
910            // pass; their signatures here (#1679).
911            CommonsItem::Capability(_)
912            | CommonsItem::Service(_)
913            | CommonsItem::Agent(_)
914            | CommonsItem::Provider(_)
915            | CommonsItem::Actor(_) => {
916                check_signature_refs(item, &types, &mut sinks);
917            }
918            // `messages` entries are plain string literals with no type refs
919            // to resolve here; commons-only legality and the reference/
920            // duplicate-code checks live in bynk-emit's project validation.
921            // #1883, slice 1a: likewise an asset (a string-literal path).
922            CommonsItem::Messages(_) | CommonsItem::Asset(_) | CommonsItem::Embed(_) => {}
923        }
924    }
925
926    {
927        let local_type_names = types.keys().cloned().collect();
928        let event_type_names = commons
929            .items
930            .iter()
931            .filter_map(|item| match item {
932                CommonsItem::Event(e) => Some(e.name.name.clone()),
933                _ => None,
934            })
935            .collect();
936        let resolved = ResolvedCommons {
937            commons: Arc::new(commons),
938            types,
939            fns,
940            methods,
941            local_type_names,
942            cross_context: CrossContextInfo::default(),
943            agents: HashMap::new(),
944            // Single-file mode has no `uses`-imported functions.
945            imported_from: HashMap::new(),
946            // Single-file mode has no `uses` at all — the rebrand this flag
947            // gates is unreachable here.
948            is_context: false,
949            uses_commons_type_names: HashSet::new(),
950            imported_fn_names: HashSet::new(),
951            event_type_names,
952            assets: local_assets,
953            embeds: local_embeds,
954            consts: local_consts,
955            shadowed_imports: HashMap::new(),
956            extensible_enums: HashSet::new(),
957            unselected_types: HashSet::new(),
958            stability: Default::default(),
959        };
960        (resolved, errors)
961    }
962}
963
964/// #3162: the note on `bynk.resolve.unknown_function`. A capitalised name in
965/// call position is an agent construction (`Counter("x")`), which is not a
966/// function and may sit in a suite rather than a commons, so it is not told
967/// that only functions of "this commons" are callable.
968pub(crate) fn unknown_function_note(name: &str) -> String {
969    if name.starts_with(|c: char| c.is_uppercase()) {
970        format!(
971            "`{name}(...)` constructs an agent, but no agent named `{name}` is declared in \
972             this unit or one it uses"
973        )
974    } else {
975        "only functions declared in this commons are callable".to_string()
976    }
977}
978
979/// #1663 (Decision B): split resolve errors into those to report and those
980/// that only echo a declaration the parser had to skip.
981///
982/// A declaration that fails to parse is dropped from the AST, so every
983/// reference to its name — `Money` in a signature, `Money.zero` as a method's
984/// owner, a call to a skipped `fn` — resolves as unknown, and one missing comma
985/// becomes twenty diagnostics. Its name is known (the parser recorded it in
986/// `broken_decl_names`); only its declaration is broken, and that is already
987/// reported. So an unknown-name diagnostic naming one is hidden.
988///
989/// The hidden errors still count as resolve errors: pass *both* halves to
990/// [`without_resolve_echoes`], so the declarations they are in reject the
991/// checker's follow-on diagnostics too.
992pub fn split_broken_decl_echoes(
993    resolve_errors: Vec<CompileError>,
994    broken_decl_names: &[String],
995) -> (Vec<CompileError>, Vec<CompileError>) {
996    const ECHO_CODES: &[&str] = &[
997        "bynk.resolve.unknown_type",
998        "bynk.resolve.method_unknown_type",
999        "bynk.resolve.unknown_name",
1000        "bynk.resolve.unknown_function",
1001        "bynk.resolve.unknown_static_member",
1002        // #1710: echoes the checker reports (so the project path splits the
1003        // checker's diagnostics too), each naming a declaration recovery may
1004        // skip: a consumed context's service, a method, a capability (as a
1005        // provider's target, in `given`, or unused for want of one), an actor.
1006        "bynk.consumes.unknown_service",
1007        "bynk.types.method_not_found",
1008        "bynk.provider.unknown_capability",
1009        "bynk.given.unknown_capability",
1010        "bynk.given.unused_capability",
1011        "bynk.actor.unknown_actor",
1012    ];
1013    // The *subject* each of these diagnostics is about, spelled as the parser
1014    // records a broken declaration (`T`, `f`, or a method as `T.m`):
1015    // - `unknown type `T``, `unknown name `x``, `unknown function `f``: the
1016    //   one backticked name;
1017    // - `method `T.m` attached to an unknown type `T``: the type, its last;
1018    // - `type `T` has no static method or variant named `m``: the member,
1019    //   qualified by its type (`T.m`), its first and last;
1020    // - `context `c` has no service named `s``: the service, its last;
1021    // - `type `T` has no instance method named `m``: the method, as `T.m`;
1022    // - `capability `C` is declared in `given` but never used`: its first;
1023    // - any other capability or actor diagnostic: its one backticked name.
1024    // Matching only the subject keeps a broken `fn m` from hiding an unrelated
1025    // `Other.m` that merely shares the name.
1026    let names = |message: &str| -> Vec<String> {
1027        message
1028            .split('`')
1029            .skip(1)
1030            .step_by(2)
1031            .map(str::to_string)
1032            .collect()
1033    };
1034    let subject = |e: &CompileError| -> Option<String> {
1035        let ns = names(&e.message);
1036        match e.category {
1037            "bynk.resolve.unknown_static_member" | "bynk.types.method_not_found" => {
1038                Some(format!("{}.{}", ns.first()?, ns.last()?))
1039            }
1040            // `capability `C` is declared in `given` but never used`: the
1041            // capability comes first (`given` is the keyword, quoted).
1042            "bynk.given.unused_capability" => ns.first().cloned(),
1043            _ => ns.last().cloned(),
1044        }
1045    };
1046    resolve_errors.into_iter().partition(|e| {
1047        !(ECHO_CODES.contains(&e.category)
1048            && subject(e).is_some_and(|s| broken_decl_names.contains(&s)))
1049    })
1050}
1051
1052/// #2618: a `private` declaration of a commons this unit `uses`, which the
1053/// unit cannot see. Keyed (in [`private_imports_in`]) by the subject an
1054/// unknown-name diagnostic names it by: `f`, `T`, or a method as `T.m`.
1055#[derive(Debug, Clone, PartialEq, Eq)]
1056pub struct PrivateImport {
1057    /// The commons that declares it.
1058    pub unit: String,
1059    /// `"function"`, `"type"`, `"method"`, `"asset"`, `"embed"` or
1060    /// `"constant"`.
1061    pub kind: &'static str,
1062}
1063
1064/// #2618: the `private` declarations of the commons `local` uses that a
1065/// reference in `local` could be reaching for. A name `local` declares itself
1066/// is left out, since a reference to it is the unit's own; so is a method of a
1067/// type `local` declares. The first `uses` target to declare a subject wins.
1068pub fn private_imports_in<'a>(
1069    local: &crate::symbols::UnitTable,
1070    uses: impl Iterator<Item = (&'a String, &'a crate::symbols::UnitTable)>,
1071) -> HashMap<String, PrivateImport> {
1072    let mut out: HashMap<String, PrivateImport> = HashMap::new();
1073    for (unit, table) in uses {
1074        for (subject, kind) in table.private_subjects() {
1075            let owner = subject.split('.').next().unwrap_or(&subject);
1076            let local_decl = local.types.contains_key(owner)
1077                || (kind != "method"
1078                    && crate::symbols::local_value_kind(local, &subject).is_some());
1079            if local_decl {
1080                continue;
1081            }
1082            out.entry(subject).or_insert(PrivateImport {
1083                unit: unit.clone(),
1084                kind,
1085            });
1086        }
1087    }
1088    out
1089}
1090
1091/// #2618: report a reference to a used commons' `private` declaration as
1092/// `bynk.visibility.private_item` rather than as the unknown name it resolves
1093/// as. An importer does not see private declarations at all (they are left
1094/// out of its composed tables, so its own declaration of the same name is no
1095/// conflict), so the reference first fails as `unknown_*`; this names the
1096/// real reason instead. The subject is read from the message exactly as
1097/// [`split_broken_decl_echoes`] reads it.
1098pub fn rewrite_private_references(
1099    errors: Vec<CompileError>,
1100    private: &HashMap<String, PrivateImport>,
1101) -> Vec<CompileError> {
1102    if private.is_empty() {
1103        return errors;
1104    }
1105    const UNKNOWN_CODES: &[&str] = &[
1106        "bynk.resolve.unknown_type",
1107        "bynk.resolve.unknown_name",
1108        "bynk.resolve.unknown_function",
1109        "bynk.resolve.unknown_static_member",
1110        "bynk.types.unknown_static_member",
1111        "bynk.types.method_not_found",
1112        "bynk.val.unknown_type",
1113    ];
1114    errors
1115        .into_iter()
1116        .map(|e| {
1117            if !UNKNOWN_CODES.contains(&e.category) {
1118                return e;
1119            }
1120            let names: Vec<&str> = e.message.split('`').skip(1).step_by(2).collect();
1121            let subject = match e.category {
1122                "bynk.resolve.unknown_static_member"
1123                | "bynk.types.unknown_static_member"
1124                | "bynk.types.method_not_found" => match (names.first(), names.last()) {
1125                    (Some(t), Some(m)) => format!("{t}.{m}"),
1126                    _ => return e,
1127                },
1128                _ => match names.last() {
1129                    Some(n) => (*n).to_string(),
1130                    None => return e,
1131                },
1132            };
1133            let Some(p) = private.get(&subject) else {
1134                return e;
1135            };
1136            CompileError::new(
1137                "bynk.visibility.private_item",
1138                e.span,
1139                format!("`{subject}` is a private {} of `{}`", p.kind, p.unit),
1140            )
1141            .with_note(format!(
1142                "a `private` declaration is visible only within its own unit and that unit's suites; use what `{}` declares without `private`, or remove the modifier there",
1143                p.unit
1144            ))
1145        })
1146        .collect()
1147}
1148
1149/// #1663 (Decision A): the checker's diagnostics after a resolve that reported
1150/// errors, keeping only those in declarations the resolver found clean.
1151///
1152/// Resolve-then-check is per *declaration*: an unknown name in `b` must not
1153/// hide a type error in `a`, so the checker runs over every declaration. Inside
1154/// a declaration the resolver rejected, the checker would only meet the same
1155/// fault again — under the same code (`unknown_function`), under its own twin
1156/// code (`types.unknown_static_member`), or as a follow-on (`unknown_name` for a
1157/// misplaced `self`, `type_in_expr` beside an unknown variant). The resolver's
1158/// report is the one that names the fault, so that declaration keeps only it.
1159/// `item_spans` are the unit's top-level declarations' spans
1160/// ([`CommonsItem::span`]). A diagnostic outside every declaration is kept
1161/// unless it overlaps a resolve error.
1162pub fn without_resolve_echoes(
1163    checked: Vec<CompileError>,
1164    resolve_errors: &[CompileError],
1165    item_spans: &[Span],
1166) -> Vec<CompileError> {
1167    let within = |outer: Span, at: Span| {
1168        outer.file == at.file
1169            && outer.start <= at.start
1170            && at.start < outer.end.max(outer.start + 1)
1171    };
1172    let rejected: Vec<Span> = item_spans
1173        .iter()
1174        .copied()
1175        .filter(|item| resolve_errors.iter().any(|r| within(*item, r.span)))
1176        .collect();
1177    checked
1178        .into_iter()
1179        .filter(|c| {
1180            !rejected.iter().any(|item| within(*item, c.span))
1181                && !resolve_errors.iter().any(|r| within(r.span, c.span))
1182        })
1183        .collect()
1184}
1185
1186/// Validate name references inside a single file's items against an
1187/// already-built symbol table (`resolved.types`, `resolved.fns`,
1188/// `resolved.methods`). Used by the project-level driver after combining
1189/// declarations from every file in a multi-file commons and from every
1190/// commons brought in by `uses`.
1191pub fn resolve_file(resolved: &ResolvedCommons) -> Result<(), Vec<CompileError>> {
1192    resolve_file_record(resolved, &mut RefSink::new())
1193}
1194
1195/// [`resolve_file`], recording binding edges into `refs` as the walk
1196/// resolves them (v0.25). The project pass sets the sink's per-file context;
1197/// a fresh sink records nothing.
1198pub fn resolve_file_record(
1199    resolved: &ResolvedCommons,
1200    refs: &mut RefSink,
1201) -> Result<(), Vec<CompileError>> {
1202    let mut errors = Vec::new();
1203    let mut sinks = Sinks {
1204        errs: &mut errors,
1205        refs,
1206    };
1207    // #2868: the capabilities this file declares or consumes, so a function
1208    // that uses one it does not list is told how to reach it.
1209    let declared_caps: HashSet<String> = resolved
1210        .commons
1211        .items
1212        .iter()
1213        .filter_map(|i| match i {
1214            CommonsItem::Capability(c) => Some(c.name.name.clone()),
1215            _ => None,
1216        })
1217        .chain(resolved.cross_context.flattened_caps.keys().cloned())
1218        .collect();
1219    for item in &resolved.commons.items {
1220        check_reserved_host_name(item, &mut sinks);
1221        if let CommonsItem::Capability(c) = item {
1222            let first_party = crate::firstparty::is_first_party_unit(&resolved.commons.name);
1223            for op in &c.ops {
1224                check_op_annotations(op, first_party, &mut sinks);
1225            }
1226        }
1227        match item {
1228            CommonsItem::Type(t) => {
1229                sinks.refs.set_owner(&t.name.name);
1230                check_type_decl_refs(t, &resolved.types, &mut sinks);
1231            }
1232            CommonsItem::Event(e) => {
1233                sinks.refs.set_owner(&e.name.name);
1234                check_type_decl_refs(&e.as_type_decl(), &resolved.types, &mut sinks);
1235            }
1236            CommonsItem::Fn(f) => {
1237                sinks.refs.set_owner(f.name.display());
1238                check_fn_refs_with(
1239                    f,
1240                    &resolved.types,
1241                    &resolved.fns,
1242                    &resolved.methods,
1243                    &resolved.assets,
1244                    &resolved.embeds,
1245                    &resolved.consts,
1246                    &resolved.shadowed_imports,
1247                    &resolved.unselected_types,
1248                    &declared_caps,
1249                    &mut sinks,
1250                );
1251            }
1252            CommonsItem::Const(c) => {
1253                sinks.refs.set_owner(&c.name.name);
1254                check_const_refs_with(
1255                    c,
1256                    &resolved.types,
1257                    &resolved.fns,
1258                    &resolved.methods,
1259                    &resolved.consts,
1260                    &resolved.unselected_types,
1261                    &mut sinks,
1262                );
1263            }
1264            CommonsItem::Capability(_)
1265            | CommonsItem::Service(_)
1266            | CommonsItem::Agent(_)
1267            | CommonsItem::Provider(_)
1268            | CommonsItem::Actor(_) => {
1269                check_signature_refs(item, &resolved.types, &mut sinks);
1270            }
1271            // `messages` entries are plain string literals with no type refs
1272            // to resolve here; commons-only legality and the reference/
1273            // duplicate-code checks live in bynk-emit's project validation.
1274            CommonsItem::Messages(_) | CommonsItem::Asset(_) | CommonsItem::Embed(_) => {}
1275        }
1276        sinks.refs.clear_owner();
1277    }
1278    if errors.is_empty() {
1279        Ok(())
1280    } else {
1281        Err(errors)
1282    }
1283}
1284
1285/// #3458: the only annotation a capability operation takes is the standard
1286/// library's `@onUndecodable(miss|fault)`, so it is refused anywhere else, and
1287/// in a first-party unit it must name a policy.
1288fn check_op_annotations(op: &bynk_syntax::ast::CapabilityOp, first_party: bool, sinks: &mut Sinks) {
1289    use crate::checker::codable::{
1290        REPLY_POLICY_ANNOTATION, ReplyPolicy, codable_op_params, mentions_any, op_reply_policy,
1291        reply_policy_word,
1292    };
1293    use bynk_syntax::ast::TypeRef;
1294    // #3458: a typed read (a `Codable` parameter in the return type) is a
1295    // first-party operation's. The provider replies with plain JSON that the
1296    // call site decodes, and what a reply that does not decode means is
1297    // declared on the operation, so a provider that could return anything is
1298    // not accepted yet.
1299    let codable = codable_op_params(op);
1300    if mentions_any(&op.return_type, &codable) {
1301        if !first_party {
1302            sinks.push(
1303                CompileError::new(
1304                    "bynk.generics.codable_op_return_not_first_party",
1305                    op.return_type.span(),
1306                    format!(
1307                        "the return type of capability operation `{}` mentions a `Codable` type parameter, but only the standard library's capabilities may do that",
1308                        op.name.name
1309                    ),
1310                )
1311                .with_note(
1312                    "typed reads are accepted only for the standard library's own capabilities for now; return `String` and decode with `Json.decode[T]` at the call site",
1313                ),
1314            );
1315        } else if !matches!(op.return_type, TypeRef::Effect(..)) {
1316            sinks.push(CompileError::new(
1317                "bynk.generics.internal_op_annotation",
1318                op.return_type.span(),
1319                format!(
1320                    "a typed read, `{}`, returns `Effect[..]` over its `Codable` payload",
1321                    op.name.name
1322                ),
1323            ));
1324        }
1325    }
1326    // A policy only governs a typed read; on any other operation it would look
1327    // in force and do nothing.
1328    if first_party
1329        && op
1330            .annotations
1331            .iter()
1332            .any(|a| a.name.name == REPLY_POLICY_ANNOTATION)
1333        && crate::checker::codable::typed_read_policy(op).is_none()
1334    {
1335        sinks.push(CompileError::new(
1336            "bynk.generics.internal_op_annotation",
1337            op.span,
1338            format!(
1339                "`@{REPLY_POLICY_ANNOTATION}` on `{}`, which is not a typed read (no `Codable` parameter in its `Effect` payload)",
1340                op.name.name
1341            ),
1342        ));
1343    }
1344    if first_party
1345        && op_reply_policy(op) == ReplyPolicy::Miss
1346        && !matches!(&op.return_type, TypeRef::Effect(inner, _) if matches!(**inner, TypeRef::Option(..)))
1347    {
1348        sinks.push(CompileError::new(
1349            "bynk.generics.internal_op_annotation",
1350            op.return_type.span(),
1351            format!(
1352                "`@{REPLY_POLICY_ANNOTATION}(miss)` on `{}` needs an `Effect[Option[..]]` return: a miss is `None`",
1353                op.name.name
1354            ),
1355        ));
1356    }
1357    // A second policy would make the written order decide the behaviour.
1358    if first_party
1359        && op
1360            .annotations
1361            .iter()
1362            .filter(|a| a.name.name == REPLY_POLICY_ANNOTATION)
1363            .count()
1364            > 1
1365    {
1366        sinks.push(CompileError::new(
1367            "bynk.generics.internal_op_annotation",
1368            op.annotations
1369                .iter()
1370                .filter(|a| a.name.name == REPLY_POLICY_ANNOTATION)
1371                .nth(1)
1372                .map_or(op.span, |a| a.span),
1373            format!(
1374                "capability operation `{}` declares `@{REPLY_POLICY_ANNOTATION}` more than once",
1375                op.name.name
1376            ),
1377        ));
1378    }
1379    for ann in &op.annotations {
1380        if !first_party {
1381            sinks.push(
1382                CompileError::new(
1383                    "bynk.generics.internal_op_annotation",
1384                    ann.span,
1385                    format!(
1386                        "`@{}` on capability operation `{}` is internal to the standard library",
1387                        ann.name.name, op.name.name
1388                    ),
1389                )
1390                .with_note("remove the annotation; capability operations take none in user code"),
1391            );
1392        } else if ann.name.name != REPLY_POLICY_ANNOTATION || reply_policy_word(ann).is_none() {
1393            sinks.push(
1394                CompileError::new(
1395                    "bynk.generics.internal_op_annotation",
1396                    ann.span,
1397                    format!(
1398                        "capability operation `{}` takes only `@{REPLY_POLICY_ANNOTATION}(miss)` or `@{REPLY_POLICY_ANNOTATION}(fault)`",
1399                        op.name.name
1400                    ),
1401                )
1402                .with_note("the one operation annotation is the failure policy of a typed read"),
1403            );
1404        }
1405    }
1406}
1407
1408/// #1679 (runtime-semantics track S12): every type named in a handler or
1409/// capability **signature** must resolve, exactly as in a `fn` signature
1410/// (`bynk.resolve.unknown_type`). Their bodies are resolved by the
1411/// context-level pass, but nothing walked the signatures, so `on call(v:
1412/// Bogus)` and `Effect[Unit]` (Bynk's unit is `()`) were accepted and the
1413/// emitter wrote a `/* unknown */` placeholder. Covered:
1414/// - service and agent handler parameters and return types;
1415/// - an agent's key type and its `store` fields' kind arguments
1416///   (`Cell[T]`, `Map[K, V]`, …);
1417/// - capability operation parameters and return types, with the operation's
1418///   own type parameters in scope;
1419/// - a service header's types: a `from websocket(in: …, out: …)` frame pair
1420///   and a `from events(…)` event type;
1421/// - provider operation parameters and return types;
1422/// - an actor's `identity` type.
1423fn check_signature_refs(
1424    item: &CommonsItem,
1425    types: &HashMap<String, Arc<TypeDecl>>,
1426    sinks: &mut Sinks,
1427) {
1428    let handler = |h: &Handler, sinks: &mut Sinks| {
1429        for p in &h.params {
1430            check_type_ref_resolves(&p.type_ref, types, sinks);
1431        }
1432        check_type_ref_resolves(&h.return_type, types, sinks);
1433    };
1434    match item {
1435        CommonsItem::Service(s) => {
1436            match &s.protocol {
1437                ServiceProtocol::WebSocket { in_type, out_type } => {
1438                    check_type_ref_resolves(in_type, types, sinks);
1439                    check_type_ref_resolves(out_type, types, sinks);
1440                }
1441                ServiceProtocol::Events { event_type, .. } => {
1442                    check_type_ref_resolves(event_type, types, sinks);
1443                }
1444                ServiceProtocol::Call
1445                | ServiceProtocol::Http
1446                | ServiceProtocol::Cron
1447                | ServiceProtocol::Queue { .. }
1448                | ServiceProtocol::Email { .. } => {}
1449            }
1450            for h in &s.handlers {
1451                handler(h, sinks);
1452            }
1453        }
1454        CommonsItem::Provider(p) => {
1455            for op in &p.ops {
1456                for param in &op.params {
1457                    check_type_ref_resolves(&param.type_ref, types, sinks);
1458                }
1459                check_type_ref_resolves(&op.return_type, types, sinks);
1460            }
1461        }
1462        CommonsItem::Actor(a) => {
1463            if let Some(identity) = &a.identity {
1464                check_type_ref_resolves(identity, types, sinks);
1465            }
1466        }
1467        CommonsItem::Agent(a) => {
1468            check_type_ref_resolves(&a.key_type, types, sinks);
1469            for f in &a.store_fields {
1470                for arg in &f.kind.args {
1471                    check_type_ref_resolves(arg, types, sinks);
1472                }
1473            }
1474            for h in &a.handlers {
1475                handler(h, sinks);
1476            }
1477        }
1478        CommonsItem::Capability(c) => {
1479            for op in &c.ops {
1480                // A generic operation has no body for a bound to serve, so
1481                // slice 0 rejects one. `Key` (slice 2) and `Codable` (slice 3)
1482                // are allowed: `Key` needs no witness, and a `Codable`
1483                // argument is encoded at the call site, so the provider
1484                // receives plain JSON and the operation's ABI does not grow.
1485                for tp in op.type_params.iter() {
1486                    let Some(bound) = tp
1487                        .bounds
1488                        .iter()
1489                        .find(|b| !matches!(b.name.as_str(), "Key" | "Codable"))
1490                    else {
1491                        continue;
1492                    };
1493                    sinks.push(
1494                        CompileError::new(
1495                            "bynk.generics.bound_on_capability_op",
1496                            bound.span,
1497                            format!(
1498                                "type parameter `{}` of capability operation `{}` carries a bound",
1499                                tp.name.name, op.name.name
1500                            ),
1501                        )
1502                        .with_note(
1503                            "capability operations take only `Key` and `Codable` bounds; remove the `: …`",
1504                        ),
1505                    );
1506                }
1507                let type_params: HashSet<String> = op
1508                    .type_params
1509                    .iter()
1510                    .map(|tp| tp.name.name.clone())
1511                    .collect();
1512                for p in &op.params {
1513                    check_type_ref_resolves_in(&p.type_ref, types, &type_params, sinks);
1514                }
1515                check_type_ref_resolves_in(&op.return_type, types, &type_params, sinks);
1516                check_key_bounds(
1517                    op.params
1518                        .iter()
1519                        .map(|p| &p.type_ref)
1520                        .chain(std::iter::once(&op.return_type)),
1521                    &op.type_params,
1522                    sinks,
1523                );
1524            }
1525        }
1526        CommonsItem::Type(_)
1527        | CommonsItem::Event(_)
1528        | CommonsItem::Fn(_)
1529        | CommonsItem::Messages(_)
1530        | CommonsItem::Asset(_)
1531        | CommonsItem::Embed(_)
1532        | CommonsItem::Const(_) => {}
1533    }
1534}
1535
1536/// v0.157 (ADR 0183): the name a record field *directly contains* — a top-level
1537/// `Named` (`f: A`) or a generic application (`f: A[T]`). Both are direct
1538/// containment edges for the cycle guards; a `List[…]`/`Option[…]` wrapper is
1539/// not (its empty/`None` inhabitant breaks the cycle).
1540fn direct_record_head(tr: &TypeRef) -> Option<&str> {
1541    match tr {
1542        TypeRef::Named(id) => Some(&id.name),
1543        TypeRef::App { name, .. } => Some(&name.name),
1544        _ => None,
1545    }
1546}
1547
1548/// Whether `target` is reachable from `start` over direct record-field edges
1549/// (bare `Named` or generic `App` heads) — the record-containment graph. Used
1550/// to reject indirect record cycles (`A = { b: B }`, `B = { a: A }`); a
1551/// `visited` set bounds the walk on graphs that already contain cycles
1552/// elsewhere.
1553fn record_field_reaches(start: &str, target: &str, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
1554    let mut visited: HashSet<String> = HashSet::new();
1555    let mut stack = vec![start.to_string()];
1556    while let Some(name) = stack.pop() {
1557        if name == target {
1558            return true;
1559        }
1560        if !visited.insert(name.clone()) {
1561            continue;
1562        }
1563        if let Some(decl) = types.get(&name)
1564            && let TypeBody::Record(r) = &decl.body
1565        {
1566            for f in &r.fields {
1567                if let Some(head) = direct_record_head(&f.type_ref) {
1568                    stack.push(head.to_string());
1569                }
1570            }
1571        }
1572    }
1573    false
1574}
1575
1576/// v0.157 (ADR 0183): reject a repeated type-parameter name — a duplicate would
1577/// collapse silently in the substitution map (the later argument winning), so a
1578/// `Pair[T, T]` mis-checks its fields. Shared by `type` and `fn` declarations.
1579fn check_duplicate_type_params(params: &[TypeParam], owner: &str, errors: &mut Sinks) {
1580    let mut seen: HashMap<&str, bynk_syntax::span::Span> = HashMap::new();
1581    for tp in params {
1582        if let Some(prev) = seen.get(tp.name.name.as_str()) {
1583            errors.push(
1584                CompileError::new(
1585                    "bynk.generics.duplicate_type_param",
1586                    tp.span,
1587                    format!(
1588                        "type parameter `{}` is declared more than once on {owner}",
1589                        tp.name.name
1590                    ),
1591                )
1592                .with_label(*prev, "previously declared here"),
1593            );
1594        } else {
1595            seen.insert(tp.name.name.as_str(), tp.span);
1596        }
1597    }
1598}
1599
1600/// Constrained generics slice 0: every bound on `params` names a known
1601/// constraint (`bynk.generics.unknown_constraint`).
1602fn check_type_param_bounds(params: &[TypeParam], errors: &mut Sinks) {
1603    for tp in params {
1604        for e in crate::checker::equality::unknown_constraints(&tp.bounds, &tp.name.name) {
1605            errors.push(e);
1606        }
1607        if let Some(w) = crate::checker::equality::redundant_eq(&tp.bounds, &tp.name.name) {
1608            errors.push(w);
1609        }
1610    }
1611}
1612
1613/// #1653: the generated TypeScript reaches host globals as `globalThis.<name>`,
1614/// so a module-scope declaration of that name (a type, function, agent,
1615/// provider, …) would hide every one of them in its module. Parameters and
1616/// locals are renamed by the emitter instead; a declaration is rejected.
1617fn check_reserved_host_name(item: &CommonsItem, errors: &mut Sinks) {
1618    if let Some(name) = item.name()
1619        && name.name == "globalThis"
1620    {
1621        errors.push(
1622            CompileError::new(
1623                "bynk.resolve.reserved_host_name",
1624                name.span,
1625                "`globalThis` cannot be used as a declaration name",
1626            )
1627            .with_note(
1628                "the generated TypeScript uses `globalThis` to reach the host's built-in objects; rename the declaration",
1629            ),
1630        );
1631    }
1632}
1633
1634/// Recursively walk a type declaration to check that every type reference
1635/// inside it resolves.
1636fn check_type_decl_refs(t: &TypeDecl, types: &HashMap<String, Arc<TypeDecl>>, errors: &mut Sinks) {
1637    // Constrained generics slice 1: the `derives` clause.
1638    let mut derive_errors = Vec::new();
1639    crate::checker::ordering::check_derives(t, types, &mut derive_errors);
1640    for e in derive_errors {
1641        errors.push(e);
1642    }
1643    // A `type` declaration may not reuse a compiler-known built-in type name
1644    // (`List`, `Map`, `Query`, …). Those names are dispatched on by the type
1645    // parser (`parser/types.rs`), so any *reference* to the alias would be
1646    // intercepted as the built-in — the declaration would be silently shadowed
1647    // (`QueueResult`) or fail with an incoherent message at the use site. Reject
1648    // it here, at the declaration, with a message the user can act on. Base
1649    // types and other reserved *keywords* (`Int`, `Result`, …) are already
1650    // rejected earlier, by `expect_ident` at parse time.
1651    if bynk_syntax::keywords::is_builtin_type_name(&t.name.name) {
1652        errors.push(
1653            CompileError::new(
1654                "bynk.resolve.reserved_builtin_type",
1655                t.name.span,
1656                format!(
1657                    "`{}` is a built-in type name and cannot be redeclared",
1658                    t.name.name
1659                ),
1660            )
1661            .with_note("rename the type — built-in type names are reserved in type position"),
1662        );
1663    }
1664    // v0.157 (ADR 0183): a record body may be generic. #593: a sum body may too
1665    // — its variant payloads resolve the parameters as rigid vars, exactly as
1666    // record fields do. Type parameters on a refined / opaque / alias body are
1667    // still rejected; a parameter shadowing a declared type is diagnosed (mirrors the
1668    // function-generics rule).
1669    let type_params: HashSet<String> = t.type_params.iter().map(|p| p.name.name.clone()).collect();
1670    if !t.type_params.is_empty() {
1671        check_duplicate_type_params(&t.type_params, &format!("type `{}`", t.name.name), errors);
1672        check_type_param_bounds(&t.type_params, errors);
1673        if !matches!(t.body, TypeBody::Record(_) | TypeBody::Sum(_)) {
1674            errors.push(
1675                CompileError::new(
1676                    "bynk.generics.generic_non_record",
1677                    t.type_params[0].span,
1678                    format!(
1679                        "type `{}` declares type parameters, but only a record (`{{ … }}`) or sum (`| … | …`) type may be generic",
1680                        t.name.name
1681                    ),
1682                )
1683                .with_note("refined, opaque and alias types cannot be generic — their base is fixed, so a parameter has nowhere to go"),
1684            );
1685        }
1686        // #593: a generic sum may not carry an `embeds` clause. `embeds E as V`
1687        // has `?` wrap an `E` error in the variant `V`; composing that conversion
1688        // with per-parameter substitution (the embedded type could itself be
1689        // generic, or mention the host's parameters) is out of scope for this
1690        // increment.
1691        if let TypeBody::Sum(s) = &t.body
1692            && let Some(clause) = s.embeds.first()
1693        {
1694            errors.push(
1695                CompileError::new(
1696                    "bynk.generics.generic_sum_embeds",
1697                    clause.span,
1698                    format!("generic sum `{}` cannot use an `embeds` clause", t.name.name),
1699                )
1700                .with_note("embedding into a generic sum is not supported — drop the `embeds` clause and wrap the error with `.mapErr(…)`, or make the sum non-generic"),
1701            );
1702        }
1703        for tp in &t.type_params {
1704            if types.contains_key(&tp.name.name) {
1705                errors.push(
1706                    CompileError::new(
1707                        "bynk.generics.type_arg_mismatch",
1708                        tp.span,
1709                        format!(
1710                            "type parameter `{}` shadows the declared type of the same name",
1711                            tp.name.name
1712                        ),
1713                    )
1714                    .with_note("rename the type parameter"),
1715                );
1716            }
1717        }
1718    }
1719    if !t.type_params.is_empty() {
1720        let field_refs: Vec<&TypeRef> = match &t.body {
1721            TypeBody::Record(r) => r.fields.iter().map(|f| &f.type_ref).collect(),
1722            TypeBody::Sum(s) => s
1723                .variants
1724                .iter()
1725                .flat_map(|v| v.payload.iter().map(|f| &f.type_ref))
1726                .collect(),
1727            _ => Vec::new(),
1728        };
1729        check_key_bounds(field_refs.into_iter(), &t.type_params, errors);
1730    }
1731    match &t.body {
1732        TypeBody::Refined { .. } => {
1733            // Refined-type bodies only reference base types directly.
1734        }
1735        TypeBody::Opaque { .. } => {
1736            // Opaque-type bodies only reference base types directly.
1737        }
1738        TypeBody::Record(r) => {
1739            let mut seen = HashMap::new();
1740            for f in &r.fields {
1741                if let Some(prev_span) = seen.get(&f.name.name) {
1742                    errors.push(
1743                        CompileError::new(
1744                            "bynk.resolve.duplicate_field",
1745                            f.name.span,
1746                            format!("field `{}` is declared more than once", f.name.name),
1747                        )
1748                        .with_label(*prev_span, "previously declared here"),
1749                    );
1750                } else {
1751                    seen.insert(f.name.name.clone(), f.name.span);
1752                }
1753                // Detect containment cycles: a direct `type A = { f: A }`,
1754                // and indirect cycles through direct record fields
1755                // (`A = { b: B }`, `B = { a: A }`). Such a cycle admits no finite
1756                // value, and defeats every structural walk downstream (zero-value
1757                // emission, codecs). A `List[...]`/`Option[...]` wrapper (whose
1758                // empty/`None` inhabitant breaks the cycle) is not a direct edge.
1759                // v0.157 (ADR 0183): a generic self-reference `f: A[T]` is a
1760                // `TypeRef::App` direct edge — caught here in the checker (and so
1761                // in the standalone LSP), not only by the emit-side boundary pass.
1762                if let Some(head) = direct_record_head(&f.type_ref) {
1763                    if head == t.name.name {
1764                        errors.push(
1765                            CompileError::new(
1766                                "bynk.resolve.recursive_record_field",
1767                                f.name.span,
1768                                format!(
1769                                    "record `{}` cannot directly contain a field of its own type",
1770                                    t.name.name
1771                                ),
1772                            )
1773                            .with_label(t.name.span, "type declared here")
1774                            .with_note(
1775                                "wrap the recursive reference in `Option[...]` to break the cycle",
1776                            ),
1777                        );
1778                    } else if record_field_reaches(head, &t.name.name, types) {
1779                        errors.push(
1780                            CompileError::new(
1781                                "bynk.resolve.recursive_record_field",
1782                                f.name.span,
1783                                format!(
1784                                    "record `{}` contains itself through this field — `{}` leads back to `{}`",
1785                                    t.name.name, head, t.name.name
1786                                ),
1787                            )
1788                            .with_label(t.name.span, "type declared here")
1789                            .with_note(
1790                                "wrap one field in the cycle in `Option[...]` to break it",
1791                            ),
1792                        );
1793                    }
1794                }
1795                check_type_ref_resolves_in(&f.type_ref, types, &type_params, errors);
1796            }
1797        }
1798        TypeBody::Sum(s) => {
1799            let mut seen = HashMap::new();
1800            for v in &s.variants {
1801                if let Some(prev_span) = seen.get(&v.name.name) {
1802                    errors.push(
1803                        CompileError::new(
1804                            "bynk.resolve.duplicate_variant",
1805                            v.name.span,
1806                            format!("variant `{}` is declared more than once", v.name.name),
1807                        )
1808                        .with_label(*prev_span, "previously declared here"),
1809                    );
1810                } else {
1811                    seen.insert(v.name.name.clone(), v.name.span);
1812                }
1813                let mut payload_seen = HashMap::new();
1814                for f in &v.payload {
1815                    if let Some(prev) = payload_seen.get(&f.name.name) {
1816                        errors.push(
1817                            CompileError::new(
1818                                "bynk.resolve.duplicate_field",
1819                                f.name.span,
1820                                format!(
1821                                    "payload field `{}` is declared more than once in variant `{}`",
1822                                    f.name.name, v.name.name
1823                                ),
1824                            )
1825                            .with_label(*prev, "previously declared here"),
1826                        );
1827                    } else {
1828                        payload_seen.insert(f.name.name.clone(), f.name.span);
1829                    }
1830                    // #1653: a variant is a flat `{ "kind": "<Variant>", ... }`
1831                    // object on the wire, so a payload field named `kind` would
1832                    // collide with the discriminant itself.
1833                    if f.name.name == "kind" {
1834                        errors.push(
1835                            CompileError::new(
1836                                "bynk.resolve.reserved_payload_field",
1837                                f.name.span,
1838                                format!(
1839                                    "variant `{}` cannot have a payload field named `kind`",
1840                                    v.name.name
1841                                ),
1842                            )
1843                            .with_note(
1844                                "`kind` carries the variant's name when a sum is encoded as JSON; rename the field (e.g. `category`)",
1845                            ),
1846                        );
1847                    }
1848                    // #593: a generic sum's declared type parameters are in scope
1849                    // in its variant payloads, resolving as rigid vars (empty set
1850                    // for a non-generic sum — the same reference walk as before).
1851                    check_type_ref_resolves_in(&f.type_ref, types, &type_params, errors);
1852                }
1853            }
1854            // v0.154 (ADR 0178): the `embeds E as V` clauses' source types must
1855            // resolve (the target variant is checked in `check_embeds`).
1856            for clause in &s.embeds {
1857                check_type_ref_resolves(&clause.source_type, types, errors);
1858            }
1859        }
1860    }
1861}
1862
1863/// [`check_fn_refs_with`] for a unit with no braced `consumes` to leave a type out.
1864#[allow(clippy::too_many_arguments)]
1865fn check_fn_refs(
1866    f: &FnDecl,
1867    types: &HashMap<String, Arc<TypeDecl>>,
1868    fns: &HashMap<String, Arc<FnDecl>>,
1869    methods: &HashMap<String, MethodTable>,
1870    assets: &HashMap<String, AssetDecl>,
1871    embeds: &HashMap<String, EmbedDecl>,
1872    consts: &HashMap<String, ConstDecl>,
1873    shadowed: &HashMap<String, ShadowedImport>,
1874    declared_caps: &HashSet<String>,
1875    errors: &mut Sinks,
1876) {
1877    let none = HashSet::new();
1878    check_fn_refs_with(
1879        f,
1880        types,
1881        fns,
1882        methods,
1883        assets,
1884        embeds,
1885        consts,
1886        shadowed,
1887        &none,
1888        declared_caps,
1889        errors,
1890    );
1891}
1892
1893/// [`check_const_refs_with`] for a unit with no braced `consumes` to leave a type out.
1894fn check_const_refs(
1895    c: &ConstDecl,
1896    types: &HashMap<String, Arc<TypeDecl>>,
1897    fns: &HashMap<String, Arc<FnDecl>>,
1898    methods: &HashMap<String, MethodTable>,
1899    consts: &HashMap<String, ConstDecl>,
1900    errors: &mut Sinks,
1901) {
1902    check_const_refs_with(c, types, fns, methods, consts, &HashSet::new(), errors);
1903}
1904
1905#[allow(clippy::too_many_arguments)]
1906fn check_fn_refs_with(
1907    f: &FnDecl,
1908    types: &HashMap<String, Arc<TypeDecl>>,
1909    fns: &HashMap<String, Arc<FnDecl>>,
1910    methods: &HashMap<String, MethodTable>,
1911    assets: &HashMap<String, AssetDecl>,
1912    embeds: &HashMap<String, EmbedDecl>,
1913    consts: &HashMap<String, ConstDecl>,
1914    shadowed: &HashMap<String, ShadowedImport>,
1915    unselected: &HashSet<String>,
1916    declared_caps: &HashSet<String>,
1917    errors: &mut Sinks,
1918) {
1919    // #2868: a `given` function reaches the capabilities it names. A consumed
1920    // context's capability is reached as `B.Cap.op(…)`; that whole chain is
1921    // admitted where it is a call receiver (`given_cap_chain`), so a bare `B`
1922    // is not a name in scope.
1923    let caps: HashSet<String> = f.given.iter().map(|g| g.key().to_string()).collect();
1924    // #2881: what to tell a use of a capability the function does not list. A
1925    // method or a function that is not `Effect[T]` cannot declare `given`
1926    // (`given_fn_refusal`), so "add `given`" would only trade one error for another.
1927    let cap_advice: String = if matches!(f.name, FnName::Method { .. }) {
1928        "a method cannot declare `given`: take the operation as a function-value parameter, `log: (String) -> Effect[()]`, and pass `(m) => Cap.op(m)` from a handler or context function that declares `given`".to_string()
1929    } else if !matches!(f.return_type, TypeRef::Effect(..)) {
1930        "a function that does not return `Effect[T]` cannot declare `given`: take the operation as a function-value parameter, `log: (String) -> Effect[()]`, and pass `(m) => Cap.op(m)` from a handler or context function that declares `given`".to_string()
1931    } else {
1932        "a context function reaches a capability through `given`: add `given {cap}` after its return type, and then every handler or function that calls it must declare it too".to_string()
1933    };
1934    // Parameter types resolve.
1935    // v0.20a: the fn's type parameters are legal named references in its
1936    // own signature and body annotations.
1937    let mut type_params: HashSet<String> = f
1938        .type_params
1939        .iter()
1940        .map(|tp| tp.name.name.clone())
1941        .collect();
1942    check_duplicate_type_params(
1943        &f.type_params,
1944        &format!("function `{}`", f.name.display()),
1945        errors,
1946    );
1947    check_type_param_bounds(&f.type_params, errors);
1948    // #594: an instance method on a generic type inherits the receiver type's
1949    // parameters into scope, so `fn Box.map[U](self, f: A -> U) -> Box[U]` may
1950    // name the type's own parameter `A` alongside the method's `U`. A method
1951    // parameter that reuses one of the type's parameter names would shadow it
1952    // ambiguously in the substitution — diagnose the collision.
1953    if let FnName::Method { type_name, .. } = &f.name
1954        && let Some(recv) = types.get(&type_name.name)
1955    {
1956        for tp in &recv.type_params {
1957            if type_params.contains(&tp.name.name) {
1958                errors.push(
1959                    CompileError::new(
1960                        "bynk.generics.duplicate_type_param",
1961                        f.type_params
1962                            .iter()
1963                            .find(|mp| mp.name.name == tp.name.name)
1964                            .map_or(tp.span, |mp| mp.span),
1965                        format!(
1966                            "type parameter `{}` is already a parameter of the receiver type `{}`",
1967                            tp.name.name, type_name.name
1968                        ),
1969                    )
1970                    .with_label(tp.span, "declared on the type here"),
1971                );
1972            }
1973            type_params.insert(tp.name.name.clone());
1974        }
1975    }
1976    // A `where` entry bounds a type parameter in scope — the method's own or
1977    // its receiver type's.
1978    for wb in &f.where_bounds {
1979        if !type_params.contains(&wb.param.name) {
1980            errors.push(
1981                CompileError::new(
1982                    "bynk.generics.unknown_where_param",
1983                    wb.param.span,
1984                    format!(
1985                        "`where` bounds `{}`, which is not a type parameter of `{}`",
1986                        wb.param.name,
1987                        f.name.display()
1988                    ),
1989                )
1990                .with_note("a `where` clause bounds a type parameter of the function or of its receiver type"),
1991            );
1992        }
1993        for e in crate::checker::equality::unknown_constraints(&wb.bounds, &wb.param.name) {
1994            errors.push(e);
1995        }
1996        if let Some(w) = crate::checker::equality::redundant_eq(&wb.bounds, &wb.param.name) {
1997            errors.push(w);
1998        }
1999    }
2000    let mut seen_params: HashMap<&str, &Ident> = HashMap::new();
2001    for p in &f.params {
2002        check_type_ref_resolves_in(&p.type_ref, types, &type_params, errors);
2003        if let Some(prev) = seen_params.get(p.name.name.as_str()) {
2004            errors.push(
2005                CompileError::new(
2006                    "bynk.resolve.duplicate_param",
2007                    p.name.span,
2008                    format!("parameter `{}` is declared more than once", p.name.name),
2009                )
2010                .with_label(prev.span, "previously declared here"),
2011            );
2012        } else {
2013            seen_params.insert(p.name.name.as_str(), &p.name);
2014        }
2015    }
2016    check_type_ref_resolves_in(&f.return_type, types, &type_params, errors);
2017
2018    // Build the initial scope: parameters plus `self` (for instance methods).
2019    let mut params: HashMap<String, ()> =
2020        f.params.iter().map(|p| (p.name.name.clone(), ())).collect();
2021    if f.has_self {
2022        params.insert("self".to_string(), ());
2023    }
2024    let in_method = matches!(f.name, FnName::Method { .. });
2025    let mut cx = RefCheckCtx {
2026        params: &params,
2027        in_method,
2028        types,
2029        type_params: &type_params,
2030        fns,
2031        methods,
2032        assets,
2033        embeds,
2034        consts,
2035        shadowed,
2036        unselected,
2037        caps: &caps,
2038        given: &f.given,
2039        cap_advice: &cap_advice,
2040        declared_caps,
2041        scopes: Vec::new(),
2042        errors,
2043    };
2044    check_block_references(&f.body, &mut cx);
2045}
2046
2047/// #2881: whether `receiver` spells `Prefix.Cap` for a consumed-context
2048/// capability in `given`: the prefix segments, then the capability, nothing
2049/// else. A bare `Prefix` (or a different chain) is not admitted.
2050fn given_cap_chain(receiver: &Expr, given: &[CapRef], shadowed: &dyn Fn(&str) -> bool) -> bool {
2051    let mut parts: Vec<&str> = Vec::new();
2052    let mut e = receiver;
2053    loop {
2054        match &e.kind {
2055            ExprKind::FieldAccess { receiver, field } => {
2056                parts.push(&field.name);
2057                e = receiver;
2058            }
2059            ExprKind::Ident(id) => {
2060                parts.push(&id.name);
2061                break;
2062            }
2063            _ => return false,
2064        }
2065    }
2066    parts.reverse();
2067    // A parameter or `let` of the head's name is a value, not the prefix.
2068    if shadowed(parts[0]) {
2069        return false;
2070    }
2071    given.iter().any(|g| {
2072        g.context.as_ref().is_some_and(|q| {
2073            parts.len() == q.parts.len() + 1
2074                && q.parts.iter().zip(&parts).all(|(a, b)| a.name == *b)
2075                && parts.last() == Some(&g.key())
2076        })
2077    })
2078}
2079
2080/// #2617: a constant's annotation resolves, and its initialiser names only
2081/// what is in scope. The initialiser has no parameters or bindings, so this is
2082/// the function walk over an empty scope; whether the initialiser is *static*
2083/// is the checker's call (`consts::static_error`).
2084fn check_const_refs_with(
2085    c: &ConstDecl,
2086    types: &HashMap<String, Arc<TypeDecl>>,
2087    fns: &HashMap<String, Arc<FnDecl>>,
2088    methods: &HashMap<String, MethodTable>,
2089    consts: &HashMap<String, ConstDecl>,
2090    unselected: &HashSet<String>,
2091    errors: &mut Sinks,
2092) {
2093    let type_params = HashSet::new();
2094    check_type_ref_resolves_in(&c.ty, types, &type_params, errors);
2095    let params = HashMap::new();
2096    let (assets, embeds, shadowed) = (HashMap::new(), HashMap::new(), HashMap::new());
2097    let mut cx = RefCheckCtx {
2098        params: &params,
2099        in_method: false,
2100        types,
2101        type_params: &type_params,
2102        fns,
2103        methods,
2104        assets: &assets,
2105        embeds: &embeds,
2106        consts,
2107        shadowed: &shadowed,
2108        unselected,
2109        caps: &HashSet::new(),
2110        given: &[],
2111        cap_advice: "",
2112        declared_caps: &HashSet::new(),
2113        scopes: Vec::new(),
2114        errors,
2115    };
2116    check_expr_references(&c.init, &mut cx);
2117}
2118
2119/// #1807, #1814: the walk the naming gates share: every place source writes
2120/// a type name, reporting each one that names a hidden type. See
2121/// [`check_hidden_type_names`] for what is walked.
2122/// How a [`Gate`] reports a gated name written at an identifier, given its owner.
2123type GateReport<'a> = dyn Fn(&Ident, &str) -> CompileError + 'a;
2124
2125struct Gate<'a> {
2126    /// Each gated type name, with its owning unit.
2127    hidden: &'a std::collections::BTreeMap<String, String>,
2128    /// #1814: the error for a gated name written at `id`, given its owner. A
2129    /// unit and a suite name the `uses` that would admit a hidden type
2130    /// differently; a shadowed import is a conflict instead (#1927).
2131    report: &'a GateReport<'a>,
2132    /// #1927: each bare variant whose construction is gated, with its sum's
2133    /// name. Empty for #1807's hidden types, whose bare variants are values
2134    /// typed by their position; a shadowed sum's construction emits its type's
2135    /// name, which the local declaration has taken.
2136    variants: std::collections::BTreeMap<String, String>,
2137    /// #3536: set, [`Gate::variants`] are reported through it wherever a bare
2138    /// variant is *written* — constructed or matched — as the sum it names.
2139    variant_report: Option<&'a GateReport<'a>>,
2140    /// #1927: for a shadowed type, the local declaration of each name, which
2141    /// answers a receiver it can serve (`svc.GET(…)` in a suite, `logo.url`).
2142    /// `None` for #1807's hidden types, which nothing local shares a name with.
2143    locals: Option<&'a HashMap<String, ShadowedImport>>,
2144    /// #3536: the names gated are capabilities, which are also written in
2145    /// `given` clauses, `provides` and a derived capability's base, and in a
2146    /// suite's `stub` clauses; a type gate does not walk those.
2147    caps: bool,
2148    /// #3536: the units a cross-context call names, by the prefix it writes
2149    /// (`pay`, `shop.pay`, or an alias), each with its unit; a method call on
2150    /// one is reported through [`Gate::report`] with the prefix as the name.
2151    units: Option<&'a std::collections::BTreeMap<String, String>>,
2152    errors: Vec<CompileError>,
2153}
2154impl Gate<'_> {
2155    /// #1927: whether the receiver `id` of a method call (`method`) or a
2156    /// field read (`field`) is the local declaration that hides the type:
2157    /// a service addressed in a suite, or an asset's `url`.
2158    fn local_receiver(&self, id: &Ident, method: Option<&Ident>, field: Option<&Ident>) -> bool {
2159        let Some(s) = self.locals.and_then(|l| l.get(&id.name)) else {
2160            return false;
2161        };
2162        match s.local {
2163            "service" => method.is_some(),
2164            "asset" => field.is_some_and(|f| f.name == "url"),
2165            _ => false,
2166        }
2167    }
2168    /// #3536: a capability named in a `given` clause (a qualified `B.Cap` names
2169    /// its unit and is not a flattened name).
2170    fn givens(&mut self, given: &[CapRef]) {
2171        if self.caps {
2172            for c in given.iter().filter(|c| c.context.is_none()) {
2173                self.name(&c.name);
2174            }
2175        }
2176    }
2177    /// #3536: a call `pay.charge(…)` on a unit named by its prefix.
2178    fn unit_call(&mut self, receiver: &Expr) {
2179        let Some(units) = self.units else { return };
2180        let Some(path) = qualified_path(receiver) else {
2181            return;
2182        };
2183        if let Some(owner) = units.get(&path) {
2184            let id = Ident {
2185                name: path,
2186                span: receiver.span,
2187            };
2188            self.errors.push((self.report)(&id, owner));
2189        }
2190    }
2191    /// #3536: a capability named where a declaration refers to one.
2192    fn capability(&mut self, id: &Ident) {
2193        if self.caps {
2194            self.name(id);
2195        }
2196    }
2197    fn name(&mut self, id: &Ident) {
2198        if let Some(owner) = self.hidden.get(&id.name) {
2199            self.errors.push((self.report)(id, owner));
2200        }
2201    }
2202    /// #1927: a bare variant constructed (`Done`, `Done(x)`) of a gated sum.
2203    /// It names the sum in the emitted module (`Status.Done`), so it is the
2204    /// conflict; the error says so, since matching the same variant is legal.
2205    fn bare_variant(&mut self, id: &Ident) {
2206        let Some(sum) = self.variants.get(&id.name) else {
2207            return;
2208        };
2209        if let Some(report) = self.variant_report {
2210            self.errors.push(report(id, sum));
2211            return;
2212        }
2213        let Some(s) = self.locals.and_then(|l| l.get(sum)) else {
2214            return;
2215        };
2216        self.errors.push(
2217            CompileError::new(
2218                "bynk.uses.name_conflict",
2219                id.span,
2220                format!(
2221                    "`{}` constructs a variant of `{sum}` from `{}`, which this unit's {} `{sum}` hides",
2222                    id.name, s.unit, s.local
2223                ),
2224            )
2225            .with_label(s.local_span, format!("{} declared here", s.local))
2226            .with_note(format!(
2227                "constructing a variant bare still names its type (`{sum}.{}`); match on it instead, or rename one of the two",
2228                id.name
2229            )),
2230        );
2231    }
2232    fn type_ref(&mut self, r: &TypeRef) {
2233        match r {
2234            TypeRef::Named(id) => self.name(id),
2235            TypeRef::App { name, args, .. } => {
2236                self.name(name);
2237                for a in args {
2238                    self.type_ref(a);
2239                }
2240            }
2241            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
2242                self.type_ref(a);
2243                self.type_ref(b);
2244            }
2245            TypeRef::Option(t, _)
2246            | TypeRef::Effect(t, _)
2247            | TypeRef::HttpResult(t, _)
2248            | TypeRef::List(t, _)
2249            | TypeRef::Set(t, _)
2250            | TypeRef::Query(t, _)
2251            | TypeRef::Stream(t, _)
2252            | TypeRef::Connection(t, _)
2253            | TypeRef::History(t, _) => self.type_ref(t),
2254            TypeRef::Fn(params, ret, _) => {
2255                for p in params {
2256                    self.type_ref(p);
2257                }
2258                self.type_ref(ret);
2259            }
2260            TypeRef::Base(..)
2261            | TypeRef::QueueResult(_)
2262            | TypeRef::Asset(_)
2263            | TypeRef::RequestHeaders(_)
2264            | TypeRef::RequestQuery(_)
2265            | TypeRef::RequestCookies(_)
2266            | TypeRef::TokenClaims(_)
2267            | TypeRef::BoundaryRejection(_)
2268            | TypeRef::ValidationError(_)
2269            | TypeRef::DecodeError(_)
2270            | TypeRef::Unit(_) => {}
2271        }
2272    }
2273    fn type_decl(&mut self, t: &TypeDecl) {
2274        match &t.body {
2275            TypeBody::Record(r) => {
2276                for f in &r.fields {
2277                    self.type_ref(&f.type_ref);
2278                    // Review of #1813: an `event` field default.
2279                    if let Some(init) = &f.init {
2280                        self.expr(init);
2281                    }
2282                }
2283            }
2284            TypeBody::Sum(s) => {
2285                for v in &s.variants {
2286                    for p in &v.payload {
2287                        self.type_ref(&p.type_ref);
2288                    }
2289                }
2290            }
2291            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
2292        }
2293    }
2294    fn signature(&mut self, params: &[Param], ret: &TypeRef) {
2295        for p in params {
2296            self.type_ref(&p.type_ref);
2297        }
2298        self.type_ref(ret);
2299    }
2300    fn pattern(&mut self, p: &Pattern) {
2301        match p {
2302            Pattern::Variant {
2303                type_name,
2304                variant,
2305                bindings,
2306                ..
2307            } => {
2308                if let Some(tn) = type_name {
2309                    self.name(tn);
2310                } else if self.variant_report.is_some() {
2311                    self.bare_variant(variant);
2312                } else if bindings.is_empty() {
2313                    // A bare, payload-less pattern may name a refined type
2314                    // rather than a variant: `s is Repo` tests a refinement.
2315                    self.name(variant);
2316                }
2317                for b in bindings {
2318                    match &b.kind {
2319                        PatternBindingKind::Positional { pattern }
2320                        | PatternBindingKind::Named { pattern, .. } => self.pattern(pattern),
2321                    }
2322                }
2323            }
2324            Pattern::Record {
2325                type_name, fields, ..
2326            } => {
2327                self.name(type_name);
2328                for (_, sub) in fields {
2329                    if let Some(sub) = sub {
2330                        self.pattern(sub);
2331                    }
2332                }
2333            }
2334            Pattern::List { elems, .. } => {
2335                for e in elems {
2336                    self.pattern(e);
2337                }
2338            }
2339            Pattern::Refined { inner, .. } => self.pattern(inner),
2340            Pattern::Or(alts, _) => {
2341                for a in alts {
2342                    self.pattern(a);
2343                }
2344            }
2345            Pattern::Wildcard(_)
2346            | Pattern::Binding(_)
2347            | Pattern::Literal { .. }
2348            | Pattern::Range(_) => {}
2349        }
2350    }
2351    fn block(&mut self, b: &Block) {
2352        for s in &b.statements {
2353            if let Statement::Let(l) | Statement::EffectLet(l) = s
2354                && let Some(t) = &l.type_annot
2355            {
2356                self.type_ref(t);
2357            }
2358        }
2359        // `expr_children` of a block expression is exactly its statements'
2360        // expressions and its tail.
2361        for e in &b.statements {
2362            let mut exprs = Vec::new();
2363            statement_exprs(e, &mut exprs);
2364            for x in exprs {
2365                self.expr(x);
2366            }
2367        }
2368        self.expr(&b.tail);
2369    }
2370    fn expr(&mut self, e: &Expr) {
2371        match &e.kind {
2372            ExprKind::Block(b) => return self.block(b),
2373            ExprKind::If {
2374                cond,
2375                then_block,
2376                else_block,
2377            } => {
2378                self.expr(cond);
2379                self.block(then_block);
2380                return self.block(else_block);
2381            }
2382            ExprKind::Match { discriminant, arms } => {
2383                self.expr(discriminant);
2384                for arm in arms {
2385                    self.pattern(&arm.pattern);
2386                    if let Some(g) = &arm.guard {
2387                        self.expr(g);
2388                    }
2389                    match &arm.body {
2390                        MatchBody::Expr(b) => self.expr(b),
2391                        MatchBody::Block(b) => self.block(b),
2392                    }
2393                }
2394                return;
2395            }
2396            ExprKind::Is { pattern, .. } => self.pattern(pattern),
2397            ExprKind::RecordConstruction { type_name, .. } => self.name(type_name),
2398            ExprKind::RecordSpread {
2399                type_name: Some(tn),
2400                ..
2401            } => self.name(tn),
2402            ExprKind::FieldAccess { receiver, field } => {
2403                if let ExprKind::Ident(id) = &receiver.kind
2404                    && !self.local_receiver(id, None, Some(field))
2405                {
2406                    self.name(id);
2407                }
2408            }
2409            ExprKind::MethodCall {
2410                receiver,
2411                method,
2412                type_args,
2413                ..
2414            } => {
2415                // #3147: `D1.peek(…)` is a case-only built-in, not a use of the
2416                // `D1` capability, so it needs no `consumes bynk.cloudflare`.
2417                if let ExprKind::Ident(id) = &receiver.kind
2418                    && !(id.name == "D1" && method.name == "peek")
2419                    && !self.local_receiver(id, Some(method), None)
2420                {
2421                    self.name(id);
2422                }
2423                self.unit_call(receiver);
2424                for t in type_args {
2425                    self.type_ref(t);
2426                }
2427            }
2428            ExprKind::Call {
2429                name, type_args, ..
2430            } => {
2431                self.bare_variant(name);
2432                for t in type_args {
2433                    self.type_ref(t);
2434                }
2435            }
2436            ExprKind::Ident(id) => self.bare_variant(id),
2437            ExprKind::Val { type_ref, .. } => self.type_ref(type_ref),
2438            ExprKind::Lambda(l) => {
2439                for p in &l.params {
2440                    if let Some(t) = &p.type_ref {
2441                        self.type_ref(t);
2442                    }
2443                }
2444            }
2445            _ => {}
2446        }
2447        for c in expr_children(e) {
2448            self.expr(c);
2449        }
2450    }
2451}
2452
2453/// #1807: the naming gate for *hidden* types. A hidden type is one this unit's
2454/// composed table carries only because an imported declaration reaches it
2455/// (`crate::project_model::close_reachable_types`): resolvable here, never
2456/// nameable, since `uses` is one level (ADR 0278). Every place the unit's
2457/// source writes a type name is walked: type references in declarations,
2458/// signatures, `let` annotations, lambda parameters and type arguments; a
2459/// record, constructor or spread's type; a type used as a receiver
2460/// (`Repo.of(…)`, `Status.Pending`); a method declared on a type; a
2461/// pattern's qualifier; and a refinement test (`s is Repo`). Bodies are
2462/// walked, and so are an agent's invariants, transitions and `store`
2463/// initialisers, and an `event` field's default. A hidden name in any of them is
2464/// `bynk.resolve.unknown_type`, the error the name gave before the closure
2465/// existed, with a note naming the commons to `uses`.
2466///
2467/// A bare variant (`Pending`) is a value, not a type name, so it is not gated:
2468/// like a literal admitted as a hidden refined type, it is typed by the
2469/// position it fills. (A context still cannot construct one: the rebrand
2470/// construction check covers a hidden commons sum like a `uses`d one.)
2471pub fn check_hidden_type_names(
2472    items: &[CommonsItem],
2473    hidden: &std::collections::BTreeMap<String, String>,
2474) -> Vec<CompileError> {
2475    let report = |id: &Ident, owner: &str| {
2476        hidden_type_error(
2477            id,
2478            format!(
2479                "`{}` reaches this unit only through an imported declaration. It is \
2480                 declared in `{owner}`, which this unit does not `uses`; add `uses \
2481                 {owner}` to name it",
2482                id.name
2483            ),
2484        )
2485    };
2486    let mut g = Gate {
2487        hidden,
2488        report: &report,
2489        variants: Default::default(),
2490        variant_report: None,
2491        locals: None,
2492        caps: false,
2493        units: None,
2494        errors: Vec::new(),
2495    };
2496    gate_items(&mut g, items);
2497    g.errors
2498}
2499
2500/// `bynk.resolve.unknown_type` for a hidden type written at `id`. Not
2501/// `unknown_type_error`: its note lists what is in scope, which a hidden
2502/// type, reached but unnameable, is not.
2503fn hidden_type_error(id: &Ident, note: String) -> CompileError {
2504    CompileError::new(
2505        "bynk.resolve.unknown_type",
2506        id.span,
2507        format!("unknown type `{}`", id.name),
2508    )
2509    .with_note(note)
2510}
2511
2512/// #3536: where a file's `consumes` clauses stand, for
2513/// [`check_unselected_type_names`]: what the unit consumes, what this file's own
2514/// clauses list, and where a clause the file lacks would go.
2515pub struct FileConsumes<'a> {
2516    /// The units the unit consumes, in any of its files.
2517    pub consumed: &'a std::collections::BTreeSet<String>,
2518    /// The unit's aliases (`consumes U { T as V }`), by alias, in any file.
2519    pub aliases: &'a HashMap<String, crate::symbols::ConsumedTypeAlias>,
2520    /// This file's own `consumes` clauses.
2521    pub clauses: &'a [ConsumesDecl],
2522    /// Where a new `consumes` line is inserted when this file has no clause for
2523    /// the owner (offset, and the line break that precedes it): after its last
2524    /// `uses` or `consumes`, else after its header. `None` when the form has no
2525    /// safe place (a braced header).
2526    pub insert_at: Option<(usize, String)>,
2527}
2528
2529impl FileConsumes<'_> {
2530    /// Whether this file's own clauses bring `name` in from `owner`: a bare
2531    /// `consumes owner`, or a braced list naming it (under its alias, if any).
2532    fn lists(&self, owner: &str, name: &str) -> bool {
2533        self.clauses
2534            .iter()
2535            .filter(|c| c.target.joined() == owner)
2536            .any(|c| match &c.selected {
2537                None => true,
2538                Some(items) => items
2539                    .iter()
2540                    .any(|i| i.alias.as_ref().unwrap_or(&i.name).name == name),
2541            })
2542    }
2543
2544    /// How `name` is written in a list: `Original as Alias` for a renamed export.
2545    fn item(&self, owner: &str, name: &str) -> String {
2546        match self.aliases.get(name) {
2547            Some(a) if a.target == owner => format!("{} as {name}", a.original),
2548            _ => name.to_string(),
2549        }
2550    }
2551}
2552
2553/// #3536: where a `consumes` line a file lacks is inserted, with the line break
2554/// (and indent) that precedes it. After the file's last `uses` or `consumes`
2555/// clause (the parser wants them ahead of every declaration); else after its
2556/// header, which is the text up to `header_end`, then the `{` of a braced file.
2557/// `None` when a braced file's `{` is not where it should be.
2558pub fn new_consumes_position(
2559    source: &str,
2560    last_clause_end: Option<usize>,
2561    header_end: usize,
2562    braced: bool,
2563) -> Option<(usize, String)> {
2564    if let Some(end) = last_clause_end {
2565        let lead = if braced {
2566            indent_after(source, end)
2567        } else {
2568            String::new()
2569        };
2570        return Some((past_trailing_comment(source, end), format!("\n{lead}")));
2571    }
2572    if !braced {
2573        let at = past_trailing_comment(source, header_end);
2574        return Some((at, "\n\n".to_string()));
2575    }
2576    let rest = source.get(header_end..)?;
2577    let open = header_end + (rest.len() - rest.trim_start().len());
2578    source[open..].starts_with('{').then_some(())?;
2579    let lead = indent_after(source, open + 1);
2580    Some((past_trailing_comment(source, open + 1), format!("\n{lead}")))
2581}
2582
2583/// `at`, or the end of its line when all that follows `at` on the line is a
2584/// comment, so a line inserted here leaves the comment on the line it was
2585/// written on instead of taking it over.
2586fn past_trailing_comment(source: &str, at: usize) -> usize {
2587    let Some(rest) = source.get(at..) else {
2588        return at;
2589    };
2590    let line = rest.split('\n').next().unwrap_or("");
2591    let trimmed = line.trim();
2592    if trimmed.is_empty() || trimmed.starts_with("//") || trimmed.starts_with("--") {
2593        at + line.trim_end_matches('\r').len()
2594    } else {
2595        at
2596    }
2597}
2598
2599/// The indent of the first non-blank line after `at`, or two spaces.
2600fn indent_after(source: &str, at: usize) -> String {
2601    source
2602        .get(at..)
2603        .and_then(|rest| rest.split('\n').skip(1).find(|l| !l.trim().is_empty()))
2604        .map_or("  ", |l| &l[..l.len() - l.trim_start().len()])
2605        .to_string()
2606}
2607
2608/// #3536: `bynk.consumes.type_not_selected`, for each place a file's source
2609/// writes the name of a type (or a bare variant of a sum) that a unit it
2610/// consumes exports and that **this file's own** `consumes` does not bring in:
2611/// either it lists other names, or only another file of the unit consumes the
2612/// unit. Imports are per file, so naming anything else
2613/// is an error, and carries a fix that edits this file's `consumes`:
2614/// extend the clause it has, or add one.
2615pub fn check_unselected_type_names(
2616    items: &[CommonsItem],
2617    resolved: &ResolvedCommons,
2618    file: &FileConsumes<'_>,
2619) -> Vec<CompileError> {
2620    let owners = resolved
2621        .imported_from
2622        .iter()
2623        .filter(|(_, owner)| file.consumed.contains(*owner))
2624        .map(|(n, o)| (n.clone(), o.clone()))
2625        .collect();
2626    unselected_gate(Names::Types, &owners, &resolved.types, file, |g| {
2627        gate_items(g, items)
2628    })
2629}
2630
2631/// #3536: `bynk.consumes.capability_not_selected`, the same rule for the
2632/// capabilities a braced `consumes U { Cap }` flattens into the unit's namespace:
2633/// naming one (a `given` clause, a call, `provides`, a derived capability's
2634/// base) in a file whose own `consumes` does not list it. `flattened` is the
2635/// unit's capabilities, each with its owner.
2636pub fn check_unselected_capabilities(
2637    items: &[CommonsItem],
2638    flattened: &HashMap<String, String>,
2639    file: &FileConsumes<'_>,
2640) -> Vec<CompileError> {
2641    let owners = flattened
2642        .iter()
2643        .map(|(n, o)| (n.clone(), o.clone()))
2644        .collect();
2645    unselected_gate(Names::Capabilities, &owners, &HashMap::new(), file, |g| {
2646        gate_items(g, items)
2647    })
2648}
2649
2650/// #3536: [`check_unselected_capabilities`] for a unit suite, whose `stub`
2651/// clauses and cases name its target's flattened capabilities.
2652pub fn check_unselected_capabilities_in_suite(
2653    suite: &SuiteDecl,
2654    owners: &std::collections::BTreeMap<String, String>,
2655    file: &FileConsumes<'_>,
2656) -> Vec<CompileError> {
2657    unselected_gate(Names::Capabilities, owners, &HashMap::new(), file, |g| {
2658        gate_suite(g, suite)
2659    })
2660}
2661
2662/// The dotted path an expression of identifiers and field accesses writes
2663/// (`pay`, `shop.pay`), or `None` for anything else.
2664fn qualified_path(e: &Expr) -> Option<String> {
2665    match &e.kind {
2666        ExprKind::Ident(id) => Some(id.name.clone()),
2667        ExprKind::FieldAccess { receiver, field } => {
2668            Some(format!("{}.{}", qualified_path(receiver)?, field.name))
2669        }
2670        _ => None,
2671    }
2672}
2673
2674/// #3536: `bynk.consumes.unit_not_consumed`, the same rule for a cross-context
2675/// call (`pay.charge(…)`): the file that writes it must itself `consumes` the
2676/// unit, in any form. `prefixes` maps each prefix a call may write (the unit's
2677/// name, or the alias of a `consumes U as A`) to the unit. The fix adds
2678/// `consumes U` to this file.
2679pub fn check_unconsumed_unit_calls(
2680    items: &[CommonsItem],
2681    prefixes: &std::collections::BTreeMap<String, String>,
2682    file: &FileConsumes<'_>,
2683) -> Vec<CompileError> {
2684    unit_gate(prefixes, file, |g| gate_items(g, items))
2685}
2686
2687/// [`check_unconsumed_unit_calls`] for a unit suite.
2688pub fn check_unconsumed_unit_calls_in_suite(
2689    suite: &SuiteDecl,
2690    prefixes: &std::collections::BTreeMap<String, String>,
2691    file: &FileConsumes<'_>,
2692) -> Vec<CompileError> {
2693    unit_gate(prefixes, file, |g| gate_suite(g, suite))
2694}
2695
2696fn unit_gate(
2697    prefixes: &std::collections::BTreeMap<String, String>,
2698    file: &FileConsumes<'_>,
2699    walk: impl FnOnce(&mut Gate<'_>),
2700) -> Vec<CompileError> {
2701    let missing: std::collections::BTreeMap<String, String> = prefixes
2702        .iter()
2703        .filter(|(_, unit)| !file.clauses.iter().any(|c| c.target.joined() == **unit))
2704        .map(|(p, u)| (p.clone(), u.clone()))
2705        .collect();
2706    let report = |id: &Ident, unit: &str| {
2707        let mut e = CompileError::new(
2708            "bynk.consumes.unit_not_consumed",
2709            id.span,
2710            format!("`{}` is not in scope: this file does not `consumes {unit}`", id.name),
2711        )
2712        .with_note(format!(
2713            "imports are per file: a call to another unit's service is in scope in a file that itself `consumes` it. Add `consumes {unit}` to this file."
2714        ));
2715        if let Some((offset, separator)) = &file.insert_at {
2716            let at = Span::new_in(id.span.file, *offset, *offset);
2717            e = e.with_suggestion(
2718                format!("add `consumes {unit}` to this file"),
2719                vec![(at, format!("{separator}consumes {unit}"))],
2720                Applicability::MachineApplicable,
2721            );
2722        }
2723        e
2724    };
2725    let mut g = Gate {
2726        hidden: &std::collections::BTreeMap::new(),
2727        report: &report,
2728        variants: Default::default(),
2729        variant_report: None,
2730        locals: None,
2731        caps: false,
2732        units: Some(&missing),
2733        errors: Vec::new(),
2734    };
2735    walk(&mut g);
2736    g.errors
2737}
2738
2739/// What a per-file gate is about.
2740#[derive(Clone, Copy)]
2741enum Names {
2742    Types,
2743    Capabilities,
2744}
2745
2746/// #3536: [`check_unselected_type_names`] for a unit suite. `owners` maps each
2747/// type a unit the suite's target consumes exports, except those the target or
2748/// the suite declares itself, to that unit; `types` is the suite's view.
2749pub fn check_unselected_type_names_in_suite(
2750    suite: &SuiteDecl,
2751    owners: &std::collections::BTreeMap<String, String>,
2752    types: &HashMap<String, Arc<TypeDecl>>,
2753    file: &FileConsumes<'_>,
2754) -> Vec<CompileError> {
2755    unselected_gate(Names::Types, owners, types, file, |g| gate_suite(g, suite))
2756}
2757
2758/// The gate both walk through: every name in `owners` this file's own clauses
2759/// do not bring in is warned on where `walk` meets it, along with the bare
2760/// variants of its sums.
2761fn unselected_gate(
2762    names: Names,
2763    owners: &std::collections::BTreeMap<String, String>,
2764    types: &HashMap<String, Arc<TypeDecl>>,
2765    file: &FileConsumes<'_>,
2766    walk: impl FnOnce(&mut Gate<'_>),
2767) -> Vec<CompileError> {
2768    let mut gated = std::collections::BTreeMap::new();
2769    let mut variants = std::collections::BTreeMap::new();
2770    for (name, owner) in owners.iter().filter(|(n, o)| !file.lists(o, n)) {
2771        gated.insert(name.clone(), owner.clone());
2772        if let Some(TypeBody::Sum(sum)) = types.get(name).map(|t| &t.body) {
2773            variants.extend(
2774                sum.variants
2775                    .iter()
2776                    .map(|v| (v.name.name.clone(), name.clone())),
2777            );
2778        }
2779    }
2780    // A variant another sum in scope declares is that sum's, not this one's.
2781    variants.retain(|v, sum| {
2782        !types.iter().any(|(n, t)| {
2783            n != sum
2784                && !gated.contains_key(n)
2785                && matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|x| x.name.name == *v))
2786        })
2787    });
2788    // Each report's name this file must list and its owner, by the byte range it
2789    // is reported at (one file's, so the range identifies the site).
2790    let hits = std::cell::RefCell::new(std::collections::BTreeMap::<
2791        (usize, usize),
2792        (String, String),
2793    >::new());
2794    let report_name = |id: &Ident, name: &str, owner: &str| {
2795        let why = if file.clauses.iter().any(|c| c.target.joined() == owner) {
2796            format!("this file's `consumes {owner}` does not list it")
2797        } else {
2798            format!("this file does not `consumes {owner}`")
2799        };
2800        let message = if matches!(names, Names::Capabilities) {
2801            format!("capability `{name}` is not in scope: {why}")
2802        } else if id.name == name {
2803            format!("`{name}` is not in scope: {why}")
2804        } else {
2805            format!(
2806                "`{}` is a variant of `{name}`, which is not in scope: {why}",
2807                id.name
2808            )
2809        };
2810        hits.borrow_mut().insert(
2811            (id.span.start, id.span.end),
2812            (name.to_string(), owner.to_string()),
2813        );
2814        let code = match names {
2815            Names::Types => "bynk.consumes.type_not_selected",
2816            Names::Capabilities => "bynk.consumes.capability_not_selected",
2817        };
2818        CompileError::new(code, id.span, message).with_note(format!(
2819            "imports are per file: a name from another unit is in scope in a file that itself `consumes` it, and in a braced list only if it is listed. Add `{name}` to this file's `consumes {owner} {{ … }}`."
2820        ))
2821    };
2822    let report = |id: &Ident, owner: &str| report_name(id, &id.name, owner);
2823    let variant_report = |id: &Ident, sum: &str| report_name(id, sum, &owners[sum]);
2824    let mut g = Gate {
2825        hidden: &gated,
2826        report: &report,
2827        variants,
2828        variant_report: Some(&variant_report),
2829        locals: None,
2830        caps: matches!(names, Names::Capabilities),
2831        units: None,
2832        errors: Vec::new(),
2833    };
2834    walk(&mut g);
2835    let errors = std::mem::take(&mut g.errors);
2836    attach_consumes_fixes(errors, &hits.into_inner(), file)
2837}
2838
2839/// #3536: give each [`check_unselected_type_names`] error a fix that edits the
2840/// file it is in. A file with a braced clause for the owner gains `, Name` in
2841/// it; one with none gains a line listing **every** name it needs from that
2842/// owner, so the errors share one edit and the batch applies it once.
2843fn attach_consumes_fixes(
2844    errors: Vec<CompileError>,
2845    hits: &std::collections::BTreeMap<(usize, usize), (String, String)>,
2846    file: &FileConsumes<'_>,
2847) -> Vec<CompileError> {
2848    let mut needed: std::collections::BTreeMap<&str, std::collections::BTreeSet<&str>> =
2849        Default::default();
2850    for (name, owner) in hits.values() {
2851        needed.entry(owner).or_default().insert(name);
2852    }
2853    let applicable = bynk_syntax::error::Applicability::MachineApplicable;
2854    errors
2855        .into_iter()
2856        .map(|e| {
2857            let Some((name, owner)) = hits.get(&(e.span.start, e.span.end)) else {
2858                return e;
2859            };
2860            let own = || file.clauses.iter().filter(|c| c.target.joined() == *owner);
2861            let extend = own().find_map(|c| c.selected.as_ref()?.last());
2862            if let Some(last) = extend {
2863                let end = last
2864                    .alias
2865                    .as_ref()
2866                    .map_or(last.name.span.end, |a| a.span.end);
2867                let at = Span::new_in(e.span.file, end, end);
2868                let item = file.item(owner, name);
2869                return e.with_suggestion(
2870                    format!("add `{name}` to this file's `consumes {owner}`"),
2871                    vec![(at, format!(", {item}"))],
2872                    applicable,
2873                );
2874            }
2875            let Some((offset, separator)) = &file.insert_at else {
2876                return e;
2877            };
2878            let offset = *offset;
2879            let list = needed[owner.as_str()]
2880                .iter()
2881                .map(|n| file.item(owner, n))
2882                .collect::<Vec<_>>()
2883                .join(", ");
2884            let at = Span::new_in(e.span.file, offset, offset);
2885            e.with_suggestion(
2886                format!("add `consumes {owner} {{ {list} }}` to this file"),
2887                vec![(at, format!("{separator}consumes {owner} {{ {list} }}"))],
2888                applicable,
2889            )
2890        })
2891        .collect()
2892}
2893
2894/// #1927: the naming gate for a `uses`-imported type the unit hides behind
2895/// its own declaration of another kind (a function, asset, service, agent or
2896/// provider: `crate::project_model::shadowed_imports`). The type stays in the
2897/// unit's table, so an imported declaration that uses it still checks, and a
2898/// value of it still flows through the unit's code. But the emitted module
2899/// binds the name to the local declaration, so the unit may not write it: every
2900/// position [`check_hidden_type_names`] gates is `bynk.uses.name_conflict`
2901/// here, and so is constructing one of the sum's variants bare (`Done`), which
2902/// emits the type's name too. Matching a variant does not.
2903pub fn check_shadowed_type_names(
2904    items: &[CommonsItem],
2905    shadowed: &HashMap<String, ShadowedImport>,
2906    types: &HashMap<String, Arc<TypeDecl>>,
2907) -> Vec<CompileError> {
2908    let (gated, variants) = shadowed_type_gate(shadowed, types);
2909    let report = |id: &Ident, _owner: &str| {
2910        let s = &shadowed[&id.name];
2911        shadowed_import_error(&id.name, id.span, s)
2912    };
2913    let mut g = Gate {
2914        hidden: &gated,
2915        report: &report,
2916        variants,
2917        variant_report: None,
2918        locals: Some(shadowed),
2919        caps: false,
2920        units: None,
2921        errors: Vec::new(),
2922    };
2923    gate_items(&mut g, items);
2924    g.errors
2925}
2926
2927/// #1927: the shadowed imported types, by name with their owning unit, and
2928/// each bare variant of a shadowed sum, with the sum's name.
2929fn shadowed_type_gate(
2930    shadowed: &HashMap<String, ShadowedImport>,
2931    types: &HashMap<String, Arc<TypeDecl>>,
2932) -> (
2933    std::collections::BTreeMap<String, String>,
2934    std::collections::BTreeMap<String, String>,
2935) {
2936    let mut gated = std::collections::BTreeMap::new();
2937    let mut variants = std::collections::BTreeMap::new();
2938    for (name, s) in shadowed.iter().filter(|(_, s)| s.imported == "type") {
2939        gated.insert(name.clone(), s.unit.clone());
2940        if let Some(TypeBody::Sum(sum)) = types.get(name).map(|t| &t.body) {
2941            for v in &sum.variants {
2942                variants.insert(v.name.name.clone(), name.clone());
2943            }
2944        }
2945    }
2946    (gated, variants)
2947}
2948
2949/// Walk every item of a unit through `g`.
2950fn gate_items(g: &mut Gate<'_>, items: &[CommonsItem]) {
2951    if g.hidden.is_empty() && g.units.is_none() {
2952        return;
2953    }
2954    for item in items {
2955        match item {
2956            CommonsItem::Type(t) => g.type_decl(t),
2957            CommonsItem::Event(e) => g.type_decl(&e.as_type_decl()),
2958            CommonsItem::Fn(f) => {
2959                if let FnName::Method { type_name, .. } = &f.name {
2960                    g.name(type_name);
2961                }
2962                g.givens(&f.given);
2963                g.signature(&f.params, &f.return_type);
2964                g.block(&f.body);
2965            }
2966            CommonsItem::Capability(c) => {
2967                if let Some(d) = &c.derived {
2968                    g.capability(&d.base);
2969                }
2970                for op in &c.ops {
2971                    g.signature(&op.params, &op.return_type);
2972                }
2973            }
2974            CommonsItem::Provider(p) => {
2975                g.capability(&p.capability);
2976                g.givens(&p.given);
2977                for op in &p.ops {
2978                    g.signature(&op.params, &op.return_type);
2979                    g.block(&op.body);
2980                }
2981            }
2982            CommonsItem::Service(s) => {
2983                match &s.protocol {
2984                    ServiceProtocol::WebSocket { in_type, out_type } => {
2985                        g.type_ref(in_type);
2986                        g.type_ref(out_type);
2987                    }
2988                    ServiceProtocol::Events { event_type, .. } => g.type_ref(event_type),
2989                    ServiceProtocol::Call
2990                    | ServiceProtocol::Http
2991                    | ServiceProtocol::Cron
2992                    | ServiceProtocol::Queue { .. }
2993                    | ServiceProtocol::Email { .. } => {}
2994                }
2995                g.givens(&s.default_given);
2996                for h in &s.handlers {
2997                    g.givens(&h.given);
2998                    g.signature(&h.params, &h.return_type);
2999                    g.block(&h.body);
3000                }
3001            }
3002            CommonsItem::Agent(a) => {
3003                g.type_ref(&a.key_type);
3004                for f in &a.store_fields {
3005                    for arg in &f.kind.args {
3006                        g.type_ref(arg);
3007                    }
3008                    if let Some(init) = &f.init {
3009                        g.expr(init);
3010                    }
3011                }
3012                for h in &a.handlers {
3013                    g.givens(&h.given);
3014                    g.signature(&h.params, &h.return_type);
3015                    g.block(&h.body);
3016                }
3017                for inv in &a.invariants {
3018                    g.expr(&inv.predicate);
3019                }
3020                for t in &a.transitions {
3021                    g.expr(&t.predicate);
3022                }
3023            }
3024            CommonsItem::Actor(a) => {
3025                if let Some(id) = &a.identity {
3026                    g.type_ref(id);
3027                }
3028            }
3029            CommonsItem::Messages(_) | CommonsItem::Asset(_) | CommonsItem::Embed(_) => {}
3030            CommonsItem::Const(c) => {
3031                g.type_ref(&c.ty);
3032                g.expr(&c.init);
3033            }
3034        }
3035    }
3036}
3037
3038/// #1814: the naming gate for a test suite's view. A suite resolves names in
3039/// its target's privileged view (a unit suite) or its harness table (a
3040/// `system` suite), each closed over the types its imported declarations reach
3041/// (`crate::project_model::close_view_types`). A hidden type is resolvable
3042/// there, so a case can build and read a reached field, but a suite may no
3043/// more name it than its target may. Walks every `stub` clause's argument
3044/// patterns and values, every case body, and every property's `for all`
3045/// bindings, `where` filter and predicate, as [`check_hidden_type_names`]
3046/// walks a unit's items. `target` is the unit whose `uses` would admit a
3047/// hidden name: the target of a unit suite, or the suite itself (`None`) for a
3048/// `system` suite, which declares its own `uses`.
3049pub fn check_hidden_type_names_in_suite(
3050    suite: &SuiteDecl,
3051    target: Option<&str>,
3052    hidden: &std::collections::BTreeMap<String, String>,
3053) -> Vec<CompileError> {
3054    let report = |id: &Ident, owner: &str| {
3055        let name = &id.name;
3056        hidden_type_error(
3057            id,
3058            match target {
3059                Some(target) => format!(
3060                    "`{name}` reaches this suite only through an imported declaration. It is \
3061                     declared in `{owner}`, which `{target}` does not `uses`; add `uses {owner}` \
3062                     to `{target}` to name it"
3063                ),
3064                None => format!(
3065                    "`{name}` reaches this suite only through an imported declaration. It is \
3066                     declared in `{owner}`, which this suite does not `uses`; add `uses {owner}` \
3067                     to name it"
3068                ),
3069            },
3070        )
3071    };
3072    let mut g = Gate {
3073        hidden,
3074        report: &report,
3075        variants: Default::default(),
3076        variant_report: None,
3077        locals: None,
3078        caps: false,
3079        units: None,
3080        errors: Vec::new(),
3081    };
3082    gate_suite(&mut g, suite);
3083    g.errors
3084}
3085
3086/// #1927: [`check_shadowed_type_names`] for a unit suite: a case may no more
3087/// write a type its target hides than the target may.
3088pub fn check_shadowed_type_names_in_suite(
3089    suite: &SuiteDecl,
3090    shadowed: &HashMap<String, ShadowedImport>,
3091    types: &HashMap<String, Arc<TypeDecl>>,
3092) -> Vec<CompileError> {
3093    let (gated, variants) = shadowed_type_gate(shadowed, types);
3094    let report =
3095        |id: &Ident, _owner: &str| shadowed_import_error(&id.name, id.span, &shadowed[&id.name]);
3096    let mut g = Gate {
3097        hidden: &gated,
3098        report: &report,
3099        variants,
3100        variant_report: None,
3101        locals: Some(shadowed),
3102        caps: false,
3103        units: None,
3104        errors: Vec::new(),
3105    };
3106    gate_suite(&mut g, suite);
3107    g.errors
3108}
3109
3110/// Walk every stub, case and property of `suite` through `g`.
3111fn gate_suite(g: &mut Gate<'_>, suite: &SuiteDecl) {
3112    if g.hidden.is_empty() && g.units.is_none() {
3113        return;
3114    }
3115    let stub = |g: &mut Gate<'_>, s: &StubClause| {
3116        g.capability(&s.capability);
3117        for a in &s.args {
3118            if let ArgPattern::Value(e) = a {
3119                g.expr(e);
3120            }
3121        }
3122        match &s.rhs {
3123            StubRhs::Returns(e) => g.expr(e),
3124            StubRhs::ReturnsEach(outcomes, _) => {
3125                for o in outcomes {
3126                    if let SeqOutcome::Value(e) = o {
3127                        g.expr(e);
3128                    }
3129                }
3130            }
3131            StubRhs::Fails(_) | StubRhs::Never(_) => {}
3132        }
3133        if let Some(a) = &s.after {
3134            g.expr(a);
3135        }
3136    };
3137    for s in &suite.stubs {
3138        stub(g, s);
3139    }
3140    // #2834: a suite helper may no more name a hidden type than a case may.
3141    for f in &suite.fns {
3142        for p in &f.params {
3143            g.type_ref(&p.type_ref);
3144        }
3145        g.type_ref(&f.return_type);
3146        g.block(&f.body);
3147    }
3148    for case in &suite.cases {
3149        for s in &case.stubs {
3150            stub(g, s);
3151        }
3152        g.block(&case.body);
3153    }
3154    for prop in &suite.properties {
3155        for b in &prop.forall.bindings {
3156            g.type_ref(&b.type_ref);
3157        }
3158        if let Some(w) = &prop.forall.where_pred {
3159            g.expr(w);
3160        }
3161        g.block(&prop.forall.body);
3162    }
3163}
3164
3165fn unknown_type_error(id: &Ident) -> CompileError {
3166    CompileError::new(
3167        "bynk.resolve.unknown_type",
3168        id.span,
3169        format!("unknown type `{}`", id.name),
3170    )
3171    .with_note(
3172        "in scope are the base types (`Int`, `Float`, `String`, `Bool`, `Duration`, \
3173         `Instant`, `Bytes`), the built-in generics (`List`, `Map`, `Option`, `Result`, …), \
3174         `ValidationError`, and the types this unit declares or imports",
3175    )
3176}
3177
3178/// v0.157 (ADR 0183): a generic type named without its `[…]` arguments.
3179fn bare_generic_type_error(id: &Ident, arity: usize) -> CompileError {
3180    CompileError::new(
3181        "bynk.generics.type_arg_count",
3182        id.span,
3183        format!(
3184            "generic type `{}` must be applied to {} type argument{} — write `{}[…]`",
3185            id.name,
3186            arity,
3187            if arity == 1 { "" } else { "s" },
3188            id.name
3189        ),
3190    )
3191    .with_note("a generic type is used only through a concrete instantiation")
3192}
3193
3194/// Recursively check that every type reference resolves.
3195fn check_type_ref_resolves(
3196    r: &TypeRef,
3197    types: &HashMap<String, Arc<TypeDecl>>,
3198    errors: &mut Sinks,
3199) {
3200    check_type_ref_resolves_in(r, types, &HashSet::new(), errors)
3201}
3202
3203/// v0.20a: like [`check_type_ref_resolves`], with the enclosing function's
3204/// type parameters in scope — a `Named` reference matching one is a type
3205/// variable, not an unknown type.
3206fn check_type_ref_resolves_in(
3207    r: &TypeRef,
3208    types: &HashMap<String, Arc<TypeDecl>>,
3209    type_params: &HashSet<String>,
3210    errors: &mut Sinks,
3211) {
3212    match r {
3213        TypeRef::Base(_, _) => {}
3214        // v0.20a: a function type's components must each resolve.
3215        TypeRef::Fn(params, ret, _) => {
3216            for p in params {
3217                check_type_ref_resolves_in(p, types, type_params, errors);
3218            }
3219            check_type_ref_resolves_in(ret, types, type_params, errors);
3220        }
3221        TypeRef::Named(id) => {
3222            if let Some(decl) = types.get(&id.name) {
3223                errors.refs.record(id.span, SymbolKind::Type, &id.name);
3224                // v0.157 (ADR 0183): a generic type must be applied to its type
3225                // arguments — a bare `Paginated` (declared `Paginated[T]`) is an
3226                // under-application.
3227                if !decl.type_params.is_empty() {
3228                    errors.push(bare_generic_type_error(id, decl.type_params.len()));
3229                }
3230            } else if !type_params.contains(&id.name) {
3231                errors.push(unknown_type_error(id));
3232            }
3233        }
3234        // v0.157 (ADR 0183): `Name[Arg, …]` — a user generic-type application.
3235        // Validate existence, that the target is generic, and arity; then walk
3236        // the arguments.
3237        TypeRef::App { name, args, span } => {
3238            match types.get(&name.name) {
3239                None if type_params.contains(&name.name) => {
3240                    // A type parameter applied to arguments (`T[Int]`) — a type
3241                    // parameter is not itself generic (no higher-kinded types).
3242                    errors.push(
3243                        CompileError::new(
3244                            "bynk.generics.type_arg_count",
3245                            *span,
3246                            format!(
3247                                "type parameter `{}` cannot take type arguments — it is not a generic type",
3248                                name.name
3249                            ),
3250                        )
3251                        .with_note("higher-kinded type parameters are not supported"),
3252                    );
3253                }
3254                None => errors.push(unknown_type_error(name)),
3255                Some(decl) => {
3256                    errors.refs.record(name.span, SymbolKind::Type, &name.name);
3257                    let expected = decl.type_params.len();
3258                    // Finding #46: `decl` comes from the combined cross-file
3259                    // symbol table (`uses`/multi-file siblings), so its span
3260                    // may belong to a different file than `name` — a label
3261                    // can't express that without per-label file identity (a
3262                    // Wave 8 follow-up). A note keeps the same conservative
3263                    // choice `bynk-emit/src/project/consistency.rs` already
3264                    // makes for its own always-cross-file diagnostics,
3265                    // rather than risk underlining unrelated text.
3266                    if expected == 0 {
3267                        errors.push(
3268                            CompileError::new(
3269                                "bynk.generics.type_arg_count",
3270                                *span,
3271                                format!(
3272                                    "type `{}` is not generic — it takes no type arguments",
3273                                    name.name
3274                                ),
3275                            )
3276                            .with_note("type declared here"),
3277                        );
3278                    } else if expected != args.len() {
3279                        errors.push(
3280                            CompileError::new(
3281                                "bynk.generics.type_arg_count",
3282                                *span,
3283                                format!(
3284                                    "type `{}` expects {} type argument{}, but {} {} given",
3285                                    name.name,
3286                                    expected,
3287                                    if expected == 1 { "" } else { "s" },
3288                                    args.len(),
3289                                    if args.len() == 1 { "was" } else { "were" },
3290                                ),
3291                            )
3292                            .with_note("type declared here"),
3293                        );
3294                    } else {
3295                        // A bound the type declares (`type Set2[T: Eq]`) is checked
3296                        // against each argument written here. A bare type
3297                        // parameter argument is not checked (slice 0: no body
3298                        // requires a type's bound).
3299                        let scope: Vec<&str> = type_params.iter().map(String::as_str).collect();
3300                        for (tp, arg) in decl.type_params.iter().zip(args) {
3301                            // Slice 1: an `Ord` bound requires an orderable argument.
3302                            if crate::checker::equality::has_ord(&tp.bounds)
3303                                && let Some(part) =
3304                                    crate::checker::ordering::typeref_not_ord(arg, &scope, types)
3305                            {
3306                                errors.push(CompileError::new(
3307                                        "bynk.types.not_orderable",
3308                                        arg.span(),
3309                                        format!(
3310                                            "`{}` requires `{}: Ord`, but this makes `{}` `{part}`, which is not orderable",
3311                                            name.name, tp.name.name, tp.name.name,
3312                                        ),
3313                                    ));
3314                                continue;
3315                            }
3316                            // Slice 2: a `Key` bound requires a key argument.
3317                            if crate::checker::equality::has_key(&tp.bounds)
3318                                && let Some(blocker) =
3319                                    crate::checker::keying::typeref_not_key(arg, &scope, types)
3320                            {
3321                                errors.push(
3322                                    CompileError::new(
3323                                        "bynk.types.not_keyable",
3324                                        arg.span(),
3325                                        format!(
3326                                            "`{}` requires `{}: Key`, but this makes `{}` `{}`, which is not `Key`{}",
3327                                            name.name,
3328                                            tp.name.name,
3329                                            tp.name.name,
3330                                            crate::checker::equality::render(arg),
3331                                            crate::checker::keying::float_clause(&blocker),
3332                                        ),
3333                                    )
3334                                    .with_note(crate::checker::keying::key_note(&blocker)),
3335                                );
3336                                continue;
3337                            }
3338                            if !crate::checker::equality::has_eq(&tp.bounds) {
3339                                continue;
3340                            }
3341                            let mut visited = HashSet::new();
3342                            let Some(blocker) = crate::checker::equality::walk_ref(
3343                                arg,
3344                                &scope,
3345                                types,
3346                                &mut visited,
3347                            ) else {
3348                                continue;
3349                            };
3350                            let top = matches!(
3351                                arg,
3352                                TypeRef::Stream(..)
3353                                    | TypeRef::Connection(..)
3354                                    | TypeRef::Fn(..)
3355                                    | TypeRef::Effect(..)
3356                                    | TypeRef::Query(..)
3357                            );
3358                            let (code, why) = crate::checker::equality::explain(blocker, top);
3359                            errors.push(CompileError::new(
3360                                code,
3361                                arg.span(),
3362                                format!(
3363                                    "`{}` requires `{}: Eq`, but this makes `{}` `{}` — {why}",
3364                                    name.name,
3365                                    tp.name.name,
3366                                    tp.name.name,
3367                                    crate::checker::equality::render(arg),
3368                                ),
3369                            ));
3370                        }
3371                    }
3372                }
3373            }
3374            for a in args {
3375                check_type_ref_resolves_in(a, types, type_params, errors);
3376            }
3377        }
3378        TypeRef::Result(t, e, _) => {
3379            check_type_ref_resolves_in(t, types, type_params, errors);
3380            check_type_ref_resolves_in(e, types, type_params, errors);
3381        }
3382        TypeRef::Option(t, _) => {
3383            check_type_ref_resolves_in(t, types, type_params, errors);
3384        }
3385        TypeRef::Effect(t, _) => {
3386            check_type_ref_resolves_in(t, types, type_params, errors);
3387        }
3388        TypeRef::HttpResult(t, _) => {
3389            check_type_ref_resolves_in(t, types, type_params, errors);
3390        }
3391        TypeRef::QueueResult(_)
3392        | TypeRef::Asset(_)
3393        | TypeRef::RequestHeaders(_)
3394        | TypeRef::RequestQuery(_)
3395        | TypeRef::RequestCookies(_)
3396        | TypeRef::TokenClaims(_)
3397        | TypeRef::BoundaryRejection(_) => {}
3398        TypeRef::List(t, _) => {
3399            check_type_ref_resolves_in(t, types, type_params, errors);
3400        }
3401        // K6a (#2596): a `Set`'s element follows the `Map`-key rule.
3402        TypeRef::Set(t, _) => {
3403            check_type_ref_resolves_in(t, types, type_params, errors);
3404            check_keyable(t, types, type_params, errors, KeyRole::SetElement);
3405        }
3406        TypeRef::Query(t, _) => {
3407            check_type_ref_resolves_in(t, types, type_params, errors);
3408        }
3409        TypeRef::Stream(t, _) => {
3410            check_type_ref_resolves_in(t, types, type_params, errors);
3411        }
3412        TypeRef::Connection(t, _) => {
3413            check_type_ref_resolves_in(t, types, type_params, errors);
3414        }
3415        // v0.119 (ADR 0155): `History[Agent]` is a test-only generator, legal only
3416        // as a `for all` binding inside a `property` (validated in
3417        // `check_property_body`). A `History[…]` reaching this declared-type walk —
3418        // a field, parameter, return, or local annotation — is out of place.
3419        TypeRef::History(_, span) => {
3420            errors.push(
3421                CompileError::new(
3422                    "bynk.history.outside_property",
3423                    *span,
3424                    "`History[…]` is only valid as a `for all` generator inside a `property`",
3425                )
3426                .with_note(
3427                    "bind a driven call-history with `for all run: History[Agent]` in a `property`",
3428                ),
3429            );
3430        }
3431        TypeRef::Map(k, v, _) => {
3432            check_type_ref_resolves_in(k, types, type_params, errors);
3433            check_type_ref_resolves_in(v, types, type_params, errors);
3434            check_keyable(k, types, type_params, errors, KeyRole::MapKey);
3435        }
3436        TypeRef::ValidationError(_) | TypeRef::DecodeError(_) => {}
3437        TypeRef::Unit(_) => {}
3438    }
3439}
3440
3441/// v0.20b: `Map` keys are confined to value-keyable types — `String`, `Int`,
3442/// and refined/opaque types over them — so the emitted `ReadonlyMap` keeps
3443/// value equality (object keys would compare by reference). A type parameter
3444/// is admitted in key position: it can only ever be instantiated through a
3445/// concrete `Map[K, V]` reference elsewhere, and that site is checked.
3446/// Which value-keyable position [`check_keyable`] is checking.
3447#[derive(Clone, Copy)]
3448enum KeyRole {
3449    MapKey,
3450    /// K6a (#2596): a `Set`'s element.
3451    SetElement,
3452}
3453
3454fn check_keyable(
3455    k: &TypeRef,
3456    types: &HashMap<String, Arc<TypeDecl>>,
3457    type_params: &HashSet<String>,
3458    errors: &mut Sinks,
3459    role: KeyRole,
3460) {
3461    let params: Vec<&str> = type_params.iter().map(String::as_str).collect();
3462    // A type parameter is admitted here: whether its declaration says `K: Key`
3463    // is checked where the declaration is (`check_key_bounds`, and the checker
3464    // for a function). An unknown name has already been reported by the
3465    // resolution walk; don't pile a keyability error on top of it.
3466    let Some(blocker) = crate::checker::keying::typeref_not_key(k, &params, types) else {
3467        return;
3468    };
3469    let what = match role {
3470        KeyRole::MapKey => "a `Map` key",
3471        KeyRole::SetElement => "a `Set` element",
3472    };
3473    errors.push(
3474        CompileError::new(
3475            "bynk.types.not_keyable",
3476            k.span(),
3477            format!(
3478                "{what} must be `Key`, but `{}` is not{}",
3479                crate::checker::equality::render(k),
3480                crate::checker::keying::float_clause(&blocker)
3481            ),
3482        )
3483        .with_note(crate::checker::keying::key_note(&blocker)),
3484    );
3485}
3486
3487/// The type parameters of `params` that `t` places in a `Map` key or `Set`
3488/// element, in source order.
3489fn key_position_params<'p>(t: &TypeRef, params: &'p [TypeParam], out: &mut Vec<&'p TypeParam>) {
3490    fn mentions<'p>(t: &TypeRef, params: &'p [TypeParam], out: &mut Vec<&'p TypeParam>) {
3491        match t {
3492            TypeRef::Named(id) => {
3493                if let Some(p) = params.iter().find(|p| p.name.name == id.name)
3494                    && !out.iter().any(|q| q.name.name == p.name.name)
3495                {
3496                    out.push(p);
3497                }
3498            }
3499            TypeRef::Option(a, _) | TypeRef::List(a, _) => mentions(a, params, out),
3500            TypeRef::App { args, .. } => args.iter().for_each(|a| mentions(a, params, out)),
3501            _ => {}
3502        }
3503    }
3504    match t {
3505        TypeRef::Map(k, v, _) => {
3506            mentions(k, params, out);
3507            key_position_params(k, params, out);
3508            key_position_params(v, params, out);
3509        }
3510        TypeRef::Set(e, _) => {
3511            mentions(e, params, out);
3512            key_position_params(e, params, out);
3513        }
3514        TypeRef::Option(a, _)
3515        | TypeRef::List(a, _)
3516        | TypeRef::Effect(a, _)
3517        | TypeRef::HttpResult(a, _)
3518        | TypeRef::Query(a, _)
3519        | TypeRef::Stream(a, _)
3520        | TypeRef::Connection(a, _)
3521        | TypeRef::History(a, _) => key_position_params(a, params, out),
3522        TypeRef::Result(a, b, _) => {
3523            key_position_params(a, params, out);
3524            key_position_params(b, params, out);
3525        }
3526        TypeRef::Fn(ps, ret, _) => {
3527            ps.iter().for_each(|p| key_position_params(p, params, out));
3528            key_position_params(ret, params, out);
3529        }
3530        TypeRef::App { args, .. } => args
3531            .iter()
3532            .for_each(|a| key_position_params(a, params, out)),
3533        _ => {}
3534    }
3535}
3536
3537/// Constrained generics slice 2 (DECISION F): a type parameter of a type
3538/// declaration or a capability operation that reaches a `Map` key or `Set`
3539/// element in `refs` is declared `Key` (`bynk.generics.missing_key_bound`, with a
3540/// machine-applicable fix on the parameter list). A function's signature is the
3541/// checker's, where the function's `where` clauses are in scope.
3542fn check_key_bounds<'a>(
3543    refs: impl Iterator<Item = &'a TypeRef>,
3544    params: &[TypeParam],
3545    errors: &mut Sinks,
3546) {
3547    let mut reported: HashSet<&str> = HashSet::new();
3548    for t in refs {
3549        let mut found = Vec::new();
3550        key_position_params(t, params, &mut found);
3551        for p in found {
3552            if crate::checker::equality::has_key(&p.bounds) || !reported.insert(&p.name.name) {
3553                continue;
3554            }
3555            // `Key` implies `Eq`: an explicit `Eq` is replaced, not joined.
3556            let edit = match p.bounds.iter().find(|b| b.name == "Eq") {
3557                Some(eq) => (eq.span, "Key".to_string()),
3558                None => {
3559                    let end = p.bounds.last().map_or(p.name.span, |b| b.span).end;
3560                    let text = if p.bounds.is_empty() {
3561                        ": Key"
3562                    } else {
3563                        " + Key"
3564                    };
3565                    (
3566                        bynk_syntax::span::Span::new_in(p.name.span.file, end, end),
3567                        text.to_string(),
3568                    )
3569                }
3570            };
3571            errors.push(
3572                CompileError::new(
3573                    "bynk.generics.missing_key_bound",
3574                    t.span(),
3575                    format!(
3576                        "a `Map` key or `Set` element mentions type parameter `{}`, which has no `Key` bound",
3577                        p.name.name
3578                    ),
3579                )
3580                .with_note(format!(
3581                    "a type parameter that keys a `Map` or `Set` must say so: declare `{}: Key`",
3582                    p.name.name
3583                ))
3584                .with_suggestion(
3585                    format!("declare `{}: Key`", p.name.name),
3586                    vec![edit],
3587                    bynk_syntax::error::Applicability::MachineApplicable,
3588                ),
3589            );
3590        }
3591    }
3592}
3593
3594/// Lookup a name across scopes. Returns true if it's bound somewhere
3595/// (param, self, or any let-scope).
3596fn name_in_scope(name: &str, params: &HashMap<String, ()>, scopes: &[HashMap<String, ()>]) -> bool {
3597    if params.contains_key(name) {
3598        return true;
3599    }
3600    scopes.iter().rev().any(|s| s.contains_key(name))
3601}
3602
3603/// Validate a record construction's *field set* — every required field present,
3604/// no undeclared extra field, no field initialised twice, and every shorthand
3605/// `{ name }` bound in scope. Pure over the declaration and the provided fields;
3606/// the caller supplies its own scope predicate (the resolver's lexical scope via
3607/// [`name_in_scope`], the checker's binding table via `Ctx::lookup`) and its own
3608/// diagnostic sink.
3609///
3610/// #711: this walk skips `Service`/`Agent`/`Actor` items, so their handler
3611/// bodies never pass through it — the checker's `check_record_construction` is
3612/// their only backstop and calls this same function. A single implementation is
3613/// the point: an earlier fix copied three of these four checks into the checker
3614/// and dropped the shorthand one, re-opening the gap for shorthand fields. Both
3615/// callers now share this, so the two cannot re-diverge.
3616pub(crate) fn check_record_field_set(
3617    type_name: &Ident,
3618    fields: &[FieldInit],
3619    record: &RecordBody,
3620    // #852: the span of the whole `TypeName { … }` literal, so the missing-field
3621    // quick-fix knows where to insert a new field (before the closing brace when
3622    // the literal is empty).
3623    construction_span: Span,
3624    in_scope: impl Fn(&str) -> bool,
3625    errors: &mut Vec<CompileError>,
3626) {
3627    let declared: HashMap<&str, &RecordField> = record
3628        .fields
3629        .iter()
3630        .map(|f| (f.name.name.as_str(), f))
3631        .collect();
3632    let mut provided: HashMap<&str, bynk_syntax::span::Span> = HashMap::new();
3633    for f in fields {
3634        if !declared.contains_key(f.name.name.as_str()) {
3635            errors.push(
3636                CompileError::new(
3637                    "bynk.resolve.unknown_field",
3638                    f.name.span,
3639                    format!(
3640                        "record type `{}` has no field `{}`",
3641                        type_name.name, f.name.name
3642                    ),
3643                )
3644                // Finding #46: `decl_name_span` may name a declaration in a
3645                // different file than this construction site (both callers
3646                // resolve against the combined cross-file symbol table) — a
3647                // note instead of a label, matching the same conservative
3648                // choice made elsewhere for cross-file provenance without
3649                // per-label file identity (a Wave 8 follow-up).
3650                .with_note("type declared here"),
3651            );
3652        }
3653        if let Some(prev) = provided.get(f.name.name.as_str()) {
3654            errors.push(
3655                CompileError::new(
3656                    "bynk.resolve.duplicate_field_init",
3657                    f.name.span,
3658                    format!("field `{}` is initialised more than once", f.name.name),
3659                )
3660                .with_label(*prev, "previously initialised here"),
3661            );
3662        } else {
3663            provided.insert(f.name.name.as_str(), f.name.span);
3664        }
3665        // A shorthand `{ name }` (no `: value`) reads the binding `name` from
3666        // scope — it must exist. The full `field: value` form is checked by the
3667        // caller (the resolver recurses into the value, the checker types it).
3668        if f.value.is_none() && !in_scope(&f.name.name) {
3669            errors.push(
3670                CompileError::new(
3671                    "bynk.resolve.unknown_name",
3672                    f.name.span,
3673                    format!(
3674                        "shorthand field initialiser `{}` requires a binding of that name in scope",
3675                        f.name.name
3676                    ),
3677                )
3678                .with_note("either bring `{name}` into scope or use the full `field: value` form"),
3679            );
3680        }
3681    }
3682    // Missing required fields. Each is a diagnostic anchored at the type name;
3683    // a field whose type has a safe default additionally carries a
3684    // machine-applicable "add field `x`" quick-fix (#852, DECISIONS B/C) that
3685    // inserts `x: <default>` at a fmt-stable position, and — when more than one
3686    // field is missing and every missing field is defaultable — the first such
3687    // diagnostic also carries an "add all missing fields" convenience.
3688    //
3689    // #2607 (Decision C): a field that declares a default is not required — a
3690    // literal that leaves it out takes the default.
3691    let missing: Vec<&RecordField> = record
3692        .fields
3693        .iter()
3694        .filter(|f| f.init.is_none() && !provided.contains_key(f.name.name.as_str()))
3695        .collect();
3696    // The edit for a `body` of one or more `name: default` entries. With
3697    // existing fields it appends `, body` right after the last one. With an
3698    // *empty* literal there is no field span to anchor to and the interior
3699    // spacing/trailing punctuation is unknown, so instead the whole ` { … }`
3700    // tail (from the end of the type name through the closing brace) is
3701    // **replaced** with a canonical ` { body }` — fmt-stable regardless of how
3702    // the empty braces were originally spelled (`{}`, `{ }`, `{  }`).
3703    let field_edit = |body: &str| -> (Span, String) {
3704        match fields.iter().map(|f| f.span.end).max() {
3705            Some(end) => (Span::new(end, end), format!(", {body}")),
3706            None => (
3707                Span::new(type_name.span.end, construction_span.end),
3708                format!(" {{ {body} }}"),
3709            ),
3710        }
3711    };
3712    // Defaultable missing fields, in declaration order, as `name: default`.
3713    let defaultable: Vec<String> = missing
3714        .iter()
3715        .filter_map(|f| field_default_init(f))
3716        .collect();
3717    let all_defaultable = defaultable.len() == missing.len();
3718
3719    for (i, decl_field) in missing.iter().enumerate() {
3720        let mut err = CompileError::new(
3721            "bynk.resolve.missing_field",
3722            type_name.span,
3723            format!(
3724                "missing required field `{}` for record `{}`",
3725                decl_field.name.name, type_name.name
3726            ),
3727        )
3728        .with_label(decl_field.name.span, "field declared here");
3729        if let Some(piece) = field_default_init(decl_field) {
3730            err = err.with_suggestion(
3731                format!("add field `{}`", decl_field.name.name),
3732                vec![field_edit(&piece)],
3733                Applicability::MachineApplicable,
3734            );
3735        }
3736        // The "add all missing fields" convenience rides on the first missing
3737        // diagnostic (they all share `type_name.span`, so it surfaces together
3738        // with the single-field fixes), and only when the whole set is
3739        // defaultable and there is more than one to add.
3740        if i == 0 && missing.len() > 1 && all_defaultable {
3741            err = err.with_suggestion(
3742                "add all missing fields",
3743                vec![field_edit(&defaultable.join(", "))],
3744                Applicability::MachineApplicable,
3745            );
3746        }
3747        errors.push(err);
3748    }
3749}
3750
3751/// The `name: <default>` initialiser for a missing record field, or `None` when
3752/// the field's type has no value that is guaranteed to re-check clean (#852,
3753/// DECISION B). Deliberately conservative: an inline-refined field or a
3754/// user-named type (which may itself be refined, a sum, or opaque) has no
3755/// synthesised default — only the unrefined built-in scalars, `Option` (`None`),
3756/// and `List` (`[]`) do, so the inserted value always type-checks.
3757fn field_default_init(field: &RecordField) -> Option<String> {
3758    if field.refinement.is_some() {
3759        return None;
3760    }
3761    let default = match &field.type_ref {
3762        TypeRef::Base(BaseType::Int, _) => "0",
3763        TypeRef::Base(BaseType::Float, _) => "0.0",
3764        TypeRef::Base(BaseType::String, _) => "\"\"",
3765        TypeRef::Base(BaseType::Bool, _) => "false",
3766        TypeRef::Option(..) => "None",
3767        TypeRef::List(..) => "[]",
3768        _ => return None,
3769    };
3770    Some(format!("{}: {}", field.name.name, default))
3771}
3772
3773#[allow(clippy::too_many_arguments)]
3774/// Bundles the reference-walk's read-only lookup tables and mutable
3775/// traversal state (finding #37): threading nine positional parameters
3776/// through a ~900-line walk meant 313 of resolver.rs's 2,346 lines were
3777/// argument names at recursive call sites.
3778struct RefCheckCtx<'a, 'b> {
3779    params: &'a HashMap<String, ()>,
3780    in_method: bool,
3781    types: &'a HashMap<String, Arc<TypeDecl>>,
3782    type_params: &'a HashSet<String>,
3783    fns: &'a HashMap<String, Arc<FnDecl>>,
3784    methods: &'a HashMap<String, MethodTable>,
3785    /// #1883, slice 1a: the asset names in scope, values of type `Asset`.
3786    assets: &'a HashMap<String, AssetDecl>,
3787    /// #2387, slice 1: the embed names in scope, `String` values.
3788    embeds: &'a HashMap<String, EmbedDecl>,
3789    /// #2617: the constant names in scope, values of their annotated types.
3790    consts: &'a HashMap<String, ConstDecl>,
3791    /// #1925: imports a local declaration of another kind hides.
3792    shadowed: &'a HashMap<String, ShadowedImport>,
3793    /// #3536: first-party types a braced `consumes` leaves out.
3794    unselected: &'a HashSet<String>,
3795    /// #2868: the capabilities a `given` function names: an identifier that is
3796    /// one is a capability receiver (`Logger.error(…)`), typed by the checker.
3797    caps: &'a HashSet<String>,
3798    /// #2881: the function's `given` clause, for the `B.Cap.op(…)` chain of a
3799    /// consumed context's capability.
3800    given: &'a [CapRef],
3801    /// #2881: the note on a use of a capability `given` does not list;
3802    /// `{cap}` stands for the capability's name.
3803    cap_advice: &'a str,
3804    /// #2868: every capability the context declares or consumes, for the note
3805    /// on a use the function's `given` does not cover.
3806    declared_caps: &'a HashSet<String>,
3807    scopes: Vec<HashMap<String, ()>>,
3808    errors: &'a mut Sinks<'b>,
3809}
3810
3811fn check_block_references(block: &Block, cx: &mut RefCheckCtx) {
3812    cx.scopes.push(HashMap::new());
3813    for stmt in &block.statements {
3814        check_statement_references(stmt, cx);
3815    }
3816    check_expr_references(&block.tail, cx);
3817    cx.scopes.pop();
3818}
3819
3820fn check_statement_references(stmt: &Statement, cx: &mut RefCheckCtx) {
3821    match stmt {
3822        Statement::Let(l) | Statement::EffectLet(l) => {
3823            check_expr_references(&l.value, cx);
3824            if let Some(annot) = &l.type_annot {
3825                check_type_ref_resolves_in(annot, cx.types, cx.type_params, cx.errors);
3826            }
3827            if let Some(prev) = cx.types.get(&l.name.name) {
3828                cx.errors.push(
3829                    CompileError::new(
3830                        "bynk.resolve.let_shadows_type",
3831                        l.name.span,
3832                        format!(
3833                            "`let {}` shadows the declared type `{}`",
3834                            l.name.name, l.name.name
3835                        ),
3836                    )
3837                    .with_label(prev.name.span, "type declared here")
3838                    .with_note("choose a different name for the let binding"),
3839                );
3840            } else if let Some(prev) = cx.fns.get(&l.name.name) {
3841                cx.errors.push(
3842                    CompileError::new(
3843                        "bynk.resolve.let_shadows_fn",
3844                        l.name.span,
3845                        format!(
3846                            "`let {}` shadows the declared function `{}`",
3847                            l.name.name, l.name.name
3848                        ),
3849                    )
3850                    .with_label(prev.name.ident().span, "function declared here")
3851                    .with_note("choose a different name for the let binding"),
3852                );
3853            } else if l.name.name != "_" {
3854                cx.scopes
3855                    .last_mut()
3856                    .unwrap()
3857                    .insert(l.name.name.clone(), ());
3858            }
3859        }
3860        Statement::Expect(a) => {
3861            check_expr_references(&a.value, cx);
3862        }
3863        Statement::Do(d) => {
3864            check_expr_references(&d.value, cx);
3865        }
3866        Statement::Assign(a) => {
3867            // v0.81: walk the RHS for references; the target resolves to a
3868            // `store` field, handled in the storage-track checker slice.
3869            check_expr_references(&a.value, cx);
3870        }
3871        Statement::Advance(a) => {
3872            check_expr_references(&a.amount, cx);
3873        }
3874        // #2640: the bindings of a `par` block are checked against the scope
3875        // outside it. Every name is declared up front so a sibling mention reads
3876        // as the checker's `bynk.par.sibling_name`, not as an unresolved name too.
3877        Statement::Par(p) => {
3878            for inner in &p.statements {
3879                if let Statement::EffectLet(l) = inner
3880                    && l.name.name != "_"
3881                {
3882                    cx.scopes
3883                        .last_mut()
3884                        .unwrap()
3885                        .insert(l.name.name.clone(), ());
3886                }
3887            }
3888            for inner in &p.statements {
3889                check_statement_references(inner, cx);
3890            }
3891        }
3892    }
3893}
3894
3895/// v0.9: `HttpResult.Variant(args)`, the qualified `HttpResult` constructor.
3896/// Reports an unknown variant, and says whether `receiver.method(args)` was one.
3897fn check_http_result_call(
3898    receiver: &Expr,
3899    method: &Ident,
3900    args: &[Expr],
3901    cx: &mut RefCheckCtx,
3902) -> bool {
3903    let ExprKind::Ident(id) = &receiver.kind else {
3904        return false;
3905    };
3906    if name_in_scope(&id.name, cx.params, &cx.scopes) || id.name != "HttpResult" {
3907        return false;
3908    }
3909    if http_variant(&method.name).is_none() {
3910        cx.errors.push(CompileError::new(
3911            "bynk.resolve.unknown_static_member",
3912            method.span,
3913            format!("`HttpResult` has no variant named `{}`", method.name),
3914        ));
3915    }
3916    for a in args {
3917        check_expr_references(a, cx);
3918    }
3919    true
3920}
3921
3922/// #3147: `D1.peek(…)` reads a participant's test database, from an
3923/// `integration` or `system` case. A function body is none: report it, and say
3924/// whether `receiver.method` was it.
3925fn refuse_peek_in_fn(receiver: &Expr, method: &Ident, cx: &mut RefCheckCtx) -> bool {
3926    let ExprKind::Ident(id) = &receiver.kind else {
3927        return false;
3928    };
3929    if id.name != "D1"
3930        || method.name != "peek"
3931        || name_in_scope(&id.name, cx.params, &cx.scopes)
3932        || cx.types.contains_key(&id.name)
3933    {
3934        return false;
3935    }
3936    cx.errors.push(
3937        CompileError::new(
3938            "bynk.test.peek_outside_case",
3939            receiver.span.merge(method.span),
3940            "`D1.peek` is only valid inside an `integration` or `system` case",
3941        )
3942        .with_note(
3943            "it reads a participant's test database, which only those tiers stand up; the deployed app has no such handle",
3944        ),
3945    );
3946    true
3947}
3948
3949#[allow(clippy::too_many_lines)]
3950fn check_expr_references(expr: &Expr, cx: &mut RefCheckCtx) {
3951    match &expr.kind {
3952        // v0.43: resolve names referenced inside each interpolation hole.
3953        ExprKind::InterpStr(parts) => {
3954            for part in parts {
3955                if let InterpPart::Hole(hole) = part {
3956                    check_expr_references(hole, cx);
3957                }
3958            }
3959        }
3960        ExprKind::IntLit { .. }
3961        | ExprKind::FloatLit { .. }
3962        | ExprKind::DecimalLit { .. }
3963        | ExprKind::DurationLit { .. }
3964        | ExprKind::StrLit(_)
3965        | ExprKind::BoolLit(_)
3966        | ExprKind::None
3967        | ExprKind::UnitLit => {}
3968        // v0.20b: a list literal — each element resolves as a value.
3969        ExprKind::ListLit(elems, ..) => {
3970            for el in elems {
3971                check_expr_references(el, cx);
3972            }
3973        }
3974        // Slice C: `Wire(<String>)` — the raw inner expression resolves as an
3975        // ordinary value (a string literal in practice).
3976        ExprKind::Wire(inner) => {
3977            check_expr_references(inner, cx);
3978        }
3979        // v0.20a: a lambda introduces a scope frame holding its params; the
3980        // body walks with the frame in place. Annotated param types resolve
3981        // through the ordinary type-ref check.
3982        ExprKind::Lambda(lambda) => {
3983            for p in &lambda.params {
3984                if let Some(tr) = &p.type_ref {
3985                    check_type_ref_resolves_in(tr, cx.types, cx.type_params, cx.errors);
3986                }
3987            }
3988            let mut frame: HashMap<String, ()> = HashMap::new();
3989            for p in &lambda.params {
3990                frame.insert(p.name.name.clone(), ());
3991            }
3992            cx.scopes.push(frame);
3993            check_expr_references(&lambda.body, cx);
3994            cx.scopes.pop();
3995        }
3996        ExprKind::EffectPure(inner) => {
3997            check_expr_references(inner, cx);
3998        }
3999        ExprKind::Expect(inner) => {
4000            check_expr_references(inner, cx);
4001        }
4002        ExprKind::Faults(f) => {
4003            // #1812: a call-site principal's identity (`by User(who)`) is an
4004            // ordinary expression, resolved like the call's arguments.
4005            if let Some(identity) = f.principal.as_ref().and_then(|p| p.identity.as_deref()) {
4006                check_expr_references(identity, cx);
4007            }
4008            check_expr_references(&f.call, cx);
4009        }
4010        ExprKind::Val { args, .. } => {
4011            // v0.9.4: the mocked type is validated by the checker; resolve any
4012            // pin-argument references here.
4013            for a in args {
4014                check_expr_references(a, cx);
4015            }
4016        }
4017        ExprKind::Observation(_) => {
4018            // v0.117: a `with` predicate's free names are the operation's
4019            // parameters, bound during type checking and not visible to name
4020            // resolution; a count is a literal. Nothing to resolve here.
4021        }
4022        ExprKind::Trace { .. } => {
4023            // v0.117: `Cap.op` names a capability seam, not value references.
4024        }
4025        ExprKind::RecordSpread {
4026            type_name,
4027            base,
4028            overrides,
4029            ..
4030        } => {
4031            if let Some(tn) = type_name
4032                && !cx.types.contains_key(&tn.name)
4033            {
4034                cx.errors.push(unknown_type_error(tn));
4035            }
4036            check_expr_references(base, cx);
4037            for f in overrides {
4038                if let Some(v) = &f.value {
4039                    check_expr_references(v, cx);
4040                }
4041            }
4042        }
4043        ExprKind::Ident(id) => {
4044            if id.name == "self" {
4045                if !cx.in_method {
4046                    cx.errors.push(
4047                        CompileError::new(
4048                            "bynk.resolve.self_outside_method",
4049                            id.span,
4050                            "`self` can only be used inside a method body",
4051                        )
4052                        .with_note(
4053                            "declare the function as `fn TypeName.method(self, ...)` if you intended a method",
4054                        ),
4055                    );
4056                }
4057                return;
4058            }
4059            if name_in_scope(&id.name, cx.params, &cx.scopes) {
4060                // OK.
4061            } else if cx.caps.contains(&id.name) {
4062                // #2868: a capability the function's `given` names; the
4063                // checker dispatches `Cap.op(…)`.
4064            } else if cx.consts.contains_key(&id.name)
4065                && cx
4066                    .shadowed
4067                    .get(&id.name)
4068                    .is_none_or(|s| s.imported == "type")
4069            {
4070                // #2617: a constant name is a value of its annotated type;
4071                // the checker types it (`check_ident`). A constant never
4072                // shares a name with a variant in scope
4073                // (`consts::variant_conflict_error`), so it is met first.
4074                cx.errors.refs.record(id.span, SymbolKind::Const, &id.name);
4075            } else if http_variant(&id.name).is_some() {
4076                // v0.9: predeclared HttpResult variant (e.g. `NoContent`,
4077                // `Unauthorized`). The checker validates payload arity and
4078                // expected-type disambiguation.
4079            } else if let Some(sum_owner) = find_unique_variant_owner(&id.name, cx) {
4080                // It's a bare variant reference. We treat it as a valid
4081                // expression in resolver — the type checker will assign
4082                // the correct sum type. Mark with no error.
4083                let _ = sum_owner;
4084            } else if cx.fns.contains_key(&id.name)
4085                && cx
4086                    .shadowed
4087                    .get(&id.name)
4088                    .is_some_and(|s| s.imported == "type")
4089            {
4090                // Review of #1933: a local function hiding an imported type of
4091                // its name answers a bare reference (a function value), as in
4092                // the emitted module; the checker judges the position
4093                // (`check_ident`'s function arm, met before types).
4094                cx.errors.refs.record(id.span, SymbolKind::Fn, &id.name);
4095            } else if (cx.assets.contains_key(&id.name) || cx.embeds.contains_key(&id.name))
4096                && cx
4097                    .shadowed
4098                    .get(&id.name)
4099                    .is_some_and(|s| s.imported == "type")
4100            {
4101                // #1927: a local asset (or #2387 embed) hiding an imported
4102                // type of its name is the asset here, as in the emitted
4103                // module; the checker types it (`check_ident` meets assets
4104                // and embeds before types).
4105            } else if let Some(s) = cx.shadowed.get(&id.name)
4106                && !matches!(s.local, "function" | "asset" | "embed" | "constant")
4107            {
4108                // #1925: the local declaration (a type, event, service,
4109                // agent or provider) is no value here, and it hides the import.
4110                cx.errors.push(shadowed_import_error(&id.name, id.span, s));
4111            } else if cx.types.contains_key(&id.name) {
4112                cx.errors.push(
4113                    CompileError::new(
4114                        "bynk.resolve.type_in_expr",
4115                        id.span,
4116                        format!("`{}` is a type, not a value", id.name),
4117                    )
4118                    .with_note(
4119                        "types cannot appear in expression position; \
4120                         use `TypeName.of(value)` or `TypeName { ... }` to construct values",
4121                    ),
4122                );
4123            } else if cx.fns.contains_key(&id.name) {
4124                // v0.20a: a bare named-function reference may be a function
4125                // VALUE where a function type is expected. The resolver has
4126                // no type information, so the judgment (and the
4127                // `bynk.resolve.fn_without_call` diagnostic for non-function
4128                // positions) now lives in the checker's ident rule. Silent
4129                // pass here keeps `unknown_name` from misfiring.
4130                cx.errors.refs.record(id.span, SymbolKind::Fn, &id.name);
4131            } else if cx.assets.contains_key(&id.name) {
4132                // #1883, slice 1a: an asset name is a value of type `Asset`;
4133                // the checker types it (`check_ident`).
4134            } else if cx.embeds.contains_key(&id.name) {
4135                // #2387, slice 1: an embed name is a `String` value; the
4136                // checker types it (`check_ident`).
4137            } else if find_ambiguous_variant_owners(&id.name, cx).len() > 1 {
4138                // #3344: a name several sums declare is settled by the
4139                // expected type, which only the checker knows; it reports
4140                // `bynk.resolve.ambiguous_variant` when nothing picks one.
4141                // Every position this walk covers is also typed by the
4142                // checker (`fn`/method bodies, constants, field defaults),
4143                // as are the handler, agent and test bodies it never walks.
4144            } else if cx.declared_caps.contains(&id.name) {
4145                cx.errors.push(
4146                    CompileError::new(
4147                        "bynk.given.undeclared_capability",
4148                        id.span,
4149                        format!(
4150                            "capability `{}` is used but not listed in the function's `given` clause",
4151                            id.name
4152                        ),
4153                    )
4154                    .with_note(cx.cap_advice.replace("{cap}", &id.name)),
4155                );
4156            } else {
4157                cx.errors.push(
4158                    CompileError::new(
4159                        "bynk.resolve.unknown_name",
4160                        id.span,
4161                        format!("unknown name `{}`", id.name),
4162                    )
4163                    .with_note(
4164                        "only parameters, `let` bindings, and functions declared \
4165                         in this commons are in scope",
4166                    ),
4167                );
4168            }
4169        }
4170        ExprKind::Call {
4171            name,
4172            type_args,
4173            args,
4174            ..
4175        } => {
4176            // #712: explicit type arguments (`identity[T](…)`) are type
4177            // references and must resolve — the checker's `check_generic_call`
4178            // otherwise dropped an unknown one silently. Validated here so
4179            // `fn`/method bodies are covered; the checker backstops handler
4180            // bodies (which never reach this walk).
4181            for ta in type_args {
4182                check_type_ref_resolves_in(ta, cx.types, cx.type_params, cx.errors);
4183            }
4184            match cx.fns.get(&name.name) {
4185                Some(decl) => {
4186                    cx.errors.refs.record(name.span, SymbolKind::Fn, &name.name);
4187                    if decl.params.len() != args.len() {
4188                        cx.errors.push(
4189                            CompileError::new(
4190                                "bynk.resolve.arity_mismatch",
4191                                name.span,
4192                                format!(
4193                                    "function `{}` expects {} argument(s), but {} were given",
4194                                    name.name,
4195                                    decl.params.len(),
4196                                    args.len()
4197                                ),
4198                            )
4199                            // Finding #46: `decl` is looked up in the
4200                            // combined cross-file symbol table, so its span
4201                            // may belong to a different file than this call
4202                            // — see the same note at the type-arity checks
4203                            // above.
4204                            .with_note("function declared here"),
4205                        );
4206                    }
4207                }
4208                None => {
4209                    // Maybe it's a variant constructor with a payload (e.g., `Placed(at, total)`).
4210                    let owners = find_ambiguous_variant_owners(&name.name, cx);
4211                    if http_variant(&name.name).is_some() {
4212                        // v0.9: predeclared HttpResult variant constructor.
4213                    } else if owners.len() == 1 {
4214                        // Single owner — treat as variant construction. Type
4215                        // checker validates arg count and types.
4216                    } else if owners.len() > 1 {
4217                        // #3344: the checker picks the owner from the
4218                        // expected type, or reports the ambiguity.
4219                    } else if let Some(s) = cx.shadowed.get(&name.name) {
4220                        // #1925: no local function answers the call (one would
4221                        // have matched above), and the local declaration of
4222                        // another kind hides the import.
4223                        cx.errors
4224                            .push(shadowed_import_error(&name.name, name.span, s));
4225                    } else if cx.types.contains_key(&name.name) {
4226                        cx.errors.push(CompileError::new(
4227                            "bynk.resolve.type_as_function",
4228                            name.span,
4229                            format!(
4230                                "`{}` is a type, not a function — use `{}.of(value)` or `{} {{ ... }}` instead",
4231                                name.name, name.name, name.name
4232                            ),
4233                        ));
4234                    } else if crate::builtin_names::faults::kind_of(&name.name).is_some() {
4235                        // #2620: the ambient `unreachable`/`todo` built-ins; the
4236                        // checker validates the call.
4237                    } else if name_in_scope(&name.name, cx.params, &cx.scopes) {
4238                        // v0.20a: an in-scope value being called may be a
4239                        // legal value application if its type is a function
4240                        // type. The resolver has no type information, so the
4241                        // judgment (and `bynk.resolve.param_as_function` for
4242                        // non-function-typed values) lives in the checker's
4243                        // call dispatch. Silent pass.
4244                    } else {
4245                        cx.errors.push(
4246                            CompileError::new(
4247                                "bynk.resolve.unknown_function",
4248                                name.span,
4249                                format!("unknown function `{}`", name.name),
4250                            )
4251                            .with_note(unknown_function_note(&name.name)),
4252                        );
4253                    }
4254                }
4255            }
4256            for a in args {
4257                check_expr_references(a, cx);
4258            }
4259        }
4260        // #1654: the right operand of `&&`/`implies` is evaluated only when the
4261        // left holds, so the left's `is` bindings are in scope there.
4262        ExprKind::BinOp(BinOp::And | BinOp::Implies, lhs, rhs) => {
4263            check_expr_references(lhs, cx);
4264            let mut extra: HashMap<String, ()> = HashMap::new();
4265            collect_is_binding_names(lhs, true, &mut extra);
4266            cx.scopes.push(extra);
4267            check_expr_references(rhs, cx);
4268            cx.scopes.pop();
4269        }
4270        ExprKind::BinOp(_, lhs, rhs) => {
4271            check_expr_references(lhs, cx);
4272            check_expr_references(rhs, cx);
4273        }
4274        ExprKind::UnaryOp(_, e) => check_expr_references(e, cx),
4275        ExprKind::Paren(e) => check_expr_references(e, cx),
4276        ExprKind::Block(b) => check_block_references(b, cx),
4277        ExprKind::If {
4278            cond,
4279            then_block,
4280            else_block,
4281        } => {
4282            check_expr_references(cond, cx);
4283            // `is`-pattern bindings the condition proves flow into the
4284            // then-branch's scope (v0.2 §3.9), and those its *falsity* proves
4285            // into the else-branch's (#1654: `if !(o is Some(v)) { … } else
4286            // { v }`).
4287            let mut then_extra: HashMap<String, ()> = HashMap::new();
4288            collect_is_binding_names(cond, true, &mut then_extra);
4289            cx.scopes.push(then_extra);
4290            check_block_references(then_block, cx);
4291            cx.scopes.pop();
4292            let mut else_extra: HashMap<String, ()> = HashMap::new();
4293            collect_is_binding_names(cond, false, &mut else_extra);
4294            cx.scopes.push(else_extra);
4295            check_block_references(else_block, cx);
4296            cx.scopes.pop();
4297        }
4298        ExprKind::Ok(inner) | ExprKind::Err(inner) | ExprKind::Question(inner) => {
4299            check_expr_references(inner, cx);
4300        }
4301        ExprKind::Some(inner) => {
4302            check_expr_references(inner, cx);
4303        }
4304        ExprKind::RecordConstruction {
4305            type_name, fields, ..
4306        } => {
4307            match cx.types.get(&type_name.name) {
4308                Some(decl) => {
4309                    cx.errors
4310                        .refs
4311                        .record(type_name.span, SymbolKind::Type, &type_name.name);
4312                    match &decl.body {
4313                        TypeBody::Record(r) => {
4314                            // Field-set validation (missing / unknown / duplicate
4315                            // / shorthand-in-scope) is shared with the checker's
4316                            // `check_record_construction` so the two cannot
4317                            // re-diverge (#711). The value recursion below stays
4318                            // here — it is the resolver's reference walk.
4319                            check_record_field_set(
4320                                type_name,
4321                                fields,
4322                                r,
4323                                expr.span,
4324                                |n| name_in_scope(n, cx.params, &cx.scopes),
4325                                cx.errors.errs,
4326                            );
4327                            for f in fields {
4328                                if let Some(v) = &f.value {
4329                                    check_expr_references(v, cx);
4330                                }
4331                            }
4332                        }
4333                        TypeBody::Opaque { .. } => {
4334                            cx.errors.push(
4335                            CompileError::new(
4336                                "bynk.resolve.opaque_record_construction",
4337                                type_name.span,
4338                                format!(
4339                                    "opaque type `{}` cannot be constructed with record-literal syntax",
4340                                    type_name.name
4341                                ),
4342                            )
4343                            // Finding #46: cross-file table lookup — see resolver.rs:1029.
4344                            .with_note("type declared here")
4345                            .with_note(
4346                                "construct opaque values via `T.of(value)` (validated) or `T.unsafe(value)` (inside the defining commons)",
4347                            ),
4348                        );
4349                        }
4350                        _ => {
4351                            cx.errors.push(
4352                            CompileError::new(
4353                                "bynk.resolve.not_a_record_type",
4354                                type_name.span,
4355                                format!(
4356                                    "`{}` is not a record type — only record types can be constructed with `{{ ... }}`",
4357                                    type_name.name
4358                                ),
4359                            )
4360                            // Finding #46: cross-file table lookup — see resolver.rs:1029.
4361                            .with_note("type declared here"),
4362                        );
4363                        }
4364                    }
4365                }
4366                None => cx.errors.push(unknown_type_error(type_name)),
4367            }
4368        }
4369        ExprKind::FieldAccess { receiver, field } => {
4370            // v0.9: `HttpResult.Variant` qualified nullary variant.
4371            if let ExprKind::Ident(id) = &receiver.kind
4372                && !name_in_scope(&id.name, cx.params, &cx.scopes)
4373                && id.name == "HttpResult"
4374            {
4375                if http_variant(&field.name).is_none() {
4376                    cx.errors.push(CompileError::new(
4377                        "bynk.resolve.unknown_static_member",
4378                        field.span,
4379                        format!("`HttpResult` has no variant named `{}`", field.name),
4380                    ));
4381                }
4382                return;
4383            }
4384            // #2341 (L4): `ErrorStatus.Forbidden` — a `RawError` status, qualified.
4385            // The checker admits it only as `RawError`'s first argument.
4386            if let ExprKind::Ident(id) = &receiver.kind
4387                && !name_in_scope(&id.name, cx.params, &cx.scopes)
4388                && id.name == "ErrorStatus"
4389                && !cx.types.contains_key(&id.name)
4390            {
4391                if bynk_syntax::ast::error_status(&field.name).is_none() {
4392                    cx.errors.push(CompileError::new(
4393                        "bynk.resolve.unknown_static_member",
4394                        field.span,
4395                        format!(
4396                            "`ErrorStatus` has no status named `{}` — the error statuses are the 4xx and 5xx `HttpResult` variants",
4397                            field.name
4398                        ),
4399                    ));
4400                }
4401                return;
4402            }
4403            // #2622: `RoundingMode.HalfEven` — a `Decimal` `round`/`div` mode,
4404            // qualified. The checker admits it only as that argument.
4405            if let ExprKind::Ident(id) = &receiver.kind
4406                && !name_in_scope(&id.name, cx.params, &cx.scopes)
4407                && id.name == "RoundingMode"
4408                && !cx.types.contains_key(&id.name)
4409            {
4410                if bynk_syntax::ast::RoundingMode::from_name(&field.name).is_none() {
4411                    cx.errors.push(CompileError::new(
4412                        "bynk.resolve.unknown_static_member",
4413                        field.span,
4414                        format!(
4415                            "`RoundingMode` has no mode named `{}` — the modes are {}",
4416                            field.name,
4417                            bynk_syntax::ast::RoundingMode::ALL
4418                                .iter()
4419                                .map(|m| format!("`{}`", m.name()))
4420                                .collect::<Vec<_>>()
4421                                .join(", ")
4422                        ),
4423                    ));
4424                }
4425                return;
4426            }
4427            // `TypeName.Variant` — qualified nullary variant reference.
4428            // #1927: not for a local asset that hides an imported type of its
4429            // name: `logo.url` reads the asset, as the emitted module does.
4430            if let ExprKind::Ident(id) = &receiver.kind
4431                && !name_in_scope(&id.name, cx.params, &cx.scopes)
4432                && !matches!(cx.shadowed.get(&id.name), Some(s) if s.imported == "type" && s.local == "asset")
4433                && let Some(decl) = cx.types.get(&id.name)
4434            {
4435                cx.errors.refs.record(id.span, SymbolKind::Type, &id.name);
4436                let known_variant = match &decl.body {
4437                    TypeBody::Sum(s) => s.variants.iter().any(|v| v.name.name == field.name),
4438                    _ => false,
4439                };
4440                if !known_variant {
4441                    cx.errors.push(
4442                        CompileError::new(
4443                            "bynk.resolve.unknown_static_member",
4444                            field.span,
4445                            format!(
4446                                "type `{}` has no static method or variant named `{}`",
4447                                id.name, field.name
4448                            ),
4449                        )
4450                        // Finding #46: cross-file table lookup — see resolver.rs:1029.
4451                        .with_note("type declared here"),
4452                    );
4453                }
4454            } else {
4455                check_expr_references(receiver, cx);
4456            }
4457        }
4458        ExprKind::MethodCall {
4459            receiver,
4460            method,
4461            args,
4462            ..
4463        } => {
4464            // #2881: `B.Cap.op(…)` on a consumed context's capability that this
4465            // function's `given` lists; the checker resolves the chain.
4466            if given_cap_chain(receiver, cx.given, &|n| {
4467                name_in_scope(n, cx.params, &cx.scopes)
4468            }) {
4469                for a in args {
4470                    check_expr_references(a, cx);
4471                }
4472                return;
4473            }
4474            if refuse_peek_in_fn(receiver, method, cx) {
4475                return;
4476            }
4477            if check_http_result_call(receiver, method, args, cx) {
4478                return;
4479            }
4480            // v0.20b: `List.empty()` / `Map.empty()` — qualified statics on
4481            // the built-in collection types (no user declaration to resolve
4482            // against; the checker owns their typing). v0.22a adds the
4483            // numeric parse statics, `Int.parse(…)` / `Float.parse(…)`.
4484            if let ExprKind::Ident(id) = &receiver.kind
4485                && !name_in_scope(&id.name, cx.params, &cx.scopes)
4486                && matches!(
4487                    id.name.as_str(),
4488                    "List"
4489                        | "Map"
4490                        | "Set"
4491                        | "Int"
4492                        | "Float"
4493                        | "Json"
4494                        | "Yaml"
4495                        | "Form"
4496                        | "Duration"
4497                        | "Instant"
4498                        | "Stream"
4499                        | "Bytes"
4500                        | "Decimal"
4501                        | "RequestHeaders"
4502                        | "RequestQuery"
4503                        | "RequestCookies"
4504                        | "TokenClaims"
4505                )
4506                && !cx.types.contains_key(&id.name)
4507            {
4508                let allowed: &[&str] = match id.name.as_str() {
4509                    "List" => &["empty"],
4510                    // K6a (#2596): `Set.empty()` and `Set.of(xs)`; #3961: `Map.of(entries)`.
4511                    "Map" | "Set" => &["empty", "of"],
4512                    // P4c (#2628): `decodeSql`, `decode` with SQLite's `0`/`1` flags.
4513                    "Json" => &["encode", "encodePlain", "decode", "decodeSql"],
4514                    // #3214: decode only; there is no `Yaml.encode`.
4515                    "Yaml" => &["decode"],
4516                    // #3276: the form codec.
4517                    "Form" => &["decode", "encode"],
4518                    // v0.86 (ADR 0112): `Duration.millis(n)`.
4519                    "Duration" => &["millis"],
4520                    // v0.90 (ADR 0114): `Instant.fromEpochMillis(n)`; K3
4521                    // (#2592): `Instant.fromIso(s)`.
4522                    "Instant" => &["fromEpochMillis", "fromIso"],
4523                    // v0.100: `Stream.of(xs)`.
4524                    "Stream" => &["of"],
4525                    // v0.110 (ADR 0142): `Bytes.fromUtf8(s)`/`fromBase64(s)`/`empty()`;
4526                    // #2016: `fromHex(s)`/`fromBase64Url(s)`.
4527                    "Bytes" => &[
4528                        "fromUtf8",
4529                        "fromBase64",
4530                        "fromHex",
4531                        "fromBase64Url",
4532                        "empty",
4533                    ],
4534                    // #2622: `Decimal.parse(s)` and `Decimal.fromInt(n)`.
4535                    "Decimal" => &["parse", "fromInt"],
4536                    // #2341 (L4): the test-side constructors.
4537                    "RequestHeaders" => &["of", "empty"],
4538                    "RequestQuery" => &["of", "empty"],
4539                    "RequestCookies" => &["of", "empty"],
4540                    // #2380 (L5): the test-side constructor.
4541                    "TokenClaims" => &["of"],
4542                    // K6b (#2598): the two constants beside `parse`.
4543                    "Float" => &["parse", "pi", "e"],
4544                    _ => &["parse"],
4545                };
4546                let only = allowed.join("`/`");
4547                if !allowed.contains(&method.name.as_str()) {
4548                    cx.errors.push(CompileError::new(
4549                        "bynk.resolve.unknown_static_member",
4550                        method.span,
4551                        format!(
4552                            "the built-in `{}` type has no static method named `{}` — the statics are `{only}`",
4553                            id.name, method.name
4554                        ),
4555                    ));
4556                }
4557                for a in args {
4558                    check_expr_references(a, cx);
4559                }
4560                return;
4561            }
4562            // If the receiver is a bare ident of a declared type (and not a
4563            // local binding), this is a static call: `T.method(args)`.
4564            // Validate the type/method/variant resolution here. Otherwise
4565            // recurse into the receiver as a value expression.
4566            if let ExprKind::Ident(id) = &receiver.kind
4567                && !name_in_scope(&id.name, cx.params, &cx.scopes)
4568                && let Some(decl) = cx.types.get(&id.name)
4569            {
4570                cx.errors.refs.record(id.span, SymbolKind::Type, &id.name);
4571                let table = cx.methods.get(&id.name).cloned().unwrap_or_default();
4572                let is_static_method = table.statics.contains_key(&method.name);
4573                let is_of_constructor = method.name == "of"
4574                    && matches!(
4575                        decl.body,
4576                        TypeBody::Refined { .. } | TypeBody::Opaque { .. }
4577                    );
4578                let is_unsafe_constructor =
4579                    method.name == "unsafe" && matches!(decl.body, TypeBody::Opaque { .. });
4580                let is_variant = match &decl.body {
4581                    TypeBody::Sum(s) => s.variants.iter().any(|v| v.name.name == method.name),
4582                    _ => false,
4583                };
4584                if !(is_static_method || is_of_constructor || is_unsafe_constructor || is_variant) {
4585                    cx.errors.push(
4586                        CompileError::new(
4587                            "bynk.resolve.unknown_static_member",
4588                            method.span,
4589                            format!(
4590                                "type `{}` has no static method or variant named `{}`",
4591                                id.name, method.name
4592                            ),
4593                        )
4594                        // Finding #46: cross-file table lookup — see resolver.rs:1029.
4595                        .with_note("type declared here"),
4596                    );
4597                }
4598            } else {
4599                check_expr_references(receiver, cx);
4600            }
4601            for a in args {
4602                check_expr_references(a, cx);
4603            }
4604        }
4605        ExprKind::Match { discriminant, arms } => {
4606            check_expr_references(discriminant, cx);
4607            for arm in arms {
4608                // Pattern bindings introduce names in the arm body. The
4609                // type checker validates the pattern against the discriminant
4610                // type. Resolver pushes a scope with those binding names so
4611                // body references resolve.
4612                let mut arm_scope = HashMap::new();
4613                collect_pattern_bindings(&arm.pattern, &mut arm_scope);
4614                cx.scopes.push(arm_scope);
4615                // #1848: the guard, in the arm's pattern scope and before the
4616                // body, as the checker types it (ADR 0169). Its `is` bindings
4617                // stay in the guard; they do not flow into the body.
4618                if let Some(guard) = &arm.guard {
4619                    check_expr_references(guard, cx);
4620                }
4621                match &arm.body {
4622                    MatchBody::Expr(e) => check_expr_references(e, cx),
4623                    MatchBody::Block(b) => check_block_references(b, cx),
4624                }
4625                cx.scopes.pop();
4626            }
4627        }
4628        ExprKind::Is { value, pattern } => {
4629            check_expr_references(value, cx);
4630            // `is` pattern bindings flow through to the truthy branch of
4631            // an enclosing context; binding scope is handled by the type
4632            // checker. Resolver doesn't introduce anything here.
4633            let _ = pattern;
4634        }
4635    }
4636}
4637
4638/// The names introduced by the `is` tests `expr` proves matched when it
4639/// evaluates to `when_true` (v0.2 §3.9). Which tests those are is the shared
4640/// rule in [`crate::narrowing`] (#1654), the one the checker and emitter use.
4641fn collect_is_binding_names(expr: &Expr, when_true: bool, into: &mut HashMap<String, ()>) {
4642    for test in crate::narrowing::matched_is_tests(expr, when_true) {
4643        if let ExprKind::Is { pattern, .. } = &test.kind {
4644            collect_is_pattern_binding_names(pattern, into);
4645        }
4646    }
4647}
4648
4649/// The depth-1 names an `is` pattern introduces — a `Variant`'s own flat
4650/// bindings (`is` supports only flat, depth-1 name bindings, ADR 0169 keeps
4651/// nesting/guards match-only, matching `gather_pattern_bindings`), or — #474
4652/// — for an or-pattern, the first alternative's (Rule 2 guarantees every
4653/// alternative gives a shared name the same type, so any one alternative's
4654/// names are representative of them all).
4655fn collect_is_pattern_binding_names(pattern: &Pattern, into: &mut HashMap<String, ()>) {
4656    match pattern {
4657        Pattern::Variant { bindings, .. } => {
4658            for b in bindings {
4659                if let Pattern::Binding(name) = b.pattern() {
4660                    into.insert(name.name.clone(), ());
4661                }
4662            }
4663        }
4664        Pattern::Record { fields, .. } => {
4665            for (name, sub) in fields {
4666                match sub {
4667                    None => {
4668                        into.insert(name.name.clone(), ());
4669                    }
4670                    Some(Pattern::Binding(n)) => {
4671                        into.insert(n.name.clone(), ());
4672                    }
4673                    Some(_) => {}
4674                }
4675            }
4676        }
4677        // #2680: a list pattern's elements that are bare names, and its `..rest`.
4678        Pattern::List { elems, rest, .. } => {
4679            for e in elems {
4680                if let Pattern::Binding(n) = e {
4681                    into.insert(n.name.clone(), ());
4682                }
4683            }
4684            if let Some(b) = rest.as_ref().and_then(|r| r.binder.as_ref()) {
4685                into.insert(b.name.clone(), ());
4686            }
4687        }
4688        Pattern::Or(alts, _) => {
4689            if let Some(first) = alts.first() {
4690                collect_is_pattern_binding_names(first, into);
4691            }
4692        }
4693        _ => {}
4694    }
4695}
4696
4697/// Walk a pattern collecting the names it would bind, recursively through
4698/// nested payload patterns (ADR 0169) — `Some(Ok(x))` binds `x`.
4699fn collect_pattern_bindings(pattern: &Pattern, into: &mut HashMap<String, ()>) {
4700    for id in pattern.bound_names() {
4701        into.insert(id.name.clone(), ());
4702    }
4703}
4704
4705/// Find the unique sum type that owns a given variant name. Returns None
4706/// if no type owns it; ignores cases of multiple owners (those are
4707/// reported via `find_ambiguous_variant_owners`).
4708fn find_unique_variant_owner<'a>(name: &str, cx: &RefCheckCtx<'a, '_>) -> Option<&'a TypeDecl> {
4709    let owners = find_ambiguous_variant_owners(name, cx);
4710    if owners.len() == 1 {
4711        Some(owners[0])
4712    } else {
4713        None
4714    }
4715}
4716
4717fn find_ambiguous_variant_owners<'a>(name: &str, cx: &RefCheckCtx<'a, '_>) -> Vec<&'a TypeDecl> {
4718    bare_variant_owners(name, cx.types, cx.unselected)
4719        .into_iter()
4720        .map(|t| t.as_ref())
4721        .collect()
4722}
4723
4724/// The sums a bare variant name may mean (#3536). A sum a braced `consumes`
4725/// leaves out (`unselected`) is not a candidate beside the sums in scope, so a
4726/// user's own `Unavailable` is never ambiguous with a standard-library one it
4727/// did not ask for. It is the answer only when nothing in scope declares the
4728/// name: such a use resolves and is reported as `bynk.consumes.type_not_selected`.
4729pub(crate) fn bare_variant_owners<'a>(
4730    name: &str,
4731    types: &'a HashMap<String, Arc<TypeDecl>>,
4732    unselected: &HashSet<String>,
4733) -> Vec<&'a Arc<TypeDecl>> {
4734    let (mut in_scope, mut left_out) = (Vec::new(), Vec::new());
4735    for t in types.values() {
4736        if let TypeBody::Sum(s) = &t.body
4737            && s.variants.iter().any(|v| v.name.name == name)
4738        {
4739            if unselected.contains(&t.name.name) {
4740                left_out.push(t);
4741            } else {
4742                in_scope.push(t);
4743            }
4744        }
4745    }
4746    if in_scope.is_empty() {
4747        left_out
4748    } else {
4749        in_scope
4750    }
4751}
4752
4753/// #1848: a match-arm guard is resolved like every other expression, in its
4754/// arm's pattern scope.
4755#[cfg(test)]
4756mod guard_resolution_tests {
4757    use crate::testkit::analyse;
4758
4759    #[test]
4760    fn an_unknown_variant_in_a_guard_is_reported_by_the_resolver() {
4761        analyse(&[(
4762            "d.bynk",
4763            "commons d\n\ntype T = enum { A, B }\n\nfn g(n: Int, t: T) -> Int {\n  match n {\n    x if t == T.Zzz => 1\n    _ => 0\n  }\n}\n",
4764        )])
4765        .assert_reports("bynk.resolve.unknown_static_member");
4766    }
4767
4768    /// True before #1848 too (the checker records it). Pinned so resolving
4769    /// guards cannot drop or double the reference.
4770    #[test]
4771    fn a_function_named_only_in_a_guard_is_a_recorded_reference() {
4772        let a = analyse(&[(
4773            "d.bynk",
4774            "commons d\n\nfn big(n: Int) -> Bool { n > 9 }\n\nfn g(n: Int) -> Int {\n  match n {\n    x if big(x) => 1\n    _ => 0\n  }\n}\n",
4775        )]);
4776        a.assert_clean();
4777        let key = a.resolves_to("d.bynk", "big(x)");
4778        assert_eq!((key.unit.as_str(), key.name.as_str()), ("d", "big"));
4779    }
4780
4781    #[test]
4782    fn a_guard_reads_its_arm_s_pattern_bindings() {
4783        analyse(&[(
4784            "d.bynk",
4785            "commons d\n\nfn g(o: Option[Int]) -> Int {\n  match o {\n    Some(v) if v > 0 => v\n    _ => 0\n  }\n}\n",
4786        )])
4787        .assert_clean();
4788    }
4789}
4790
4791#[cfg(test)]
4792mod op_annotation_tests {
4793    use crate::testkit::analyse;
4794
4795    fn unit(name: &str, annotation: &str) -> String {
4796        format!(
4797            "context {name}\n\ncapability Store {{\n  fn load[T: Codable](id: String) -> Effect[Option[T]] {annotation}\n}}\n"
4798        )
4799    }
4800
4801    /// #3458: a first-party unit (under the reserved `bynk` root) may declare
4802    /// the reply policy, but only as `miss` or `fault`.
4803    #[test]
4804    fn a_first_party_operation_takes_only_a_reply_policy() {
4805        analyse(&[("a.bynk", &unit("bynk.t", "@onUndecodable(skip)"))])
4806            .assert_reports("bynk.generics.internal_op_annotation");
4807        analyse(&[("a.bynk", &unit("bynk.t", "@other(miss)"))])
4808            .assert_reports("bynk.generics.internal_op_annotation");
4809        analyse(&[("a.bynk", &unit("bynk.t", "@onUndecodable(by: miss)"))])
4810            .assert_reports("bynk.generics.internal_op_annotation");
4811    }
4812
4813    /// #3458: a typed read, a `Codable` parameter in the `Effect` payload, is a
4814    /// first-party operation's: it resolves cleanly there, and is refused in a
4815    /// user unit.
4816    #[test]
4817    fn a_typed_read_is_first_party_only() {
4818        let first_party = analyse(&[("a.bynk", &unit("bynk.t", "@onUndecodable(miss)"))]);
4819        for refused in [
4820            "bynk.generics.codable_op_return_not_first_party",
4821            "bynk.generics.internal_op_annotation",
4822        ] {
4823            assert!(
4824                !first_party.categories().contains(&refused),
4825                "a first-party typed read is accepted, got:\n{}",
4826                first_party.render()
4827            );
4828        }
4829        analyse(&[("a.bynk", &unit("shop", ""))])
4830            .assert_reports("bynk.generics.codable_op_return_not_first_party");
4831    }
4832
4833    /// A miss is `None`, so it needs an `Option` payload; a typed read returns an `Effect`.
4834    #[test]
4835    fn a_miss_needs_an_option_payload_and_a_typed_read_an_effect() {
4836        let src = "context bynk.t\n\ncapability Store {\n  fn load[T: Codable](id: String) -> Effect[T] @onUndecodable(miss)\n}\n";
4837        analyse(&[("a.bynk", src)]).assert_reports("bynk.generics.internal_op_annotation");
4838        let src = "context bynk.t\n\ncapability Store {\n  fn load[T: Codable](id: String) -> Option[T]\n}\n";
4839        analyse(&[("a.bynk", src)]).assert_reports("bynk.generics.internal_op_annotation");
4840    }
4841
4842    /// Two policies are refused, and each valid spelling resolves cleanly.
4843    #[test]
4844    fn a_policy_is_declared_once_and_valid_spellings_are_clean() {
4845        analyse(&[(
4846            "a.bynk",
4847            &unit("bynk.t", "@onUndecodable(miss) @onUndecodable(fault)"),
4848        )])
4849        .assert_reports("bynk.generics.internal_op_annotation");
4850        for ok in ["@onUndecodable(miss)", "@onUndecodable(fault)", ""] {
4851            let a = analyse(&[("a.bynk", &unit("bynk.t", ok))]);
4852            assert!(
4853                !a.categories()
4854                    .contains(&"bynk.generics.internal_op_annotation"),
4855                "{ok}: {}",
4856                a.render()
4857            );
4858        }
4859    }
4860
4861    /// The policy an operation declares: a fault by default, a miss or a fault when written.
4862    #[test]
4863    fn the_declared_policy_is_read_back() {
4864        use crate::checker::codable::{ReplyPolicy, op_reply_policy};
4865        let policy = |ann: &str| {
4866            let src = unit("bynk.t", ann);
4867            let toks = bynk_syntax::lexer::tokenize(&src).unwrap();
4868            let bynk_syntax::ast::SourceUnit::Context(c) =
4869                bynk_syntax::parser::parse_unit(&toks, &src).unwrap()
4870            else {
4871                panic!("a context")
4872            };
4873            let Some(bynk_syntax::ast::CommonsItem::Capability(cap)) = c.items.first() else {
4874                panic!("a capability")
4875            };
4876            op_reply_policy(&cap.ops[0])
4877        };
4878        assert_eq!(policy(""), ReplyPolicy::Fault);
4879        assert_eq!(policy("@onUndecodable(fault)"), ReplyPolicy::Fault);
4880        assert_eq!(policy("@onUndecodable(miss)"), ReplyPolicy::Miss);
4881        assert_eq!(policy("@onUndecodable(skip)"), ReplyPolicy::Fault);
4882    }
4883
4884    /// A policy on an operation that is not a typed read is refused: it would do nothing.
4885    #[test]
4886    fn a_policy_needs_a_typed_read() {
4887        let src = "context bynk.t\n\ncapability Store {\n  fn f() -> Effect[Option[String]] @onUndecodable(miss)\n}\n";
4888        analyse(&[("a.bynk", src)]).assert_reports("bynk.generics.internal_op_annotation");
4889    }
4890
4891    /// A user unit may not declare one at all.
4892    #[test]
4893    fn a_user_operation_takes_no_annotation() {
4894        analyse(&[("a.bynk", &unit("shop", "@onUndecodable(miss)"))])
4895            .assert_reports("bynk.generics.internal_op_annotation");
4896    }
4897}
4898
4899#[cfg(test)]
4900mod consumes_position_tests {
4901    use super::new_consumes_position;
4902
4903    fn insert(src: &str, last: Option<&str>, header: &str, braced: bool) -> Option<String> {
4904        let header_end = src.find(header).unwrap() + header.len();
4905        let last_end = last.map(|l| src.find(l).unwrap() + l.len());
4906        let (at, sep) = new_consumes_position(src, last_end, header_end, braced)?;
4907        Some(format!("{}{sep}X{}", &src[..at], &src[at..]))
4908    }
4909
4910    /// A headerless file takes the clause after its header, a blank line away.
4911    #[test]
4912    fn a_fragment_gets_a_blank_line_after_its_header() {
4913        let src = "context a\n\nfn f() -> Int { 1 }\n";
4914        assert_eq!(
4915            insert(src, None, "context a", false).unwrap(),
4916            "context a\n\nX\n\nfn f() -> Int { 1 }\n"
4917        );
4918    }
4919
4920    /// A braced file takes it after the `{`, indented like the first member.
4921    #[test]
4922    fn a_braced_file_takes_the_clause_after_the_brace_at_the_members_indent() {
4923        let src = "suite shop as unit {\n    case \"c\" {\n    }\n}\n";
4924        assert_eq!(
4925            insert(src, None, "as unit", true).unwrap(),
4926            "suite shop as unit {\n    X\n    case \"c\" {\n    }\n}\n"
4927        );
4928    }
4929
4930    /// Beside an existing clause, the new line takes the next line's indent.
4931    #[test]
4932    fn a_new_line_follows_the_last_clause_at_the_next_lines_indent() {
4933        let src = "suite s {\n  uses m\n  case \"c\" { }\n}\n";
4934        assert_eq!(
4935            insert(src, Some("uses m"), "suite s", true).unwrap(),
4936            "suite s {\n  uses m\n  X\n  case \"c\" { }\n}\n"
4937        );
4938    }
4939
4940    /// When the clause is the last line before `}`, that line is the brace, so
4941    /// the new line has no indent: only cosmetic, and the formatter repairs it.
4942    #[test]
4943    fn a_last_clause_before_the_closing_brace_gets_no_indent() {
4944        let src = "suite s {\n  uses m\n}\n";
4945        assert_eq!(
4946            insert(src, Some("uses m"), "suite s", true).unwrap(),
4947            "suite s {\n  uses m\nX\n}\n"
4948        );
4949    }
4950
4951    /// A braced file whose header is not followed by `{` has no safe place.
4952    #[test]
4953    fn a_header_not_followed_by_a_brace_gets_no_position() {
4954        let src = "suite s as unit\n\ncase \"c\" { }\n";
4955        assert!(insert(src, None, "as unit", true).is_none());
4956    }
4957}