Skip to main content

bynk_check/
symbols.rs

1use std::collections::{BTreeMap, HashMap};
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use crate::checker::CapabilityInfo;
6use crate::index::{IndexBuilder, ProjectIndex, RefSink, SiteRef, SymbolKind};
7use crate::project_model::UnitInfo;
8use crate::resolver::{self, MethodTable as ResolverMethodTable};
9use bynk_project::{ParsedFile, UnitKind};
10use bynk_syntax::ast::SourceUnit;
11use bynk_syntax::ast::{
12    ActorDecl, AgentDecl, AssetDecl, BaseType, Block, CapRef, CapabilityDecl, CommonsItem,
13    ConstDecl, EmbedDecl, EventDecl, ExportKind, Expr, ExprId, ExprKind, FnDecl, FnName,
14    HandlerKind, Ident, Param, ProviderDecl, ServiceDecl, ServiceProtocol, Trivia, TypeBody,
15    TypeDecl, TypeRef, Visibility,
16};
17use bynk_syntax::error::CompileError;
18use bynk_syntax::span::Span;
19
20/// v0.25 (ADR 0053): walk every parsed file's top-level declarations into
21/// the def table (synthetic first-party units and test files excluded —
22/// neither declares user-editable symbols), then qualify and attach the
23/// recorded edges. Methods register as owners only (attribution), not as
24/// symbols — they are deferred along with fields and op names.
25pub fn assemble_index(
26    parsed: &[ParsedFile],
27    unit_uses: &HashMap<String, Vec<String>>,
28    unit_consumes: &HashMap<String, Vec<String>>,
29    unit_type_aliases: &HashMap<String, HashMap<String, ConsumedTypeAlias>>,
30    refs: RefSink,
31) -> ProjectIndex {
32    let mut builder = IndexBuilder::default();
33    let mut uses = unit_uses.clone();
34    uses.extend(refs.extra_uses);
35    builder.set_uses(uses);
36    builder.set_consumes(unit_consumes.clone());
37    // #2887: only the aliases `phase_resolve_consumes` accepted.
38    let type_aliases = unit_type_aliases
39        .iter()
40        .map(|(unit, aliases)| {
41            let aliases = aliases
42                .iter()
43                .map(|(alias, a)| (alias.clone(), (a.target.clone(), a.original.clone())))
44                .collect();
45            (unit.clone(), aliases)
46        })
47        .collect();
48    builder.set_type_aliases(type_aliases);
49    for pf in parsed {
50        // #2834: a suite's helper `fn`s are definitions in the suite's own
51        // namespace (`test_suites::suite_helper_namespace`); its cases are
52        // not declarations.
53        if let SourceUnit::Suite(suite) = pf.unit() {
54            let path = pf.identity_path();
55            let ns = crate::test_suites::suite_helper_namespace(&suite.target.joined(), &path);
56            // #2841: a fixture is a constant of the suite, like an embed.
57            for f in &suite.fixtures {
58                builder.add_leaf_def(
59                    &ns,
60                    SymbolKind::Embed,
61                    &f.name.name,
62                    SiteRef {
63                        path: path.clone(),
64                        span: f.name.span,
65                    },
66                    symbol_modifiers(&ns, None),
67                );
68            }
69            // #3066: a suite's own types and constants are definitions of the
70            // suite's namespace too.
71            for t in &suite.types {
72                builder.add_def(
73                    &ns,
74                    SymbolKind::Type,
75                    &t.name.name,
76                    SiteRef {
77                        path: path.clone(),
78                        span: t.name.span,
79                    },
80                    symbol_modifiers(&ns, Some(t)),
81                );
82            }
83            for c in &suite.consts {
84                builder.add_leaf_def(
85                    &ns,
86                    SymbolKind::Const,
87                    &c.name.name,
88                    SiteRef {
89                        path: path.clone(),
90                        span: c.name.span,
91                    },
92                    symbol_modifiers(&ns, None),
93                );
94            }
95            for f in &suite.fns {
96                if let FnName::Free(id) = &f.name {
97                    builder.add_def(
98                        &ns,
99                        SymbolKind::Fn,
100                        &id.name,
101                        SiteRef {
102                            path: path.clone(),
103                            span: id.span,
104                        },
105                        symbol_modifiers(&ns, None),
106                    );
107                }
108            }
109        }
110        if matches!(pf.kind(), UnitKind::Test | UnitKind::Integration) {
111            continue;
112        }
113        let unit = pf.unit().name().joined();
114        // v0.28 (ADR 0057): synthetic first-party units stay out of
115        // `symbols` (their defs point at files not on disk — the v0.25
116        // rule), but their declarations register for the second
117        // qualification pass so references to them colour as tokens.
118        if pf.is_synthetic() {
119            for item in pf.items() {
120                let (kind, name, modifiers) = match item {
121                    CommonsItem::Type(t) => (
122                        SymbolKind::Type,
123                        &t.name.name,
124                        symbol_modifiers(&unit, Some(t)),
125                    ),
126                    // Events track, slice 0 (spine #936): an `event` indexes
127                    // as an ordinary `Type` symbol — it *is* one, a record,
128                    // registered via `EventDecl::as_type_decl`. A dedicated
129                    // `SymbolKind::Event` (its own hover/completion icon) is
130                    // a follow-on, not a slice-0 blocker.
131                    CommonsItem::Event(e) => (
132                        SymbolKind::Type,
133                        &e.name.name,
134                        symbol_modifiers(&unit, None),
135                    ),
136                    CommonsItem::Fn(f) => match &f.name {
137                        FnName::Free(id) => {
138                            (SymbolKind::Fn, &id.name, symbol_modifiers(&unit, None))
139                        }
140                        FnName::Method { .. } => continue,
141                    },
142                    CommonsItem::Capability(c) => (
143                        SymbolKind::Capability,
144                        &c.name.name,
145                        symbol_modifiers(&unit, None),
146                    ),
147                    CommonsItem::Service(s) => (
148                        SymbolKind::Service,
149                        &s.name.name,
150                        symbol_modifiers(&unit, None),
151                    ),
152                    CommonsItem::Agent(a) => (
153                        SymbolKind::Agent,
154                        &a.name.name,
155                        symbol_modifiers(&unit, None),
156                    ),
157                    CommonsItem::Provider(p) => (
158                        SymbolKind::Provider,
159                        &p.provider_name.name,
160                        symbol_modifiers(&unit, None),
161                    ),
162                    CommonsItem::Actor(a) => (
163                        SymbolKind::Actor,
164                        &a.name.name,
165                        symbol_modifiers(&unit, None),
166                    ),
167                    CommonsItem::Messages(m) => {
168                        (SymbolKind::Messages, &m.tag, symbol_modifiers(&unit, None))
169                    }
170                    // #1883: an asset indexes under its own kind, keyed by
171                    // name in the declaring unit.
172                    CommonsItem::Asset(a) => (
173                        SymbolKind::Asset,
174                        &a.name.name,
175                        symbol_modifiers(&unit, None),
176                    ),
177                    // #2387: an embed indexes under its own kind, keyed by
178                    // name in the declaring unit.
179                    CommonsItem::Embed(e) => (
180                        SymbolKind::Embed,
181                        &e.name.name,
182                        symbol_modifiers(&unit, None),
183                    ),
184                    // #2617: a constant indexes under its own kind, keyed by
185                    // name in the declaring unit.
186                    CommonsItem::Const(c) => (
187                        SymbolKind::Const,
188                        &c.name.name,
189                        symbol_modifiers(&unit, None),
190                    ),
191                };
192                builder.add_first_party_def(&unit, kind, name, modifiers);
193            }
194            continue;
195        }
196        let site = |id: &Ident| SiteRef {
197            path: pf.identity_path(),
198            span: id.span,
199        };
200        for item in pf.items() {
201            match item {
202                CommonsItem::Type(t) => {
203                    builder.add_def(
204                        &unit,
205                        SymbolKind::Type,
206                        &t.name.name,
207                        site(&t.name),
208                        symbol_modifiers(&unit, Some(t)),
209                    );
210                    // v0.129 (#259): record a refined/opaque type's builtin base
211                    // for the refinement-family codelens. A plain alias
212                    // (`type Age = Int`) counts — it parses as `Refined { …, base }`
213                    // with no `where`, still declared over the base.
214                    if let TypeBody::Refined {
215                        base, base_span, ..
216                    }
217                    | TypeBody::Opaque {
218                        base, base_span, ..
219                    } = &t.body
220                    {
221                        let opaque = matches!(t.body, TypeBody::Opaque { .. });
222                        let base_site = SiteRef {
223                            path: pf.identity_path(),
224                            span: *base_span,
225                        };
226                        builder.add_refinement(&unit, &t.name.name, *base, opaque, base_site);
227                    }
228                    // v0.36 (ADR 0069, slice 2): record fields are first-class
229                    // symbols keyed by the compound `"Type.field"` name.
230                    if let TypeBody::Record(r) = &t.body {
231                        for field in &r.fields {
232                            builder.add_def(
233                                &unit,
234                                SymbolKind::Field,
235                                &format!("{}.{}", t.name.name, field.name.name),
236                                site(&field.name),
237                                symbol_modifiers(&unit, None),
238                            );
239                        }
240                    }
241                }
242                // Events track, slice 0 (spine #936): an `event` indexes
243                // exactly like a `Type` whose body is a record — same
244                // `SymbolKind::Type`/`SymbolKind::Field` reuse as the
245                // synthetic-unit arm above, so hover/go-to-def/rename work
246                // on an event and its fields without a new symbol kind.
247                CommonsItem::Event(e) => {
248                    builder.add_def(
249                        &unit,
250                        SymbolKind::Type,
251                        &e.name.name,
252                        site(&e.name),
253                        symbol_modifiers(&unit, None),
254                    );
255                    for field in &e.body.fields {
256                        builder.add_def(
257                            &unit,
258                            SymbolKind::Field,
259                            &format!("{}.{}", e.name.name, field.name.name),
260                            site(&field.name),
261                            symbol_modifiers(&unit, None),
262                        );
263                    }
264                }
265                CommonsItem::Fn(f) => match &f.name {
266                    FnName::Free(id) => {
267                        builder.add_def(
268                            &unit,
269                            SymbolKind::Fn,
270                            &id.name,
271                            site(id),
272                            symbol_modifiers(&unit, None),
273                        );
274                    }
275                    FnName::Method { .. } => {
276                        // v0.36 (ADR 0069): a method is a first-class symbol
277                        // keyed by the compound `"Type.method"` name, and (as
278                        // before) an attribution owner for call-hierarchy.
279                        builder.add_owner(&unit, &f.name.display(), &pf.identity_path());
280                        builder.add_def(
281                            &unit,
282                            SymbolKind::Method,
283                            &f.name.display(),
284                            site(f.name.ident()),
285                            symbol_modifiers(&unit, None),
286                        );
287                    }
288                },
289                CommonsItem::Capability(c) => {
290                    builder.add_def(
291                        &unit,
292                        SymbolKind::Capability,
293                        &c.name.name,
294                        site(&c.name),
295                        symbol_modifiers(&unit, None),
296                    );
297                    // v0.36 (ADR 0069, slice 2): capability operations are
298                    // first-class symbols keyed by the compound `"Cap.op"` name.
299                    for op in &c.ops {
300                        builder.add_def(
301                            &unit,
302                            SymbolKind::CapabilityOp,
303                            &format!("{}.{}", c.name.name, op.name.name),
304                            site(&op.name),
305                            symbol_modifiers(&unit, None),
306                        );
307                    }
308                }
309                CommonsItem::Service(s) => add_service_defs(&mut builder, &unit, pf, s),
310                CommonsItem::Agent(a) => {
311                    builder.add_def(
312                        &unit,
313                        SymbolKind::Agent,
314                        &a.name.name,
315                        site(&a.name),
316                        symbol_modifiers(&unit, None),
317                    );
318                    // #304: an agent handler is a first-class symbol keyed by
319                    // the compound `"Agent.handler"` name, mirroring the
320                    // v0.36 (ADR 0069) method/field/op convention. Service
321                    // handlers have no per-handler name (`method_name` is
322                    // always `None`), so this is naturally agent-only.
323                    for h in &a.handlers {
324                        if let Some(name) = &h.method_name {
325                            builder.add_def(
326                                &unit,
327                                SymbolKind::Handler,
328                                &format!("{}.{}", a.name.name, name.name),
329                                site(name),
330                                symbol_modifiers(&unit, None),
331                            );
332                        }
333                    }
334                }
335                CommonsItem::Provider(p) => {
336                    builder.add_def(
337                        &unit,
338                        SymbolKind::Provider,
339                        &p.provider_name.name,
340                        site(&p.provider_name),
341                        symbol_modifiers(&unit, None),
342                    );
343                }
344                CommonsItem::Actor(a) => {
345                    builder.add_def(
346                        &unit,
347                        SymbolKind::Actor,
348                        &a.name.name,
349                        site(&a.name),
350                        symbol_modifiers(&unit, None),
351                    );
352                }
353                CommonsItem::Messages(m) => {
354                    // The tag is a string literal, not an `Ident`, so build the
355                    // `SiteRef` from its span directly rather than via `site`.
356                    builder.add_def(
357                        &unit,
358                        SymbolKind::Messages,
359                        &m.tag,
360                        SiteRef {
361                            path: pf.identity_path(),
362                            span: m.tag_span,
363                        },
364                        symbol_modifiers(&unit, None),
365                    );
366                }
367                // #1883: an asset's declaration site, for hover, go-to-
368                // definition, references, rename and semantic tokens. A bare
369                // use in a unit that `uses` this one resolves here through the
370                // qualification pass, as a function's does. A leaf def: an
371                // asset encloses no call site, so it registers no owner (one
372                // would clash with a same-named service's — review of #1924).
373                CommonsItem::Asset(a) => {
374                    builder.add_leaf_def(
375                        &unit,
376                        SymbolKind::Asset,
377                        &a.name.name,
378                        site(&a.name),
379                        symbol_modifiers(&unit, None),
380                    );
381                }
382                // #2387: an embed's declaration site, for hover, go-to-
383                // definition, references, rename and semantic tokens — a leaf
384                // def, like an asset, so it takes over no owner entry.
385                CommonsItem::Embed(e) => {
386                    builder.add_leaf_def(
387                        &unit,
388                        SymbolKind::Embed,
389                        &e.name.name,
390                        site(&e.name),
391                        symbol_modifiers(&unit, None),
392                    );
393                }
394                // #2617: a constant's declaration site — a def that owns the
395                // references in its initialiser (another constant, a type).
396                CommonsItem::Const(c) => {
397                    builder.add_leaf_def(
398                        &unit,
399                        SymbolKind::Const,
400                        &c.name.name,
401                        site(&c.name),
402                        symbol_modifiers(&unit, None),
403                    );
404                }
405            }
406        }
407    }
408    builder.build(refs.edges)
409}
410
411/// A service's definition, and (#3582) its callable handlers — `on call` and each `on http` route —
412/// as call-only `Handler` symbols keyed `"service.call"` / `"service.POST /path"`,
413/// so a cross-context call has a handler to be an edge to. The definition site is
414/// the handler's `on` keyword; no other handler
415/// kind can be called or is named by method and path.
416fn add_service_defs(
417    builder: &mut IndexBuilder,
418    unit: &str,
419    pf: &ParsedFile,
420    service: &ServiceDecl,
421) {
422    let (path, source) = (pf.identity_path(), pf.source());
423    builder.add_def(
424        unit,
425        SymbolKind::Service,
426        &service.name.name,
427        SiteRef {
428            path: path.clone(),
429            span: service.name.span,
430        },
431        symbol_modifiers(unit, None),
432    );
433    for h in &service.handlers {
434        let label = match &h.kind {
435            HandlerKind::Call => "call".to_string(),
436            HandlerKind::Http { method, path } => format!("{} {path}", method.as_str()),
437            _ => continue,
438        };
439        let start = on_keyword_start(source, h);
440        let span = Span {
441            start,
442            end: start + 2,
443            ..h.span
444        };
445        builder.add_call_only_def(
446            unit,
447            &format!("{}.{label}", service.name.name),
448            SiteRef {
449                path: path.clone(),
450                span,
451            },
452        );
453    }
454}
455
456/// Byte offset of a handler's `on` keyword. `Handler.span` starts at the first
457/// annotation when there is one, so skip past the annotations (and any
458/// whitespace or `//` comments after them) in the source.
459fn on_keyword_start(source: &str, h: &bynk_syntax::ast::Handler) -> usize {
460    let Some(last) = h.annotations.last() else {
461        return h.span.start;
462    };
463    let mut at = last.span.end;
464    while let Some(rest) = source.get(at..) {
465        let trimmed = rest.trim_start();
466        at += rest.len() - trimmed.len();
467        if trimmed.starts_with("//") {
468            at += trimmed.find('\n').map_or(trimmed.len(), |n| n + 1);
469        } else {
470            break;
471        }
472    }
473    if source.get(at..).is_some_and(|r| r.starts_with("on")) {
474        at
475    } else {
476        h.span.start
477    }
478}
479
480/// v0.28 (ADR 0057): a symbol's semantic-token modifiers from its
481/// declaration. `refined` only when a refinement is present — `type X = Int`
482/// is `Refined { refinement: None }`, a plain alias, and carries neither;
483/// `opaque` is orthogonal (an `opaque … where` type carries both).
484/// `platform_native` when the declaring unit is a platform adapter.
485fn symbol_modifiers(unit: &str, type_decl: Option<&TypeDecl>) -> crate::index::SymbolModifiers {
486    let (refined, opaque) = match type_decl.map(|t| &t.body) {
487        Some(TypeBody::Refined { refinement, .. }) => (refinement.is_some(), false),
488        Some(TypeBody::Opaque { refinement, .. }) => (refinement.is_some(), true),
489        _ => (false, false),
490    };
491    crate::index::SymbolModifiers {
492        refined,
493        opaque,
494        platform_native: crate::firstparty::platform_of(unit).is_some(),
495    }
496}
497
498/// Combined symbol tables for a single logical commons or context.
499#[derive(Clone, Default)]
500pub struct UnitTable {
501    /// #2719: the build's needs-context set, stamped on once every unit is
502    /// checked (empty before). Emission reads it to decide which handlers' `deps`
503    /// carry the execution context; a table is the one value every such gate
504    /// already holds.
505    pub exec_plan: Arc<crate::exec_plan::ExecPlan>,
506    pub kind: Option<UnitKind>,
507    pub types: HashMap<String, Arc<TypeDecl>>,
508    pub fns: HashMap<String, Arc<FnDecl>>,
509    pub methods: HashMap<String, ResolverMethodTable>,
510    /// Per-context capabilities (v0.5). Empty for commons.
511    pub capabilities: HashMap<String, CapabilityDecl>,
512    /// Per-context providers (v0.5). One provider per capability in v0.5.
513    /// Key: capability name. Value: provider declaration.
514    pub providers: HashMap<String, ProviderDecl>,
515    /// Per-context services (v0.5). Empty for commons.
516    pub services: HashMap<String, ServiceDecl>,
517    /// Per-context agents (v0.5). Empty for commons.
518    pub agents: HashMap<String, Arc<AgentDecl>>,
519    /// State-migrations S3 (#2248): the context's `removed agent`
520    /// declarations, across its files.
521    pub removed_agents: Vec<bynk_syntax::ast::RemovedAgentDecl>,
522    /// v0.45: actors — boundary contracts consumed by handler `by` clauses.
523    pub actors: HashMap<String, ActorDecl>,
524    /// v0.15: capability names this context offers to consumers via
525    /// `exports capability { … }`. Empty for commons.
526    pub exported_capabilities: std::collections::HashSet<String>,
527    /// Events track, slice 0 (spine #936): `event` declarations. Each also
528    /// registers into `types` (via `EventDecl::as_type_decl`) so ordinary
529    /// type-reference/exports/consumes/construction machinery treats it like
530    /// any other record type; this table is the separate "is `name`
531    /// specifically an event" answer — owner-only emission and the
532    /// `from Events(E)`/`Events.emit[E]` "must name a declared event, not
533    /// just any type" checks key off it. Empty for commons/adapters
534    /// (`bynk.event.outside_context` rejects it there).
535    pub events: HashMap<String, EventDecl>,
536    /// #1883, slice 1a: `asset` declarations, by name — values of the
537    /// built-in type `Asset`, local to this unit. A context or commons only
538    /// (`bynk.asset.outside_context_or_commons`); a unit's visible assets
539    /// add those of the commons it `uses` (`assets::compose_unit_assets`).
540    pub assets: HashMap<String, AssetDecl>,
541    /// #2387, slice 1: `embed` declarations, by name — `String` constants
542    /// holding a project file's text, local to this unit. A context or commons
543    /// only (`bynk.embed.outside_context_or_commons`); a unit's visible embeds
544    /// add those of the commons it `uses` (`embeds::compose_unit_embeds`).
545    pub embeds: HashMap<String, EmbedDecl>,
546    /// #2617: `const` declarations, by name — values of their annotated type,
547    /// local to this unit. A context or commons only
548    /// (`bynk.resolve.const_outside_context_or_commons`); a unit's visible
549    /// constants add those of the commons it `uses`
550    /// (`consts::compose_unit_consts`).
551    pub consts: HashMap<String, ConstDecl>,
552    /// #291: the capabilities this unit flattens in with `consumes U { Cap }`,
553    /// each mapped to the unit providing it — `phase_resolve_consumes`'s
554    /// per-unit answer, recorded by [`record_flattened_caps`] so a test body's
555    /// privileged view sees the target's platform seams.
556    pub flattened_caps: HashMap<String, String>,
557    /// #2887: the exported types this unit renames with `consumes U { T as
558    /// Alias }`, keyed by the alias. Recorded by [`record_flattened_caps`].
559    pub consumed_type_aliases: HashMap<String, ConsumedTypeAlias>,
560    /// #3536: the types of the first-party units this unit consumes with a
561    /// braced list (`consumes bynk { Logger }`) that the list does not name.
562    /// A selective `consumes` brings in only what it lists, so these are not
563    /// candidates for a name clash or a bare-variant lookup, and a declaration
564    /// of this unit's own wins over them. Recorded by
565    /// [`record_unselected_consumed_types`].
566    pub unselected_consumed_types: std::collections::BTreeSet<String>,
567    /// #3536: every type of those units the braces do not list, including the
568    /// ones a listed capability's signatures reach (which stay in scope as
569    /// values, so [`UnitTable::unselected_consumed_types`] leaves them out).
570    /// What `bynk.consumes.type_not_selected` is reported against.
571    pub unlisted_consumed_types: std::collections::BTreeSet<String>,
572    /// S4a (#1966): the derived capabilities (`capability Sessions = Kv`)
573    /// this context declares, by name, once resolved to their base by
574    /// [`crate::project_model::phase_resolve_derived`]. Each is also in
575    /// [`UnitTable::capabilities`], with its base's operations, so `given`,
576    /// calls and test views treat it as an ordinary capability.
577    pub derived: HashMap<String, DerivedInstance>,
578}
579
580/// One type's methods: its name, then its instance and static methods in key order.
581pub(crate) type SortedMethods<'a> = (
582    &'a String,
583    Vec<(&'a String, &'a Arc<FnDecl>)>,
584    Vec<(&'a String, &'a Arc<FnDecl>)>,
585);
586
587/// A method table with its maps in key order, so its `Debug` is the same for two
588/// equal tables however their `HashMap`s happen to iterate (#3243 S2.3b: the
589/// language server hashes the rendering).
590pub(crate) fn sorted_methods(
591    methods: &HashMap<String, ResolverMethodTable>,
592) -> Vec<SortedMethods<'_>> {
593    fn sorted(m: &HashMap<String, Arc<FnDecl>>) -> Vec<(&String, &Arc<FnDecl>)> {
594        let mut v: Vec<_> = m.iter().collect();
595        v.sort_by(|a, b| a.0.cmp(b.0));
596        v
597    }
598    let mut out: Vec<_> = methods
599        .iter()
600        .map(|(k, t)| (k, sorted(&t.instance), sorted(&t.statics)))
601        .collect();
602    out.sort_by(|a, b| a.0.cmp(b.0));
603    out
604}
605
606impl UnitTable {
607    /// #3536: [`UnitTable::unselected_consumed_types`] as a set.
608    pub fn unselected_names(&self) -> std::collections::HashSet<String> {
609        self.unselected_consumed_types.iter().cloned().collect()
610    }
611
612    /// The parts of this table that are **not** a function of the unit's own
613    /// files (#3243 S2.3b): everything `phase_symbol_tables` builds from a unit's
614    /// own sources is covered by hashing those sources, so a file-check digest
615    /// takes only these, which `record_flattened_caps` and
616    /// `phase_resolve_derived` fill in from other units.
617    ///
618    /// Exhaustive on purpose: a new field must be classified here, as own-source
619    /// (named `_`) or cross-unit (returned).
620    pub(crate) fn cross_unit_facts(&self) -> impl std::fmt::Debug + '_ {
621        fn sorted<K: Ord, V>(m: &HashMap<K, V>) -> Vec<(&K, &V)> {
622            let mut v: Vec<_> = m.iter().collect();
623            v.sort_by(|a, b| a.0.cmp(b.0));
624            v
625        }
626        let UnitTable {
627            // Stamped after every unit is checked.
628            exec_plan: _,
629            kind,
630            // Built by `phase_symbol_tables` from the unit's own files.
631            types: _,
632            fns: _,
633            methods: _,
634            capabilities: _,
635            providers: _,
636            services: _,
637            agents: _,
638            removed_agents: _,
639            actors: _,
640            exported_capabilities: _,
641            events: _,
642            assets: _,
643            embeds: _,
644            consts: _,
645            // Filled in from other units.
646            flattened_caps,
647            consumed_type_aliases,
648            unselected_consumed_types,
649            unlisted_consumed_types,
650            derived,
651        } = self;
652        (
653            *kind,
654            sorted(flattened_caps),
655            sorted(consumed_type_aliases),
656            unselected_consumed_types,
657            unlisted_consumed_types,
658            sorted(derived),
659        )
660    }
661
662    /// #2618: does this unit declare anything `private`?
663    pub fn has_private(&self) -> bool {
664        self.types.values().any(|d| d.private.is_some())
665            || self.fns.values().any(|d| d.private.is_some())
666            || self.assets.values().any(|d| d.private.is_some())
667            || self.embeds.values().any(|d| d.private.is_some())
668            || self.consts.values().any(|d| d.private.is_some())
669            || self.methods.values().any(|mt| {
670                mt.instance
671                    .values()
672                    .chain(mt.statics.values())
673                    .any(|d| d.private.is_some())
674            })
675    }
676
677    /// #2618: the table as a unit that `uses` this one sees it — without its
678    /// `private` declarations. A private type's methods go with it, public or
679    /// not: an importer can neither name the type nor reach a value of it.
680    ///
681    /// Borrowed when the unit declares nothing private (every unit before
682    /// #2618), so an import costs no copy. The unit itself, and its suites,
683    /// read the full table instead.
684    pub fn importable(&self) -> std::borrow::Cow<'_, UnitTable> {
685        if !self.has_private() {
686            return std::borrow::Cow::Borrowed(self);
687        }
688        let mut t = self.clone();
689        let private_types: std::collections::HashSet<String> = t
690            .types
691            .iter()
692            .filter(|(_, d)| d.private.is_some())
693            .map(|(n, _)| n.clone())
694            .collect();
695        t.types.retain(|n, _| !private_types.contains(n));
696        t.fns.retain(|_, d| d.private.is_none());
697        t.assets.retain(|_, d| d.private.is_none());
698        t.embeds.retain(|_, d| d.private.is_none());
699        t.consts.retain(|_, d| d.private.is_none());
700        t.methods.retain(|n, _| !private_types.contains(n));
701        for mt in t.methods.values_mut() {
702            mt.instance.retain(|_, d| d.private.is_none());
703            mt.statics.retain(|_, d| d.private.is_none());
704        }
705        std::borrow::Cow::Owned(t)
706    }
707
708    /// #2618: the declarations this unit makes `private`, each keyed by the
709    /// subject an unknown-name diagnostic names it by (`f`, `T`, or a method
710    /// as `T.m`), with its kind. A reference from an importing unit that
711    /// meets one is `bynk.visibility.private_item`
712    /// ([`crate::resolver::rewrite_private_references`]).
713    pub fn private_subjects(&self) -> Vec<(String, &'static str)> {
714        let mut out: Vec<(String, &'static str)> = Vec::new();
715        for (n, d) in &self.types {
716            if d.private.is_some() {
717                out.push((n.clone(), "type"));
718            }
719        }
720        for (n, d) in &self.fns {
721            if d.private.is_some() {
722                out.push((n.clone(), "function"));
723            }
724        }
725        for (n, d) in &self.assets {
726            if d.private.is_some() {
727                out.push((n.clone(), "asset"));
728            }
729        }
730        for (n, d) in &self.embeds {
731            if d.private.is_some() {
732                out.push((n.clone(), "embed"));
733            }
734        }
735        for (n, d) in &self.consts {
736            if d.private.is_some() {
737                out.push((n.clone(), "constant"));
738            }
739        }
740        for (ty, mt) in &self.methods {
741            let type_private = self.types.get(ty).is_some_and(|d| d.private.is_some());
742            for (m, d) in mt.instance.iter().chain(mt.statics.iter()) {
743                if d.private.is_some() || type_private {
744                    out.push((format!("{ty}.{m}"), "method"));
745                }
746            }
747        }
748        out
749    }
750}
751
752/// S4a (#1966): a resolved derived capability: a distinct instance of a
753/// platform capability, provided by that platform's own provider bound to this
754/// instance's Worker binding.
755#[derive(Debug, Clone, PartialEq, Eq)]
756pub struct DerivedInstance {
757    /// The unit providing the base capability (`bynk.cloudflare`).
758    pub base_unit: String,
759    /// The base capability (`Kv`).
760    pub base_cap: String,
761    /// The instance's Worker binding name (`KV_SESSIONS`).
762    pub binding: String,
763    /// Its creation options, each with its literal value, as written
764    /// (`[("worker", Str("legacy-billing"))]`, interop I5 #1972; `[("limit",
765    /// Int(100)), ("period", Seconds(60))]`, P3 #2342).
766    pub options: Vec<(String, OptionValue)>,
767    /// The `capability … = …` declaration.
768    pub span: bynk_syntax::span::Span,
769}
770
771/// Whether `unit.capability` is `bynk.cloudflare.EdgeCache` (L7, #2414),
772/// whose instances turn Workers Cache on and have no `env` binding.
773pub fn is_edge_cache_base(unit: &str, capability: &str) -> bool {
774    unit == crate::firstparty::CLOUDFLARE_UNIT && capability == "EdgeCache"
775}
776
777/// The value of one instance option (standard-library P3, #2342).
778#[derive(Debug, Clone, PartialEq, Eq)]
779pub enum OptionValue {
780    /// A string literal (`@worker("legacy-billing")`).
781    Str(String),
782    /// A positive `Int` literal (`@limit(100)`).
783    Int(i64),
784    /// A `Duration` literal, in whole seconds (`@period(60.seconds)`).
785    Seconds(i64),
786    /// A list of string literals (`@allowedSenders(["[email protected]"])`,
787    /// #3302), in source order.
788    List(Vec<String>),
789}
790
791impl DerivedInstance {
792    /// The value of string option `name`, if the instance carries it.
793    pub fn option(&self, name: &str) -> Option<&str> {
794        self.options
795            .iter()
796            .find(|(o, _)| o == name)
797            .and_then(|(_, v)| match v {
798                OptionValue::Str(s) => Some(s.as_str()),
799                _ => None,
800            })
801    }
802
803    /// The value of list option `name` (a list of string literals), or empty
804    /// when the instance does not carry it.
805    pub fn list(&self, name: &str) -> &[String] {
806        self.options
807            .iter()
808            .find(|(o, _)| o == name)
809            .and_then(|(_, v)| match v {
810                OptionValue::List(items) => Some(items.as_slice()),
811                _ => None,
812            })
813            .unwrap_or_default()
814    }
815
816    /// The value of numeric option `name` (an `Int`, or a `Duration` in
817    /// seconds), if the instance carries it.
818    pub fn number(&self, name: &str) -> Option<i64> {
819        self.options
820            .iter()
821            .find(|(o, _)| o == name)
822            .and_then(|(_, v)| match v {
823                OptionValue::Int(n) | OptionValue::Seconds(n) => Some(*n),
824                OptionValue::Str(_) | OptionValue::List(_) => None,
825            })
826    }
827
828    /// Whether this is a `RateLimit` instance (P3, #2342).
829    pub fn is_ratelimit(&self) -> bool {
830        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "RateLimit"
831    }
832
833    /// Whether this is an `EdgeCache` instance (L7, #2414).
834    pub fn is_edge_cache(&self) -> bool {
835        is_edge_cache_base(&self.base_unit, &self.base_cap)
836    }
837
838    /// A `RateLimit` instance's `(limit, period in seconds)`, or `None` for
839    /// any other kind.
840    pub fn rate_limit(&self) -> Option<(i64, i64)> {
841        if !self.is_ratelimit() {
842            return None;
843        }
844        Some((
845            self.number(crate::firstparty::RATELIMIT_LIMIT_OPTION)?,
846            self.number(crate::firstparty::RATELIMIT_PERIOD_OPTION)?,
847        ))
848    }
849
850    /// The jurisdiction an `R2` instance's bucket is pinned to (P5, #2323), or
851    /// `None` for an unpinned one or any other kind.
852    pub fn jurisdiction(&self) -> Option<&str> {
853        self.is_r2()
854            .then(|| self.option(crate::firstparty::R2_JURISDICTION_OPTION))
855            .flatten()
856    }
857
858    /// Whether this is an `R2` instance.
859    pub fn is_r2(&self) -> bool {
860        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "R2"
861    }
862
863    /// The Worker a `Service` instance reaches (interop I5, #1972), or `None`
864    /// for any other kind.
865    pub fn worker(&self) -> Option<&str> {
866        (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Service")
867            .then(|| self.option(crate::firstparty::SERVICE_WORKER_OPTION))
868            .flatten()
869    }
870
871    /// The Secrets Store a `StoredSecret` instance reads from (#3301), by the
872    /// name the account gives it; `None` for any other kind.
873    pub fn store(&self) -> Option<&str> {
874        self.is_stored_secret()
875            .then(|| self.option(crate::firstparty::STORED_SECRET_STORE_OPTION))
876            .flatten()
877    }
878
879    /// The secret a `StoredSecret` instance reads, by its name in its store;
880    /// `None` for any other kind.
881    pub fn stored_secret(&self) -> Option<&str> {
882        self.is_stored_secret()
883            .then(|| self.option(crate::firstparty::STORED_SECRET_SECRET_OPTION))
884            .flatten()
885    }
886
887    /// The one recipient an `Email` instance pins every message to (`@to`,
888    /// #3302); `None` for an unpinned one or any other kind.
889    pub fn email_to(&self) -> Option<&str> {
890        self.is_email()
891            .then(|| self.option(crate::firstparty::EMAIL_TO_OPTION))
892            .flatten()
893    }
894
895    /// The recipients an `Email` instance may send to (`@allowedRecipients`);
896    /// empty for an unrestricted one or any other kind.
897    pub fn email_allowed_recipients(&self) -> &[String] {
898        self.list(crate::firstparty::EMAIL_ALLOWED_RECIPIENTS_OPTION)
899    }
900
901    /// The senders an `Email` instance may send as (`@allowedSenders`); empty
902    /// for an unrestricted one or any other kind.
903    pub fn email_allowed_senders(&self) -> &[String] {
904        self.list(crate::firstparty::EMAIL_ALLOWED_SENDERS_OPTION)
905    }
906
907    /// Whether this is a `Postgres` instance (Hyperdrive H1, #3318).
908    pub fn is_postgres(&self) -> bool {
909        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Postgres"
910    }
911
912    /// Whether this is a `MySql` instance (Hyperdrive H5, #3322).
913    pub fn is_mysql(&self) -> bool {
914        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "MySql"
915    }
916
917    /// The TLS mode a `MySql` instance's `@tls("…")` names, or `None` when it
918    /// carries none (the default, `required`) or is another kind.
919    pub fn tls(&self) -> Option<&str> {
920        self.is_mysql()
921            .then(|| self.option(crate::firstparty::MYSQL_TLS_OPTION))
922            .flatten()
923    }
924
925    /// Whether this is a `Vectorize` instance (#3479).
926    pub fn is_vectorize(&self) -> bool {
927        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Vectorize"
928    }
929
930    /// A `Vectorize` instance's `@dimensions`; `None` for any other kind.
931    pub fn vectorize_dimensions(&self) -> Option<i64> {
932        self.is_vectorize()
933            .then(|| self.number(crate::firstparty::VECTORIZE_DIMENSIONS_OPTION))
934            .flatten()
935    }
936
937    /// A `Vectorize` instance's `@metric`; `None` for any other kind.
938    pub fn vectorize_metric(&self) -> Option<&str> {
939        self.is_vectorize()
940            .then(|| self.option(crate::firstparty::VECTORIZE_METRIC_OPTION))
941            .flatten()
942    }
943
944    /// A `Vectorize` instance's `@indexed` entries as written (`name:type`);
945    /// empty when it has none or is another kind.
946    pub fn vectorize_indexed(&self) -> &[String] {
947        self.list(crate::firstparty::VECTORIZE_INDEXED_OPTION)
948    }
949
950    /// Whether this is a `Container` instance (#3477).
951    pub fn is_container(&self) -> bool {
952        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Container"
953    }
954
955    /// A `Container` instance's `@build` directory as written; `None` for any
956    /// other kind.
957    pub fn container_build(&self) -> Option<&str> {
958        self.is_container()
959            .then(|| self.option(crate::firstparty::CONTAINER_BUILD_OPTION))
960            .flatten()
961    }
962
963    /// A `Container` instance's `@port`; `None` for any other kind.
964    pub fn container_port(&self) -> Option<i64> {
965        self.is_container()
966            .then(|| self.number(crate::firstparty::CONTAINER_PORT_OPTION))
967            .flatten()
968    }
969
970    /// A `Container` instance's `@sleepAfter` in seconds, when it has one.
971    pub fn container_sleep_after(&self) -> Option<i64> {
972        self.is_container()
973            .then(|| self.number(crate::firstparty::CONTAINER_SLEEP_AFTER_OPTION))
974            .flatten()
975    }
976
977    /// A `Container` instance's `@instanceType`, when it has one.
978    pub fn container_instance_type(&self) -> Option<&str> {
979        self.is_container()
980            .then(|| self.option(crate::firstparty::CONTAINER_INSTANCE_TYPE_OPTION))
981            .flatten()
982    }
983
984    /// A `Container` instance's `@forward` names; empty when it has none or is
985    /// another kind.
986    pub fn container_forward(&self) -> &[String] {
987        self.list(crate::firstparty::CONTAINER_FORWARD_OPTION)
988    }
989
990    /// Whether this is an `Email` instance (#3302).
991    pub fn is_email(&self) -> bool {
992        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Email"
993    }
994
995    /// The AI Search instance an `AiSearch` declaration names (#3480), as
996    /// written; `None` for any other kind.
997    pub fn ai_search_instance(&self) -> Option<&str> {
998        (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "AiSearch")
999            .then(|| self.option(crate::firstparty::AI_SEARCH_INSTANCE_OPTION))
1000            .flatten()
1001    }
1002
1003    /// The client certificate an `MtlsCertificate` declaration names (#3513 A), as
1004    /// written; `None` for any other kind.
1005    pub fn mtls_certificate(&self) -> Option<&str> {
1006        (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "MtlsCertificate")
1007            .then(|| self.option(crate::firstparty::MTLS_CERTIFICATE_OPTION))
1008            .flatten()
1009    }
1010
1011    /// Whether this is a `StoredSecret` instance (#3301).
1012    pub fn is_stored_secret(&self) -> bool {
1013        self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "StoredSecret"
1014    }
1015
1016    /// The queue a `Queue` instance sends to (standard-library P2, #2578), as
1017    /// written, before `bynk deploy` environment-qualifies it; `None` for any
1018    /// other kind.
1019    pub fn queue(&self) -> Option<&str> {
1020        (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Queue")
1021            .then(|| self.option(crate::firstparty::QUEUE_NAME_OPTION))
1022            .flatten()
1023    }
1024}
1025
1026/// #2887: one `T as Alias` in a `consumes U { … }` list: the type `original`
1027/// that `target` exports, in scope in the consuming unit only under the alias.
1028#[derive(Clone, Debug, PartialEq, Eq)]
1029pub struct ConsumedTypeAlias {
1030    pub target: String,
1031    pub original: String,
1032}
1033
1034/// #291: record each unit's flattened capabilities (`consumes U { Cap }`, from
1035/// `phase_resolve_consumes`) on its table.
1036pub fn record_flattened_caps(
1037    unit_tables: &mut HashMap<String, UnitTable>,
1038    unit_flattened: &HashMap<String, HashMap<String, String>>,
1039    unit_type_aliases: &HashMap<String, HashMap<String, ConsumedTypeAlias>>,
1040) {
1041    for (name, flattened) in unit_flattened {
1042        if let Some(t) = unit_tables.get_mut(name) {
1043            t.flattened_caps = flattened.clone();
1044        }
1045    }
1046    for (name, aliases) in unit_type_aliases {
1047        if let Some(t) = unit_tables.get_mut(name) {
1048            t.consumed_type_aliases = aliases.clone();
1049        }
1050    }
1051}
1052
1053/// #3536: record, on each unit's table, the types of its first-party consumed
1054/// units that its braces leave out. A bare `consumes bynk` (or one stated bare
1055/// in any of the unit's files) is the whole-module form and leaves nothing out;
1056/// a braced list brings in only the names it lists, so every other type of that
1057/// unit is *unselected*. Types stay resolvable, so that `bynk.consumes.type_not_selected` can
1058/// report them with a fix rather than as an unknown name, but are neither clash nor ambiguity
1059/// candidates, and the unit's own declarations win over them.
1060pub type ConsumeSelections = HashMap<String, Vec<(String, Option<Vec<String>>)>>;
1061
1062pub fn record_unselected_consumed_types(
1063    unit_tables: &mut HashMap<String, UnitTable>,
1064    consumes: &ConsumeSelections,
1065) {
1066    type Sets = std::collections::BTreeSet<String>;
1067    let mut out: HashMap<String, (Sets, Sets)> = HashMap::new();
1068    for (unit, clauses) in consumes {
1069        // target -> Some(listed names) | None for the whole-module form.
1070        let mut selection: HashMap<&str, Option<std::collections::HashSet<&str>>> = HashMap::new();
1071        for (target, names) in clauses {
1072            if !is_first_party_name(target) {
1073                continue;
1074            }
1075            match (names, selection.get_mut(target.as_str())) {
1076                (None, _) => {
1077                    selection.insert(target, None);
1078                }
1079                (Some(_), Some(None)) => {}
1080                (Some(names), Some(Some(listed))) => {
1081                    listed.extend(names.iter().map(String::as_str))
1082                }
1083                (Some(names), None) => {
1084                    selection.insert(target, Some(names.iter().map(String::as_str).collect()));
1085                }
1086            }
1087        }
1088        for (target, listed) in selection {
1089            let (Some(listed), Some(table)) = (listed, unit_tables.get(target)) else {
1090                continue;
1091            };
1092            let unlisted: Vec<&String> = table
1093                .types
1094                .keys()
1095                .filter(|t| !listed.contains(t.as_str()))
1096                .collect();
1097            // A listed capability's signatures use types that must keep meaning
1098            // the standard library's, so a declaration of the unit's own
1099            // cannot silently take their name.
1100            let reached = signature_types(table, &listed);
1101            let entry = out.entry(unit.clone()).or_default();
1102            entry.0.extend(unlisted.iter().map(|t| (*t).clone()));
1103            entry.1.extend(
1104                unlisted
1105                    .into_iter()
1106                    .filter(|t| !reached.contains(*t))
1107                    .cloned(),
1108            );
1109        }
1110    }
1111    for (unit, (unlisted, unselected)) in out {
1112        if let Some(t) = unit_tables.get_mut(&unit) {
1113            t.unlisted_consumed_types = unlisted;
1114            t.unselected_consumed_types = unselected;
1115        }
1116    }
1117}
1118
1119/// The types of `table` that the signatures of the capabilities `listed`
1120/// names mention, and that those types' own fields and payloads reach.
1121fn signature_types(
1122    table: &UnitTable,
1123    listed: &std::collections::HashSet<&str>,
1124) -> std::collections::HashSet<String> {
1125    fn names(r: &TypeRef, out: &mut Vec<String>) {
1126        match r {
1127            TypeRef::Named(id) => out.push(id.name.clone()),
1128            TypeRef::App { name, args, .. } => {
1129                out.push(name.name.clone());
1130                args.iter().for_each(|a| names(a, out));
1131            }
1132            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
1133                names(a, out);
1134                names(b, out);
1135            }
1136            TypeRef::Option(t, _)
1137            | TypeRef::Effect(t, _)
1138            | TypeRef::HttpResult(t, _)
1139            | TypeRef::List(t, _)
1140            | TypeRef::Set(t, _)
1141            | TypeRef::Query(t, _)
1142            | TypeRef::Stream(t, _)
1143            | TypeRef::Connection(t, _)
1144            | TypeRef::History(t, _) => names(t, out),
1145            TypeRef::Fn(params, ret, _) => {
1146                params.iter().for_each(|p| names(p, out));
1147                names(ret, out);
1148            }
1149            _ => {}
1150        }
1151    }
1152    let mut todo: Vec<String> = Vec::new();
1153    for cap in table
1154        .capabilities
1155        .values()
1156        .filter(|c| listed.contains(c.name.name.as_str()))
1157    {
1158        for op in &cap.ops {
1159            op.params.iter().for_each(|p| names(&p.type_ref, &mut todo));
1160            names(&op.return_type, &mut todo);
1161        }
1162    }
1163    let mut seen = std::collections::HashSet::new();
1164    while let Some(n) = todo.pop() {
1165        if !seen.insert(n.clone()) {
1166            continue;
1167        }
1168        match table.types.get(&n).map(|t| &t.body) {
1169            Some(TypeBody::Record(r)) => {
1170                r.fields.iter().for_each(|f| names(&f.type_ref, &mut todo))
1171            }
1172            Some(TypeBody::Sum(s)) => s
1173                .variants
1174                .iter()
1175                .flat_map(|v| &v.payload)
1176                .for_each(|p| names(&p.type_ref, &mut todo)),
1177            _ => {}
1178        }
1179    }
1180    seen
1181}
1182
1183/// Whether a unit name is under the reserved `bynk` root: the toolchain's own.
1184pub(crate) fn is_first_party_name(unit: &str) -> bool {
1185    unit == "bynk" || unit.starts_with("bynk.")
1186}
1187
1188/// #696: each table-construction diagnostic is attributed to the project-relative
1189/// `identity_path` of the file whose item produced it. Every error-producing loop
1190/// below iterates `for &i in indices`, so it shadows a local `errors` vec and
1191/// drains it into `out`, tagged with `parsed[i].identity_path()`, at the end of each
1192/// file's pass — leaving the many inner `errors.push(…)` sites untouched.
1193pub fn build_unit_table(
1194    _name: &str,
1195    kind: UnitKind,
1196    indices: &[usize],
1197    parsed: &[ParsedFile],
1198    out: &mut Vec<(PathBuf, CompileError)>,
1199) -> UnitTable {
1200    let mut table = UnitTable {
1201        kind: Some(kind),
1202        ..UnitTable::default()
1203    };
1204    for &i in indices {
1205        let mut errors: Vec<CompileError> = Vec::new();
1206        table
1207            .removed_agents
1208            .extend(parsed[i].removed_agents().iter().cloned());
1209        for item in parsed[i].items() {
1210            // Events track, slice 0 (spine #936): an `event` registers into
1211            // `types` exactly like a `type` (via `EventDecl::as_type_decl`,
1212            // so name-conflict detection against ordinary types is a single
1213            // check regardless of declaration order within the file) and
1214            // additionally into `events`, the separate "is this specifically
1215            // an event" table.
1216            if let CommonsItem::Event(e) = item
1217                && kind != UnitKind::Context
1218            {
1219                errors.push(CompileError::new(
1220                    "bynk.event.outside_context",
1221                    e.span,
1222                    "`event` declarations are only allowed inside a context",
1223                ));
1224                continue;
1225            }
1226            let as_type: Option<(&Ident, TypeDecl, bool)> = match item {
1227                CommonsItem::Type(t) => Some((&t.name, t.clone(), false)),
1228                CommonsItem::Event(e) => Some((&e.name, e.as_type_decl(), true)),
1229                _ => None,
1230            };
1231            if let Some((name, decl, is_event)) = as_type {
1232                if let Some(prev) = table.types.get(&name.name) {
1233                    errors.push(
1234                        CompileError::new(
1235                            "bynk.resolve.duplicate_type",
1236                            name.span,
1237                            format!("type `{}` is already declared", name.name),
1238                        )
1239                        .with_label(prev.name.span, "previously declared here"),
1240                    );
1241                } else {
1242                    table.methods.entry(name.name.clone()).or_default();
1243                    if is_event {
1244                        let CommonsItem::Event(e) = item else {
1245                            unreachable!("is_event only set for CommonsItem::Event")
1246                        };
1247                        table.events.insert(name.name.clone(), e.clone());
1248                    }
1249                    table.types.insert(name.name.clone(), Arc::new(decl));
1250                }
1251            }
1252        }
1253        out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1254    }
1255    // v0.15: collect the names a context exports as capabilities.
1256    // v0.17: adapters export capabilities too.
1257    for &i in indices {
1258        {
1259            for clause in parsed[i].exports() {
1260                if matches!(clause.kind, ExportKind::Capability) {
1261                    for n in clause.names.iter().map(|e| &e.name) {
1262                        table.exported_capabilities.insert(n.name.clone());
1263                    }
1264                }
1265            }
1266        }
1267    }
1268    // v0.5: collect capabilities, providers, services, agents.
1269    for &i in indices {
1270        let mut errors: Vec<CompileError> = Vec::new();
1271        for item in parsed[i].items() {
1272            match item {
1273                CommonsItem::Capability(c) => {
1274                    if kind != UnitKind::Context && kind != UnitKind::Adapter {
1275                        errors.push(CompileError::new(
1276                            "bynk.capability.outside_context",
1277                            c.span,
1278                            "`capability` declarations are only allowed inside a context or adapter",
1279                        ));
1280                        continue;
1281                    }
1282                    if let Some(prev) = table.capabilities.get(&c.name.name) {
1283                        errors.push(
1284                            CompileError::new(
1285                                "bynk.resolve.duplicate_capability",
1286                                c.name.span,
1287                                format!("capability `{}` is already declared", c.name.name),
1288                            )
1289                            .with_label(prev.name.span, "previously declared here"),
1290                        );
1291                    } else {
1292                        table.capabilities.insert(c.name.name.clone(), c.clone());
1293                    }
1294                }
1295                CommonsItem::Provider(p) => {
1296                    match kind {
1297                        UnitKind::Context => {
1298                            // v0.17: a bodiless (external) provider is only legal
1299                            // inside an adapter.
1300                            if p.external {
1301                                errors.push(CompileError::new(
1302                                    "bynk.context.external_provider",
1303                                    p.span,
1304                                    "an external (bodiless) provider is only allowed inside an `adapter` — a context provider must have a Bynk body",
1305                                ));
1306                                continue;
1307                            }
1308                        }
1309                        UnitKind::Adapter => {
1310                            // v0.17: an adapter provider must be external — its
1311                            // implementation comes from the binding.
1312                            if !p.external {
1313                                errors.push(CompileError::new(
1314                                    "bynk.adapter.provider_has_body",
1315                                    p.span,
1316                                    "a provider inside an `adapter` must be external (no body) — its implementation is supplied by the binding",
1317                                ));
1318                                continue;
1319                            }
1320                        }
1321                        // The parser rejects `provides` anywhere else
1322                        // (`bynk.provider.outside_context`) before a symbol
1323                        // table is built (#1662).
1324                        _ => continue,
1325                    }
1326                    if let Some(prev) = table.providers.get(&p.capability.name) {
1327                        errors.push(
1328                            CompileError::new(
1329                                "bynk.resolve.duplicate_provider",
1330                                p.span,
1331                                format!(
1332                                    "capability `{}` already has a provider in this context",
1333                                    p.capability.name
1334                                ),
1335                            )
1336                            .with_label(prev.span, "previously provided here"),
1337                        );
1338                    } else {
1339                        table.providers.insert(p.capability.name.clone(), p.clone());
1340                    }
1341                }
1342                CommonsItem::Service(s) => {
1343                    if kind == UnitKind::Adapter {
1344                        errors.push(CompileError::new(
1345                            "bynk.adapter.disallowed_item",
1346                            s.span,
1347                            "an `adapter` may not declare a `service` — adapters contain only capabilities, boundary types, external providers, and helpers",
1348                        ));
1349                        continue;
1350                    }
1351                    // An adapter's is rejected just above
1352                    // (`bynk.adapter.disallowed_item`), and the parser rejects
1353                    // a `service` in a commons (`bynk.service.outside_context`)
1354                    // before a symbol table is built, so only a context reaches
1355                    // here (#1662).
1356                    if kind != UnitKind::Context {
1357                        continue;
1358                    }
1359                    if let Some(prev) = table.services.get(&s.name.name) {
1360                        errors.push(
1361                            CompileError::new(
1362                                "bynk.resolve.duplicate_service",
1363                                s.name.span,
1364                                format!("service `{}` is already declared", s.name.name),
1365                            )
1366                            .with_label(prev.name.span, "previously declared here"),
1367                        );
1368                    } else {
1369                        table.services.insert(s.name.name.clone(), s.clone());
1370                    }
1371                }
1372                CommonsItem::Agent(a) => {
1373                    if kind == UnitKind::Adapter {
1374                        errors.push(CompileError::new(
1375                            "bynk.adapter.disallowed_item",
1376                            a.span,
1377                            "an `adapter` may not declare an `agent` — adapters contain only capabilities, boundary types, external providers, and helpers",
1378                        ));
1379                        continue;
1380                    }
1381                    // An adapter's is rejected just above
1382                    // (`bynk.adapter.disallowed_item`), and the parser rejects
1383                    // an `agent` in a commons (`bynk.agent.outside_context`)
1384                    // before a symbol table is built, so only a context reaches
1385                    // here (#1662).
1386                    if kind != UnitKind::Context {
1387                        continue;
1388                    }
1389                    if let Some(prev) = table.agents.get(&a.name.name) {
1390                        errors.push(
1391                            CompileError::new(
1392                                "bynk.resolve.duplicate_agent",
1393                                a.name.span,
1394                                format!("agent `{}` is already declared", a.name.name),
1395                            )
1396                            .with_label(prev.name.span, "previously declared here"),
1397                        );
1398                    } else {
1399                        table
1400                            .agents
1401                            .insert(a.name.name.clone(), Arc::new(a.clone()));
1402                    }
1403                }
1404                CommonsItem::Actor(a) => {
1405                    if kind == UnitKind::Adapter {
1406                        errors.push(CompileError::new(
1407                            "bynk.adapter.disallowed_item",
1408                            a.span,
1409                            "an `adapter` may not declare an `actor` — adapters contain only capabilities, boundary types, external providers, and helpers",
1410                        ));
1411                        continue;
1412                    }
1413                    if let Some(prev) = table.actors.get(&a.name.name) {
1414                        errors.push(
1415                            CompileError::new(
1416                                "bynk.resolve.duplicate_actor",
1417                                a.name.span,
1418                                format!("actor `{}` is already declared", a.name.name),
1419                            )
1420                            .with_label(prev.name.span, "previously declared here"),
1421                        );
1422                    } else {
1423                        table.actors.insert(a.name.name.clone(), a.clone());
1424                    }
1425                }
1426                _ => {}
1427            }
1428        }
1429        out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1430    }
1431    for &i in indices {
1432        let mut errors: Vec<CompileError> = Vec::new();
1433        for item in parsed[i].items() {
1434            let CommonsItem::Fn(f) = item else { continue };
1435            match &f.name {
1436                FnName::Free(id) => {
1437                    if let Some(prev) = table.fns.get(&id.name) {
1438                        errors.push(
1439                            CompileError::new(
1440                                "bynk.resolve.duplicate_fn",
1441                                id.span,
1442                                format!("function `{}` is already declared", id.name),
1443                            )
1444                            .with_label(prev.name.ident().span, "previously declared here"),
1445                        );
1446                    } else if let Some(prev) = table.types.get(&id.name) {
1447                        errors.push(
1448                            CompileError::new(
1449                                "bynk.resolve.name_conflict",
1450                                id.span,
1451                                format!(
1452                                    "function `{}` conflicts with a type of the same name",
1453                                    id.name
1454                                ),
1455                            )
1456                            .with_label(prev.name.span, "type declared here"),
1457                        );
1458                    } else {
1459                        table.fns.insert(id.name.clone(), Arc::new(f.clone()));
1460                    }
1461                }
1462                FnName::Method {
1463                    type_name,
1464                    method_name,
1465                } => {
1466                    if !table.types.contains_key(&type_name.name) {
1467                        errors.push(
1468                            CompileError::new(
1469                                "bynk.resolve.method_unknown_type",
1470                                type_name.span,
1471                                format!(
1472                                    "method `{}.{}` attached to an unknown type `{}`",
1473                                    type_name.name, method_name.name, type_name.name
1474                                ),
1475                            )
1476                            .with_note(
1477                                "methods can only be declared on types defined in the same commons or context (across all of its files)",
1478                            ),
1479                        );
1480                        continue;
1481                    }
1482                    let mt = table.methods.entry(type_name.name.clone()).or_default();
1483                    let bucket = if f.has_self {
1484                        &mut mt.instance
1485                    } else {
1486                        &mut mt.statics
1487                    };
1488                    if let Some(prev) = bucket.get(&method_name.name) {
1489                        errors.push(
1490                            CompileError::new(
1491                                "bynk.resolve.duplicate_method",
1492                                method_name.span,
1493                                format!(
1494                                    "method `{}.{}` is already declared",
1495                                    type_name.name, method_name.name
1496                                ),
1497                            )
1498                            .with_label(prev.name.ident().span, "previously declared here"),
1499                        );
1500                    } else {
1501                        bucket.insert(method_name.name.clone(), Arc::new(f.clone()));
1502                    }
1503                }
1504            }
1505        }
1506        out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1507    }
1508    // #1883, slice 1a: `asset` declarations. After the function pass, so an
1509    // asset that shares a function's or type's name is reported whichever
1510    // was declared first: an asset is a value, in the same namespace as a
1511    // free function, and a type name in expression position is an error.
1512    for &i in indices {
1513        let mut errors: Vec<CompileError> = Vec::new();
1514        for item in parsed[i].items() {
1515            let CommonsItem::Asset(a) = item else {
1516                continue;
1517            };
1518            if !matches!(kind, UnitKind::Context | UnitKind::Commons) {
1519                errors.push(
1520                    CompileError::new(
1521                        "bynk.asset.outside_context_or_commons",
1522                        a.span,
1523                        "`asset` declarations are only allowed inside a context or a commons",
1524                    )
1525                    .with_note(
1526                        "an asset ships with the Worker of each context that declares it or `uses` a commons that does",
1527                    ),
1528                );
1529                continue;
1530            }
1531            errors.extend(crate::assets::at_path_error(a));
1532            if let Some(err) = crate::assets::path_errors(a) {
1533                errors.push(err);
1534                // Still registered below: the declaration is otherwise
1535                // well-formed, so its uses should not also report
1536                // `unknown_name`.
1537            }
1538            let key = &a.name.name;
1539            match crate::assets::name_error(
1540                a,
1541                table.assets.get(key).map(|p| &p.name),
1542                table.fns.get(key).map(|f| f.name.ident()),
1543                table.types.get(key).map(|t| &t.name),
1544            ) {
1545                Some(err) => errors.push(err),
1546                None => {
1547                    table.assets.insert(key.clone(), a.clone());
1548                }
1549            }
1550        }
1551        out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1552    }
1553    // #2387, slice 1: `embed` declarations, after the asset pass so an embed
1554    // that shares an asset's, function's or type's name is reported on the
1555    // embed whichever was declared first: an embed is a value, in the same
1556    // namespace as a free function.
1557    for &i in indices {
1558        let mut errors: Vec<CompileError> = Vec::new();
1559        for item in parsed[i].items() {
1560            let CommonsItem::Embed(e) = item else {
1561                continue;
1562            };
1563            if !matches!(kind, UnitKind::Context | UnitKind::Commons) {
1564                errors.push(crate::embeds::placement_error(e));
1565                continue;
1566            }
1567            if let Some(err) = crate::embeds::path_errors(e) {
1568                errors.push(err);
1569                // Still registered below, as for an asset: the declaration is
1570                // otherwise well-formed, so its uses should not also report
1571                // `unknown_name`.
1572            }
1573            let key = &e.name.name;
1574            match crate::embeds::name_error(
1575                e,
1576                table.embeds.get(key).map(|p| &p.name),
1577                table.assets.get(key).map(|a| &a.name),
1578                table.fns.get(key).map(|f| f.name.ident()),
1579                table.types.get(key).map(|t| &t.name),
1580            ) {
1581                Some(err) => errors.push(err),
1582                None => {
1583                    table.embeds.insert(key.clone(), e.clone());
1584                }
1585            }
1586        }
1587        out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1588    }
1589    // #2617: `const` declarations, after the embed pass, by the same rule: a
1590    // constant is a value, in the same namespace as a free function.
1591    for &i in indices {
1592        let mut errors: Vec<CompileError> = Vec::new();
1593        for item in parsed[i].items() {
1594            let CommonsItem::Const(c) = item else {
1595                continue;
1596            };
1597            if !matches!(kind, UnitKind::Context | UnitKind::Commons) {
1598                errors.push(crate::consts::placement_error(c));
1599                continue;
1600            }
1601            let key = &c.name.name;
1602            match crate::consts::name_error(
1603                c,
1604                table.consts.get(key).map(|p| &p.name),
1605                table.embeds.get(key).map(|p| &p.name),
1606                table.assets.get(key).map(|a| &a.name),
1607                table.fns.get(key).map(|f| f.name.ident()),
1608                table.types.get(key).map(|t| &t.name),
1609            )
1610            .or_else(|| crate::consts::builtin_name_error(c))
1611            {
1612                Some(err) => errors.push(err),
1613                None => {
1614                    table.consts.insert(key.clone(), c.clone());
1615                }
1616            }
1617        }
1618        out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1619    }
1620    // #1925: a service, agent or provider shares one namespace with the
1621    // unit's functions, assets, types and events (and with each other) — they
1622    // are all one scope of the emitted TypeScript module, so a shared name
1623    // would be declared twice. After every other pass, so each table is
1624    // complete whatever the file and declaration order; reported at the
1625    // service, agent or provider, the later kinds in this order. An external
1626    // (bodiless) provider emits no declaration, so it takes no name.
1627    let mut providers_seen: HashMap<&str, Span> = HashMap::new();
1628    for &i in indices {
1629        let mut errors: Vec<CompileError> = Vec::new();
1630        for item in parsed[i].items() {
1631            // Only the declaration registered: a duplicate has already
1632            // reported `duplicate_service` / `duplicate_agent` /
1633            // `duplicate_provider`.
1634            let (what, name) = match item {
1635                CommonsItem::Service(s)
1636                    if table.services.get(&s.name.name).map(|p| p.name.span)
1637                        == Some(s.name.span) =>
1638                {
1639                    (ValueKind::Service, &s.name)
1640                }
1641                CommonsItem::Agent(a)
1642                    if table.agents.get(&a.name.name).map(|p| p.name.span) == Some(a.name.span) =>
1643                {
1644                    (ValueKind::Agent, &a.name)
1645                }
1646                CommonsItem::Provider(p)
1647                    if !p.external
1648                        && table.providers.get(&p.capability.name).map(|q| q.span)
1649                            == Some(p.span) =>
1650                {
1651                    (ValueKind::Provider, &p.provider_name)
1652                }
1653                _ => continue,
1654            };
1655            // Provider against provider only. A provider meets a service or
1656            // agent through their tables whichever comes first, so the pair
1657            // is reported once, at the provider.
1658            let earlier_provider = (what == ValueKind::Provider)
1659                .then(|| providers_seen.get(name.name.as_str()).copied())
1660                .flatten();
1661            if let Some(err) = value_namespace_error(&table, what, name, earlier_provider) {
1662                errors.push(err);
1663            }
1664            if what == ValueKind::Provider {
1665                providers_seen.entry(&name.name).or_insert(name.span);
1666            }
1667        }
1668        out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1669    }
1670    // message-bundles slice 1 (#859): a commons declaring at least one
1671    // `messages` block also gets a synthetic `render(tag: LocaleTag, msg:
1672    // Message) -> String` in its own local function table — not just emitted
1673    // TS. Without this, a Bynk-source `render(...)` call has no local
1674    // declaration to resolve to and silently falls through to `bynk.locale`'s
1675    // *imported* `render` (same signature, wrong — bundle-free — behaviour):
1676    // resolution would "type-check" while quietly calling the wrong function.
1677    // Registering it here, in the same local `table.fns` a real `CommonsItem::Fn`
1678    // would populate, makes ordinary lexical precedence (local beats
1679    // `uses`-imported, `compose_unit_symbols`) and call-site type-checking
1680    // (`fns.get(name)`, never touching `.body`) work with no changes anywhere
1681    // else. The body is a placeholder — nothing ever type-checks it, since
1682    // body-checking walks `commons.items` (real AST items) directly, and this
1683    // entry is never added there.
1684    if kind == UnitKind::Commons
1685        && let Some(m) = indices.iter().find_map(|&i| {
1686            parsed[i].items().iter().find_map(|item| match item {
1687                CommonsItem::Messages(m) => Some(m),
1688                _ => None,
1689            })
1690        })
1691    {
1692        if let Some(prev) = table.fns.get("render") {
1693            out.push((
1694                parsed[indices[0]].identity_path(),
1695                CompileError::new(
1696                    "bynk.resolve.duplicate_fn",
1697                    m.span,
1698                    "function `render` is already declared",
1699                )
1700                .with_label(prev.name.ident().span, "previously declared here")
1701                .with_note(
1702                    "a `messages` block in this commons implicitly declares its own \
1703                     `render(tag, msg) -> String` — name it something else",
1704                ),
1705            ));
1706        } else {
1707            table
1708                .fns
1709                .insert("render".to_string(), Arc::new(synthetic_render_fn()));
1710        }
1711    }
1712    table
1713}
1714
1715/// #1925: what `name` is in `table`'s own value namespace — its kind, as a
1716/// diagnostic names it, and its declaration's name span — or `None` when the
1717/// unit declares no value of that name. The predicate both compositions use
1718/// to let a local declaration of any kind shadow a `uses`-imported function or
1719/// asset (`project_model::compose_unit_symbols`,
1720/// `assets::compose_unit_assets`), as the emitted module does.
1721pub fn local_value_kind(table: &UnitTable, name: &str) -> Option<(&'static str, Span)> {
1722    if let Some(f) = table.fns.get(name) {
1723        Some(("function", f.name.ident().span))
1724    } else if let Some(a) = table.assets.get(name) {
1725        Some(("asset", a.name.span))
1726    } else if let Some(e) = table.embeds.get(name) {
1727        Some(("embed", e.name.span))
1728    } else if let Some(c) = table.consts.get(name) {
1729        Some(("constant", c.name.span))
1730    } else if let Some(e) = table.events.get(name) {
1731        Some(("event", e.name.span))
1732    } else if let Some(t) = table.types.get(name) {
1733        Some(("type", t.name.span))
1734    } else if let Some(s) = table.services.get(name) {
1735        Some(("service", s.name.span))
1736    } else if let Some(a) = table.agents.get(name) {
1737        Some(("agent", a.name.span))
1738    } else {
1739        table
1740            .providers
1741            .values()
1742            .find(|p| !p.external && p.provider_name.name == name)
1743            .map(|p| ("provider", p.provider_name.span))
1744    }
1745}
1746
1747/// #1925: the kinds [`value_namespace_error`] checks, in the order the
1748/// conflict pass meets them.
1749#[derive(Clone, Copy, PartialEq, Eq)]
1750enum ValueKind {
1751    Service,
1752    Agent,
1753    Provider,
1754}
1755
1756/// #1925: `bynk.resolve.name_conflict` for a service, agent or provider
1757/// (`what`) whose `name` the unit also gives a function, an asset, a type or
1758/// event, or a kind `what` follows in the pass: an agent conflicts with a
1759/// service, a provider with a service, an agent or `earlier_provider`. `None`
1760/// when the name is free.
1761fn value_namespace_error(
1762    table: &UnitTable,
1763    what: ValueKind,
1764    name: &Ident,
1765    earlier_provider: Option<Span>,
1766) -> Option<CompileError> {
1767    let key = &name.name;
1768    let services = || table.services.get(key).map(|s| s.name.span);
1769    let agents = || table.agents.get(key).map(|a| a.name.span);
1770    let (other, prev) = if let Some(f) = table.fns.get(key) {
1771        ("function", f.name.ident().span)
1772    } else if let Some(a) = table.assets.get(key) {
1773        ("asset", a.name.span)
1774    } else if let Some(e) = table.embeds.get(key) {
1775        ("embed", e.name.span)
1776    } else if let Some(c) = table.consts.get(key) {
1777        ("constant", c.name.span)
1778    } else if let Some(e) = table.events.get(key) {
1779        ("event", e.name.span)
1780    } else if let Some(t) = table.types.get(key) {
1781        ("type", t.name.span)
1782    } else if let Some(span) = (what != ValueKind::Service).then(services).flatten() {
1783        ("service", span)
1784    } else if let Some(span) = (what == ValueKind::Provider).then(agents).flatten() {
1785        ("agent", span)
1786    } else if let Some(span) = earlier_provider {
1787        ("provider", span)
1788    } else {
1789        return None;
1790    };
1791    let what = match what {
1792        ValueKind::Service => "service",
1793        ValueKind::Agent => "agent",
1794        ValueKind::Provider => "provider",
1795    };
1796    let other_article = if matches!(other, "asset" | "embed" | "event" | "agent") {
1797        "an"
1798    } else {
1799        "a"
1800    };
1801    Some(
1802        CompileError::new(
1803            "bynk.resolve.name_conflict",
1804            name.span,
1805            format!("{what} `{key}` conflicts with {other_article} {other} of the same name"),
1806        )
1807        .with_label(prev, format!("{other} declared here"))
1808        .with_note(
1809            "a unit's services, agents, providers, functions, assets, embeds, constants, types and events share one namespace",
1810        ),
1811    )
1812}
1813
1814/// The synthetic `FnDecl` [`build_unit_table`] registers for a messages-bearing
1815/// commons. Its body is never checked (see the call site's comment) — it
1816/// exists only so `Param`/`TypeRef`/`FnDecl` construction has somewhere to put
1817/// a syntactically valid placeholder.
1818fn synthetic_render_fn() -> FnDecl {
1819    let span = Span::default();
1820    FnDecl {
1821        type_params: Vec::new(),
1822        name: FnName::Free(Ident {
1823            name: "render".to_string(),
1824            span,
1825        }),
1826        params: vec![
1827            Param {
1828                name: Ident {
1829                    name: "tag".to_string(),
1830                    span,
1831                },
1832                type_ref: TypeRef::Named(Ident {
1833                    name: "LocaleTag".to_string(),
1834                    span,
1835                }),
1836                span,
1837            },
1838            Param {
1839                name: Ident {
1840                    name: "msg".to_string(),
1841                    span,
1842                },
1843                type_ref: TypeRef::Named(Ident {
1844                    name: "Message".to_string(),
1845                    span,
1846                }),
1847                span,
1848            },
1849        ],
1850        return_type: TypeRef::Base(BaseType::String, span),
1851        given: Vec::new(),
1852        where_bounds: Vec::new(),
1853        requires: Vec::new(),
1854        ensures: Vec::new(),
1855        body: Block {
1856            statements: Vec::new(),
1857            tail: Box::new(Expr {
1858                id: ExprId::SYNTHETIC,
1859                kind: ExprKind::StrLit(String::new()),
1860                span,
1861            }),
1862            span,
1863            tail_leading_comments: Vec::new(),
1864            implicit_tail: false,
1865        },
1866        has_self: false,
1867        documentation: None,
1868        span,
1869        trivia: Trivia::default(),
1870        private: None,
1871    }
1872}
1873
1874/// #1824: whether `f` is the synthetic `render` [`build_unit_table`] registers
1875/// for a messages-bearing commons. It stands in for `bynk.locale`'s `render`,
1876/// and its `LocaleTag`/`Message` mean `bynk.locale`'s, whatever the commons
1877/// itself declares under those names: the emitted bundle names the stdlib
1878/// types (#1697).
1879pub fn is_synthetic_render(f: &FnDecl) -> bool {
1880    matches!(&f.name, FnName::Free(n) if n.name == "render")
1881        && f.span == Span::default()
1882        && f.body.tail.id == ExprId::SYNTHETIC
1883}
1884
1885/// For each name declared in the unit (type, fn, method, agent), record which
1886/// source file declared it. Used by the emitter to render relative imports.
1887#[derive(Clone)]
1888pub struct FileDeclIndex {
1889    pub types: HashMap<String, PathBuf>,
1890    pub fns: HashMap<String, PathBuf>,
1891    pub methods: HashMap<String, HashMap<String, PathBuf>>,
1892    /// #1820: an agent's declaring file. A sibling file that constructs it
1893    /// calls its factory, `__make<Agent>`, which that file exports.
1894    pub agents: HashMap<String, PathBuf>,
1895    /// #1820: a capability's declaring file. A sibling file names the
1896    /// capability's interface in a handler's `deps` and a provider's
1897    /// `implements`, so it imports the type from there.
1898    pub capabilities: HashMap<String, PathBuf>,
1899}
1900
1901/// **Tree-relative, deliberately.** This is an *emit* structure, not an index:
1902/// `record_name_ref` compares these paths against `ctx.source_path`
1903/// (`emitter.rs`), which is the file's `include`-root-relative path. Keying it
1904/// by `identity_path` (ADR 0198) makes `path != &ctx.source_path` always true
1905/// for a split project, so a name declared in the *same* file is emitted as a
1906/// sibling import of itself — the module then cannot load, and a workers
1907/// runtime test hangs rather than fails. See ADR 0201 (E).
1908pub fn build_file_decl_index(indices: &[usize], parsed: &[ParsedFile]) -> FileDeclIndex {
1909    let mut idx = FileDeclIndex {
1910        types: HashMap::new(),
1911        fns: HashMap::new(),
1912        methods: HashMap::new(),
1913        agents: HashMap::new(),
1914        capabilities: HashMap::new(),
1915    };
1916    for &i in indices {
1917        let path = parsed[i].source_path();
1918        for item in parsed[i].items() {
1919            match item {
1920                CommonsItem::Type(t) => {
1921                    idx.types
1922                        .entry(t.name.name.clone())
1923                        .or_insert_with(|| path.clone());
1924                }
1925                // Events track, slice 0 (spine #936): an `event` name shares
1926                // the `types` file index — it registers into the same
1927                // `types` symbol table as an ordinary `type` everywhere else
1928                // in this module.
1929                CommonsItem::Event(e) => {
1930                    idx.types
1931                        .entry(e.name.name.clone())
1932                        .or_insert_with(|| path.clone());
1933                }
1934                CommonsItem::Fn(f) => match &f.name {
1935                    FnName::Free(id) => {
1936                        idx.fns
1937                            .entry(id.name.clone())
1938                            .or_insert_with(|| path.clone());
1939                    }
1940                    FnName::Method {
1941                        type_name,
1942                        method_name,
1943                    } => {
1944                        idx.methods
1945                            .entry(type_name.name.clone())
1946                            .or_default()
1947                            .entry(method_name.name.clone())
1948                            .or_insert_with(|| path.clone());
1949                    }
1950                },
1951                CommonsItem::Agent(a) => {
1952                    idx.agents
1953                        .entry(a.name.name.clone())
1954                        .or_insert_with(|| path.clone());
1955                }
1956                CommonsItem::Capability(c) => {
1957                    idx.capabilities
1958                        .entry(c.name.name.clone())
1959                        .or_insert_with(|| path.clone());
1960                }
1961                CommonsItem::Provider(_)
1962                | CommonsItem::Service(_)
1963                | CommonsItem::Actor(_)
1964                // `messages` bundles aren't cross-file-imported by name in
1965                // slice 1 (no multi-file bundle merge yet).
1966                | CommonsItem::Messages(_) => {}
1967                // #1883, slice 1b: an asset is an exported constant of its
1968                // file, in the function namespace, so a sibling file or a
1969                // `uses`-ing unit imports it the way it imports a function.
1970                CommonsItem::Asset(a) => {
1971                    idx.fns
1972                        .entry(a.name.name.clone())
1973                        .or_insert_with(|| path.clone());
1974                }
1975                // #2387, slice 2: an embed is an exported constant of its
1976                // file, in the function namespace, imported like an asset.
1977                CommonsItem::Embed(e) => {
1978                    idx.fns
1979                        .entry(e.name.name.clone())
1980                        .or_insert_with(|| path.clone());
1981                }
1982                // #2617: a constant is an exported function of its file, in the
1983                // function namespace, imported like an embed.
1984                CommonsItem::Const(c) => {
1985                    idx.fns
1986                        .entry(c.name.name.clone())
1987                        .or_insert_with(|| path.clone());
1988                }
1989            }
1990        }
1991    }
1992    idx
1993}
1994
1995/// #696: returns the `parsed` index of the owning file alongside the `uses`
1996/// clause span, so the caller can attribute the diagnostic to that file.
1997pub fn uses_span_of(
1998    parsed: &[ParsedFile],
1999    indices: &[usize],
2000    target: &str,
2001) -> Option<(usize, Span)> {
2002    for &i in indices {
2003        for u in parsed[i].uses() {
2004            if u.target.joined() == target {
2005                return Some((i, u.span));
2006            }
2007        }
2008    }
2009    None
2010}
2011
2012/// Build the [`resolver::CrossContextInfo`] for a given consuming context.
2013/// Used by both the resolver/checker (per-file processing) and the emitter
2014/// (composition root + boundary casts).
2015pub fn build_cross_context_info(
2016    name: &str,
2017    unit_consumes: &HashMap<String, Vec<String>>,
2018    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
2019    unit_uses: &HashMap<String, Vec<String>>,
2020    unit_tables: &HashMap<String, UnitTable>,
2021) -> resolver::CrossContextInfo {
2022    let consumed_contexts: Vec<String> = unit_consumes.get(name).cloned().unwrap_or_default();
2023    let aliases: HashMap<String, String> =
2024        unit_consumes_aliases.get(name).cloned().unwrap_or_default();
2025    let mut consumed_services: HashMap<String, HashMap<String, resolver::CrossContextService>> =
2026        HashMap::new();
2027    let mut consumed_types: HashMap<String, HashMap<String, Arc<TypeDecl>>> = HashMap::new();
2028    let mut consumed_capabilities: HashMap<
2029        String,
2030        HashMap<String, resolver::CrossContextCapability>,
2031    > = HashMap::new();
2032    // Events track, slice 0 (spine #936): each consumed context's own event
2033    // names, so a subscriber's `from Events(E)` can be checked against a
2034    // foreign owner too — mirrors `discover_event_subscribers` below, which
2035    // already resolves ownership this same way for wiring.
2036    let mut consumed_event_names: HashMap<String, std::collections::HashSet<String>> =
2037        HashMap::new();
2038    let mut consumed_type_owners: HashMap<String, HashMap<String, String>> = HashMap::new();
2039    let mut consumed_type_aliases: HashMap<String, HashMap<String, String>> = HashMap::new();
2040    let mut callee_type_aliases: HashMap<String, HashMap<String, String>> = HashMap::new();
2041    let mut callee_alias_keys_out: HashMap<String, HashMap<String, String>> = HashMap::new();
2042    for t in &consumed_contexts {
2043        if let Some(own) = unit_tables
2044            .get(t)
2045            .map(|table| &table.consumed_type_aliases)
2046            .filter(|own| !own.is_empty())
2047        {
2048            callee_type_aliases.insert(
2049                t.clone(),
2050                own.iter()
2051                    .map(|(alias, a)| (alias.clone(), a.original.clone()))
2052                    .collect(),
2053            );
2054        }
2055        let (mut other_types_combined, mut owners) =
2056            contract_types_for(t, unit_tables, unit_uses, unit_consumes);
2057        // #2901: the key `t`'s view holds the declaration behind each type `t`
2058        // renamed from a context of its own, where a caller names it (see below).
2059        let callee_keys = callee_alias_keys(t, unit_tables, &other_types_combined);
2060        // #2887: the exports of `t` this unit renames (`consumes t { T as U }`):
2061        // the view files them under the alias, and every signature it lifts
2062        // below names them by it, so a call's `T` is the type `U` here and not
2063        // a same-named local one.
2064        let renames: HashMap<String, String> = unit_tables
2065            .get(name)
2066            .map(|table| {
2067                table
2068                    .consumed_type_aliases
2069                    .iter()
2070                    .filter(|(_, a)| a.target == *t)
2071                    .map(|(alias, a)| (a.original.clone(), alias.clone()))
2072                    .collect()
2073            })
2074            .unwrap_or_default();
2075        if !renames.is_empty() {
2076            other_types_combined = other_types_combined
2077                .into_iter()
2078                .map(|(key, decl)| {
2079                    let key = renames.get(&key).cloned().unwrap_or(key);
2080                    let decl = rename_consumed_decl(&decl, &key, &renames);
2081                    (key, decl)
2082                })
2083                .collect();
2084        }
2085        if !renames.is_empty() {
2086            consumed_type_aliases.insert(
2087                t.clone(),
2088                renames
2089                    .iter()
2090                    .map(|(o, a)| (a.clone(), o.clone()))
2091                    .collect(),
2092            );
2093        }
2094        // #2901: a caller of `t` reads a type `t` renamed (`consumes lib { Code
2095        // as LibCode }`) as the declaration, not as `t`'s alias. The signatures
2096        // lifted below are rewritten to `key`: the declared name, or the
2097        // qualified key `t`'s view files it under when `t` has a type of that
2098        // name of its own (#2087), never the bare name then, which would be
2099        // `t`'s. The alias stays a key of the view, which the contract hash
2100        // reads (it is `t`'s own spelling).
2101        for (alias, (key, decl)) in &callee_keys {
2102            if let Some(owner) = owners.get(alias).cloned() {
2103                owners.entry(key.clone()).or_insert(owner);
2104            }
2105            other_types_combined
2106                .entry(key.clone())
2107                .or_insert_with(|| decl.clone());
2108        }
2109        let key_of: HashMap<String, String> = callee_keys
2110            .iter()
2111            .map(|(alias, (key, _))| (alias.clone(), key.clone()))
2112            .collect();
2113        if !key_of.is_empty() {
2114            callee_alias_keys_out.insert(
2115                t.clone(),
2116                key_of
2117                    .iter()
2118                    .map(|(alias, key)| (key.clone(), alias.clone()))
2119                    .collect(),
2120            );
2121        }
2122        consumed_types.insert(t.clone(), other_types_combined);
2123        if !owners.is_empty() {
2124            consumed_type_owners.insert(t.clone(), owners);
2125        }
2126        let Some(other_table) = unit_tables.get(t) else {
2127            continue;
2128        };
2129        consumed_event_names.insert(t.clone(), other_table.events.keys().cloned().collect());
2130        let mut svcs: HashMap<String, resolver::CrossContextService> = HashMap::new();
2131        for (sname, sdecl) in &other_table.services {
2132            if let Some(mut svc) = resolver::cross_context_service_for(sname, sdecl) {
2133                for (_, tr) in svc.params.iter_mut() {
2134                    rename_type_ref(tr, &renames);
2135                }
2136                rename_type_ref(&mut svc.return_type, &renames);
2137                for (_, tr) in svc.params.iter_mut() {
2138                    rename_type_ref(tr, &key_of);
2139                }
2140                rename_type_ref(&mut svc.return_type, &key_of);
2141                svc.foreign_callers = sdecl
2142                    .handlers
2143                    .iter()
2144                    .find_map(|h| crate::actors::call_admission_for(h, &other_table.actors))
2145                    .map(|a| a.foreign.into_iter().map(|f| f.actor).collect())
2146                    .unwrap_or_default();
2147                svcs.insert(sname.clone(), svc);
2148            }
2149        }
2150        consumed_services.insert(t.clone(), svcs);
2151
2152        // v0.15: gather the consumed context's exported capabilities, each
2153        // paired with the provider that implements it.
2154        let mut caps: HashMap<String, resolver::CrossContextCapability> = HashMap::new();
2155        for cap_name in &other_table.exported_capabilities {
2156            let Some(decl) = other_table.capabilities.get(cap_name) else {
2157                continue;
2158            };
2159            let Some(provider) = other_table.providers.get(cap_name) else {
2160                continue;
2161            };
2162            let ops = decl
2163                .ops
2164                .iter()
2165                .map(|op| resolver::CrossContextCapabilityOp {
2166                    name: op.name.name.clone(),
2167                    type_params: op.type_params.iter().map(|p| p.name.name.clone()).collect(),
2168                    params: op
2169                        .params
2170                        .iter()
2171                        .map(|p| {
2172                            let mut tr = p.type_ref.clone();
2173                            rename_type_ref(&mut tr, &renames);
2174                            rename_type_ref(&mut tr, &key_of);
2175                            (p.name.name.clone(), tr)
2176                        })
2177                        .collect(),
2178                    return_type: {
2179                        let mut tr = op.return_type.clone();
2180                        rename_type_ref(&mut tr, &renames);
2181                        rename_type_ref(&mut tr, &key_of);
2182                        tr
2183                    },
2184                    codable_params: crate::checker::codable::codable_op_params(op),
2185                    reply_policy: crate::checker::codable::op_reply_policy(op),
2186                })
2187                .collect();
2188            caps.insert(
2189                cap_name.clone(),
2190                resolver::CrossContextCapability {
2191                    name: cap_name.clone(),
2192                    ops,
2193                    provider_name: provider.provider_name.name.clone(),
2194                    provider_given: provider
2195                        .given
2196                        .iter()
2197                        .filter(|c| !c.is_cross_context())
2198                        .map(|c| c.key().to_string())
2199                        .collect(),
2200                    span: decl.span,
2201                },
2202            );
2203        }
2204        consumed_capabilities.insert(t.clone(), caps);
2205    }
2206    resolver::CrossContextInfo {
2207        self_context: Some(name.to_string()),
2208        consumed_contexts,
2209        aliases,
2210        consumed_services,
2211        consumed_types,
2212        // Set by the emitter (#1932).
2213        consumed_type_renames: HashMap::new(),
2214        consumed_capabilities,
2215        // Set by the caller from the unit's `consumes U { … }` clauses.
2216        flattened_caps: unit_tables
2217            .get(name)
2218            .map(|t| t.flattened_caps.clone())
2219            .unwrap_or_default(),
2220        consumed_event_names,
2221        consumed_type_owners,
2222        consumed_type_aliases,
2223        callee_type_aliases,
2224        callee_alias_keys: callee_alias_keys_out,
2225        cookie_records: unit_tables
2226            .get(name)
2227            .map(crate::context_checks::cookie_records_of)
2228            .unwrap_or_default(),
2229        signed_cookie_names: unit_tables
2230            .get(name)
2231            .map(|t| {
2232                t.actors
2233                    .values()
2234                    .filter_map(|a| crate::actors::signed_cookie_seam_of(a, None))
2235                    .map(|seam| seam.cookie)
2236                    .collect()
2237            })
2238            .unwrap_or_default(),
2239    }
2240}
2241
2242/// #2901: for each type `t` renames from a context of its own, the key a
2243/// caller of `t` names the declaration by, and the declaration filed under it.
2244/// `view` is [`contract_types_for`] of `t`, which holds the declaration under
2245/// the alias.
2246///
2247/// The key is the declared name when `view` holds that declaration under it.
2248/// When `t` has a different type of that name (a `uses` commons type), the
2249/// bare name is `t`'s own and is not used: the key is the declaration's own
2250/// context and name, as the view files a clashing borrowed type (#2087).
2251fn callee_alias_keys(
2252    t: &str,
2253    unit_tables: &HashMap<String, UnitTable>,
2254    view: &HashMap<String, Arc<TypeDecl>>,
2255) -> HashMap<String, (String, Arc<TypeDecl>)> {
2256    let Some(table) = unit_tables.get(t) else {
2257        return HashMap::new();
2258    };
2259    let mut out = HashMap::new();
2260    for (alias, a) in &table.consumed_type_aliases {
2261        let Some(decl) = view.get(alias) else {
2262            continue;
2263        };
2264        let same = |d: &Arc<TypeDecl>| Arc::ptr_eq(d, decl) || d.span == decl.span;
2265        let (key, decl) = if view.get(&a.original).is_some_and(same) {
2266            (a.original.clone(), decl.clone())
2267        } else {
2268            let key = format!("{}__{}", a.target.replace('.', "_"), a.original);
2269            let mut renamed = (**decl).clone();
2270            renamed.name.name = key.clone();
2271            (key, Arc::new(renamed))
2272        };
2273        out.insert(alias.clone(), (key, decl));
2274    }
2275    out
2276}
2277
2278/// Events track, slice 0 (spine #936): project-wide "who subscribes to what"
2279/// — for every `service ... from Events(E) { on event ... }` anywhere in the
2280/// project, resolve `E` to its *owning* context (the one whose `events` table
2281/// actually declares it — bare-name resolution, since `TypeRef` has no dotted
2282/// form) and group subscribers under `(owning_context, event_type_name)`. No
2283/// prior art to reuse: cross-context wiring elsewhere is driven by an
2284/// explicit author-written `consumes` clause, resolved eagerly in
2285/// `phase_resolve_consumes`; this is the first wiring driven by an *implicit*
2286/// relationship (a bare event-type name shared between a publisher's `event`
2287/// declaration and a subscriber's `from Events(E)` header) — the same
2288/// ownership resolution [`build_cross_context_info`]'s own `consumed_event_names`
2289/// performs above, for the same reason (#936, events track slice 0).
2290pub fn discover_event_subscribers(
2291    unit_tables: &HashMap<String, UnitTable>,
2292    unit_consumes: &HashMap<String, Vec<String>>,
2293) -> BTreeMap<(String, String), Vec<(String, String)>> {
2294    let mut out: BTreeMap<(String, String), Vec<(String, String)>> = BTreeMap::new();
2295    for (ctx_name, table) in unit_tables {
2296        for (svc_name, svc) in &table.services {
2297            let ServiceProtocol::Events { event_type, .. } = &svc.protocol else {
2298                continue;
2299            };
2300            let TypeRef::Named(id) = event_type else {
2301                continue;
2302            };
2303            let name = &id.name;
2304            let owner = if table.events.contains_key(name) {
2305                Some(ctx_name.clone())
2306            } else {
2307                unit_consumes.get(ctx_name).and_then(|consumed| {
2308                    consumed
2309                        .iter()
2310                        .find(|c| {
2311                            unit_tables
2312                                .get(c.as_str())
2313                                .is_some_and(|t| t.events.contains_key(name))
2314                        })
2315                        .cloned()
2316                })
2317            };
2318            if let Some(owner) = owner {
2319                out.entry((owner, name.clone()))
2320                    .or_default()
2321                    .push((ctx_name.clone(), svc_name.clone()));
2322            }
2323        }
2324    }
2325    // `unit_tables`/`table.services` are `HashMap`s, so the pushes above race
2326    // across builds — a multi-subscriber event's dispatch order (and so the
2327    // emitted `__eventsDispatch` closure's `await sub1; await sub2;`
2328    // sequence) would otherwise vary build to build with no source change.
2329    for subs in out.values_mut() {
2330        subs.sort();
2331    }
2332    out
2333}
2334
2335/// P6.x (#1137): one context's own cron expressions (`on cron "expr"`) and
2336/// queue names (`from queue("name")`), sorted and deduped — the two `wrangler.toml`
2337/// binding lists a context's own compose entry needs. `v0.44`: one queue binding
2338/// per service, on the `from queue(...)` header.
2339pub fn cron_and_queue_triggers(table: &UnitTable) -> (Vec<String>, Vec<String>) {
2340    let mut crons: Vec<String> = Vec::new();
2341    let mut queues: Vec<String> = Vec::new();
2342    for service in table.services.values() {
2343        for handler in &service.handlers {
2344            if let HandlerKind::Cron { expr } = &handler.kind {
2345                crons.push(expr.clone());
2346            }
2347        }
2348        if let ServiceProtocol::Queue { name } = &service.protocol {
2349            queues.push(name.clone());
2350        }
2351    }
2352    crons.sort();
2353    crons.dedup();
2354    queues.sort();
2355    queues.dedup();
2356    (crons, queues)
2357}
2358
2359/// v0.15: validate one `given` capability reference. A bare reference must name
2360/// a capability declared in this context; a cross-context reference (`given
2361/// B.Cap`) must name a capability the consumed context exports. Returns the
2362/// local [`CapabilityInfo`] to add to the in-scope map for bare references;
2363/// cross-context references return `None` (their calls are type-checked via
2364/// `consumed_capabilities` at the call site) but are still validated here.
2365/// v0.25: record a clause-position capability reference (`provides Cap`,
2366/// bare `given Cap`), qualifying a flattened bare name to its providing
2367/// unit. The span is the name segment only.
2368pub fn record_capability_clause_ref(
2369    name: &Ident,
2370    cross_context: &resolver::CrossContextInfo,
2371    refs: &mut RefSink,
2372) {
2373    record_capability_clause_ref_inner(name, cross_context, refs, false);
2374}
2375
2376/// v0.35 (ADR 0068): the `Cap` of a `provides Cap = Provider` clause — a
2377/// capability reference *and* an implementation edge (the ambient owner is the
2378/// provider). Flagged so assembly can tell it apart from the provider's own
2379/// `given` deps, which are capability refs owned by the same provider.
2380pub fn record_provides_clause_ref(
2381    name: &Ident,
2382    cross_context: &resolver::CrossContextInfo,
2383    refs: &mut RefSink,
2384) {
2385    record_capability_clause_ref_inner(name, cross_context, refs, true);
2386}
2387
2388fn record_capability_clause_ref_inner(
2389    name: &Ident,
2390    cross_context: &resolver::CrossContextInfo,
2391    refs: &mut RefSink,
2392    provides: bool,
2393) {
2394    let unit = cross_context.flattened_caps.get(&name.name);
2395    if provides {
2396        refs.record_provides(name.span, &name.name, unit.map(String::as_str));
2397    } else if let Some(unit) = unit {
2398        refs.record_in_unit(name.span, SymbolKind::Capability, &name.name, unit);
2399    } else {
2400        refs.record(name.span, SymbolKind::Capability, &name.name);
2401    }
2402}
2403
2404pub fn resolve_given_cap_ref(
2405    cap_ref: &CapRef,
2406    capability_info_map: &HashMap<String, CapabilityInfo>,
2407    cross_context: &resolver::CrossContextInfo,
2408    errors: &mut Vec<CompileError>,
2409    refs: &mut RefSink,
2410) -> Option<CapabilityInfo> {
2411    let Some(prefix) = cap_ref.prefix() else {
2412        // Local capability.
2413        match capability_info_map.get(cap_ref.key()) {
2414            Some(info) => {
2415                record_capability_clause_ref(&cap_ref.name, cross_context, refs);
2416                // Interop I5 (#1972): a kind every use of which needs an
2417                // option (a `Service` names its Worker) is reached only
2418                // through a named instance. Still resolved, so the handler's
2419                // calls are not refused a second time as undeclared.
2420                if let Some(unit) = cross_context.flattened_caps.get(cap_ref.key())
2421                    && let Some(kind) = crate::firstparty::instantiable(unit, cap_ref.key())
2422                    && !kind.bare
2423                {
2424                    let example = crate::project_model::instance_example(kind);
2425                    errors.push(
2426                        CompileError::new(
2427                            "bynk.capability.instance_only",
2428                            cap_ref.span,
2429                            format!(
2430                                "`{unit}.{}` is used only through a named instance",
2431                                cap_ref.key()
2432                            ),
2433                        )
2434                        .with_note(format!("declare one and use it instead: `{example}`")),
2435                    );
2436                }
2437                return Some(info.clone());
2438            }
2439            None => {
2440                errors.push(CompileError::new(
2441                    "bynk.given.unknown_capability",
2442                    cap_ref.span,
2443                    format!(
2444                        "capability `{}` is not declared in this context",
2445                        cap_ref.key()
2446                    ),
2447                ));
2448                return None;
2449            }
2450        }
2451    };
2452    // Cross-context capability (`given B.Cap` / `given Alias.Cap`).
2453    let Some(ctx_name) = cross_context.resolve_prefix(&prefix) else {
2454        errors.push(
2455            CompileError::new(
2456                "bynk.resolve.unconsumed_context",
2457                cap_ref.span,
2458                format!(
2459                    "`given {}.{}` refers to a context that this context does not `consumes`",
2460                    prefix,
2461                    cap_ref.key()
2462                ),
2463            )
2464            .with_note(
2465                "add a `consumes` clause for the providing context (optionally with an alias) at the top of this context",
2466            ),
2467        );
2468        return None;
2469    };
2470    let exports_it = cross_context
2471        .consumed_capabilities
2472        .get(&ctx_name)
2473        .is_some_and(|m| m.contains_key(cap_ref.key()));
2474    if exports_it {
2475        // v0.25: dotted `given B.Cap` — the name segment, in the consumed
2476        // unit's namespace.
2477        refs.record_in_unit(
2478            cap_ref.name.span,
2479            SymbolKind::Capability,
2480            cap_ref.key(),
2481            &ctx_name,
2482        );
2483    }
2484    if !exports_it {
2485        errors.push(
2486            CompileError::new(
2487                "bynk.given.cross_context_unknown_capability",
2488                cap_ref.span,
2489                format!(
2490                    "context `{}` does not export a capability named `{}`",
2491                    ctx_name,
2492                    cap_ref.key()
2493                ),
2494            )
2495            .with_note(
2496                "the providing context must list the capability in an `exports capability { … }` clause",
2497            ),
2498        );
2499    }
2500    None
2501}
2502
2503/// Build the combined type table for `unit`: its own types merged with the
2504/// types of every commons it `uses`. Used by cross-context resolution so we
2505/// can resolve a consumed context's service signatures against that context's
2506/// own view of types (v0.6 §4.5).
2507/// v0.177 (#643): the callee's own type namespace — its local declarations plus
2508/// the commons types it `uses`.
2509///
2510/// Shared deliberately. The **caller** reaches this table through
2511/// `consumed_types[callee]` and the **callee** builds it for itself; both must
2512/// canonicalise the callee's contract from the *same* table or their hashes
2513/// diverge and every call 409s. Routing both through one function makes that
2514/// agreement structural rather than a thing to keep in step by hand.
2515/// #2073: the type table a context's service signatures resolve in, as a
2516/// caller and the context itself both see it: [`combined_types_for`] (its own
2517/// types and its `uses` commons'), plus the types of the contexts it consumes,
2518/// which a signature may name (`on call(o: Order)` in `shop.ledger`, `Order`
2519/// from `shop.order`). Its own types win a name clash. The second map names
2520/// the declaring context of each type that came from a consumed context.
2521///
2522/// A borrowed type's body resolves in its declaring context's view, not this
2523/// one's: `shop.order`'s `Order { region: Region }` names `shop.order`'s
2524/// `Region` even when `shop.ledger` declares a `Region` of its own. Where the
2525/// two would differ, the reference is renamed to a key qualified by the
2526/// declaring context (`shop_order__Region`) under which that context's
2527/// declaration is added, so canonicalising (the contract hash) and walking
2528/// the table both see the right shape. A name two consumed contexts both
2529/// declare is added bare for neither; a signature cannot name it bare
2530/// anyway (an exported clash is `bynk.consumes.name_conflict`), and a body
2531/// that reaches it does so through its own context's qualified key.
2532///
2533/// Both sides of a cross-context call build the contract hash from this one
2534/// table, so they agree by construction.
2535pub fn contract_types_for(
2536    unit: &str,
2537    unit_tables: &HashMap<String, UnitTable>,
2538    unit_uses: &HashMap<String, Vec<String>>,
2539    unit_consumes: &HashMap<String, Vec<String>>,
2540) -> (HashMap<String, Arc<TypeDecl>>, HashMap<String, String>) {
2541    let mut walk = ContractWalk::default();
2542    let (table, owners, _) =
2543        contract_types_inner(unit, unit_tables, unit_uses, unit_consumes, &mut walk);
2544    (table, owners)
2545}
2546
2547/// #2087: the name a user reads for a type `contract_types_for` may have
2548/// filed under a qualified key. A key is the declaring context's namespace,
2549/// `__`, and the declaration's own name (`shop_order__Code`); the declaration
2550/// carries the key as its name too, so every path that prints a type name to a
2551/// user goes through this, and reads `Code`. Any other name is returned as is:
2552/// a key's prefix is a lowercase namespace and its last segment a capitalised
2553/// type name, which a declared type name never is.
2554pub fn display_type_name(name: &str) -> &str {
2555    match name.rsplit_once("__") {
2556        Some((prefix, last))
2557            if prefix.starts_with(|c: char| c.is_ascii_lowercase())
2558                && prefix
2559                    .chars()
2560                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
2561                && last.starts_with(|c: char| c.is_ascii_uppercase()) =>
2562        {
2563            last
2564        }
2565        _ => name,
2566    }
2567}
2568
2569/// #2087: `text` (a contract's normal form, say) with every qualified key in
2570/// it shown by its declaration's own name ([`display_type_name`]).
2571pub fn display_type_names_in(text: &str) -> String {
2572    let mut out = String::with_capacity(text.len());
2573    let mut word = String::new();
2574    let flush = |word: &mut String, out: &mut String| {
2575        out.push_str(display_type_name(word));
2576        word.clear();
2577    };
2578    for c in text.chars() {
2579        if c.is_ascii_alphanumeric() || c == '_' {
2580            word.push(c);
2581        } else {
2582            flush(&mut word, &mut out);
2583            out.push(c);
2584        }
2585    }
2586    flush(&mut word, &mut out);
2587    out
2588}
2589
2590/// A context's contract table and the declaring context of each borrowed type.
2591type ContractView = (HashMap<String, Arc<TypeDecl>>, HashMap<String, String>);
2592
2593/// #2073 review: one `contract_types_for` walk. `visiting` breaks a `consumes`
2594/// cycle; `memo` holds each context's view once it is computed, so a layered
2595/// `consumes` DAG costs one walk per context, not one per path. A view that
2596/// met a cycle depends on where the walk entered it, so it is not memoised.
2597#[derive(Default)]
2598struct ContractWalk {
2599    visiting: std::collections::HashSet<String>,
2600    memo: HashMap<String, ContractView>,
2601}
2602
2603/// The view, its owners, and whether computing it met a `consumes` cycle.
2604fn contract_types_inner(
2605    unit: &str,
2606    unit_tables: &HashMap<String, UnitTable>,
2607    unit_uses: &HashMap<String, Vec<String>>,
2608    unit_consumes: &HashMap<String, Vec<String>>,
2609    walk: &mut ContractWalk,
2610) -> (
2611    HashMap<String, Arc<TypeDecl>>,
2612    HashMap<String, String>,
2613    bool,
2614) {
2615    if let Some((table, owners)) = walk.memo.get(unit) {
2616        return (table.clone(), owners.clone(), false);
2617    }
2618    let mut out = combined_types_for(unit, unit_tables, unit_uses);
2619    let mut owners: HashMap<String, String> = HashMap::new();
2620    if !walk.visiting.insert(unit.to_string()) {
2621        // A `consumes` cycle: stop at the unit's own view.
2622        return (out, owners, true);
2623    }
2624    let mut consumed: Vec<&String> = unit_consumes
2625        .get(unit)
2626        .into_iter()
2627        .flatten()
2628        .filter(|u| {
2629            unit_tables
2630                .get(*u)
2631                .is_some_and(|t| t.kind == Some(UnitKind::Context))
2632        })
2633        .collect();
2634    consumed.sort();
2635    consumed.dedup();
2636    // Each consumed context's own view, in which its types' bodies resolve.
2637    let mut cyclic = false;
2638    let views: HashMap<String, ContractView> = consumed
2639        .iter()
2640        .map(|u| {
2641            let (table, owners, met) =
2642                contract_types_inner(u, unit_tables, unit_uses, unit_consumes, walk);
2643            cyclic |= met;
2644            ((*u).clone(), (table, owners))
2645        })
2646        .collect();
2647    // The context that declares `r` as `owner`'s view resolves it: `owner`
2648    // itself, a context `owner` consumes, or none (a commons type, whose
2649    // codecs and namespace are the commons').
2650    let declarer = |owner: &str, r: &str, target: &Arc<TypeDecl>| -> Option<String> {
2651        if unit_tables
2652            .get(owner)
2653            .and_then(|t| t.types.get(r))
2654            .is_some_and(|d| Arc::ptr_eq(d, target) || d.span == target.span)
2655        {
2656            return Some(owner.to_string());
2657        }
2658        views.get(owner).and_then(|(_, o)| o.get(r).cloned())
2659    };
2660    let mut by_name: std::collections::BTreeMap<&String, Vec<&String>> = Default::default();
2661    for u in &consumed {
2662        for n in unit_tables[*u].types.keys() {
2663            if !out.contains_key(n) {
2664                by_name.entry(n).or_default().push(u);
2665            }
2666        }
2667    }
2668    let mut queue: Vec<(String, String)> = Vec::new();
2669    for (n, us) in by_name {
2670        if let [u] = us.as_slice() {
2671            out.insert(n.clone(), unit_tables[*u].types[n].clone());
2672            owners.insert(n.clone(), (*u).clone());
2673            queue.push((n.clone(), (*u).clone()));
2674        }
2675    }
2676    // #2890: a service signature of this unit may name an export it renamed
2677    // (`consumes lib { Code as LibCode }`), and a caller of the unit reads the
2678    // service's types through this view, so the alias is a key of it as well.
2679    // The contract states the type by the alias (it is the unit's own spelling).
2680    if let Some(table) = unit_tables.get(unit) {
2681        for (alias, a) in &table.consumed_type_aliases {
2682            let Some((view, view_owners)) = views.get(&a.target) else {
2683                continue;
2684            };
2685            let Some(decl) = view.get(&a.original) else {
2686                continue;
2687            };
2688            let renames: HashMap<String, String> = table
2689                .consumed_type_aliases
2690                .iter()
2691                .filter(|(_, o)| o.target == a.target)
2692                .map(|(alias, o)| (o.original.clone(), alias.clone()))
2693                .collect();
2694            out.insert(alias.clone(), rename_consumed_decl(decl, alias, &renames));
2695            owners.insert(
2696                alias.clone(),
2697                view_owners
2698                    .get(&a.original)
2699                    .cloned()
2700                    .unwrap_or_else(|| a.target.clone()),
2701            );
2702            queue.push((alias.clone(), a.target.clone()));
2703        }
2704    }
2705    queue.sort();
2706    let same = |a: &Arc<TypeDecl>, b: &Arc<TypeDecl>| Arc::ptr_eq(a, b) || a.span == b.span;
2707    // `via`: the consumed context whose view the key came from, in which its
2708    // body's references resolve (the declarer, for `owners`, may be a context
2709    // `via` itself consumes).
2710    while let Some((key, via)) = queue.pop() {
2711        let owner = via;
2712        let Some((view, _)) = views.get(&owner) else {
2713            continue;
2714        };
2715        let decl = out[&key].clone();
2716        let mut subst: HashMap<String, String> = HashMap::new();
2717        for r in crate::project_model::type_decl_ref_names(&decl) {
2718            let Some(target) = view.get(&r) else {
2719                continue;
2720            };
2721            match out.get(&r) {
2722                Some(here) if same(here, target) => {}
2723                None => {
2724                    out.insert(r.clone(), target.clone());
2725                    if let Some(d) = declarer(&owner, &r, target) {
2726                        owners.insert(r.clone(), d);
2727                    }
2728                    queue.push((r, owner.clone()));
2729                }
2730                Some(_) => {
2731                    let d = declarer(&owner, &r, target);
2732                    let qualified = format!(
2733                        "{}__{r}",
2734                        d.as_deref().unwrap_or(owner.as_str()).replace('.', "_")
2735                    );
2736                    if !out.contains_key(&qualified) {
2737                        // #2087: the declaration takes its key as its name, so a
2738                        // type resolved through the key (`Ty::Named`'s name is
2739                        // the declaration's) looks up this declaration, not the
2740                        // unit's same-named one.
2741                        let mut renamed = (**target).clone();
2742                        renamed.name.name = qualified.clone();
2743                        out.insert(qualified.clone(), Arc::new(renamed));
2744                        if let Some(d) = d {
2745                            owners.insert(qualified.clone(), d);
2746                        }
2747                        queue.push((qualified.clone(), owner.clone()));
2748                    }
2749                    subst.insert(r, qualified);
2750                }
2751            }
2752        }
2753        if !subst.is_empty() {
2754            out.insert(key, Arc::new(rename_decl_refs(&decl, &subst)));
2755        }
2756    }
2757    walk.visiting.remove(unit);
2758    if !cyclic {
2759        walk.memo
2760            .insert(unit.to_string(), (out.clone(), owners.clone()));
2761    }
2762    (out, owners, cyclic)
2763}
2764
2765/// #2887: a consumed export's declaration as the consuming unit sees it: filed
2766/// under `key` (its alias, or its own name) with the references it makes to its
2767/// unit's other aliased exports renamed to their aliases.
2768pub fn rename_consumed_decl(
2769    decl: &Arc<TypeDecl>,
2770    key: &str,
2771    renames: &HashMap<String, String>,
2772) -> Arc<TypeDecl> {
2773    if renames.is_empty() {
2774        return decl.clone();
2775    }
2776    let mut out = rename_decl_refs(decl, renames);
2777    out.name.name = key.to_string();
2778    Arc::new(out)
2779}
2780
2781/// #2073: `decl` with every type it names renamed by `subst` (its own name
2782/// kept).
2783fn rename_decl_refs(decl: &TypeDecl, subst: &HashMap<String, String>) -> TypeDecl {
2784    let mut out = decl.clone();
2785    match &mut out.body {
2786        TypeBody::Record(r) => {
2787            for f in &mut r.fields {
2788                rename_type_ref(&mut f.type_ref, subst);
2789            }
2790        }
2791        TypeBody::Sum(sum) => {
2792            for v in &mut sum.variants {
2793                for f in &mut v.payload {
2794                    rename_type_ref(&mut f.type_ref, subst);
2795                }
2796            }
2797        }
2798        TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
2799    }
2800    out
2801}
2802
2803/// #2073: rename every user type `r` names, in place. Exhaustive over
2804/// `TypeRef`, like `crate::project_model::type_ref_names`.
2805pub fn rename_type_ref(r: &mut TypeRef, subst: &HashMap<String, String>) {
2806    match r {
2807        TypeRef::Named(id) => {
2808            if let Some(to) = subst.get(&id.name) {
2809                id.name = to.clone();
2810            }
2811        }
2812        TypeRef::App { name, args, .. } => {
2813            if let Some(to) = subst.get(&name.name) {
2814                name.name = to.clone();
2815            }
2816            for a in args {
2817                rename_type_ref(a, subst);
2818            }
2819        }
2820        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
2821            rename_type_ref(a, subst);
2822            rename_type_ref(b, subst);
2823        }
2824        TypeRef::Option(t, _)
2825        | TypeRef::Effect(t, _)
2826        | TypeRef::HttpResult(t, _)
2827        | TypeRef::List(t, _)
2828        | TypeRef::Set(t, _)
2829        | TypeRef::Query(t, _)
2830        | TypeRef::Stream(t, _)
2831        | TypeRef::Connection(t, _)
2832        | TypeRef::History(t, _) => rename_type_ref(t, subst),
2833        TypeRef::Fn(params, ret, _) => {
2834            for p in params {
2835                rename_type_ref(p, subst);
2836            }
2837            rename_type_ref(ret, subst);
2838        }
2839        TypeRef::Base(..)
2840        | TypeRef::QueueResult(_)
2841        | TypeRef::Asset(_)
2842        | TypeRef::RequestHeaders(_)
2843        | TypeRef::RequestQuery(_)
2844        | TypeRef::RequestCookies(_)
2845        | TypeRef::TokenClaims(_)
2846        | TypeRef::BoundaryRejection(_)
2847        | TypeRef::ValidationError(_)
2848        | TypeRef::DecodeError(_)
2849        | TypeRef::Unit(_) => {}
2850    }
2851}
2852
2853pub fn combined_types_for(
2854    unit: &str,
2855    unit_tables: &HashMap<String, UnitTable>,
2856    unit_uses: &HashMap<String, Vec<String>>,
2857) -> HashMap<String, Arc<TypeDecl>> {
2858    let mut out: HashMap<String, Arc<TypeDecl>> = HashMap::new();
2859    if let Some(table) = unit_tables.get(unit) {
2860        for (n, d) in &table.types {
2861            out.insert(n.clone(), d.clone());
2862        }
2863    }
2864    if let Some(targets) = unit_uses.get(unit) {
2865        for t in targets {
2866            if let Some(used) = unit_tables.get(t) {
2867                for (n, d) in &used.types {
2868                    out.entry(n.clone()).or_insert_with(|| d.clone());
2869                }
2870            }
2871        }
2872    }
2873    out
2874}
2875
2876/// P6.18: a `uses`-imported type's own combined visible types (one level,
2877/// matching [`combined_types_for`]'s identical shape) — the narrow resolution
2878/// scope a signature-lowering pass needs for that unit's own attached
2879/// methods. Reimplemented against [`UnitInfo`] rather than calling
2880/// `combined_types_for` directly: that function takes the flat, project-wide
2881/// `unit_tables`/`unit_uses` maps a per-unit emission prologue doesn't thread
2882/// this deep (only the coarser, already-merged `unit_info` reaches there) —
2883/// rebuilding those two maps from `unit_info` on every call would be needless
2884/// O(units) cloning for a per-unit prologue already called once per emitted
2885/// unit.
2886pub fn combined_types_for_unit_info(
2887    unit: &str,
2888    unit_info: &BTreeMap<String, UnitInfo>,
2889) -> HashMap<String, Arc<TypeDecl>> {
2890    let mut out: HashMap<String, Arc<TypeDecl>> = HashMap::new();
2891    let Some(info) = unit_info.get(unit) else {
2892        return out;
2893    };
2894    for (n, d) in &info.table.types {
2895        out.insert(n.clone(), d.clone());
2896    }
2897    for t in &info.uses {
2898        if let Some(used) = unit_info.get(t) {
2899            for (n, d) in &used.table.types {
2900                out.entry(n.clone()).or_insert_with(|| d.clone());
2901            }
2902        }
2903    }
2904    out
2905}
2906
2907/// Locale capability track, slice 2 (#882): the message bundle a context's
2908/// `Locale.current()` negotiates against, auto-detected from the context's
2909/// *direct* `uses` (one level, not transitive — see [`combined_types_for`]
2910/// just above, the precedent for this rule). `None`/`One`/`Many` drive three
2911/// different behaviours: unchanged fixed-default `Locale`, real negotiation
2912/// wiring, or (when the context also consumes `Locale`)
2913/// `bynk.messages.multiple_message_bundles` — see `check_locale_bundle_ambiguity`
2914/// (`bynk-emit/src/project/validate.rs`) and the per-Worker composition loop
2915/// (`bynk-emit/src/project.rs`).
2916// `pub`, not `pub(crate)`: `MessageBundleInfo` appears in `emit_worker_compose`'s
2917// public signature (`bynk-emit/src/emitter/workers.rs`), which must expose
2918// types at least as visible as itself (matching `UnitTable`'s own `pub`).
2919pub enum ContextMessageBundle {
2920    /// No directly-`uses`d commons declares a `messages` block.
2921    None,
2922    /// Exactly one — the negotiable case.
2923    One(MessageBundleInfo),
2924    /// Two or more (each commons's own qualified name, for the diagnostic).
2925    Many(Vec<String>),
2926}
2927
2928pub struct MessageBundleInfo {
2929    /// The commons's qualified unit name (e.g. `"app.msgs"`).
2930    pub commons: String,
2931    /// Project-relative path of the file carrying the `@reference` block —
2932    /// the import target for `__messagesLocales`/`__messagesReferenceLocale`.
2933    /// (A bundle genuinely split across multiple files, per the track doc's
2934    /// own §4.1, is not correctly merged by `emit_messages_bundle` today —
2935    /// each file emits independently, `bynk-emit/src/project.rs`'s per-file
2936    /// `emit_items` loop — this detection mirrors that same file-scoped
2937    /// reality rather than a wider, currently-unimplemented merge.)
2938    pub source_path: PathBuf,
2939}
2940
2941/// Walks `ctx`'s own direct `uses` list for commons declaring a `messages`
2942/// bundle with exactly one `@reference` block (a bundle missing or
2943/// duplicating its own reference is already diagnosed by
2944/// `check_messages_bundles` — this function simply doesn't count it as
2945/// "found", rather than compounding an already-reported error).
2946pub fn detect_context_message_bundle(
2947    ctx: &str,
2948    unit_uses: &HashMap<String, Vec<String>>,
2949    groups: &BTreeMap<String, Vec<usize>>,
2950    kinds: &BTreeMap<String, UnitKind>,
2951    parsed: &[ParsedFile],
2952) -> ContextMessageBundle {
2953    let mut found: Vec<MessageBundleInfo> = Vec::new();
2954    for target in unit_uses.get(ctx).into_iter().flatten() {
2955        if kinds.get(target) != Some(&UnitKind::Commons) {
2956            continue;
2957        }
2958        let Some(indices) = groups.get(target) else {
2959            continue;
2960        };
2961        for &i in indices {
2962            let has_reference = parsed[i].items().iter().any(|item| {
2963                // #2618: a `private` bundle stays in its commons.
2964                matches!(item, CommonsItem::Messages(m) if m.private.is_none() && m.annotations.iter().any(|a| a.name.name == "reference"))
2965            });
2966            if has_reference {
2967                found.push(MessageBundleInfo {
2968                    commons: target.clone(),
2969                    source_path: parsed[i].source_path(),
2970                });
2971                break;
2972            }
2973        }
2974    }
2975    match found.len() {
2976        0 => ContextMessageBundle::None,
2977        1 => ContextMessageBundle::One(found.pop().expect("len == 1")),
2978        _ => ContextMessageBundle::Many(found.into_iter().map(|b| b.commons).collect()),
2979    }
2980}
2981
2982#[cfg(test)]
2983mod detect_context_message_bundle_tests {
2984    use super::*;
2985    use bynk_syntax::ast::{
2986        Annotation, Commons, CommonsForm, Context, MessagesDecl, QualifiedName, SourceUnit,
2987        UsesDecl,
2988    };
2989
2990    fn ident(name: &str) -> Ident {
2991        Ident {
2992            name: name.to_string(),
2993            span: Span::default(),
2994        }
2995    }
2996
2997    fn qualified(name: &str) -> QualifiedName {
2998        QualifiedName {
2999            parts: name.split('.').map(ident).collect(),
3000            span: Span::default(),
3001        }
3002    }
3003
3004    /// A commons `ParsedFile` declaring one `messages <tag>` block, its
3005    /// `@reference` annotation present or not. `source_path` is derived from
3006    /// `name` so each test bundle gets a distinct, recognisable import
3007    /// target — real content doesn't matter, only that a path exists.
3008    fn commons_with_messages(name: &str, tag: &str, is_reference: bool) -> ParsedFile {
3009        let annotations = if is_reference {
3010            vec![Annotation {
3011                name: ident("reference"),
3012                args: Vec::new(),
3013                span: Span::default(),
3014            }]
3015        } else {
3016            Vec::new()
3017        };
3018        let messages = MessagesDecl {
3019            tag: tag.to_string(),
3020            tag_span: Span::default(),
3021            annotations,
3022            entries: Vec::new(),
3023            documentation: None,
3024            span: Span::default(),
3025            trivia: Trivia::default(),
3026            private: None,
3027        };
3028        ParsedFile::new(
3029            PathBuf::from(format!("{}.bynk", name.replace('.', "/"))),
3030            PathBuf::from(format!("src/{}.bynk", name.replace('.', "/"))),
3031            None,
3032            String::new(),
3033            SourceUnit::Commons(Commons {
3034                name: qualified(name),
3035                items: vec![CommonsItem::Messages(messages)],
3036                uses: Vec::new(),
3037                documentation: None,
3038                form: CommonsForm::Brace,
3039                span: Span::default(),
3040                trivia: Trivia::default(),
3041                trailing_comments: Vec::new(),
3042            }),
3043            UnitKind::Commons,
3044            false,
3045        )
3046    }
3047
3048    /// A minimal context `ParsedFile` with no items of its own — only its
3049    /// `uses` list matters for this function.
3050    fn context_using(name: &str, targets: &[&str]) -> ParsedFile {
3051        ParsedFile::new(
3052            PathBuf::from(format!("{}.bynk", name.replace('.', "/"))),
3053            PathBuf::from(format!("src/{}.bynk", name.replace('.', "/"))),
3054            None,
3055            String::new(),
3056            SourceUnit::Context(Context {
3057                removed_agents: Vec::new(),
3058                name: qualified(name),
3059                uses: targets
3060                    .iter()
3061                    .map(|t| UsesDecl {
3062                        target: qualified(t),
3063                        span: Span::default(),
3064                        trivia: Trivia::default(),
3065                        blank_before: false,
3066                    })
3067                    .collect(),
3068                consumes: Vec::new(),
3069                exports: Vec::new(),
3070                items: Vec::new(),
3071                documentation: None,
3072                form: CommonsForm::Brace,
3073                span: Span::default(),
3074                trivia: Trivia::default(),
3075                trailing_comments: Vec::new(),
3076            }),
3077            UnitKind::Context,
3078            false,
3079        )
3080    }
3081
3082    /// The four tables `detect_context_message_bundle`'s real callers
3083    /// already build — bundled here so [`scenario`] doesn't need a
3084    /// clippy-unfriendly four-tuple return type.
3085    struct Scenario {
3086        parsed: Vec<ParsedFile>,
3087        groups: BTreeMap<String, Vec<usize>>,
3088        kinds: BTreeMap<String, UnitKind>,
3089        unit_uses: HashMap<String, Vec<String>>,
3090    }
3091
3092    /// Assembles a [`Scenario`] from a context plus its bundle files.
3093    fn scenario(ctx_name: &str, ctx_uses: &[&str], bundles: Vec<(&str, ParsedFile)>) -> Scenario {
3094        let mut parsed = vec![context_using(ctx_name, ctx_uses)];
3095        let mut groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
3096        let mut kinds: BTreeMap<String, UnitKind> = BTreeMap::new();
3097        groups.insert(ctx_name.to_string(), vec![0]);
3098        kinds.insert(ctx_name.to_string(), UnitKind::Context);
3099        for (name, pf) in bundles {
3100            let idx = parsed.len();
3101            parsed.push(pf);
3102            groups.entry(name.to_string()).or_default().push(idx);
3103            kinds.insert(name.to_string(), UnitKind::Commons);
3104        }
3105        let mut unit_uses: HashMap<String, Vec<String>> = HashMap::new();
3106        unit_uses.insert(
3107            ctx_name.to_string(),
3108            ctx_uses.iter().map(|s| s.to_string()).collect(),
3109        );
3110        Scenario {
3111            parsed,
3112            groups,
3113            kinds,
3114            unit_uses,
3115        }
3116    }
3117
3118    #[test]
3119    fn zero_bundles_when_uses_reaches_no_messages_commons() {
3120        let Scenario {
3121            parsed,
3122            groups,
3123            kinds,
3124            unit_uses,
3125        } = scenario("app.web", &["app.other"], vec![]);
3126        assert!(matches!(
3127            detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3128            ContextMessageBundle::None
3129        ));
3130    }
3131
3132    #[test]
3133    fn zero_bundles_when_uses_is_empty() {
3134        let Scenario {
3135            parsed,
3136            groups,
3137            kinds,
3138            unit_uses,
3139        } = scenario("app.web", &[], vec![]);
3140        assert!(matches!(
3141            detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3142            ContextMessageBundle::None
3143        ));
3144    }
3145
3146    #[test]
3147    fn one_bundle_is_found_by_its_reference_block() {
3148        let bundle = commons_with_messages("app.msgs", "en", true);
3149        let Scenario {
3150            parsed,
3151            groups,
3152            kinds,
3153            unit_uses,
3154        } = scenario("app.web", &["app.msgs"], vec![("app.msgs", bundle)]);
3155        let found = detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed);
3156        let ContextMessageBundle::One(info) = found else {
3157            panic!("expected exactly one bundle");
3158        };
3159        assert_eq!(info.commons, "app.msgs");
3160        assert_eq!(info.source_path, PathBuf::from("app/msgs.bynk"));
3161    }
3162
3163    #[test]
3164    fn a_bundle_missing_its_reference_block_is_not_counted() {
3165        // Not a `@reference` block — already diagnosed elsewhere
3166        // (`bynk.messages.missing_reference`); this function simply doesn't
3167        // count it, rather than compounding an already-reported error.
3168        let bundle = commons_with_messages("app.msgs", "en", false);
3169        let Scenario {
3170            parsed,
3171            groups,
3172            kinds,
3173            unit_uses,
3174        } = scenario("app.web", &["app.msgs"], vec![("app.msgs", bundle)]);
3175        assert!(matches!(
3176            detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3177            ContextMessageBundle::None
3178        ));
3179    }
3180
3181    #[test]
3182    fn two_bundles_report_both_commons_names() {
3183        let a = commons_with_messages("app.msgs_a", "en", true);
3184        let b = commons_with_messages("app.msgs_b", "en", true);
3185        let Scenario {
3186            parsed,
3187            groups,
3188            kinds,
3189            unit_uses,
3190        } = scenario(
3191            "app.web",
3192            &["app.msgs_a", "app.msgs_b"],
3193            vec![("app.msgs_a", a), ("app.msgs_b", b)],
3194        );
3195        let found = detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed);
3196        let ContextMessageBundle::Many(names) = found else {
3197            panic!("expected two bundles");
3198        };
3199        let mut names = names;
3200        names.sort();
3201        assert_eq!(
3202            names,
3203            vec!["app.msgs_a".to_string(), "app.msgs_b".to_string()]
3204        );
3205    }
3206
3207    #[test]
3208    fn a_commons_reached_only_transitively_is_not_counted() {
3209        // `app.web` uses `app.mid`, which itself uses the bundle — `uses` is
3210        // one level, not transitive (message-bundles' own established rule),
3211        // so this must still report `None`.
3212        let bundle = commons_with_messages("app.msgs", "en", true);
3213        let mut mid = context_using("app.mid", &["app.msgs"]);
3214        // `app.mid` needs to be a commons for this scenario to be legal, but
3215        // `context_using` builds a Context — for this narrow test only the
3216        // `uses` *resolution* (does app.web's own direct list reach the
3217        // bundle) matters, and app.web's own list never names `app.msgs`
3218        // directly, so the unit kind of the intermediate is irrelevant.
3219        mid.set_kind(UnitKind::Commons);
3220        let Scenario {
3221            mut parsed,
3222            mut groups,
3223            mut kinds,
3224            unit_uses,
3225        } = scenario("app.web", &["app.mid"], vec![("app.msgs", bundle)]);
3226        let mid_idx = parsed.len();
3227        parsed.push(mid);
3228        groups.insert("app.mid".to_string(), vec![mid_idx]);
3229        kinds.insert("app.mid".to_string(), UnitKind::Commons);
3230        assert!(matches!(
3231            detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3232            ContextMessageBundle::None
3233        ));
3234    }
3235}
3236
3237/// #696: returns the `parsed` index of the owning file alongside the `consumes`
3238/// clause span, so the caller can attribute the diagnostic to that file.
3239pub fn consumes_span_of(
3240    parsed: &[ParsedFile],
3241    indices: &[usize],
3242    target: &str,
3243) -> Option<(usize, Span)> {
3244    for &i in indices {
3245        for c in parsed[i].consumes() {
3246            if c.target.joined() == target {
3247                return Some((i, c.span));
3248            }
3249        }
3250    }
3251    None
3252}
3253
3254/// #696: returns the `parsed` index of the owning file alongside the alias span,
3255/// so the caller can attribute the diagnostic to that file.
3256pub fn parsed_alias_span(
3257    parsed: &[ParsedFile],
3258    indices: &[usize],
3259    alias: &str,
3260) -> Option<(usize, Span)> {
3261    for &i in indices {
3262        for c in parsed[i].consumes() {
3263            if let Some(a) = &c.alias
3264                && a.name == alias
3265            {
3266                return Some((i, a.span));
3267            }
3268        }
3269    }
3270    None
3271}
3272
3273/// A type imported into a context via `consumes`. Carries enough metadata for
3274/// the checker and emitter to enforce / express visibility.
3275#[derive(Debug, Clone)]
3276pub struct ConsumedType {
3277    pub owning_context: String,
3278    pub visibility: Visibility,
3279}
3280
3281/// #1925: every pair of top-level declarations sharing one name, in one
3282/// context, against the rule that a unit's services, agents, providers,
3283/// functions, assets, types and events share one namespace — the scope of the
3284/// emitted TypeScript module. Capabilities and actors keep their own.
3285#[cfg(test)]
3286mod value_namespace_tests {
3287    use super::*;
3288    use crate::testkit::analyse;
3289
3290    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
3291    enum Kind {
3292        Fn,
3293        Type,
3294        Event,
3295        Asset,
3296        Embed,
3297        Const,
3298        Service,
3299        Agent,
3300        Provider,
3301        Capability,
3302        Actor,
3303    }
3304
3305    const ALL: [Kind; 11] = [
3306        Kind::Fn,
3307        Kind::Type,
3308        Kind::Event,
3309        Kind::Asset,
3310        Kind::Embed,
3311        Kind::Const,
3312        Kind::Service,
3313        Kind::Agent,
3314        Kind::Provider,
3315        Kind::Capability,
3316        Kind::Actor,
3317    ];
3318
3319    /// The kind a declaration names, and so the side of the rule it takes.
3320    /// Exhaustive on purpose: a new declaration kind does not compile here
3321    /// until it is placed in or out of the value namespace (and in [`ALL`]).
3322    fn kind_of(item: &CommonsItem) -> Option<Kind> {
3323        match item {
3324            CommonsItem::Fn(_) => Some(Kind::Fn),
3325            CommonsItem::Type(_) => Some(Kind::Type),
3326            CommonsItem::Event(_) => Some(Kind::Event),
3327            CommonsItem::Asset(_) => Some(Kind::Asset),
3328            CommonsItem::Embed(_) => Some(Kind::Embed),
3329            CommonsItem::Const(_) => Some(Kind::Const),
3330            CommonsItem::Service(_) => Some(Kind::Service),
3331            CommonsItem::Agent(_) => Some(Kind::Agent),
3332            CommonsItem::Provider(_) => Some(Kind::Provider),
3333            CommonsItem::Capability(_) => Some(Kind::Capability),
3334            CommonsItem::Actor(_) => Some(Kind::Actor),
3335            // Keyed by locale tag, in a commons only: it names nothing.
3336            CommonsItem::Messages(_) => None,
3337        }
3338    }
3339
3340    fn shares_the_value_namespace(k: Kind) -> bool {
3341        !matches!(k, Kind::Capability | Kind::Actor)
3342    }
3343
3344    /// A declaration of `kind` named `n`. A provider brings the capability it
3345    /// provides, under a name no other snippet uses.
3346    fn decl(kind: Kind, n: &str) -> String {
3347        match kind {
3348            Kind::Fn => format!("fn {n}() -> Int {{\n  1\n}}\n"),
3349            Kind::Type => format!("type {n} = {{ n: Int }}\n"),
3350            Kind::Event => format!("event {n} = {{ n: Int }}\n"),
3351            Kind::Asset => format!("asset {n} = \"assets/x.json\"\n"),
3352            Kind::Embed => format!("embed {n} = \"embeds/x.txt\"\n"),
3353            Kind::Const => format!("const {n}: Int = 1\n"),
3354            Kind::Service => {
3355                format!(
3356                    "service {n} {{\n  on call() -> Effect[Int] by Caller {{\n    Effect.pure(1)\n  }}\n}}\n"
3357                )
3358            }
3359            Kind::Agent => format!(
3360                "agent {n} {{\n  key id: String\n\n  store hits: Cell[Int]\n\n  on call ping() -> Effect[Int] {{\n    1\n  }}\n}}\n"
3361            ),
3362            Kind::Provider => format!(
3363                "capability ProbeCap {{\n  fn go() -> Effect[Int]\n}}\n\nprovides ProbeCap = {n} {{\n  fn go() -> Effect[Int] {{\n    Effect.pure(1)\n  }}\n}}\n"
3364            ),
3365            Kind::Capability => format!("capability {n} {{\n  fn go() -> Effect[Int]\n}}\n"),
3366            Kind::Actor => {
3367                format!("actor {n} {{ auth = Bearer(secret = \"S\"), identity = ProbeId }}\n")
3368            }
3369        }
3370    }
3371
3372    const HEADER: &str = "context app\n\ntype ProbeId = opaque String\n\n";
3373
3374    #[test]
3375    fn each_snippet_declares_its_kind() {
3376        for k in ALL {
3377            let src = format!("{HEADER}{}", decl(k, "Thing"));
3378            let tokens = bynk_syntax::lexer::tokenize(&src).expect("lexes");
3379            let unit = bynk_syntax::parser::parse_unit(&tokens, &src).expect("parses");
3380            let bynk_syntax::ast::SourceUnit::Context(c) = unit else {
3381                panic!("a context")
3382            };
3383            assert!(
3384                c.items.iter().any(|i| kind_of(i) == Some(k)),
3385                "the {k:?} snippet declares no {k:?}"
3386            );
3387        }
3388    }
3389
3390    #[test]
3391    fn every_pair_of_kinds_against_the_value_namespace() {
3392        for (x, &a) in ALL.iter().enumerate() {
3393            for &b in &ALL[x + 1..] {
3394                // Both declaration orders, under both casings.
3395                for (first, second) in [(a, b), (b, a)] {
3396                    for n in ["thing", "Thing"] {
3397                        // A constant's name is upper-camel or it is also
3398                        // `bynk.resolve.const_name_case`; one casing suffices.
3399                        if n == "thing" && (a == Kind::Const || b == Kind::Const) {
3400                            continue;
3401                        }
3402                        let src = format!("{HEADER}{}\n{}", decl(first, n), decl(second, n));
3403                        let r = analyse(&[
3404                            ("app/main.bynk", &src),
3405                            ("assets/x.json", "{}"),
3406                            ("embeds/x.txt", "x"),
3407                        ]);
3408                        let cats = r.error_categories();
3409                        if shares_the_value_namespace(a) && shares_the_value_namespace(b) {
3410                            let want = if matches!((a, b), (Kind::Type, Kind::Event)) {
3411                                "bynk.resolve.duplicate_type"
3412                            } else {
3413                                "bynk.resolve.name_conflict"
3414                            };
3415                            assert_eq!(cats, vec![want], "{first:?} then {second:?} `{n}`");
3416                        } else {
3417                            assert!(
3418                                cats.is_empty(),
3419                                "{first:?} then {second:?} `{n}` should check clean: {cats:?}"
3420                            );
3421                        }
3422                    }
3423                }
3424            }
3425        }
3426    }
3427
3428    /// A context split across files is one namespace: the conflict is found
3429    /// whichever file declares which, and reported in the service's file.
3430    #[test]
3431    fn a_split_context_is_one_namespace() {
3432        for (svc_file, asset_file) in [("a.bynk", "z.bynk"), ("z.bynk", "a.bynk")] {
3433            let svc = format!("context app\n\n{}", decl(Kind::Service, "api"));
3434            let asset = format!("context app\n\n{}", decl(Kind::Asset, "api"));
3435            let svc_path = format!("app/{svc_file}");
3436            let asset_path = format!("app/{asset_file}");
3437            let r = analyse(&[
3438                (svc_path.as_str(), svc.as_str()),
3439                (asset_path.as_str(), asset.as_str()),
3440                ("assets/x.json", "{}"),
3441            ]);
3442            assert_eq!(r.error_categories(), vec!["bynk.resolve.name_conflict"]);
3443            let d = &r.analysis.errors[0];
3444            assert!(
3445                d.source_path
3446                    .as_deref()
3447                    .is_some_and(|p| p.ends_with(svc_file)),
3448                "reported in the service's file: {:?}",
3449                d.source_path
3450            );
3451        }
3452    }
3453
3454    /// Two bodied providers of different capabilities under one name each
3455    /// emit a class of that name.
3456    #[test]
3457    fn two_providers_under_one_name_conflict() {
3458        let src = "context app\n\ncapability A {\n  fn go() -> Effect[Int]\n}\n\ncapability B {\n  fn go() -> Effect[Int]\n}\n\nprovides A = Impl {\n  fn go() -> Effect[Int] {\n    Effect.pure(1)\n  }\n}\n\nprovides B = Impl {\n  fn go() -> Effect[Int] {\n    Effect.pure(2)\n  }\n}\n";
3459        let r = analyse(&[("app/main.bynk", src)]);
3460        assert_eq!(r.error_categories(), vec!["bynk.resolve.name_conflict"]);
3461    }
3462}
3463
3464/// #2073 review: a borrowed type's body resolves in its declaring context's
3465/// view, so the contract table hashes the shape the wire carries.
3466#[cfg(test)]
3467mod contract_types_tests {
3468    use crate::testkit::analyse;
3469
3470    const ORDER: &str = "context shop.order\n\nexports transparent { Order }\n\ntype Region = enum { Domestic, International }\n\ntype Order = { id: String, region: Region }\n";
3471    const POST: &str = "context shop.post\n\nexports transparent { Parcel }\n\ntype Region = enum { North, South }\n\ntype Parcel = { ref: String, region: Region }\n";
3472    const LEDGER: &str = "context shop.ledger\n\nconsumes shop.order\nconsumes shop.post\n\ntype Region = enum { Here, There }\n\nservice orderId {\n  on call(o: Order) -> Effect[String] by Caller {\n    o.id\n  }\n}\n\nservice parcelRef {\n  on call(p: Parcel) -> Effect[String] by Caller {\n    p.ref\n  }\n}\n";
3473
3474    fn normal_form(service: &str) -> String {
3475        let a = analyse(&[
3476            ("shop/order.bynk", ORDER),
3477            ("shop/post.bynk", POST),
3478            ("shop/ledger.bynk", LEDGER),
3479        ]);
3480        a.assert_clean();
3481        let info = &a.analysis.boundary_info["shop.ledger"];
3482        let svc = crate::resolver::cross_context_service_for(service, &info.services[service])
3483            .expect("an `on call` service");
3484        crate::contract::service_normal_form(&svc, &info.types)
3485    }
3486
3487    /// #2087: a qualified key reads as its declaration's own name wherever a
3488    /// type is shown to a user. `Ty::display` is the renderer behind every
3489    /// checker diagnostic that names a type.
3490    #[test]
3491    fn a_qualified_key_displays_as_its_declarations_name() {
3492        use super::{display_type_name, display_type_names_in};
3493        assert_eq!(display_type_name("shop_order__Code"), "Code");
3494        assert_eq!(display_type_name("shop_ledger__shop_order__Code"), "Code");
3495        assert_eq!(display_type_name("Code"), "Code");
3496        assert_eq!(display_type_name("My__Thing"), "My__Thing");
3497        assert_eq!(display_type_name("shop_order__lower"), "shop_order__lower");
3498        assert_eq!(
3499            display_type_names_in("orderId(o: Order{code: shop_order__Code(String)})"),
3500            "orderId(o: Order{code: Code(String)})"
3501        );
3502        let tys = crate::checker::Types::default();
3503        let key = tys.intern(crate::checker::Ty::Named {
3504            name: "shop_order__Code".to_string(),
3505            kind: crate::checker::NamedKind::Opaque(bynk_syntax::ast::BaseType::String),
3506            args: Vec::new(),
3507        });
3508        assert_eq!(tys.display(key), "Code");
3509        let listed = tys.intern(crate::checker::Ty::List(key));
3510        assert_eq!(tys.display(listed), "List[Code]");
3511    }
3512
3513    #[test]
3514    fn a_borrowed_record_names_its_own_contexts_field_type() {
3515        let order = normal_form("orderId");
3516        assert!(
3517            order.contains("Domestic") && !order.contains("Here") && !order.contains("North"),
3518            "{order}"
3519        );
3520        let parcel = normal_form("parcelRef");
3521        assert!(
3522            parcel.contains("North") && !parcel.contains("Here") && !parcel.contains("Domestic"),
3523            "{parcel}"
3524        );
3525    }
3526}