Skip to main content

bynk_check/checker/
calls.rs

1//! Call / application dispatch.
2//!
3//! Split out of `checker.rs` (v0.29.10) verbatim; the parent module
4//! re-exports these via `use calls::*`.
5
6use super::codable::{check_op_codable_args, check_reply_codable, op_encoding};
7use super::*;
8
9/// v0.39 (ADR 0072): record a parameter-name inlay hint for one call argument,
10/// unless it would be noise — the `_`/`self` placeholders, or an argument that
11/// is already the identically-named identifier (`f(count)` for parameter
12/// `count`, matching rust-analyzer's suppression).
13fn record_param_hint(hints: &mut HintSink, param_name: &str, arg: &Expr) {
14    if param_name == "_" || param_name == "self" {
15        return;
16    }
17    if let ExprKind::Ident(id) = &arg.kind
18        && id.name == param_name
19    {
20        return;
21    }
22    hints.record_param(arg.span, format!("{param_name}:"));
23}
24
25#[allow(clippy::too_many_arguments)]
26pub(crate) fn check_fn(
27    f: &FnDecl,
28    input: &ResolvedCommons,
29    expr_types: &mut HashMap<ExprId, TypedExpr>,
30    callees: &mut HashMap<ExprId, Callee>,
31    errors: &mut Vec<CompileError>,
32    refs: &mut RefSink,
33    hints: &mut HintSink,
34    locals: &mut LocalsSink,
35    requirements: &mut RequirementSink,
36    tys: &Types,
37) {
38    check_fn_in(
39        f,
40        false,
41        None,
42        input,
43        expr_types,
44        callees,
45        errors,
46        refs,
47        hints,
48        locals,
49        requirements,
50        tys,
51    );
52}
53
54/// #2868: the capability scope of a context function that declares `given`.
55pub struct FnCaps {
56    /// The function's own `given`, resolved, by deps key.
57    pub capabilities: HashMap<String, CapabilityInfo>,
58    /// Every capability the context declares, so a use outside `given` is
59    /// reported as undeclared rather than unknown.
60    pub declared_capabilities: HashMap<String, CapabilityInfo>,
61}
62
63/// #2868: check a context function that declares `given`, with its capabilities
64/// in scope.
65#[allow(clippy::too_many_arguments)]
66pub fn check_context_fn(
67    f: &FnDecl,
68    caps: FnCaps,
69    input: &ResolvedCommons,
70    expr_types: &mut HashMap<ExprId, TypedExpr>,
71    callees: &mut HashMap<ExprId, Callee>,
72    errors: &mut Vec<CompileError>,
73    refs: &mut RefSink,
74    hints: &mut HintSink,
75    locals: &mut LocalsSink,
76    requirements: &mut RequirementSink,
77    tys: &Types,
78) {
79    check_fn_in(
80        f,
81        false,
82        Some(caps),
83        input,
84        expr_types,
85        callees,
86        errors,
87        refs,
88        hints,
89        locals,
90        requirements,
91        tys,
92    );
93}
94
95/// #2834: check a suite-local helper `fn` against `input` (the suite's view,
96/// with its sibling helpers), admitting test-only values.
97#[allow(clippy::too_many_arguments)]
98pub fn check_suite_fn(
99    f: &FnDecl,
100    input: &ResolvedCommons,
101    expr_types: &mut HashMap<ExprId, TypedExpr>,
102    callees: &mut HashMap<ExprId, Callee>,
103    errors: &mut Vec<CompileError>,
104    refs: &mut RefSink,
105    hints: &mut HintSink,
106    locals: &mut LocalsSink,
107    requirements: &mut RequirementSink,
108    tys: &Types,
109) {
110    // #2868: a suite helper is no context function, so it cannot declare
111    // `given`; its cases get the target's capabilities instead.
112    if !f.given.is_empty() {
113        errors.extend(given_fn_refusal(f, false));
114        return;
115    }
116    check_fn_in(
117        f,
118        true,
119        None,
120        input,
121        expr_types,
122        callees,
123        errors,
124        refs,
125        hints,
126        locals,
127        requirements,
128        tys,
129    );
130}
131
132/// [`check_fn`], for a body that may use test-only values when `test_values`
133/// (a suite-local helper, #2834).
134#[allow(clippy::too_many_arguments)]
135pub(crate) fn check_fn_in(
136    f: &FnDecl,
137    test_values: bool,
138    // #2868: for a context function with `given`, the capabilities in scope
139    // (the declared ones, resolved) and every capability the context declares.
140    fn_caps: Option<FnCaps>,
141    input: &ResolvedCommons,
142    expr_types: &mut HashMap<ExprId, TypedExpr>,
143    callees: &mut HashMap<ExprId, Callee>,
144    errors: &mut Vec<CompileError>,
145    refs: &mut RefSink,
146    hints: &mut HintSink,
147    locals: &mut LocalsSink,
148    requirements: &mut RequirementSink,
149    tys: &Types,
150) {
151    // v0.20a: the fn's type parameters are *rigid* type variables while
152    // checking its own body. A type param shadowing a declared type is
153    // confusing — diagnose the collision.
154    let mut vars: HashSet<String> = f
155        .type_params
156        .iter()
157        .map(|tp| tp.name.name.clone())
158        .collect();
159    for tp in &f.type_params {
160        if input.types.contains_key(&tp.name.name) {
161            errors.push(
162                CompileError::new(
163                    "bynk.generics.type_arg_mismatch",
164                    tp.span,
165                    format!(
166                        "type parameter `{}` shadows the declared type of the same name",
167                        tp.name.name
168                    ),
169                )
170                .with_note("rename the type parameter"),
171            );
172        }
173    }
174    // #594: an instance method on a generic type inherits the receiver type's
175    // parameters as additional rigid vars, so its signature and body may name
176    // them (`self: Box[A]`, `f: A -> U`). The receiver's parameters are the
177    // type's own — they never shadow a declared type — so they bypass the guard
178    // above.
179    if let FnName::Method { type_name, .. } = &f.name
180        && let Some(decl) = input.types.get(&type_name.name)
181    {
182        for tp in &decl.type_params {
183            vars.insert(tp.name.name.clone());
184        }
185    }
186    let return_ty = match resolve_type_ref_in(&f.return_type, &input.types, &vars, tys) {
187        Some(t) => t,
188        None => return,
189    };
190    record_type_refs(&f.return_type, &input.types, &vars, refs);
191    let mut param_scope: HashMap<String, TyId> = HashMap::new();
192    // For methods, the implicit `self` parameter has the attached type. #594: on
193    // a generic receiver, `self` is the type applied to its own parameters as
194    // rigid vars (`Box[A]`), so field access substitutes them and the body's
195    // uses of `A` line up with the signature.
196    if let FnName::Method { type_name, .. } = &f.name
197        && f.has_self
198        && let Some(decl) = input.types.get(&type_name.name)
199    {
200        let self_args = decl
201            .type_params
202            .iter()
203            .map(|tp| tys.intern(Ty::Var(tp.name.name.clone())))
204            .collect();
205        param_scope.insert("self".to_string(), named_ty_with_args(decl, self_args, tys));
206    }
207    for p in &f.params {
208        if let Some(ty) = resolve_type_ref_in(&p.type_ref, &input.types, &vars, tys) {
209            record_type_refs(&p.type_ref, &input.types, &vars, refs);
210            // v0.31: a fn parameter is in scope over the whole body.
211            if p.name.name != "_" {
212                locals.record(
213                    p.name.name.clone(),
214                    p.name.span,
215                    crate::locals::LocalKind::Param,
216                    ty.display(tys),
217                    f.body.span,
218                );
219            }
220            param_scope.insert(p.name.name.clone(), ty);
221        }
222    }
223    let eq = EqScope::for_fn(f, input);
224    // Slice 2 (DECISION F): a type parameter in a `Map` key or `Set` element of
225    // the signature is declared `Key`.
226    if !vars.is_empty() {
227        super::keying::require_key_positions(
228            tys,
229            &vars,
230            &eq,
231            errors,
232            return_ty,
233            f.return_type.span(),
234        );
235        for p in &f.params {
236            if let Some(ty) = param_scope.get(&p.name.name).copied() {
237                super::keying::require_key_positions(
238                    tys,
239                    &vars,
240                    &eq,
241                    errors,
242                    ty,
243                    p.type_ref.span(),
244                );
245            }
246        }
247    }
248    // v0.115: check the function's contract clauses (`requires`/`ensures`) in
249    // the parameter scope before the body — a contract is the invariant
250    // predicate attached to a function (ADR 0144). `result` in an `ensures` is
251    // the return value, awaited for an `Effect`.
252    if !f.requires.is_empty() || !f.ensures.is_empty() {
253        let result_ty = match &*tys.get(return_ty) {
254            Ty::Effect(inner) => *inner,
255            _ => return_ty,
256        };
257        let has_result_param = f.params.iter().any(|p| p.name.name == "result");
258        let fn_label = format!("function `{}`", f.name.display());
259        check_contracts(
260            &f.requires,
261            &f.ensures,
262            &param_scope,
263            result_ty,
264            has_result_param,
265            &fn_label,
266            input,
267            expr_types,
268            errors,
269            refs,
270            hints,
271            locals,
272            requirements,
273            callees,
274            &vars,
275            &eq,
276            tys,
277        );
278    }
279    let effectful = return_ty.is_effect(tys);
280    let mut ctx = Ctx {
281        input,
282        tys,
283        expr_types,
284        errors,
285        refs,
286        hints,
287        locals,
288        requirements,
289        callees,
290        scopes: vec![param_scope],
291        list_lens: HashMap::new(),
292        row_links: HashMap::new(),
293        is_binding_cache: HashMap::new(),
294        admitted_literals: HashMap::new(),
295        pattern_binding_types: HashMap::new(),
296        let_else_removals: HashMap::new(),
297        store_writing_lambdas: HashMap::new(),
298        question_let_binders: HashMap::new(),
299        return_ty,
300        return_ty_span: f.return_type.span(),
301        effectful,
302        agent_state_ty: None,
303        commit_seen: false,
304        caps: match fn_caps {
305            Some(c) => {
306                let given_entries: Vec<(String, Span)> = f
307                    .given
308                    .iter()
309                    .map(|g| (g.key().to_string(), g.span))
310                    .collect();
311                CapabilityCtx {
312                    capabilities: c.capabilities,
313                    declared_capabilities: c.declared_capabilities,
314                    given_remaining: given_entries.iter().map(|(k, _)| k.clone()).collect(),
315                    given_used: HashSet::new(),
316                    given_entries,
317                    given_anchor: Some(f.return_type.span()),
318                    ..Default::default()
319                }
320            }
321            // #2868: a plain effectful function in a context has no `given`, but
322            // a call to one that does is fixed by adding it, after the return type.
323            None => CapabilityCtx {
324                given_anchor: (input.is_context
325                    && !test_values
326                    && matches!(f.name, FnName::Free(_))
327                    && effectful)
328                    .then(|| f.return_type.span()),
329                ..CapabilityCtx::default()
330            },
331        },
332        in_test_body: false,
333        oidc_binder: None,
334        test_services: HashMap::new(),
335        test_actors: HashMap::new(),
336        type_vars: vars.clone(),
337        eq: eq.clone(),
338        last_witness: None,
339        store_fields: HashMap::new(),
340        in_agent_handler: false,
341        in_service_handler: false,
342        in_fn_body: true,
343        test_values,
344    };
345    let Some(body_ty) = type_of_block(&f.body, Some(return_ty), &mut ctx) else {
346        return;
347    };
348    // #718: run the held-resource linearity pass over `fn`/method bodies too, not
349    // just handlers. The caller side treats passing a held value into a function
350    // as a transfer (disposal), so the callee *owns* any held parameter and must
351    // dispose it (close, store, or transfer) before returning — otherwise a
352    // `swallow(c)` leaks and a double `c.close()` goes undiagnosed. No parameter
353    // is borrowed here (the borrowed case is a handler's firing connection), so
354    // the borrowed set is empty; every held param is seeded owned.
355    linearity::check(
356        &f.body,
357        &f.params,
358        &input.types,
359        ctx.expr_types,
360        &ctx.pattern_binding_types,
361        &HashSet::new(),
362        ctx.errors,
363        tys,
364    );
365    if !compatible(body_ty, return_ty, tys) {
366        let err = CompileError::new(
367            "bynk.types.return_mismatch",
368            f.body.tail.span,
369            format!(
370                "function body has type `{}`, but the declared return type is `{}`",
371                body_ty.display(tys),
372                return_ty.display(tys)
373            ),
374        )
375        .with_label(f.return_type.span(), "declared return type");
376        ctx.errors.push(with_of_hint(err, body_ty, return_ty, &ctx));
377    }
378    if !f.given.is_empty() {
379        let entries = ctx.caps.given_entries.clone();
380        report_unused_given(
381            &mut ctx,
382            &entries,
383            f.return_type.span(),
384            f.return_type.span(),
385        );
386    }
387}
388
389/// The shared discipline behind both `check_state_initialiser` (agent `store`
390/// fields) and `check_event_field_default` (Events slice 3a, #972, event
391/// record fields): the initialiser must be a *static* value of the field
392/// type — checked in an empty, pure scope (so `self`, parameters,
393/// capabilities, and effects are all out of reach) with the field type as
394/// the expected type, so refined literals admit (v0.9.4) and sum variants
395/// resolve. The init's expression types are recorded into `expr_types` for
396/// emission, and its `Callee` classification (a `.of`/`.unsafe`/variant-
397/// constructor call, at most) into `callees` (P6.7, #1163) — every
398/// `Callee`-driven reader of a call-shaped expression reads `program.callees`
399/// unconditionally (ADR 0334), so a call-shaped static initialiser with no
400/// entry there would panic on a certified program the checker legitimately
401/// accepted, not a recoverable state. (The IR-side `Cell`-init lowering that
402/// first motivated this was deleted by Slice D1 of #1542; the invariant
403/// outlives it because `bynk-emit`'s own emitter reads the same table.)
404/// `code`/`subject`
405/// name the caller's own diagnostic and the noun used in its message ("state
406/// field initialiser" / "event field default").
407#[allow(clippy::too_many_arguments)]
408fn check_static_initialiser(
409    init: &Expr,
410    field_type: &TypeRef,
411    input: &ResolvedCommons,
412    expr_types: &mut HashMap<ExprId, TypedExpr>,
413    callees: &mut HashMap<ExprId, Callee>,
414    errors: &mut Vec<CompileError>,
415    refs: &mut RefSink,
416    hints: &mut HintSink,
417    locals: &mut LocalsSink,
418    code: &'static str,
419    subject: &str,
420    tys: &Types,
421) {
422    let Some((field_ty, result, local_errors)) = type_static_initialiser(
423        init, field_type, input, expr_types, callees, refs, hints, locals, tys,
424    ) else {
425        return; // an unresolved field type is reported elsewhere
426    };
427    let compatible_result = matches!(&result, Some(t) if compatible(*t, field_ty, tys));
428    if !compatible_result || !local_errors.is_empty() {
429        // #2908: a variant of a `uses`-sourced commons sum is refused by
430        // design; report that refusal rather than "an invalid expression".
431        // Other typing diagnostics stay folded into the field-default code.
432        if local_errors
433            .iter()
434            .any(|e| e.category == "bynk.context.rebrand_construction")
435        {
436            errors.extend(
437                local_errors
438                    .into_iter()
439                    .filter(|e| e.category == "bynk.context.rebrand_construction"),
440            );
441            return;
442        }
443        let got = result
444            .map(|t| t.display(tys))
445            .unwrap_or_else(|| "an invalid expression".to_string());
446        errors.push(
447            CompileError::new(
448                code,
449                init.span,
450                format!(
451                    "{subject} must be a static value of type `{}` (got `{got}`)",
452                    field_ty.display(tys),
453                ),
454            )
455            .with_note(
456                "an initialiser is a compile-time value — a literal (including one admitted to a \
457                 refined type), a sum variant of a type this context may construct, \
458                 `Some`/`None`/`Ok`/`Err`, a record, or — for an opaque type — `T.unsafe(lit)` — \
459                 with no reference to `self`, parameters, or capabilities",
460            ),
461        );
462    }
463}
464
465/// The typing half of [`check_static_initialiser`]: `init` typed against
466/// `field_type` in an empty, pure scope, recording its expression types and
467/// callees. Returns the resolved field type, the initialiser's type and the
468/// diagnostics the typing raised (unreported), or `None` when `field_type`
469/// does not resolve.
470#[allow(clippy::too_many_arguments)]
471fn type_static_initialiser(
472    init: &Expr,
473    field_type: &TypeRef,
474    input: &ResolvedCommons,
475    expr_types: &mut HashMap<ExprId, TypedExpr>,
476    callees: &mut HashMap<ExprId, Callee>,
477    refs: &mut RefSink,
478    hints: &mut HintSink,
479    locals: &mut LocalsSink,
480    tys: &Types,
481) -> Option<(TyId, Option<TyId>, Vec<CompileError>)> {
482    let field_ty = resolve_type_ref(field_type, &input.types, tys)?;
483    let mut local_errors: Vec<CompileError> = Vec::new();
484    // A static initialiser is a pure value — no capability calls reach here —
485    // so requirements are discarded into a throwaway sink.
486    let mut init_requirements = RequirementSink::new();
487    let result = {
488        let mut ctx = Ctx {
489            input,
490            tys,
491            expr_types,
492            errors: &mut local_errors,
493            refs,
494            hints,
495            locals,
496            requirements: &mut init_requirements,
497            callees,
498            scopes: vec![HashMap::new()],
499            list_lens: HashMap::new(),
500            row_links: HashMap::new(),
501            is_binding_cache: HashMap::new(),
502            admitted_literals: HashMap::new(),
503            pattern_binding_types: HashMap::new(),
504            let_else_removals: HashMap::new(),
505            store_writing_lambdas: HashMap::new(),
506            question_let_binders: HashMap::new(),
507            return_ty: field_ty,
508            return_ty_span: init.span,
509            effectful: false,
510            agent_state_ty: None,
511            commit_seen: false,
512            caps: CapabilityCtx::default(),
513            in_test_body: false,
514            oidc_binder: None,
515            test_services: HashMap::new(),
516            test_actors: HashMap::new(),
517            type_vars: HashSet::new(),
518            eq: EqScope::default(),
519            last_witness: None,
520            store_fields: HashMap::new(),
521            in_agent_handler: false,
522            in_service_handler: false,
523            in_fn_body: false,
524            test_values: false,
525        };
526        type_of(init, Some(field_ty), &mut ctx)
527    };
528    Some((field_ty, result, local_errors))
529}
530
531/// #2617: check a `const` declaration declared in this file. Its name is
532/// upper-camel (`bynk.resolve.const_name_case`) and is no variant of a sum
533/// type in scope (`bynk.resolve.name_conflict`); its initialiser is inside the
534/// closed static set (`bynk.resolve.bad_const_initialiser`, decision A) and,
535/// typed against the annotation in an empty, pure scope (the
536/// `check_static_initialiser` discipline), a value of that type. A diagnostic
537/// the typing raises (a literal its refined type rejects, `.unsafe` outside the
538/// defining commons) is reported as it stands; a value of another type is
539/// `bynk.resolve.bad_const_initialiser`. The initialiser's expression types
540/// are recorded for the emitter.
541#[allow(clippy::too_many_arguments)]
542pub fn check_const_decl(
543    c: &ConstDecl,
544    input: &ResolvedCommons,
545    tys: &Types,
546    expr_types: &mut HashMap<ExprId, TypedExpr>,
547    callees: &mut HashMap<ExprId, Callee>,
548    errors: &mut Vec<CompileError>,
549    refs: &mut RefSink,
550    hints: &mut HintSink,
551    locals: &mut LocalsSink,
552) {
553    errors.extend(crate::consts::name_case_error(c));
554    errors.extend(crate::consts::variant_conflict_error(
555        c,
556        &input.types,
557        &input.unselected_types,
558    ));
559    if let Some(err) = crate::consts::static_error(c, &input.consts, &input.types) {
560        errors.push(err);
561        return;
562    }
563    let Some((field_ty, result, local_errors)) = type_static_initialiser(
564        &c.init, &c.ty, input, expr_types, callees, refs, hints, locals, tys,
565    ) else {
566        return; // an unresolved annotation is the resolver's to report
567    };
568    if !local_errors.is_empty() {
569        errors.extend(local_errors);
570        return;
571    }
572    let Some(got) = result else { return };
573    if !compatible(got, field_ty, tys) {
574        errors.push(
575            CompileError::new(
576                "bynk.resolve.bad_const_initialiser",
577                c.init.span,
578                format!(
579                    "constant `{}` is declared `{}`, but its initialiser is a `{}`",
580                    c.name.name,
581                    field_ty.display(tys),
582                    got.display(tys),
583                ),
584            )
585            .with_label(c.ty.span(), "declared type"),
586        );
587    }
588}
589
590/// v0.11: type-check an agent state-field initialiser (`field: T = init`).
591/// See `check_static_initialiser`. Pushes `bynk.agents.bad_state_initialiser`.
592#[allow(clippy::too_many_arguments)]
593pub fn check_state_initialiser(
594    init: &Expr,
595    field_type: &TypeRef,
596    input: &ResolvedCommons,
597    tys: &Types,
598    expr_types: &mut HashMap<ExprId, TypedExpr>,
599    callees: &mut HashMap<ExprId, Callee>,
600    errors: &mut Vec<CompileError>,
601    refs: &mut RefSink,
602    hints: &mut HintSink,
603    locals: &mut LocalsSink,
604) {
605    check_static_initialiser(
606        init,
607        field_type,
608        input,
609        expr_types,
610        callees,
611        errors,
612        refs,
613        hints,
614        locals,
615        "bynk.agents.bad_state_initialiser",
616        "state field initialiser",
617        tys,
618    );
619}
620
621/// Events slice 3a (#972): type-check an event field's default expression
622/// (`field: T = init`), reusing `check_static_initialiser`'s empty-pure-scope
623/// discipline. Pushes `bynk.types.bad_field_default`.
624///
625/// One admission `check_static_initialiser` doesn't cover on its own: an
626/// opaque type's `T.unsafe(lit)` is, by design (ADR 0182), a bypass of its
627/// own refinement — `type_of`'s ordinary static-call handling only
628/// checks `lit`'s *base* type, not the refinement, since that's the whole
629/// point of `unsafe`. An event field default is different: it becomes part
630/// of the wire codec (slice 3a lowers it to its *wire* JSON form and splices
631/// it into `deserialise_<Event>`, which validates a defaulted value exactly
632/// like a real one), so a default that bypasses its own refinement would
633/// compile cleanly and then fail at runtime the first time an old event
634/// actually triggers it — a deferred, surprising failure this check closes
635/// statically instead. Only `T.unsafe(lit)` on a *literal* argument is
636/// checked here (anything else already fails the static-value requirement
637/// above); a violated refinement pushes the same `bynk.types.bad_field_default`.
638#[allow(clippy::too_many_arguments)]
639pub fn check_event_field_default(
640    init: &Expr,
641    field_type: &TypeRef,
642    // #2607: what the default belongs to, for the message ("event field
643    // default", "record field default").
644    subject: &str,
645    input: &ResolvedCommons,
646    tys: &Types,
647    expr_types: &mut HashMap<ExprId, TypedExpr>,
648    callees: &mut HashMap<ExprId, Callee>,
649    errors: &mut Vec<CompileError>,
650    refs: &mut RefSink,
651    hints: &mut HintSink,
652    locals: &mut LocalsSink,
653) {
654    check_static_initialiser(
655        init,
656        field_type,
657        input,
658        expr_types,
659        callees,
660        errors,
661        refs,
662        hints,
663        locals,
664        "bynk.types.bad_field_default",
665        subject,
666        tys,
667    );
668    // `T.unsafe(lit)` parses as `ExprKind::MethodCall { receiver: Ident(T),
669    // method: "unsafe", .. }` — confirmed by direct AST inspection; the
670    // parser never distinguishes a type-qualified call from an ordinary
671    // instance method call (that's a resolver-time decision).
672    if let ExprKind::MethodCall {
673        receiver,
674        method,
675        args,
676        ..
677    } = &init.kind
678        && let ExprKind::Ident(type_name) = &receiver.kind
679        && method.name == "unsafe"
680        && let [lit_expr] = args.as_slice()
681        && let Some(decl) = input.types.get(&type_name.name)
682        && matches!(decl.body, TypeBody::Opaque { .. })
683        && let Some(refinement) = refinements::type_decl_refinement(decl)
684        && let Some(lit) = refinements::const_literal(lit_expr)
685        && let Some(failed) = refinements::first_failed_predicate(refinement, &lit)
686    {
687        errors.push(
688            CompileError::new(
689                "bynk.types.bad_field_default",
690                lit_expr.span,
691                format!(
692                    "`{}.unsafe(...)` bypasses its own refinement, but a {subject} \
693                     must be a value the wire could actually carry — this literal fails `{}`",
694                    type_name.name,
695                    failed.name(),
696                ),
697            )
698            .with_note(
699                "a default is spliced into the same codec that validates a real wire value on \
700                 receipt, so a refinement-violating `.unsafe(lit)` default would compile cleanly \
701                 and then fail at runtime the first time an old event actually triggers it",
702            ),
703        );
704    }
705}
706
707/// Standard-library S3 (#1963): refuse a use of the experimental first-party
708/// item `path` at `span` unless the project's `[unstable] allow` covers it.
709pub(super) fn refuse_experimental(path: &str, span: Span, ctx: &mut Ctx) {
710    if let Some(err) = ctx.input.stability.policy.check(path, span) {
711        ctx.errors.push(err);
712    }
713}
714
715/// S3 (#1963): a reference to an imported first-party name the project's policy
716/// blocks, called or passed as a value. The unit's blocked imports were decided where its provenance is
717/// known, so this holds in handler bodies too.
718pub(crate) fn refuse_experimental_import(name: &Ident, ctx: &mut Ctx) {
719    if let Some(path) = ctx.input.stability.blocked_imports.get(&name.name).cloned() {
720        refuse_experimental(&path, name.span, ctx);
721    }
722}
723
724/// The deprecated `bynk.list` free functions and the `List` method form each
725/// rewrites to. One table, read by the warning below and by the wasm
726/// `bynk_reference` catalogue so the two cannot drift. Since #3962 every
727/// function has a method form.
728pub const BYNK_LIST_DEPRECATED: &[(&str, &str)] = &[
729    ("reverse", "xs.reverse()"),
730    ("map", "xs.map(f)"),
731    ("filter", "xs.filter(p)"),
732    ("find", "xs.find(p)"),
733    ("any", "xs.any(p)"),
734    ("all", "xs.all(p)"),
735    ("traverse", "xs.traverse(f)"),
736    ("sort", "xs.sort()"),
737    ("min", "xs.min()"),
738    ("max", "xs.max()"),
739];
740
741/// v0.91 (ADR 0116 D6, completed by #3962): every `bynk.list` free function is
742/// **deprecated** in favour of the method-chain vocabulary. Emits a non-failing
743/// warning (ADR 0117) with a machine-applicable rewrite to the method form —
744/// `map(xs, f)` → `xs.map(f)`, `reverse(xs)` → `xs.reverse()`.
745fn warn_bynk_list_deprecation(name: &Ident, args: &[Expr], call_span: Span, ctx: &mut Ctx) {
746    let module = ctx.input.imported_from.get(&name.name).map(String::as_str);
747    // #3961: `bynk.map` and `bynk.set` are deprecated the same way.
748    if matches!(module, Some("bynk.map" | "bynk.set")) {
749        return super::collections::warn_deprecated_collection_fn(name, args, call_span, ctx);
750    }
751    if module != Some("bynk.list") {
752        return;
753    }
754    // The method-form spelling each free function rewrites to.
755    let Some(&(_, method_form)) = BYNK_LIST_DEPRECATED
756        .iter()
757        .find(|(f, _)| *f == name.name.as_str())
758    else {
759        return;
760    };
761    let mut err = CompileError::new(
762        "bynk.list.deprecated_function",
763        name.span,
764        format!(
765            "`bynk.list.{}` is deprecated — use the `List` method form `{method_form}`",
766            name.name
767        ),
768    )
769    .with_note(
770        "the `bynk.list.*` free functions are superseded by the method-chain vocabulary (ADR 0116); the method form reads left-to-right and chains",
771    );
772    // The auto-fix needs the (list) or (list, fn) shape — a wrong-arity call is
773    // reported elsewhere; only offer the rewrite when it is well-formed.
774    let keyless = matches!(name.name.as_str(), "reverse" | "sort" | "min" | "max");
775    let edits = match (keyless, args.len()) {
776        // delete `name(` — the receiver becomes the first argument.
777        (true, 1) => Some(vec![
778            (
779                Span::new(name.span.start, args[0].span.start),
780                String::new(),
781            ),
782            (
783                Span::new(args[0].span.end, call_span.end),
784                format!(".{}()", name.name),
785            ),
786        ]),
787        // the `, ` between the two args becomes `.<method>(`.
788        (false, 2) => Some(vec![
789            (
790                Span::new(name.span.start, args[0].span.start),
791                String::new(),
792            ),
793            (
794                Span::new(args[0].span.end, args[1].span.start),
795                format!(".{}(", name.name),
796            ),
797        ]),
798        _ => None,
799    };
800    if let Some(edits) = edits {
801        err = err.with_suggestion(
802            format!("rewrite to the `List` method form `{method_form}`"),
803            edits,
804            Applicability::MachineApplicable,
805        );
806    }
807    ctx.errors.push(err);
808}
809
810/// #2868: a call to (or reference to) a function that declares `given` is legal
811/// only where the caller has those capabilities itself. Checked at each call, so
812/// the rule is transitive without a graph walk: `f` calls `g`, so `f` declares
813/// `g`'s; a handler calls `f`, so it declares `f`'s. Recursion needs no special
814/// case. A test case supplies the capabilities its target's handlers would get.
815/// The capabilities the callee needs count as used by the caller.
816pub(crate) fn require_callee_given(name: &Ident, callee: &FnDecl, ctx: &mut Ctx) {
817    // #2881: a refused declaration (`given_fn_refusal`) is reported once, at
818    // the declaration; its callers cannot act on a missing `given`. A function
819    // this unit does not declare came in through `uses`, which only brings in a
820    // commons, so a `given` on it is always refused there.
821    if callee.given.is_empty() {
822        return;
823    }
824    if ctx.input.imported_fn_names.contains(&callee.name.display())
825        || given_fn_refusal(callee, ctx.input.is_context).is_some()
826    {
827        return;
828    }
829    let mut missing: Vec<String> = Vec::new();
830    for c in &callee.given {
831        let key = c.key().to_string();
832        // `given_remaining` holds every declared key, including a consumed
833        // context's (`given B.Cap`), which has no `capabilities` entry.
834        if ctx.caps.given_remaining.contains(&key) {
835            ctx.caps.given_used.insert(key);
836        } else if !missing.contains(&c.display_name()) {
837            missing.push(c.display_name());
838        }
839    }
840    if missing.is_empty() || ctx.in_test_body {
841        return;
842    }
843    let list = missing.join(", ");
844    let mut err = CompileError::new(
845        "bynk.given.missing_for_call",
846        name.span,
847        format!(
848            "`{}` needs `given {list}`, which the enclosing body does not declare",
849            name.name
850        ),
851    )
852    .with_label(
853        callee.name.ident().span,
854        format!(
855            "`{}` declares `given {}`",
856            name.name,
857            callee
858                .given
859                .iter()
860                .map(|c| c.display_name())
861                .collect::<Vec<_>>()
862                .join(", ")
863        ),
864    )
865    .with_note(if ctx.test_values {
866        // A suite helper is not a context function, so it cannot declare
867        // `given` to pass the capabilities on.
868        "a suite helper has no capabilities of its own to pass on: call it from a `case`, which gets the target's capabilities as its handlers do, or take the operation as a function parameter".to_string()
869    } else if ctx.caps.given_anchor.is_none() && ctx.caps.given_entries.is_empty() {
870        // A method, a pure function or a lambda in one cannot declare `given`.
871        "this body cannot declare `given`: take the operation as a function parameter, or call it from a handler or a context function that declares `given`".to_string()
872    } else {
873        format!(
874            "a capability never appears in a body without appearing in the signature of every handler and function on the path to it: add `{list}` to the caller's `given` clause"
875        )
876    });
877    if !ctx.test_values
878        && let Some((span, insert)) =
879            given_insertion_edit(&ctx.caps.given_entries, ctx.caps.given_anchor, &list)
880    {
881        err = err.with_suggestion(
882            format!("add `{list}` to the `given` clause"),
883            vec![(span, insert)],
884            Applicability::MachineApplicable,
885        );
886    }
887    ctx.errors.push(err);
888}
889
890pub(crate) fn check_call(
891    name: &Ident,
892    type_args: &[TypeRef],
893    args: &[Expr],
894    span: Span,
895    // #593: the binding's expected type grounds a generic variant constructor
896    // whose payload cannot determine every parameter (`let o: Opt[Int] = Nil`).
897    expected: Option<TyId>,
898    // P6.0 (#1139): the outer `Call` expression's own identity — keys the
899    // `Callee` classification recorded at whichever branch below dispatches.
900    expr_id: ExprId,
901    ctx: &mut Ctx,
902) -> Option<TyId> {
903    let tys = ctx.tys;
904    if let Some(fn_decl) = ctx.input.fns.get(&name.name) {
905        ctx.refs.record(name.span, SymbolKind::Fn, &name.name);
906        let fn_decl = Arc::clone(fn_decl);
907        ctx.callees
908            .insert(expr_id, Callee::Fn(Arc::clone(&fn_decl), Vec::new()));
909        warn_bynk_list_deprecation(name, args, span, ctx);
910        refuse_experimental_import(name, ctx);
911        require_callee_given(name, &fn_decl, ctx);
912        let ret = check_call_against_fn(name, &fn_decl, type_args, args, expected, ctx);
913        // Slice 1: the comparator witnesses the generic-call path resolved.
914        if let Some(witnesses) = ctx.last_witness.take() {
915            ctx.callees
916                .insert(expr_id, Callee::Fn(Arc::clone(&fn_decl), witnesses));
917        }
918        return ret;
919    }
920    // #3051: `TestConnection[F]()` — a case's recording handle for a websocket
921    // connection.
922    if name.name == "TestConnection" {
923        return check_test_connection_new(type_args, args, span, expr_id, ctx);
924    }
925    // v0.20a: explicit type arguments only apply to (generic) functions.
926    if !type_args.is_empty() {
927        ctx.errors.push(CompileError::new(
928            "bynk.generics.type_arg_mismatch",
929            span,
930            format!(
931                "`{}` is not a generic function — it takes no type arguments",
932                name.name
933            ),
934        ));
935        for a in args {
936            let _ = type_of(a, None, ctx);
937        }
938        return None;
939    }
940    // Could be a bare variant constructor with payload. Borrow the matching
941    // sum decls' own `Arc`s (a pointer bump each, no full-body clones); the
942    // ambiguity check below reuses the same list.
943    let owners: Vec<&Arc<TypeDecl>> = crate::resolver::bare_variant_owners(
944        &name.name,
945        &ctx.input.types,
946        &ctx.input.unselected_types,
947    );
948    // #3344: several sums in scope share the name; the expected type picks one.
949    let left_out = left_out_variant_owner(
950        &name.name,
951        &ctx.input.types,
952        &ctx.input.unselected_types,
953        expected,
954        tys,
955    );
956    if let Some(sum) = left_out.or_else(|| variant_owner(&owners, expected, tys)) {
957        ctx.callees.insert(
958            expr_id,
959            Callee::Ctor {
960                sum: Arc::clone(sum),
961                tag: name.name.clone(),
962            },
963        );
964        return check_variant_construction(sum, &name.name, args, span, expected, ctx);
965    }
966    // Agent instantiation: `AgentName(key)` constructs an instance keyed by
967    // `key`. The result type carries the agent's name so subsequent
968    // `agent_instance.method(args)` lookups can find the agent's handler set.
969    if let Some(agent) = ctx.input.agents.get(&name.name).cloned() {
970        ctx.refs.record(name.span, SymbolKind::Agent, &name.name);
971        ctx.callees
972            .insert(expr_id, Callee::AgentInit(name.name.clone()));
973        let key_ty = resolve_type_ref(&agent.key_type, &ctx.input.types, tys);
974        if args.len() != 1 {
975            let mut err = CompileError::new(
976                "bynk.agent.construction_arity",
977                span,
978                format!(
979                    "agent `{}` is constructed with one key argument, but {} were given",
980                    name.name,
981                    args.len()
982                ),
983            );
984            // #1925: the agent hides a `uses`-imported value of its name,
985            // which may be what the call meant.
986            if let Some(s) = ctx.input.shadowed_imports.get(&name.name) {
987                err = err.with_note(format!(
988                    "this unit's agent `{}` hides the {} of that name from `{}`; rename one to use the {}",
989                    name.name, s.imported, s.unit, s.imported
990                ));
991            }
992            ctx.errors.push(err);
993            for a in args {
994                let _ = type_of(a, None, ctx);
995            }
996            return None;
997        }
998        let arg_ty = type_of(&args[0], key_ty, ctx);
999        if let (Some(a), Some(k)) = (arg_ty, key_ty)
1000            && !compatible(a, k, tys)
1001        {
1002            ctx.errors.push(CompileError::new(
1003                "bynk.agent.key_mismatch",
1004                args[0].span,
1005                format!(
1006                    "agent `{}` key is `{}`, but a value of type `{}` was given",
1007                    name.name,
1008                    k.display(tys),
1009                    a.display(tys)
1010                ),
1011            ));
1012        }
1013        return Some(tys.intern(Ty::Named {
1014            name: name.name.clone(),
1015            kind: NamedKind::Record,
1016            args: Vec::new(),
1017        }));
1018    }
1019    // v0.20a: value application — calling a scope binding (param/local) of
1020    // function type. Placed AFTER fns/variants/agents: putting scope first
1021    // would change the meaning of currently-passing programs (the additive
1022    // guard); the resulting ident/call precedence asymmetry is pre-existing
1023    // and documented in §5.
1024    if let Some(ty) = ctx.lookup(&name.name) {
1025        return match &*tys.get(ty) {
1026            Ty::Fn { params, ret } => {
1027                ctx.callees
1028                    .insert(expr_id, Callee::Value(name.name.clone()));
1029                check_value_application(name, params, *ret, args, span, ctx)
1030            }
1031            _ => {
1032                // Relocated from the resolver (which has no type info): a
1033                // non-function-typed value called as a function.
1034                ctx.errors.push(
1035                    CompileError::new(
1036                        "bynk.resolve.param_as_function",
1037                        span,
1038                        format!(
1039                            "`{}` has type `{}` and is not callable",
1040                            name.name,
1041                            ty.display(tys)
1042                        ),
1043                    )
1044                    .with_note("only values of function type can be applied"),
1045                );
1046                for a in args {
1047                    let _ = type_of(a, None, ctx);
1048                }
1049                None
1050            }
1051        };
1052    }
1053    // #2620: the ambient fault built-ins. After every declaration and local
1054    // above, so a user `fn`/binding of the same name shadows them.
1055    if let Some(kind) = crate::builtin_names::faults::kind_of(&name.name) {
1056        return check_fault_call(name, kind, type_args, args, span, expr_id, ctx);
1057    }
1058    // Nothing owns the call. The resolver's reference walk reports these in
1059    // `fn`/method bodies, but handler/service/agent bodies and test bodies
1060    // never pass through that walk — the checker is their only backstop, and
1061    // a silent `None` here admitted any unknown call and emitted it verbatim.
1062    // Mirror the resolver's ladder. #1708: test bodies were exempt, for the
1063    // same since-repaired reason as `check_ident`'s twin gate; dropped with it.
1064    for a in args {
1065        let _ = type_of(a, None, ctx);
1066    }
1067    if owners.len() > 1 {
1068        ctx.errors.push(ambiguous_variant_error(
1069            &name.name, name.span, &owners, true,
1070        ));
1071        return None;
1072    }
1073    // #1925: no local function or agent answers the call, and a local
1074    // declaration of another kind hides the import.
1075    if let Some(err) = ctx.input.shadowed_import_error(&name.name, name.span) {
1076        ctx.errors.push(err);
1077        return None;
1078    }
1079    if ctx.input.types.contains_key(&name.name) {
1080        ctx.errors.push(CompileError::new(
1081            "bynk.resolve.type_as_function",
1082            span,
1083            format!(
1084                "`{}` is a type, not a function — use `{}.of(value)` or `{} {{ ... }}` instead",
1085                name.name, name.name, name.name
1086            ),
1087        ));
1088        return None;
1089    }
1090    ctx.errors.push(
1091        CompileError::new(
1092            "bynk.resolve.unknown_function",
1093            span,
1094            format!("unknown function `{}`", name.name),
1095        )
1096        .with_note(crate::resolver::unknown_function_note(&name.name)),
1097    );
1098    None
1099}
1100
1101/// #3051: `TestConnection[F]()`. Only a test body can name it (elsewhere the
1102/// resolver reports an unknown function, so a program has no way to make a
1103/// connection); `F` is the service's `out` frame type.
1104fn check_test_connection_new(
1105    type_args: &[TypeRef],
1106    args: &[Expr],
1107    span: Span,
1108    expr_id: ExprId,
1109    ctx: &mut Ctx,
1110) -> Option<TyId> {
1111    let tys = ctx.tys;
1112    for a in args {
1113        let _ = type_of(a, None, ctx);
1114    }
1115    if type_args.len() != 1 || !args.is_empty() {
1116        ctx.errors.push(CompileError::new(
1117            "bynk.generics.type_arg_mismatch",
1118            span,
1119            "`TestConnection[F]()` takes the service's `out` frame type as its one type argument and no value arguments",
1120        ));
1121        return None;
1122    }
1123    let frame = resolve_type_ref(&type_args[0], &ctx.input.types, tys)?;
1124    ctx.callees.insert(
1125        expr_id,
1126        Callee::intrinsic(StaticOp::TestConnection(TestConnectionStatic::New)),
1127    );
1128    Some(tys.intern(Ty::TestConnection(frame)))
1129}
1130
1131/// #2620 (DECISIONS A–F): `unreachable(message)` and `todo(message)` take one
1132/// `String` and have the bottom type, so they fit any position. `todo` also
1133/// raises the non-failing `bynk.fault.todo` warning so `--deny-warnings` can
1134/// refuse unfinished code.
1135fn check_fault_call(
1136    name: &Ident,
1137    kind: &'static str,
1138    type_args: &[TypeRef],
1139    args: &[Expr],
1140    span: Span,
1141    expr_id: ExprId,
1142    ctx: &mut Ctx,
1143) -> Option<TyId> {
1144    let tys = ctx.tys;
1145    ctx.callees.insert(expr_id, Callee::Fault { kind });
1146    if !type_args.is_empty() {
1147        ctx.errors.push(CompileError::new(
1148            "bynk.generics.type_arg_mismatch",
1149            span,
1150            format!(
1151                "`{}` is not a generic function — it takes no type arguments",
1152                name.name
1153            ),
1154        ));
1155    }
1156    if args.len() != 1 {
1157        ctx.errors.push(CompileError::new(
1158            "bynk.types.call_arity",
1159            span,
1160            format!(
1161                "`{}` takes 1 argument (a message), but {} were given",
1162                name.name,
1163                args.len()
1164            ),
1165        ));
1166        for a in args {
1167            let _ = type_of(a, None, ctx);
1168        }
1169    } else {
1170        let string = tys.intern(Ty::Base(BaseType::String));
1171        if let Some(a) = type_of(&args[0], Some(string), ctx)
1172            && !compatible(a, string, tys)
1173        {
1174            ctx.errors.push(CompileError::new(
1175                "bynk.types.argument_mismatch",
1176                args[0].span,
1177                format!(
1178                    "argument has type `{}`, but `{}` expects `String`",
1179                    a.display(tys),
1180                    name.name
1181                ),
1182            ));
1183        }
1184    }
1185    if name.name == crate::builtin_names::faults::TODO {
1186        ctx.errors.push(
1187            CompileError::new(
1188                "bynk.fault.todo",
1189                span,
1190                "`todo` marks unfinished code and faults when it runs",
1191            )
1192            .with_note("replace it with the implementation, or use `unreachable` for a case that cannot happen"),
1193        );
1194    }
1195    Some(tys.intern(Ty::Never))
1196}
1197
1198fn check_value_application(
1199    name: &Ident,
1200    params: &[TyId],
1201    ret: TyId,
1202    args: &[Expr],
1203    span: Span,
1204    ctx: &mut Ctx,
1205) -> Option<TyId> {
1206    let tys = ctx.tys;
1207    if ret.is_effect(tys) && !ctx.effectful {
1208        ctx.errors.push(
1209            CompileError::new(
1210                "bynk.effect.fn_value_in_pure_context",
1211                span,
1212                format!(
1213                    "`{}` is an effectful function (`{}`) and cannot be called in a pure context",
1214                    name.name,
1215                    Ty::Fn {
1216                        params: params.to_vec(),
1217                        ret,
1218                    }
1219                    .display(tys)
1220                ),
1221            )
1222            .with_note(
1223                "effectful function values may only be called where the enclosing body is effectful (its return type is an Effect)",
1224            ),
1225        );
1226    }
1227    if params.len() != args.len() {
1228        ctx.errors.push(CompileError::new(
1229            "bynk.types.call_arity",
1230            span,
1231            format!(
1232                "`{}` takes {} argument(s), but {} were given",
1233                name.name,
1234                params.len(),
1235                args.len()
1236            ),
1237        ));
1238        for a in args {
1239            let _ = type_of(a, None, ctx);
1240        }
1241        return None;
1242    }
1243    for (arg, param_ty) in args.iter().zip(params) {
1244        let arg_ty = type_of(arg, Some(*param_ty), ctx);
1245        if let Some(a) = arg_ty
1246            && !compatible(a, *param_ty, tys)
1247        {
1248            let err = CompileError::new(
1249                "bynk.types.argument_mismatch",
1250                arg.span,
1251                format!(
1252                    "argument has type `{}`, but `{}` expects `{}`",
1253                    a.display(tys),
1254                    name.name,
1255                    param_ty.display(tys)
1256                ),
1257            );
1258            ctx.errors.push(with_of_hint(err, a, *param_ty, ctx));
1259        }
1260    }
1261    Some(ret)
1262}
1263
1264/// Constrained generics slice 4 (DECISION C): the expected type as the last
1265/// resort for a generic call's type parameters. Runs after the non-lambda
1266/// argument pass and before the lambda pass, and only fills `names` that the
1267/// non-lambda arguments left undetermined. A program that compiled keeps its
1268/// types (both orders pick a compatible `T`); one whose `T` only a lambda's
1269/// return type would have fixed now grounds from the binding first. The declared return type is matched
1270/// structurally against `expected`; an `expected` that is still being inferred
1271/// (it mentions a flexible variable of an enclosing call) carries nothing and
1272/// is ignored. The call's result is still checked against `expected` by its
1273/// caller, so a mismatch is reported where it always was.
1274fn ground_from_expected(
1275    ret_pattern: TyId,
1276    expected: Option<TyId>,
1277    names: &[String],
1278    subst: &mut HashMap<String, TyId>,
1279    ctx: &Ctx,
1280) {
1281    let tys = ctx.tys;
1282    let Some(expected) = expected else {
1283        return;
1284    };
1285    if names.iter().all(|n| subst.contains_key(n))
1286        || matches!(&*tys.get(expected), Ty::Error | Ty::Never)
1287        || contains_flexible_var(expected, &ctx.type_vars, tys)
1288    {
1289        return;
1290    }
1291    let mut scratch: HashMap<String, TyId> = HashMap::new();
1292    if !unify(ret_pattern, expected, &mut scratch, tys) {
1293        return;
1294    }
1295    for n in names {
1296        if !subst.contains_key(n)
1297            && let Some(t) = scratch.get(n)
1298        {
1299            subst.insert(n.clone(), *t);
1300        }
1301    }
1302}
1303
1304/// v0.20a: instantiate and check a call to a generic function. Two-pass
1305/// argument-directed inference: pass 1 types every **non-lambda** argument
1306/// left-to-right against the (possibly still Var-bearing) expected — safe
1307/// because every expected-driven feature in `type_of` matches concrete
1308/// variants, so a Var falls through benignly (pinned by a unit test) — and
1309/// unifies; pass 2 types **lambda** arguments against the now-substituted
1310/// expecteds (a lambda whose expected params are still Var-bearing is
1311/// uninferable) and unifies the result, capturing return-position variables.
1312/// Conflicts demand exact equality (`bynk.generics.type_arg_mismatch`); the
1313/// explicit `name[T](…)` form builds the substitution directly.
1314fn check_generic_call(
1315    name: &Ident,
1316    fn_decl: &FnDecl,
1317    type_args: &[TypeRef],
1318    args: &[Expr],
1319    expected: Option<TyId>,
1320    ctx: &mut Ctx,
1321) -> Option<TyId> {
1322    let tys = ctx.tys;
1323    let vars: HashSet<String> = fn_decl
1324        .type_params
1325        .iter()
1326        .map(|tp| tp.name.name.clone())
1327        .collect();
1328    if fn_decl.params.len() != args.len() {
1329        // Same backstop as the non-generic path: the resolver only covers
1330        // `fn`/method bodies, so the checker must report for handler bodies.
1331        ctx.errors.push(
1332            CompileError::new(
1333                "bynk.resolve.arity_mismatch",
1334                name.span,
1335                format!(
1336                    "function `{}` expects {} argument(s), but {} were given",
1337                    name.name,
1338                    fn_decl.params.len(),
1339                    args.len()
1340                ),
1341            )
1342            .with_label(fn_decl.name.ident().span, "function declared here"),
1343        );
1344        for a in args {
1345            let _ = type_of(a, None, ctx);
1346        }
1347        return None;
1348    }
1349    let var_params: Vec<Option<TyId>> = fn_decl
1350        .params
1351        .iter()
1352        .map(|p| resolve_type_ref_in(&p.type_ref, &ctx.input.types, &vars, tys))
1353        .collect();
1354    let ret_pattern = resolve_type_ref_in(&fn_decl.return_type, &ctx.input.types, &vars, tys)?;
1355
1356    let mut subst: HashMap<String, TyId> = HashMap::new();
1357    if !type_args.is_empty() {
1358        if type_args.len() != fn_decl.type_params.len() {
1359            ctx.errors.push(CompileError::new(
1360                "bynk.generics.type_arg_mismatch",
1361                name.span,
1362                format!(
1363                    "`{}` takes {} type argument(s), but {} were given",
1364                    name.name,
1365                    fn_decl.type_params.len(),
1366                    type_args.len()
1367                ),
1368            ));
1369            return None;
1370        }
1371        for (tp, ta) in fn_decl.type_params.iter().zip(type_args) {
1372            // Resolve explicit type args with the *enclosing* fn's type
1373            // params in scope, so `identity[A](x)` inside a generic body
1374            // works. #712: report (not silently drop) an unknown type arg —
1375            // the resolver never validates `Call::type_args` (it destructures
1376            // `Call { name, args, .. }`), so this is the only guard.
1377            let ty = resolve_expr_type_ref(ta, ctx)?;
1378            subst.insert(tp.name.name.clone(), ty);
1379        }
1380    }
1381
1382    let mut arg_tys: Vec<Option<TyId>> = vec![None; args.len()];
1383    // Pass 1 — non-lambda arguments.
1384    for (i, arg) in args.iter().enumerate() {
1385        if matches!(arg.kind, ExprKind::Lambda(_)) {
1386            continue;
1387        }
1388        let expected = var_params[i].map(|p| substitute(p, &subst, tys));
1389        let ty = type_of(arg, expected, ctx);
1390        if let (Some(pattern), Some(actual)) = (var_params[i], ty)
1391            && !unify(pattern, actual, &mut subst, tys)
1392        {
1393            ctx.errors.push(CompileError::new(
1394                "bynk.generics.type_arg_mismatch",
1395                arg.span,
1396                format!(
1397                    "argument {} infers a type for `{}`'s type parameter that conflicts with an earlier argument — annotate with `{}[T](…)`",
1398                    i + 1,
1399                    name.name,
1400                    name.name
1401                ),
1402            ));
1403            return None;
1404        }
1405        arg_tys[i] = ty;
1406    }
1407    // Slice 4 (DECISION C): the expected type grounds what the arguments left
1408    // open, so a lambda argument can use it.
1409    let own: Vec<String> = fn_decl
1410        .type_params
1411        .iter()
1412        .map(|tp| tp.name.name.clone())
1413        .collect();
1414    ground_from_expected(ret_pattern, expected, &own, &mut subst, ctx);
1415    // Pass 2 — lambda arguments, against substituted expecteds.
1416    for (i, arg) in args.iter().enumerate() {
1417        if !matches!(arg.kind, ExprKind::Lambda(_)) {
1418            continue;
1419        }
1420        let expected = var_params[i].map(|p| substitute(p, &subst, tys));
1421        let params_unconstrained = expected.is_some_and(|e| {
1422            matches!(&*tys.get(e), Ty::Fn { params, .. }
1423                if params.iter().any(|p| contains_var(*p, tys)))
1424        });
1425        let fully_annotated = matches!(
1426            &arg.kind,
1427            ExprKind::Lambda(l) if l.params.iter().all(|p| lambda_param_is_typed(p, ctx))
1428        );
1429        if params_unconstrained && !fully_annotated {
1430            ctx.errors.push(
1431                CompileError::new(
1432                    "bynk.generics.uninferable_type_arg",
1433                    arg.span,
1434                    format!(
1435                        "the lambda's parameter types depend on `{}`'s type parameters, which the other arguments do not determine",
1436                        name.name
1437                    ),
1438                )
1439                .with_note("annotate the lambda's parameters, or give explicit type arguments: `name[T](…)`"),
1440            );
1441            return None;
1442        }
1443        // A fully-annotated lambda grounds the variables itself: type it
1444        // bottom-up and let unify capture them.
1445        let ty = if params_unconstrained {
1446            type_of(arg, None, ctx)
1447        } else {
1448            type_of(arg, expected, ctx)
1449        };
1450        if let (Some(pattern), Some(actual)) = (var_params[i], ty)
1451            && !unify(pattern, actual, &mut subst, tys)
1452        {
1453            ctx.errors.push(CompileError::new(
1454                "bynk.generics.type_arg_mismatch",
1455                arg.span,
1456                format!(
1457                    "the lambda's type conflicts with `{}`'s inferred type arguments",
1458                    name.name
1459                ),
1460            ));
1461            return None;
1462        }
1463        arg_tys[i] = ty;
1464    }
1465    // Every type parameter must now be determined.
1466    for tp in &fn_decl.type_params {
1467        if !subst.contains_key(&tp.name.name) {
1468            ctx.errors.push(
1469                CompileError::new(
1470                    "bynk.generics.uninferable_type_arg",
1471                    name.span,
1472                    format!(
1473                        "type parameter `{}` of `{}` is neither inferable from the arguments nor given explicitly",
1474                        tp.name.name, name.name
1475                    ),
1476                )
1477                .with_label(tp.span, "declared here")
1478                .with_note("give explicit type arguments: `name[T](…)`"),
1479            );
1480            return None;
1481        }
1482    }
1483    // Final compatibility over the fully-ground parameter types.
1484    let mut ok = true;
1485    for (i, (pattern, arg)) in var_params.iter().zip(args).enumerate() {
1486        record_param_hint(ctx.hints, &fn_decl.params[i].name.name, arg);
1487        let (Some(pattern), Some(arg_ty)) = (pattern, arg_tys[i].as_ref()) else {
1488            continue;
1489        };
1490        let ground = substitute(*pattern, &subst, tys);
1491        if !compatible(*arg_ty, ground, tys) {
1492            let err = CompileError::new(
1493                "bynk.types.argument_mismatch",
1494                arg.span,
1495                format!(
1496                    "argument {} to `{}` has type `{}`, but `{}` is expected",
1497                    i + 1,
1498                    name.name,
1499                    arg_ty.display(tys),
1500                    ground.display(tys)
1501                ),
1502            );
1503            ctx.errors.push(with_of_hint(err, *arg_ty, ground, ctx));
1504            ok = false;
1505        }
1506    }
1507    if !ok {
1508        return None;
1509    }
1510    // Constrained generics slice 0: each `Eq`-bounded type parameter of the
1511    // callee must be instantiated with an equality-supporting type. A callee
1512    // that compares a parameter it has not yet declared (reported in its own
1513    // body) is held to it too, so one pass reports a whole chain of generics
1514    // that need the bound and a single fix-all applies them.
1515    let compared = match ctx.input.fns.get(&name.name) {
1516        Some(decl) if std::ptr::eq(decl.as_ref(), fn_decl) => {
1517            super::equality::compared_type_params(decl, ctx)
1518        }
1519        _ => Default::default(),
1520    };
1521    let ord_names = super::ordering::witness_params(fn_decl, &ctx.input.types);
1522    let key_names = super::keying::key_params(fn_decl, &ctx.input.types);
1523    let eq_params: Vec<(String, Option<Span>)> = fn_decl
1524        .type_params
1525        .iter()
1526        .filter(|tp| super::equality::has_eq(&tp.bounds) || compared.contains(&tp.name.name))
1527        // An `Ord`- or `Key`-bounded parameter is checked as such below, which
1528        // covers `Eq`.
1529        .filter(|tp| !ord_names.contains(&tp.name.name) && !key_names.contains(&tp.name.name))
1530        .map(|tp| (tp.name.name.clone(), Some(tp.span)))
1531        .collect();
1532    if !super::equality::check_declared_eq_args(&name.name, name.span, &eq_params, &subst, ctx) {
1533        return None;
1534    }
1535    // Slice 1: each `Ord`-bounded type parameter takes an orderable type, and
1536    // the call carries a comparator witness for it.
1537    let witnesses = super::codable::check_declared_witness_args(
1538        &name.name,
1539        name.span,
1540        &super::codable::witness_list(fn_decl, &ctx.input.types),
1541        &subst,
1542        ctx,
1543    )?;
1544    // Slice 2: each `Key`-bounded type parameter takes a key type. `Key` is
1545    // witness-free: nothing is recorded on the call.
1546    if !super::keying::check_declared_key_args(&name.name, name.span, &key_names, &subst, ctx) {
1547        return None;
1548    }
1549    // v0.39 (ADR 0072): when the user omitted the type arguments, show the
1550    // inferred ones as a `Type`-kind hint after the function name —
1551    // `identity` ⟨`[Int]`⟩ `(5)`. Declaration order; skipped if any var stayed
1552    // unresolved (defensive — the arg loop above already grounds them).
1553    if type_args.is_empty() && !fn_decl.type_params.is_empty() {
1554        let rendered: Option<Vec<String>> = fn_decl
1555            .type_params
1556            .iter()
1557            .map(|tp| subst.get(&tp.name.name).map(|t| t.display(tys)))
1558            .collect();
1559        if let Some(parts) = rendered {
1560            ctx.hints
1561                .record(name.span, format!("[{}]", parts.join(", ")));
1562        }
1563    }
1564    if !witnesses.is_empty() {
1565        ctx.last_witness = Some(witnesses);
1566    }
1567    let ret = substitute(ret_pattern, &subst, tys);
1568    // v0.20b: the return is ground *up to the caller's rigid type
1569    // parameters* — a generic fn calling another generic fn (bynk.list's
1570    // `map` calling `reverse`) legitimately instantiates the callee at its
1571    // own rigid vars, which flow through `compatible` by name-equality.
1572    Some(ret)
1573}
1574
1575fn check_call_against_fn(
1576    name: &Ident,
1577    fn_decl: &FnDecl,
1578    type_args: &[TypeRef],
1579    args: &[Expr],
1580    expected: Option<TyId>,
1581    ctx: &mut Ctx,
1582) -> Option<TyId> {
1583    let tys = ctx.tys;
1584    // v0.20a: generic functions take the instantiation path; the
1585    // non-generic path below runs byte-identically to v0.19 (the additive
1586    // guard). Explicit type args on a non-generic fn are rejected.
1587    if !fn_decl.type_params.is_empty() {
1588        return check_generic_call(name, fn_decl, type_args, args, expected, ctx);
1589    }
1590    if !type_args.is_empty() {
1591        ctx.errors.push(CompileError::new(
1592            "bynk.generics.type_arg_mismatch",
1593            name.span,
1594            format!(
1595                "`{}` is not a generic function — it takes no type arguments",
1596                name.name
1597            ),
1598        ));
1599        for a in args {
1600            let _ = type_of(a, None, ctx);
1601        }
1602        return None;
1603    }
1604    if fn_decl.params.len() != args.len() {
1605        // The resolver reports this in `fn`/method bodies; handler/service/
1606        // agent/test bodies only reach the checker, so report here too (a
1607        // resolve error stops the pipeline first, so this cannot double up).
1608        ctx.errors.push(
1609            CompileError::new(
1610                "bynk.resolve.arity_mismatch",
1611                name.span,
1612                format!(
1613                    "function `{}` expects {} argument(s), but {} were given",
1614                    name.name,
1615                    fn_decl.params.len(),
1616                    args.len()
1617                ),
1618            )
1619            .with_label(fn_decl.name.ident().span, "function declared here"),
1620        );
1621        for a in args {
1622            let _ = type_of(a, None, ctx);
1623        }
1624        return None;
1625    }
1626    let resolved_params: Vec<(Option<TyId>, &Param)> = fn_decl
1627        .params
1628        .iter()
1629        .map(|p| (resolve_type_ref(&p.type_ref, &ctx.input.types, tys), p))
1630        .collect();
1631    let mut ok = true;
1632    for (i, ((param_ty, param), arg)) in resolved_params.iter().zip(args.iter()).enumerate() {
1633        record_param_hint(ctx.hints, &param.name.name, arg);
1634        let arg_ty = type_of(arg, *param_ty, ctx);
1635        let (Some(arg_ty), Some(param_ty)) = (arg_ty, *param_ty) else {
1636            ok = false;
1637            continue;
1638        };
1639        if !compatible(arg_ty, param_ty, tys) {
1640            let err = CompileError::new(
1641                "bynk.types.argument_mismatch",
1642                arg.span,
1643                format!(
1644                    "argument {} to `{}` has type `{}`, but parameter `{}` expects `{}`",
1645                    i + 1,
1646                    name.name,
1647                    arg_ty.display(tys),
1648                    param.name.name,
1649                    param_ty.display(tys)
1650                ),
1651            )
1652            .with_label(param.span, "parameter declared here");
1653            ctx.errors.push(with_of_hint(err, arg_ty, param_ty, ctx));
1654            ok = false;
1655        }
1656    }
1657    if !ok {
1658        return None;
1659    }
1660    resolve_type_ref(&fn_decl.return_type, &ctx.input.types, tys)
1661}
1662
1663/// Slice 3: infer the type arguments of a capability operation from its
1664/// arguments, when they determine every type parameter. Returns the inference
1665/// (if complete) and the arguments' own types, which the caller reuses so no
1666/// argument is checked twice.
1667fn infer_op_type_args(
1668    op: &CapabilityOpInfo,
1669    args: &[Expr],
1670    ctx: &mut Ctx,
1671) -> (Option<HashMap<String, TyId>>, Vec<Option<TyId>>) {
1672    let tys = ctx.tys;
1673    let mut subst: HashMap<String, TyId> = HashMap::new();
1674    let mut typed = Vec::with_capacity(args.len());
1675    let mut ok = true;
1676    for (pattern, arg) in op.params.iter().zip(args) {
1677        // Only an argument whose parameter mentions a type parameter takes part
1678        // in inference; the others are checked against their own parameter type,
1679        // so contextual typing (`None`, `[]`, a literal for a `Float`) still holds.
1680        if !contains_var(*pattern, tys) {
1681            typed.push(type_of(arg, Some(*pattern), ctx));
1682            continue;
1683        }
1684        let t = type_of(arg, None, ctx);
1685        match t {
1686            Some(t) => ok &= unify(*pattern, t, &mut subst, tys),
1687            None => ok = false,
1688        }
1689        typed.push(t);
1690    }
1691    let complete = ok && op.type_params.iter().all(|tp| subst.contains_key(tp));
1692    (complete.then_some(subst), typed)
1693}
1694
1695/// Type-check a kernel-method argument against its expected type, with the
1696/// expected type propagated in (so lambdas and literals type contextually).
1697pub(crate) fn check_arg(arg: &Expr, expected: TyId, what: &str, ctx: &mut Ctx) {
1698    let tys = ctx.tys;
1699    let Some(actual) = type_of(arg, Some(expected), ctx) else {
1700        return;
1701    };
1702    if !compatible(actual, expected, tys) {
1703        ctx.errors.push(CompileError::new(
1704            "bynk.types.type_mismatch",
1705            arg.span,
1706            format!(
1707                "{what} has type `{}`, but `{}` is required",
1708                actual.display(tys),
1709                expected.display(tys)
1710            ),
1711        ));
1712    }
1713}
1714
1715/// 1A.33 (Decision A): which first-party capability the local name `cap` is, seen from
1716/// the unit being checked: declared here (this unit is `bynk`) or flattened in from it.
1717fn local_first_party(cap: &str, ctx: &Ctx) -> Option<crate::firstparty::FirstPartyCap> {
1718    crate::firstparty::resolve(
1719        cap,
1720        &ctx.input.commons.name.joined(),
1721        &ctx.input.cross_context.flattened_caps,
1722    )
1723}
1724
1725/// 1A.33 (Decision A): which first-party capability `consumed.cap` is: the capability is
1726/// declared in `consumed`, so it is bynk's own exactly when `consumed` is the `bynk` unit.
1727fn cross_first_party(consumed: &str, cap: &str) -> Option<crate::firstparty::FirstPartyCap> {
1728    crate::firstparty::resolve(cap, consumed, &HashMap::new())
1729}
1730
1731/// Record a capability reference's binding edge, qualifying flattened bare
1732/// names (`consumes U { Cap }`) to their providing unit (v0.25). A bare
1733/// non-flattened name is the consuming unit's own declaration — qualified
1734/// at assembly.
1735fn record_capability_ref(span: Span, name: &str, ctx: &mut Ctx) {
1736    if let Some(unit) = ctx.input.cross_context.flattened_caps.get(name) {
1737        ctx.refs
1738            .record_in_unit(span, SymbolKind::Capability, name, unit);
1739    } else {
1740        ctx.refs.record(span, SymbolKind::Capability, name);
1741    }
1742}
1743
1744/// The type of `T.of(value)`: `Result[T, ValidationError]`, except on a named
1745/// type with no predicate (#3946), where nothing can fail and it is `T`.
1746/// Compile-time literal admission (v0.9.4) happens instead wherever an expected
1747/// refined type is known — see `admit_refined_literal`, used by `type_of` — so
1748/// `.of`'s type depends on the declaration, never on the form of its argument.
1749fn of_result_ty(decl: &Arc<TypeDecl>, base: BaseType, tys: &Types) -> TyId {
1750    if bynk_syntax::ast::of_is_total(
1751        base,
1752        type_decl_refinement(decl),
1753        matches!(decl.body, TypeBody::Opaque { .. }),
1754    ) {
1755        return named_ty(decl, tys);
1756    }
1757    let named = named_ty(decl, tys);
1758    let err = tys.intern(Ty::ValidationError);
1759    tys.intern(Ty::Result(named, err))
1760}
1761
1762#[allow(clippy::too_many_arguments)]
1763pub(crate) fn check_static_call(
1764    type_name: &Ident,
1765    method: &Ident,
1766    // #926: explicit type arguments for a generic capability operation
1767    // (`Cap.op[T](…)`). Consumed only by the capability-dispatch branch below
1768    // — the user-declared-static branch never receives a non-empty slice,
1769    // since `check_method_call`'s gate only lets type args through for a
1770    // capability (or the `Json` codec, handled separately) receiver.
1771    type_args: &[TypeRef],
1772    args: &[Expr],
1773    span: Span,
1774    // #593: threaded to `check_variant_construction` so a qualified generic
1775    // variant (`Opt.Nil`) can ground its arguments from the binding's type.
1776    expected: Option<TyId>,
1777    // P6.0 (#1139): the outer expression's identity — the `MethodCall` node
1778    // `check_method_call` is dispatching on behalf of.
1779    expr_id: ExprId,
1780    ctx: &mut Ctx,
1781) -> Option<TyId> {
1782    let tys = ctx.tys;
1783    // Capability dispatch (v0.5): if `type_name` names a capability declared
1784    // in the context, dispatch via the capability table. If the capability is
1785    // declared but not in `given`, error specifically.
1786    if ctx.caps.declared_capabilities.contains_key(&type_name.name)
1787        && !ctx.caps.capabilities.contains_key(&type_name.name)
1788    {
1789        record_capability_ref(type_name.span, &type_name.name, ctx);
1790        ctx.callees.insert(
1791            expr_id,
1792            Callee::Capability {
1793                cap: type_name.name.clone(),
1794                op: method.name.clone(),
1795                wire: None,
1796                first_party: local_first_party(&type_name.name, ctx),
1797                event: None,
1798            },
1799        );
1800        let mut err = CompileError::new(
1801            "bynk.given.undeclared_capability",
1802            type_name.span,
1803            format!(
1804                "capability `{}` is used but not listed in the handler's `given` clause",
1805                type_name.name
1806            ),
1807        )
1808        .with_note(format!(
1809            "add `{}` to the handler's `given` clause so the dependency surface is visible at the declaration site",
1810            type_name.name
1811        ));
1812        // v0.26 (ADR 0054): the one-click counterpart of the note.
1813        if let Some((span, insert)) = given_insertion_edit(
1814            &ctx.caps.given_entries,
1815            ctx.caps.given_anchor,
1816            &type_name.name,
1817        ) {
1818            err = err.with_suggestion(
1819                format!("add `{}` to the `given` clause", type_name.name),
1820                vec![(span, insert)],
1821                Applicability::MachineApplicable,
1822            );
1823        }
1824        ctx.errors.push(err);
1825        // v0.99: an uncovered direct capability call — record it so the ghost
1826        // `given` inlay hint can offer the same clause at the declaration site
1827        // (DECISION D/E). `span` is the call site (the inner `given_insertion_edit`
1828        // binding shadowed it only within the `if let` above).
1829        record_requirement(
1830            ctx,
1831            &type_name.name,
1832            span,
1833            RequirementSource::DirectCall {
1834                op: method.name.clone(),
1835            },
1836            false,
1837        );
1838        for a in args {
1839            let _ = type_of(a, None, ctx);
1840        }
1841        return None;
1842    }
1843    if let Some(cap) = ctx.caps.capabilities.get(&type_name.name).cloned() {
1844        record_capability_ref(type_name.span, &type_name.name, ctx);
1845        // S3 (#1963): a flattened capability's operation, by its owning unit.
1846        if let Some(unit) = ctx
1847            .input
1848            .cross_context
1849            .flattened_caps
1850            .get(&type_name.name)
1851            .cloned()
1852        {
1853            refuse_experimental(
1854                &format!("{unit}.{}.{}", type_name.name, method.name),
1855                method.span,
1856                ctx,
1857            );
1858        }
1859        ctx.callees.insert(
1860            expr_id,
1861            Callee::Capability {
1862                cap: type_name.name.clone(),
1863                op: method.name.clone(),
1864                wire: None,
1865                first_party: local_first_party(&type_name.name, ctx),
1866                event: None,
1867            },
1868        );
1869        if !ctx.effectful {
1870            ctx.errors.push(
1871                CompileError::new(
1872                    "bynk.effect.capability_in_pure_context",
1873                    span,
1874                    format!(
1875                        "capability `{}` can only be called inside an effectful body (one returning `Effect[T]`)",
1876                        type_name.name
1877                    ),
1878                ),
1879            );
1880        }
1881        ctx.caps.given_used.insert(type_name.name.clone());
1882        // v0.99: a covered direct capability call — the call site *is* the
1883        // reason (DECISION C). Recorded so hover can explain what a declared
1884        // `given Cap` is for; no inlay hint (already covered).
1885        record_requirement(
1886            ctx,
1887            &type_name.name,
1888            span,
1889            RequirementSource::DirectCall {
1890                op: method.name.clone(),
1891            },
1892            true,
1893        );
1894        // #2865: `select[T]` / `firstAs[T]` on a derived `D1` are lowered by
1895        // the compiler over `all`/`first`, not declared operations.
1896        if d1::is_typed_read(cap.derived_from.as_ref(), &method.name) {
1897            return d1::check_typed_read(
1898                cap.derived_from.as_ref(),
1899                &type_name.name,
1900                method,
1901                type_args,
1902                args,
1903                span,
1904                expr_id,
1905                ctx,
1906            );
1907        }
1908        let Some(op) = cap.ops.iter().find(|o| o.name == method.name) else {
1909            ctx.errors.push(CompileError::new(
1910                "bynk.capability.unknown_operation",
1911                method.span,
1912                format!(
1913                    "capability `{}` has no operation named `{}`",
1914                    type_name.name, method.name
1915                ),
1916            ));
1917            for a in args {
1918                let _ = type_of(a, None, ctx);
1919            }
1920            return None;
1921        };
1922        // v0.36 (ADR 0069, slice 2): the op is an index symbol keyed by the
1923        // compound `"Cap.op"` name; this local call is a reference. S4a
1924        // (#1966): a derived capability declares no operations, so its call
1925        // references the base's, in the base's unit, and is refused as the
1926        // base's would be.
1927        match &cap.derived_from {
1928            Some((unit, base)) => {
1929                refuse_experimental(&format!("{unit}.{base}.{}", method.name), method.span, ctx);
1930                ctx.refs.record_in_unit(
1931                    method.span,
1932                    SymbolKind::CapabilityOp,
1933                    &format!("{base}.{}", method.name),
1934                    unit,
1935                );
1936            }
1937            None => ctx.refs.record(
1938                method.span,
1939                SymbolKind::CapabilityOp,
1940                &format!("{}.{}", type_name.name, method.name),
1941            ),
1942        }
1943        // #2634: a flattened cross-unit op whose signature names a type the
1944        // consumer binds to a different shape is refused at the call (the
1945        // refs above are recorded first, so a refused call still indexes).
1946        if let Some((unit, name, in_param)) = &op.boundary_conflict {
1947            let err = rebranded_return_mismatch(
1948                &format!("{}.{}", type_name.name, method.name),
1949                name,
1950                unit,
1951                *in_param,
1952                span,
1953                ctx,
1954            );
1955            ctx.errors.push(err);
1956            for a in args {
1957                let _ = type_of(a, None, ctx);
1958            }
1959            return None;
1960        }
1961        // P4c (#2628): a `D1` statement's SQL is a literal.
1962        d1::check_sql_argument(
1963            cap.derived_from.as_ref(),
1964            &type_name.name,
1965            &method.name,
1966            args,
1967            ctx,
1968        );
1969        if op.params.len() != args.len() {
1970            ctx.errors.push(CompileError::new(
1971                "bynk.capability.op_arity",
1972                span,
1973                format!(
1974                    "capability operation `{}.{}` expects {} argument(s), but {} were given",
1975                    type_name.name,
1976                    method.name,
1977                    op.params.len(),
1978                    args.len()
1979                ),
1980            ));
1981            for a in args {
1982                let _ = type_of(a, None, ctx);
1983            }
1984            return None;
1985        }
1986        let op_clone = op.clone();
1987        // #926: resolve the op's own type parameter(s) from an explicit
1988        // call-site type argument, or (#4113) from the arguments when they
1989        // determine every one.
1990        let mut subst: HashMap<String, TyId> = HashMap::new();
1991        // Slice 3, widened by #4113: an operation with type parameters infers its type
1992        // arguments from the arguments, when they determine every one.
1993        let mut arg_tys: Option<Vec<Option<TyId>>> = None;
1994        if type_args.is_empty()
1995            && (!op_clone.codable_params.is_empty() || !op_clone.type_params.is_empty())
1996        {
1997            let (inferred, typed) = infer_op_type_args(&op_clone, args, ctx);
1998            arg_tys = Some(typed);
1999            if let Some(found) = inferred {
2000                subst = found;
2001            }
2002        }
2003        if !op_clone.type_params.is_empty() || !type_args.is_empty() {
2004            if type_args.is_empty() && subst.len() < op_clone.type_params.len() {
2005                ctx.errors.push(
2006                    CompileError::new(
2007                        "bynk.generics.uninferable_type_arg",
2008                        span,
2009                        format!(
2010                            "capability operation `{}.{}` takes a type parameter, but none of its arguments determine it",
2011                            type_name.name, method.name
2012                        ),
2013                    )
2014                    .with_note(format!(
2015                        "give it explicitly: `{}.{}[T](…)`",
2016                        type_name.name, method.name
2017                    )),
2018                );
2019                if arg_tys.is_none() {
2020                    for a in args {
2021                        let _ = type_of(a, None, ctx);
2022                    }
2023                }
2024                return None;
2025            }
2026            if !type_args.is_empty() && type_args.len() != op_clone.type_params.len() {
2027                ctx.errors.push(CompileError::new(
2028                    "bynk.generics.type_arg_mismatch",
2029                    span,
2030                    format!(
2031                        "capability operation `{}.{}` takes {} type argument(s), but {} were given",
2032                        type_name.name,
2033                        method.name,
2034                        op_clone.type_params.len(),
2035                        type_args.len()
2036                    ),
2037                ));
2038                for a in args {
2039                    let _ = type_of(a, None, ctx);
2040                }
2041                return None;
2042            }
2043            // #4113: an inferred type argument meets the same owner-only check as a written one.
2044            if type_args.is_empty() {
2045                for ty in op_clone.type_params.iter().filter_map(|tp| subst.get(tp)) {
2046                    super::events_emit::check_emit_owner(
2047                        local_first_party(&type_name.name, ctx),
2048                        &method.name,
2049                        (*ty, span, expr_id),
2050                        ctx,
2051                    );
2052                }
2053            }
2054            for (tp, ta) in op_clone.type_params.iter().zip(type_args) {
2055                let ty = resolve_expr_type_ref(ta, ctx)?;
2056                super::events_emit::check_emit_owner(
2057                    local_first_party(&type_name.name, ctx),
2058                    &method.name,
2059                    (ty, ta.span(), expr_id),
2060                    ctx,
2061                );
2062                subst.insert(tp.clone(), ty);
2063            }
2064        }
2065        // Slice 3: each `Codable` type parameter takes a codable type, and the
2066        // call records how it encodes the parameters that mention one.
2067        if !check_op_codable_args(
2068            &format!("{}.{}", type_name.name, method.name),
2069            span,
2070            &op_clone.codable_params,
2071            &subst,
2072            ctx,
2073        ) {
2074            if arg_tys.is_none() {
2075                for a in args {
2076                    let _ = type_of(a, None, ctx);
2077                }
2078            }
2079            return None;
2080        }
2081        if !record_capability_wire(
2082            &op_clone,
2083            (&type_name.name, &method.name),
2084            span,
2085            expr_id,
2086            &subst,
2087            arg_tys.is_none().then_some(args),
2088            ctx,
2089        ) {
2090            return None;
2091        }
2092        for (i, (param_ty, arg)) in op_clone.params.iter().zip(args.iter()).enumerate() {
2093            let param_ty = substitute(*param_ty, &subst, tys);
2094            let arg_ty = match &arg_tys {
2095                Some(cached) => cached[i],
2096                None => type_of(arg, Some(param_ty), ctx),
2097            };
2098            if let Some(actual) = arg_ty
2099                && !compatible(actual, param_ty, tys)
2100            {
2101                ctx.errors.push(CompileError::new(
2102                    "bynk.types.argument_mismatch",
2103                    arg.span,
2104                    format!(
2105                        "argument {} to capability `{}.{}` has type `{}`, but parameter expects `{}`",
2106                        i + 1,
2107                        type_name.name,
2108                        method.name,
2109                        actual.display(tys),
2110                        param_ty.display(tys)
2111                    ),
2112                ));
2113            }
2114        }
2115        return Some(substitute(op_clone.return_ty, &subst, tys));
2116    }
2117    let decl = ctx.input.types.get(&type_name.name)?;
2118    ctx.refs
2119        .record(type_name.span, SymbolKind::Type, &type_name.name);
2120
2121    // 1) User-declared static method. Borrow the method table and decl
2122    // straight out of the (immutable) input rather than cloning the whole
2123    // `MethodTable`/`FnDecl` on every static-shaped call.
2124    if let Some(method_decl) = ctx
2125        .input
2126        .methods
2127        .get(&type_name.name)
2128        .and_then(|table| table.statics.get(&method.name))
2129    {
2130        ctx.callees
2131            .insert(expr_id, Callee::Static(Arc::clone(method_decl), Vec::new()));
2132        // Constrained generics slice 4: a static on a generic type is generic
2133        // over the type's parameters; infer them like an instance method's.
2134        if !decl.type_params.is_empty() {
2135            let type_params: Vec<String> = decl
2136                .type_params
2137                .iter()
2138                .map(|p| p.name.name.clone())
2139                .collect();
2140            let ret = check_generic_method_call(
2141                &type_name.name,
2142                &type_params,
2143                None,
2144                method_decl,
2145                method,
2146                type_args,
2147                args,
2148                expected,
2149                ctx,
2150            );
2151            if let Some(witnesses) = ctx.last_witness.take() {
2152                ctx.callees
2153                    .insert(expr_id, Callee::Static(Arc::clone(method_decl), witnesses));
2154            }
2155            return ret;
2156        }
2157        return check_method_args(method_decl, args, ctx, type_name, method);
2158    }
2159
2160    // 2) Built-in `of` constructor on refined or opaque types.
2161    if method.name == OF
2162        && let Some(base) = type_decl_base(decl)
2163    {
2164        ctx.callees
2165            .insert(expr_id, Callee::Refine(Arc::clone(decl)));
2166        if args.len() != 1 {
2167            ctx.errors.push(CompileError::new(
2168                "bynk.types.constructor_arity",
2169                span,
2170                format!(
2171                    "constructor `{}.of` expects 1 argument, but {} were given",
2172                    type_name.name,
2173                    args.len()
2174                ),
2175            ));
2176            return None;
2177        }
2178        let arg = &args[0];
2179        let expected = tys.intern(Ty::Base(base));
2180        let arg_ty = type_of(arg, Some(expected), ctx)?;
2181        if !compatible(arg_ty, expected, tys) {
2182            ctx.errors.push(CompileError::new(
2183                "bynk.types.constructor_base_mismatch",
2184                arg.span,
2185                format!(
2186                    "constructor `{}.of` expects a `{}` argument, but got `{}`",
2187                    type_name.name,
2188                    base.name(),
2189                    arg_ty.display(tys)
2190                ),
2191            ));
2192            return None;
2193        }
2194        return Some(of_result_ty(decl, base, tys));
2195    }
2196
2197    // 2b) Built-in `unsafe` constructor on opaque types — only available
2198    // inside the defining commons.
2199    if method.name == UNSAFE
2200        && let TypeBody::Opaque { base, .. } = &decl.body
2201    {
2202        ctx.callees
2203            .insert(expr_id, Callee::Unsafe(Arc::clone(decl)));
2204        if !ctx.input.is_local_type(&decl.name.name) {
2205            ctx.errors.push(
2206                CompileError::new(
2207                    "bynk.types.opaque_unsafe_outside",
2208                    method.span,
2209                    format!(
2210                        "`{}.unsafe(...)` is only available within the commons that defines the opaque type `{}`",
2211                        type_name.name, type_name.name
2212                    ),
2213                )
2214                .with_note(
2215                    "outside the defining commons, opaque values are constructed via `T.of(value)`",
2216                ),
2217            );
2218            return None;
2219        }
2220        if args.len() != 1 {
2221            ctx.errors.push(CompileError::new(
2222                "bynk.types.constructor_arity",
2223                span,
2224                format!(
2225                    "`{}.unsafe` expects 1 argument, but {} were given",
2226                    type_name.name,
2227                    args.len()
2228                ),
2229            ));
2230            return None;
2231        }
2232        let arg = &args[0];
2233        let expected = tys.intern(Ty::Base(*base));
2234        let arg_ty = type_of(arg, Some(expected), ctx)?;
2235        if !compatible(arg_ty, expected, tys) {
2236            ctx.errors.push(CompileError::new(
2237                "bynk.types.constructor_base_mismatch",
2238                arg.span,
2239                format!(
2240                    "`{}.unsafe` expects a `{}` argument, but got `{}`",
2241                    type_name.name,
2242                    base.name(),
2243                    arg_ty.display(tys)
2244                ),
2245            ));
2246            return None;
2247        }
2248        return Some(named_ty(decl, tys));
2249    }
2250
2251    // 3) Qualified variant construction `TypeName.Variant(args)`.
2252    if let TypeBody::Sum(_) = &decl.body {
2253        ctx.callees.insert(
2254            expr_id,
2255            Callee::Ctor {
2256                sum: Arc::clone(decl),
2257                tag: method.name.clone(),
2258            },
2259        );
2260        return check_variant_construction(decl, &method.name, args, span, expected, ctx);
2261    }
2262
2263    ctx.errors.push(
2264        CompileError::new(
2265            "bynk.types.unknown_static_member",
2266            method.span,
2267            format!(
2268                "type `{}` has no static method or variant named `{}`",
2269                type_name.name, method.name
2270            ),
2271        )
2272        // Finding #46: `decl` comes from the combined cross-file symbol
2273        // table — see resolver.rs:1029 for the full rationale.
2274        .with_note("type declared here"),
2275    );
2276    None
2277}
2278
2279fn check_method_args(
2280    method_decl: &FnDecl,
2281    args: &[Expr],
2282    ctx: &mut Ctx,
2283    type_name: &Ident,
2284    method: &Ident,
2285) -> Option<TyId> {
2286    let tys = ctx.tys;
2287    if method_decl.params.len() != args.len() {
2288        ctx.errors.push(
2289            CompileError::new(
2290                "bynk.types.method_arity",
2291                method.span,
2292                format!(
2293                    "static method `{}.{}` expects {} argument(s), but {} were given",
2294                    type_name.name,
2295                    method.name,
2296                    method_decl.params.len(),
2297                    args.len()
2298                ),
2299            )
2300            .with_label(method_decl.name.ident().span, "method declared here"),
2301        );
2302        for a in args {
2303            let _ = type_of(a, None, ctx);
2304        }
2305        return None;
2306    }
2307    let mut ok = true;
2308    for (i, (param, arg)) in method_decl.params.iter().zip(args.iter()).enumerate() {
2309        record_param_hint(ctx.hints, &param.name.name, arg);
2310        let expected = resolve_type_ref(&param.type_ref, &ctx.input.types, tys);
2311        let actual = type_of(arg, expected, ctx);
2312        let (Some(actual), Some(expected)) = (actual, expected) else {
2313            ok = false;
2314            continue;
2315        };
2316        if !compatible(actual, expected, tys) {
2317            let err = CompileError::new(
2318                "bynk.types.argument_mismatch",
2319                arg.span,
2320                format!(
2321                    "argument {} to `{}.{}` has type `{}`, but parameter `{}` expects `{}`",
2322                    i + 1,
2323                    type_name.name,
2324                    method.name,
2325                    actual.display(tys),
2326                    param.name.name,
2327                    expected.display(tys)
2328                ),
2329            );
2330            ctx.errors.push(with_of_hint(err, actual, expected, ctx));
2331            ok = false;
2332        }
2333    }
2334    if !ok {
2335        return None;
2336    }
2337    resolve_type_ref(&method_decl.return_type, &ctx.input.types, tys)
2338}
2339
2340/// v0.82 (ADR 0110): resolve a storage-map operation `<map>.<op>(args)` on a
2341/// `store Map[K, V]` field. The ops are effect-typed (storage I/O, awaited with
2342/// `<-`): `put`/`update`/`upsert`/`remove` → `Effect[()]`, `get` →
2343/// `Effect[Option[V]]`, `contains` → `Effect[Bool]`, `size` → `Effect[Int]`.
2344/// `update` on an absent key is a runtime fault; `upsert` is the default-if-absent
2345/// form. Dispatched by receiver provenance, so it never shadows the immutable
2346/// value `Map`'s pure methods.
2347pub(crate) fn check_store_map_op(
2348    method: &Ident,
2349    args: &[Expr],
2350    k: TyId,
2351    v: TyId,
2352    span: Span,
2353    ctx: &mut Ctx,
2354) -> Option<TyId> {
2355    let tys = ctx.tys;
2356    let vfn = || Ty::Fn {
2357        params: vec![v],
2358        ret: v,
2359    };
2360    // v0.105 (slice 3b-ii): a held `Map[K, Connection]` stores connection ids and
2361    // resolves them by identity; `update`/`upsert` transform the value through a
2362    // `(V) -> V` function, which has no meaning for a held resource — you cannot
2363    // derive a new connection from an old one. Reject them (the other entry ops —
2364    // `put`/`get`/`remove`/`contains`/`size` — are admitted) so the program is a
2365    // clean compile error rather than a silent miscompile.
2366    if v.is_held(tys) && matches!(method.name.as_str(), "update" | "upsert") {
2367        ctx.errors.push(
2368            CompileError::new(
2369                "bynk.held.unsupported_map_op",
2370                method.span,
2371                format!(
2372                    "a held `Map[K, Connection]` has no `{}` operation — a held resource cannot be transformed by a `(Connection) -> Connection` function",
2373                    method.name
2374                ),
2375            )
2376            .with_note(
2377                "held connections are stored and resolved by identity; use `put`/`get`/`remove`",
2378            ),
2379        );
2380        for a in args {
2381            type_of(a, None, ctx);
2382        }
2383        return None;
2384    }
2385    let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2386        "put" => (vec![k, v], tys.intern(Ty::Unit)),
2387        "get" => (vec![k], tys.intern(Ty::Option(v))),
2388        "remove" => (vec![k], tys.intern(Ty::Unit)),
2389        "contains" => (vec![k], tys.intern(Ty::Base(BaseType::Bool))),
2390        "size" => (vec![], tys.intern(Ty::Base(BaseType::Int))),
2391        "update" => (vec![k, tys.intern(vfn())], tys.intern(Ty::Unit)),
2392        "upsert" => (vec![k, v, tys.intern(vfn())], tys.intern(Ty::Unit)),
2393        other => {
2394            ctx.errors.push(
2395                CompileError::new(
2396                    "bynk.store.unknown_op",
2397                    method.span,
2398                    format!(
2399                        "a `Map` store field has no operation `{other}` — expected `put`, `get`, \
2400                         `update`, `upsert`, `remove`, `contains`, or `size`"
2401                    ),
2402                )
2403                .with_note("storage-map ops are entry-level and effectful (await with `<-`)"),
2404            );
2405            for a in args {
2406                type_of(a, None, ctx);
2407            }
2408            return None;
2409        }
2410    };
2411    let effect = Ty::Effect(result);
2412    if args.len() != expected.len() {
2413        ctx.errors.push(CompileError::new(
2414            "bynk.types.call_arity",
2415            span,
2416            format!(
2417                "`Map.{}` takes {} argument(s), found {}",
2418                method.name,
2419                expected.len(),
2420                args.len()
2421            ),
2422        ));
2423        for a in args {
2424            type_of(a, None, ctx);
2425        }
2426        return Some(tys.intern(effect));
2427    }
2428    for (a, exp) in args.iter().zip(expected.iter()) {
2429        if let Some(at) = type_of(a, Some(*exp), ctx)
2430            && !compatible(at, *exp, tys)
2431        {
2432            ctx.errors.push(CompileError::new(
2433                "bynk.types.argument_mismatch",
2434                a.span,
2435                format!(
2436                    "expected `{}`, found `{}`",
2437                    exp.display(tys),
2438                    at.display(tys)
2439                ),
2440            ));
2441        }
2442    }
2443    Some(tys.intern(effect))
2444}
2445
2446/// v0.99: record a capability requirement at `site` into the ledger, and — when
2447/// the enclosing handler's `given` does not cover it — push the diagnostic. The
2448/// single producer behind both the bare diagnostic and the editor surfaces
2449/// (DECISION D): every requirement is *recorded*, covered or not; only an
2450/// uncovered one errors. The `code`/`message` are the consuming feature's, so a
2451/// store op keeps its precise diagnostic; the ledger's *reason* renders from
2452/// `source` alone (DECISION C), never from `code`.
2453fn require_capability(
2454    site: Span,
2455    capability: &str,
2456    source: RequirementSource,
2457    ctx: &mut Ctx,
2458    code: &'static str,
2459    message: &str,
2460) {
2461    let covered = ctx.caps.capabilities.contains_key(capability);
2462    if covered {
2463        ctx.caps.given_used.insert(capability.to_string());
2464    } else {
2465        ctx.errors
2466            .push(CompileError::new(code, site, message).with_note(format!(
2467                "add `{capability}` to the handler's `given` clause"
2468            )));
2469    }
2470    record_requirement(ctx, capability, site, source, covered);
2471}
2472
2473/// Push a [`Requirement`] into the ledger. For an uncovered requirement it also
2474/// computes the materialization edit (the ghost `given` inlay hint's one-click
2475/// apply) from the handler's existing `given` entries and anchor — the same
2476/// `given_insertion_edit` the undeclared-capability quick-fix uses.
2477fn record_requirement(
2478    ctx: &mut Ctx,
2479    capability: &str,
2480    site: Span,
2481    source: RequirementSource,
2482    covered: bool,
2483) {
2484    let materialize = if covered {
2485        None
2486    } else {
2487        given_insertion_edit(&ctx.caps.given_entries, ctx.caps.given_anchor, capability).map(
2488            |(edit_span, edit_text)| Materialize {
2489                anchor: ctx.caps.given_anchor.unwrap_or(ctx.return_ty_span),
2490                edit_span,
2491                edit_text,
2492            },
2493        )
2494    };
2495    ctx.requirements.record(Requirement {
2496        capability: capability.to_string(),
2497        site,
2498        source,
2499        covered,
2500        materialize,
2501    });
2502}
2503
2504/// v0.87 (ADR 0113): resolve a storage-`Cache` operation `<cache>.<op>(args)` on
2505/// a `store Cache[K, V]` field. The op set is the storage `Map`'s
2506/// (`put`/`get`/`update`/`upsert`/`remove`/`contains`/`size`); every op but
2507/// `remove` additionally requires `given Clock` (eviction reads the clock).
2508pub(crate) fn check_store_cache_op(
2509    method: &Ident,
2510    args: &[Expr],
2511    k: TyId,
2512    v: TyId,
2513    span: Span,
2514    ctx: &mut Ctx,
2515) -> Option<TyId> {
2516    let tys = ctx.tys;
2517    let vfn = || Ty::Fn {
2518        params: vec![v],
2519        ret: v,
2520    };
2521    let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2522        "put" => (vec![k, v], tys.intern(Ty::Unit)),
2523        "get" => (vec![k], tys.intern(Ty::Option(v))),
2524        "remove" => (vec![k], tys.intern(Ty::Unit)),
2525        "contains" => (vec![k], tys.intern(Ty::Base(BaseType::Bool))),
2526        "size" => (vec![], tys.intern(Ty::Base(BaseType::Int))),
2527        "update" => (vec![k, tys.intern(vfn())], tys.intern(Ty::Unit)),
2528        "upsert" => (vec![k, v, tys.intern(vfn())], tys.intern(Ty::Unit)),
2529        other => {
2530            ctx.errors.push(
2531                CompileError::new(
2532                    "bynk.store.unknown_op",
2533                    method.span,
2534                    format!(
2535                        "a `Cache` store field has no operation `{other}` — expected `put`, \
2536                         `get`, `update`, `upsert`, `remove`, `contains`, or `size`"
2537                    ),
2538                )
2539                .with_note("storage-cache ops are entry-level and effectful (await with `<-`)"),
2540            );
2541            for a in args {
2542                type_of(a, None, ctx);
2543            }
2544            return None;
2545        }
2546    };
2547    // D4: every op but `remove` reads the clock for TTL expiry.
2548    if method.name != "remove" {
2549        require_capability(
2550            method.span,
2551            "Clock",
2552            RequirementSource::StoreOp {
2553                kind: StoreKind::Cache,
2554                op: method.name.clone(),
2555            },
2556            ctx,
2557            "bynk.store.cache_needs_clock",
2558            "a `Cache` operation applies TTL expiry, which reads the clock — the handler must declare `given Clock`",
2559        );
2560    }
2561    let effect = Ty::Effect(result);
2562    if args.len() != expected.len() {
2563        ctx.errors.push(CompileError::new(
2564            "bynk.types.call_arity",
2565            span,
2566            format!(
2567                "`Cache.{}` takes {} argument(s), found {}",
2568                method.name,
2569                expected.len(),
2570                args.len()
2571            ),
2572        ));
2573        for a in args {
2574            type_of(a, None, ctx);
2575        }
2576        return Some(tys.intern(effect));
2577    }
2578    for (a, exp) in args.iter().zip(expected.iter()) {
2579        if let Some(at) = type_of(a, Some(*exp), ctx)
2580            && !compatible(at, *exp, tys)
2581        {
2582            ctx.errors.push(CompileError::new(
2583                "bynk.types.argument_mismatch",
2584                a.span,
2585                format!(
2586                    "expected `{}`, found `{}`",
2587                    exp.display(tys),
2588                    at.display(tys)
2589                ),
2590            ));
2591        }
2592    }
2593    Some(tys.intern(effect))
2594}
2595
2596/// v0.95 (ADR 0121): resolve a storage-`Log` operation `<log>.<op>(args)` on a
2597/// `store Log[T]` field. `append(e)` is the effectful, **non-idempotent** write
2598/// (`Effect[()]`) and the one clock-consuming op — it stamps `Clock.now()`, so it
2599/// requires `given Clock`. The time-window roots — `since(Instant)`/
2600/// `before(Instant)` / `between(Instant, Instant)` / `recent(Int)` / `reversed()`
2601/// — and the general query vocabulary lift the log into a lazy `Query[T]` over its
2602/// entry values; these need no clock (window bounds are explicit `Instant`s).
2603pub(crate) fn check_store_log_op(
2604    method: &Ident,
2605    args: &[Expr],
2606    elem: TyId,
2607    span: Span,
2608    ctx: &mut Ctx,
2609) -> Option<TyId> {
2610    let tys = ctx.tys;
2611    let query = || Ty::Query(elem);
2612    let arity = |n: usize, ctx: &mut Ctx| {
2613        if args.len() != n {
2614            ctx.errors.push(CompileError::new(
2615                "bynk.types.call_arity",
2616                span,
2617                format!(
2618                    "`Log.{}` takes {n} argument(s), found {}",
2619                    method.name,
2620                    args.len()
2621                ),
2622            ));
2623            for a in args {
2624                type_of(a, None, ctx);
2625            }
2626            return false;
2627        }
2628        true
2629    };
2630    let window_arg = |a: &Expr, what: &str, ctx: &mut Ctx| {
2631        if let Some(at) = type_of(a, Some(tys.intern(Ty::Base(BaseType::Instant))), ctx)
2632            && !compatible(at, tys.intern(Ty::Base(BaseType::Instant)), tys)
2633        {
2634            ctx.errors.push(CompileError::new(
2635                "bynk.types.argument_mismatch",
2636                a.span,
2637                format!("{what} expects `Instant`, found `{}`", at.display(tys)),
2638            ));
2639        }
2640    };
2641    match method.name.as_str() {
2642        // The one effectful write — non-idempotent; stamps the clock.
2643        "append" => {
2644            require_capability(
2645                method.span,
2646                "Clock",
2647                RequirementSource::StoreOp {
2648                    kind: StoreKind::Log,
2649                    op: method.name.clone(),
2650                },
2651                ctx,
2652                "bynk.store.log_needs_clock",
2653                "`Log.append` stamps the current time, which reads the clock — the handler must declare `given Clock`",
2654            );
2655            if !arity(1, ctx) {
2656                return Some(tys.intern(Ty::Effect(tys.intern(Ty::Unit))));
2657            }
2658            if let Some(at) = type_of(&args[0], Some(elem), ctx)
2659                && !compatible(at, elem, tys)
2660            {
2661                ctx.errors.push(CompileError::new(
2662                    "bynk.types.argument_mismatch",
2663                    args[0].span,
2664                    format!(
2665                        "expected `{}`, found `{}`",
2666                        elem.display(tys),
2667                        at.display(tys)
2668                    ),
2669                ));
2670            }
2671            Some(tys.intern(Ty::Effect(tys.intern(Ty::Unit))))
2672        }
2673        // Time-window query roots → `Query[T]` (lazy; no clock).
2674        "since" | "before" => {
2675            if !arity(1, ctx) {
2676                return Some(tys.intern(query()));
2677            }
2678            window_arg(&args[0], &format!("`Log.{}`", method.name), ctx);
2679            Some(tys.intern(query()))
2680        }
2681        "between" => {
2682            if !arity(2, ctx) {
2683                return Some(tys.intern(query()));
2684            }
2685            window_arg(&args[0], "`Log.between` start", ctx);
2686            window_arg(&args[1], "`Log.between` end", ctx);
2687            Some(tys.intern(query()))
2688        }
2689        "recent" => {
2690            if !arity(1, ctx) {
2691                return Some(tys.intern(query()));
2692            }
2693            check_arg(
2694                &args[0],
2695                tys.intern(Ty::Base(BaseType::Int)),
2696                "the `Log.recent` count",
2697                ctx,
2698            );
2699            Some(tys.intern(query()))
2700        }
2701        "reversed" => {
2702            if !arity(0, ctx) {
2703                return Some(tys.intern(query()));
2704            }
2705            Some(tys.intern(query()))
2706        }
2707        // The general query vocabulary over the entry values.
2708        name if is_query_op(name) => {
2709            let r =
2710                check_query_kernel_method(method, QueryOp::from_name(name), args, elem, span, ctx);
2711            par::reject_store_write_in_closure(method, args, ctx);
2712            r
2713        }
2714        other => {
2715            ctx.errors.push(
2716                CompileError::new(
2717                    "bynk.store.unknown_op",
2718                    method.span,
2719                    format!(
2720                        "a `Log` store field has no operation `{other}` — `append`, the \
2721                         time-window roots (`since`/`before`/`between`/`recent`/`reversed`), \
2722                         and the query builders/terminals"
2723                    ),
2724                )
2725                .with_note(
2726                    "`Log` reads are lazy `Query[T]`; only `append` is effectful and writes",
2727                ),
2728            );
2729            for a in args {
2730                type_of(a, None, ctx);
2731            }
2732            None
2733        }
2734    }
2735}
2736
2737/// v0.83: resolve a storage-set operation `<set>.<op>(args)` on a `store Set[T]`
2738/// field. Effect-typed entry ops: `add(t)`/`remove(t)` → `Effect[()]` (both
2739/// idempotent), `contains(t)` → `Effect[Bool]`, `size()` → `Effect[Int]`. Set
2740/// algebra (`union`/`intersection`/`difference`) is deferred (it needs a value
2741/// `Set` return type). Dispatched by receiver provenance.
2742pub(crate) fn check_store_set_op(
2743    method: &Ident,
2744    args: &[Expr],
2745    t: TyId,
2746    span: Span,
2747    ctx: &mut Ctx,
2748) -> Option<TyId> {
2749    let tys = ctx.tys;
2750    let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2751        "add" => (vec![t], tys.intern(Ty::Unit)),
2752        "remove" => (vec![t], tys.intern(Ty::Unit)),
2753        "contains" => (vec![t], tys.intern(Ty::Base(BaseType::Bool))),
2754        "size" => (vec![], tys.intern(Ty::Base(BaseType::Int))),
2755        other => {
2756            ctx.errors.push(
2757                CompileError::new(
2758                    "bynk.store.unknown_op",
2759                    method.span,
2760                    format!(
2761                        "a `Set` store field has no operation `{other}` — expected `add`, \
2762                         `remove`, `contains`, or `size`"
2763                    ),
2764                )
2765                .with_note(
2766                    "set algebra (`union`/`intersection`/`difference`) is not in this slice",
2767                ),
2768            );
2769            for a in args {
2770                type_of(a, None, ctx);
2771            }
2772            return None;
2773        }
2774    };
2775    let effect = Ty::Effect(result);
2776    if args.len() != expected.len() {
2777        ctx.errors.push(CompileError::new(
2778            "bynk.types.call_arity",
2779            span,
2780            format!(
2781                "`Set.{}` takes {} argument(s), found {}",
2782                method.name,
2783                expected.len(),
2784                args.len()
2785            ),
2786        ));
2787        for a in args {
2788            type_of(a, None, ctx);
2789        }
2790        return Some(tys.intern(effect));
2791    }
2792    for (a, exp) in args.iter().zip(expected.iter()) {
2793        if let Some(at) = type_of(a, Some(*exp), ctx)
2794            && !compatible(at, *exp, tys)
2795        {
2796            ctx.errors.push(CompileError::new(
2797                "bynk.types.argument_mismatch",
2798                a.span,
2799                format!(
2800                    "expected `{}`, found `{}`",
2801                    exp.display(tys),
2802                    at.display(tys)
2803                ),
2804            ));
2805        }
2806    }
2807    Some(tys.intern(effect))
2808}
2809
2810/// v0.98 (ADR 0125): resolve a storage-`Cell` operation `<cell>.<op>(args)` on a
2811/// `store Cell[T]` field. The single method-shaped cell op is `update(f)` —
2812/// `f: (T) -> T` — a read-modify-write typed `Effect[()]`. Reading a cell is the
2813/// bare-name sugar and writing it is `:=`, so `read`/`write` are not callable
2814/// methods (DECISION B). The combiner is a non-effectful `Ty::Fn`, so an
2815/// effectful body (including a bare read of another cell) fails the existing
2816/// function-type check (DECISION E). Dispatched by receiver provenance.
2817pub(crate) fn check_store_cell_op(
2818    method: &Ident,
2819    args: &[Expr],
2820    t: TyId,
2821    span: Span,
2822    ctx: &mut Ctx,
2823) -> Option<TyId> {
2824    let tys = ctx.tys;
2825    let tfn = || Ty::Fn {
2826        params: vec![t],
2827        ret: t,
2828    };
2829    let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2830        "update" => (vec![tys.intern(tfn())], tys.intern(Ty::Unit)),
2831        other => {
2832            ctx.errors.push(
2833                CompileError::new(
2834                    "bynk.store.unknown_op",
2835                    method.span,
2836                    format!("a `Cell` store field has no operation `{other}` — expected `update`"),
2837                )
2838                .with_note(
2839                    "a cell is read by its bare name and written with `:=`; `update` is the only \
2840                     method-shaped op",
2841                ),
2842            );
2843            for a in args {
2844                type_of(a, None, ctx);
2845            }
2846            return None;
2847        }
2848    };
2849    let effect = Ty::Effect(result);
2850    if args.len() != expected.len() {
2851        ctx.errors.push(CompileError::new(
2852            "bynk.types.call_arity",
2853            span,
2854            format!(
2855                "`Cell.{}` takes {} argument(s), found {}",
2856                method.name,
2857                expected.len(),
2858                args.len()
2859            ),
2860        ));
2861        for a in args {
2862            type_of(a, None, ctx);
2863        }
2864        return Some(tys.intern(effect));
2865    }
2866    for (a, exp) in args.iter().zip(expected.iter()) {
2867        if let Some(at) = type_of(a, Some(*exp), ctx)
2868            && !compatible(at, *exp, tys)
2869        {
2870            ctx.errors.push(CompileError::new(
2871                "bynk.types.argument_mismatch",
2872                a.span,
2873                format!(
2874                    "expected `{}`, found `{}`",
2875                    exp.display(tys),
2876                    at.display(tys)
2877                ),
2878            ));
2879        }
2880    }
2881    Some(tys.intern(effect))
2882}
2883
2884/// Constrained generics slice 4 (DECISION B, I): the explicit type-argument list
2885/// is admitted only for a user static on a generic type (`Box.empty[Int]()`) —
2886/// never for a qualified variant (`Opt.None[Int]`), whose parameters ground from
2887/// the expected type.
2888fn receiver_is_generic_static(receiver: &Expr, method: &Ident, ctx: &Ctx) -> bool {
2889    let ExprKind::Ident(id) = &receiver.kind else {
2890        return false;
2891    };
2892    ctx.lookup(id.name.as_str()).is_none()
2893        && ctx
2894            .input
2895            .types
2896            .get(&id.name)
2897            .is_some_and(|d| !d.type_params.is_empty())
2898        && ctx
2899            .input
2900            .methods
2901            .get(&id.name)
2902            .is_some_and(|t| t.statics.contains_key(&method.name))
2903}
2904
2905/// #2795: whether `recv_ty` is a user type whose instance method `method` has
2906/// type parameters of its own, the only receiver that takes explicit type
2907/// arguments on an instance call. They name the method's own parameters; the
2908/// receiver's are already ground.
2909fn receiver_has_generic_instance_method(recv_ty: TyId, method: &Ident, ctx: &Ctx) -> bool {
2910    let Ty::Named { name, .. } = &*ctx.tys.get(recv_ty) else {
2911        return false;
2912    };
2913    ctx.input
2914        .methods
2915        .get(name)
2916        .and_then(|t| t.instance.get(&method.name))
2917        .is_some_and(|m| !m.type_params.is_empty())
2918}
2919
2920fn reject_method_type_args(method: &Ident, args: &[Expr], span: Span, ctx: &mut Ctx) {
2921    ctx.errors.push(CompileError::new(
2922        "bynk.generics.type_arg_mismatch",
2923        span,
2924        format!(
2925            "`{}` does not take explicit type arguments — only a generic method with type parameters of its own does",
2926            method.name
2927        ),
2928    ));
2929    for a in args {
2930        let _ = type_of(a, None, ctx);
2931    }
2932}
2933
2934/// Record a built-in method call's resolved [`KernelOp`] and pass the checker's
2935/// result through. `op` is `None` for a spelling the receiver's kernel does not
2936/// have, which the kernel checker has then rejected (`method_not_found`), so no
2937/// callee is recorded; an *accepted* call with no op is a gap between the
2938/// checker's dispatch and [`crate::kernel_op`], a compiler bug.
2939fn record_kernel(
2940    ctx: &mut Ctx,
2941    expr_id: ExprId,
2942    recv: TyId,
2943    op: Option<KernelOp>,
2944    method: &Ident,
2945    result: Option<TyId>,
2946) -> Option<TyId> {
2947    match op {
2948        Some(op) => {
2949            ctx.callees.insert(expr_id, Callee::Kernel { recv, op });
2950        }
2951        // A debug assertion, not a hard one: this runs in the language server
2952        // on every edit, where a gap should not be a panic.
2953        None => debug_assert!(
2954            result.is_none(),
2955            "bynk internal error (#3164): kernel method `{}` was accepted but has no `KernelOp`",
2956            method.name
2957        ),
2958    }
2959    result
2960}
2961
2962/// #3277: type a method call on a handler's raw `cookies` (`RequestCookies`) and
2963/// record its kernel op.
2964fn check_request_cookies_call(
2965    method: &Ident,
2966    recv_ty: TyId,
2967    args: &[Expr],
2968    span: Span,
2969    expr_id: ExprId,
2970    ctx: &mut Ctx,
2971) -> Option<TyId> {
2972    let kop = RequestCookiesOp::from_name(&method.name);
2973    let r = check_request_cookies_method(method, kop, args, span, ctx);
2974    record_kernel(
2975        ctx,
2976        expr_id,
2977        recv_ty,
2978        kop.map(KernelOp::RequestCookies),
2979        method,
2980        r,
2981    )
2982}
2983
2984/// #3277: record and type `RequestCookies.of(…)` / `RequestCookies.empty()`.
2985fn check_request_cookies_static_call(
2986    method: &Ident,
2987    args: &[Expr],
2988    span: Span,
2989    expr_id: ExprId,
2990    ctx: &mut Ctx,
2991) -> Option<TyId> {
2992    if let Some(op) = StaticOp::resolve(IntrinsicNs::RequestCookies, &method.name) {
2993        ctx.callees.insert(expr_id, Callee::intrinsic(op));
2994    }
2995    check_request_cookies_static(method, args, span, ctx)
2996}
2997
2998/// Whether `receiver` names a capability: a bare local or declared one, or a cross-context one
2999/// (flattened `Cap` or qualified `B.Cap`).
3000fn receiver_names_capability(receiver: &Expr, ctx: &Ctx) -> bool {
3001    matches!(&receiver.kind, ExprKind::Ident(id)
3002            if ctx.caps.capabilities.contains_key(&id.name)
3003                || ctx.caps.declared_capabilities.contains_key(&id.name))
3004        || flatten_ident_chain(receiver).is_some_and(|chain| {
3005            ctx.input
3006                .cross_context
3007                .resolve_cross_capability(&chain)
3008                .is_some()
3009        })
3010}
3011
3012#[allow(clippy::too_many_arguments)]
3013pub(crate) fn check_method_call(
3014    receiver: &Expr,
3015    method: &Ident,
3016    type_args: &[TypeRef],
3017    args: &[Expr],
3018    span: Span,
3019    expected: Option<TyId>,
3020    // P6.0 (#1139): the outer `MethodCall` expression's own identity.
3021    expr_id: ExprId,
3022    ctx: &mut Ctx,
3023) -> Option<TyId> {
3024    let tys = ctx.tys;
3025    // v0.22b: explicit type arguments apply only to the `Json.decode[T]`
3026    // static — every other method/static takes none (the 0039/0045 rule). A
3027    // user-declared type named `Json` shadows the codec module and takes no type
3028    // arguments. #594: a generic *user* instance method infers its type
3029    // arguments from the receiver and the argument types; #2795: an explicit
3030    // `x.map[U](…)` names the method's own parameters only (the receiver's are
3031    // already ground), and is admitted once the receiver's type is known.
3032    // #926: a capability operation may declare its own type parameter(s),
3033    // resolved only from an explicit call-site type argument (never
3034    // inferred) — the same explicit-only discipline as `Json.decode[T]`, so
3035    // it joins that carve-out rather than `#594`'s inference. Covers a bare
3036    // local/declared capability receiver and a cross-context one (flattened
3037    // `Cap.op[T](…)` or qualified `B.Cap.op[T](…)`); arity/substitution
3038    // happens downstream in `check_static_call` /
3039    // `check_cross_context_capability_call`.
3040    let receiver_is_capability = receiver_names_capability(receiver, ctx);
3041    // #2795: a receiver that is a value may be a generic user instance method's
3042    // receiver, so the verdict waits for its type (below); any other shape is
3043    // refused here as before.
3044    let value_receiver = ctx.lookup_root_ident(receiver).is_some()
3045        || ctx.root_ident_is_store_field(receiver)
3046        || flatten_ident_chain(receiver).is_none();
3047    let type_args_pending = !type_args.is_empty()
3048        && !matches!(&receiver.kind, ExprKind::Ident(id) if (id.name == JSON || id.name == YAML || id.name == FORM)
3049            && !ctx.input.types.contains_key(id.name.as_str()))
3050        && !receiver_is_capability
3051        && !receiver_is_generic_static(receiver, method, ctx);
3052    if type_args_pending && !value_receiver {
3053        reject_method_type_args(method, args, span, ctx);
3054        return None;
3055    }
3056    if let Some(r) = super::peek::check_peek_call(
3057        receiver, method, type_args, args, span, expected, expr_id, ctx,
3058    ) {
3059        return r;
3060    }
3061    if let Some(r) = super::kernels::check_cookie_call(receiver, method, args, span, expr_id, ctx) {
3062        return r;
3063    }
3064    // v0.25 / v0.178: a test body invokes the target's service as
3065    // `svc.call(args)`. The emitter wires the call from the same service set;
3066    // the checker resolves the service's `on call` handler and verifies the
3067    // call's arity and argument types (v0.178, #662 — before this, the branch
3068    // matched the literal method name `call` without checking the handler
3069    // exists, so `api.call(…)` on a `from http` service passed `check` and
3070    // crashed at runtime, #654). #1934: the call is typed by what the handler
3071    // yields, and the binding edge is recorded for test-file references. Returns here: the
3072    // resolution must not fall through to the receiver walk, which would
3073    // report the service name as unknown (#504 backstop).
3074    if let ExprKind::Ident(id) = &receiver.kind
3075        && ctx.lookup(id.name.as_str()).is_none()
3076        && let Some(sig) = ctx.test_services.get(&id.name).cloned()
3077    {
3078        if let Some(unit) = ctx.input.cross_context.self_context.clone() {
3079            ctx.refs
3080                .record_in_unit(id.span, SymbolKind::Service, &id.name, &unit);
3081        }
3082        return check_test_service_address(&sig, id, method, args, expr_id, ctx);
3083    }
3084    // v0.6: cross-context service call. Two shapes:
3085    //   - `Alias.service(args)`           where Alias is from `consumes X as Alias`
3086    //   - `prefix.tail.service(args)`     where `prefix.tail` is a consumed context's
3087    //                                     qualified name (parsed as nested FieldAccess).
3088    // The full-qualified-name form must be checked before the bare-ident form
3089    // (the prefix's first segment doesn't resolve as anything local).
3090    if ctx.lookup_root_ident(receiver).is_none() && !ctx.root_ident_is_store_field(receiver) {
3091        // v0.15: cross-context capability call — `B.Cap.op(args)` /
3092        // `Alias.Cap.op(args)`. Checked before the service-call shape because
3093        // the receiver carries an extra (capability) segment.
3094        if let Some(chain) = flatten_ident_chain(receiver)
3095            && let Some((consumed, cap)) = ctx.input.cross_context.resolve_cross_capability(&chain)
3096        {
3097            // v0.25: the capability name-segment (`Cap` in `B.Cap` /
3098            // `Alias.Cap`) is the outermost field of the receiver chain.
3099            if let ExprKind::FieldAccess { field, .. } = &receiver.kind {
3100                ctx.refs
3101                    .record_in_unit(field.span, SymbolKind::Capability, &cap, &consumed);
3102            }
3103            return check_cross_context_capability_call(
3104                receiver, &consumed, &cap, method, type_args, args, span, expr_id, ctx,
3105            );
3106        }
3107        if let Some(consumed) = cross_context_prefix(receiver, ctx) {
3108            return check_cross_context_call(receiver, &consumed, method, args, span, expr_id, ctx);
3109        }
3110        // Looks like a dotted prefix (no local binding for the root). If the
3111        // chain matches the shape of a consumed-context call but the prefix
3112        // isn't actually consumed, surface an explicit diagnostic so the user
3113        // can fix the missing `consumes` clause rather than seeing a silent
3114        // "no methods" error later.
3115        //
3116        // #1930: not for a chain rooted in an asset (`sheet.url.startsWith(…)`),
3117        // which is a method on the asset's `url`. Only here, after both
3118        // resolutions above failed: an asset named like a consumed context's
3119        // root segment (`shop` beside `consumes shop.payment`) still lets a
3120        // real cross-context call resolve (review of #1937).
3121        if let ExprKind::FieldAccess { .. } = &receiver.kind
3122            && !ctx.root_ident_is_asset(receiver)
3123            && let Some(chain) = flatten_ident_chain(receiver)
3124            && chain.contains('.')
3125        {
3126            let info = &ctx.input.cross_context;
3127            let in_context = info.self_context.is_some();
3128            if in_context && info.resolve_prefix(&chain).is_none() {
3129                ctx.errors.push(
3130                    CompileError::new(
3131                        "bynk.resolve.unconsumed_context",
3132                        receiver.span,
3133                        format!(
3134                            "`{chain}.{}` looks like a cross-context service call, but `{chain}` is not in this context's `consumes` clauses",
3135                            method.name
3136                        ),
3137                    )
3138                    .with_note(
3139                        "add a `consumes {chain}` clause at the top of the context, or use an alias and call it through the alias",
3140                    ),
3141                );
3142                for a in args {
3143                    let _ = type_of(a, None, ctx);
3144                }
3145                return None;
3146            }
3147        }
3148    }
3149    // Detect capability call (v0.5): receiver is a bare Ident naming a
3150    // capability declared in the context (in scope via `given`, or declared
3151    // but undeclared in `given` — the static-call path emits the error).
3152    if let ExprKind::Ident(id) = &receiver.kind
3153        && ctx.lookup(id.name.as_str()).is_none()
3154        && (ctx.caps.capabilities.contains_key(&id.name)
3155            || ctx.caps.declared_capabilities.contains_key(&id.name))
3156    {
3157        return check_static_call(id, method, type_args, args, span, expected, expr_id, ctx);
3158    }
3159    // Detect static-call shape: receiver is a bare Ident naming a declared
3160    // type (not a local/param). Dispatch to check_static_call. `type_args` is
3161    // always empty here — `check_method_call`'s gate above only admits a
3162    // non-empty slice for a capability (handled just above) or the `Json`
3163    // codec (handled separately, `check_json_static`).
3164    if let ExprKind::Ident(id) = &receiver.kind
3165        && ctx.lookup(id.name.as_str()).is_none()
3166        && ctx.input.types.contains_key(&id.name)
3167    {
3168        return check_static_call(id, method, type_args, args, span, expected, expr_id, ctx);
3169    }
3170    // v0.20b: qualified statics on the built-in collection types —
3171    // `List.empty()` / `Map.empty()`. Like an empty `[]`, they need an
3172    // expected type to pin their element/key/value types.
3173    if let ExprKind::Ident(id) = &receiver.kind
3174        && ctx.lookup(id.name.as_str()).is_none()
3175        && !ctx.input.types.contains_key(&id.name)
3176        && (id.name == LIST || id.name == MAP || id.name == SET)
3177    {
3178        let ns = if id.name == LIST {
3179            IntrinsicNs::List
3180        } else if id.name == MAP {
3181            IntrinsicNs::Map
3182        } else {
3183            IntrinsicNs::Set
3184        };
3185        if let Some(op) = StaticOp::resolve(ns, &method.name) {
3186            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3187        }
3188        return check_collection_static(id, method, args, span, expected, ctx);
3189    }
3190    // v0.22a: the numeric parse statics — `Int.parse(s)` / `Float.parse(s)`.
3191    // The parser only admits these keywords in receiver position when
3192    // followed by `.`, so the Ident shape here is exactly the static form.
3193    if let ExprKind::Ident(id) = &receiver.kind
3194        && (id.name == INT || id.name == FLOAT)
3195    {
3196        let ns = if id.name == INT {
3197            IntrinsicNs::Int
3198        } else {
3199            IntrinsicNs::Float
3200        };
3201        if let Some(op) = StaticOp::resolve(ns, &method.name) {
3202            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3203        }
3204        return check_numeric_parse_static(id, method, args, span, ctx);
3205    }
3206    // #2622: the `Decimal` statics — `Decimal.parse(s)` / `Decimal.fromInt(n)`.
3207    if let ExprKind::Ident(id) = &receiver.kind
3208        && id.name == DECIMAL
3209        && ctx.lookup(DECIMAL).is_none()
3210        && !ctx.input.types.contains_key(DECIMAL)
3211    {
3212        if let Some(op) = StaticOp::resolve(IntrinsicNs::Decimal, &method.name) {
3213            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3214        }
3215        return check_decimal_static(method, args, span, ctx);
3216    }
3217    // v0.86 (ADR 0112): the `Duration.millis(n)` static constructor — the way to
3218    // build a `Duration` from a runtime `Int` (the literal covers constants).
3219    if let ExprKind::Ident(id) = &receiver.kind
3220        && id.name == DURATION
3221        && ctx.lookup(DURATION).is_none()
3222        && !ctx.input.types.contains_key(DURATION)
3223    {
3224        if let Some(op) = StaticOp::resolve(IntrinsicNs::Duration, &method.name) {
3225            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3226        }
3227        return check_duration_static(method, args, span, ctx);
3228    }
3229    // v0.90 (ADR 0114 D6): the `Instant.fromEpochMillis(n)` static constructor.
3230    if let ExprKind::Ident(id) = &receiver.kind
3231        && id.name == INSTANT
3232        && ctx.lookup(INSTANT).is_none()
3233        && !ctx.input.types.contains_key(INSTANT)
3234    {
3235        if let Some(op) = StaticOp::resolve(IntrinsicNs::Instant, &method.name) {
3236            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3237        }
3238        return check_instant_static(method, args, span, ctx);
3239    }
3240    // v0.110 (ADR 0142 D2): the `Bytes` static constructors —
3241    // `Bytes.fromUtf8(s)` / `Bytes.fromBase64(s)` / `Bytes.empty()`.
3242    if let ExprKind::Ident(id) = &receiver.kind
3243        && id.name == BYTES
3244        && ctx.lookup(BYTES).is_none()
3245        && !ctx.input.types.contains_key(BYTES)
3246    {
3247        if let Some(op) = StaticOp::resolve(IntrinsicNs::Bytes, &method.name) {
3248            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3249        }
3250        return check_bytes_static(method, args, span, ctx);
3251    }
3252    // #2380 (L5): `TokenClaims.of(lines)` — how a test builds the claims an
3253    // `Oidc` actor's handler reads.
3254    if let ExprKind::Ident(id) = &receiver.kind
3255        && id.name == TOKEN_CLAIMS
3256        && ctx.lookup(TOKEN_CLAIMS).is_none()
3257        && !ctx.input.types.contains_key(TOKEN_CLAIMS)
3258    {
3259        if let Some(op) = StaticOp::resolve(IntrinsicNs::TokenClaims, &method.name) {
3260            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3261        }
3262        return check_token_claims_static(method, args, span, ctx);
3263    }
3264    // #2341 (L4): `RequestHeaders.of(lines)` / `RequestHeaders.empty()` — how
3265    // a test builds the headers an HTTP handler reads.
3266    if let ExprKind::Ident(id) = &receiver.kind
3267        && id.name == REQUEST_HEADERS
3268        && ctx.lookup(REQUEST_HEADERS).is_none()
3269        && !ctx.input.types.contains_key(REQUEST_HEADERS)
3270    {
3271        if let Some(op) = StaticOp::resolve(IntrinsicNs::RequestHeaders, &method.name) {
3272            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3273        }
3274        return check_request_headers_static(method, args, span, ctx);
3275    }
3276    // #2854: `RequestQuery.of(pairs)` / `RequestQuery.empty()` — how a test
3277    // builds the raw query view an HTTP handler reads.
3278    if let ExprKind::Ident(id) = &receiver.kind
3279        && id.name == REQUEST_QUERY
3280        && ctx.lookup(REQUEST_QUERY).is_none()
3281        && !ctx.input.types.contains_key(REQUEST_QUERY)
3282    {
3283        if let Some(op) = StaticOp::resolve(IntrinsicNs::RequestQuery, &method.name) {
3284            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3285        }
3286        return check_request_query_static(method, args, span, ctx);
3287    }
3288    // #3277: `RequestCookies.of(pairs)` / `RequestCookies.empty()`, the test-side
3289    // way to build the raw cookies view a handler reads.
3290    if let ExprKind::Ident(id) = &receiver.kind
3291        && id.name == REQUEST_COOKIES
3292        && ctx.lookup(REQUEST_COOKIES).is_none()
3293        && !ctx.input.types.contains_key(REQUEST_COOKIES)
3294    {
3295        return check_request_cookies_static_call(method, args, span, expr_id, ctx);
3296    }
3297    // v0.22b: the typed JSON codec statics (ADR 0045).
3298    if let ExprKind::Ident(id) = &receiver.kind
3299        && id.name == JSON
3300        && ctx.lookup(JSON).is_none()
3301        && !ctx.input.types.contains_key(JSON)
3302    {
3303        if let Some(op) = StaticOp::resolve(IntrinsicNs::Json, &method.name) {
3304            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3305        }
3306        return check_json_static(JSON, method, type_args, args, span, expected, ctx);
3307    }
3308    // #3214: `Yaml.decode[T]`, the YAML front end of the same typed decode.
3309    if let ExprKind::Ident(id) = &receiver.kind
3310        && id.name == YAML
3311        && ctx.lookup(YAML).is_none()
3312        && !ctx.input.types.contains_key(YAML)
3313    {
3314        if let Some(op) = StaticOp::resolve(IntrinsicNs::Yaml, &method.name) {
3315            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3316        }
3317        return check_json_static(YAML, method, type_args, args, span, expected, ctx);
3318    }
3319    // #3276: `Form.decode[T]` / `Form.encode(v)`, the form-body mapping as a codec.
3320    if let ExprKind::Ident(id) = &receiver.kind
3321        && id.name == FORM
3322        && ctx.lookup(FORM).is_none()
3323        && !ctx.input.types.contains_key(FORM)
3324    {
3325        if let Some(op) = StaticOp::resolve(IntrinsicNs::Form, &method.name) {
3326            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3327        }
3328        return check_json_static(FORM, method, type_args, args, span, expected, ctx);
3329    }
3330    // v0.100: the `Stream.of(xs)` static constructor (real-time track slice 0).
3331    if let ExprKind::Ident(id) = &receiver.kind
3332        && id.name == STREAM
3333        && ctx.lookup(STREAM).is_none()
3334        && !ctx.input.types.contains_key(STREAM)
3335    {
3336        if let Some(op) = StaticOp::resolve(IntrinsicNs::Stream, &method.name) {
3337            ctx.callees.insert(expr_id, Callee::intrinsic(op));
3338        }
3339        return check_stream_static(method, args, span, ctx);
3340    }
3341    // v0.20b: `insert`/`prepend` return their receiver's collection type —
3342    // propagate an expected collection type down the chain so
3343    // `let m: Map[String, Int] = Map.empty().insert("a", 1)` infers. #1889:
3344    // `append`/`concat` return their receiver's list type too.
3345    let recv_expected = match (expected, method.name.as_str()) {
3346        (Some(t), "insert") => peel_to_map(t, tys)
3347            .map(|(k, v)| tys.intern(Ty::Map(k, v)))
3348            .or_else(|| peel_to_set(t, tys).map(|e| tys.intern(Ty::Set(e)))),
3349        (Some(t), "remove") => peel_to_set(t, tys).map(|e| tys.intern(Ty::Set(e))),
3350        (Some(t), "prepend" | "append" | "concat") => {
3351            peel_to_list(t, tys).map(|e| tys.intern(Ty::List(e)))
3352        }
3353        _ => None,
3354    };
3355    let recv_ty = type_of(receiver, recv_expected, ctx)?;
3356    if type_args_pending && !receiver_has_generic_instance_method(recv_ty, method, ctx) {
3357        reject_method_type_args(method, args, span, ctx);
3358        return None;
3359    }
3360    // v0.20b: built-in kernel methods on the collection types. These are
3361    // compiler-known special forms typed directly here — generic in their
3362    // accumulator without the (deferred) declared-generic-methods feature;
3363    // the deferral bites only on declared methods (ADR 0037).
3364    match &*tys.get(recv_ty) {
3365        Ty::List(elem) => {
3366            let kop = ListOp::from_name(&method.name);
3367            let r = check_list_kernel_method(method, kop, args, *elem, span, ctx);
3368            par::reject_store_write_in_closure(method, args, ctx);
3369            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::List), method, r);
3370        }
3371        // v0.91 (ADR 0115): a chained builder/terminal on a lazy `Query[T]`.
3372        Ty::Query(elem) => {
3373            let kop = QueryOp::from_name(&method.name);
3374            let r = check_query_kernel_method(method, kop, args, *elem, span, ctx);
3375            par::reject_store_write_in_closure(method, args, ctx);
3376            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Query), method, r);
3377        }
3378        // v0.100: a chained builder/terminal on a `Stream[T]`.
3379        Ty::Stream(elem) => {
3380            let kop = StreamOp::from_name(&method.name);
3381            let r = check_stream_kernel_method(method, kop, args, *elem, span, ctx);
3382            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Stream), method, r);
3383        }
3384        // v0.102: the held-resource operations on a `Connection[F]` — `send(f)`
3385        // (non-consuming) and `close()` (consuming). The linearity pass tracks
3386        // the ownership transitions; this types the operations.
3387        Ty::Connection(frame) => {
3388            let kop = ConnectionOp::from_name(&method.name);
3389            let r = check_connection_method(method, kop, args, *frame, span, ctx);
3390            return record_kernel(
3391                ctx,
3392                expr_id,
3393                recv_ty,
3394                kop.map(KernelOp::Connection),
3395                method,
3396                r,
3397            );
3398        }
3399        // #3051: a case's recording `TestConnection[F]`.
3400        Ty::TestConnection(frame) => {
3401            let kop = TestConnectionOp::from_name(&method.name);
3402            let r = check_test_connection_method(method, kop, args, *frame, span, ctx);
3403            return record_kernel(
3404                ctx,
3405                expr_id,
3406                recv_ty,
3407                kop.map(KernelOp::TestConnection),
3408                method,
3409                r,
3410            );
3411        }
3412        Ty::Map(key, val) => {
3413            let kop = MapOp::from_name(&method.name);
3414            let r = check_map_kernel_method(method, kop, args, *key, *val, span, ctx);
3415            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Map), method, r);
3416        }
3417        // K6a (#2596): the `Set` kernel.
3418        Ty::Set(elem) => {
3419            let kop = SetOp::from_name(&method.name);
3420            let r = check_set_kernel_method(method, kop, args, *elem, span, ctx);
3421            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Set), method, r);
3422        }
3423        // v0.21: the numeric kernel — conversions as value methods on the
3424        // bare base types. A refined value reaches these too, but via the
3425        // refined-receiver fallback below (after its own declared methods),
3426        // not via any `.raw` surface — a refined type's only source-level
3427        // constructors are `.of` and literal admission (ADR 0182); unlike an
3428        // opaque type it exposes no `.unsafe` (that is opaque-only, confined
3429        // to the defining commons).
3430        Ty::Base(base @ (BaseType::Int | BaseType::Float)) => {
3431            let op = match *base {
3432                BaseType::Int => IntOp::from_name(&method.name).map(KernelOp::Int),
3433                _ => FloatOp::from_name(&method.name).map(KernelOp::Float),
3434            };
3435            let r = check_numeric_kernel_method(method, op, args, *base, span, ctx);
3436            return record_kernel(ctx, expr_id, recv_ty, op, method, r);
3437        }
3438        // v0.86 (ADR 0112): the `Duration` kernel — `toMillis`/`toString`.
3439        Ty::Base(BaseType::Duration) => {
3440            let kop = DurationOp::from_name(&method.name);
3441            let r = check_duration_kernel_method(method, kop, args, span, ctx);
3442            return record_kernel(
3443                ctx,
3444                expr_id,
3445                recv_ty,
3446                kop.map(KernelOp::Duration),
3447                method,
3448                r,
3449            );
3450        }
3451        // v0.90 (ADR 0114): the `Instant` kernel — `toEpochMillis`/`toString`.
3452        Ty::Base(BaseType::Instant) => {
3453            let kop = InstantOp::from_name(&method.name);
3454            let r = check_instant_kernel_method(method, kop, args, span, ctx);
3455            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Instant), method, r);
3456        }
3457        // #2341 (decision A): an HTTP handler's `headers` — `get`, `bearer`,
3458        // `clientIp`.
3459        Ty::RequestHeaders => {
3460            let kop = RequestHeadersOp::from_name(&method.name);
3461            let r = check_request_headers_method(method, kop, args, span, ctx);
3462            return record_kernel(
3463                ctx,
3464                expr_id,
3465                recv_ty,
3466                kop.map(KernelOp::RequestHeaders),
3467                method,
3468                r,
3469            );
3470        }
3471        // #3277: an `HttpResult[T]` — `withCookie`, `clearCookie`, `cookies`.
3472        Ty::HttpResult(_) => {
3473            let kop = HttpResultOp::from_name(&method.name);
3474            let r = check_http_result_method(method, kop, recv_ty, args, span, ctx);
3475            return record_kernel(
3476                ctx,
3477                expr_id,
3478                recv_ty,
3479                kop.map(KernelOp::HttpResult),
3480                method,
3481                r,
3482            );
3483        }
3484        // #2854 (decision B): an HTTP handler's `query` — `get`, `all`, `params`.
3485        Ty::RequestQuery => {
3486            let kop = RequestQueryOp::from_name(&method.name);
3487            let r = check_request_query_method(method, kop, args, span, ctx);
3488            return record_kernel(
3489                ctx,
3490                expr_id,
3491                recv_ty,
3492                kop.map(KernelOp::RequestQuery),
3493                method,
3494                r,
3495            );
3496        }
3497        // #3277: an HTTP handler's raw `cookies` — `get`, `all`, `names`.
3498        Ty::RequestCookies => {
3499            return check_request_cookies_call(method, recv_ty, args, span, expr_id, ctx);
3500        }
3501        // #2380 (L5): an `Oidc` binder's claims — `get`, `has`.
3502        Ty::TokenClaims => {
3503            let kop = TokenClaimsOp::from_name(&method.name);
3504            let r = check_token_claims_method(method, kop, args, span, ctx);
3505            return record_kernel(
3506                ctx,
3507                expr_id,
3508                recv_ty,
3509                kop.map(KernelOp::TokenClaims),
3510                method,
3511                r,
3512            );
3513        }
3514        // v0.110 (ADR 0142): the `Bytes` kernel — `length`/`toBase64`/`decodeUtf8`.
3515        Ty::Base(BaseType::Bytes) => {
3516            let kop = BytesOp::from_name(&method.name);
3517            let r = check_bytes_kernel_method(method, kop, args, span, ctx);
3518            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Bytes), method, r);
3519        }
3520        // #2622: the `Decimal` kernel.
3521        Ty::Base(BaseType::Decimal) => {
3522            let kop = DecimalOp::from_name(&method.name);
3523            let r = check_decimal_kernel_method(method, kop, args, span, ctx);
3524            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Decimal), method, r);
3525        }
3526        // v0.22a: the string kernel (ADR 0046).
3527        Ty::Base(BaseType::String) => {
3528            let kop = StringOp::from_name(&method.name);
3529            let r = check_string_kernel_method(method, kop, args, span, ctx);
3530            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::String), method, r);
3531        }
3532        // v0.22a: the Option/Result combinators as kernel methods (ADR 0048).
3533        Ty::Option(inner) => {
3534            let kop = OptionOp::from_name(&method.name);
3535            let r = check_option_kernel_method(method, kop, args, *inner, span, ctx);
3536            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Option), method, r);
3537        }
3538        Ty::Result(ok, err) => {
3539            let kop = ResultOp::from_name(&method.name);
3540            let r = check_result_kernel_method(method, kop, args, *ok, *err, span, ctx);
3541            return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Result), method, r);
3542        }
3543        // The `Effect[Result[T, E]]` combinators (§2.8.3): `mapOk`/`mapErr`/
3544        // `flatMapOk`/`flatMapErr` on the universal cross-context shape. Only an
3545        // `Effect` wrapping a `Result` has methods; any other `Effect[_]` falls
3546        // through to the "no methods" error below.
3547        Ty::Effect(inner) => {
3548            // #2683, #2711, #3437: `within`, `race` and `detach` are on every
3549            // `Effect[T]`, and win over the `Effect[Result]` combinators (they are
3550            // not among them), so `Effect[Result[T, E]].within(d)` is the plain
3551            // nested case.
3552            if matches!(method.name.as_str(), "within" | "race" | "detach") {
3553                let op = EffectOp::from_name(&method.name).map(KernelOp::Effect);
3554                let r = check_effect_method(method, receiver, args, *inner, span, ctx);
3555                return record_kernel(ctx, expr_id, recv_ty, op, method, r);
3556            }
3557            if let Ty::Result(ok, err) = &*tys.get(*inner) {
3558                let kop = EffectResultOp::from_name(&method.name);
3559                let r = check_effect_result_kernel_method(method, kop, args, *ok, *err, span, ctx);
3560                return record_kernel(
3561                    ctx,
3562                    expr_id,
3563                    recv_ty,
3564                    kop.map(KernelOp::EffectResult),
3565                    method,
3566                    r,
3567                );
3568            }
3569        }
3570        _ => {}
3571    }
3572    // Find a named type for the receiver, then look up its instance methods.
3573    let type_name = match &*tys.get(recv_ty) {
3574        Ty::Named { name, .. } => name.clone(),
3575        _ => {
3576            ctx.errors.push(CompileError::new(
3577                "bynk.types.method_on_non_named_type",
3578                method.span,
3579                format!(
3580                    "type `{}` has no methods — only user-declared types support method calls",
3581                    recv_ty.display(tys)
3582                ),
3583            ));
3584            return None;
3585        }
3586    };
3587    // Agent handler dispatch: when the receiver is an agent instance, look
3588    // up the method against the agent's declared `on call` handlers and
3589    // resolve to the handler's return type.
3590    if let Some(agent) = ctx.input.agents.get(&type_name).cloned() {
3591        let Some(handler) = agent.handlers.iter().find(|h| {
3592            h.method_name
3593                .as_ref()
3594                .is_some_and(|n| n.name == method.name)
3595        }) else {
3596            ctx.errors.push(CompileError::new(
3597                "bynk.agent.handler_not_found",
3598                method.span,
3599                format!(
3600                    "agent `{}` has no handler named `{}`",
3601                    type_name, method.name
3602                ),
3603            ));
3604            for a in args {
3605                let _ = type_of(a, None, ctx);
3606            }
3607            return None;
3608        };
3609        ctx.callees.insert(
3610            expr_id,
3611            Callee::Agent {
3612                agent: type_name.clone(),
3613                handler: method.name.clone(),
3614            },
3615        );
3616        // #304: the handler is a first-class index symbol, keyed by the
3617        // compound `"Agent.handler"` name — same convention and same
3618        // recorded-regardless-of-downstream-errors placement as the
3619        // ordinary instance-method call below.
3620        ctx.refs.record(
3621            method.span,
3622            SymbolKind::Handler,
3623            &format!("{type_name}.{}", method.name),
3624        );
3625        if handler.params.len() != args.len() {
3626            ctx.errors.push(CompileError::new(
3627                "bynk.agent.handler_arity",
3628                method.span,
3629                format!(
3630                    "agent handler `{}.{}` expects {} argument(s), but {} were given",
3631                    type_name,
3632                    method.name,
3633                    handler.params.len(),
3634                    args.len()
3635                ),
3636            ));
3637            for a in args {
3638                let _ = type_of(a, None, ctx);
3639            }
3640            return None;
3641        }
3642        for (p, arg) in handler.params.iter().zip(args.iter()) {
3643            let pty = resolve_type_ref(&p.type_ref, &ctx.input.types, tys);
3644            let arg_ty = type_of(arg, pty, ctx);
3645            if let (Some(a), Some(p_ty)) = (arg_ty, pty.as_ref())
3646                && !compatible(a, *p_ty, tys)
3647            {
3648                ctx.errors.push(CompileError::new(
3649                    "bynk.types.argument_mismatch",
3650                    arg.span,
3651                    format!(
3652                        "argument has type `{}`, but `{}.{}` expects `{}`",
3653                        a.display(tys),
3654                        type_name,
3655                        method.name,
3656                        p_ty.display(tys)
3657                    ),
3658                ));
3659            }
3660        }
3661        return resolve_type_ref(&handler.return_type, &ctx.input.types, tys);
3662    }
3663    let table = ctx
3664        .input
3665        .methods
3666        .get(&type_name)
3667        .cloned()
3668        .unwrap_or_default();
3669    let Some(method_decl) = table.instance.get(&method.name).cloned() else {
3670        // #561: a refined receiver inherits its base type's read-only kernel
3671        // methods as a fallback *after* its own declared methods (DECISION D).
3672        // A refined value erases to its base at runtime, so the base methods
3673        // already apply bit-for-bit; only the checker had to be taught to look.
3674        // Results are base-typed (DECISION B) and refined arguments widen via
3675        // `compatible`, so the base kernel checkers need no change. The match
3676        // is `Refined` only — opaque types deliberately do not widen, so they
3677        // keep reporting `method_not_found`. `Bool` (and any base without a
3678        // kernel) inherits nothing and falls through to the same error.
3679        if let Ty::Named {
3680            kind: NamedKind::Refined(base),
3681            ..
3682        } = &*tys.get(recv_ty)
3683        {
3684            let op = KernelOp::for_base(*base, &method.name);
3685            let r = match base {
3686                BaseType::Int | BaseType::Float => {
3687                    check_numeric_kernel_method(method, op, args, *base, span, ctx)
3688                }
3689                BaseType::String => check_string_kernel_method(
3690                    method,
3691                    StringOp::from_name(&method.name),
3692                    args,
3693                    span,
3694                    ctx,
3695                ),
3696                BaseType::Duration => check_duration_kernel_method(
3697                    method,
3698                    DurationOp::from_name(&method.name),
3699                    args,
3700                    span,
3701                    ctx,
3702                ),
3703                BaseType::Instant => check_instant_kernel_method(
3704                    method,
3705                    InstantOp::from_name(&method.name),
3706                    args,
3707                    span,
3708                    ctx,
3709                ),
3710                BaseType::Bytes => check_bytes_kernel_method(
3711                    method,
3712                    BytesOp::from_name(&method.name),
3713                    args,
3714                    span,
3715                    ctx,
3716                ),
3717                BaseType::Decimal => check_decimal_kernel_method(
3718                    method,
3719                    DecimalOp::from_name(&method.name),
3720                    args,
3721                    span,
3722                    ctx,
3723                ),
3724                // `Bool` has no kernel: fall through to `method_not_found`.
3725                BaseType::Bool => None,
3726            };
3727            if !matches!(base, BaseType::Bool) {
3728                return record_kernel(ctx, expr_id, recv_ty, op, method, r);
3729            }
3730        }
3731        ctx.errors.push(CompileError::new(
3732            "bynk.types.method_not_found",
3733            method.span,
3734            format!(
3735                "type `{}` has no instance method named `{}`",
3736                type_name, method.name
3737            ),
3738        ));
3739        return None;
3740    };
3741    // v0.36 (ADR 0069): the method is a first-class index symbol, keyed by the
3742    // compound `"Type.method"` name. Recorded already-spelled from the resolved
3743    // receiver type; the bare edge resolves through the same `uses`/`consumes`
3744    // qualification as cross-file type references.
3745    ctx.refs.record(
3746        method.span,
3747        SymbolKind::Method,
3748        &format!("{type_name}.{}", method.name),
3749    );
3750    ctx.callees.insert(
3751        expr_id,
3752        Callee::Method(Arc::clone(&method_decl), Vec::new()),
3753    );
3754    // #594: a generic instance method — one on a generic receiver, or one
3755    // carrying its own type parameters — resolves its parameter and return
3756    // types against a substitution seeded from the receiver's type arguments,
3757    // then infers the method's own parameters from the argument types
3758    // (argument-directed unification, ADR 0029). A method on a non-generic
3759    // receiver with no own type parameters takes the plain path below,
3760    // byte-identically to before.
3761    let recv_type_params: Vec<String> = ctx
3762        .input
3763        .types
3764        .get(&type_name)
3765        .map(|d| d.type_params.iter().map(|p| p.name.name.clone()).collect())
3766        .unwrap_or_default();
3767    if !recv_type_params.is_empty() || !method_decl.type_params.is_empty() {
3768        let ret = check_generic_method_call(
3769            &type_name,
3770            &recv_type_params,
3771            Some(recv_ty),
3772            &method_decl,
3773            method,
3774            type_args,
3775            args,
3776            expected,
3777            ctx,
3778        );
3779        // Slice 1: the comparator witnesses the generic-call path resolved.
3780        if let Some(witnesses) = ctx.last_witness.take() {
3781            ctx.callees
3782                .insert(expr_id, Callee::Method(Arc::clone(&method_decl), witnesses));
3783        }
3784        return ret;
3785    }
3786    // Param count excludes the implicit `self`.
3787    if method_decl.params.len() != args.len() {
3788        ctx.errors.push(
3789            CompileError::new(
3790                "bynk.types.method_arity",
3791                method.span,
3792                format!(
3793                    "method `{}.{}` expects {} argument(s), but {} were given",
3794                    type_name,
3795                    method.name,
3796                    method_decl.params.len(),
3797                    args.len()
3798                ),
3799            )
3800            .with_label(method_decl.name.ident().span, "method declared here"),
3801        );
3802        for a in args {
3803            let _ = type_of(a, None, ctx);
3804        }
3805        return None;
3806    }
3807    let mut ok = true;
3808    for (i, (param, arg)) in method_decl.params.iter().zip(args.iter()).enumerate() {
3809        record_param_hint(ctx.hints, &param.name.name, arg);
3810        let expected = resolve_type_ref(&param.type_ref, &ctx.input.types, tys);
3811        let actual = type_of(arg, expected, ctx);
3812        let (Some(actual), Some(expected)) = (actual, expected) else {
3813            ok = false;
3814            continue;
3815        };
3816        if !compatible(actual, expected, tys) {
3817            ctx.errors.push(CompileError::new(
3818                "bynk.types.argument_mismatch",
3819                arg.span,
3820                format!(
3821                    "argument {} to `{}.{}` has type `{}`, but parameter `{}` expects `{}`",
3822                    i + 1,
3823                    type_name,
3824                    method.name,
3825                    actual.display(tys),
3826                    param.name.name,
3827                    expected.display(tys)
3828                ),
3829            ));
3830            ok = false;
3831        }
3832    }
3833    let _ = span;
3834    if !ok {
3835        return None;
3836    }
3837    resolve_type_ref(&method_decl.return_type, &ctx.input.types, tys)
3838}
3839
3840/// #594: type-check a call to a generic instance method — one attached to a
3841/// generic type (so `self` carries the type's parameters) and/or carrying its
3842/// own `[U]` parameters. Mirrors [`check_generic_call`] (the free-function
3843/// path, ADR 0029): resolve the method's parameter/return patterns with the
3844/// rigid vars in scope, seed the substitution from the receiver's concrete type
3845/// arguments, then drive argument-directed inference over the method's own
3846/// parameters. The receiver's parameters are already ground (from the receiver
3847/// type), so only the method's own parameters need inferring.
3848///
3849/// Constrained generics slice 4: the same function checks a generic *static*
3850/// (`recv_ty` is `None`). A static has no receiver to seed from, so the type's
3851/// parameters are inferred like the method's own — from the arguments, then the
3852/// expected type, or from the explicit `type_args` (the type's parameters, then
3853/// the method's own, all or none; DECISION B).
3854#[allow(clippy::too_many_arguments)]
3855fn check_generic_method_call(
3856    type_name: &str,
3857    recv_type_params: &[String],
3858    recv_ty: Option<TyId>,
3859    method_decl: &FnDecl,
3860    method: &Ident,
3861    type_args: &[TypeRef],
3862    args: &[Expr],
3863    call_expected: Option<TyId>,
3864    ctx: &mut Ctx,
3865) -> Option<TyId> {
3866    let tys = ctx.tys;
3867    let is_static = recv_ty.is_none();
3868    let what = if is_static { "static method" } else { "method" };
3869    // Rigid vars: the receiver type's parameters plus the method's own.
3870    let mut vars: HashSet<String> = recv_type_params.iter().cloned().collect();
3871    for tp in &method_decl.type_params {
3872        vars.insert(tp.name.name.clone());
3873    }
3874    // Param count excludes the implicit `self`.
3875    if method_decl.params.len() != args.len() {
3876        ctx.errors.push(
3877            CompileError::new(
3878                "bynk.types.method_arity",
3879                method.span,
3880                format!(
3881                    "{what} `{}.{}` expects {} argument(s), but {} were given",
3882                    type_name,
3883                    method.name,
3884                    method_decl.params.len(),
3885                    args.len()
3886                ),
3887            )
3888            .with_label(method_decl.name.ident().span, "method declared here"),
3889        );
3890        for a in args {
3891            let _ = type_of(a, None, ctx);
3892        }
3893        return None;
3894    }
3895    // Seed the substitution from the receiver's concrete type arguments: the
3896    // type's parameters are ground the moment the receiver's type is known
3897    // (`self.map(g)` on a `Box[User]` binds the type's `A` to `User`; on `self`
3898    // it binds `A` to its own rigid var). An arity mismatch here means the
3899    // receiver was under-applied — reported where the receiver was typed — so we
3900    // leave those parameters unseeded and fail below as uninferable.
3901    let mut subst: HashMap<String, TyId> = HashMap::new();
3902    if let Some(recv_ty) = recv_ty
3903        && let Ty::Named {
3904            args: recv_args, ..
3905        } = &*tys.get(recv_ty)
3906        && recv_args.len() == recv_type_params.len()
3907    {
3908        for (name, arg) in recv_type_params.iter().zip(recv_args.iter()) {
3909            subst.insert(name.clone(), *arg);
3910        }
3911    }
3912    // The parameters still to determine, in declaration order: for a static the
3913    // type's own, then the method's (the witness and emitted order; DECISION B).
3914    let mut all_params: Vec<String> = Vec::new();
3915    if is_static {
3916        all_params.extend(recv_type_params.iter().cloned());
3917    }
3918    all_params.extend(
3919        method_decl
3920            .type_params
3921            .iter()
3922            .map(|tp| tp.name.name.clone()),
3923    );
3924    if !type_args.is_empty() {
3925        if type_args.len() != all_params.len() {
3926            ctx.errors.push(CompileError::new(
3927                "bynk.generics.type_arg_mismatch",
3928                method.span,
3929                format!(
3930                    "`{}.{}` takes {} type argument(s), but {} were given",
3931                    type_name,
3932                    method.name,
3933                    all_params.len(),
3934                    type_args.len()
3935                ),
3936            ));
3937            for a in args {
3938                let _ = type_of(a, None, ctx);
3939            }
3940            return None;
3941        }
3942        for (name, ta) in all_params.iter().zip(type_args) {
3943            let Some(ty) = resolve_expr_type_ref(ta, ctx) else {
3944                // Type the arguments so their own errors are still reported.
3945                for a in args {
3946                    let _ = type_of(a, None, ctx);
3947                }
3948                return None;
3949            };
3950            subst.insert(name.clone(), ty);
3951        }
3952    }
3953    // Resolve the method's parameter and return patterns with every rigid var in
3954    // scope (a name matching one resolves to `Ty::Var`, not an unknown type).
3955    let var_params: Vec<Option<TyId>> = method_decl
3956        .params
3957        .iter()
3958        .map(|p| resolve_type_ref_in(&p.type_ref, &ctx.input.types, &vars, tys))
3959        .collect();
3960    let ret_pattern = resolve_type_ref_in(&method_decl.return_type, &ctx.input.types, &vars, tys)?;
3961
3962    let mut arg_tys: Vec<Option<TyId>> = vec![None; args.len()];
3963    // Pass 1 — non-lambda arguments (mirrors `check_generic_call`).
3964    for (i, arg) in args.iter().enumerate() {
3965        if matches!(arg.kind, ExprKind::Lambda(_)) {
3966            continue;
3967        }
3968        let expected = var_params[i].map(|p| substitute(p, &subst, tys));
3969        let ty = type_of(arg, expected, ctx);
3970        if let (Some(pattern), Some(actual)) = (var_params[i], ty)
3971            && !unify(pattern, actual, &mut subst, tys)
3972        {
3973            ctx.errors.push(CompileError::new(
3974                "bynk.generics.type_arg_mismatch",
3975                arg.span,
3976                format!(
3977                    "argument {} infers a type for `{}.{}`'s type parameter that conflicts with an earlier argument or the receiver",
3978                    i + 1,
3979                    type_name,
3980                    method.name
3981                ),
3982            ));
3983            return None;
3984        }
3985        arg_tys[i] = ty;
3986    }
3987    // Slice 4 (DECISION C): the call's expected type grounds what the
3988    // receiver and the arguments left open, before the lambdas need it.
3989    ground_from_expected(ret_pattern, call_expected, &all_params, &mut subst, ctx);
3990    // Pass 2 — lambda arguments, against the now-substituted expecteds.
3991    for (i, arg) in args.iter().enumerate() {
3992        if !matches!(arg.kind, ExprKind::Lambda(_)) {
3993            continue;
3994        }
3995        let expected = var_params[i].map(|p| substitute(p, &subst, tys));
3996        let params_unconstrained = expected.is_some_and(|e| {
3997            matches!(&*tys.get(e), Ty::Fn { params, .. }
3998                if params.iter().any(|p| contains_var(*p, tys)))
3999        });
4000        let fully_annotated = matches!(
4001            &arg.kind,
4002            ExprKind::Lambda(l) if l.params.iter().all(|p| lambda_param_is_typed(p, ctx))
4003        );
4004        if params_unconstrained && !fully_annotated {
4005            ctx.errors.push(
4006                CompileError::new(
4007                    "bynk.generics.uninferable_type_arg",
4008                    arg.span,
4009                    format!(
4010                        "the lambda's parameter types depend on `{}.{}`'s type parameters, which the receiver and other arguments do not determine",
4011                        type_name, method.name
4012                    ),
4013                )
4014                .with_note("annotate the lambda's parameters"),
4015            );
4016            return None;
4017        }
4018        let ty = if params_unconstrained {
4019            type_of(arg, None, ctx)
4020        } else {
4021            type_of(arg, expected, ctx)
4022        };
4023        if let (Some(pattern), Some(actual)) = (var_params[i], ty)
4024            && !unify(pattern, actual, &mut subst, tys)
4025        {
4026            ctx.errors.push(CompileError::new(
4027                "bynk.generics.type_arg_mismatch",
4028                arg.span,
4029                format!(
4030                    "the lambda's type conflicts with `{}.{}`'s inferred type arguments",
4031                    type_name, method.name
4032                ),
4033            ));
4034            return None;
4035        }
4036        arg_tys[i] = ty;
4037    }
4038    // Every one of the method's own type parameters must now be determined (the
4039    // receiver's parameters were seeded above). A static must determine the
4040    // type's parameters too.
4041    for name in &all_params {
4042        if !subst.contains_key(name) {
4043            let mut err = CompileError::new(
4044                "bynk.generics.uninferable_type_arg",
4045                method.span,
4046                if is_static {
4047                    format!(
4048                        "type parameter `{name}` of `{}.{}` is neither inferable from the arguments nor given explicitly",
4049                        type_name, method.name
4050                    )
4051                } else {
4052                    format!(
4053                        "type parameter `{name}` of `{}.{}` is not inferable from the receiver or the arguments",
4054                        type_name, method.name
4055                    )
4056                },
4057            );
4058            if let Some(tp) = method_decl
4059                .type_params
4060                .iter()
4061                .find(|tp| &tp.name.name == name)
4062            {
4063                err = err.with_label(tp.span, "declared here");
4064            }
4065            if is_static {
4066                err = err.with_note(
4067                    "annotate the binding, or give explicit type arguments: `Type.method[T](…)`",
4068                );
4069            }
4070            ctx.errors.push(err);
4071            return None;
4072        }
4073    }
4074    // Final compatibility over the fully-ground parameter types.
4075    let mut ok = true;
4076    for (i, (pattern, arg)) in var_params.iter().zip(args).enumerate() {
4077        record_param_hint(ctx.hints, &method_decl.params[i].name.name, arg);
4078        let (Some(pattern), Some(arg_ty)) = (pattern, arg_tys[i].as_ref()) else {
4079            continue;
4080        };
4081        let ground = substitute(*pattern, &subst, tys);
4082        if !compatible(*arg_ty, ground, tys) {
4083            ctx.errors.push(CompileError::new(
4084                "bynk.types.argument_mismatch",
4085                arg.span,
4086                format!(
4087                    "argument {} to `{}.{}` has type `{}`, but `{}` is expected",
4088                    i + 1,
4089                    type_name,
4090                    method.name,
4091                    arg_ty.display(tys),
4092                    ground.display(tys)
4093                ),
4094            ));
4095            ok = false;
4096        }
4097    }
4098    if !ok {
4099        return None;
4100    }
4101    // The same call-site bound as a generic function's, over the method's own
4102    // parameters and the receiver parameters its `where` clause bounds (or that
4103    // it compares without yet saying so).
4104    let decl = ctx.input.methods.get(type_name).and_then(|t| {
4105        t.instance
4106            .get(&method.name)
4107            .or_else(|| t.statics.get(&method.name))
4108            .cloned()
4109    });
4110    let compared = match &decl {
4111        Some(decl) if std::ptr::eq(decl.as_ref(), method_decl) => {
4112            super::equality::compared_type_params(decl, ctx)
4113        }
4114        _ => Default::default(),
4115    };
4116    let recv_decl = ctx.input.types.get(type_name);
4117    let declared_eq = |name: &str| {
4118        // A bound the receiver type declares (`type Set2[T: Eq]`) holds in its
4119        // methods, with no `where` clause.
4120        recv_decl.is_some_and(|d| {
4121            d.type_params
4122                .iter()
4123                .any(|tp| tp.name.name == name && super::equality::has_eq(&tp.bounds))
4124        }) || method_decl
4125            .type_params
4126            .iter()
4127            .any(|tp| tp.name.name == name && super::equality::has_eq(&tp.bounds))
4128            || method_decl
4129                .where_bounds
4130                .iter()
4131                .any(|wb| wb.param.name == name && super::equality::has_eq(&wb.bounds))
4132    };
4133    let mut eq_params: Vec<(String, Option<Span>)> = method_decl
4134        .type_params
4135        .iter()
4136        .map(|tp| (tp.name.name.clone(), Some(tp.span)))
4137        .collect();
4138    eq_params.extend(recv_type_params.iter().map(|p| (p.clone(), None)));
4139    let ord_params = super::ordering::witness_params(method_decl, &ctx.input.types);
4140    let key_params = super::keying::key_params(method_decl, &ctx.input.types);
4141    eq_params.retain(|(p, _)| {
4142        (declared_eq(p) || compared.contains(p))
4143            && !ord_params.iter().any(|o| o == p)
4144            && !key_params.iter().any(|k| k == p)
4145    });
4146    let callee = format!("{type_name}.{}", method.name);
4147    if !super::equality::check_declared_eq_args(&callee, method.span, &eq_params, &subst, ctx) {
4148        return None;
4149    }
4150    let witnesses = super::codable::check_declared_witness_args(
4151        &callee,
4152        method.span,
4153        &super::codable::witness_list(method_decl, &ctx.input.types),
4154        &subst,
4155        ctx,
4156    )?;
4157    if !super::keying::check_declared_key_args(&callee, method.span, &key_params, &subst, ctx) {
4158        return None;
4159    }
4160    if !witnesses.is_empty() {
4161        ctx.last_witness = Some(witnesses);
4162    }
4163    // v0.39 (ADR 0072)-style hint: show the inferred method type arguments after
4164    // the method name (`box.map` [Int] `(f)`). Only the method's own
4165    // parameters — the receiver's are visible in the receiver's type.
4166    if !all_params.is_empty() && type_args.is_empty() {
4167        let rendered: Option<Vec<String>> = all_params
4168            .iter()
4169            .map(|n| subst.get(n).map(|t| t.display(tys)))
4170            .collect();
4171        if let Some(parts) = rendered {
4172            ctx.hints
4173                .record(method.span, format!("[{}]", parts.join(", ")));
4174        }
4175    }
4176    Some(substitute(ret_pattern, &subst, tys))
4177}
4178
4179/// v0.178 (#662) / v0.182 (#664): resolve a test-body service invocation against
4180/// the target's declared handlers and check its arity and argument types. The
4181/// address form depends on the method name:
4182///
4183/// - `svc.call(args)` — the `on call` handler (#662);
4184/// - `svc.<VERB>("/path", …)` — an http route (`GET`/`POST`/`PUT`/`PATCH`/`DELETE`);
4185/// - `svc.schedule("<expr>", …)` — a cron handler by its schedule string;
4186/// - `svc.message(msg)` — the queue message handler.
4187///
4188/// #1934 (re-opening ADR 0203): the call is typed by what it yields. A
4189/// resolved handler yields its declared return type. An http
4190/// address carrying a `Wire(…)` argument, or naming a method the path declares
4191/// no handler for, yields `Effect[HttpOutcome[T]]` instead (`by Nobody`, which
4192/// lives on the statement, is applied by [`nobody_outcome`]); an asset fetch
4193/// yields `Effect[HttpResult[()]]`. The call-site principal (`by <Actor>`) is
4194/// checked separately at the statement level. Returns `None` in an arm that
4195/// reported an error.
4196fn check_test_service_address(
4197    sig: &TestServiceSig,
4198    id: &Ident,
4199    method: &Ident,
4200    args: &[Expr],
4201    // P6.0 (#1139): the outer `MethodCall` expression's own identity.
4202    expr_id: ExprId,
4203    ctx: &mut Ctx,
4204) -> Option<TyId> {
4205    use bynk_syntax::ast::{ExprKind as EK, HandlerKind};
4206
4207    // `svc.call(...)` — the `on call` handler (Slice 0).
4208    if method.name == "call" {
4209        ctx.callees.insert(
4210            expr_id,
4211            Callee::TestService {
4212                service: id.name.clone(),
4213                address: HandlerAddress::Call,
4214                extra_headers: false,
4215            },
4216        );
4217        let Some(handler) = sig.call_handler() else {
4218            let message = match &sig.protocol {
4219                Some(protocol) => format!(
4220                    "`{}` is a `from {protocol}` service and has no `on call` handler to invoke",
4221                    id.name
4222                ),
4223                None => format!("service `{}` has no `on call` handler to invoke", id.name),
4224            };
4225            ctx.errors.push(
4226                CompileError::new("bynk.test.service_no_call_handler", method.span, message)
4227                    .with_note(
4228                        "call an `on call` service with `svc.call(...)`, an http route with `svc.GET(\"/path\")`, cron with `svc.schedule(\"…\")`, or a queue with `svc.message(m)`",
4229                    ),
4230            );
4231            for a in args {
4232                let _ = type_of(a, None, ctx);
4233            }
4234            return None;
4235        };
4236        let params = handler.params.clone();
4237        check_address_args(&id.name, "call", &params, args, method.span, ctx);
4238        return handler_outcome(handler, ctx);
4239    }
4240
4241    // #3051: `svc.open(tc, …)` / `svc.message(tc, frame)` / `svc.close(tc)` on a
4242    // `from websocket` service.
4243    if sig.ws_frames.is_some() && matches!(method.name.as_str(), "open" | "message" | "close") {
4244        return check_ws_address(sig, id, method, args, expr_id, ctx);
4245    }
4246
4247    // `svc.<VERB>("/path", …)` — an http route. The first argument is the route
4248    // *pattern* (a compile-time-resolved name), the rest are positional path
4249    // params then the body, matched against the handler's declared params.
4250    // `HttpMethod::from_ident` is the single source of truth the emitter shares.
4251    if bynk_syntax::ast::HttpMethod::from_ident(&method.name).is_some() {
4252        ctx.callees.insert(
4253            expr_id,
4254            Callee::TestService {
4255                service: id.name.clone(),
4256                address: http_address(method, None),
4257                extra_headers: false,
4258            },
4259        );
4260        // #1883, slice 3 ([DECISION F]): `svc.GET(style)` — an `Asset` as the
4261        // address. The platform serves an asset before the Worker runs, so no
4262        // handler is involved: the call answers with the file the target's
4263        // Worker ships, as the platform would (`HttpResult.Raw`).
4264        if let Some(first) = args.first()
4265            && !matches!(first.kind, EK::StrLit(_))
4266            && is_asset_value(first, ctx)
4267        {
4268            let _ = type_of(first, None, ctx);
4269            // Review of #1922: only an HTTP service fronts a Worker the
4270            // platform serves assets beside.
4271            if sig.protocol.as_deref() != Some("http") {
4272                ctx.errors.push(
4273                    CompileError::new(
4274                        "bynk.test.service_bad_address",
4275                        method.span,
4276                        format!(
4277                            "`{}` is not a `from http` service, so it cannot fetch an asset",
4278                            id.name
4279                        ),
4280                    )
4281                    .with_note("fetch an asset through one of the target's `from http` services: `api.GET(asset)`"),
4282                );
4283                // Review of #1923: still type the rest, as every other
4284                // error arm here does, so a mistake inside them is reported.
4285                for a in &args[1..] {
4286                    let _ = type_of(a, None, ctx);
4287                }
4288                return None;
4289            }
4290            if method.name != "GET" {
4291                ctx.errors.push(
4292                    CompileError::new(
4293                        "bynk.test.asset_address_method",
4294                        method.span,
4295                        format!(
4296                            "an asset is fetched with `{}.GET(asset)`, not `{}`",
4297                            id.name, method.name
4298                        ),
4299                    )
4300                    .with_note(
4301                        "the platform serves an asset to `GET` and answers every other method with `405`",
4302                    ),
4303                );
4304            }
4305            if args.len() > 1 {
4306                ctx.errors.push(CompileError::new(
4307                    "bynk.test.service_call_arity",
4308                    args[1].span,
4309                    format!(
4310                        "`{}.{}(asset)` takes the asset alone; remove the other arguments",
4311                        id.name, method.name
4312                    ),
4313                ));
4314                for a in &args[1..] {
4315                    let _ = type_of(a, None, ctx);
4316                }
4317            }
4318            ctx.callees.insert(
4319                expr_id,
4320                Callee::TestAssetFetch {
4321                    service: id.name.clone(),
4322                },
4323            );
4324            // `Raw(body, contentType)` or `NotFound`: no handler's `T` is involved.
4325            let unit = ctx.tys.intern(Ty::Unit);
4326            return Some(effect_of(ctx.tys.intern(Ty::HttpResult(unit)), ctx));
4327        }
4328        let Some(EK::StrLit(path)) = args.first().map(|a| &a.kind) else {
4329            ctx.errors.push(
4330                CompileError::new(
4331                    "bynk.test.service_bad_address",
4332                    method.span,
4333                    format!(
4334                        "`{}.{}` addresses an http route, so its first argument must be the route pattern string (e.g. `\"/todos\"`)",
4335                        id.name, method.name
4336                    ),
4337                ),
4338            );
4339            for a in args {
4340                let _ = type_of(a, None, ctx);
4341            }
4342            return None;
4343        };
4344        // The classification recorded above (verb only) is enriched here,
4345        // now that the route pattern — the thing `sig.handlers` is actually
4346        // matched against below — is known; a later go-to-definition
4347        // consumer needs the path, not just the verb, to resolve a handler.
4348        ctx.callees.insert(
4349            expr_id,
4350            Callee::TestService {
4351                service: id.name.clone(),
4352                address: http_address(method, Some(path)),
4353                extra_headers: false,
4354            },
4355        );
4356        let matched = sig.handlers.iter().find(|h| {
4357            matches!(&h.kind, HandlerKind::Http { method: m, path: p } if m.as_str() == method.name && p == path)
4358        });
4359        let Some(handler) = matched else {
4360            // #707: the method has no handler at this path. If the *path* is
4361            // declared (for some other method), this is a **wrong-method** call —
4362            // the `405` fall-through test. Allow it: it drives the router with a
4363            // method the path has no handler for and observes `Rejected(
4364            // MethodNotAllowed)`. There is no handler, so no args are matched (a
4365            // `405` is synthesised before the body is read), and the outcome is an
4366            // `HttpOutcome` over `()`: no handler's `T` is involved.
4367            let path_declared = sig
4368                .handlers
4369                .iter()
4370                .any(|h| matches!(&h.kind, HandlerKind::Http { path: p, .. } if p == path));
4371            if path_declared {
4372                let _ = type_of(&args[0], None, ctx);
4373                // A wrong-method call has no handler, so it takes only the path;
4374                // diagnose extra args rather than silently dropping them (the
4375                // lowering forwards only method+path to the generic driver).
4376                if args.len() > 1 {
4377                    ctx.errors.push(
4378                        CompileError::new(
4379                            "bynk.test.service_call_arity",
4380                            method.span,
4381                            format!(
4382                                "`{}.{}(\"{}\")` is a wrong-method `405` test and takes only the route path, but {} argument(s) were given",
4383                                id.name,
4384                                method.name,
4385                                path,
4386                                args.len() - 1
4387                            ),
4388                        )
4389                        .with_note("a wrong-method call reaches no handler, so it passes no body or params"),
4390                    );
4391                    for a in &args[1..] {
4392                        let _ = type_of(a, None, ctx);
4393                    }
4394                }
4395                let unit = ctx.tys.intern(Ty::Unit);
4396                return Some(effect_of(ctx.tys.intern(Ty::HttpOutcome(unit)), ctx));
4397            }
4398            ctx.errors.push(
4399                CompileError::new(
4400                    "bynk.test.service_unknown_route",
4401                    method.span,
4402                    format!(
4403                        "`{}` declares no route at `\"{}\"` (no handler for any method)",
4404                        id.name, path
4405                    ),
4406                )
4407                .with_note("the path must match a declared route; drive a wrong method against an existing path to test the `405` fall-through"),
4408            );
4409            for a in args {
4410                let _ = type_of(a, None, ctx);
4411            }
4412            return None;
4413        };
4414        let params = handler.params.clone();
4415        // Type the route-pattern string as an ordinary string; check the rest.
4416        let _ = type_of(&args[0], None, ctx);
4417        let mut positional = &args[1..];
4418        // #2910: a route that declares no `headers:` parameter may still be
4419        // sent request headers: a trailing `RequestHeaders` argument. A route
4420        // that declares one fills it with the argument already, so a further
4421        // one is an ordinary arity error (with a note saying why). The
4422        // trailing argument is typed once, here, and not again below.
4423        let declares_headers = params.iter().any(|p| {
4424            p.name.name == "headers"
4425                && matches!(p.type_ref, bynk_syntax::ast::TypeRef::RequestHeaders(_))
4426        });
4427        let trailing = if positional.len() == params.len() + 1
4428            && let Some((last, rest)) = positional.split_last()
4429            && !matches!(last.kind, EK::Wire(_))
4430        {
4431            let is_headers = type_of(last, None, ctx)
4432                .is_some_and(|t| matches!(&*ctx.tys.get(t), Ty::RequestHeaders));
4433            Some((last, rest, is_headers))
4434        } else {
4435            None
4436        };
4437        match trailing {
4438            Some((last, rest, true)) if !declares_headers => {
4439                positional = rest;
4440                check_extra_headers_authorization(last, ctx);
4441                ctx.callees.insert(
4442                    expr_id,
4443                    Callee::TestService {
4444                        service: id.name.clone(),
4445                        address: http_address(method, Some(path)),
4446                        extra_headers: true,
4447                    },
4448                );
4449                check_address_args(
4450                    &id.name,
4451                    &method.name,
4452                    &params,
4453                    positional,
4454                    method.span,
4455                    ctx,
4456                );
4457            }
4458            Some((_, rest, is_headers)) => {
4459                // The extra argument is no `RequestHeaders` this route can
4460                // take: report the arity once, and still check the others.
4461                let mut err = CompileError::new(
4462                    "bynk.test.service_call_arity",
4463                    method.span,
4464                    format!(
4465                        "`{}.{}` expects {} argument(s), but {} were given",
4466                        id.name,
4467                        method.name,
4468                        params.len(),
4469                        positional.len()
4470                    ),
4471                );
4472                err = if is_headers {
4473                    err.with_note("the route already declares `headers: RequestHeaders`, so that argument is its request headers; a second `RequestHeaders` cannot be sent")
4474                } else {
4475                    err.with_note("handler declared here")
4476                };
4477                ctx.errors.push(err);
4478                for a in rest {
4479                    let _ = type_of(a, None, ctx);
4480                }
4481            }
4482            None => check_address_args(
4483                &id.name,
4484                &method.name,
4485                &params,
4486                positional,
4487                method.span,
4488                ctx,
4489            ),
4490        }
4491        // A `Wire(…)` argument reaches the router unvalidated, so the call
4492        // observes the boundary as well as the handler: the raw driver decodes
4493        // an `HttpOutcome`. The emitter picks that driver on the same test.
4494        let outcome = handler_outcome(handler, ctx);
4495        if args[1..].iter().any(|a| matches!(a.kind, EK::Wire(_))) {
4496            return outcome.map(|t| wire_outcome(t, ctx));
4497        }
4498        return outcome;
4499    }
4500
4501    // `svc.schedule("<expr>", …)` — a cron handler, matched by its schedule.
4502    if method.name == "schedule" {
4503        ctx.callees.insert(
4504            expr_id,
4505            Callee::TestService {
4506                service: id.name.clone(),
4507                address: HandlerAddress::Schedule { expr: None },
4508                extra_headers: false,
4509            },
4510        );
4511        let Some(expr) = args.first().and_then(|a| schedule_literal_text(a, ctx)) else {
4512            ctx.errors.push(CompileError::new(
4513                "bynk.test.service_bad_address",
4514                method.span,
4515                format!(
4516                    "`{}.schedule` addresses a cron handler, so its first argument must be the schedule string, or a `String` or `CronSchedule` constant bound to one",
4517                    id.name
4518                ),
4519            ));
4520            for a in args {
4521                let _ = type_of(a, None, ctx);
4522            }
4523            return None;
4524        };
4525        // Enrich with the schedule expression `sig.handlers` is matched
4526        // against below — same reasoning as the http-verb branch above.
4527        ctx.callees.insert(
4528            expr_id,
4529            Callee::TestService {
4530                service: id.name.clone(),
4531                address: HandlerAddress::schedule(&expr),
4532                extra_headers: false,
4533            },
4534        );
4535        let matched = sig
4536            .handlers
4537            .iter()
4538            .find(|h| matches!(&h.kind, HandlerKind::Cron { expr: e } if *e == expr));
4539        let Some(handler) = matched else {
4540            ctx.errors.push(CompileError::new(
4541                "bynk.test.service_unknown_route",
4542                method.span,
4543                format!(
4544                    "`{}` declares no `on schedule(\"{}\")` handler",
4545                    id.name, expr
4546                ),
4547            ));
4548            for a in args {
4549                let _ = type_of(a, None, ctx);
4550            }
4551            return None;
4552        };
4553        let params = handler.params.clone();
4554        let _ = type_of(&args[0], None, ctx);
4555        check_address_args(&id.name, "schedule", &params, &args[1..], method.span, ctx);
4556        return handler_outcome(handler, ctx);
4557    }
4558
4559    // `svc.message(msg)` — the queue message handler.
4560    if method.name == "message" {
4561        ctx.callees.insert(
4562            expr_id,
4563            Callee::TestService {
4564                service: id.name.clone(),
4565                address: HandlerAddress::Message,
4566                extra_headers: false,
4567            },
4568        );
4569        let matched = sig
4570            .handlers
4571            .iter()
4572            .find(|h| matches!(&h.kind, HandlerKind::Message));
4573        let Some(handler) = matched else {
4574            ctx.errors.push(CompileError::new(
4575                "bynk.test.service_unknown_route",
4576                method.span,
4577                format!("`{}` declares no `on message(...)` handler", id.name),
4578            ));
4579            for a in args {
4580                let _ = type_of(a, None, ctx);
4581            }
4582            return None;
4583        };
4584        let params = handler.params.clone();
4585        check_address_args(&id.name, "message", &params, args, method.span, ctx);
4586        return handler_outcome(handler, ctx);
4587    }
4588
4589    // #2052: `svc.event(payload)` / `svc.event(payload, envelope)` — one
4590    // delivery to a `from Events(E)` service's `on event` handler.
4591    if method.name == "event"
4592        && let Some(handler) = sig
4593            .handlers
4594            .iter()
4595            .find(|h| matches!(&h.kind, HandlerKind::Event))
4596    {
4597        ctx.callees.insert(
4598            expr_id,
4599            Callee::TestService {
4600                service: id.name.clone(),
4601                address: HandlerAddress::Event,
4602                extra_headers: false,
4603            },
4604        );
4605        let handler = handler.clone();
4606        check_event_address(sig, id, &handler, args, method.span, ctx);
4607        return handler_outcome(&handler, ctx);
4608    }
4609
4610    // Not a recognised address form for this service.
4611    let proto = sig.protocol.as_deref().unwrap_or("call");
4612    let mut err = CompileError::new(
4613        "bynk.test.service_bad_address",
4614        method.span,
4615        format!(
4616            "`{}.{}` is not a way to address a `from {proto}` service in a test body",
4617            id.name, method.name
4618        ),
4619    );
4620    if method.name == "event" {
4621        err = err.with_note(
4622            "only a `from Events(E)` service is addressed with `svc.event(e)`; it delivers one event to the service's `on event` handler",
4623        );
4624    }
4625    ctx.errors.push(err);
4626    for a in args {
4627        let _ = type_of(a, None, ctx);
4628    }
4629    None
4630}
4631
4632/// #3051: a `from websocket` service's lifecycle addresses. The first argument
4633/// is the case's `TestConnection[out]`; `open` then takes the handler's route
4634/// parameters, `message` the decoded inbound frame alone and `close` nothing —
4635/// the connection remembers the route values and the principal from `open`, as
4636/// the platform recovers them from the socket. The callee's address carries what
4637/// the emitter needs: `ws open`, `ws message <frame index> <param count>`,
4638/// `ws close <param count>`.
4639fn check_ws_address(
4640    sig: &TestServiceSig,
4641    id: &Ident,
4642    method: &Ident,
4643    args: &[Expr],
4644    expr_id: ExprId,
4645    ctx: &mut Ctx,
4646) -> Option<TyId> {
4647    use bynk_syntax::ast::HandlerKind;
4648    let tys = ctx.tys;
4649    let which = method.name.as_str();
4650    let (in_ref, out_ref) = sig.ws_frames.clone()?;
4651    let handler = sig
4652        .handlers
4653        .iter()
4654        .find(|h| {
4655            matches!(
4656                (which, &h.kind),
4657                ("open", HandlerKind::Open)
4658                    | ("message", HandlerKind::Message)
4659                    | ("close", HandlerKind::Close)
4660            )
4661        })
4662        .cloned();
4663    let service = id.name.clone();
4664    ctx.callees.insert(
4665        expr_id,
4666        Callee::TestService {
4667            service: service.clone(),
4668            address: HandlerAddress::Ws(match which {
4669                "open" => WsAddress::Open,
4670                "message" => WsAddress::Message { frame: None },
4671                _ => WsAddress::Close { params: None },
4672            }),
4673            extra_headers: false,
4674        },
4675    );
4676    let Some(handler) = handler else {
4677        ctx.errors.push(CompileError::new(
4678            "bynk.test.service_unknown_route",
4679            method.span,
4680            format!("`{service}` declares no `on {which}` handler"),
4681        ));
4682        for a in args {
4683            let _ = type_of(a, None, ctx);
4684        }
4685        return None;
4686    };
4687    let out_ty = resolve_type_ref(&out_ref, &ctx.input.types, tys)?;
4688    let in_ty = resolve_type_ref(&in_ref, &ctx.input.types, tys)?;
4689    let tc_ty = tys.intern(Ty::TestConnection(out_ty));
4690    let Some(first) = args.first() else {
4691        ctx.errors.push(
4692            CompileError::new(
4693                "bynk.test.service_call_arity",
4694                method.span,
4695                format!(
4696                    "`{service}.{which}` takes the case's `TestConnection` as its first argument"
4697                ),
4698            )
4699            .with_note(format!(
4700                "build one with `TestConnection[{}]()`",
4701                out_ty.display(tys)
4702            )),
4703        );
4704        return None;
4705    };
4706    check_arg(
4707        first,
4708        tc_ty,
4709        &format!("the connection of `{service}.{which}`"),
4710        ctx,
4711    );
4712    let rest = &args[1..];
4713    match which {
4714        "open" => {
4715            let params = handler.params.clone();
4716            check_address_args(&service, "open", &params, rest, method.span, ctx);
4717        }
4718        "message" => {
4719            let frame_idx = handler
4720                .params
4721                .iter()
4722                .position(|p| resolve_type_ref(&p.type_ref, &ctx.input.types, tys) == Some(in_ty))
4723                .unwrap_or(0);
4724            ctx.callees.insert(
4725                expr_id,
4726                Callee::TestService {
4727                    service: service.clone(),
4728                    address: HandlerAddress::ws_message(frame_idx, handler.params.len()),
4729                    extra_headers: false,
4730                },
4731            );
4732            if rest.len() != 1 {
4733                ctx.errors.push(
4734                    CompileError::new(
4735                        "bynk.test.service_call_arity",
4736                        method.span,
4737                        format!(
4738                            "`{service}.message` takes the connection and one inbound frame, but {} argument(s) were given",
4739                            args.len()
4740                        ),
4741                    )
4742                    .with_note("the route values were given at `open`; the connection remembers them"),
4743                );
4744                for a in rest {
4745                    let _ = type_of(a, None, ctx);
4746                }
4747            } else {
4748                check_arg(
4749                    &rest[0],
4750                    in_ty,
4751                    &format!("the frame of `{service}.message`"),
4752                    ctx,
4753                );
4754            }
4755        }
4756        _ => {
4757            ctx.callees.insert(
4758                expr_id,
4759                Callee::TestService {
4760                    service: service.clone(),
4761                    address: HandlerAddress::ws_close(handler.params.len()),
4762                    extra_headers: false,
4763                },
4764            );
4765            if !rest.is_empty() {
4766                ctx.errors.push(CompileError::new(
4767                    "bynk.test.service_call_arity",
4768                    method.span,
4769                    format!(
4770                        "`{service}.close` takes only the connection, but {} argument(s) were given",
4771                        args.len()
4772                    ),
4773                ));
4774                for a in rest {
4775                    let _ = type_of(a, None, ctx);
4776                }
4777            }
4778        }
4779    }
4780    handler_outcome(&handler, ctx)
4781}
4782
4783/// #1934: what a case's call to `handler` yields — its declared return type,
4784/// an `Effect[_]` (`bynk.service.return_not_effect`). `None` if the type does
4785/// not resolve in the case, which a checked target's handler always does.
4786fn handler_outcome(handler: &TestHandler, ctx: &mut Ctx) -> Option<TyId> {
4787    resolve_type_ref(&handler.return_type, &ctx.input.types, ctx.tys)
4788}
4789
4790/// `Effect[ty]`.
4791fn effect_of(ty: TyId, ctx: &Ctx) -> TyId {
4792    ctx.tys.intern(Ty::Effect(ty))
4793}
4794
4795/// #1934: an http handler's outcome `Effect[HttpResult[T]]` as a `system`-tier
4796/// case observes it past the handler's types: `Effect[HttpOutcome[T]]`.
4797fn wire_outcome(outcome: TyId, ctx: &Ctx) -> TyId {
4798    let tys = ctx.tys;
4799    let inner = match &*tys.get(outcome) {
4800        Ty::Effect(t) => *t,
4801        _ => outcome,
4802    };
4803    let t = match &*tys.get(inner) {
4804        Ty::HttpResult(t) => *t,
4805        _ => return outcome,
4806    };
4807    tys.intern(Ty::Effect(tys.intern(Ty::HttpOutcome(t))))
4808}
4809
4810/// #1934: the type an effect-let binds for `value` driven `by Nobody`. The
4811/// no-credential driver decodes an `HttpOutcome` (a `401` from the auth seam is
4812/// `Rejected(Unauthorized)`), so a typed http address's `Effect[HttpResult[T]]`
4813/// becomes `Effect[HttpOutcome[T]]`; anything else is unchanged.
4814/// #2155: on an actor sum with an open member (`Visitor`), say why the seam
4815/// never answers `401`.
4816fn with_open_sum_note(err: CompileError, handler: &TestHandler, ctx: &Ctx) -> CompileError {
4817    let open = handler
4818        .by_clause
4819        .as_ref()
4820        .is_some_and(|by| by.is_sum() && crate::actors::sum_has_open_member(by, &ctx.test_actors));
4821    if open {
4822        err.with_note(
4823            "this actor sum admits an open member (`Visitor`): a request with a missing or bad credential resolves as it, so the seam never answers `401`",
4824        )
4825    } else {
4826        err
4827    }
4828}
4829
4830/// The typed address of `svc.<VERB>(…)`: the verb is the method, the route once it is read.
4831fn http_address(method: &Ident, path: Option<&str>) -> HandlerAddress {
4832    HandlerAddress::Http {
4833        verb: bynk_syntax::ast::HttpMethod::from_ident(&method.name).expect("the branch's guard"),
4834        path: path.map(str::to_string),
4835    }
4836}
4837
4838/// 1A.33: classify a call-site principal clause ([`CallSitePrincipal::of`], the one
4839/// classification of the reserved names) and record it on the clause's own id, so the emitter
4840/// and the later passes read what the checker decided. Idempotent.
4841pub(crate) fn record_principal(
4842    p: &bynk_syntax::ast::CallSiteActor,
4843    ctx: &mut Ctx,
4844) -> CallSitePrincipal {
4845    let kind = CallSitePrincipal::of(&p.actor.name);
4846    ctx.callees.insert(p.id, Callee::Principal(kind.clone()));
4847    kind
4848}
4849
4850/// #3052, #3225: what an `Oidc`-only failure principal is, for the diagnostic
4851/// raised when the call does not reach an `Oidc` seam.
4852struct OidcOnlyPrincipal {
4853    /// The diagnostic code.
4854    code: &'static str,
4855    /// What it sends, as the message words it.
4856    sends: &'static str,
4857    /// What the note adds after "use `by X` on a route guarded by an `Oidc`
4858    /// actor" for a handler whose route has no such seam.
4859    why_not_elsewhere: &'static str,
4860}
4861
4862/// The `Oidc`-only failure principals; `None` for every other name.
4863fn oidc_only_principal(bad: BadCredential) -> Option<OidcOnlyPrincipal> {
4864    let (code, sends, why_not_elsewhere) = match bad {
4865        BadCredential::WrongIssuer => (
4866            "bynk.test.wrong_issuer_needs_oidc_route",
4867            "a token for another issuer",
4868            "; a `Bearer` token has no issuer to check",
4869        ),
4870        BadCredential::WrongAudience => (
4871            "bynk.test.wrong_audience_needs_oidc_route",
4872            "a token for another audience",
4873            "; a `Bearer` token has no audience to check",
4874        ),
4875        BadCredential::WrongAlgorithm => (
4876            "bynk.test.wrong_algorithm_needs_oidc_route",
4877            "tokens signed under a refused algorithm (`alg: none`, and `HS256` keyed with the public key)",
4878            "; only an `Oidc` seam is driven with these tokens",
4879        ),
4880        BadCredential::NoSubject => (
4881            "bynk.test.no_subject_needs_oidc_route",
4882            "tokens with an empty and with a missing `sub`",
4883            "; only an `Oidc` seam is driven with these tokens",
4884        ),
4885        BadCredential::Forged | BadCredential::Stale | BadCredential::Expired => return None,
4886    };
4887    Some(OidcOnlyPrincipal {
4888        code,
4889        sends,
4890        why_not_elsewhere,
4891    })
4892}
4893
4894/// #2380 (L5): a call-site principal's claims (`by W("id", claims)`) are a `TokenClaims`, and
4895/// only an `Oidc` actor's handler reads them.
4896fn check_principal_claims(p: &bynk_syntax::ast::CallSiteActor, ctx: &mut Ctx) {
4897    let tys = ctx.tys;
4898    if let Some(claims) = &p.claims {
4899        let want = tys.intern(Ty::TokenClaims);
4900        check_arg(claims, want, "the principal's claims", ctx);
4901        let oidc = ctx.test_actors.get(&p.actor.name).is_some_and(|decl| {
4902            decl.auth
4903                .as_ref()
4904                .is_some_and(|a| a.name.as_str() == "Oidc")
4905        });
4906        if !oidc {
4907            ctx.errors.push(
4908                CompileError::new(
4909                    "bynk.test.principal_claims_not_oidc",
4910                    claims.span,
4911                    format!(
4912                        "`{}` isn't an `Oidc` actor, so its handlers read no token claims",
4913                        p.actor.name
4914                    ),
4915                )
4916                .with_note("claims are passed as `by Workload(\"id\", TokenClaims.of([\"name: value\"]))` for an `Oidc` actor"),
4917            );
4918        }
4919    }
4920}
4921
4922pub(crate) fn nobody_outcome(value: &Expr, ty: TyId, ctx: &Ctx) -> TyId {
4923    let is_http_address = matches!(
4924        ctx.callees.get(&value.id),
4925        Some(Callee::TestService {
4926            address: HandlerAddress::Http { .. },
4927            ..
4928        })
4929    );
4930    if is_http_address {
4931        wire_outcome(ty, ctx)
4932    } else {
4933        ty
4934    }
4935}
4936
4937/// What identity, if any, a resolved actor expects (v0.182).
4938enum ActorIdentity {
4939    Typed(TyId),
4940    CallerString,
4941    Unit,
4942    Unknown,
4943}
4944
4945/// Resolve an actor name to the identity it carries (v0.182).
4946fn resolve_actor_identity(name: &str, ctx: &Ctx) -> ActorIdentity {
4947    let tys = ctx.tys;
4948    use crate::actors::{Identity, prelude_actor};
4949    if let Some(decl) = ctx.test_actors.get(name) {
4950        // #3890: a refinement over the prelude `Caller` carries a `CallerId`.
4951        if crate::actors::caller_refinement(decl, &ctx.test_actors).is_some() {
4952            return ActorIdentity::CallerString;
4953        }
4954        // #2019: a refinement (`actor Admin = User where …`) narrows its base by
4955        // a claim and inherits the base's identity: the Worker's Bearer seam
4956        // follows the refinement to its base and mints the base identity
4957        // (`bearer_seam_for`). A refinement whose base is missing or is itself a
4958        // refinement is malformed (`bynk.actor.refinement_base_unsupported`),
4959        // so it resolves to no identity at all rather than passing as `Unit`.
4960        let decl = match &decl.refinement {
4961            Some(r) => match ctx.test_actors.get(&r.base.name) {
4962                Some(base) if base.refinement.is_none() => base,
4963                _ => return ActorIdentity::Unknown,
4964            },
4965            None => decl,
4966        };
4967        return match &decl.identity {
4968            Some(t) => match resolve_type_ref(t, &ctx.input.types, tys) {
4969                Some(ty) => ActorIdentity::Typed(ty),
4970                None => ActorIdentity::Unit,
4971            },
4972            None => ActorIdentity::Unit,
4973        };
4974    }
4975    match prelude_actor(name) {
4976        Some(c) => match c.identity {
4977            Identity::Unit => ActorIdentity::Unit,
4978            Identity::CallerId => ActorIdentity::CallerString,
4979            Identity::Declared(_) => ActorIdentity::Unit,
4980        },
4981        None => ActorIdentity::Unknown,
4982    }
4983}
4984
4985/// The actor a handler runs as: its declared `by <Actor>`, or the protocol
4986/// default (`Call`->`Caller`, `Cron`->`Scheduler`, `Queue`->`Producer`; http
4987/// has no default, so an http handler always declares one) (v0.182).
4988fn handler_actor_name(handler: &TestHandler, protocol: Option<&str>) -> Option<String> {
4989    if let Some(by) = &handler.by_clause {
4990        return Some(by.primary().name.clone());
4991    }
4992    match protocol {
4993        None => Some("Caller".to_string()),
4994        Some("cron") => Some("Scheduler".to_string()),
4995        Some("queue") => Some("Producer".to_string()),
4996        _ => None,
4997    }
4998}
4999
5000/// #1883, slice 3: whether `e` is an `Asset` value — an asset name in scope
5001/// (not shadowed by a local), or a field/expression that types as `Asset` —
5002/// without recording anything. Decides the `svc.GET(asset)` address form.
5003fn is_asset_value(e: &Expr, ctx: &Ctx) -> bool {
5004    match &e.kind {
5005        ExprKind::Ident(id) => ctx
5006            .lookup(id.name.as_str())
5007            .map(|t| matches!(&*ctx.tys.get(t), Ty::Asset))
5008            .unwrap_or_else(|| ctx.input.assets.contains_key(&id.name)),
5009        _ => false,
5010    }
5011}
5012
5013/// #3875 [DECISION C]: the schedule a `svc.schedule(…)` address names: a string
5014/// literal, or a bare reference to a constant declared `String` or exactly
5015/// `CronSchedule` that, following constant-to-constant references, is bound to a
5016/// literal. The address is then matched to its handler by the resolved text, so
5017/// a test that names the constant follows a schedule change. `None` for
5018/// anything else (a local shadows a constant of the same name).
5019fn schedule_literal_text(e: &Expr, ctx: &Ctx) -> Option<String> {
5020    use bynk_syntax::ast::ExprKind as EK;
5021    match &e.kind {
5022        EK::StrLit(s) => Some(s.clone()),
5023        EK::Ident(id) if ctx.lookup(id.name.as_str()).is_none() => {
5024            let start = ctx.input.consts.get(id.name.as_str())?;
5025            let lit = crate::consts::chain_literal_with(
5026                start,
5027                BaseType::String,
5028                crate::consts::is_schedule_type,
5029                ctx.input.consts.len(),
5030                |n| ctx.input.consts.get(n),
5031            )?;
5032            match &lit.kind {
5033                EK::StrLit(s) => Some(s.clone()),
5034                _ => None,
5035            }
5036        }
5037        _ => None,
5038    }
5039}
5040
5041/// v0.182 (#664): resolve the handler a test-body address invocation targets,
5042/// without side effects. Shared by the argument check and the principal check.
5043fn resolve_test_address<'a>(
5044    sig: &'a TestServiceSig,
5045    method: &str,
5046    args: &[Expr],
5047    ctx: &Ctx,
5048) -> Option<&'a TestHandler> {
5049    use bynk_syntax::ast::{ExprKind as EK, HandlerKind, HttpMethod};
5050    if method == "call" {
5051        return sig.call_handler();
5052    }
5053    if HttpMethod::from_ident(method).is_some() {
5054        let EK::StrLit(path) = &args.first()?.kind else {
5055            return None;
5056        };
5057        return sig.handlers.iter().find(|h| {
5058            matches!(&h.kind, HandlerKind::Http { method: m, path: p } if m.as_str() == method && p == path)
5059        });
5060    }
5061    if method == "schedule" {
5062        let expr = schedule_literal_text(args.first()?, ctx)?;
5063        return sig
5064            .handlers
5065            .iter()
5066            .find(|h| matches!(&h.kind, HandlerKind::Cron { expr: e } if *e == expr));
5067    }
5068    if method == "message" {
5069        return sig
5070            .handlers
5071            .iter()
5072            .find(|h| matches!(&h.kind, HandlerKind::Message));
5073    }
5074    // #3051: the websocket `on open` handler.
5075    if method == "open" && sig.ws_frames.is_some() {
5076        return sig
5077            .handlers
5078            .iter()
5079            .find(|h| matches!(&h.kind, HandlerKind::Open));
5080    }
5081    // #2052: the `on event` handler of a `from Events(E)` service.
5082    if method == "event" {
5083        return sig
5084            .handlers
5085            .iter()
5086            .find(|h| matches!(&h.kind, HandlerKind::Event));
5087    }
5088    None
5089}
5090
5091/// v0.182 (#664): validate the call-site principal of a test `effect_let`
5092/// against the ADDRESSED HANDLER. This is where per-case identity isolation is
5093/// enforced: an identity-carrying handler driven with a unit principal (`by
5094/// Visitor`) or no `by` at all would otherwise emit a call with
5095/// `deps.identity === undefined`. The identity value is typed against the
5096/// handler's required identity type, not the principal actor's.
5097pub(crate) fn check_effect_let_principal(
5098    value: &Expr,
5099    principal: Option<&bynk_syntax::ast::CallSiteActor>,
5100    ctx: &mut Ctx,
5101) {
5102    let tys = ctx.tys;
5103    // 1A.33: classify the clause once; the rules below read the result.
5104    let kind = principal.map(|p| record_principal(p, ctx));
5105    if let Some(p) = principal {
5106        check_principal_claims(p, ctx);
5107    }
5108    let ExprKind::MethodCall {
5109        receiver,
5110        method,
5111        args,
5112        ..
5113    } = &value.kind
5114    else {
5115        if let Some(p) = principal {
5116            report_principal_actor(p, ctx);
5117        }
5118        return;
5119    };
5120    let ExprKind::Ident(id) = &receiver.kind else {
5121        if let Some(p) = principal {
5122            report_principal_actor(p, ctx);
5123        }
5124        return;
5125    };
5126    let Some(sig) = ctx.test_services.get(&id.name).cloned() else {
5127        if let Some(p) = principal {
5128            report_principal_actor(p, ctx);
5129        }
5130        return;
5131    };
5132    // #3051: a connection's principal is established once, at `open`
5133    // (#3046): `message` and `close` carry it from there and take no `by`.
5134    if sig.ws_frames.is_some() && matches!(method.name.as_str(), "message" | "close") {
5135        if let Some(p) = principal {
5136            ctx.errors.push(
5137                CompileError::new(
5138                    "bynk.test.ws_lifecycle_by",
5139                    p.span,
5140                    format!(
5141                        "`{}.{}` takes no `by`: the connection's principal was given at `open`",
5142                        id.name, method.name
5143                    ),
5144                )
5145                .with_note("open a new `TestConnection` to act as a different principal"),
5146            );
5147            if let Some(idv) = &p.identity {
5148                let _ = type_of(idv, None, ctx);
5149            }
5150        }
5151        return;
5152    }
5153    let Some(handler) = resolve_test_address(&sig, &method.name, args, ctx).cloned() else {
5154        if let Some(p) = principal
5155            && args.first().is_some_and(|a| is_asset_value(a, ctx))
5156        {
5157            // #1883, slice 3: an asset is public and served before the Worker
5158            // runs, so no principal reaches it.
5159            ctx.errors.push(
5160                CompileError::new(
5161                    "bynk.test.principal_on_asset",
5162                    p.span,
5163                    format!(
5164                        "an asset is public and served before the Worker runs, so `by {}` is meaningless",
5165                        p.actor.name
5166                    ),
5167                )
5168                .with_note("drop the `by` clause on an asset fetch"),
5169            );
5170            if let Some(id) = &p.identity {
5171                let _ = type_of(id, None, ctx);
5172            }
5173            return;
5174        }
5175        if let Some(p) = principal {
5176            // #707: a wrong-method `405` test (an http method whose path is
5177            // declared for *another* method) reaches no handler, so a `by` clause
5178            // is meaningless — reject it clearly. (An unresolvable address of any
5179            // other shape already errors in `check_test_service_address`; only the
5180            // now-allowed wrong-method call would otherwise drop the `by`.)
5181            let wrong_method = bynk_syntax::ast::HttpMethod::from_ident(&method.name).is_some()
5182                && matches!(args.first().map(|a| &a.kind), Some(bynk_syntax::ast::ExprKind::StrLit(path))
5183                    if sig.handlers.iter().any(|h| matches!(&h.kind, bynk_syntax::ast::HandlerKind::Http { path: p, .. } if p == path)));
5184            if wrong_method {
5185                ctx.errors.push(
5186                    CompileError::new(
5187                        "bynk.test.principal_on_wrong_method",
5188                        p.span,
5189                        format!(
5190                            "a wrong-method `405` test reaches no handler, so `by {}` is meaningless",
5191                            p.actor.name
5192                        ),
5193                    )
5194                    .with_note("drop the `by` clause on a wrong-method call"),
5195                );
5196                if let Some(id) = &p.identity {
5197                    let _ = type_of(id, None, ctx);
5198                }
5199            } else {
5200                report_principal_actor(p, ctx);
5201            }
5202        }
5203        return;
5204    };
5205
5206    // #706: `by Nobody` is the reserved "no credential" principal. It drives the
5207    // route with no `Authorization` header so the real auth seam rejects it
5208    // (`401` → `Rejected(Unauthorized)`), so it is valid on any http handler
5209    // regardless of the required identity — the whole point is that *no* valid
5210    // credential is presented. It carries no identity (`by Nobody(...)` is
5211    // meaningless). The `system`-only tier rule is enforced at emit time, like
5212    // `Wire`'s (the checker has no tier).
5213    if let Some(p) = principal
5214        && kind == Some(CallSitePrincipal::Nobody)
5215    {
5216        // #710-style: `by Nobody` is only *implemented* for a Bearer- or
5217        // (#2135) Signature-secured route — the no-auth driver leaves out the
5218        // `Authorization` header the Bearer seam checks, or the signature
5219        // headers the Signature seam checks. On an unsecured
5220        // (`Visitor`/`None`) route there is no such seam to reject a
5221        // missing credential, so reject it here rather than emit a call to a
5222        // driver that was never generated.
5223        // #2155: an actor sum is secured when a member is.
5224        let secured = handler
5225            .by_clause
5226            .as_ref()
5227            .is_some_and(|by| crate::actors::route_is_secured(by, &ctx.test_actors));
5228        if !secured {
5229            let err = CompileError::new(
5230                "bynk.test.nobody_needs_secured_route",
5231                p.span,
5232                "`by Nobody` drives the auth seam to a `401`, but this handler's route has no seam that refuses a missing credential",
5233            )
5234            .with_note(
5235                "use `by Nobody` only on a route guarded by a `Bearer`, `Oidc` or `Signature` actor; a public (`Visitor`) route has no seam to test",
5236            );
5237            ctx.errors.push(with_open_sum_note(err, &handler, ctx));
5238        }
5239        if let Some(idv) = &p.identity {
5240            ctx.errors.push(CompileError::new(
5241                "bynk.test.actor_no_identity",
5242                p.span,
5243                "`Nobody` presents no credential, so it takes no identity — write `by Nobody`",
5244            ));
5245            let _ = type_of(idv, None, ctx);
5246        }
5247        return;
5248    }
5249
5250    // #2135, #2864: `by Forged` / `by Stale` / `by Expired` are reserved
5251    // principals, like `Nobody`: the `system` driver signs a `Signature` route
5252    // with a wrong secret, or `tolerance + 60` seconds in the past, and a
5253    // Bearer route with a token signed by a wrong secret, or one whose `exp`
5254    // is an hour past, so the real seam refuses it. They name no actor and
5255    // take no identity. The `system`-only tier rule is enforced with the
5256    // case's tier (`bynk.test.forged_needs_system`).
5257    if let Some(p) = principal
5258        && let Some(CallSitePrincipal::BadCredential(bad)) = kind
5259    {
5260        let name = p.actor.name.as_str();
5261        let by = handler.by_clause.as_ref();
5262        let sig_seam =
5263            by.and_then(|by| crate::actors::signature_seam_of_route(by, &ctx.test_actors));
5264        let bearer =
5265            by.is_some_and(|by| crate::actors::route_refuses_bad_token(by, &ctx.test_actors));
5266        // #3052: an `Oidc` route's seam refuses a bad token too.
5267        let oidc = by.is_some_and(|by| crate::actors::by_clause_is_oidc(by, &ctx.test_actors));
5268        match (bad, sig_seam) {
5269            (BadCredential::Expired, _) if !bearer && !oidc => {
5270                let err = CompileError::new(
5271                    "bynk.test.expired_needs_bearer_route",
5272                    p.span,
5273                    "`by Expired` sends an expired token to a `Bearer` or `Oidc` seam, but this handler's route has no such seam that refuses one",
5274                )
5275                .with_note(
5276                    "use `by Expired` on a route guarded by a `Bearer` or `Oidc` actor; on a `Signature` route, `by Stale` sends a stale signature",
5277                );
5278                ctx.errors.push(with_open_sum_note(err, &handler, ctx));
5279            }
5280            (BadCredential::Expired, _) => {}
5281            (n, _) if !oidc && oidc_only_principal(n).is_some() => {
5282                let kind = oidc_only_principal(n).expect("matched above");
5283                ctx.errors.push(
5284                    CompileError::new(
5285                        kind.code,
5286                        p.span,
5287                        format!(
5288                            "`by {name}` sends {} to an `Oidc` seam, but this handler's route has no `Oidc` seam that checks it",
5289                            kind.sends
5290                        ),
5291                    )
5292                    .with_note(format!(
5293                        "use `by {name}` on a route guarded by an `Oidc` actor{}",
5294                        kind.why_not_elsewhere
5295                    )),
5296                );
5297            }
5298            (n, _) if oidc_only_principal(n).is_some() => {}
5299            (BadCredential::Forged | BadCredential::Stale, None)
5300                if !(bad == BadCredential::Forged && (bearer || oidc)) =>
5301            {
5302                let err = CompileError::new(
5303                    "bynk.test.forged_needs_signature_route",
5304                    p.span,
5305                    if bad == BadCredential::Forged {
5306                        "`by Forged` sends a bad credential to a `Signature`, `Bearer` or `Oidc` seam, but this handler's route has none of these seams to refuse one".to_string()
5307                    } else {
5308                        "`by Stale` sends a stale signature to a `Signature` seam, but this handler's route has no `Signature` seam that refuses one".to_string()
5309                    },
5310                )
5311                .with_note(
5312                    "use `by Forged` on a route guarded by a `Signature`, `Bearer` or `Oidc` actor, and `by Stale` on a `Signature` one; `by Nobody` drives any of them to a `401`",
5313                );
5314                ctx.errors.push(with_open_sum_note(err, &handler, ctx));
5315            }
5316            (BadCredential::Stale, Some(seam))
5317                if seam.timestamp_header.is_none() || seam.tolerance_secs.is_none() =>
5318            {
5319                ctx.errors.push(
5320                    CompileError::new(
5321                        "bynk.test.stale_needs_timestamp",
5322                        p.span,
5323                        "`by Stale` signs in the past, but this route's `Signature` actor declares no `timestamp` header and `tolerance` for the seam to refuse it by",
5324                    )
5325                    .with_note(
5326                        "declare `timestamp = \"<Header>\"` and `tolerance = <seconds>` on the actor, or test the seam with `by Forged`",
5327                    ),
5328                );
5329            }
5330            _ => {}
5331        }
5332        if let Some(idv) = &p.identity {
5333            ctx.errors.push(CompileError::new(
5334                "bynk.test.actor_no_identity",
5335                p.span,
5336                format!("`{name}` presents a bad credential, not an identity, so it takes none — write `by {name}`"),
5337            ));
5338            let _ = type_of(idv, None, ctx);
5339        }
5340        return;
5341    }
5342
5343    if let Some(p) = principal {
5344        check_principal_admitted(&handler, p, ctx);
5345    }
5346
5347    // #2020: a sum (`by who: User | Visitor`) runs as whichever member
5348    // resolves, so the case may act as any member, each with its own identity.
5349    if let Some(by) = handler.by_clause.as_ref().filter(|by| by.is_sum()) {
5350        check_sum_principal(by, principal, value.span, ctx);
5351        return;
5352    }
5353
5354    let required = handler_actor_name(&handler, sig.protocol.as_deref())
5355        .map(|actor| resolve_actor_identity(&actor, ctx));
5356
5357    match (required, principal) {
5358        (Some(ActorIdentity::Typed(ty)), principal) => match principal {
5359            Some(p) => match resolve_actor_identity(&p.actor.name, ctx) {
5360                ActorIdentity::Unknown => report_principal_actor(p, ctx),
5361                ActorIdentity::Unit | ActorIdentity::CallerString => {
5362                    ctx.errors.push(CompileError::new(
5363                        "bynk.test.principal_identity_mismatch",
5364                        p.span,
5365                        format!(
5366                            "this handler runs as an actor carrying `{}`, but `by {}` supplies no matching identity",
5367                            ty.display(tys),
5368                            p.actor.name
5369                        ),
5370                    ));
5371                    if let Some(idv) = &p.identity {
5372                        let _ = type_of(idv, None, ctx);
5373                    }
5374                }
5375                ActorIdentity::Typed(_) => match &p.identity {
5376                    Some(idv) => {
5377                        let got = type_of(idv, Some(ty), ctx);
5378                        if let Some(g) = got
5379                            && !compatible(g, ty, tys)
5380                        {
5381                            ctx.errors.push(CompileError::new(
5382                                "bynk.types.argument_mismatch",
5383                                idv.span,
5384                                format!(
5385                                    "identity has type `{}`, but the handler expects `{}`",
5386                                    g.display(tys),
5387                                    ty.display(tys)
5388                                ),
5389                            ));
5390                        }
5391                    }
5392                    None => ctx.errors.push(CompileError::new(
5393                        "bynk.test.actor_identity_required",
5394                        p.span,
5395                        format!(
5396                            "actor `{}` carries an identity, so write `by {}(...)`",
5397                            p.actor.name, p.actor.name
5398                        ),
5399                    )),
5400                },
5401            },
5402            None => ctx.errors.push(
5403                CompileError::new(
5404                    "bynk.test.principal_required",
5405                    value.span,
5406                    format!(
5407                        "this handler runs as a verified actor carrying `{}`; the case must act as it with `by <Actor>(<identity>)`",
5408                        ty.display(tys)
5409                    ),
5410                )
5411                .with_note("append a call-site actor, e.g. `... by User(\"alice\")`"),
5412            ),
5413        },
5414        // #1978: an `on call` handler that binds its caller (`by c: Caller`)
5415        // reads `deps.identity`, the calling context's name. A test has no
5416        // calling context, so the case must name one with `by Caller("…")`;
5417        // without it the emitted call carries no identity and fails `tsc`.
5418        (Some(ActorIdentity::CallerString), principal) if handler_binds_caller(&handler, ctx) => {
5419            match principal {
5420                None => ctx.errors.push(
5421                    CompileError::new(
5422                        "bynk.test.actor_identity_required",
5423                        value.span,
5424                        "this handler binds its caller's identity (`by <binder>: Caller`), so the case must name the calling context with `by Caller(\"...\")`",
5425                    )
5426                    .with_note("append a call-site actor, e.g. `... by Caller(\"orders\")`"),
5427                ),
5428                Some(p) => match resolve_actor_identity(&p.actor.name, ctx) {
5429                    ActorIdentity::CallerString if p.identity.is_none() => {
5430                        ctx.errors.push(CompileError::new(
5431                            "bynk.test.actor_identity_required",
5432                            p.span,
5433                            format!(
5434                                "this handler binds its caller's identity, so write `by {}(\"...\")` naming the calling context",
5435                                p.actor.name
5436                            ),
5437                        ))
5438                    }
5439                    ActorIdentity::Unit => {
5440                        ctx.errors.push(CompileError::new(
5441                            "bynk.test.principal_identity_mismatch",
5442                            p.span,
5443                            format!(
5444                                "this handler binds its caller's identity, but `by {}` supplies none — write `by Caller(\"...\")`",
5445                                p.actor.name
5446                            ),
5447                        ));
5448                        if let Some(idv) = &p.identity {
5449                            let _ = type_of(idv, None, ctx);
5450                        }
5451                    }
5452                    _ => report_principal_actor(p, ctx),
5453                },
5454            }
5455        }
5456        (_, Some(p)) => report_principal_actor(p, ctx),
5457        (_, None) => {}
5458    }
5459}
5460
5461/// #2020: check a call-site principal against a handler whose `by` clause is
5462/// an actor sum (`by who: User | Visitor`, or an `on call` sum such as
5463/// `Caller | Legacy`). The handler reads the resolved member as `deps.who`, so
5464/// the case must name a member, with exactly the identity that member
5465/// carries: `by User("ada")` or `by Visitor`. A non-member, or no `by` at all,
5466/// would leave `deps.who` unbuilt.
5467fn check_sum_principal(
5468    by: &bynk_syntax::ast::ByClause,
5469    principal: Option<&bynk_syntax::ast::CallSiteActor>,
5470    value_span: Span,
5471    ctx: &mut Ctx,
5472) {
5473    let members = format!(
5474        "`{}`",
5475        by.actors
5476            .iter()
5477            .map(|a| a.name.as_str())
5478            .collect::<Vec<_>>()
5479            .join(" | ")
5480    );
5481    let Some(p) = principal else {
5482        ctx.errors.push(
5483            CompileError::new(
5484                "bynk.test.principal_required",
5485                value_span,
5486                format!(
5487                    "this handler runs as one of the actors {members}; the case must act as one with `by <Actor>`"
5488                ),
5489            )
5490            .with_note(format!(
5491                "append a call-site actor naming a member, e.g. `... by {}`",
5492                sum_member_example(&by.actors[0].name, ctx)
5493            )),
5494        );
5495        return;
5496    };
5497    let name = &p.actor.name;
5498    if !by.actors.iter().any(|a| &a.name == name) {
5499        if matches!(resolve_actor_identity(name, ctx), ActorIdentity::Unknown) {
5500            report_principal_actor(p, ctx);
5501            return;
5502        }
5503        ctx.errors.push(
5504            CompileError::new(
5505                "bynk.test.principal_identity_mismatch",
5506                p.span,
5507                format!(
5508                    "this handler runs as one of the actors {members}, but `by {name}` names none of them"
5509                ),
5510            )
5511            .with_note("act as a member of the handler's `by` sum"),
5512        );
5513        if let Some(idv) = &p.identity {
5514            let _ = type_of(idv, None, ctx);
5515        }
5516        return;
5517    }
5518    match resolve_actor_identity(name, ctx) {
5519        // The sum's `Caller` arm carries the calling context's name
5520        // (`{ tag: "Caller", identity: string }`), so it must be named.
5521        ActorIdentity::CallerString if p.identity.is_none() => ctx.errors.push(CompileError::new(
5522            "bynk.test.actor_identity_required",
5523            p.span,
5524            format!(
5525                "the `{name}` arm carries the calling context's name, so write `by {name}(\"...\")`"
5526            ),
5527        )),
5528        _ => report_principal_actor(p, ctx),
5529    }
5530}
5531
5532/// An example call-site principal for a sum member, for a note.
5533fn sum_member_example(name: &str, ctx: &Ctx) -> String {
5534    match resolve_actor_identity(name, ctx) {
5535        ActorIdentity::Typed(_) | ActorIdentity::CallerString => format!("{name}(...)"),
5536        ActorIdentity::Unit | ActorIdentity::Unknown => name.to_string(),
5537    }
5538}
5539
5540/// #1978: whether an `on call` handler binds the prelude `Caller`'s identity
5541/// (`by c: Caller`), so its emitted `deps` requires `identity`. This mirrors
5542/// `bynk_model::lower_actor_seam_ir`, which resolves a sum `by` clause
5543/// (`by who: Caller | …`) as a sum (`deps.who`) before it consults
5544/// [`crate::actors::caller_binder_for`]; hence the `!is_sum()` that
5545/// `caller_binder_for` alone does not need.
5546fn handler_binds_caller(handler: &TestHandler, ctx: &Ctx) -> bool {
5547    use crate::actors::{Identity, prelude_actor};
5548    let Some(by) = &handler.by_clause else {
5549        return false;
5550    };
5551    let Some(binder) = &by.binder else {
5552        return false;
5553    };
5554    let name = &by.primary().name;
5555    matches!(handler.kind, bynk_syntax::ast::HandlerKind::Call)
5556        && !by.is_sum()
5557        && (!ctx.test_actors.contains_key(name)
5558            && prelude_actor(name).map(|c| c.identity) == Some(Identity::CallerId)
5559            // #3890: a refinement over `Caller` binds the same `CallerId`.
5560            || ctx.test_actors.get(name).is_some_and(|d| {
5561                crate::actors::caller_refinement(d, &ctx.test_actors).is_some()
5562            }))
5563        && !handler.params.iter().any(|p| p.name.name == binder.name)
5564}
5565
5566/// #3890: a call-site `by <Actor>("<context>")` names a calling context. When the
5567/// handler's actor, or the named one, is a refinement over `Caller` whose
5568/// predicate refuses that context, the case could never be admitted:
5569/// `bynk.actor.caller_not_admitted`, as at a call site in the program.
5570fn check_principal_admitted(
5571    handler: &TestHandler,
5572    p: &bynk_syntax::ast::CallSiteActor,
5573    ctx: &mut Ctx,
5574) {
5575    let Some(idv) = &p.identity else {
5576        return;
5577    };
5578    let ExprKind::StrLit(context) = &idv.kind else {
5579        return;
5580    };
5581    let mut names = vec![p.actor.name.clone()];
5582    if let Some(by) = handler.by_clause.as_ref().filter(|by| !by.is_sum()) {
5583        names.push(by.primary().name.clone());
5584    }
5585    names.dedup();
5586    for name in names {
5587        let Some(pred) = ctx
5588            .test_actors
5589            .get(&name)
5590            .and_then(|d| crate::actors::caller_refinement(d, &ctx.test_actors))
5591        else {
5592            continue;
5593        };
5594        if !pred.admits(context) {
5595            ctx.errors.push(
5596                CompileError::new(
5597                    "bynk.actor.caller_not_admitted",
5598                    idv.span,
5599                    format!("`{name}` does not admit calls from `{context}`"),
5600                )
5601                .with_note(format!(
5602                    "the actor is `Caller` refined by `IsContext(…)`, which names the contexts that may call; this case names `{context}`"
5603                )),
5604            );
5605            return;
5606        }
5607    }
5608}
5609
5610/// Resolve a call-site principal actor for its own diagnostics (v0.182).
5611fn report_principal_actor(p: &bynk_syntax::ast::CallSiteActor, ctx: &mut Ctx) {
5612    let tys = ctx.tys;
5613    let name = &p.actor.name;
5614    let kind = record_principal(p, ctx);
5615    match resolve_actor_identity(name, ctx) {
5616        // A declared actor that resolves to nothing is a malformed refinement,
5617        // already reported at its declaration
5618        // (`bynk.actor.refinement_base_unsupported`). It is still an actor of
5619        // the target, so `unknown_actor` would mislead.
5620        ActorIdentity::Unknown if ctx.test_actors.contains_key(name) => {
5621            if let Some(id) = &p.identity {
5622                let _ = type_of(id, None, ctx);
5623            }
5624        }
5625        // #2135, #2864: a reserved bad-credential principal reaching no http
5626        // route (a `call`, an event, a cron or queue address) has no
5627        // `Signature` or `Bearer` seam to refuse it.
5628        ActorIdentity::Unknown if matches!(kind, CallSitePrincipal::BadCredential(_)) => {
5629            let CallSitePrincipal::BadCredential(bad) = kind else {
5630                unreachable!("matched above")
5631            };
5632            let err = if bad == BadCredential::Expired {
5633                CompileError::new(
5634                    "bynk.test.expired_needs_bearer_route",
5635                    p.span,
5636                    "`by Expired` sends an expired token to a `Bearer` or `Oidc` seam, but this address reaches no `Bearer`- or `Oidc`-secured http route",
5637                )
5638                .with_note("use `by Expired` on an http route guarded by a `Bearer` or `Oidc` actor")
5639            } else if let Some(kind) = oidc_only_principal(bad) {
5640                CompileError::new(
5641                    kind.code,
5642                    p.span,
5643                    format!("`by {name}` sends {} to an `Oidc` seam, but this address reaches no `Oidc`-secured http route", kind.sends),
5644                )
5645                .with_note(format!("use `by {name}` on an http route guarded by an `Oidc` actor"))
5646            } else {
5647                CompileError::new(
5648                    "bynk.test.forged_needs_signature_route",
5649                    p.span,
5650                    format!("`by {name}` sends a bad credential to a `Signature`, `Bearer` or `Oidc` seam, but this address reaches no `Signature`-, `Bearer`- or `Oidc`-secured http route"),
5651                )
5652                .with_note("use `by Forged` on an http route guarded by a `Signature`, `Bearer` or `Oidc` actor, and `by Stale` on a `Signature` one")
5653            };
5654            ctx.errors.push(err);
5655            if let Some(id) = &p.identity {
5656                let _ = type_of(id, None, ctx);
5657            }
5658        }
5659        ActorIdentity::Unknown => {
5660            ctx.errors.push(
5661                CompileError::new(
5662                    "bynk.test.unknown_actor",
5663                    p.actor.span,
5664                    format!("`{name}` is not an actor of the target context or a prelude actor"),
5665                )
5666                .with_note("name an `actor` the target declares, or a prelude actor (`Visitor`, `Caller`, …)"),
5667            );
5668            if let Some(id) = &p.identity {
5669                let _ = type_of(id, None, ctx);
5670            }
5671        }
5672        ActorIdentity::Typed(ty) => match &p.identity {
5673            Some(id) => {
5674                let got = type_of(id, Some(ty), ctx);
5675                if let Some(g) = got
5676                    && !compatible(g, ty, tys)
5677                {
5678                    ctx.errors.push(CompileError::new(
5679                        "bynk.types.argument_mismatch",
5680                        id.span,
5681                        format!(
5682                            "identity has type `{}`, but actor `{name}` expects `{}`",
5683                            g.display(tys),
5684                            ty.display(tys)
5685                        ),
5686                    ));
5687                }
5688            }
5689            None => ctx.errors.push(CompileError::new(
5690                "bynk.test.actor_identity_required",
5691                p.span,
5692                format!("actor `{name}` carries an identity, so `by {name}(...)` needs an identity value"),
5693            )),
5694        },
5695        ActorIdentity::CallerString => {
5696            if let Some(id) = &p.identity {
5697                let _ = type_of(id, None, ctx);
5698            }
5699        }
5700        ActorIdentity::Unit => {
5701            if let Some(id) = &p.identity {
5702                let _ = type_of(id, None, ctx);
5703                ctx.errors.push(CompileError::new(
5704                    "bynk.test.actor_no_identity",
5705                    p.span,
5706                    format!("actor `{name}` has no identity, so write `by {name}` with no argument"),
5707                ));
5708            }
5709        }
5710    }
5711}
5712
5713/// #2910: `bynk.test.extra_headers_authorization` — request headers sent
5714/// beside a route's declared parameters may not carry `Authorization`: the
5715/// case's `by <Actor>` owns the credential. Checked on the literal form
5716/// `RequestHeaders.of(["…", …])`, written in the call or bound by a local `let`
5717/// (see `check_extra_headers_let`); a value built elsewhere is not inspected.
5718fn check_extra_headers_authorization(arg: &Expr, ctx: &mut Ctx) {
5719    ctx.errors.extend(extra_headers_authorization_errors(arg));
5720}
5721
5722/// The `bynk.test.extra_headers_authorization` errors for one headers value.
5723/// `pub(crate)` so the suite pass can run it on the `RequestHeaders.of([…])`
5724/// a local `let` bound before the call passed by name.
5725pub(crate) fn extra_headers_authorization_errors(arg: &Expr) -> Vec<CompileError> {
5726    use bynk_syntax::ast::ExprKind as EK;
5727    let mut errors = Vec::new();
5728    let EK::MethodCall {
5729        receiver,
5730        method,
5731        args,
5732        ..
5733    } = &arg.kind
5734    else {
5735        return errors;
5736    };
5737    let (EK::Ident(r), "of", Some(EK::ListLit(lines, ..))) = (
5738        &receiver.kind,
5739        method.name.as_str(),
5740        args.first().map(|a| &a.kind),
5741    ) else {
5742        return errors;
5743    };
5744    if r.name != REQUEST_HEADERS {
5745        return errors;
5746    }
5747    for line in lines {
5748        if let EK::StrLit(text) = &line.kind
5749            && text
5750                .split_once(':')
5751                .is_some_and(|(n, _)| n.trim().eq_ignore_ascii_case("authorization"))
5752        {
5753            errors.push(
5754                CompileError::new(
5755                    "bynk.test.extra_headers_authorization",
5756                    line.span,
5757                    "`Authorization` cannot be sent as an extra request header",
5758                )
5759                .with_note("the case's `by <Actor>` owns the credential the driver sends; choose the actor instead"),
5760            );
5761        }
5762    }
5763    errors
5764}
5765
5766/// #2904: `Wire(…)` drives an http body or path segment (the book documents it
5767/// nowhere else). A queue message, cron tick, `on call` or event address has no
5768/// raw text form to deliver, so it would be handed to a typed codec as a
5769/// string and fail at run time with a misleading error.
5770fn is_wire(e: &Expr) -> bool {
5771    matches!(e.kind, bynk_syntax::ast::ExprKind::Wire(_))
5772}
5773
5774/// A rejected `Wire(inner)` argument still has its inner typed against
5775/// `String`, as `check_address_args` does, so an unknown name inside it reports.
5776fn type_wire_inner(e: &Expr, ctx: &mut Ctx) {
5777    if let bynk_syntax::ast::ExprKind::Wire(inner) = &e.kind {
5778        let string = ctx.tys.intern(Ty::Base(BaseType::String));
5779        let _ = type_of(inner, Some(string), ctx);
5780    }
5781}
5782
5783fn reject_wire_args(svc: &str, addr: &str, args: &[Expr], ctx: &mut Ctx) {
5784    for a in args {
5785        if is_wire(a) {
5786            ctx.errors.push(
5787                CompileError::new(
5788                    "bynk.test.wire_http_only",
5789                    a.span,
5790                    format!("`Wire(...)` cannot be passed to `{svc}.{addr}`"),
5791                )
5792                .with_note(
5793                    "`Wire` drives an http body or path segment; pass a queue message, cron tick or event as a typed value",
5794                ),
5795            );
5796        }
5797    }
5798}
5799
5800/// Shared arity + argument-type check for a resolved test-body service address.
5801/// `positional` are the arguments that map to the handler's declared params (for
5802/// http/cron the leading pattern string has already been split off).
5803fn check_address_args(
5804    svc: &str,
5805    addr: &str,
5806    params: &[bynk_syntax::ast::Param],
5807    positional: &[Expr],
5808    err_span: Span,
5809    ctx: &mut Ctx,
5810) {
5811    let tys = ctx.tys;
5812    if addr == "call" || addr == "schedule" || addr == "message" {
5813        reject_wire_args(svc, addr, positional, ctx);
5814    }
5815    if params.len() != positional.len() {
5816        ctx.errors.push(
5817            CompileError::new(
5818                "bynk.test.service_call_arity",
5819                err_span,
5820                format!(
5821                    "`{svc}.{addr}` expects {} argument(s), but {} were given",
5822                    params.len(),
5823                    positional.len()
5824                ),
5825            )
5826            // Finding #46: `handler_span` is the target unit's handler — a
5827            // test file and the unit it tests are normally different files.
5828            .with_note("handler declared here"),
5829        );
5830        for a in positional {
5831            if is_wire(a) {
5832                type_wire_inner(a, ctx);
5833            } else {
5834                let _ = type_of(a, None, ctx);
5835            }
5836        }
5837        return;
5838    }
5839    for (i, (param, arg)) in params.iter().zip(positional.iter()).enumerate() {
5840        record_param_hint(ctx.hints, &param.name.name, arg);
5841        // Slice C: a `Wire(<String>)` argument is *raw* — it deliberately bypasses
5842        // the param's type so a case can drive the boundary with input the type
5843        // forbids. Validate only that the inner is a `String` (the wire form); the
5844        // `system`-only tier rule is enforced at emit time (where the tier is
5845        // known), alongside `system_needs_wire`. Intercept before the generic
5846        // `type_of`, which would otherwise report the address-arg `Wire` as
5847        // misplaced.
5848        if let bynk_syntax::ast::ExprKind::Wire(inner) = &arg.kind {
5849            let _ = type_of(inner, Some(tys.intern(Ty::Base(BaseType::String))), ctx);
5850            continue;
5851        }
5852        let expected = resolve_type_ref(&param.type_ref, &ctx.input.types, tys);
5853        let arg_ty = type_of(arg, expected, ctx);
5854        if let (Some(a), Some(p)) = (arg_ty, expected)
5855            && !compatible(a, p, tys)
5856        {
5857            ctx.errors.push(CompileError::new(
5858                "bynk.types.argument_mismatch",
5859                arg.span,
5860                format!(
5861                    "argument {} has type `{}`, but `{svc}.{addr}` expects `{}` for `{}`",
5862                    i + 1,
5863                    a.display(tys),
5864                    p.display(tys),
5865                    param.name.name
5866                ),
5867            ));
5868        }
5869    }
5870}
5871
5872/// #2052: arity and argument types of `svc.event(payload)` /
5873/// `svc.event(payload, envelope)`. The payload is typed against the handler's
5874/// first parameter, which `bynk.event.handler_param_type_mismatch` holds to the
5875/// header's event type `E`; the envelope against `EventEnvelope`, whether or
5876/// not the handler declares one (a `via schema(N)` guard reads it either way).
5877fn check_event_address(
5878    sig: &TestServiceSig,
5879    id: &Ident,
5880    handler: &TestHandler,
5881    args: &[Expr],
5882    err_span: Span,
5883    ctx: &mut Ctx,
5884) {
5885    let tys = ctx.tys;
5886    let svc = &id.name;
5887    reject_wire_args(svc, "event", args, ctx);
5888    if args.is_empty() || args.len() > 2 {
5889        ctx.errors.push(
5890            CompileError::new(
5891                "bynk.test.service_call_arity",
5892                err_span,
5893                format!(
5894                    "`{svc}.event` takes the event and, optionally, an `EventEnvelope`, but {} argument(s) were given",
5895                    args.len()
5896                ),
5897            )
5898            .with_note("deliver an event with `svc.event(e)`, or `svc.event(e, env)` to choose its envelope"),
5899        );
5900        for a in args {
5901            if is_wire(a) {
5902                type_wire_inner(a, ctx);
5903            } else {
5904                let _ = type_of(a, None, ctx);
5905            }
5906        }
5907        return;
5908    }
5909    // #2052 review: a default envelope names the event's publisher, which must
5910    // resolve to one context, as the service's header resolves `E`.
5911    if args.len() == 1
5912        && let Some(Err(candidates)) = &sig.event_publisher
5913    {
5914        let found = if candidates.is_empty() {
5915            "no context the target declares or consumes declares it".to_string()
5916        } else {
5917            format!(
5918                "it is declared by {}",
5919                candidates
5920                    .iter()
5921                    .map(|c| format!("`{c}`"))
5922                    .collect::<Vec<_>>()
5923                    .join(", ")
5924            )
5925        };
5926        ctx.errors.push(
5927            CompileError::new(
5928                "bynk.test.event_publisher_ambiguous",
5929                err_span,
5930                format!("`{svc}.event(e)` has no single publisher to name in its default envelope: {found}"),
5931            )
5932            .with_note("pass the envelope yourself: `svc.event(e, env)`"),
5933        );
5934    }
5935    let payload = &args[0];
5936    type_wire_inner(payload, ctx);
5937    if !is_wire(payload) {
5938        let expected = handler
5939            .params
5940            .first()
5941            .and_then(|p| resolve_type_ref(&p.type_ref, &ctx.input.types, tys));
5942        let arg_ty = type_of(payload, expected, ctx);
5943        if let (Some(a), Some(p)) = (arg_ty, expected)
5944            && !compatible(a, p, tys)
5945        {
5946            let other_event = match &*tys.get(a) {
5947                Ty::Named { name, .. } if sig.known_events.contains(name) => Some(name.clone()),
5948                _ => None,
5949            };
5950            let err = match other_event {
5951                Some(other) => CompileError::new(
5952                    "bynk.test.event_not_subscribed",
5953                    payload.span,
5954                    format!(
5955                        "`{svc}` subscribes to `{}`, not `{other}`",
5956                        p.display(tys)
5957                    ),
5958                )
5959                .with_note(
5960                    "an event address delivers only the event the service's `from Events(E)` header names",
5961                ),
5962                None => CompileError::new(
5963                    "bynk.types.argument_mismatch",
5964                    payload.span,
5965                    format!(
5966                        "argument 1 has type `{}`, but `{svc}.event` expects the event it subscribes to, `{}`",
5967                        a.display(tys),
5968                        p.display(tys)
5969                    ),
5970                ),
5971            };
5972            ctx.errors.push(err);
5973        }
5974    }
5975    let Some(envelope) = args.get(1) else {
5976        return;
5977    };
5978    if is_wire(envelope) {
5979        type_wire_inner(envelope, ctx);
5980        return;
5981    }
5982    let envelope_ref = TypeRef::Named(Ident {
5983        name: "EventEnvelope".to_string(),
5984        span: envelope.span,
5985    });
5986    let expected = resolve_type_ref(&envelope_ref, &ctx.input.types, tys);
5987    let env_ty = type_of(envelope, expected, ctx);
5988    let Some(a) = env_ty else {
5989        return;
5990    };
5991    // `EventEnvelope` is `bynk`'s; a suite names it only when its target
5992    // consumes `bynk`, and no other value is one.
5993    let mismatch = match expected {
5994        Some(p) => !compatible(a, p, tys),
5995        None => true,
5996    };
5997    if mismatch {
5998        let mut err = CompileError::new(
5999            "bynk.types.argument_mismatch",
6000            envelope.span,
6001            format!(
6002                "argument 2 has type `{}`, but `{svc}.event` expects an `EventEnvelope`",
6003                a.display(tys)
6004            ),
6005        );
6006        if expected.is_none() {
6007            err = err.with_note(
6008                "`EventEnvelope` comes from `bynk`; the suite's target must `consumes bynk` to build one",
6009            );
6010        }
6011        ctx.errors.push(err);
6012    }
6013}
6014
6015/// If `receiver` resolves to a consumed-context prefix (an alias or a
6016/// dotted qualified name appearing in `consumes`), return the consumed
6017/// context's qualified name. Otherwise None. Local bindings, types, and
6018/// capabilities take precedence — those are checked at the call site.
6019fn cross_context_prefix(receiver: &Expr, ctx: &Ctx) -> Option<String> {
6020    let info = &ctx.input.cross_context;
6021    if info.consumed_contexts.is_empty() && info.aliases.is_empty() {
6022        return None;
6023    }
6024    // Walk the receiver to assemble a candidate dotted name. Supports:
6025    //   Ident(X)                                 -> "X"
6026    //   FieldAccess { Ident(A), B }              -> "A.B"
6027    //   FieldAccess { FieldAccess { Ident(A), B }, C } -> "A.B.C"
6028    let candidate = flatten_ident_chain(receiver)?;
6029    let head = candidate.split('.').next().unwrap_or("");
6030    // The head must not shadow a local binding / capability / declared type.
6031    if ctx.lookup(head).is_some() {
6032        return None;
6033    }
6034    if ctx.caps.capabilities.contains_key(head) || ctx.caps.declared_capabilities.contains_key(head)
6035    {
6036        return None;
6037    }
6038    // If the head is a known local type, only an alias whose name happens to
6039    // collide could redirect this; aliases conflicting with types are an
6040    // error in project.rs, so a clash here is impossible at this point.
6041    info.resolve_prefix(candidate.as_str())
6042}
6043
6044/// Flatten an `Ident`/`FieldAccess` chain into its dotted name, or None if
6045/// any segment isn't a bare identifier.
6046fn flatten_ident_chain(expr: &Expr) -> Option<String> {
6047    match &expr.kind {
6048        ExprKind::Ident(id) => Some(id.name.clone()),
6049        ExprKind::FieldAccess { receiver, field } => {
6050            let head = flatten_ident_chain(receiver)?;
6051            Some(format!("{head}.{}", field.name))
6052        }
6053        _ => None,
6054    }
6055}
6056
6057/// Type-check a cross-context service call (v0.6 §4.2). `receiver` carries
6058/// the prefix's source span for diagnostics. `consumed` is the resolved
6059/// qualified name of the consumed context.
6060/// v0.15: type-check a cross-context capability call `B.Cap.op(args)` /
6061/// `Alias.Cap.op(args)`. The capability operation signatures are carried in
6062/// `consumed_capabilities` (in the providing context's namespace); the
6063/// capability must be listed in the handler/provider's `given` clause.
6064#[allow(clippy::too_many_arguments)]
6065fn check_cross_context_capability_call(
6066    receiver: &Expr,
6067    consumed: &str,
6068    cap: &str,
6069    method: &Ident,
6070    // #926 (Decision G): explicit type arguments for a generic capability
6071    // operation, qualified form (`B.Cap.op[T](…)` / `Alias.Cap.op[T](…)`).
6072    type_args: &[TypeRef],
6073    args: &[Expr],
6074    span: Span,
6075    // P6.0 (#1139): the outer `MethodCall` expression's own identity.
6076    expr_id: ExprId,
6077    ctx: &mut Ctx,
6078) -> Option<TyId> {
6079    let tys = ctx.tys;
6080    // S3 (#1963): a qualified capability's operation, `U.Cap.op`.
6081    refuse_experimental(
6082        &format!("{consumed}.{cap}.{}", method.name),
6083        method.span,
6084        ctx,
6085    );
6086    ctx.callees.insert(
6087        expr_id,
6088        Callee::CrossCap {
6089            unit: consumed.to_string(),
6090            cap: cap.to_string(),
6091            op: method.name.clone(),
6092            wire: None,
6093            first_party: cross_first_party(consumed, cap),
6094        },
6095    );
6096    // Capability calls require an effectful body (same rule as local ones).
6097    if !ctx.effectful {
6098        ctx.errors.push(CompileError::new(
6099            "bynk.effect.capability_in_pure_context",
6100            method.span,
6101            format!(
6102                "capability `{consumed}.{cap}` can only be called inside an effectful body (one returning `Effect[T]`)"
6103            ),
6104        ));
6105    }
6106    // The capability must be declared in this handler/provider's `given`.
6107    // The local deps key is the capability's simple name.
6108    if !ctx.caps.given_remaining.contains(cap) {
6109        let mut err = CompileError::new(
6110            "bynk.given.undeclared_capability",
6111            receiver.span,
6112            format!("capability `{consumed}.{cap}` is used but not listed in the `given` clause"),
6113        )
6114        .with_note(format!(
6115            "add `{consumed}.{cap}` to the handler's `given` clause so the dependency surface is visible at the declaration site"
6116        ));
6117        // v0.26 (ADR 0054): the one-click counterpart of the note — the
6118        // clause entry is the qualified form the user writes (`B.Cap`).
6119        if let Some((span, insert)) = given_insertion_edit(
6120            &ctx.caps.given_entries,
6121            ctx.caps.given_anchor,
6122            &format!("{consumed}.{cap}"),
6123        ) {
6124            err = err.with_suggestion(
6125                format!("add `{consumed}.{cap}` to the `given` clause"),
6126                vec![(span, insert)],
6127                Applicability::MachineApplicable,
6128            );
6129        }
6130        ctx.errors.push(err);
6131        for a in args {
6132            let _ = type_of(a, None, ctx);
6133        }
6134        return None;
6135    }
6136    ctx.caps.given_used.insert(cap.to_string());
6137
6138    let info = &ctx.input.cross_context;
6139    let op = info
6140        .consumed_capabilities
6141        .get(consumed)
6142        .and_then(|caps| caps.get(cap))
6143        .and_then(|c| c.ops.iter().find(|o| o.name == method.name))
6144        .cloned();
6145    let Some(op) = op else {
6146        ctx.errors.push(CompileError::new(
6147            "bynk.capability.unknown_operation",
6148            method.span,
6149            format!(
6150                "capability `{consumed}.{cap}` has no operation named `{}`",
6151                method.name
6152            ),
6153        ));
6154        for a in args {
6155            let _ = type_of(a, None, ctx);
6156        }
6157        return None;
6158    };
6159    // v0.36 (ADR 0069, slice 2): a cross-context op call references the op,
6160    // recorded already-qualified into the providing unit (where the op is
6161    // declared), mirroring the cross-context capability reference.
6162    ctx.refs.record_in_unit(
6163        method.span,
6164        SymbolKind::CapabilityOp,
6165        &format!("{cap}.{}", method.name),
6166        consumed,
6167    );
6168    if op.params.len() != args.len() {
6169        ctx.errors.push(CompileError::new(
6170            "bynk.capability.op_arity",
6171            method.span,
6172            format!(
6173                "capability operation `{consumed}.{cap}.{}` expects {} argument(s), but {} were given",
6174                method.name,
6175                op.params.len(),
6176                args.len()
6177            ),
6178        ));
6179        for a in args {
6180            let _ = type_of(a, None, ctx);
6181        }
6182        return None;
6183    }
6184
6185    // Resolve parameter / return types in the consumed context's namespace.
6186    let consumed_types = info
6187        .consumed_types
6188        .get(consumed)
6189        .cloned()
6190        .unwrap_or_default();
6191    // #926: resolve the op's own type parameter(s) — declared in the
6192    // *consumed* context's namespace but instantiated from an explicit type
6193    // argument named in the *calling* context's own namespace (same split
6194    // `resolve_type_ref`/`resolve_expr_type_ref` already draw for
6195    // params/return vs. call-site type args in the local-capability path,
6196    // `check_static_call`). Explicit only, never inferred.
6197    let vars: HashSet<String> = op.type_params.iter().cloned().collect();
6198    let mut subst: HashMap<String, TyId> = HashMap::new();
6199    if !op.type_params.is_empty() || !type_args.is_empty() {
6200        if type_args.is_empty() {
6201            ctx.errors.push(
6202                CompileError::new(
6203                    "bynk.generics.uninferable_type_arg",
6204                    method.span,
6205                    format!(
6206                        "capability operation `{consumed}.{cap}.{}` takes a type parameter, but none of its arguments determine it",
6207                        method.name
6208                    ),
6209                )
6210                .with_note(format!(
6211                    "a qualified cross-context call takes its type arguments explicitly: `{consumed}.{cap}.{}[T](…)`",
6212                    method.name
6213                )),
6214            );
6215            for a in args {
6216                let _ = type_of(a, None, ctx);
6217            }
6218            return None;
6219        }
6220        if type_args.len() != op.type_params.len() {
6221            ctx.errors.push(CompileError::new(
6222                "bynk.generics.type_arg_mismatch",
6223                method.span,
6224                format!(
6225                    "capability operation `{consumed}.{cap}.{}` takes {} type argument(s), but {} were given",
6226                    method.name,
6227                    op.type_params.len(),
6228                    type_args.len()
6229                ),
6230            ));
6231            for a in args {
6232                let _ = type_of(a, None, ctx);
6233            }
6234            return None;
6235        }
6236        for (tp, ta) in op.type_params.iter().zip(type_args) {
6237            let ty = resolve_expr_type_ref(ta, ctx)?;
6238            subst.insert(tp.clone(), ty);
6239        }
6240    }
6241    // Slice 3: each `Codable` type parameter takes a codable type, and the call
6242    // records how it encodes the parameters that mention one.
6243    if !op.codable_params.is_empty() {
6244        if !check_op_codable_args(
6245            &format!("{consumed}.{cap}.{}", method.name),
6246            method.span,
6247            &op.codable_params,
6248            &subst,
6249            ctx,
6250        ) {
6251            for a in args {
6252                let _ = type_of(a, None, ctx);
6253            }
6254            return None;
6255        }
6256        let patterns: Vec<TyId> = op
6257            .params
6258            .iter()
6259            .map(|(_, tr)| {
6260                resolve_type_ref_in(tr, &consumed_types, &vars, tys).unwrap_or(tys.intern(Ty::Unit))
6261            })
6262            .collect();
6263        let ret_pattern = resolve_type_ref_in(&op.return_type, &consumed_types, &vars, tys)
6264            .unwrap_or(tys.intern(Ty::Unit));
6265        if let Some(wire) = op_encoding(
6266            &op.type_params,
6267            &op.codable_params,
6268            &patterns,
6269            ret_pattern,
6270            op.reply_policy,
6271            &subst,
6272            tys,
6273        ) {
6274            if !check_reply_codable(
6275                &format!("{consumed}.{cap}.{}", method.name),
6276                method.span,
6277                &op.codable_params,
6278                &wire,
6279                ctx,
6280            ) {
6281                for a in args {
6282                    let _ = type_of(a, None, ctx);
6283                }
6284                return None;
6285            }
6286            ctx.callees.insert(
6287                expr_id,
6288                Callee::CrossCap {
6289                    unit: consumed.to_string(),
6290                    cap: cap.to_string(),
6291                    op: method.name.clone(),
6292                    wire: Some(wire),
6293                    first_party: cross_first_party(consumed, cap),
6294                },
6295            );
6296        }
6297    }
6298    // #1941: a value this caller holds may be of a consumed context's
6299    // unexported type, which only the projection resolves.
6300    let (caller_types, ambiguous) = projected_types(&ctx.input.types, &info.consumed_types, tys);
6301    let mut all_ok = true;
6302    for (i, ((pname, ptype_ref), arg)) in op.params.iter().zip(args.iter()).enumerate() {
6303        record_param_hint(ctx.hints, pname, arg);
6304        let param_ty = resolve_type_ref_in(ptype_ref, &consumed_types, &vars, tys)
6305            .unwrap_or(tys.intern(Ty::Unit));
6306        let param_ty = substitute(param_ty, &subst, tys);
6307        // #2025: against the parameter's type; see `type_cross_context_arg`.
6308        let (arg_ty, crosses) =
6309            type_cross_context_arg(arg, param_ty, &caller_types, &consumed_types, consumed, ctx);
6310        let Some(arg_ty) = arg_ty else {
6311            all_ok = false;
6312            continue;
6313        };
6314        if !crosses {
6315            let mut err = CompileError::new(
6316                "bynk.boundary.structural_mismatch",
6317                arg.span,
6318                format!(
6319                    "cross-context argument {} to `{consumed}.{cap}.{}` has type `{}`, but parameter `{pname}` expects `{}`",
6320                    i + 1,
6321                    method.name,
6322                    arg_ty.display(tys),
6323                    param_ty.display(tys),
6324                ),
6325            );
6326            if let Some(note) = ambiguous_projection_note(arg_ty, &ambiguous, tys) {
6327                err = err.with_note(note);
6328            }
6329            ctx.errors.push(err);
6330            all_ok = false;
6331        }
6332    }
6333    if !all_ok {
6334        return None;
6335    }
6336    let raw_ret = resolve_type_ref_in(&op.return_type, &consumed_types, &vars, tys)
6337        .unwrap_or(tys.intern(Ty::Unit));
6338    let raw_ret = substitute(raw_ret, &subst, tys);
6339    let rebrand_types = rebrand_table(&ctx.input.types, &consumed_types);
6340    if let Some(name) =
6341        rebrand_conflict(raw_ret, &consumed_types, &rebrand_types, &caller_types, tys)
6342    {
6343        ctx.errors.push(rebranded_return_mismatch(
6344            &format!("{consumed}.{cap}.{}", method.name),
6345            &name,
6346            consumed,
6347            false,
6348            span,
6349            ctx,
6350        ));
6351        return None;
6352    }
6353    Some(rebrand_return_type(raw_ret, &rebrand_types, tys))
6354}
6355
6356/// #1941: a returned value takes the caller's type of the same name (§6.5).
6357/// When that type has a different shape, the value is not one of it: the
6358/// caller's own `Box` would otherwise type a field read of the provider's.
6359fn rebranded_return_mismatch(
6360    callee: &str,
6361    name: &str,
6362    consumed: &str,
6363    in_param: bool,
6364    span: Span,
6365    ctx: &Ctx,
6366) -> CompileError {
6367    let caller = ctx
6368        .input
6369        .cross_context
6370        .self_context
6371        .as_deref()
6372        .unwrap_or("?");
6373    CompileError::new(
6374        "bynk.boundary.structural_mismatch",
6375        span,
6376        format!(
6377            "cross-context call `{callee}` {} `{consumed}`'s type `{name}`, but `{name}` in \
6378             `{caller}` is a different type",
6379            if in_param {
6380                "takes as a parameter"
6381            } else {
6382                "returns"
6383            }
6384        ),
6385    )
6386    .with_note(
6387        "a value crossing the boundary takes the receiving context's type of the same name, so \
6388         the two must be structurally compatible; rename one of them",
6389    )
6390}
6391
6392/// #2025, #2039, #2072: type one cross-context argument against its
6393/// parameter's type, returning the type and whether the argument crosses the
6394/// boundary.
6395///
6396/// A literal at a refined position in the parameter's type is admitted
6397/// against that type's own declaration, from the consumed context's table.
6398/// This covers a literal passed directly (`t.pay.charge(250)`) and one
6399/// nested in an `Option`/`Result` payload, a list element, or a field of a
6400/// record literal, a generic one included (`t.pay.maybe(Some(250))`,
6401/// `Page { items: [250] }`). It is checked against the callee's predicate,
6402/// whether or not the caller `uses` the declaring commons and whatever the
6403/// caller binds under that name. Such a literal is the callee's type by
6404/// construction, so it needs no structural check; neither does a `None` or
6405/// an empty list, which take the parameter's type as their hint.
6406///
6407/// Every other part of the argument is a *leaf*, typed in the caller's own
6408/// scope with its position's type as the hint, and the structural check
6409/// decides whether each leaf crosses. A shorthand record field (`{ cents }`)
6410/// is a leaf too, checked by its binding's type. An argument with no literal
6411/// or empty constructor in it is a single leaf, so it is checked whole, as
6412/// before; a leaf `type_of` did not record falls back to the whole argument
6413/// too.
6414fn type_cross_context_arg(
6415    arg: &Expr,
6416    param_ty: TyId,
6417    caller_types: &HashMap<String, Arc<TypeDecl>>,
6418    consumed_types: &HashMap<String, Arc<TypeDecl>>,
6419    consumed: &str,
6420    ctx: &mut Ctx,
6421) -> (Option<TyId>, bool) {
6422    let tys = ctx.tys;
6423    let mut found = CrossingPositions::default();
6424    collect_crossing_positions(arg, param_ty, caller_types, consumed_types, tys, &mut found);
6425    let CrossingPositions {
6426        literals,
6427        mut leaves,
6428        bindings,
6429    } = found;
6430    for (lit, pos) in literals {
6431        let before = ctx.errors.len();
6432        match admit_refined_literal_in(lit, Some(pos), consumed_types, ctx) {
6433            Some(ty) => {
6434                for err in &mut ctx.errors[before..] {
6435                    err.notes.push(format!(
6436                        "`{}` is the type at this position of the parameter, as `{consumed}` declares it",
6437                        ty.display(tys)
6438                    ));
6439                }
6440                ctx.admitted_literals.insert(lit.id, ty);
6441            }
6442            // Not a literal of the refined type's base: an ordinary leaf.
6443            None => leaves.push((lit, pos)),
6444        }
6445    }
6446    let arg_ty = type_of(arg, Some(param_ty), ctx);
6447    let Some(ty) = arg_ty else {
6448        return (None, false);
6449    };
6450    let whole = || structurally_compatible(ty, param_ty, caller_types, consumed_types, tys);
6451    let leaves_cross = leaves.iter().all(|(leaf, pos)| {
6452        // A leaf `type_of` did not record is checked through the whole
6453        // argument instead.
6454        match ctx.expr_types.get(&leaf.id) {
6455            Some(t) => structurally_compatible(t.ty, *pos, caller_types, consumed_types, tys),
6456            None => whole(),
6457        }
6458    });
6459    let bindings_cross = bindings.iter().all(|(name, pos)| match ctx.lookup(name) {
6460        Some(t) => structurally_compatible(t, *pos, caller_types, consumed_types, tys),
6461        None => whole(),
6462    });
6463    (arg_ty, leaves_cross && bindings_cross)
6464}
6465
6466/// #2039: what [`collect_crossing_positions`] finds in a cross-context
6467/// argument, each paired with the type at its position, named in the
6468/// consumed context's table.
6469#[derive(Default)]
6470struct CrossingPositions<'e> {
6471    /// Literals at refined positions, admitted against the callee.
6472    literals: Vec<(&'e Expr, TyId)>,
6473    /// Parts the structural check still has to decide.
6474    leaves: Vec<(&'e Expr, TyId)>,
6475    /// #2072: shorthand record fields, by the binding each one reads.
6476    bindings: Vec<(&'e str, TyId)>,
6477}
6478
6479/// #2039: walk a cross-context argument alongside its parameter's type,
6480/// collecting the literals at refined positions and the leaves the
6481/// structural check still has to decide.
6482///
6483/// The walk follows `Some`/`Ok`/`Err` payloads, list elements, and the
6484/// fields of a record literal whose type is the very declaration the
6485/// callee's parameter names (the same commons type). #2072: for a generic
6486/// record, its type arguments are substituted into the field types, and a
6487/// shorthand field is collected by its binding. Anything else is a leaf.
6488fn collect_crossing_positions<'e>(
6489    e: &'e Expr,
6490    pos: TyId,
6491    caller_types: &HashMap<String, Arc<TypeDecl>>,
6492    consumed_types: &HashMap<String, Arc<TypeDecl>>,
6493    tys: &Types,
6494    found: &mut CrossingPositions<'e>,
6495) {
6496    let node = tys.get(pos);
6497    let walk = |inner: &'e Expr, at: TyId, found: &mut CrossingPositions<'e>| {
6498        collect_crossing_positions(inner, at, caller_types, consumed_types, tys, found)
6499    };
6500    // A compile-time literal, negated ones (`-3`) included.
6501    if const_literal(e).is_some()
6502        && matches!(
6503            &*node,
6504            Ty::Named {
6505                kind: NamedKind::Refined(_),
6506                ..
6507            }
6508        )
6509    {
6510        return found.literals.push((e, pos));
6511    }
6512    match (&e.kind, &*node) {
6513        (ExprKind::Paren(inner), _) => walk(inner, pos, found),
6514        // Typed from the hint: the parameter's own type at this position.
6515        (ExprKind::None, Ty::Option(_)) => {}
6516        (ExprKind::ListLit(items, ..), Ty::List(_)) if items.is_empty() => {}
6517        // #2043: `List.empty()` / `Map.empty()`, likewise.
6518        (
6519            ExprKind::MethodCall {
6520                receiver,
6521                method,
6522                type_args,
6523                args,
6524                ..
6525            },
6526            Ty::List(_) | Ty::Map(..) | Ty::Set(_),
6527        ) if method.name == "empty"
6528            && type_args.is_empty()
6529            && args.is_empty()
6530            && matches!(
6531                &receiver.kind,
6532                ExprKind::Ident(id)
6533                    if id.name == match &*node {
6534                        Ty::List(_) => "List",
6535                        Ty::Set(_) => "Set",
6536                        _ => "Map",
6537                    }
6538            ) => {}
6539        (ExprKind::Some(inner), Ty::Option(t)) => walk(inner, *t, found),
6540        (ExprKind::Ok(inner), Ty::Result(t, _)) => walk(inner, *t, found),
6541        (ExprKind::Err(inner), Ty::Result(_, t)) => walk(inner, *t, found),
6542        (ExprKind::ListLit(items, ..), Ty::List(t)) => {
6543            for item in items {
6544                walk(item, *t, found);
6545            }
6546        }
6547        (
6548            ExprKind::RecordConstruction {
6549                type_name, fields, ..
6550            },
6551            Ty::Named {
6552                name,
6553                kind: NamedKind::Record,
6554                args,
6555            },
6556        ) if type_name.name == *name => {
6557            let Some(field_positions) =
6558                record_field_positions(name, args, fields, caller_types, consumed_types, tys)
6559            else {
6560                return found.leaves.push((e, pos));
6561            };
6562            for (f, field_ty) in field_positions {
6563                match &f.value {
6564                    Some(value) => walk(value, field_ty, found),
6565                    // #2072: a shorthand field reads the same-named binding.
6566                    None => found.bindings.push((f.name.name.as_str(), field_ty)),
6567                }
6568            }
6569        }
6570        _ => found.leaves.push((e, pos)),
6571    }
6572}
6573
6574/// #2039, #2072: the type of each field a record literal sets, in the
6575/// consumed context's table, when the literal's type is the very
6576/// declaration the callee names (the same commons type). A generic record's
6577/// type arguments are substituted into its field types. `None` when the
6578/// record is not the callee's declaration, or a field is not one it
6579/// declares: the record is then checked whole.
6580fn record_field_positions<'f>(
6581    name: &str,
6582    args: &[TyId],
6583    fields: &'f [FieldInit],
6584    caller_types: &HashMap<String, Arc<TypeDecl>>,
6585    consumed_types: &HashMap<String, Arc<TypeDecl>>,
6586    tys: &Types,
6587) -> Option<Vec<(&'f FieldInit, TyId)>> {
6588    let decl = consumed_types.get(name)?;
6589    if !caller_types.get(name).is_some_and(|c| Arc::ptr_eq(c, decl)) {
6590        return None;
6591    }
6592    let TypeBody::Record(record) = &decl.body else {
6593        return None;
6594    };
6595    if decl.type_params.len() != args.len() {
6596        return None;
6597    }
6598    let vars: HashSet<String> = decl
6599        .type_params
6600        .iter()
6601        .map(|p| p.name.name.clone())
6602        .collect();
6603    let subst: HashMap<String, TyId> = decl
6604        .type_params
6605        .iter()
6606        .map(|p| p.name.name.clone())
6607        .zip(args.iter().copied())
6608        .collect();
6609    fields
6610        .iter()
6611        .map(|f| {
6612            let declared = record.fields.iter().find(|d| d.name.name == f.name.name)?;
6613            let ty = resolve_type_ref_in(&declared.type_ref, consumed_types, &vars, tys)?;
6614            Some((f, substitute(ty, &subst, tys)))
6615        })
6616        .collect()
6617}
6618
6619/// #2073: a consumed context's service whose signature reaches a type that
6620/// context consumes from a third (`shop.ledger.isDomestic(o: Order)`, `Order`
6621/// from `shop.order`) crosses the boundary as that third context's type. The
6622/// caller names it, and builds its codecs, through the declaring context, so
6623/// it must consume that context too; otherwise `bynk.consumes.signature_type_unconsumed`.
6624fn check_signature_owners_consumed(
6625    consumed: &str,
6626    service: &crate::resolver::CrossContextService,
6627    method: &Ident,
6628    ctx: &mut Ctx,
6629) -> bool {
6630    let info = &ctx.input.cross_context;
6631    let Some(owners) = info.consumed_type_owners.get(consumed) else {
6632        return false;
6633    };
6634    let types = info.consumed_types.get(consumed);
6635    let mut seen: HashSet<String> = HashSet::new();
6636    let mut stack: Vec<String> = Vec::new();
6637    let vars = HashSet::new();
6638    for (_, t) in &service.params {
6639        crate::project_model::type_ref_names(t, &vars, &mut stack);
6640    }
6641    crate::project_model::type_ref_names(&service.return_type, &vars, &mut stack);
6642    let mut missing: std::collections::BTreeMap<String, String> = Default::default();
6643    while let Some(n) = stack.pop() {
6644        if !seen.insert(n.clone()) {
6645            continue;
6646        }
6647        if let Some(owner) = owners.get(&n)
6648            && info.self_context.as_deref() != Some(owner.as_str())
6649            && !info.consumed_contexts.contains(owner)
6650        {
6651            // The declaration's own name, not the key `contract_types_for`
6652            // may have qualified it under (`shop_base__Region`).
6653            let declared = n
6654                .strip_prefix(&format!("{}__", owner.replace('.', "_")))
6655                .unwrap_or(&n)
6656                .to_string();
6657            missing.entry(owner.clone()).or_insert(declared);
6658        }
6659        if let Some(d) = types.and_then(|t| t.get(&n)) {
6660            stack.extend(crate::project_model::type_decl_ref_names(d));
6661        }
6662    }
6663    let refused = !missing.is_empty();
6664    for (owner, ty) in missing {
6665        ctx.errors.push(
6666            CompileError::new(
6667                "bynk.consumes.signature_type_unconsumed",
6668                method.span,
6669                format!(
6670                    "`{consumed}.{}` takes or returns `{ty}`, declared in `{owner}`, but this context does not consume `{owner}`",
6671                    method.name
6672                ),
6673            )
6674            .with_note(format!(
6675                "add `consumes {owner}`: a value of `{ty}` crosses this call as `{owner}`'s type"
6676            )),
6677        );
6678    }
6679    refused
6680}
6681
6682fn check_cross_context_call(
6683    receiver: &Expr,
6684    consumed: &str,
6685    method: &Ident,
6686    args: &[Expr],
6687    span: Span,
6688    // P6.0 (#1139): the outer `MethodCall` expression's own identity.
6689    expr_id: ExprId,
6690    ctx: &mut Ctx,
6691) -> Option<TyId> {
6692    let tys = ctx.tys;
6693    ctx.callees.insert(
6694        expr_id,
6695        Callee::Cross {
6696            unit: consumed.to_string(),
6697            service: method.name.clone(),
6698        },
6699    );
6700    // The consuming context must be effectful at this call site (services
6701    // and agent handlers are; pure free fns are not).
6702    if !ctx.effectful {
6703        ctx.errors.push(
6704            CompileError::new(
6705                "bynk.effect.cross_context_in_pure_context",
6706                method.span,
6707                format!(
6708                    "cross-context service call `{}.{}` can only be made inside an effectful body (one returning `Effect[T]`)",
6709                    consumed, method.name
6710                ),
6711            )
6712            .with_label(receiver.span, "consumed context prefix"),
6713        );
6714    }
6715    let info = &ctx.input.cross_context;
6716    let Some(svcs) = info.consumed_services.get(consumed) else {
6717        ctx.errors.push(
6718            CompileError::new(
6719                "bynk.consumes.unknown_context",
6720                receiver.span,
6721                format!("context `{consumed}` is not in scope here"),
6722            )
6723            .with_note(
6724                "add a `consumes` clause for the target context at the top of the consuming context",
6725            ),
6726        );
6727        for a in args {
6728            let _ = type_of(a, None, ctx);
6729        }
6730        return None;
6731    };
6732    let Some(service) = svcs.get(&method.name).cloned() else {
6733        ctx.errors.push(
6734            CompileError::new(
6735                "bynk.consumes.unknown_service",
6736                method.span,
6737                format!(
6738                    "context `{consumed}` has no service named `{}`",
6739                    method.name
6740                ),
6741            )
6742            .with_note(
6743                "cross-context calls require an `on call` service handler in the consumed context",
6744            ),
6745        );
6746        for a in args {
6747            let _ = type_of(a, None, ctx);
6748        }
6749        return None;
6750    };
6751    ctx.refs
6752        .record_in_unit(method.span, SymbolKind::Service, &method.name, consumed);
6753    // #3582: also the service's `on call` handler, so the call is an edge in the
6754    // call hierarchy (a call-only symbol: Find References keeps reading the
6755    // `Service` ref above). `consumed` is already the alias-resolved unit.
6756    ctx.refs.record_in_unit(
6757        method.span,
6758        SymbolKind::Handler,
6759        &format!("{}.call", method.name),
6760        consumed,
6761    );
6762    // A refused signature's arguments would only repeat it as a mismatch.
6763    let unconsumed = check_signature_owners_consumed(consumed, &service, method, ctx);
6764
6765    if service.params.len() != args.len() {
6766        ctx.errors.push(
6767            CompileError::new(
6768                "bynk.consumes.service_arity",
6769                method.span,
6770                format!(
6771                    "cross-context service `{consumed}.{}` expects {} argument(s), but {} were given",
6772                    method.name,
6773                    service.params.len(),
6774                    args.len()
6775                ),
6776            )
6777            // Finding #46: `service` belongs to the *consumed*
6778            // context — a different unit/file than this call, almost
6779            // always. A label would risk underlining unrelated text
6780            // there; a note carries the information safely (per-label
6781            // file identity is a Wave 8 follow-up).
6782            .with_note("service declared here"),
6783        );
6784        for a in args {
6785            let _ = type_of(a, None, ctx);
6786        }
6787        return None;
6788    }
6789
6790    // Resolve the consumed-context types so we can describe parameter shapes.
6791    let consumed_types = info
6792        .consumed_types
6793        .get(consumed)
6794        .cloned()
6795        .unwrap_or_default();
6796
6797    // #1941: as for a capability operation, the caller's table plus the
6798    // consumed contexts' types it holds values of without naming.
6799    let (caller_types, ambiguous) = projected_types(&ctx.input.types, &info.consumed_types, tys);
6800
6801    // Walk each argument, checking structural compatibility (Phase 4).
6802    let mut all_ok = true;
6803    for (i, ((pname, ptype_ref), arg)) in service.params.iter().zip(args.iter()).enumerate() {
6804        record_param_hint(ctx.hints, pname, arg);
6805        let param_ty =
6806            resolve_type_ref(ptype_ref, &consumed_types, tys).unwrap_or(tys.intern(Ty::Unit));
6807        // Type-check the argument in the caller's context (#2025: against
6808        // the parameter's type; see `type_cross_context_arg`).
6809        let (arg_ty, crosses) =
6810            type_cross_context_arg(arg, param_ty, &caller_types, &consumed_types, consumed, ctx);
6811        let Some(arg_ty) = arg_ty else {
6812            all_ok = false;
6813            continue;
6814        };
6815        if !crosses && !unconsumed {
6816            let mut err = CompileError::new(
6817                    "bynk.boundary.structural_mismatch",
6818                    arg.span,
6819                    format!(
6820                        "cross-context argument {} to `{consumed}.{}` has type `{}` in `{}`, but parameter `{pname}` expects `{}` in `{}`",
6821                        i + 1,
6822                        method.name,
6823                        arg_ty.display(tys),
6824                        ctx.input
6825                            .cross_context
6826                            .self_context
6827                            .as_deref()
6828                            .unwrap_or("?"),
6829                        param_ty.display(tys),
6830                        consumed,
6831                    ),
6832                )
6833                // Finding #46: same cross-unit provenance as above.
6834                .with_note("service declared here")
6835                .with_note(
6836                    "values crossing a context boundary must have structurally compatible types (same commons-derived type, or identical record/sum shape)",
6837                );
6838            if let Some(note) = ambiguous_projection_note(arg_ty, &ambiguous, tys) {
6839                err = err.with_note(note);
6840            }
6841            ctx.errors.push(err);
6842            all_ok = false;
6843        }
6844    }
6845    if !all_ok {
6846        return None;
6847    }
6848
6849    // Return type rebrand: project the consumed context's return type into
6850    // the calling context's namespace by renaming named types whose unqualified
6851    // name appears in the caller's type table (v0.6 §4.5).
6852    let raw_ret = resolve_type_ref(&service.return_type, &consumed_types, tys)
6853        .unwrap_or(tys.intern(Ty::Unit));
6854    let rebrand_types = rebrand_table(&ctx.input.types, &consumed_types);
6855    if let Some(name) =
6856        rebrand_conflict(raw_ret, &consumed_types, &rebrand_types, &caller_types, tys)
6857    {
6858        ctx.errors.push(rebranded_return_mismatch(
6859            &format!("{consumed}.{}", method.name),
6860            &name,
6861            consumed,
6862            false,
6863            span,
6864            ctx,
6865        ));
6866        return None;
6867    }
6868    Some(rebrand_return_type(raw_ret, &rebrand_types, tys))
6869}
6870
6871/// #2808: a `String`, `Int`, … handed to a refined or opaque type over that
6872/// base is the commonest way to meet a mismatch, and `<Type>.of(…)` is the way
6873/// across. The hint is withheld when `.of` would be refused: a type consumed
6874/// from another context is the owner's to construct (`external_construction`),
6875/// so only a type declared here or imported from a commons is offered.
6876pub(crate) fn with_of_hint(
6877    err: CompileError,
6878    actual: TyId,
6879    expected: TyId,
6880    ctx: &Ctx,
6881) -> CompileError {
6882    let Ty::Base(base) = *ctx.tys.get(actual) else {
6883        return err;
6884    };
6885    let ty = ctx.tys.get(expected);
6886    let Ty::Named {
6887        name,
6888        kind: NamedKind::Refined(b) | NamedKind::Opaque(b),
6889        args,
6890    } = &*ty
6891    else {
6892        return err;
6893    };
6894    if *b != base
6895        || !args.is_empty()
6896        || !(ctx.input.is_local_type(name) || ctx.input.is_uses_commons_type(name))
6897    {
6898        return err;
6899    }
6900    err.with_note(format!(
6901        "to make a `{name}` from a `{}`, use `{name}.of(value)`, which checks the value and returns a `Result`",
6902        base.name()
6903    ))
6904}
6905
6906/// #3458: a typed read's instantiated payload must be `Codable`; on failure the
6907/// arguments still get typed (`untyped`, when they were not already) so their own
6908/// errors are reported.
6909fn reply_codable_or_type_args(
6910    op: &str,
6911    span: Span,
6912    codable: &[String],
6913    wire: &super::codable::CapEncoding,
6914    untyped: Option<&[Expr]>,
6915    ctx: &mut Ctx,
6916) -> bool {
6917    if check_reply_codable(op, span, codable, wire, ctx) {
6918        return true;
6919    }
6920    for a in untyped.unwrap_or_default() {
6921        let _ = type_of(a, None, ctx);
6922    }
6923    false
6924}
6925
6926/// Record how a same-context capability call encodes its `Codable` arguments
6927/// and decodes a typed read's reply (#3458). `false` when the payload is not
6928/// `Codable`; `untyped` are the arguments still to type for their own errors.
6929fn record_capability_wire(
6930    op: &CapabilityOpInfo,
6931    (cap, name): (&str, &str),
6932    span: Span,
6933    expr_id: ExprId,
6934    subst: &HashMap<String, TyId>,
6935    untyped: Option<&[Expr]>,
6936    ctx: &mut Ctx,
6937) -> bool {
6938    let Some(wire) = op_encoding(
6939        &op.type_params,
6940        &op.codable_params,
6941        &op.params,
6942        op.return_ty,
6943        op.reply_policy,
6944        subst,
6945        ctx.tys,
6946    ) else {
6947        return true;
6948    };
6949    if !reply_codable_or_type_args(
6950        &format!("{cap}.{name}"),
6951        span,
6952        &op.codable_params,
6953        &wire,
6954        untyped,
6955        ctx,
6956    ) {
6957        return false;
6958    }
6959    ctx.callees.insert(
6960        expr_id,
6961        Callee::Capability {
6962            cap: cap.to_string(),
6963            op: name.to_string(),
6964            wire: Some(wire),
6965            first_party: local_first_party(cap, ctx),
6966            event: None,
6967        },
6968    );
6969    true
6970}
6971
6972#[cfg(test)]
6973mod tests {
6974    use crate::testkit::analyse;
6975
6976    /// A single-file `commons demo` project.
6977    fn commons(body: &str) -> crate::testkit::Analysed {
6978        analyse(&[("demo.bynk", &format!("commons demo\n\n{body}"))])
6979    }
6980
6981    /// A single-file `context demo` project.
6982    fn context(body: &str) -> crate::testkit::Analysed {
6983        analyse(&[("demo.bynk", &format!("context demo\n\n{body}"))])
6984    }
6985
6986    const CLOCK: &str = "capability Clock {\n  fn now() -> Effect[Int]\n}\n\n\
6987                         provides Clock = FixedClock {\n  fn now() -> Effect[Int] {\n    Effect.pure(0)\n  }\n}\n";
6988
6989    #[test]
6990    fn a_call_to_a_declared_fn_has_its_return_type() {
6991        let a = commons("fn double(x: Int) -> Int { x * 2 }\n\nfn four() -> Int { double(2) }\n");
6992        a.assert_clean();
6993        assert_eq!(a.type_at("demo.bynk", "double(2)"), "Int");
6994    }
6995
6996    #[test]
6997    fn an_argument_of_the_wrong_type_is_a_mismatch() {
6998        let a = commons(
6999            "fn double(x: Int) -> Int { x * 2 }\n\nfn bad(s: String) -> Int { double(s) }\n",
7000        );
7001        a.assert_reports("bynk.types.argument_mismatch");
7002    }
7003
7004    #[test]
7005    fn a_fn_called_with_too_many_arguments_is_an_arity_error() {
7006        let a = commons("fn double(x: Int) -> Int { x * 2 }\n\nfn bad() -> Int { double(1, 2) }\n");
7007        a.assert_reports("bynk.resolve.arity_mismatch");
7008    }
7009
7010    #[test]
7011    fn a_fn_value_called_with_too_many_arguments_is_a_call_arity_error() {
7012        let a = commons("fn f(g: (Int) -> Int) -> Int { g(1, 2) }\n");
7013        a.assert_reports("bynk.types.call_arity");
7014    }
7015
7016    #[test]
7017    fn a_fn_value_call_has_the_value_s_return_type() {
7018        let a = commons("fn f(g: (Int) -> String) -> String { g(1) }\n");
7019        a.assert_clean();
7020        assert_eq!(a.type_at("demo.bynk", "g(1)"), "String");
7021    }
7022
7023    #[test]
7024    fn a_generic_call_infers_its_type_argument_from_the_argument() {
7025        let a = commons("fn id[A](x: A) -> A { x }\n\nfn s() -> String { id(\"s\") }\n");
7026        a.assert_clean();
7027        assert_eq!(a.type_at("demo.bynk", "id(\"s\")"), "String");
7028    }
7029
7030    #[test]
7031    fn a_list_literal_argument_infers_the_type_argument() {
7032        let a = commons(
7033            "fn size[T](xs: List[T]) -> Int { 0 }\n\n\
7034             fn s() -> Int { size([1, 2]) }\n\n\
7035             fn n() -> Int { size([[1], [2, 3]]) }\n",
7036        );
7037        a.assert_clean();
7038    }
7039
7040    #[test]
7041    fn a_list_literal_argument_grounds_a_later_lambda() {
7042        let a = commons(
7043            "fn count_by[T](xs: List[T], f: (T) -> Int) -> Int { 0 }\n\n\
7044             fn s() -> Int { count_by([\"ant\", \"bee\"], (w) => w.length()) }\n",
7045        );
7046        a.assert_clean();
7047    }
7048
7049    #[test]
7050    fn list_literals_binding_one_type_argument_two_ways_still_conflict() {
7051        let a = commons(
7052            "fn size2[T](a: List[T], b: List[T]) -> Int { 0 }\n\n\
7053             fn bad() -> Int { size2([1], [\"x\"]) }\n",
7054        );
7055        a.assert_reports("bynk.types.list_element_mismatch");
7056    }
7057
7058    #[test]
7059    fn a_list_literal_with_mixed_elements_is_still_a_mismatch_in_a_generic_call() {
7060        let a = commons(
7061            "fn size[T](xs: List[T]) -> Int { 0 }\n\n\
7062             fn bad() -> Int { size([1, \"x\"]) }\n",
7063        );
7064        a.assert_reports("bynk.types.list_element_mismatch");
7065    }
7066
7067    #[test]
7068    fn a_some_argument_infers_the_type_argument() {
7069        let a = commons(
7070            "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7071             fn one[T](x: Option[T]) -> Int { 0 }\n\n\
7072             fn s() -> Int { size([None, Some(1)]) }\n\n\
7073             fn t() -> Int { one(Some(\"a\")) }\n",
7074        );
7075        a.assert_clean();
7076    }
7077
7078    #[test]
7079    fn ok_and_err_arguments_infer_the_type_arguments() {
7080        let a = commons(
7081            "fn okay[T](x: Result[T, String]) -> Int { 0 }\n\n\
7082             fn bad[E](x: Result[Int, E]) -> Int { 0 }\n\n\
7083             fn s() -> Int { okay(Ok(1)) }\n\n\
7084             fn t() -> Int { bad(Err(\"x\")) }\n",
7085        );
7086        a.assert_clean();
7087    }
7088
7089    #[test]
7090    fn a_mixed_some_list_in_a_generic_call_still_reports() {
7091        let a = commons(
7092            "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7093             fn bad() -> Int { size([None, Some(1), Some(\"a\")]) }\n",
7094        );
7095        a.assert_reports("bynk.types.some_value_mismatch");
7096    }
7097
7098    #[test]
7099    fn an_all_deferred_list_does_not_come_back_untyped() {
7100        let a = commons(
7101            "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7102             fn s() -> Int { size([None]) }\n",
7103        );
7104        let b = commons(
7105            "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7106             fn s() -> Int { size([]) }\n",
7107        );
7108        // An all-deferred list types as `List[Option[T]]` and leaves `T`
7109        // unsolved, exactly as the empty `size([])` already does.
7110        a.assert_clean();
7111        b.assert_clean();
7112    }
7113
7114    #[test]
7115    fn an_http_result_ok_argument_infers_the_type_argument() {
7116        let a = commons(
7117            "fn h[T](x: HttpResult[T]) -> Int { 0 }\n\n\
7118             fn s() -> Int { h(Ok(1)) }\n",
7119        );
7120        a.assert_clean();
7121    }
7122
7123    #[test]
7124    fn a_context_typed_payload_inside_some_ok_and_err_keeps_its_context() {
7125        let a = commons(
7126            "fn one[T](x: Option[Option[T]]) -> Int { 0 }\n\n\
7127             fn two[T](x: Option[List[T]]) -> Int { 0 }\n\n\
7128             fn three[T](x: Result[Option[T], String]) -> Int { 0 }\n\n\
7129             fn four[T](x: Result[Int, Option[T]]) -> Int { 0 }\n\n\
7130             fn s() -> Int { one(Some(None)) }\n\n\
7131             fn t() -> Int { two(Some([])) }\n\n\
7132             fn u() -> Int { three(Ok(None)) }\n\n\
7133             fn v() -> Int { four(Err(None)) }\n",
7134        );
7135        a.assert_clean();
7136    }
7137
7138    #[test]
7139    fn a_lambda_payload_inside_some_and_ok_keeps_its_parameter_types() {
7140        let a = commons(
7141            "fn ap[T](f: Option[(Int) -> T]) -> Int { 0 }\n\n\
7142             fn bp[T](f: Result[(Int) -> T, String]) -> Int { 0 }\n\n\
7143             fn s() -> Int { ap(Some((x) => x + 1)) }\n\n\
7144             fn t() -> Int { bp(Ok((x) => x + 1)) }\n",
7145        );
7146        a.assert_clean();
7147    }
7148
7149    #[test]
7150    fn mixed_deferred_ok_and_err_elements_infer_both_type_arguments() {
7151        let a = commons(
7152            "fn size[T, E](xs: List[Result[T, E]]) -> Int { 0 }\n\n\
7153             fn s() -> Int { size([Ok(1), Err(\"x\")]) }\n\n\
7154             fn t() -> Int { size([Err(\"x\"), Ok(1)]) }\n",
7155        );
7156        a.assert_clean();
7157    }
7158
7159    #[test]
7160    fn mixed_deferred_result_elements_that_disagree_still_report() {
7161        for list in [
7162            "[Ok(1), Err(\"x\"), Err(2)]",
7163            "[Err(\"x\"), Ok(1), Ok(\"a\")]",
7164        ] {
7165            let a = commons(&format!(
7166                "fn size[T, E](xs: List[Result[T, E]]) -> Int {{ 0 }}\n\n\
7167                 fn bad() -> Int {{ size({list}) }}\n"
7168            ));
7169            // Once a sibling has refined the element type, a later one is
7170            // checked against it (`Err(2)` against `Result[Int, String]`).
7171            assert!(
7172                a.categories().iter().any(|c| matches!(
7173                    *c,
7174                    "bynk.types.list_element_mismatch"
7175                        | "bynk.types.err_value_mismatch"
7176                        | "bynk.types.ok_value_mismatch"
7177                )),
7178                "{list} should report, got {:?}",
7179                a.categories()
7180            );
7181        }
7182    }
7183
7184    #[test]
7185    fn mixed_deferred_elements_solve_the_type_arguments_they_supply() {
7186        let a = commons(
7187            "fn first_err[T, E](xs: List[Result[T, E]]) -> Option[E] { None }\n\n\
7188             fn s() -> Option[String] { first_err([Ok(1), Err(\"x\")]) }\n",
7189        );
7190        a.assert_clean();
7191    }
7192
7193    #[test]
7194    fn deferred_siblings_merge_through_fn_and_effect_types_in_either_order() {
7195        for list in [
7196            "[Err(\"x\"), Ok((x) => x + 1)]",
7197            "[Ok((x) => x + 1), Err(\"x\")]",
7198        ] {
7199            let a = commons(&format!(
7200                "fn size[T, E](xs: List[Result[(Int) -> T, E]]) -> Int {{ 0 }}\n\n\
7201                 fn s() -> Int {{ size({list}) }}\n"
7202            ));
7203            a.assert_clean();
7204        }
7205    }
7206
7207    #[test]
7208    fn deferred_siblings_merge_through_nested_effect_types() {
7209        let a = commons(
7210            "fn size[T](xs: List[Option[Effect[T]]]) -> Int { 0 }\n\n\
7211             fn s(e: Effect[Int]) -> Int { size([None, Some(e)]) }\n\n\
7212             fn t(e: Effect[Int]) -> Int { size([Some(e), None]) }\n",
7213        );
7214        a.assert_clean();
7215    }
7216
7217    #[test]
7218    fn deferred_fn_siblings_that_disagree_still_report() {
7219        let a = commons(
7220            "fn size[T, E](xs: List[Result[(Int) -> T, E]]) -> Int { 0 }\n\n\
7221             fn bad() -> Int { size([Ok((x) => x + 1), Ok((x) => \"s\")]) }\n",
7222        );
7223        a.assert_reports("bynk.types.lambda_mismatch");
7224    }
7225
7226    #[test]
7227    fn deferred_effect_siblings_that_disagree_still_report() {
7228        let a = commons(
7229            "fn size[T](xs: List[Option[Effect[T]]]) -> Int { 0 }\n\n\
7230             fn bad(a: Effect[Int], b: Effect[String]) -> Int { size([None, Some(a), Some(b)]) }\n",
7231        );
7232        a.assert_reports("bynk.types.some_value_mismatch");
7233    }
7234
7235    #[test]
7236    fn a_concrete_some_mismatch_still_reports() {
7237        let a = commons("fn f() -> Int { let x: Option[Int] = Some(\"a\")\n 0 }\n");
7238        a.assert_reports("bynk.types.some_value_mismatch");
7239    }
7240
7241    #[test]
7242    fn a_some_argument_conflicting_with_a_bound_type_argument_still_reports() {
7243        let a = commons(
7244            "fn two[T](a: Option[T], b: Option[T]) -> Int { 0 }\n\n\
7245             fn bad() -> Int { two(Some(1), Some(\"x\")) }\n",
7246        );
7247        a.assert_reports("bynk.types.some_value_mismatch");
7248    }
7249
7250    #[test]
7251    fn a_generic_call_binding_one_type_argument_two_ways_is_a_conflict() {
7252        let a =
7253            commons("fn both[A](x: A, y: A) -> A { x }\n\nfn bad() -> Int { both(1, \"two\") }\n");
7254        a.assert_reports("bynk.generics.type_arg_mismatch");
7255    }
7256
7257    #[test]
7258    fn a_type_argument_no_parameter_mentions_is_uninferable() {
7259        let a = commons(
7260            "fn first_of[A](x: Int) -> A { identity_helper(x) }\n\n\
7261             fn identity_helper[A](x: A) -> A { x }\n\n\
7262             fn misuse() -> Int { let y = first_of(5)\n 0 }\n",
7263        );
7264        a.assert_reports("bynk.generics.uninferable_type_arg");
7265    }
7266
7267    #[test]
7268    fn calling_an_undeclared_name_is_an_unknown_function() {
7269        let a = commons("fn bad() -> Int { nope(1) }\n");
7270        a.assert_reports("bynk.resolve.unknown_function");
7271    }
7272
7273    #[test]
7274    fn calling_a_record_type_like_a_function_is_rejected() {
7275        let a = commons("type P = { a: Int }\n\nfn f() -> P { P(1) }\n");
7276        a.assert_reports("bynk.resolve.type_as_function");
7277    }
7278
7279    #[test]
7280    fn a_capability_op_call_has_the_op_s_return_type() {
7281        let a = context(&format!(
7282            "{CLOCK}\nservice probe {{\n  on call() -> Effect[Int] by Caller given Clock {{\n    Clock.now()\n  }}\n}}\n"
7283        ));
7284        a.assert_clean();
7285        assert_eq!(a.type_at("demo.bynk", "Clock.now()"), "Effect[Int]");
7286    }
7287
7288    #[test]
7289    fn a_capability_op_called_with_an_extra_argument_is_an_arity_error() {
7290        let a = context(&format!(
7291            "{CLOCK}\nservice probe {{\n  on call() -> Effect[Int] by Caller given Clock {{\n    Clock.now(1)\n  }}\n}}\n"
7292        ));
7293        a.assert_reports("bynk.capability.op_arity");
7294    }
7295
7296    #[test]
7297    fn a_capability_called_inside_a_pure_lambda_is_rejected() {
7298        let a = context(&format!(
7299            "{CLOCK}\nservice probe {{\n  on call() -> Effect[Int] by Caller given Clock {{\n    \
7300             let f: (Int) -> Int = (n) => Clock.now()\n    Effect.pure(1)\n  }}\n}}\n"
7301        ));
7302        a.assert_reports("bynk.effect.capability_in_pure_context");
7303    }
7304
7305    #[test]
7306    fn an_unknown_cell_op_is_rejected() {
7307        let a = context(
7308            "agent Counter {\n  key id: String\n  store n: Cell[Int] = 0\n\n  \
7309             on call bad() -> Effect[()] {\n    let _ <- n.foo()\n    Effect.pure(())\n  }\n}\n",
7310        );
7311        a.assert_reports("bynk.store.unknown_op");
7312    }
7313
7314    #[test]
7315    fn a_cell_update_is_an_effect_of_unit() {
7316        let a = context(
7317            "agent Counter {\n  key id: String\n  store n: Cell[Int] = 0\n\n  \
7318             on call bump() -> Effect[()] {\n    n.update((c) => c + 1)\n  }\n}\n",
7319        );
7320        a.assert_clean();
7321        assert_eq!(
7322            a.type_at("demo.bynk", "n.update((c) => c + 1)"),
7323            "Effect[()]"
7324        );
7325    }
7326
7327    #[test]
7328    fn a_cell_update_whose_function_returns_another_type_is_a_mismatch() {
7329        let a = context(
7330            "agent Counter {\n  key id: String\n  store n: Cell[Int] = 0\n\n  \
7331             on call bad() -> Effect[()] {\n    n.update((c) => \"x\")\n  }\n}\n",
7332        );
7333        a.assert_reports("bynk.types.lambda_mismatch");
7334    }
7335
7336    #[test]
7337    fn a_cell_update_with_no_function_is_a_call_arity_error() {
7338        let a = context(
7339            "agent Counter {\n  key id: String\n  store n: Cell[Int] = 0\n\n  \
7340             on call bad() -> Effect[()] {\n    n.update()\n  }\n}\n",
7341        );
7342        a.assert_reports("bynk.types.call_arity");
7343    }
7344
7345    /// #1941: a provider context with an unexported `Box` (and its field's
7346    /// `Amount`), a service returning one and a service taking one back, and
7347    /// a capability operation doing the same.
7348    const SHOP: &str = "context shop\n\nexports capability { Store }\n\n\
7349                        type Amount = { cents: Int }\n\ntype Box = { a: Amount }\n\n\
7350                        capability Store {\n  fn get() -> Effect[Box]\n  fn put(b: Box) -> Effect[Int]\n}\n\n\
7351                        provides Store = Shelf {\n  fn get() -> Effect[Box] {\n    Effect.pure(Box { a: Amount { cents: 1 } })\n  }\n\n  \
7352                        fn put(b: Box) -> Effect[Int] {\n    Effect.pure(b.a.cents)\n  }\n}\n\n\
7353                        service quote {\n  on call() -> Effect[Box] by Caller {\n    Effect.pure(Box { a: Amount { cents: 1 } })\n  }\n}\n\n\
7354                        service take {\n  on call(b: Box) -> Effect[Int] by Caller {\n    Effect.pure(b.a.cents)\n  }\n}\n";
7355
7356    /// A `till` context consuming `shop`, declaring `decls`, with `body` as
7357    /// a service handler's body (given `shop.Store` when it calls it).
7358    fn till(decls: &str, body: &str) -> String {
7359        let given = if body.contains("Store") {
7360            " given shop.Store"
7361        } else {
7362            ""
7363        };
7364        format!(
7365            "context till\n\nconsumes shop\n\n{decls}service total {{\n  \
7366             on call() -> Effect[Int] by Caller{given} {{\n{body}\n  }}\n}}\n"
7367        )
7368    }
7369
7370    /// #2802: a provider returning `Label` and a `till` declaring a `Label` of
7371    /// its own take the same name, so the value is projected onto the caller's
7372    /// declaration (`rebrand_conflict`) with the *provider* as the sender.
7373    fn label_provider(max: u32) -> String {
7374        format!(
7375            "context shop\n\ntype Label = String where MaxLength({max})\n\n\
7376             service label {{\n  on call() -> Effect[Result[Label, Int]] by Caller {{\n    Effect.pure(Ok(\"a\"))\n  }}\n}}\n"
7377        )
7378    }
7379
7380    #[test]
7381    fn a_stronger_returned_refinement_is_admitted_by_the_callers_same_named_type() {
7382        let a = analyse(&[
7383            ("shop.bynk", &label_provider(4)),
7384            (
7385                "till.bynk",
7386                &till(
7387                    "type Label = String where MaxLength(8)\n\n",
7388                    "    let l <- shop.label()\n    Effect.pure(0)",
7389                ),
7390            ),
7391        ]);
7392        a.assert_clean();
7393    }
7394
7395    #[test]
7396    fn a_weaker_returned_refinement_is_rejected_by_the_callers_same_named_type() {
7397        let a = analyse(&[
7398            ("shop.bynk", &label_provider(8)),
7399            (
7400                "till.bynk",
7401                &till(
7402                    "type Label = String where MaxLength(4)\n\n",
7403                    "    let l <- shop.label()\n    Effect.pure(0)",
7404                ),
7405            ),
7406        ]);
7407        a.assert_reports("bynk.boundary.structural_mismatch");
7408    }
7409
7410    /// #2802: the `Opaque` arm of `structural_compare_named` shares
7411    /// `refinements_match`, so a same-named opaque peer widens like a refined
7412    /// one. The predicate of an opaque type is not part of the contract (the
7413    /// consumer cannot observe it), so a stronger sender is as safe as for a
7414    /// refined type.
7415    fn opaque_provider(max: u32) -> String {
7416        format!(
7417            "context shop\n\ntype Tag = opaque String where MaxLength({max})\n\n\
7418             service check {{\n  on call(t: Tag) -> Effect[Int] by Caller {{\n    Effect.pure(0)\n  }}\n}}\n"
7419        )
7420    }
7421
7422    fn opaque_till(max: u32) -> String {
7423        format!(
7424            "context till\n\nconsumes shop\n\ntype Tag = opaque String where MaxLength({max})\n\n\
7425             service total {{\n  on call(t: Tag) -> Effect[Int] by Caller {{\n    shop.check(t)\n  }}\n}}\n"
7426        )
7427    }
7428
7429    #[test]
7430    fn a_stronger_opaque_sender_is_admitted_and_a_weaker_one_rejected() {
7431        analyse(&[
7432            ("shop.bynk", &opaque_provider(8)),
7433            ("till.bynk", &opaque_till(4)),
7434        ])
7435        .assert_clean();
7436        analyse(&[
7437            ("shop.bynk", &opaque_provider(4)),
7438            ("till.bynk", &opaque_till(8)),
7439        ])
7440        .assert_reports("bynk.boundary.structural_mismatch");
7441    }
7442
7443    /// #2802: two consumed contexts that declare one unexported type name agree
7444    /// when each entails the other, so `Positive` and `Positive && NonNegative`
7445    /// (equivalent, but different canonical sets) no longer make the name
7446    /// ambiguous, and a value of it passes back to the context it came from.
7447    #[test]
7448    fn equivalent_refinements_of_one_name_do_not_make_it_ambiguous() {
7449        let owner = "context shop\n\ntype Label = Int where Positive\n\n\
7450                     service make {\n  on call() -> Effect[Result[Label, Int]] by Caller {\n    Effect.pure(Ok(1))\n  }\n}\n\n\
7451                     service take {\n  on call(l: Label) -> Effect[Int] by Caller {\n    Effect.pure(0)\n  }\n}\n";
7452        let other = "context other\n\ntype Label = Int where Positive && NonNegative\n\n\
7453                     service peek {\n  on call() -> Effect[Int] by Caller {\n    Effect.pure(0)\n  }\n}\n";
7454        let till = "context till\n\nconsumes shop\n\nconsumes other\n\n\
7455                    service total {\n  on call() -> Effect[Int] by Caller {\n    \
7456                    let r <- shop.make()\n    match r {\n      Ok(l) => shop.take(l)\n      Err(_) => Effect.pure(0)\n    }\n  }\n}\n";
7457        analyse(&[
7458            ("shop.bynk", owner),
7459            ("other.bynk", other),
7460            ("till.bynk", till),
7461        ])
7462        .assert_clean();
7463    }
7464
7465    #[test]
7466    fn an_unexported_value_passes_back_to_its_service() {
7467        let a = analyse(&[
7468            ("shop.bynk", SHOP),
7469            (
7470                "till.bynk",
7471                &till("", "    let b <- shop.quote()\n    shop.take(b)"),
7472            ),
7473        ]);
7474        a.assert_clean();
7475    }
7476
7477    #[test]
7478    fn an_unexported_value_passes_back_to_its_capability() {
7479        let a = analyse(&[
7480            ("shop.bynk", SHOP),
7481            (
7482                "till.bynk",
7483                &till("", "    let b <- shop.Store.get()\n    shop.Store.put(b)"),
7484            ),
7485        ]);
7486        a.assert_clean();
7487    }
7488
7489    #[test]
7490    fn a_caller_type_of_another_shape_cannot_receive_a_service_return() {
7491        let a = analyse(&[
7492            ("shop.bynk", SHOP),
7493            (
7494                "till.bynk",
7495                &till(
7496                    "type Box = { label: String }\n\n",
7497                    "    let b <- shop.quote()\n    Effect.pure(1)",
7498                ),
7499            ),
7500        ]);
7501        a.assert_reports("bynk.boundary.structural_mismatch");
7502    }
7503
7504    #[test]
7505    fn a_caller_type_of_another_shape_cannot_receive_a_capability_return() {
7506        let a = analyse(&[
7507            ("shop.bynk", SHOP),
7508            (
7509                "till.bynk",
7510                &till(
7511                    "type Box = { label: String }\n\n",
7512                    "    let b <- shop.Store.get()\n    Effect.pure(1)",
7513                ),
7514            ),
7515        ]);
7516        a.assert_reports("bynk.boundary.structural_mismatch");
7517    }
7518
7519    #[test]
7520    fn a_caller_type_of_the_same_shape_receives_a_return() {
7521        let a = analyse(&[
7522            ("shop.bynk", SHOP),
7523            (
7524                "till.bynk",
7525                &till(
7526                    "type Coins = { cents: Int }\n\ntype Box = { a: Coins }\n\n",
7527                    "    let b <- shop.quote()\n    let c <- shop.Store.get()\n    \
7528                     Effect.pure(b.a.cents + c.a.cents)",
7529                ),
7530            ),
7531        ]);
7532        a.assert_clean();
7533    }
7534
7535    #[test]
7536    fn an_ambiguous_unexported_name_explains_its_rejection() {
7537        let other = "context depot\n\ntype Box = { label: String }\n\n\
7538                     service quote {\n  on call() -> Effect[Box] by Caller {\n    Effect.pure(Box { label: \"x\" })\n  }\n}\n";
7539        let a = analyse(&[
7540            ("shop.bynk", SHOP),
7541            ("depot.bynk", other),
7542            (
7543                "till.bynk",
7544                "context till\n\nconsumes shop\n\nconsumes depot\n\n\
7545                 service total {\n  on call() -> Effect[Int] by Caller {\n    \
7546                 let b <- shop.quote()\n    shop.take(b)\n  }\n}\n",
7547            ),
7548        ]);
7549        let err = a
7550            .analysis
7551            .errors
7552            .iter()
7553            .find(|e| e.error.category == "bynk.boundary.structural_mismatch")
7554            .expect("the argument is rejected");
7555        assert!(
7556            err.error
7557                .notes
7558                .iter()
7559                .any(|n| n.contains("more than one consumed context declares a type `Box`")),
7560            "{:?}",
7561            err.error.notes
7562        );
7563    }
7564
7565    #[test]
7566    fn a_return_the_caller_does_not_rebrand_is_not_checked_against_a_projection() {
7567        // Review of #1949: `shop` and `depot` declare the same-shaped `Box`, so
7568        // the projection holds one of them (`depot`'s, in name order). `till`
7569        // declares no `Box`, so `quote`'s `Box` is not rebranded and needs
7570        // no check, however `depot`'s `Box.a` would resolve against `till`'s
7571        // own, unrelated `Amount`.
7572        let pair = |name: &str, svc: &str| {
7573            format!(
7574                "context {name}\n\ntype Amount = {{ cents: Int }}\n\ntype Box = {{ a: Amount }}\n\n{svc}"
7575            )
7576        };
7577        let shop = pair(
7578            "shop",
7579            "service quote {\n  on call() -> Effect[Box] by Caller {\n    Effect.pure(Box { a: Amount { cents: 1 } })\n  }\n}\n",
7580        );
7581        let depot = pair(
7582            "depot",
7583            "service store {\n  on call(b: Box) -> Effect[Int] by Caller {\n    Effect.pure(b.a.cents)\n  }\n}\n",
7584        );
7585        let a = analyse(&[
7586            ("shop.bynk", &shop),
7587            ("depot.bynk", &depot),
7588            (
7589                "till.bynk",
7590                "context till\n\nconsumes shop\n\nconsumes depot\n\n\
7591                 type Amount = { dollars: Int }\n\n\
7592                 fn mine() -> Amount {\n  Amount { dollars: 1 }\n}\n\n\
7593                 service total {\n  on call() -> Effect[Int] by Caller {\n    \
7594                 let b <- shop.quote()\n    Effect.pure(1)\n  }\n}\n",
7595            ),
7596        ]);
7597        a.assert_clean();
7598    }
7599
7600    /// Review of #1949: a provider whose `Box` is returned inside each
7601    /// container a cross-context return can carry, for a caller whose own
7602    /// `Box` has another shape.
7603    fn caller_box_differs_inside(ret: &str, value: &str) {
7604        let shop = format!(
7605            "context shop\n\ntype Box = {{ a: Int }}\n\n\
7606             service quote {{\n  on call() -> Effect[{ret}] by Caller {{\n    Effect.pure({value})\n  }}\n}}\n"
7607        );
7608        let a = analyse(&[
7609            ("shop.bynk", &shop),
7610            (
7611                "till.bynk",
7612                "context till\n\nconsumes shop\n\ntype Box = { label: String }\n\n\
7613                 service total {\n  on call() -> Effect[Int] by Caller {\n    \
7614                 let b <- shop.quote()\n    Effect.pure(1)\n  }\n}\n",
7615            ),
7616        ]);
7617        a.assert_reports("bynk.boundary.structural_mismatch");
7618    }
7619
7620    #[test]
7621    fn a_differing_caller_type_is_found_in_a_result() {
7622        caller_box_differs_inside("Result[Box, String]", "Ok(Box { a: 1 })");
7623    }
7624
7625    #[test]
7626    fn a_differing_caller_type_is_found_in_a_map_value() {
7627        caller_box_differs_inside("Map[String, Box]", "Map.empty()");
7628    }
7629
7630    #[test]
7631    fn a_differing_caller_type_is_found_in_an_option() {
7632        caller_box_differs_inside("Option[Box]", "None");
7633    }
7634
7635    #[test]
7636    fn a_differing_caller_type_is_found_in_a_list() {
7637        caller_box_differs_inside("List[Box]", "[]");
7638    }
7639
7640    #[test]
7641    fn a_differing_caller_type_is_found_in_an_http_result() {
7642        caller_box_differs_inside("HttpResult[Box]", "Ok(Box { a: 1 })");
7643    }
7644
7645    #[test]
7646    fn agreeing_declarations_project_in_context_name_order() {
7647        // Review of #1949: `depot`'s `Box` names `Coins` and `shop`'s names
7648        // `Amount`, of the same shape, so the two agree and either may be
7649        // projected. `till`'s own `Amount` differs: `shop`'s `Box` would
7650        // read its field as `till`'s, and `depot`'s would not. The projection
7651        // takes contexts in name order, so `depot`'s is the one, on every run.
7652        let a = analyse(&[
7653            (
7654                "shop.bynk",
7655                "context shop\n\ntype Amount = { cents: Int }\n\ntype Box = { a: Amount }\n\n\
7656                 service quote {\n  on call() -> Effect[Box] by Caller {\n    \
7657                 Effect.pure(Box { a: Amount { cents: 1 } })\n  }\n}\n",
7658            ),
7659            (
7660                "depot.bynk",
7661                "context depot\n\ntype Coins = { cents: Int }\n\ntype Box = { a: Coins }\n\n\
7662                 service store {\n  on call(b: Box) -> Effect[Int] by Caller {\n    Effect.pure(b.a.cents)\n  }\n}\n",
7663            ),
7664            (
7665                "till.bynk",
7666                "context till\n\nconsumes shop\n\nconsumes depot\n\n\
7667                 type Amount = { dollars: Int }\n\n\
7668                 fn mine() -> Amount {\n  Amount { dollars: 1 }\n}\n\n\
7669                 service total {\n  on call() -> Effect[Int] by Caller {\n    \
7670                 let b <- shop.quote()\n    depot.store(b)\n  }\n}\n",
7671            ),
7672        ]);
7673        a.assert_clean();
7674    }
7675}