Skip to main content

bynk_check/
project_model.rs

1//! Project-wide orchestration: discovery → parse → group → resolve, shared
2//! between `bynk-emit`'s `run_checks` (both `Mode::Build` and `Mode::Analyse`)
3//! and this crate's own [`crate::analysis::analyse_project`].
4//!
5//! P4.1 (#1115), second scope finding on the tracking issue: this pipeline —
6//! `phase_discovery` through `assemble_unit_info`, plus the per-unit symbol
7//! composition (`compose_unit_symbols`/`merge_consumed_exports`/
8//! `collect_unit_methods`) — used to live only in `bynk-emit/src/project.rs`,
9//! inline in `run_checks`. A literal no-indirection `bynk-check`-side analysis
10//! entry point needs the identical sequence, so rather than write a second,
11//! independently-maintained copy (the mistake this whole design track's
12//! `extract, don't duplicate` principle exists to prevent — see
13//! `lower_field_default_wire`, `build_capability_op_info` for the same move
14//! made earlier in this track), it moved here. `bynk-emit`'s `run_checks`
15//! becomes a caller of these functions instead of owning the logic, the same
16//! way P4.0 turned `project.rs` into a caller of `bynk-project`.
17//!
18//! What stayed in `bynk-emit` (not shared, because only the `Mode::Build` path
19//! needs it, or because it's genuinely emission-shaped): the `Mode::Build`
20//! bail gate and everything from emission onward (`EmitUnitCtx`, `emit_unit`,
21//! `collect_history_target_agents`). The whole-project `messages`/locale-
22//! ambiguity/event-subscription checks (P5.0/P5.1), the function-type-
23//! boundary check (P5.2, [`phase_function_type_boundaries`]), and
24//! schema-registry reconciliation/platform-lock enforcement (P5.3,
25//! [`crate::schema_registry::reconcile`]/[`phase_platform_lock`]) have since
26//! moved here too — the P5.2 move closed `phase_group`'s optional
27//! boundary-check hook, which used to be the only way `run_checks` and the
28//! new entry point could reach it without duplicating the diagnostic-ordering
29//! logic (see `analysis.rs` for the residual-gap accounting that remains).
30
31use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
32use std::path::{Path, PathBuf};
33use std::sync::{Arc, OnceLock};
34
35use crate::checker::{self, Ty, TyId, Types};
36use crate::context_checks::{
37    CAPABILITY_SIGNATURE, RECORD_FIELD, REQUEST_RECORD_PARAM, SUM_PAYLOAD,
38    build_capability_op_info, reject_fn_types, ts_type_ref_display, type_ref_is_held,
39    type_ref_to_display, validate_store_field_value_types,
40};
41use crate::firstparty::{self, Platform};
42use crate::icu;
43use crate::index::{RefSink, SymbolKind};
44use crate::resolver::MethodTable as ResolverMethodTable;
45use crate::symbols::{
46    ConsumedType, ContextMessageBundle, FileDeclIndex, UnitTable, build_file_decl_index,
47    build_unit_table, consumes_span_of, detect_context_message_bundle, parsed_alias_span,
48    uses_span_of,
49};
50use bynk_project::{
51    AttributedError, LabelFile, ParsedFile, UnitKind, check_directory_kind_consistency,
52    check_directory_name_consistency, check_file_directory_conflicts, check_group_kind_consistency,
53    check_group_module_docs, check_path_name_alignment, detect_consumes_cycles,
54    discover_bynk_files, is_unpinned_range, normalize_rel, parse_sources, parse_sources_recovering,
55    read_adapter_binding, read_adapter_include, read_source,
56};
57use bynk_syntax::ast::*;
58/// P6.49 (design/tracks/the-ir.md §6b), following P6.27's `ExprId` precedent
59/// (`checker.rs:39`): re-exported because this module's own public API —
60/// [`compose_unit_symbols`]'s `combined_types`/`combined_fns`,
61/// [`collect_unit_methods`]'s return, and [`UnitInfo::exports`]'s value type
62/// — is already parameterised by these three types. `bynk-emit` only ever
63/// plumbs the resulting tables through to other `bynk-check` calls; it never
64/// matches a variant of any of the three.
65pub use bynk_syntax::ast::{FnDecl, TypeDecl, Visibility};
66use bynk_syntax::error::CompileError;
67use bynk_syntax::lexer;
68use bynk_syntax::parser;
69use bynk_syntax::span::{FileId, Span};
70
71/// Collection-point error sink (ADR 0052). Helpers keep their plain
72/// `&mut Vec<CompileError>` signatures; call sites attribute via
73/// `extend_for` with the file in scope at that point.
74///
75/// P4.1 (#1115): relocated from `bynk-emit/src/project/diagnostics.rs`
76/// alongside the `phase_*` functions above, which all take `&mut ErrorSink` —
77/// the same "shared logic pulls its own types down with it" pattern already
78/// applied to `UnitTable`/`ConsumedType` in the `symbols.rs` move. `Mode` and
79/// `ProjectFailure` (the other two `diagnostics.rs` pipeline-driving types)
80/// stayed in `bynk-emit`, unaffected — neither is a dependency of anything
81/// this module needs.
82#[derive(Clone)]
83pub struct ErrorSink {
84    entries: Vec<AttributedError>,
85    /// v0.89 (ADR 0117): non-failing warnings, classified on push by
86    /// `Severity::for_error`. Kept apart so `is_empty`/`len` — the build-failure
87    /// gates — stay errors-only, while every warning source (commons-fn checks,
88    /// service/agent handler validation, parser) is captured uniformly.
89    warnings: Vec<AttributedError>,
90    /// The identity path of every parsed project file, by the `FileId` its
91    /// spans carry ([`Self::register_file`]). Read when the sink is drained,
92    /// to say which file each secondary label lies in (`label_files`).
93    files: HashMap<FileId, PathBuf>,
94    /// #3431: every project source, kept only when some file declares a
95    /// `SignedCookie` actor, so `signed_cookie_unprefixed` can tell whether its
96    /// cookie name is read anywhere else before offering a rename.
97    cookie_sources: Vec<(FileId, Arc<str>)>,
98    /// The `(address, length)` of each parsed source `cookie_sources` was built
99    /// from, so a repeat `register_parsed` over the same files skips the rebuild.
100    cookie_key: Vec<(usize, usize)>,
101}
102
103impl Default for ErrorSink {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109impl ErrorSink {
110    pub fn new() -> Self {
111        Self {
112            entries: Vec::new(),
113            warnings: Vec::new(),
114            files: HashMap::new(),
115            cookie_sources: Vec::new(),
116            cookie_key: Vec::new(),
117        }
118    }
119    /// Record that spans carrying `file` lie in the project file `identity`.
120    pub fn register_file(&mut self, file: FileId, identity: PathBuf) {
121        self.files.insert(file, identity);
122    }
123    /// Register every file of `parsed` that was read from disk, by the durable
124    /// `FileId` its absolute path interns to (`parse_cache::file_id_for`) — the
125    /// one map both an error's file ([`Self::extend_attributed_by_span`]) and
126    /// each label's (when the sink is drained) are read from, so the two never
127    /// disagree. `phase_parse` registers every file it parses; a
128    /// toolchain-injected unit, with no absolute path, is never registered.
129    pub fn register_parsed(&mut self, parsed: &[ParsedFile]) {
130        let key: Vec<(usize, usize)> = parsed
131            .iter()
132            .map(|pf| (pf.source().as_ptr() as usize, pf.source().len()))
133            .collect();
134        if key != self.cookie_key {
135            self.cookie_key = key;
136            self.cookie_sources = Self::cookie_sources_of(parsed);
137        }
138        self.register_files(parsed);
139    }
140    /// #3431: the project's sources, when some file declares a `SignedCookie`.
141    fn cookie_sources_of(parsed: &[ParsedFile]) -> Vec<(FileId, Arc<str>)> {
142        if parsed.iter().any(|pf| pf.source().contains("SignedCookie")) {
143            parsed
144                .iter()
145                .filter_map(|pf| {
146                    let id = bynk_project::parse_cache::file_id_for(&pf.abs_path()?);
147                    Some((id, Arc::from(pf.source())))
148                })
149                .collect()
150        } else {
151            Vec::new()
152        }
153    }
154    fn register_files(&mut self, parsed: &[ParsedFile]) {
155        for pf in parsed {
156            if let Some(abs) = pf.abs_path() {
157                self.register_file(
158                    bynk_project::parse_cache::file_id_for(&abs),
159                    pf.identity_path(),
160                );
161            }
162        }
163    }
164    pub fn push_for(&mut self, file: Option<&Path>, mut error: CompileError) {
165        // #2223: a dependency unit's canonical name reads as
166        // `org/package:unit` wherever a diagnostic names it.
167        display_canonical_names(&mut error);
168        let attributed = AttributedError::new(file.map(Path::to_path_buf), error);
169        match bynk_syntax::Severity::for_error(&attributed.error) {
170            bynk_syntax::Severity::Warning | bynk_syntax::Severity::Hint => {
171                self.warnings.push(attributed)
172            }
173            bynk_syntax::Severity::Error => self.entries.push(attributed),
174        }
175    }
176    pub fn extend_for(
177        &mut self,
178        file: Option<&Path>,
179        errs: impl IntoIterator<Item = CompileError>,
180    ) {
181        for e in errs {
182            self.push_for(file, e);
183        }
184    }
185    /// #1659 (closes #696's gap): attribute each error to the parsed file its
186    /// span is in, by `FileId`. Every parsed file's spans carry the durable
187    /// `FileId` its absolute path interns to (`parse_cache::file_id_for`), so
188    /// the owning file is recoverable from the span alone. Suite and
189    /// integration diagnostics were pushed unattributed, because threading a
190    /// file through their many internal push sites was deferred, and rendered
191    /// with no file, line or span. An error whose span matches no parsed file
192    /// stays unattributed, as before. `parsed` is registered first
193    /// ([`Self::register_parsed`]), so a file `phase_parse` never saw is still
194    /// found.
195    pub fn extend_attributed_by_span(
196        &mut self,
197        parsed: &[ParsedFile],
198        errs: impl IntoIterator<Item = CompileError>,
199    ) {
200        self.register_parsed(parsed);
201        self.extend_attributed(errs);
202    }
203    /// [`Self::extend_attributed_by_span`] for a caller that has already called
204    /// [`Self::register_parsed`] on the final `parsed` set. Registering hashes
205    /// every file's path, so a caller that attributes once per unit (the
206    /// per-unit check loops) registers once up front and calls this: doing it
207    /// per call made that loop cost units times files (#3243).
208    pub fn extend_attributed(&mut self, errs: impl IntoIterator<Item = CompileError>) {
209        for e in errs {
210            let file = self.files.get(&e.span.file).cloned();
211            self.push_for(file.as_deref(), e);
212        }
213    }
214    /// Append everything `other` collected (#3243 S2.3): the per-file scratch
215    /// sink a file's check wrote into, folded into the project's in the order
216    /// the checks ran, so the result is what one shared sink would hold.
217    pub fn absorb(&mut self, other: ErrorSink) {
218        self.entries.extend(other.entries);
219        self.warnings.extend(other.warnings);
220    }
221    /// True when no **error-severity** diagnostic has been collected — the
222    /// build-failure gate. Warnings do not count (ADR 0117).
223    pub fn is_empty(&self) -> bool {
224        self.entries.is_empty()
225    }
226    /// Consume the sink, yielding the non-failing **warnings** (ADR 0117).
227    pub fn into_warnings(self) -> Vec<AttributedError> {
228        let mut warnings = self.warnings;
229        attach_cookie_rename_fix(&self.cookie_sources, &mut warnings);
230        attribute_labels(&self.files, &mut warnings);
231        warnings
232    }
233    /// Consume the sink, yielding errors then warnings — the full diagnostic
234    /// list the LSP and a failed build render together.
235    pub fn into_all(self) -> Vec<AttributedError> {
236        let mut all = self.entries;
237        all.extend(self.warnings);
238        attach_cookie_rename_fix(&self.cookie_sources, &mut all);
239        attribute_labels(&self.files, &mut all);
240        all
241    }
242    /// The count of **error-severity** diagnostics.
243    pub fn len(&self) -> usize {
244        self.entries.len()
245    }
246}
247
248/// #3431: offer `signed_cookie_unprefixed`'s rename to `__Host-…` only when no
249/// other site in the project mentions the cookie name. A read site (a typed
250/// `cookies` field or `@name("x")`, `RequestCookies.get("x")`, a test) names it
251/// as a string literal, so the test is deliberately textual and conservative:
252/// any other occurrence of the quoted name anywhere in the project's sources,
253/// comments included, keeps the diagnostic note-only. The rename logs existing
254/// users out, so it is `MaybeIncorrect`: a quick fix, never fix-all's.
255fn attach_cookie_rename_fix(sources: &[(FileId, Arc<str>)], errors: &mut [AttributedError]) {
256    for ae in errors {
257        let e = &mut ae.error;
258        if e.category != "bynk.actor.signed_cookie_unprefixed" || !e.suggestions.is_empty() {
259            continue;
260        }
261        let Some((_, text)) = sources.iter().find(|(id, _)| *id == e.span.file) else {
262            continue;
263        };
264        let Some(literal) = text.get(e.span.range()) else {
265            continue;
266        };
267        let name = match literal.strip_prefix('"').and_then(|l| l.strip_suffix('"')) {
268            Some(n) if !n.is_empty() && !n.contains(['\\', '"']) => n,
269            _ => continue,
270        };
271        let mentions: usize = sources
272            .iter()
273            .map(|(_, t)| t.matches(literal).count())
274            .sum();
275        if mentions != 1 {
276            continue;
277        }
278        // A `__Secure-` name is swapped, not stacked: `__Host-sid`, not `__Host-__Secure-sid`.
279        let base = match name.get(..9) {
280            Some(p) if p.eq_ignore_ascii_case("__Secure-") => &name[9..],
281            _ => name,
282        };
283        if base.is_empty() {
284            continue;
285        }
286        e.suggestions.push(bynk_syntax::error::Suggestion {
287            message: format!(
288                "rename the cookie to `__Host-{base}` (no other site in the project names `{name}`; existing users are logged out when the name changes)"
289            ),
290            edits: vec![(e.span, format!("\"__Host-{base}\""))],
291            applicability: bynk_syntax::error::Applicability::MaybeIncorrect,
292        });
293    }
294}
295
296/// Fill in each error's `label_files` from the `FileId` its labels' spans
297/// carry, against the files `phase_parse` registered. A label is in the
298/// error's own file when its span has the primary span's `FileId`, carries no
299/// file identity (`FileId::UNKNOWN`, a span built without one), or names the
300/// error's own `source_path`. One naming another registered file is
301/// [`LabelFile::Other`]; one naming a toolchain-injected unit's reserved id is
302/// [`LabelFile::FirstParty`] (#1956), carrying that unit's own source; any other
303/// is [`LabelFile::Unavailable`]. Neither is ever drawn against the primary
304/// file's text.
305fn attribute_labels(files: &HashMap<FileId, PathBuf>, errors: &mut [AttributedError]) {
306    for ae in errors {
307        let primary = ae.error.span.file;
308        ae.label_files = ae
309            .error
310            .labels
311            .iter()
312            .map(|(span, _)| {
313                if span.file == primary || span.file == FileId::UNKNOWN {
314                    return LabelFile::Primary;
315                }
316                match files.get(&span.file) {
317                    Some(path) if Some(path) == ae.source_path.as_ref() => LabelFile::Primary,
318                    Some(path) => LabelFile::Other(path.clone()),
319                    None => match firstparty_unit_for(span.file) {
320                        Some(unit) => LabelFile::FirstParty {
321                            identity_path: unit.identity_path,
322                            source: unit.source,
323                        },
324                        None => LabelFile::Unavailable,
325                    },
326                }
327            })
328            .collect();
329    }
330}
331
332/// v0.17: a resolved adapter binding — the user-authored `.binding.ts` module
333/// that supplies an adapter's external provider symbols. Copied verbatim into
334/// the output beside the adapter's emitted interface module so that `tsc`
335/// checks the `implements` contract and compose can import the symbols.
336pub struct AdapterBinding {
337    /// Output path, relative to the output root (e.g. `tokens.binding.ts`).
338    pub output_path: PathBuf,
339    /// Verbatim TypeScript content read from the source tree.
340    pub content: String,
341    /// #2321: the files the `binding … includes [ … ]` clause ships beside it.
342    pub includes: Vec<IncludedFile>,
343}
344
345/// #2321: one file an adapter binding includes, copied byte for byte.
346#[derive(Clone)]
347pub struct IncludedFile {
348    /// Output path, relative to the output root (beside the binding).
349    pub output_path: PathBuf,
350    pub bytes: Vec<u8>,
351}
352
353/// The build target. Determines how cross-context calls and per-context
354/// modules are emitted (v0.8). Bundle mode is the default — all contexts
355/// emit into one TypeScript bundle and cross-context calls are direct
356/// function invocations. Workers mode produces per-context Cloudflare
357/// Worker bundles that communicate via Service Bindings.
358#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
359pub enum BuildTarget {
360    /// Existing behaviour: one TS bundle, direct function calls between
361    /// contexts.
362    #[default]
363    Bundle,
364    /// One Worker per context. Cross-context calls become Service Binding
365    /// invocations using a JSON wire format with refinement validation on
366    /// the receiving side.
367    Workers,
368}
369
370pub fn normalize_service_defaults(parsed: &mut [ParsedFile]) {
371    for pf in parsed.iter_mut() {
372        let items = match pf.unit_mut() {
373            SourceUnit::Commons(c) => &mut c.items,
374            SourceUnit::Context(c) => &mut c.items,
375            SourceUnit::Adapter(a) => &mut a.items,
376            SourceUnit::Suite(_) => continue,
377        };
378        for item in items.iter_mut() {
379            if let CommonsItem::Service(svc) = item {
380                inject_service_defaults(svc);
381            }
382        }
383    }
384}
385
386/// Inject a single service's `by`/`given` defaults into its handlers. A handler
387/// that names its own `by` (or `given`) overrides the default outright — the
388/// default fills only an *absent* clause, never merges. A service with no default
389/// is left untouched (byte-for-byte the pre-v0.155 behaviour).
390pub fn inject_service_defaults(svc: &mut ServiceDecl) {
391    let default_by = svc.default_by.clone();
392    let default_given = svc.default_given.clone();
393    if default_by.is_none() && default_given.is_empty() {
394        return;
395    }
396    for handler in svc.handlers.iter_mut() {
397        // #2341 (decision C): `on rejected` runs for a request no handler took,
398        // before any actor is known, and uses no capability.
399        if handler.kind == HandlerKind::Rejected {
400            continue;
401        }
402        if handler.by_clause.is_none()
403            && let Some(def) = &default_by
404        {
405            handler.by_clause = Some(def.clone());
406        }
407        if handler.given.is_empty() && !default_given.is_empty() {
408            handler.given = default_given.clone();
409        }
410    }
411}
412
413/// Phase 1: discover the `.bynk` files under the source (and, in split mode,
414/// the tests) root by walking the filesystem. Pushes any discovery error into
415/// `errors` and signals a pipeline bail via `Err(())` (the caller terminates
416/// with `finish`); otherwise returns the discovered `(src_files, tests_files)`.
417///
418/// #1077/#1081 review: this is the on-disk half only — `no_sources`/
419/// `check_file_directory_conflicts` moved to [`check_discovered_files`], which
420/// `run_checks` calls on the result *either* this walk *or* a caller-supplied
421/// `discovered` list produces, so a `CompileOptions.sources`-driven compile
422/// (the CLI's own path as of #1081) still gets both checks — they are
423/// properties of "what files does this build have," not of having just
424/// walked the disk to find them.
425/// R3.9 (#1113): walks every `(root, prefix)` tree `Roots::trees` resolves
426/// to, not a hardcoded primary/secondary pair — `trees[0]` is the mandatory
427/// tree (a missing directory is a real error, via `discover_bynk_files`
428/// itself); every later tree is optional, same as the old secondary tree
429/// always was (a project may simply have no such subtree).
430#[allow(clippy::result_unit_err)]
431pub fn phase_discovery(
432    trees: &[(PathBuf, PathBuf)],
433    excludes: &[PathBuf],
434    errors: &mut ErrorSink,
435) -> Result<Vec<Vec<PathBuf>>, ()> {
436    let mut out = Vec::with_capacity(trees.len());
437    for (i, (root, _prefix)) in trees.iter().enumerate() {
438        match discover_bynk_files(root, excludes) {
439            Ok(f) => out.push(f),
440            // Every tree past the first is optional — a missing directory is
441            // not an error, same as the old secondary tree always was. Tried
442            // via `discover_bynk_files` itself (a `fs::read_dir`) rather than
443            // a `root.exists()` pre-check, which would cost a redundant
444            // `stat()` per optional tree for the same answer.
445            Err(e) if i > 0 && e.category == "bynk.project.no_root" => {
446                out.push(Vec::new());
447            }
448            Err(e) => {
449                errors.push_for(None, e);
450                return Err(());
451            }
452        }
453    }
454    Ok(out)
455}
456
457/// The checks every tree's file list must pass regardless of where it came
458/// from — a real disk walk ([`phase_discovery`]) or a caller-supplied
459/// `discovered`/`CompileOptions.sources` list (#1077/#1081 review). An empty
460/// project (`bynk.project.no_sources`) signals a bail via `Err(())`; a
461/// file/directory name conflict is a non-fatal diagnostic.
462#[allow(clippy::result_unit_err)]
463pub fn check_discovered_files(
464    trees: &[(PathBuf, PathBuf)],
465    file_lists: &[Vec<PathBuf>],
466    errors: &mut ErrorSink,
467) -> Result<(), ()> {
468    if file_lists.iter().all(|f| f.is_empty()) {
469        errors.push_for(
470            None,
471            CompileError::new(
472                "bynk.project.no_sources",
473                Span::default(),
474                format!(
475                    "no `.bynk` source files found under {}",
476                    trees[0].0.display()
477                ),
478            ),
479        );
480        return Err(());
481    }
482    for ((root, _prefix), files) in trees.iter().zip(file_lists.iter()) {
483        if let Err(e) = check_file_directory_conflicts(root, files) {
484            errors.extend_for(None, e);
485        }
486    }
487    Ok(())
488}
489
490/// A memoized parse of one first-party synthetic source, keyed by the
491/// caller's `cache` — `inject_firstparty` passes one per registry entry.
492/// Finding #55/#65: the source text is a fixed `include_str!` constant, so its
493/// parse is a pure function of that constant and only needs computing once per
494/// process, not once per compile/analyse round. Which units a project injects
495/// is still decided fresh for every project from its own parsed
496/// `uses`/`consumes`; only the parse *result* is cached.
497/// T3.4 (R2.4): each first-party synthetic unit reserves its own 1M-wide
498/// `ExprId` block, spaced far above anything a real project's own file count
499/// could ever reach — see [`firstparty_parsed`]'s doc comment for why a fixed
500/// reservation, not a threaded counter, is the right shape here.
501pub const FIRSTPARTY_ID_BLOCK: u32 = 1_000_000;
502pub const FIRSTPARTY_ID_BASE: u32 = 1_000_000_000;
503
504/// #1956: the first `FileId` reserved for first-party synthetic units. Each
505/// unit's spans carry `FIRSTPARTY_FILE_ID_BASE + id_block` ([`firstparty_file_id`]),
506/// fixed for the same reason as its `ExprId` block: the parse is cached per
507/// process, so the id can't come from any one project's interner. The range
508/// sits just below `FileId::UNKNOWN` (`u32::MAX`), far above any id
509/// `parse_cache::file_id_for` hands a real file. Without an identity of their
510/// own, a first-party span counted as the error's own file, and a "declared
511/// here" label into `bynk.bynk` was drawn at the same offsets in the user's.
512pub const FIRSTPARTY_FILE_ID_BASE: u32 = 0xFFFF_0000;
513
514/// The `FileId` every span of first-party `unit` carries.
515pub fn firstparty_file_id(unit: &firstparty::Unit) -> FileId {
516    FileId(FIRSTPARTY_FILE_ID_BASE + unit.id_block)
517}
518
519/// The first-party unit whose spans carry `file`, if any.
520fn firstparty_unit_for(file: FileId) -> Option<&'static firstparty::Unit> {
521    firstparty::UNITS
522        .iter()
523        .find(|unit| firstparty_file_id(unit) == file)
524}
525
526pub fn firstparty_parsed(
527    cache: &'static OnceLock<Result<ParsedFile, Vec<CompileError>>>,
528    identity_path: &'static str,
529    src: &'static str,
530    kind: UnitKind,
531    // T3.4 (R2.4): a fixed base, not a live project counter — `cache` is a
532    // `OnceLock`, parsed once per *process*, and reused as-is across every
533    // later compile in that process regardless of how many real files that
534    // *particular* compile happens to have. A threaded counter can't work
535    // here (this parse doesn't know, and must never depend on, which compile
536    // triggers it first); a fixed, permanently-reserved range that no real
537    // project could ever grow into does. Call sites space their bases
538    // `FIRSTPARTY_ID_BLOCK` apart, one block per registry entry
539    // (`firstparty::Unit::id_block`), so first-party units can never collide
540    // with each other either, however many of them one project injects.
541    id_base: u32,
542    // #1956: the unit's reserved `FileId` ([`firstparty_file_id`]), stamped on
543    // every span so a label into it is never taken for the user's file.
544    file: FileId,
545) -> Result<ParsedFile, Vec<CompileError>> {
546    cache
547        .get_or_init(|| {
548            lexer::tokenize_in(src, file)
549                .map_err(|e| vec![e])
550                .and_then(|toks| {
551                    parser::parse_unit_with_warnings_from(&toks, src, &mut { id_base })
552                        .map(|(unit, _warnings)| unit)
553                })
554                .map(|unit| {
555                    ParsedFile::synthetic(
556                        PathBuf::from(identity_path),
557                        PathBuf::from(identity_path),
558                        src.to_string(),
559                        unit,
560                        kind,
561                    )
562                })
563        })
564        .clone()
565}
566
567/// #1663: every syntax error in `source`, from a recovering parse, when the
568/// strict parse failed with `strict` (its first), merged with it
569/// ([`bynk_syntax::parser::merge_syntax_errors`]). #2807: a lex error recovers too.
570fn all_syntax_errors(source: &str, strict: Vec<CompileError>) -> Vec<CompileError> {
571    let (tokens, lex_errors) = bynk_syntax::lexer::tokenize_recovering(source);
572    let recovered = bynk_syntax::parser::parse_units_recovering(&tokens, source).errors;
573    let recovered = bynk_syntax::lexer::without_lex_echoes(&lex_errors, &tokens, recovered);
574    bynk_syntax::parser::merge_syntax_errors(strict, recovered)
575}
576
577/// Phase 2: parse every discovered file into a `ParsedFile`, recording each
578/// file's source text into `snapshots` and any parse errors into `errors`.
579/// Then inject the first-party units the project consumes or uses
580/// (`inject_firstparty`). Returns the parsed units, the registry entries
581/// injected, and (#1710) each unit's [`BrokenDeclNames`]; signals a pipeline
582/// bail via `Err(())` when parsing produced errors and yielded no units at all.
583#[allow(clippy::too_many_arguments)]
584#[allow(clippy::result_unit_err)]
585pub fn phase_parse(
586    // R3.9 (#1113): one `(root, prefix)` pair per `Roots::trees` entry, not a
587    // hardcoded primary/secondary pair — every `include` tree is walked.
588    trees: &[(PathBuf, PathBuf)],
589    file_lists: &[Vec<PathBuf>],
590    overlay: &HashMap<PathBuf, String>,
591    errors: &mut ErrorSink,
592    snapshots: &mut Vec<(PathBuf, String)>,
593) -> Result<(Vec<ParsedFile>, InjectedUnits, BrokenDeclNames), ()> {
594    let mut parsed: Vec<ParsedFile> = Vec::new();
595    let mut broken: BrokenDeclNames = HashMap::new();
596    // P8.4 (#1515): `FileId`/`ExprId` allocation is no longer threaded through
597    // this function — `parse_sources` now resolves both through
598    // `bynk_project::parse_cache`'s own durable, process-lifetime counters
599    // (see that module's own doc comment, [DECISION D]), which trivially
600    // keeps the old within-one-call uniqueness guarantee T3.4/T3.5 named
601    // (global uniqueness implies uniqueness within any one call).
602    let parse_tree = |root: &Path,
603                      prefix: &Path,
604                      files: &[PathBuf],
605                      parsed: &mut Vec<ParsedFile>,
606                      broken: &mut BrokenDeclNames,
607                      errors: &mut ErrorSink,
608                      snapshots: &mut Vec<(PathBuf, String)>| {
609        for path in files {
610            // Tree-relative: what unit validation reads.
611            let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
612            // Slice 0 — project-relative: what *names* the file. Equal to `rel`
613            // for a single root (empty prefix).
614            let id = prefix.join(&rel);
615            let source = match read_source(path, overlay) {
616                Ok(s) => s,
617                Err(e) => {
618                    errors.push_for(
619                        Some(&id),
620                        CompileError::new(
621                            "bynk.project.read_failed",
622                            Span::default(),
623                            format!("could not read `{}`: {e}", path.display()),
624                        ),
625                    );
626                    continue;
627                }
628            };
629            snapshots.push((id.clone(), source.clone()));
630            match parse_sources(root, prefix, path, source) {
631                Ok((pfs, warnings)) => {
632                    parsed.extend(pfs);
633                    // ADR 0117: the sink classifies these as warnings — they
634                    // surface with the build but never gate it.
635                    errors.extend_for(Some(&id), warnings);
636                }
637                // #1663: the strict parse stops at a file's first syntax
638                // error. Report every one, from a recovering parse. #1710: the
639                // declarations that recovery kept are checked too, with the
640                // ones it skipped as known names (Decision B), so the file's
641                // other faults aren't hidden behind its syntax error. Nothing
642                // is emitted: the syntax errors already fail the build.
643                Err(errs) => {
644                    let source = snapshots.last().expect("pushed just above").1.clone();
645                    match parse_sources_recovering(root, prefix, path, source.clone()) {
646                        Some(recovered) => {
647                            errors.extend_for(
648                                Some(&id),
649                                bynk_syntax::parser::merge_syntax_errors(errs, recovered.errors),
650                            );
651                            // The parser records skipped names per file, so
652                            // each unit the file declares (a `commons` beside
653                            // its `suite`, say) gets them all: wider, but only
654                            // within the one file.
655                            for pf in &recovered.files {
656                                broken
657                                    .entry(pf.unit().name().joined())
658                                    .or_default()
659                                    .extend(recovered.broken_decl_names.iter().cloned());
660                            }
661                            parsed.extend(recovered.files);
662                        }
663                        None => errors.extend_for(Some(&id), all_syntax_errors(&source, errs)),
664                    }
665                }
666            }
667        }
668    };
669    for ((root, prefix), files) in trees.iter().zip(file_lists.iter()) {
670        parse_tree(
671            root,
672            prefix,
673            files,
674            &mut parsed,
675            &mut broken,
676            errors,
677            snapshots,
678        );
679    }
680    errors.register_parsed(&parsed);
681    if !errors.is_empty() && parsed.is_empty() {
682        return Err(());
683    }
684
685    let injected = inject_firstparty(&mut parsed, errors);
686    Ok((parsed, injected, broken))
687}
688
689/// The first-party units a project injected, as registry entries in ascending
690/// [`firstparty::Unit::id_block`] order. A unit whose source failed to parse is
691/// still listed, so its binding is still supplied. Its own `uses`/`consumes`
692/// cannot be read, though, so the units only it reaches are not injected: a
693/// malformed first-party source (which `every_first_party_source_parses` rejects
694/// in CI) reports its parse error and may add unresolved-name errors for those.
695pub type InjectedUnits = Vec<&'static firstparty::Unit>;
696
697/// Inject the first-party units the project reaches (standard-library S1,
698/// #1945). A unit in the [`firstparty::UNITS`] registry is reached when a parsed
699/// unit `consumes` it (an adapter) or `uses` it (a commons). The units it reaches
700/// in turn are its own source's `uses`/`consumes` lines, so injection repeats
701/// until nothing new is reached: the dependencies between first-party units
702/// (`bynk.map` uses `bynk.list`; the `bynk` adapter uses `bynk.locale.types`)
703/// come from their sources, never a hand-kept list. Each injected unit flows
704/// through the normal pipeline (tables, exports, emission, compose), and an
705/// adapter's binding is supplied by the toolchain (§4.2). Units are pushed in
706/// [`firstparty::Unit::id_block`] order, whatever order they were reached in.
707fn inject_firstparty(parsed: &mut Vec<ParsedFile>, errors: &mut ErrorSink) -> InjectedUnits {
708    const N: usize = firstparty::UNITS.len();
709    static CACHES: [OnceLock<Result<ParsedFile, Vec<CompileError>>>; N] =
710        [const { OnceLock::new() }; N];
711    let reaches = |pf: &ParsedFile, unit: &firstparty::Unit| match unit.kind {
712        firstparty::UnitKind::Adapter => {
713            pf.consumes().iter().any(|c| c.target.joined() == unit.name)
714        }
715        firstparty::UnitKind::Commons => pf.uses().iter().any(|u| u.target.joined() == unit.name),
716    };
717    let mut reached: Vec<Option<Option<ParsedFile>>> = vec![None; N];
718    loop {
719        let mut grew = false;
720        for (i, unit) in firstparty::UNITS.iter().enumerate() {
721            if reached[i].is_some() {
722                continue;
723            }
724            let injected = reached.iter().flatten().flatten();
725            if !parsed.iter().chain(injected).any(|pf| reaches(pf, unit)) {
726                continue;
727            }
728            let kind = match unit.kind {
729                firstparty::UnitKind::Adapter => UnitKind::Adapter,
730                firstparty::UnitKind::Commons => UnitKind::Commons,
731            };
732            let parse = firstparty_parsed(
733                &CACHES[i],
734                unit.identity_path,
735                unit.source,
736                kind,
737                FIRSTPARTY_ID_BASE + unit.id_block * FIRSTPARTY_ID_BLOCK,
738                firstparty_file_id(unit),
739            );
740            reached[i] = Some(match parse {
741                Ok(pf) => Some(pf),
742                Err(errs) => {
743                    errors.extend_for(None, errs);
744                    None
745                }
746            });
747            grew = true;
748        }
749        if !grew {
750            break;
751        }
752    }
753    let mut order: Vec<usize> = (0..N).filter(|&i| reached[i].is_some()).collect();
754    order.sort_by_key(|&i| firstparty::UNITS[i].id_block);
755    for &i in &order {
756        if let Some(Some(pf)) = reached[i].take() {
757            parsed.push(pf);
758        }
759    }
760    order.into_iter().map(|i| &firstparty::UNITS[i]).collect()
761}
762
763/// S4a (#1966): resolve each derived capability (`capability Sessions = Kv`)
764/// against the capabilities its context flattens in with `consumes U { Kv }`,
765/// and record it. A valid one enters the unit's capability table with its
766/// base's operations, so every later check treats it as an ordinary
767/// capability; its provision is implied (the base's platform provider, bound to
768/// the instance's own Worker binding). Runs after
769/// [`crate::symbols::record_flattened_caps`].
770pub fn phase_resolve_derived(
771    groups: &BTreeMap<String, Vec<usize>>,
772    kinds: &BTreeMap<String, UnitKind>,
773    parsed: &[ParsedFile],
774    layout: &bynk_project::worker_layout::WorkerLayout,
775    unit_tables: &mut HashMap<String, UnitTable>,
776    errors: &mut ErrorSink,
777) {
778    // #3536: recorded here, the phase that already holds the groups, kinds,
779    // parsed files and mutable tables of both pipelines.
780    let selections = consume_selections(groups, kinds, parsed);
781    crate::symbols::record_unselected_consumed_types(unit_tables, &selections);
782    for (name, indices) in groups {
783        for &i in indices {
784            if parsed[i].is_synthetic() {
785                continue;
786            }
787            let path = parsed[i].identity_path();
788            for item in parsed[i].items() {
789                let CommonsItem::Capability(c) = item else {
790                    continue;
791                };
792                let Some(d) = &c.derived else { continue };
793                if kinds.get(name) != Some(&UnitKind::Context) {
794                    errors.push_for(
795                        Some(&path),
796                        CompileError::new(
797                            "bynk.capability.derived_outside_context",
798                            c.span,
799                            format!(
800                                "derived capability `{}` is declared outside a context",
801                                c.name.name
802                            ),
803                        )
804                        .with_note("a named instance of a platform resource belongs to the context that owns its data"),
805                    );
806                    continue;
807                }
808                let Some(table) = unit_tables.get(name) else {
809                    continue;
810                };
811                let Some(owner) = table.flattened_caps.get(&d.base.name).cloned() else {
812                    errors.push_for(
813                        Some(&path),
814                        CompileError::new(
815                            "bynk.capability.unknown_base",
816                            d.base.span,
817                            format!(
818                                "`{}` is not a capability this context selects with `consumes U {{ … }}`",
819                                d.base.name
820                            ),
821                        )
822                        .with_note(format!(
823                            "a derived capability's base is a platform capability, selected by name: `consumes bynk.cloudflare {{ {} }}`",
824                            d.base.name
825                        )),
826                    );
827                    continue;
828                };
829                let Some(kind) = crate::firstparty::instantiable(&owner, &d.base.name) else {
830                    let mut error = CompileError::new(
831                        "bynk.capability.base_not_instantiable",
832                        d.base.span,
833                        format!(
834                            "`{owner}.{}` has no named instances: a derived capability's base must be a platform resource kind",
835                            d.base.name
836                        ),
837                    );
838                    // #3300: a one-per-Worker capability is used bare.
839                    if crate::firstparty::singleton(&owner, &d.base.name).is_some() {
840                        error = error.with_note(format!(
841                            "a Worker has one `{0}` binding, so `{0}` is used bare: write `given {0}` where it is needed, not a capability over it",
842                            d.base.name
843                        ));
844                    }
845                    errors.push_for(Some(&path), error);
846                    continue;
847                };
848                // Interop I5 (#1972): each option's value, once valid.
849                let mut options: Vec<(String, crate::symbols::OptionValue)> = Vec::new();
850                for ann in &d.annotations {
851                    if let Some(option_kind) = kind.option_kind(&ann.name.name) {
852                        if options.iter().any(|(o, _)| *o == ann.name.name) {
853                            errors.push_for(
854                                Some(&path),
855                                CompileError::new(
856                                    "bynk.capability.invalid_option",
857                                    ann.span,
858                                    format!("`@{}` is given twice", ann.name.name),
859                                )
860                                .with_note("an instance takes each option once"),
861                            );
862                        } else if let Some(value) =
863                            instance_option_value(ann, option_kind, &d.base.name, &path, errors)
864                        {
865                            // A Worker the build itself makes is a Bynk
866                            // context: deploy and dev read any build Worker
867                            // as a project edge, never a foreign one, so it
868                            // is reached with `consumes` (review of #2008).
869                            let own = match &value {
870                                crate::symbols::OptionValue::Str(value)
871                                    if ann.name.name == firstparty::SERVICE_WORKER_OPTION =>
872                                {
873                                    kinds.iter().find(|(unit, kind)| {
874                                        **kind == UnitKind::Context
875                                            && layout.script_name(unit) == *value
876                                    })
877                                }
878                                _ => None,
879                            };
880                            if let Some((context, _)) = own {
881                                errors.push_for(
882                                    Some(&path),
883                                    CompileError::new(
884                                        "bynk.capability.invalid_option",
885                                        ann.span,
886                                        format!(
887                                            "`{}` is this project's context `{context}`, not a Worker outside it",
888                                            layout.script_name(context)
889                                        ),
890                                    )
891                                    .with_note(format!(
892                                        "reach a Bynk context with `consumes {context}`, which checks its contract"
893                                    )),
894                                );
895                            } else {
896                                options.push((ann.name.name.clone(), value));
897                            }
898                        }
899                    }
900                    if kind.option_kind(&ann.name.name).is_none() {
901                        let allowed = if d.base.name == "Analytics" {
902                            // P3b (#2582): the dataset's name is derived.
903                            "`Analytics` instances take no options: `bynk deploy` names the dataset for the context and the capability".to_string()
904                        } else if kind.options.is_empty() {
905                            format!("`{}` instances take no options", d.base.name)
906                        } else {
907                            format!(
908                                "`{}` instances take {}",
909                                d.base.name,
910                                kind.option_names()
911                                    .map(|o| format!("`@{o}`"))
912                                    .collect::<Vec<_>>()
913                                    .join(", ")
914                            )
915                        };
916                        errors.push_for(
917                            Some(&path),
918                            CompileError::new(
919                                "bynk.capability.unknown_option",
920                                ann.span,
921                                format!(
922                                    "`@{}` is not an option of a `{}` instance",
923                                    ann.name.name, d.base.name
924                                ),
925                            )
926                            .with_note(allowed),
927                        );
928                    }
929                }
930                for required in kind.required {
931                    if !d.annotations.iter().any(|a| a.name.name == *required) {
932                        errors.push_for(
933                            Some(&path),
934                            CompileError::new(
935                                "bynk.capability.missing_option",
936                                c.span,
937                                format!("a `{}` instance needs `@{required}(…)`", d.base.name),
938                            )
939                            .with_note(format!("write `{}`", instance_example(kind))),
940                        );
941                    }
942                }
943                if table.exported_capabilities.contains(&c.name.name) {
944                    errors.push_for(
945                        Some(&path),
946                        CompileError::new(
947                            "bynk.exports.derived_capability",
948                            c.span,
949                            format!("derived capability `{}` cannot be exported", c.name.name),
950                        )
951                        .with_note("an instance's data belongs to this context; another context reaches it through this context's services"),
952                    );
953                }
954                let ops = unit_tables
955                    .get(&owner)
956                    .and_then(|t| t.capabilities.get(&d.base.name))
957                    .map(|base| base.ops.clone())
958                    .unwrap_or_default();
959                let binding = crate::worker_bindings::instance_binding_name(
960                    kind.binding_prefix,
961                    &c.name.name,
962                );
963                let table = unit_tables.get_mut(name).expect("checked above");
964                // L7 (#2414): Workers Cache is one Worker-wide setting, so a
965                // context declares at most one `EdgeCache` instance.
966                if crate::symbols::is_edge_cache_base(&owner, &d.base.name)
967                    && let Some((earlier, _)) =
968                        table.derived.iter().find(|(_, inst)| inst.is_edge_cache())
969                {
970                    errors.push_for(
971                        Some(&path),
972                        CompileError::new(
973                            "bynk.cloudflare.edge_cache_duplicate",
974                            c.span,
975                            format!(
976                                "context `{name}` already declares `EdgeCache` instance `{earlier}`"
977                            ),
978                        )
979                        .with_note(format!(
980                            "the edge cache is one setting for the whole Worker, so one instance turns it on and purges it; use `{earlier}`"
981                        )),
982                    );
983                    continue;
984                }
985                if let Some(decl) = table.capabilities.get_mut(&c.name.name) {
986                    decl.ops = ops;
987                }
988                table.derived.insert(
989                    c.name.name.clone(),
990                    crate::symbols::DerivedInstance {
991                        base_unit: owner,
992                        base_cap: d.base.name.clone(),
993                        binding,
994                        options,
995                        span: c.span,
996                    },
997                );
998            }
999        }
1000    }
1001    phase_edge_cache_reach(groups, parsed, unit_tables, errors);
1002}
1003
1004/// L7 (#2414, Decision D): an `EdgeCache` purge reaches the cache only from
1005/// the Worker's own `fetch`, so the instance is refused where anything else
1006/// runs: an agent handler (a Durable Object,
1007/// `bynk.cloudflare.edge_cache_in_agent`), a queue consumer
1008/// (`bynk.cloudflare.edge_cache_in_queue`), an `on schedule` handler
1009/// (`bynk.cloudflare.edge_cache_in_schedule`: deployed, its purge answers
1010/// `success` and clears nothing), and an exported capability, which a consumer
1011/// builds in its own Worker (`bynk.cloudflare.edge_cache_exported`).
1012/// A handler reaches the instance
1013/// through its own `given`, or through a local capability whose provider's
1014/// `given` does, at any depth.
1015pub fn phase_edge_cache_reach(
1016    groups: &BTreeMap<String, Vec<usize>>,
1017    parsed: &[ParsedFile],
1018    unit_tables: &HashMap<String, UnitTable>,
1019    errors: &mut ErrorSink,
1020) {
1021    for (name, indices) in groups {
1022        let Some(table) = unit_tables.get(name) else {
1023            continue;
1024        };
1025        // Each capability that reaches an instance, with the instance it
1026        // reaches.
1027        let mut reaches: BTreeMap<String, String> = table
1028            .derived
1029            .iter()
1030            .filter(|(_, d)| d.is_edge_cache())
1031            .map(|(cap, _)| (cap.clone(), cap.clone()))
1032            .collect();
1033        if reaches.is_empty() {
1034            continue;
1035        }
1036        loop {
1037            let mut grew = false;
1038            for (cap, provider) in &table.providers {
1039                if reaches.contains_key(cap) {
1040                    continue;
1041                }
1042                let via = provider
1043                    .given
1044                    .iter()
1045                    .filter(|g| !g.is_cross_context())
1046                    .find_map(|g| reaches.get(g.key()).cloned());
1047                if let Some(instance) = via {
1048                    reaches.insert(cap.clone(), instance);
1049                    grew = true;
1050                }
1051            }
1052            if !grew {
1053                break;
1054            }
1055        }
1056        for &i in indices {
1057            let path = parsed[i].identity_path();
1058            for item in parsed[i].items() {
1059                // A consuming context builds an exported capability's provider
1060                // in its own Worker, whose purge would miss this one's cache.
1061                if let CommonsItem::Capability(c) = item
1062                    && c.derived.is_none()
1063                    && table.exported_capabilities.contains(&c.name.name)
1064                    && let Some(instance) = reaches.get(&c.name.name)
1065                {
1066                    errors.push_for(
1067                        Some(&path),
1068                        CompileError::new(
1069                            "bynk.cloudflare.edge_cache_exported",
1070                            c.span,
1071                            format!(
1072                                "exported capability `{}` reaches `EdgeCache` instance `{instance}`, which purges only from this context's own Worker",
1073                                c.name.name
1074                            ),
1075                        )
1076                        .with_note(
1077                            "a context that consumes it would build its provider in its own Worker, whose purge misses this Worker's cache; export a service that purges instead",
1078                        ),
1079                    );
1080                }
1081                // Review of #2417: an opted-in Worker shares a `scope: public`
1082                // `2xx` with every later caller. `public` lets the cache store
1083                // even a response to a request carrying `Authorization` (RFC
1084                // 9111 §3.5, confirmed deployed), so such a route must not
1085                // depend on who calls it.
1086                if let CommonsItem::Service(svc) = item
1087                    && matches!(svc.protocol, ServiceProtocol::Http)
1088                {
1089                    for h in &svc.handlers {
1090                        let public = h.annotations.iter().any(|a| {
1091                            a.name.name == "cache"
1092                                && a.args.iter().any(|arg| {
1093                                    arg.label.as_ref().is_some_and(|l| l.name == "scope")
1094                                        && matches!(&arg.value.kind, ExprKind::Ident(id) if id.name == "public")
1095                                })
1096                        });
1097                        let Some(by) = h.by_clause.as_ref().or(svc.default_by.as_ref()) else {
1098                            continue;
1099                        };
1100                        let closed = by.actors.iter().find(|a| {
1101                            let single = ByClause {
1102                                binder: None,
1103                                actors: vec![(*a).clone()],
1104                                span: by.span,
1105                            };
1106                            !crate::actors::sum_has_open_member(&single, &table.actors)
1107                        });
1108                        if let (true, Some(actor)) = (public, closed) {
1109                            errors.push_for(
1110                                Some(&path),
1111                                CompileError::new(
1112                                    "bynk.cloudflare.edge_cache_public_authenticated",
1113                                    by.span,
1114                                    format!(
1115                                        "a `@cache(scope: public)` route by `{}` would share one caller's response with every caller at Cloudflare's edge",
1116                                        actor.name
1117                                    ),
1118                                )
1119                                .with_note(format!(
1120                                    "context `{name}` declares `EdgeCache`, and the edge cache keys a response by its URL alone; use `scope: private`, or serve the route `by Visitor`"
1121                                )),
1122                            );
1123                        }
1124                    }
1125                }
1126                let (handlers, code, place, note) = match item {
1127                    CommonsItem::Agent(a) => (
1128                        &a.handlers,
1129                        "bynk.cloudflare.edge_cache_in_agent",
1130                        format!("agent `{}`", a.name.name),
1131                        "an agent runs in a Durable Object, whose purge would not reach this Worker's cache; purge from the service handler that calls the agent",
1132                    ),
1133                    CommonsItem::Service(svc)
1134                        if matches!(svc.protocol, ServiceProtocol::Queue { .. }) =>
1135                    {
1136                        (
1137                            &svc.handlers,
1138                            "bynk.cloudflare.edge_cache_in_queue",
1139                            format!("queue consumer `{}`", svc.name.name),
1140                            "a queue consumer is not the entrypoint the cache serves, and its purge is not known to reach that cache; purge from a service handler",
1141                        )
1142                    }
1143                    CommonsItem::Service(svc) if matches!(svc.protocol, ServiceProtocol::Cron) => (
1144                        &svc.handlers,
1145                        "bynk.cloudflare.edge_cache_in_schedule",
1146                        format!("`on schedule` service `{}`", svc.name.name),
1147                        "Cloudflare accepts a purge from a cron run but it clears nothing from the cache the Worker's `fetch` serves; purge from a service handler",
1148                    ),
1149                    _ => continue,
1150                };
1151                for h in handlers {
1152                    for g in h.given.iter().filter(|g| !g.is_cross_context()) {
1153                        let Some(instance) = reaches.get(g.key()) else {
1154                            continue;
1155                        };
1156                        let how = if g.key() == instance {
1157                            String::new()
1158                        } else {
1159                            format!(" (through `{}`)", g.key())
1160                        };
1161                        errors.push_for(
1162                            Some(&path),
1163                            CompileError::new(
1164                                code,
1165                                g.span,
1166                                format!(
1167                                    "{place} reaches `EdgeCache` instance `{instance}`{how}, which purges only from the Worker's `fetch`"
1168                                ),
1169                            )
1170                            .with_note(note),
1171                        );
1172                    }
1173                }
1174            }
1175        }
1176    }
1177}
1178
1179/// The example instance declaration a note about `kind` shows: every
1180/// required option set to a sample value (P3, #2342, so a `RateLimit` note
1181/// shows `@limit(100) @period(60.seconds)`, not a Worker name).
1182pub(crate) fn instance_example(kind: &firstparty::Instantiable) -> String {
1183    let name = match kind.capability {
1184        "Service" => "Billing",
1185        "RateLimit" => "LoginLimit",
1186        "EdgeCache" => "Edge",
1187        "Queue" => "OrderEvents",
1188        "Analytics" => "Signups",
1189        "D1" => "Orders",
1190        "StoredSecret" => "StripeKey",
1191        "Email" => "Mail",
1192        "Postgres" => "Main",
1193        "MySql" => "Legacy",
1194        "Vectorize" => "Docs",
1195        "Container" => "Renderer",
1196        "AiSearch" => "Kb",
1197        "MtlsCertificate" => "Backend",
1198        _ => "Archives",
1199    };
1200    let mut out = format!("capability {name} = {}", kind.capability);
1201    for required in kind.required {
1202        out.push_str(&format!(" @{required}({})", option_sample(required)));
1203    }
1204    out
1205}
1206
1207/// A sample value of option `option`, as a note writes it.
1208fn option_sample(option: &str) -> &'static str {
1209    match option {
1210        firstparty::R2_JURISDICTION_OPTION => "\"eu\"",
1211        firstparty::RATELIMIT_LIMIT_OPTION => "100",
1212        firstparty::RATELIMIT_PERIOD_OPTION => "60.seconds",
1213        firstparty::QUEUE_NAME_OPTION => "\"order-events\"",
1214        firstparty::STORED_SECRET_STORE_OPTION => "\"payments\"",
1215        firstparty::STORED_SECRET_SECRET_OPTION => "\"stripe-live\"",
1216        firstparty::EMAIL_TO_OPTION => "\"[email protected]\"",
1217        firstparty::EMAIL_ALLOWED_RECIPIENTS_OPTION | firstparty::EMAIL_ALLOWED_SENDERS_OPTION => {
1218            "[\"[email protected]\"]"
1219        }
1220        firstparty::AI_SEARCH_INSTANCE_OPTION => "\"support-docs\"",
1221        firstparty::MTLS_CERTIFICATE_OPTION => "\"acme-client\"",
1222        firstparty::VECTORIZE_DIMENSIONS_OPTION => "768",
1223        firstparty::VECTORIZE_METRIC_OPTION => "\"cosine\"",
1224        firstparty::VECTORIZE_INDEXED_OPTION => "[\"category:string\"]",
1225        firstparty::CONTAINER_BUILD_OPTION => "\"containers/renderer\"",
1226        firstparty::CONTAINER_PORT_OPTION => "8080",
1227        firstparty::CONTAINER_SLEEP_AFTER_OPTION => "5.minutes",
1228        firstparty::CONTAINER_INSTANCE_TYPE_OPTION => "\"lite\"",
1229        firstparty::CONTAINER_FORWARD_OPTION => "[\"API_KEY\"]",
1230        _ => "\"legacy-billing\"",
1231    }
1232}
1233
1234/// Why a `Vectorize` `@dimensions` literal is outside Cloudflare's range of
1235/// 32 to 1536: `("least", 32)` or `("most", 1536)`. `None` when it is inside, or
1236/// not positive (which the positive-`Int` check reports).
1237fn vectorize_dimensions_problem(value: i64) -> Option<(&'static str, i64)> {
1238    if value > firstparty::VECTORIZE_MAX_DIMENSIONS {
1239        Some(("most", firstparty::VECTORIZE_MAX_DIMENSIONS))
1240    } else if value > 0 && value < firstparty::VECTORIZE_MIN_DIMENSIONS {
1241        Some(("least", firstparty::VECTORIZE_MIN_DIMENSIONS))
1242    } else {
1243        None
1244    }
1245}
1246
1247/// #3513 A: an `MtlsCertificate` `@certificate` that is not a certificate name. A
1248/// certificate is named by whoever uploaded it, in any text, so only a name the account
1249/// could not have given one is refused: an empty one, or one with a control character.
1250fn mtls_certificate_error(
1251    base: &str,
1252    option: &str,
1253    text: &str,
1254    span: bynk_syntax::span::Span,
1255) -> Option<CompileError> {
1256    (base == "MtlsCertificate"
1257        && option == crate::firstparty::MTLS_CERTIFICATE_OPTION
1258        && (text.trim().is_empty() || text.chars().any(char::is_control)))
1259    .then(|| {
1260        CompileError::new(
1261            "bynk.capability.invalid_option",
1262            span,
1263            format!("{text:?} is not a certificate name a `{base}` can reach"),
1264        )
1265        .with_note(
1266            "name the certificate as it was uploaded to the account (`wrangler mtls-certificate list` shows it), for example `@certificate(\"acme-client\")`",
1267        )
1268    })
1269}
1270
1271/// #3480: an `AiSearch` `@instance` that is not an instance name. The instance
1272/// is a path segment of the REST call that links it, and Cloudflare's API
1273/// documents an instance id as 1 to 64 lowercase letters, digits, hyphens and
1274/// underscores.
1275fn ai_search_instance_error(
1276    base: &str,
1277    option: &str,
1278    text: &str,
1279    span: bynk_syntax::span::Span,
1280) -> Option<CompileError> {
1281    (base == "AiSearch"
1282        && option == crate::firstparty::AI_SEARCH_INSTANCE_OPTION
1283        && !is_ai_search_instance_name(text))
1284    .then(|| {
1285        CompileError::new(
1286            "bynk.capability.invalid_option",
1287            span,
1288            format!("`{text}` is not an instance name a `{base}` can reach"),
1289        )
1290        .with_note(
1291            "an instance name is 1 to 64 lowercase letters, digits, `-` or `_`, the form Cloudflare's API documents",
1292        )
1293    })
1294}
1295
1296/// #3479 (DECISION A): a `Vectorize` `@metric` outside the closed set.
1297fn vectorize_metric_error(
1298    base: &str,
1299    option: &str,
1300    text: &str,
1301    span: bynk_syntax::span::Span,
1302) -> Option<CompileError> {
1303    (base == "Vectorize"
1304        && option == crate::firstparty::VECTORIZE_METRIC_OPTION
1305        && !crate::firstparty::VECTORIZE_METRICS.contains(&text))
1306    .then(|| {
1307        CompileError::new(
1308            "bynk.capability.invalid_option",
1309            span,
1310            format!("`{text}` is not a distance metric a `{base}` index can use"),
1311        )
1312        .with_note(format!(
1313            "the metrics are {}",
1314            crate::firstparty::VECTORIZE_METRICS
1315                .iter()
1316                .map(|m| format!("`\"{m}\"`"))
1317                .collect::<Vec<_>>()
1318                .join(", ")
1319        ))
1320    })
1321}
1322
1323/// Interop I5 (#1972): the value of one instance option: one positional
1324/// literal of the option's kind (P3, #2342). `@worker("name")` names a Worker,
1325/// so it must be a Worker name as Cloudflare takes one: lowercase letters,
1326/// digits, `-` and `_`, at most 63 characters, not starting or ending with
1327/// `-`. `@jurisdiction` is one of R2's; `@limit` a positive `Int`; `@period`
1328/// one of the rate limiting windows; a `Queue`'s `@name` a queue name (P2,
1329/// #2578). `None`, with the error pushed, when the
1330/// value is not one of these.
1331fn instance_option_value(
1332    ann: &bynk_syntax::ast::Annotation,
1333    kind: firstparty::OptionKind,
1334    base: &str,
1335    path: &std::path::Path,
1336    errors: &mut ErrorSink,
1337) -> Option<crate::symbols::OptionValue> {
1338    use crate::symbols::OptionValue;
1339    let option = ann.name.name.as_str();
1340    let invalid = |span, message: String| {
1341        CompileError::new("bynk.capability.invalid_option", span, message).with_note(format!(
1342            "write `@{option}({})`, for example",
1343            option_sample(option)
1344        ))
1345    };
1346    let [arg] = ann.args.as_slice() else {
1347        errors.push_for(
1348            Some(path),
1349            invalid(
1350                ann.span,
1351                format!("`@{option}` takes one positional argument"),
1352            ),
1353        );
1354        return None;
1355    };
1356    if arg.label.is_some() {
1357        errors.push_for(
1358            Some(path),
1359            invalid(
1360                ann.span,
1361                format!("`@{option}` takes one positional argument"),
1362            ),
1363        );
1364        return None;
1365    }
1366    let value = match (kind, &arg.value.kind) {
1367        (firstparty::OptionKind::Str, ExprKind::StrLit(value)) => OptionValue::Str(value.clone()),
1368        (firstparty::OptionKind::Str, _) => {
1369            errors.push_for(
1370                Some(path),
1371                invalid(arg.span, format!("`@{option}` takes a string literal")),
1372            );
1373            return None;
1374        }
1375        (firstparty::OptionKind::StrList, ExprKind::ListLit(items, ..)) => {
1376            let mut out = Vec::new();
1377            for item in items {
1378                let ExprKind::StrLit(text) = &item.kind else {
1379                    errors.push_for(
1380                        Some(path),
1381                        invalid(
1382                            item.span,
1383                            format!("`@{option}` takes a list of string literals"),
1384                        ),
1385                    );
1386                    return None;
1387                };
1388                out.push(text.clone());
1389            }
1390            if out.is_empty() {
1391                errors.push_for(
1392                    Some(path),
1393                    invalid(
1394                        arg.span,
1395                        format!(
1396                            "`@{option}` takes at least one {}",
1397                            if base == "Container" {
1398                                "entry"
1399                            } else {
1400                                "address"
1401                            }
1402                        ),
1403                    ),
1404                );
1405                return None;
1406            }
1407            OptionValue::List(out)
1408        }
1409        (firstparty::OptionKind::StrList, _) => {
1410            errors.push_for(
1411                Some(path),
1412                invalid(
1413                    arg.span,
1414                    format!("`@{option}` takes a list of string literals"),
1415                ),
1416            );
1417            return None;
1418        }
1419        (firstparty::OptionKind::PositiveInt, ExprKind::IntLit { value, .. })
1420            if base == "Vectorize"
1421                && option == firstparty::VECTORIZE_DIMENSIONS_OPTION
1422                && vectorize_dimensions_problem(*value).is_some() =>
1423        {
1424            let (bound, limit) = vectorize_dimensions_problem(*value).unwrap_or_default();
1425            errors.push_for(
1426                Some(path),
1427                CompileError::new(
1428                    "bynk.capability.invalid_option",
1429                    arg.span,
1430                    format!("`@{option}` is at {bound} {limit} for a `{base}` index"),
1431                )
1432                .with_note("Cloudflare creates an index only with a dimension count in its supported range, 32 to 1536"),
1433            );
1434            return None;
1435        }
1436        (firstparty::OptionKind::PositiveInt, ExprKind::IntLit { value, .. })
1437            if base == "Container"
1438                && option == firstparty::CONTAINER_PORT_OPTION
1439                && crate::containers::port_problem(*value).is_some() =>
1440        {
1441            errors.push_for(
1442                Some(path),
1443                CompileError::new(
1444                    "bynk.capability.invalid_option",
1445                    arg.span,
1446                    format!("`@{option}` is not a port a `{base}` can listen on"),
1447                )
1448                .with_note("a port is a TCP port, 1 to 65535"),
1449            );
1450            return None;
1451        }
1452        (firstparty::OptionKind::PositiveInt, ExprKind::IntLit { value, .. }) if *value > 0 => {
1453            OptionValue::Int(*value)
1454        }
1455        (firstparty::OptionKind::PositiveInt, _) => {
1456            errors.push_for(
1457                Some(path),
1458                invalid(
1459                    arg.span,
1460                    format!("`@{option}` takes a positive `Int` literal"),
1461                ),
1462            );
1463            return None;
1464        }
1465        (firstparty::OptionKind::Duration, _) if base == "Container" => OptionValue::Seconds(
1466            container_sleep_after(&arg.value.kind, arg.span, path, errors)?,
1467        ),
1468        (firstparty::OptionKind::Duration, ExprKind::DurationLit { millis, .. })
1469            if *millis % 1000 == 0 && firstparty::RATELIMIT_PERIODS.contains(&(*millis / 1000)) =>
1470        {
1471            OptionValue::Seconds(*millis / 1000)
1472        }
1473        (firstparty::OptionKind::Duration, _) => {
1474            errors.push_for(
1475                Some(path),
1476                CompileError::new(
1477                    "bynk.capability.invalid_option",
1478                    arg.span,
1479                    format!("`@{option}` must be a window a `{base}` offers"),
1480                )
1481                .with_note(format!(
1482                    "the windows are {}",
1483                    firstparty::RATELIMIT_PERIODS
1484                        .iter()
1485                        .map(|s| format!("`{s}.seconds`"))
1486                        .collect::<Vec<_>>()
1487                        .join(" and ")
1488                )),
1489            );
1490            return None;
1491        }
1492    };
1493    if let OptionValue::List(items) = &value {
1494        // #3477: a `Container`'s `@forward` names Worker secrets.
1495        if base == "Container" {
1496            return container_forward_ok(items, ann, path, errors).then_some(value);
1497        }
1498        // #3479: a `Vectorize`'s `@indexed` entries are metadata indexes.
1499        if base == "Vectorize" {
1500            return vectorize_indexed_ok(items, ann, path, errors).then_some(value);
1501        }
1502        // Every address is checked as the platform will see it (#3302).
1503        if !email_list_ok(items, base, ann, path, errors) {
1504            return None;
1505        }
1506        return Some(value);
1507    }
1508    let OptionValue::Str(text) = &value else {
1509        return Some(value);
1510    };
1511    if base == "Email" && option == crate::firstparty::EMAIL_TO_OPTION && !is_email_address(text) {
1512        errors.push_for(
1513            Some(path),
1514            invalid(
1515                ann.span,
1516                format!(
1517                    "`{}` is not an email address a `{base}` can use",
1518                    text.escape_debug()
1519                ),
1520            )
1521            .with_note("an address is `name@domain`, with no spaces or control characters"),
1522        );
1523        return None;
1524    }
1525    if option == crate::firstparty::R2_JURISDICTION_OPTION
1526        && !r2_jurisdiction_ok(text, base, ann, path, errors)
1527    {
1528        return None;
1529    }
1530    if let Some(error) = vectorize_metric_error(base, option, text, ann.span) {
1531        errors.push_for(Some(path), error);
1532        return None;
1533    }
1534    // #3477: a `Container`'s `@build` and `@instanceType`.
1535    if base == "Container" && !container_str_ok(text, option, ann, path, errors) {
1536        return None;
1537    }
1538    // Hyperdrive H5 (#3322, DECISION B): `@tls` is one of a closed set.
1539    if option == crate::firstparty::MYSQL_TLS_OPTION
1540        && !crate::firstparty::MYSQL_TLS_MODES
1541            .iter()
1542            .any(|(mode, _)| mode == text)
1543    {
1544        errors.push_for(
1545            Some(path),
1546            CompileError::new(
1547                "bynk.capability.invalid_option",
1548                ann.span,
1549                format!("`{text}` is not a TLS mode a `{base}` can use"),
1550            )
1551            .with_note(format!(
1552                "the modes are {}; `\"required\"` is the default",
1553                crate::firstparty::MYSQL_TLS_MODES
1554                    .iter()
1555                    .map(|(m, _)| format!("`\"{m}\"`"))
1556                    .collect::<Vec<_>>()
1557                    .join(", ")
1558            )),
1559        );
1560        return None;
1561    }
1562    if option == crate::firstparty::SERVICE_WORKER_OPTION && !is_worker_name(text) {
1563        errors.push_for(
1564            Some(path),
1565            CompileError::new(
1566                "bynk.capability.invalid_option",
1567                ann.span,
1568                format!("`{text}` is not a Worker name a `{base}` can reach"),
1569            )
1570            .with_note(
1571                "a Worker name is 1 to 63 lowercase letters, digits, `-` or `_`, and does not start or end with `-`",
1572            ),
1573        );
1574        return None;
1575    }
1576    if let Some(error) = ai_search_instance_error(base, option, text, ann.span) {
1577        errors.push_for(Some(path), error);
1578        return None;
1579    }
1580    if let Some(error) = mtls_certificate_error(base, option, text, ann.span) {
1581        errors.push_for(Some(path), error);
1582        return None;
1583    }
1584    if base == "StoredSecret"
1585        && matches!(
1586            option,
1587            crate::firstparty::STORED_SECRET_STORE_OPTION
1588                | crate::firstparty::STORED_SECRET_SECRET_OPTION
1589        )
1590        && !is_secrets_store_name(text)
1591    {
1592        let what = if option == crate::firstparty::STORED_SECRET_STORE_OPTION {
1593            "store"
1594        } else {
1595            "secret"
1596        };
1597        errors.push_for(
1598            Some(path),
1599            CompileError::new(
1600                "bynk.capability.invalid_option",
1601                ann.span,
1602                format!("`{text}` is not a {what} name a `{base}` can read"),
1603            )
1604            .with_note("a Secrets Store name is 1 to 255 letters, digits, `-` or `_`"),
1605        );
1606        return None;
1607    }
1608    if option == crate::firstparty::QUEUE_NAME_OPTION && base == "Queue" && !is_queue_name(text) {
1609        errors.push_for(
1610            Some(path),
1611            CompileError::new(
1612                "bynk.capability.invalid_option",
1613                ann.span,
1614                format!("`{text}` is not a queue name a `{base}` can send to"),
1615            )
1616            .with_note(
1617                "a queue name is 1 to 63 lowercase letters, digits or `-`, and starts and ends with a letter or digit",
1618            ),
1619        );
1620        return None;
1621    }
1622    Some(value)
1623}
1624
1625/// #3302: whether every entry of an `Email` instance's address list is an
1626/// address the platform takes. Pushes the error and returns `false` otherwise.
1627fn email_list_ok(
1628    items: &[String],
1629    base: &str,
1630    ann: &bynk_syntax::ast::Annotation,
1631    path: &std::path::Path,
1632    errors: &mut ErrorSink,
1633) -> bool {
1634    let option = ann.name.name.as_str();
1635    let Some(item) = items.iter().find(|item| !is_email_address(item)) else {
1636        return true;
1637    };
1638    errors.push_for(
1639        Some(path),
1640        CompileError::new(
1641            "bynk.capability.invalid_option",
1642            ann.span,
1643            format!(
1644                "`{}` is not an email address a `{base}` can use",
1645                item.escape_debug()
1646            ),
1647        )
1648        .with_note(format!(
1649            "write `@{option}({})`, for example",
1650            option_sample(option)
1651        ))
1652        .with_note("an address is `name@domain`, with no spaces or control characters"),
1653    );
1654    false
1655}
1656
1657/// Whether `text` is a jurisdiction an `R2` bucket can be pinned to. Pushes the
1658/// error and returns `false` otherwise.
1659fn r2_jurisdiction_ok(
1660    text: &str,
1661    base: &str,
1662    ann: &bynk_syntax::ast::Annotation,
1663    path: &std::path::Path,
1664    errors: &mut ErrorSink,
1665) -> bool {
1666    if crate::firstparty::R2_JURISDICTIONS.contains(&text) {
1667        return true;
1668    }
1669    errors.push_for(
1670        Some(path),
1671        CompileError::new(
1672            "bynk.capability.invalid_option",
1673            ann.span,
1674            format!("`{text}` is not a jurisdiction a `{base}` bucket can be pinned to"),
1675        )
1676        .with_note(format!(
1677            "the jurisdictions are {}",
1678            crate::firstparty::R2_JURISDICTIONS
1679                .iter()
1680                .map(|j| format!("`\"{j}\"`"))
1681                .collect::<Vec<_>>()
1682                .join(" and ")
1683        )),
1684    );
1685    false
1686}
1687
1688/// #3477: whether a `Container`'s string option `option` is a value the
1689/// platform takes: `@build` a directory inside the project, `@instanceType` one
1690/// of a closed set. Pushes the error and returns `false` otherwise.
1691fn container_str_ok(
1692    text: &str,
1693    option: &str,
1694    ann: &bynk_syntax::ast::Annotation,
1695    path: &std::path::Path,
1696    errors: &mut ErrorSink,
1697) -> bool {
1698    let error = if option == firstparty::CONTAINER_BUILD_OPTION {
1699        crate::containers::build_path_problem(text).map(|problem| {
1700            CompileError::new(
1701                "bynk.container.build_path",
1702                ann.span,
1703                format!("`@build(\"{}\")` {problem}", text.escape_debug()),
1704            )
1705            .with_note(
1706                "`@build` names the directory that holds the `Dockerfile`, relative to the project root, for example `@build(\"containers/renderer\")`",
1707            )
1708        })
1709    } else if option == firstparty::CONTAINER_INSTANCE_TYPE_OPTION
1710        && !firstparty::CONTAINER_INSTANCE_TYPES.contains(&text)
1711    {
1712        Some(
1713            CompileError::new(
1714                "bynk.capability.invalid_option",
1715                ann.span,
1716                format!("`{text}` is not an instance type a `Container` can start with"),
1717            )
1718            .with_note(format!(
1719                "the instance types are {}",
1720                firstparty::CONTAINER_INSTANCE_TYPES
1721                    .iter()
1722                    .map(|t| format!("`\"{t}\"`"))
1723                    .collect::<Vec<_>>()
1724                    .join(", ")
1725            )),
1726        )
1727    } else {
1728        None
1729    };
1730    let Some(error) = error else {
1731        return true;
1732    };
1733    errors.push_for(Some(path), error);
1734    false
1735}
1736
1737/// #3477: a `Container`'s `@sleepAfter` in whole seconds: more than zero and at
1738/// most 6 hours. Pushes the error and returns `None` otherwise.
1739fn container_sleep_after(
1740    kind: &ExprKind,
1741    span: bynk_syntax::span::Span,
1742    path: &std::path::Path,
1743    errors: &mut ErrorSink,
1744) -> Option<i64> {
1745    let seconds = match kind {
1746        ExprKind::DurationLit { millis, .. } => crate::containers::sleep_after_seconds(*millis),
1747        _ => None,
1748    };
1749    if seconds.is_none() {
1750        errors.push_for(
1751            Some(path),
1752            CompileError::new(
1753                "bynk.capability.invalid_option",
1754                span,
1755                "`@sleepAfter` is not a time a `Container` can sleep after".to_string(),
1756            )
1757            .with_note(
1758                "write a whole number of seconds, more than zero and at most 6 hours, for example `5.minutes`",
1759            ),
1760        );
1761    }
1762    seconds
1763}
1764
1765/// #3477 (DECISION J): whether a `Container`'s `@forward` is a list of Worker
1766/// secret names a process environment can hold. Pushes the error and returns
1767/// `false` otherwise.
1768fn container_forward_ok(
1769    items: &[String],
1770    ann: &bynk_syntax::ast::Annotation,
1771    path: &std::path::Path,
1772    errors: &mut ErrorSink,
1773) -> bool {
1774    let Some(message) = crate::containers::forward_problem(items) else {
1775        return true;
1776    };
1777    errors.push_for(
1778        Some(path),
1779        CompileError::new("bynk.capability.invalid_option", ann.span, message).with_note(
1780            "write `@forward([\"API_KEY\"])`: the names of Worker secrets, each a letter or `_` then letters, digits or `_`; their values are never written into source or config",
1781        ),
1782    );
1783    false
1784}
1785
1786/// #3479 (DECISION C): whether a `Vectorize`'s `@indexed` entries are a list of
1787/// at most [`firstparty::VECTORIZE_MAX_INDEXED`] metadata indexes, each
1788/// `name:type` with a type the platform indexes, none repeated. Pushes the
1789/// error and returns `false` otherwise.
1790fn vectorize_indexed_ok(
1791    items: &[String],
1792    ann: &bynk_syntax::ast::Annotation,
1793    path: &std::path::Path,
1794    errors: &mut ErrorSink,
1795) -> bool {
1796    let types = firstparty::VECTORIZE_INDEXED_TYPES;
1797    let problem = if items.len() > firstparty::VECTORIZE_MAX_INDEXED {
1798        Some(format!(
1799            "an index has at most {} metadata indexes, and `@indexed` lists {}",
1800            firstparty::VECTORIZE_MAX_INDEXED,
1801            items.len()
1802        ))
1803    } else {
1804        items.iter().enumerate().find_map(|(i, item)| {
1805            let Some((name, ty)) = item.split_once(':') else {
1806                return Some(format!("`{}` is not `name:type`", item.escape_debug()));
1807            };
1808            if !types.contains(&ty) {
1809                return Some(format!(
1810                    "`{}` is not a type a metadata index holds",
1811                    ty.escape_debug()
1812                ));
1813            }
1814            if !is_metadata_property(name) {
1815                return Some(format!(
1816                    "`{}` is not a metadata property a filter can name",
1817                    name.escape_debug()
1818                ));
1819            }
1820            items[..i]
1821                .iter()
1822                .any(|p| p.split_once(':').is_some_and(|(n, _)| n == name))
1823                .then(|| format!("`{name}` is listed twice"))
1824        })
1825    };
1826    let Some(message) = problem else {
1827        return true;
1828    };
1829    errors.push_for(
1830        Some(path),
1831        CompileError::new("bynk.capability.invalid_option", ann.span, message).with_note(format!(
1832            "write `@indexed([\"category:string\", \"year:number\"])`: at most {} entries, each `name:type` with the type {}",
1833            firstparty::VECTORIZE_MAX_INDEXED,
1834            types
1835                .iter()
1836                .map(|t| format!("`{t}`"))
1837                .collect::<Vec<_>>()
1838                .join(", ")
1839        )),
1840    );
1841    false
1842}
1843
1844/// Whether `name` is a metadata property a filter can name (#3479): a dotted
1845/// path whose every segment is non-empty, has no `"` or `|` and does not start
1846/// with `$`, at most 512 characters in all. A dot nests (`author.name`).
1847fn is_metadata_property(name: &str) -> bool {
1848    name.chars().count() <= 512
1849        && name
1850            .split('.')
1851            .all(|seg| !seg.is_empty() && !seg.starts_with('$') && !seg.contains(['"', '|']))
1852}
1853
1854/// Whether `name` is a Cloudflare queue name ([`instance_option_value`]):
1855/// Cloudflare allows letters, digits and `-`, starting and ending with a letter
1856/// or digit, 1 to 63 characters. Lowercase only, as every name `bynk deploy`
1857/// derives is, and so `env_qualify`'s `-<env>` suffix reads the same. The suffix
1858/// counts toward the 63, which this cannot see: a name near the limit can
1859/// overflow once qualified, and nothing checks that before `wrangler queues create`.
1860pub(crate) fn is_queue_name(name: &str) -> bool {
1861    let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit();
1862    (1..=63).contains(&name.len())
1863        && name.bytes().all(|b| alnum(b) || b == b'-')
1864        && name.bytes().next().is_some_and(alnum)
1865        && name.bytes().last().is_some_and(alnum)
1866}
1867
1868/// Whether `text` can be an email address (#3302): `local@domain`, one `@`,
1869/// both sides non-empty, a host name after it, no whitespace, control or angle-bracket characters.
1870/// The platform judges the rest; this only keeps a typo, or a header-shaped
1871/// string, out of a deploy-time policy that is written into configuration.
1872pub(crate) fn is_email_address(text: &str) -> bool {
1873    let Some((local, domain)) = text.split_once('@') else {
1874        return false;
1875    };
1876    !local.is_empty()
1877        && !domain.is_empty()
1878        // A host name: the domain is looked up by the deploy.
1879        && domain
1880            .bytes()
1881            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
1882        && !text
1883            .chars()
1884            .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>' | '"' | ','))
1885}
1886
1887/// Whether `name` is a Secrets Store's or a secret's name as Cloudflare takes
1888/// one ([`instance_option_value`], #3301): 1 to 255 letters, digits, `-` or
1889/// `_`.
1890pub(crate) fn is_secrets_store_name(name: &str) -> bool {
1891    (1..=255).contains(&name.len())
1892        && name
1893            .bytes()
1894            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
1895}
1896
1897/// Whether `name` can name an AI Search instance ([`instance_option_value`]).
1898fn is_ai_search_instance_name(name: &str) -> bool {
1899    (1..=64).contains(&name.len())
1900        && name
1901            .bytes()
1902            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1903}
1904
1905/// Whether `name` is a Cloudflare Worker name ([`instance_option_value`]).
1906fn is_worker_name(name: &str) -> bool {
1907    (1..=63).contains(&name.len())
1908        && name
1909            .bytes()
1910            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1911        && !name.starts_with('-')
1912        && !name.ends_with('-')
1913}
1914
1915/// #1710: for each unit with a file the strict parse rejected, the names of
1916/// the declarations recovery skipped there. References to them, from any file
1917/// that can see the unit, are known names, not unknown ones (#1663's Decision
1918/// B); see [`crate::check_pipeline::prepare_unit_check_ctx`].
1919pub type BrokenDeclNames = HashMap<String, Vec<String>>;
1920
1921/// The `include` tree that discovered `pf`, found by matching its absolute
1922/// path against each tree's root — not `trees[0]` unconditionally, since
1923/// R3.9 (#1113) lets a file live under any `include` tree, not just the
1924/// first. Falls back to `trees[0]` for a `pf` with no `abs_path` (unreachable
1925/// for a real adapter: only synthetic units, which never declare `binding`,
1926/// go without one) or if it somehow matches none. The longest matching root
1927/// wins, in case one `include` tree is nested inside another.
1928///
1929/// A `trees` root is only absolute when `Roots`'s own `project_root` is — a
1930/// relative project root (`bynk compile .`, the ordinary CLI shape) leaves
1931/// every tree root relative, while `pf.abs_path()` (`bynk-project`'s
1932/// `parse_sources`, via `std::path::absolute`) is always absolute. Comparing
1933/// them directly with `starts_with` would never match, silently collapsing
1934/// this back to the `trees[0]` bug it exists to fix. Each root is resolved
1935/// through the same `std::path::absolute` before comparing, matching
1936/// `abs_path`'s own normalisation exactly rather than requiring the caller
1937/// to have already absolutised `Roots::project_root`.
1938pub fn tree_root_for<'a>(trees: &'a [(PathBuf, PathBuf)], pf: &ParsedFile) -> &'a Path {
1939    let Some(abs) = pf.abs_path() else {
1940        return trees[0].0.as_path();
1941    };
1942    trees
1943        .iter()
1944        .filter_map(|(root, _)| {
1945            std::path::absolute(root)
1946                .ok()
1947                .map(|abs_root| (root, abs_root))
1948        })
1949        .filter(|(_, abs_root)| abs.starts_with(abs_root))
1950        .max_by_key(|(root, _)| root.as_os_str().len())
1951        .map(|(root, _)| root.as_path())
1952        .unwrap_or_else(|| trees[0].0.as_path())
1953}
1954
1955/// #2321: resolve an adapter binding's `includes [ … ]` list. Each path is
1956/// relative to the adapter's own directory, must stay inside it (no absolute
1957/// path, no `..`), must be a `.wasm`, and must be unique once normalised; the
1958/// file is read beside the binding (a dependency's from beside the file it was
1959/// read from, like the binding itself, #2223). Reports the four
1960/// `bynk.adapter.include_*` diagnostics and skips the offending entry.
1961fn resolve_binding_includes(
1962    pf: &ParsedFile,
1963    a: &AdapterDecl,
1964    b: &BindingDecl,
1965    adapter_dir: &Path,
1966    adapter_src_dir: &Path,
1967    errors: &mut ErrorSink,
1968) -> Vec<IncludedFile> {
1969    let adapter = a.name.joined();
1970    let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
1971    let mut out = Vec::new();
1972    for inc in &b.includes {
1973        let raw = Path::new(&inc.path);
1974        let escapes = raw.is_absolute()
1975            || raw.components().any(|c| {
1976                matches!(
1977                    c,
1978                    std::path::Component::ParentDir
1979                        | std::path::Component::RootDir
1980                        | std::path::Component::Prefix(_)
1981                )
1982            });
1983        if escapes {
1984            errors.push_for(
1985                Some(&pf.identity_path()),
1986                CompileError::new(
1987                    "bynk.adapter.include_outside",
1988                    inc.span,
1989                    format!(
1990                        "adapter `{adapter}` includes `{}`, which is outside the adapter's directory",
1991                        inc.path
1992                    ),
1993                )
1994                .with_note("an included path is relative to the adapter's file and may not be absolute or contain `..`"),
1995            );
1996            continue;
1997        }
1998        let rel = normalize_rel(raw);
1999        if rel.extension().and_then(|e| e.to_str()) != Some("wasm") {
2000            errors.push_for(
2001                Some(&pf.identity_path()),
2002                CompileError::new(
2003                    "bynk.adapter.include_kind",
2004                    inc.span,
2005                    format!(
2006                        "adapter `{adapter}` includes `{}`, which is not a `.wasm` file",
2007                        inc.path
2008                    ),
2009                )
2010                .with_note("only WebAssembly modules (`.wasm`) can be included beside a binding"),
2011            );
2012            continue;
2013        }
2014        if !seen.insert(rel.clone()) {
2015            errors.push_for(
2016                Some(&pf.identity_path()),
2017                CompileError::new(
2018                    "bynk.adapter.include_duplicate",
2019                    inc.span,
2020                    format!("adapter `{adapter}` includes `{}` more than once", inc.path),
2021                )
2022                .with_note("remove the repeated entry"),
2023            );
2024            continue;
2025        }
2026        match read_adapter_include(&adapter_src_dir.join(&rel)) {
2027            Ok(bytes) => out.push(IncludedFile {
2028                output_path: normalize_rel(&adapter_dir.join(&rel)),
2029                bytes,
2030            }),
2031            Err(e) => errors.push_for(
2032                Some(&pf.identity_path()),
2033                CompileError::new(
2034                    "bynk.adapter.include_missing",
2035                    inc.span,
2036                    format!(
2037                        "adapter `{adapter}` includes `{}`, which could not be read ({e})",
2038                        inc.path
2039                    ),
2040                )
2041                .with_note("the path is resolved relative to the adapter's source file"),
2042            ),
2043        }
2044    }
2045    out
2046}
2047
2048/// Phase 3: group the parsed units by qualified name (production units, unit
2049/// tests, and integration suites tracked separately), run the per-directory
2050/// and path/name consistency checks, enforce the reserved `bynk` namespace and
2051/// the adapter `binding` rules, resolve each adapter's binding module, and fold
2052/// the adapters' pinned npm dependencies. Pushes diagnostics into `errors` and
2053/// returns the production `groups`/`kinds`, the `test`/`integration` groups, the
2054/// resolved `adapter_bindings`, and the collected `npm_deps`.
2055#[allow(clippy::type_complexity)]
2056#[allow(clippy::too_many_arguments)]
2057pub fn phase_group(
2058    parsed: &[ParsedFile],
2059    trees: &[(PathBuf, PathBuf)],
2060    platform: Platform,
2061    injected: &[&'static firstparty::Unit],
2062    overlay: &HashMap<PathBuf, String>,
2063    errors: &mut ErrorSink,
2064) -> (
2065    BTreeMap<String, Vec<usize>>,
2066    BTreeMap<String, UnitKind>,
2067    BTreeMap<String, Vec<usize>>,
2068    BTreeMap<String, Vec<usize>>,
2069    HashMap<String, AdapterBinding>,
2070    std::collections::BTreeMap<String, String>,
2071) {
2072    // Tests (v0.7) are tracked separately from production units. Their
2073    // `target` joined-name can intentionally coincide with a commons or
2074    // context name; they don't enter the production groups/kinds maps.
2075    let mut groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2076    let mut kinds: BTreeMap<String, UnitKind> = BTreeMap::new();
2077    let mut test_groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2078    // v0.16: integration tests are tracked by suite name, separately again from
2079    // unit tests — their `name()` is the synthetic `integration <suite>`.
2080    let mut integration_groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2081    for (i, pf) in parsed.iter().enumerate() {
2082        let name = pf.unit().name().joined();
2083        if pf.kind() == UnitKind::Integration {
2084            integration_groups.entry(name).or_default().push(i);
2085        } else if pf.kind() == UnitKind::Test {
2086            test_groups.entry(name).or_default().push(i);
2087        } else {
2088            groups.entry(name.clone()).or_default().push(i);
2089            kinds.entry(name).or_insert(pf.kind());
2090        }
2091    }
2092    // #696: the consistency checks pair each error with the project-relative
2093    // path of the file its primary span belongs to, so the CLI renders them
2094    // with ariadne source context rather than the plain fallback.
2095    if let Err(e) = check_directory_name_consistency(parsed) {
2096        for (path, err) in e {
2097            errors.push_for(Some(&path), err);
2098        }
2099    }
2100    if let Err(e) = check_directory_kind_consistency(parsed) {
2101        errors.extend_for(None, e);
2102    }
2103    // A group must agree on kind across all its files (different name but
2104    // same kind is fine; same name but different kind is an error).
2105    if let Err(e) = check_group_kind_consistency(parsed, &groups) {
2106        for (path, err) in e {
2107            errors.push_for(Some(&path), err);
2108        }
2109    }
2110    // #1885 (DECISION D): a unit split across files carries at most one
2111    // module doc.
2112    if let Err(e) = check_group_module_docs(parsed, &groups) {
2113        for (path, err) in e {
2114            errors.push_for(Some(&path), err);
2115        }
2116    }
2117    // Each *source* unit's file path must match its declared qualified name.
2118    // v0.113 (DECISION S): a `suite` has no path-identity requirement — it names
2119    // its target and is legal in any file — so test-ness carries no path check.
2120    if let Err(e) = check_path_name_alignment(parsed) {
2121        for (path, err) in e {
2122            errors.push_for(Some(&path), err);
2123        }
2124    }
2125
2126    // v0.20a: function types are confined to non-boundary positions. P5.2:
2127    // this used to be an injected hook (`function_type_boundary_check`) so
2128    // `run_checks` and the new analysis entry point could reach it without
2129    // `bynk-check` reaching back into `bynk-emit`; now that the check lives
2130    // here too, it's a direct call at the exact point the hook used to fire,
2131    // preserving diagnostic order for both callers with no hook needed.
2132    phase_function_type_boundaries(parsed, errors);
2133
2134    // v0.17: the `bynk` root namespace is reserved for the toolchain. No user
2135    // unit of any kind may be named `bynk` or `bynk.*` (§3.4).
2136    for pf in parsed {
2137        if pf.is_synthetic() {
2138            continue;
2139        }
2140        let qn = pf.unit().name();
2141        if qn.parts.first().is_some_and(|p| p.name == "bynk") {
2142            errors.push_for(Some(&pf.identity_path()),
2143                CompileError::new(
2144                    "bynk.namespace.reserved",
2145                    qn.span,
2146                    format!(
2147                        "`{}` uses the reserved `bynk` namespace — the `bynk` root is reserved for the toolchain's conformance surface",
2148                        qn.joined()
2149                    ),
2150                )
2151                .with_note("rename the unit so its first segment is not `bynk`"),
2152            );
2153        }
2154    }
2155
2156    // v0.17: an adapter that declares any external provider must name a
2157    // `binding` module to supply the implementation symbols (§3.5). First-party
2158    // (synthetic) adapters omit the clause — the toolchain supplies the binding.
2159    for pf in parsed {
2160        if pf.is_synthetic() {
2161            continue;
2162        }
2163        if let Some(a) = pf.adapter() {
2164            let has_external = a
2165                .items
2166                .iter()
2167                .any(|it| matches!(it, CommonsItem::Provider(p) if p.external));
2168            if has_external && a.binding.is_none() {
2169                errors.push_for(Some(&pf.identity_path()),
2170                    CompileError::new(
2171                        "bynk.adapter.no_binding",
2172                        a.span,
2173                        format!(
2174                            "adapter `{}` declares an external provider but has no `binding` clause to supply its implementation",
2175                            a.name.joined()
2176                        ),
2177                    )
2178                    .with_note(
2179                        "add a `binding \"<module>\"` clause naming the TypeScript module that exports the provider symbols",
2180                    ),
2181                );
2182            }
2183        }
2184    }
2185
2186    // v0.17: resolve each adapter's binding module (relative to the adapter's
2187    // source file) and read it, so compose can import the external provider
2188    // symbols and the binding is copied into the output for the `tsc` gate.
2189    let mut adapter_bindings: HashMap<String, AdapterBinding> = HashMap::new();
2190    // v0.17/v0.19: the toolchain supplies each injected first-party adapter's
2191    // binding — the `bynk` surface's per platform, a platform adapter's single
2192    // one (the lock check rejects other `--platform` selections).
2193    for unit in injected {
2194        if let Some((output_path, content)) = unit.binding_for(platform) {
2195            adapter_bindings.insert(
2196                unit.name.to_string(),
2197                AdapterBinding {
2198                    output_path: PathBuf::from(output_path),
2199                    content: content.to_string(),
2200                    includes: Vec::new(),
2201                },
2202            );
2203        }
2204    }
2205    for pf in parsed {
2206        let Some(a) = pf.adapter() else { continue };
2207        let Some(b) = &a.binding else { continue };
2208        let pf_source_path = pf.source_path();
2209        let adapter_dir = pf_source_path.parent().unwrap_or(Path::new(""));
2210        let out_rel = normalize_rel(&adapter_dir.join(&b.module));
2211        // #2223: a dependency file's `source_path` is its output layout
2212        // (`deps/<org>/<package>/…`), so its binding is found beside the file
2213        // it was read from.
2214        let src_abs = match (pf.package(), pf.abs_path()) {
2215            (Some(_), Some(abs)) => {
2216                let dir = abs.parent().unwrap_or(Path::new("")).to_path_buf();
2217                dir.join(normalize_rel(Path::new(&b.module)))
2218            }
2219            _ => tree_root_for(trees, pf).join(&out_rel),
2220        };
2221        match read_adapter_binding(&src_abs, overlay) {
2222            Ok(content) => {
2223                // The adapter file's own directory on disk — what includes are
2224                // relative to (the binding may sit in a subdirectory of it).
2225                let adapter_src_dir = match (pf.package(), pf.abs_path()) {
2226                    (Some(_), Some(abs)) => abs.parent().unwrap_or(Path::new("")).to_path_buf(),
2227                    _ => tree_root_for(trees, pf).join(adapter_dir),
2228                };
2229                let includes =
2230                    resolve_binding_includes(pf, a, b, adapter_dir, &adapter_src_dir, errors);
2231                adapter_bindings.insert(
2232                    a.name.joined(),
2233                    AdapterBinding {
2234                        output_path: out_rel,
2235                        content,
2236                        includes,
2237                    },
2238                );
2239            }
2240            Err(e) => {
2241                errors.push_for(Some(&pf.identity_path()),
2242                    CompileError::new(
2243                        "bynk.adapter.no_binding",
2244                        b.module_span,
2245                        format!(
2246                            "adapter `{}` names binding module `{}`, which could not be read ({e})",
2247                            a.name.joined(),
2248                            b.module
2249                        ),
2250                    )
2251                    .with_note(
2252                        "the binding path is resolved relative to the adapter's source file; author the `.binding.ts` there",
2253                    ),
2254                );
2255            }
2256        }
2257    }
2258
2259    // v0.17: collect adapter npm dependencies for `package.json`, rejecting
2260    // unpinned ranges ([DECISION L] stub — fold + pin-check only, no allow-list).
2261    // #2201: two entries for one package must agree on the range; a different
2262    // range is refused rather than intersected or overwritten.
2263    let mut npm_deps: std::collections::BTreeMap<String, String> =
2264        std::collections::BTreeMap::new();
2265    // package → (adapter, its file's identity path, entry span) of the first entry.
2266    let mut first_dep: HashMap<String, (String, PathBuf, Span)> = HashMap::new();
2267    for pf in parsed {
2268        let Some(a) = pf.adapter() else { continue };
2269        let Some(b) = &a.binding else { continue };
2270        for dep in &b.requires {
2271            if is_unpinned_range(&dep.range) {
2272                errors.push_for(Some(&pf.identity_path()),
2273                    CompileError::new(
2274                        "bynk.requires.unpinned_dependency",
2275                        dep.span,
2276                        format!(
2277                            "dependency `{}` has an unpinned version range `{}` — pin a concrete range (e.g. `^1.2.0`)",
2278                            dep.package, dep.range
2279                        ),
2280                    )
2281                    .with_note(
2282                        "unpinned ranges (`*`, `latest`, …) make builds irreproducible and are rejected",
2283                    ),
2284                );
2285                continue;
2286            }
2287            let adapter = a.name.joined();
2288            let identity = pf.identity_path();
2289            if conflicts_with_first_party_pin(dep, &adapter, &identity, errors) {
2290                continue;
2291            }
2292            if let Some(range) = npm_deps.get(&dep.package) {
2293                if *range != dep.range {
2294                    let (first_adapter, first_path, first_span) = &first_dep[&dep.package];
2295                    let message = if *first_adapter == adapter {
2296                        format!(
2297                            "adapter `{adapter}` requires `{}` at both `{range}` and `{}`",
2298                            dep.package, dep.range
2299                        )
2300                    } else {
2301                        format!(
2302                            "adapter `{adapter}` requires `{}` at `{}`, but adapter `{first_adapter}` requires it at `{range}`",
2303                            dep.package, dep.range
2304                        )
2305                    };
2306                    let mut err =
2307                        CompileError::new("bynk.requires.conflicting_range", dep.span, message);
2308                    if *first_path == identity {
2309                        err = err.with_label(*first_span, "first required here");
2310                    }
2311                    errors.push_for(
2312                        Some(&identity),
2313                        err.with_note(format!(
2314                            "`{}` is first required at `{range}` by adapter `{first_adapter}` (in `{}`); the project installs one version of each package, so every adapter must state the same range",
2315                            dep.package,
2316                            first_path
2317                                .components()
2318                                .map(|c| c.as_os_str().to_string_lossy())
2319                                .collect::<Vec<_>>()
2320                                .join("/")
2321                        )),
2322                    );
2323                }
2324                continue;
2325            }
2326            first_dep.insert(dep.package.clone(), (adapter, identity, dep.span));
2327            npm_deps.insert(dep.package.clone(), dep.range.clone());
2328        }
2329    }
2330
2331    (
2332        groups,
2333        kinds,
2334        test_groups,
2335        integration_groups,
2336        adapter_bindings,
2337        npm_deps,
2338    )
2339}
2340
2341/// ADR 0799 C: the toolchain pins its own npm packages exactly, and a project
2342/// installs one version of each package, so an adapter may name such a package
2343/// only at that version. Reports `bynk.requires.conflicting_range` and says so.
2344fn conflicts_with_first_party_pin(
2345    dep: &bynk_syntax::ast::RequiresDep,
2346    adapter: &str,
2347    identity: &Path,
2348    errors: &mut ErrorSink,
2349) -> bool {
2350    let Some(pin) = crate::firstparty::FIRST_PARTY_NPM
2351        .iter()
2352        .find(|p| p.package == dep.package && p.version != dep.range)
2353    else {
2354        return false;
2355    };
2356    errors.push_for(
2357        Some(identity),
2358        CompileError::new(
2359            "bynk.requires.conflicting_range",
2360            dep.span,
2361            format!(
2362                "adapter `{adapter}` requires `{}` at `{}`, but the toolchain pins it at `{}`",
2363                dep.package, dep.range, pin.version
2364            ),
2365        )
2366        .with_note(
2367            "the toolchain's own binding uses this package at an exact version; an adapter that needs it must require that version",
2368        ),
2369    );
2370    true
2371}
2372
2373/// v0.20a: apply the function-type boundary confinement to every serialisable
2374/// or boundary-crossing position in a file's items: record fields and sum
2375/// payloads (types can cross contexts and persist), service/agent handler
2376/// signatures (the Workers wire), capability operation signatures (kept out
2377/// in v0.20a — see ADR 0030), agent state fields, and agent keys. Free `fn`
2378/// signatures are deliberately NOT walked — they are the non-boundary home
2379/// of function types.
2380///
2381/// #696: each diagnostic is paired with the project-relative `identity_path` of
2382/// the file whose items produced it, so the CLI renders it against that file's
2383/// source.
2384///
2385/// P5.2 (`design/tracks/semantics-in-the-checker.md` §6): relocated verbatim
2386/// from `bynk-emit/src/project/validate.rs`'s `check_function_type_boundaries`
2387/// — category 6 of `analysis.rs`'s own seven-category accounting. Previously
2388/// reached only through `phase_group`'s optional `function_type_boundary_check`
2389/// hook (`Some` from `run_checks`, `None` from the new entry point); that hook
2390/// is gone — [`phase_group`] itself now calls this function directly, at the
2391/// exact point the hook used to fire, so both callers see it in the same
2392/// diagnostic-ordering position as before and can no longer drift on whether
2393/// the check runs at all.
2394pub fn phase_function_type_boundaries(parsed: &[ParsedFile], errors: &mut ErrorSink) {
2395    // v0.174 (#592): the boundary check now also rejects a *recursive* generic
2396    // record (`reject_fn_types`' `App` arm), which needs the type declarations to
2397    // walk the containment graph. Build the project-wide table once — a generic
2398    // referenced from one file may be declared in another.
2399    let types = collect_type_decls(parsed.iter().flat_map(|pf| pf.items()));
2400    for pf in parsed {
2401        let mut file_errors: Vec<CompileError> = Vec::new();
2402        check_function_type_boundary_items(pf.items(), &types, &mut file_errors);
2403        for err in file_errors {
2404            errors.push_for(Some(&pf.identity_path()), err);
2405        }
2406    }
2407}
2408
2409/// v0.174 (#592): a `name -> TypeDecl` table over a set of items, for the
2410/// recursive-generic boundary walk. Relocated alongside
2411/// `phase_function_type_boundaries` (P5.2) — public since `bynk-emit`'s
2412/// single-file compile path (`lib.rs`) also needs it, across the crate
2413/// boundary this relocation now draws.
2414pub fn collect_type_decls<'a>(
2415    items: impl Iterator<Item = &'a CommonsItem>,
2416) -> HashMap<String, Arc<TypeDecl>> {
2417    let mut out = HashMap::new();
2418    for item in items {
2419        match item {
2420            CommonsItem::Type(t) => {
2421                out.entry(t.name.name.clone())
2422                    .or_insert_with(|| Arc::new(t.clone()));
2423            }
2424            // Events track, slice 0 (spine #936): an event's synthetic
2425            // `TypeDecl` joins the same table, so a field referencing an
2426            // event type recurses into it exactly like any other type.
2427            CommonsItem::Event(e) => {
2428                out.entry(e.name.name.clone())
2429                    .or_insert_with(|| Arc::new(e.as_type_decl()));
2430            }
2431            _ => {}
2432        }
2433    }
2434    out
2435}
2436
2437/// #3192: a generic type may refer to itself only uniformly (its own parameters,
2438/// in order); any other recursive edge is polymorphic recursion, refused at the
2439/// declaration with `bynk.generics.polymorphic_recursion`. Uniform recursion
2440/// declares and works in memory and is refused only where a codec is required.
2441fn check_polymorphic_recursion(
2442    decl: &TypeDecl,
2443    types: &HashMap<String, Arc<TypeDecl>>,
2444    errors: &mut Vec<CompileError>,
2445) {
2446    for (callee, span) in bynk_syntax::ast::polymorphic_recursion_edges(decl, types) {
2447        let name = &decl.name.name;
2448        let params = decl
2449            .type_params
2450            .iter()
2451            .map(|p| p.name.name.as_str())
2452            .collect::<Vec<_>>()
2453            .join(", ");
2454        let note = if callee == *name {
2455            format!(
2456                "a recursive generic type must pass its parameters through unchanged, as `{callee}[{params}]`"
2457            )
2458        } else {
2459            format!(
2460                "a mutually recursive generic may be applied only to `{name}`'s own type parameters ({params}) or to types that mention none; wrapping a parameter (`List[T]`) makes the set of instantiations unbounded"
2461            )
2462        };
2463        errors.push(
2464            CompileError::new(
2465                "bynk.generics.polymorphic_recursion",
2466                span,
2467                format!(
2468                    "`{name}` refers to `{callee}` with arguments other than its own type parameters — polymorphic recursion generates an unbounded set of instantiations"
2469                ),
2470            )
2471            .with_note(note),
2472        );
2473    }
2474}
2475
2476/// Item-level body of the boundary confinement, shared with the single-file
2477/// (legacy) compile path in `bynk-emit`'s `lib.rs`. Relocated alongside
2478/// `phase_function_type_boundaries` (P5.2).
2479pub fn check_function_type_boundary_items(
2480    items: &[CommonsItem],
2481    types: &HashMap<String, Arc<TypeDecl>>,
2482    errors: &mut Vec<CompileError>,
2483) {
2484    for item in items {
2485        match item {
2486            CommonsItem::Type(t) => match &t.body {
2487                TypeBody::Record(r) => {
2488                    check_polymorphic_recursion(t, types, errors);
2489                    for f in &r.fields {
2490                        reject_fn_types(&f.type_ref, RECORD_FIELD, types, errors);
2491                    }
2492                }
2493                TypeBody::Sum(s) => {
2494                    check_polymorphic_recursion(t, types, errors);
2495                    for v in &s.variants {
2496                        for p in &v.payload {
2497                            reject_fn_types(&p.type_ref, SUM_PAYLOAD, types, errors);
2498                        }
2499                    }
2500                }
2501                TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
2502            },
2503            // Events track, slice 0 (spine #936): an event's fields are
2504            // boundary values (an emission crosses a context boundary),
2505            // so the same record-field rule applies as for a `type`.
2506            CommonsItem::Event(e) => {
2507                for f in &e.body.fields {
2508                    reject_fn_types(&f.type_ref, "an event field", types, errors);
2509                }
2510            }
2511            CommonsItem::Capability(c) => {
2512                for op in &c.ops {
2513                    for p in &op.params {
2514                        reject_fn_types(&p.type_ref, CAPABILITY_SIGNATURE, types, errors);
2515                    }
2516                    // v0.102 (§2.9.1): a capability operation may *produce* a
2517                    // held value — it is the canonical held source — so an
2518                    // `Effect[Connection[F]]` return is admitted.
2519                    if !type_ref_is_held(&op.return_type) {
2520                        reject_fn_types(&op.return_type, CAPABILITY_SIGNATURE, types, errors);
2521                    }
2522                }
2523            }
2524            CommonsItem::Service(s) => {
2525                for h in &s.handlers {
2526                    for p in &h.params {
2527                        // #2341 (decision A): an HTTP handler's `headers` is
2528                        // the one place `RequestHeaders` may appear.
2529                        let http_headers = matches!(h.kind, HandlerKind::Http { .. })
2530                            && ((p.name.name == "headers"
2531                                && matches!(p.type_ref, TypeRef::RequestHeaders(_)))
2532                                // #2854: and `query` is the one place `RequestQuery` may.
2533                                || (p.name.name == "query"
2534                                    && matches!(p.type_ref, TypeRef::RequestQuery(_)))
2535                                // #3277: and `cookies` the one place `RequestCookies` may.
2536                                || (p.name.name == "cookies"
2537                                    && matches!(p.type_ref, TypeRef::RequestCookies(_))));
2538                        // #2341 (decision C): and `on rejected`'s parameter is
2539                        // the one place `BoundaryRejection` may appear.
2540                        let http_headers = http_headers
2541                            || (h.kind == HandlerKind::Rejected
2542                                && matches!(p.type_ref, TypeRef::BoundaryRejection(_)));
2543                        // v0.102 (§2.9.4): the framework may supply a held
2544                        // value as a handler parameter (the `on open`
2545                        // connection), so a `Connection[F]` parameter is
2546                        // admitted.
2547                        // #2854: `RequestQuery` off an HTTP route has no request
2548                        // whose query string it could be.
2549                        if matches!(p.type_ref, TypeRef::RequestQuery(_))
2550                            && !matches!(h.kind, HandlerKind::Http { .. })
2551                        {
2552                            errors.push(
2553                                CompileError::new(
2554                                    "bynk.http.query_not_http",
2555                                    p.type_ref.span(),
2556                                    "`RequestQuery` is the query string of an HTTP request, so only an `on http` handler's `query` parameter can have it",
2557                                )
2558                                .with_note("a handler that is not an HTTP route has no query string to read"),
2559                            );
2560                            continue;
2561                        }
2562                        // #3277: `RequestCookies` off an HTTP route has no request
2563                        // whose cookies it could be.
2564                        if matches!(p.type_ref, TypeRef::RequestCookies(_))
2565                            && !matches!(h.kind, HandlerKind::Http { .. })
2566                        {
2567                            errors.push(
2568                                CompileError::new(
2569                                    "bynk.http.cookies_not_http",
2570                                    p.type_ref.span(),
2571                                    "`RequestCookies` is the cookies of an HTTP request, so only an `on http` handler's `cookies` parameter can have it",
2572                                )
2573                                .with_note("a handler that is not an HTTP route has no cookies to read"),
2574                            );
2575                            continue;
2576                        }
2577                        // #3276: a `@multipart` handler's `body` is where its `File`
2578                        // parts are received.
2579                        let multipart_body = p.name.name == "body"
2580                            && h.annotations.iter().any(|a| a.name.name == "multipart");
2581                        // #3343: and the record a request reader fills (`cookies`, `query`,
2582                        // a `@form` body) is where `@name` fields are allowed.
2583                        let request_record = matches!(h.kind, HandlerKind::Http { .. })
2584                            && (matches!(p.name.name.as_str(), "cookies" | "query")
2585                                || (p.name.name == "body"
2586                                    && h.annotations.iter().any(|a| a.name.name == "form")));
2587                        // #3380: a `@raw` handler's `body` may be a `Stream[Bytes]`, the
2588                        // request body as it arrives; without `@raw` it has no wire form,
2589                        // so it is refused with the fix rather than a generic boundary
2590                        // error. Any other stream position keeps `stream_at_boundary`.
2591                        let is_http_body = matches!(h.kind, HandlerKind::Http { .. })
2592                            && p.name.name == "body";
2593                        let has_raw = h.annotations.iter().any(|a| a.name.name == "raw");
2594                        // Any stream on a `@raw` body passes this check: `@raw`'s own check
2595                        // refuses an element type but `Bytes` (`raw_body_not_bytes`).
2596                        let streamed_body = is_http_body
2597                            && matches!(p.type_ref, TypeRef::Stream(..))
2598                            && has_raw;
2599                        if is_http_body
2600                            && crate::context_checks::is_byte_stream(&p.type_ref)
2601                            && !has_raw
2602                        {
2603                            errors.push(
2604                                CompileError::new(
2605                                    "bynk.http.stream_body_not_raw",
2606                                    p.type_ref.span(),
2607                                    "a `Stream[Bytes]` `body` needs `@raw`",
2608                                )
2609                                .with_note(
2610                                    "a request body has a JSON wire form unless the route says otherwise; write `@raw(contentType: \"…\")` and a `@limit` to receive it as a stream",
2611                                ),
2612                            );
2613                            continue;
2614                        }
2615                        if streamed_body {
2616                            continue;
2617                        }
2618                        if !type_ref_is_held(&p.type_ref) && !http_headers && !multipart_body {
2619                            // Only the `@name` arm is relaxed for a request record;
2620                            // every other boundary check still runs on it.
2621                            let what = if request_record {
2622                                REQUEST_RECORD_PARAM
2623                            } else {
2624                                "a service handler signature"
2625                            };
2626                            reject_fn_types(&p.type_ref, what, types, errors);
2627                        }
2628                    }
2629                    reject_fn_types(&h.return_type, "a service handler signature", types, errors);
2630                }
2631            }
2632            CommonsItem::Agent(a) => {
2633                reject_fn_types(&a.key_type, "an agent key", types, errors);
2634                for f in &a.store_fields {
2635                    validate_store_field_value_types(f, types, errors);
2636                }
2637                for h in &a.handlers {
2638                    for p in &h.params {
2639                        // v0.102 (§2.9.4): a held value may be transferred to
2640                        // an agent handler as a parameter.
2641                        if !type_ref_is_held(&p.type_ref) {
2642                            reject_fn_types(
2643                                &p.type_ref,
2644                                "an agent handler signature",
2645                                types,
2646                                errors,
2647                            );
2648                        }
2649                    }
2650                    reject_fn_types(&h.return_type, "an agent handler signature", types, errors);
2651                }
2652            }
2653            CommonsItem::Actor(a) => {
2654                if let Some(id) = &a.identity {
2655                    reject_fn_types(id, "an actor identity type", types, errors);
2656                }
2657            }
2658            // slice 1: `MessageEntry.code`/`.template` are plain string
2659            // literals, no fn-type-bearing fields to reject here.
2660            CommonsItem::Fn(_)
2661            | CommonsItem::Provider(_)
2662            | CommonsItem::Messages(_)
2663            | CommonsItem::Asset(_)
2664            | CommonsItem::Embed(_)
2665            // #2617: a constant's initialiser is static, so it can never hold
2666            // a function value; its type needs no boundary rule.
2667            | CommonsItem::Const(_) => {}
2668        }
2669    }
2670}
2671
2672/// Phase 4: build each production unit's combined symbol table from its files,
2673/// pushing any table-construction errors into `errors`.
2674pub fn phase_symbol_tables(
2675    groups: &BTreeMap<String, Vec<usize>>,
2676    kinds: &BTreeMap<String, UnitKind>,
2677    parsed: &[ParsedFile],
2678    errors: &mut ErrorSink,
2679) -> HashMap<String, UnitTable> {
2680    let mut unit_tables: HashMap<String, UnitTable> = HashMap::new();
2681    for (name, indices) in groups {
2682        let kind = *kinds.get(name).expect("every group has a kind");
2683        // #696: build_unit_table pairs each diagnostic with its declaring file.
2684        let mut table_errors: Vec<(PathBuf, CompileError)> = Vec::new();
2685        let table = build_unit_table(name, kind, indices, parsed, &mut table_errors);
2686        for (path, err) in table_errors {
2687            errors.push_for(Some(&path), err);
2688        }
2689        unit_tables.insert(name.clone(), table);
2690    }
2691    unit_tables
2692}
2693
2694/// Phase 5: resolve each unit's `uses` clauses, checking the target exists, is
2695/// a commons, and is not self-referential. Returns unit → deduplicated list of
2696/// used commons; diagnostics go into `errors`.
2697/// #1702 review: the order to check units in — every `uses` target before the
2698/// units that use it, ties broken by name, so the order stays a function of
2699/// the source alone (`deterministic_diagnostic_order_behaviour`). A generic
2700/// function's compared type parameters (#1688) are computed while its own unit
2701/// is checked, in that unit's environment, so an importer must come after.
2702/// Units on a `uses` cycle (already an error) are appended in name order.
2703pub fn uses_first_order<'a, I>(
2704    names: I,
2705    unit_uses: &HashMap<String, Vec<String>>,
2706) -> Vec<&'a String>
2707where
2708    I: IntoIterator<Item = &'a String>,
2709{
2710    let names: BTreeSet<&String> = names.into_iter().collect();
2711    let mut placed: HashSet<&String> = HashSet::new();
2712    let mut order = Vec::with_capacity(names.len());
2713    loop {
2714        let ready: Vec<&String> = names
2715            .iter()
2716            .copied()
2717            .filter(|n| !placed.contains(n))
2718            .filter(|n| {
2719                unit_uses.get(*n).is_none_or(|deps| {
2720                    deps.iter()
2721                        .all(|d| !names.contains(d) || placed.iter().any(|p| *p == d))
2722                })
2723            })
2724            .collect();
2725        if ready.is_empty() {
2726            break;
2727        }
2728        for n in ready {
2729            placed.insert(n);
2730            order.push(n);
2731        }
2732    }
2733    order.extend(names.iter().copied().filter(|n| !placed.contains(n)));
2734    order
2735}
2736
2737/// Phases 4, 5 and 5a: build the unit tables, resolve each unit's `uses`, then
2738/// resolve a constant named by a literal-only annotation argument to the literal
2739/// it denotes (#3445, [`crate::annotation_consts`]). The last rewrites `parsed`
2740/// and the tables built from it, ahead of every reader of annotation arguments.
2741pub fn phase_tables_uses_consts(
2742    groups: &BTreeMap<String, Vec<usize>>,
2743    kinds: &BTreeMap<String, UnitKind>,
2744    parsed: &mut [ParsedFile],
2745    policy: &crate::stability::StabilityPolicy,
2746    errors: &mut ErrorSink,
2747    refs: &mut RefSink,
2748) -> (HashMap<String, UnitTable>, HashMap<String, Vec<String>>) {
2749    let mut unit_tables = phase_symbol_tables(groups, kinds, parsed, errors);
2750    let unit_uses = phase_resolve_uses(groups, kinds, parsed, &unit_tables, policy, errors);
2751    crate::annotation_consts::resolve_annotation_consts(
2752        groups,
2753        kinds,
2754        parsed,
2755        &mut unit_tables,
2756        &unit_uses,
2757        refs,
2758    );
2759    (unit_tables, unit_uses)
2760}
2761
2762pub fn phase_resolve_uses(
2763    groups: &BTreeMap<String, Vec<usize>>,
2764    kinds: &BTreeMap<String, UnitKind>,
2765    parsed: &[ParsedFile],
2766    unit_tables: &HashMap<String, UnitTable>,
2767    // S3 (#1963): `uses` of an experimental commons needs an `[unstable]` opt-in.
2768    policy: &crate::stability::StabilityPolicy,
2769    errors: &mut ErrorSink,
2770) -> HashMap<String, Vec<String>> {
2771    let mut unit_uses: HashMap<String, Vec<String>> = HashMap::new();
2772    for (name, indices) in groups {
2773        let mut uses_targets: Vec<String> = Vec::new();
2774        for &i in indices {
2775            for u in parsed[i].uses() {
2776                let target = u.target.joined();
2777                if !unit_tables.contains_key(&target) {
2778                    errors.push_for(
2779                        Some(&parsed[i].identity_path()),
2780                        CompileError::new(
2781                            "bynk.uses.unknown_commons",
2782                            u.span,
2783                            format!("unknown commons `{target}`"),
2784                        )
2785                        .with_note(
2786                            "the target of a `uses` clause must be a commons in the project",
2787                        ),
2788                    );
2789                    continue;
2790                }
2791                // A first-party unit's own dependencies are the library's
2792                // business, never the project's opt-in.
2793                if !parsed[i].is_synthetic()
2794                    && let Some(err) = policy.check(&target, u.target.span)
2795                {
2796                    errors.push_for(Some(&parsed[i].identity_path()), err);
2797                }
2798                let target_kind = *kinds.get(&target).unwrap();
2799                if target_kind != UnitKind::Commons {
2800                    errors.push_for(Some(&parsed[i].identity_path()),
2801                        CompileError::new(
2802                            "bynk.uses.target_is_context",
2803                            u.span,
2804                            format!(
2805                                "`uses {target}` targets a context — `uses` may only target a commons"
2806                            ),
2807                        )
2808                        .with_note(
2809                            "to declare a dependency on a context, use `consumes` instead",
2810                        ),
2811                    );
2812                    continue;
2813                }
2814                if target == *name {
2815                    errors.push_for(
2816                        Some(&parsed[i].identity_path()),
2817                        CompileError::new(
2818                            "bynk.uses.self_reference",
2819                            u.span,
2820                            format!("`{name}` cannot `uses` itself"),
2821                        ),
2822                    );
2823                    continue;
2824                }
2825                if !uses_targets.contains(&target) {
2826                    uses_targets.push(target);
2827                }
2828            }
2829        }
2830        unit_uses.insert(name.clone(), uses_targets);
2831    }
2832    unit_uses
2833}
2834
2835/// #3536: each context's or adapter's `consumes` clauses as `(target, listed
2836/// names)` — `None` for the whole-module form (no braces), `Some(names)` for a
2837/// braced list — across all the unit's files, for
2838/// [`crate::symbols::record_unselected_consumed_types`].
2839pub fn consume_selections(
2840    groups: &BTreeMap<String, Vec<usize>>,
2841    kinds: &BTreeMap<String, UnitKind>,
2842    parsed: &[ParsedFile],
2843) -> crate::symbols::ConsumeSelections {
2844    let mut out = HashMap::new();
2845    for (name, indices) in groups {
2846        if !matches!(kinds.get(name), Some(UnitKind::Context | UnitKind::Adapter)) {
2847            continue;
2848        }
2849        let clauses: Vec<(String, Option<Vec<String>>)> = indices
2850            .iter()
2851            .flat_map(|&i| parsed[i].consumes())
2852            .map(|c| {
2853                let names = c
2854                    .selected
2855                    .as_ref()
2856                    .map(|items| items.iter().map(|n| n.name.name.clone()).collect());
2857                (c.target.joined(), names)
2858            })
2859            .collect();
2860        out.insert(name.clone(), clauses);
2861    }
2862    out
2863}
2864
2865/// Phase 5b: resolve each unit's `consumes` clauses (target exists, is a context
2866/// or adapter, not self-referential, obeys the adapter selection rules), and for
2867/// the braced `consumes U { Cap, … }` form validate and record the flattened
2868/// capabilities. Returns unit → consumed targets and unit → flattened-cap → owning
2869/// unit; diagnostics go into `errors` and clause-position references into `refs`.
2870#[allow(clippy::type_complexity)]
2871pub fn phase_resolve_consumes(
2872    groups: &BTreeMap<String, Vec<usize>>,
2873    kinds: &BTreeMap<String, UnitKind>,
2874    parsed: &[ParsedFile],
2875    unit_tables: &HashMap<String, UnitTable>,
2876    // S3 (#1963): consuming an experimental adapter, or selecting an
2877    // experimental capability, needs an `[unstable]` opt-in.
2878    policy: &crate::stability::StabilityPolicy,
2879    errors: &mut ErrorSink,
2880    refs: &mut RefSink,
2881) -> (
2882    HashMap<String, Vec<String>>,
2883    HashMap<String, HashMap<String, String>>,
2884    HashMap<String, HashMap<String, crate::symbols::ConsumedTypeAlias>>,
2885) {
2886    let mut unit_consumes: HashMap<String, Vec<String>> = HashMap::new();
2887    // #2887: `consumes U { T as Alias }` — unit → alias → the type it renames.
2888    let mut unit_type_aliases: HashMap<String, HashMap<String, crate::symbols::ConsumedTypeAlias>> =
2889        HashMap::new();
2890    // v0.17: `consumes U { Cap, … }` flattens selected caps into the consumer's
2891    // local namespace. unit → bare-cap → consumed unit providing it.
2892    let mut unit_flattened: HashMap<String, HashMap<String, String>> = HashMap::new();
2893    // #2765: does `target` export the type `name` (`exports transparent|opaque`)?
2894    let exports_type = |target: &str, name: &str| {
2895        groups.get(target).is_some_and(|files| {
2896            files.iter().any(|&j| {
2897                parsed[j].exports().iter().any(|clause| {
2898                    matches!(clause.kind, ExportKind::Type(_))
2899                        && clause.names.iter().any(|e| e.name.name == name)
2900                })
2901            })
2902        })
2903    };
2904    // #2765: type names already selected, per (file, target), so a repeat in
2905    // one file is refused as a repeated capability is.
2906    let mut type_selected: HashSet<(usize, String, String)> = HashSet::new();
2907    for (name, indices) in groups {
2908        let kind = *kinds.get(name).unwrap();
2909        let mut consumes_targets: Vec<String> = Vec::new();
2910        let mut flattened: HashMap<String, String> = HashMap::new();
2911        // #1857: the file that first selected each flattened capability, so a
2912        // file of a split context may repeat another file's selection.
2913        let mut flattened_in: HashMap<String, usize> = HashMap::new();
2914        // #2887: the aliases of this unit, the alias each `(target, type)` was
2915        // given (and in which file), and the types selected bare. A context's
2916        // `consumes` apply to all its files, so another file may repeat an
2917        // alias; only a pair that disagrees is refused.
2918        let mut type_aliases: HashMap<String, crate::symbols::ConsumedTypeAlias> = HashMap::new();
2919        let mut alias_of: HashMap<(String, String), (String, usize)> = HashMap::new();
2920        let mut bare_types: HashSet<(String, String)> = HashSet::new();
2921        let mut alias_sites: HashMap<String, (usize, Span)> = HashMap::new();
2922        let local_caps: HashSet<String> = unit_tables
2923            .get(name)
2924            .map(|t| t.capabilities.keys().cloned().collect())
2925            .unwrap_or_default();
2926        for &i in indices {
2927            refs.enter_file(&parsed[i].identity_path(), name, parsed[i].is_synthetic());
2928            for c in parsed[i].consumes() {
2929                let target = c.target.joined();
2930                // v0.18: an adapter's `consumes` is the braced capability-selection
2931                // form only — an adapter has no services to RPC-call, so the
2932                // whole-unit and `as Alias` forms are meaningless inside one.
2933                // #2765: braces that select only types name no capability, so
2934                // they trip the same guard.
2935                let selects_only_types = c.selected.as_ref().is_some_and(|names| {
2936                    let caps = unit_tables.get(&target).map(|t| &t.exported_capabilities);
2937                    !names.is_empty()
2938                        && names.iter().all(|n| {
2939                            !caps.is_some_and(|c| c.contains(&n.name.name))
2940                                && exports_type(&target, &n.name.name)
2941                        })
2942                });
2943                if kind == UnitKind::Adapter && (c.selected.is_none() || selects_only_types) {
2944                    errors.push_for(Some(&parsed[i].identity_path()),
2945                        CompileError::new(
2946                            "bynk.adapter.consumes_requires_selection",
2947                            c.span,
2948                            format!(
2949                                "an adapter's `consumes` must select capabilities — write `consumes {target} {{ Cap, … }}`",
2950                            ),
2951                        )
2952                        .with_note(
2953                            "adapters depend on capabilities, never on services; the whole-unit and aliased forms are context-only",
2954                        ),
2955                    );
2956                    continue;
2957                }
2958                if !unit_tables.contains_key(&target) {
2959                    errors.push_for(
2960                        Some(&parsed[i].identity_path()),
2961                        CompileError::new(
2962                            "bynk.consumes.unknown_context",
2963                            c.span,
2964                            format!("unknown context `{target}`"),
2965                        )
2966                        .with_note(
2967                            "the target of a `consumes` clause must be a context in the project",
2968                        ),
2969                    );
2970                    continue;
2971                }
2972                let target_kind = *kinds.get(&target).unwrap();
2973                // v0.17: `consumes` may target a context or an adapter (the host
2974                // boundary). It may not target a commons (use `uses` for that).
2975                if target_kind != UnitKind::Context && target_kind != UnitKind::Adapter {
2976                    errors.push_for(Some(&parsed[i].identity_path()),
2977                        CompileError::new(
2978                            "bynk.consumes.target_is_commons",
2979                            c.span,
2980                            format!(
2981                                "`consumes {target}` targets a commons — `consumes` may only target a context or adapter"
2982                            ),
2983                        )
2984                        .with_note(
2985                            "to mix in declarations from a commons, use `uses` instead",
2986                        ),
2987                    );
2988                    continue;
2989                }
2990                // v0.18: adapter dependencies are adapter-to-adapter (spec §4.5) —
2991                // an adapter consuming a *context* would pull service logic into
2992                // the host boundary.
2993                if kind == UnitKind::Adapter && target_kind == UnitKind::Context {
2994                    errors.push_for(Some(&parsed[i].identity_path()),
2995                        CompileError::new(
2996                            "bynk.adapter.consumes_context",
2997                            c.span,
2998                            format!(
2999                                "adapter `{name}` cannot `consumes` the context `{target}` — adapter dependencies are adapter-to-adapter"
3000                            ),
3001                        )
3002                        .with_note(
3003                            "an adapter may only depend on capabilities exported by other adapters (e.g. the `bynk` surface)",
3004                        ),
3005                    );
3006                    continue;
3007                }
3008                if target == *name {
3009                    let kind_word = if kind == UnitKind::Adapter {
3010                        "adapter"
3011                    } else {
3012                        "context"
3013                    };
3014                    errors.push_for(
3015                        Some(&parsed[i].identity_path()),
3016                        CompileError::new(
3017                            "bynk.consumes.self_reference",
3018                            c.span,
3019                            format!("{kind_word} `{name}` cannot `consumes` itself"),
3020                        ),
3021                    );
3022                    continue;
3023                }
3024                if !parsed[i].is_synthetic()
3025                    && let Some(err) = policy.check(&target, c.target.span)
3026                {
3027                    errors.push_for(Some(&parsed[i].identity_path()), err);
3028                }
3029                // v0.17: `consumes U { Cap, … }` — validate each selected name is
3030                // a capability `U` exports, detect clashes, and record the
3031                // flattening so bare `given Cap` resolves through the local path.
3032                if let Some(names) = &c.selected {
3033                    let exported = unit_tables
3034                        .get(&target)
3035                        .map(|t| &t.exported_capabilities)
3036                        .cloned()
3037                        .unwrap_or_default();
3038                    for item in names {
3039                        let cap = &item.name;
3040                        if !parsed[i].is_synthetic()
3041                            && let Some(err) =
3042                                policy.check(&format!("{target}.{}", cap.name), cap.span)
3043                        {
3044                            errors.push_for(Some(&parsed[i].identity_path()), err);
3045                        }
3046                        // #2765: the braces may also name a type `U` exports
3047                        // (`consumes bynk { TimedOut }`). Exported types are
3048                        // already in scope for any `consumes U`, so a type
3049                        // selection has nothing to flatten; it only states the
3050                        // dependency.
3051                        if let Some(alias) = &item.alias {
3052                            let key = (target.clone(), cap.name.clone());
3053                            let refuse =
3054                                |code: &'static str, span: Span, msg: String, note: String| {
3055                                    CompileError::new(code, span, msg).with_note(note)
3056                                };
3057                            if exported.contains(&cap.name) {
3058                                errors.push_for(
3059                                    Some(&parsed[i].identity_path()),
3060                                    refuse(
3061                                        "bynk.consumes.type_alias_capability",
3062                                        alias.span,
3063                                        format!(
3064                                            "`{}` is a capability of `{target}`; only exported types can be aliased",
3065                                            cap.name
3066                                        ),
3067                                        "a capability keeps its own name: select it bare (`consumes U { Cap }`), or qualify it as `given U.Cap`".to_string(),
3068                                    ),
3069                                );
3070                                continue;
3071                            }
3072                            if !exports_type(&target, &cap.name) {
3073                                errors.push_for(
3074                                    Some(&parsed[i].identity_path()),
3075                                    refuse(
3076                                        "bynk.consumes.type_alias_unknown_export",
3077                                        cap.span,
3078                                        format!(
3079                                            "`{target}` does not export a type named `{}`, so there is nothing to alias",
3080                                            cap.name
3081                                        ),
3082                                        "only an exported type can be aliased: `consumes U { Type as Alias }`".to_string(),
3083                                    ),
3084                                );
3085                                continue;
3086                            }
3087                            if !type_selected.insert((i, target.clone(), cap.name.clone())) {
3088                                errors.push_for(
3089                                    Some(&parsed[i].identity_path()),
3090                                    refuse(
3091                                        "bynk.consumes.type_alias_repeated",
3092                                        cap.span,
3093                                        format!(
3094                                            "`{}` is selected from `{target}` more than once in this file",
3095                                            cap.name
3096                                        ),
3097                                        "a type is aliased once; remove the repeat".to_string(),
3098                                    ),
3099                                );
3100                                continue;
3101                            }
3102                            if let Some((prev, prev_file)) = alias_of.get(&key)
3103                                && (*prev != alias.name || *prev_file == i)
3104                            {
3105                                errors.push_for(
3106                                    Some(&parsed[i].identity_path()),
3107                                    refuse(
3108                                        "bynk.consumes.type_alias_repeated",
3109                                        alias.span,
3110                                        format!(
3111                                            "`{}` from `{target}` is already aliased as `{prev}`",
3112                                            cap.name
3113                                        ),
3114                                        "a type is in scope under one alias; remove one of them"
3115                                            .to_string(),
3116                                    ),
3117                                );
3118                                continue;
3119                            }
3120                            if bare_types.contains(&key) {
3121                                errors.push_for(
3122                                    Some(&parsed[i].identity_path()),
3123                                    refuse(
3124                                        "bynk.consumes.type_alias_repeated",
3125                                        alias.span,
3126                                        format!(
3127                                            "`{}` from `{target}` is selected both bare and aliased",
3128                                            cap.name
3129                                        ),
3130                                        "the type is in scope as the alias only; drop the bare selection".to_string(),
3131                                    ),
3132                                );
3133                                continue;
3134                            }
3135                            let this = crate::symbols::ConsumedTypeAlias {
3136                                target: target.clone(),
3137                                original: cap.name.clone(),
3138                            };
3139                            if let Some(other) = type_aliases.get(&alias.name)
3140                                && *other != this
3141                            {
3142                                errors.push_for(
3143                                    Some(&parsed[i].identity_path()),
3144                                    refuse(
3145                                        "bynk.consumes.type_alias_conflict",
3146                                        alias.span,
3147                                        format!(
3148                                            "alias `{}` already names `{}` from `{}`",
3149                                            alias.name, other.original, other.target
3150                                        ),
3151                                        "give each aliased type its own name".to_string(),
3152                                    ),
3153                                );
3154                                continue;
3155                            }
3156                            alias_sites
3157                                .entry(alias.name.clone())
3158                                .or_insert((i, alias.span));
3159                            alias_of.insert(key, (alias.name.clone(), i));
3160                            type_aliases.insert(alias.name.clone(), this);
3161                            // Both names lead to the real declaration.
3162                            refs.record_in_unit(cap.span, SymbolKind::Type, &cap.name, &target);
3163                            refs.record_in_unit(alias.span, SymbolKind::Type, &cap.name, &target);
3164                            continue;
3165                        }
3166                        if !exported.contains(&cap.name) && exports_type(&target, &cap.name) {
3167                            if alias_of.contains_key(&(target.clone(), cap.name.clone())) {
3168                                errors.push_for(
3169                                    Some(&parsed[i].identity_path()),
3170                                    CompileError::new(
3171                                        "bynk.consumes.type_alias_repeated",
3172                                        cap.span,
3173                                        format!(
3174                                            "`{}` from `{target}` is selected both bare and aliased",
3175                                            cap.name
3176                                        ),
3177                                    )
3178                                    .with_note("the type is in scope as the alias only; drop the bare selection"),
3179                                );
3180                                continue;
3181                            }
3182                            bare_types.insert((target.clone(), cap.name.clone()));
3183                            if !type_selected.insert((i, target.clone(), cap.name.clone())) {
3184                                errors.push_for(
3185                                    Some(&parsed[i].identity_path()),
3186                                    CompileError::new(
3187                                        "bynk.consumes.capability_name_clash",
3188                                        cap.span,
3189                                        format!(
3190                                            "`{}` is selected from `{target}` more than once in this file",
3191                                            cap.name
3192                                        ),
3193                                    ),
3194                                );
3195                                continue;
3196                            }
3197                            refs.record_in_unit(cap.span, SymbolKind::Type, &cap.name, &target);
3198                            continue;
3199                        }
3200                        if !exported.contains(&cap.name) {
3201                            errors.push_for(
3202                                Some(&parsed[i].identity_path()),
3203                                CompileError::new(
3204                                    "bynk.given.cross_context_unknown_capability",
3205                                    cap.span,
3206                                    format!(
3207                                        "`{target}` does not export a capability named `{}`",
3208                                        cap.name
3209                                    ),
3210                                ),
3211                            );
3212                            continue;
3213                        }
3214                        if local_caps.contains(&cap.name) {
3215                            errors.push_for(Some(&parsed[i].identity_path()), CompileError::new(
3216                                "bynk.consumes.capability_name_clash",
3217                                cap.span,
3218                                format!(
3219                                    "flattened capability `{}` clashes with a capability declared locally — use qualified `given {target}.{}` instead",
3220                                    cap.name, cap.name
3221                                ),
3222                            ));
3223                            continue;
3224                        }
3225                        if let Some(prev) = flattened.get(&cap.name) {
3226                            // #1857: the same selection, repeated in another
3227                            // file of the context, is one selection.
3228                            if *prev == target && flattened_in.get(&cap.name) != Some(&i) {
3229                                refs.record_in_unit(
3230                                    cap.span,
3231                                    SymbolKind::Capability,
3232                                    &cap.name,
3233                                    &target,
3234                                );
3235                                continue;
3236                            }
3237                            errors.push_for(Some(&parsed[i].identity_path()), CompileError::new(
3238                                "bynk.consumes.capability_name_clash",
3239                                cap.span,
3240                                format!(
3241                                    "capability `{}` is flattened from both `{prev}` and `{target}` — qualify one with `given U.{}`",
3242                                    cap.name, cap.name
3243                                ),
3244                            ));
3245                            continue;
3246                        }
3247                        // v0.25: the selection list names the capability in
3248                        // the consumed unit (clause-position reference).
3249                        refs.record_in_unit(cap.span, SymbolKind::Capability, &cap.name, &target);
3250                        flattened.insert(cap.name.clone(), target.clone());
3251                        flattened_in.insert(cap.name.clone(), i);
3252                    }
3253                }
3254                if !consumes_targets.contains(&target) {
3255                    consumes_targets.push(target);
3256                }
3257            }
3258        }
3259        unit_consumes.insert(name.clone(), consumes_targets);
3260        // An alias is a type name; a capability of the same name (flattened
3261        // from a `consumes`, or local) would bind it twice in the emitted
3262        // module and in the unit's own scope.
3263        let mut clashing: Vec<&String> = type_aliases
3264            .keys()
3265            .filter(|a| flattened.contains_key(*a) || local_caps.contains(*a))
3266            .collect();
3267        clashing.sort();
3268        for alias in clashing {
3269            let (file, span) = alias_sites[alias];
3270            errors.push_for(
3271                Some(&parsed[file].identity_path()),
3272                CompileError::new(
3273                    "bynk.consumes.type_alias_conflict",
3274                    span,
3275                    format!("alias `{alias}` is also the name of a capability in this context"),
3276                )
3277                .with_note("choose an alias that is not a capability's name"),
3278            );
3279        }
3280        unit_flattened.insert(name.clone(), flattened);
3281        if !type_aliases.is_empty() {
3282            unit_type_aliases.insert(name.clone(), type_aliases);
3283        }
3284    }
3285    (unit_consumes, unit_flattened, unit_type_aliases)
3286}
3287
3288/// Phases 5b'/5b'': collect each context's `consumes` aliases (alias →
3289/// consumed-context name), reporting alias-vs-alias conflicts (5b'), then report
3290/// any alias that clashes with a locally-declared type/fn/capability/service/agent
3291/// (5b''). Returns the per-context alias maps; diagnostics go into `errors`.
3292pub fn phase_consumes_aliases(
3293    groups: &BTreeMap<String, Vec<usize>>,
3294    kinds: &BTreeMap<String, UnitKind>,
3295    parsed: &[ParsedFile],
3296    unit_tables: &HashMap<String, UnitTable>,
3297    errors: &mut ErrorSink,
3298) -> HashMap<String, HashMap<String, String>> {
3299    let mut unit_consumes_aliases: HashMap<String, HashMap<String, String>> = HashMap::new();
3300    for (name, indices) in groups {
3301        let kind = *kinds.get(name).unwrap();
3302        if kind != UnitKind::Context {
3303            continue;
3304        }
3305        let mut aliases: HashMap<String, String> = HashMap::new();
3306        // #1857: where each alias, and each aliased target, was first seen:
3307        // `(the other half of the pair, file index, alias span)`. A context's
3308        // `consumes` clauses apply to all its files, so a file may repeat one
3309        // another file states, as it repeats `context`; only a pair that
3310        // disagrees is a conflict.
3311        let mut by_alias: HashMap<String, (String, usize, Span)> = HashMap::new();
3312        let mut by_target: HashMap<String, (String, usize, Span)> = HashMap::new();
3313        for &i in indices {
3314            for c in parsed[i].consumes() {
3315                let Some(alias) = &c.alias else { continue };
3316                let target = c.target.joined();
3317                if !unit_tables.contains_key(&target) {
3318                    // Already reported as unknown context above.
3319                    continue;
3320                }
3321                // #1857: a repeat is fine in *another* file; twice in one file
3322                // is still a conflict.
3323                let first = by_alias
3324                    .get(&alias.name)
3325                    .filter(|(t, f, _)| *t != target || *f == i)
3326                    .map(|(t, f, sp)| {
3327                        let what = if *t == target {
3328                            "the same clause appears earlier in this file".to_string()
3329                        } else {
3330                            format!("alias `{}` already names `{t}`", alias.name)
3331                        };
3332                        (what, *f, *sp)
3333                    })
3334                    .or_else(|| {
3335                        by_target
3336                            .get(&target)
3337                            .filter(|(a, _, _)| *a != alias.name)
3338                            .map(|(a, f, sp)| {
3339                                (format!("`{target}` is already consumed as `{a}`"), *f, *sp)
3340                            })
3341                    });
3342                if let Some((what, prev_file, prev_span)) = first {
3343                    // A label can point only into this file; another file's
3344                    // clause is named in the message.
3345                    let where_ = if prev_file == i {
3346                        String::new()
3347                    } else {
3348                        // `/`-separated on every platform, as the project
3349                        // layout is written (a Windows `display()` uses `\`).
3350                        format!(
3351                            " (first stated in `{}`)",
3352                            parsed[prev_file]
3353                                .identity_path()
3354                                .components()
3355                                .map(|c| c.as_os_str().to_string_lossy())
3356                                .collect::<Vec<_>>()
3357                                .join("/")
3358                        )
3359                    };
3360                    let mut err = CompileError::new(
3361                        "bynk.consumes.alias_conflict",
3362                        alias.span,
3363                        format!(
3364                            "`consumes {target} as {}` conflicts with another `consumes` clause in context `{name}`: {what}{where_}",
3365                            alias.name
3366                        ),
3367                    );
3368                    if prev_file == i {
3369                        err = err.with_label(prev_span, "previously defined here");
3370                    }
3371                    errors.push_for(
3372                        Some(&parsed[i].identity_path()),
3373                        err.with_note(
3374                            "a context may consume a unit under one alias, and an alias may name one unit; repeating the same clause in another file is fine",
3375                        ),
3376                    );
3377                    continue;
3378                }
3379                if by_alias.contains_key(&alias.name) {
3380                    // #1857: the same clause, repeated in another file.
3381                    continue;
3382                }
3383                aliases.insert(alias.name.clone(), target.clone());
3384                by_alias.insert(alias.name.clone(), (target.clone(), i, alias.span));
3385                by_target.insert(target, (alias.name.clone(), i, alias.span));
3386            }
3387        }
3388        unit_consumes_aliases.insert(name.clone(), aliases);
3389    }
3390
3391    // -- 5b''. Detect alias-vs-local-decl conflicts. An alias must not clash
3392    //          with any locally declared type/fn/capability/service/agent.
3393    for (name, aliases) in &unit_consumes_aliases {
3394        let Some(local) = unit_tables.get(name) else {
3395            continue;
3396        };
3397        for alias in aliases.keys() {
3398            let alias_site = parsed_alias_span(parsed, &groups[name], alias);
3399            let alias_span = alias_site.map(|(_, s)| s).unwrap_or_default();
3400            let alias_file = alias_site.map(|(i, _)| parsed[i].identity_path());
3401            let conflict_kind = if local.types.contains_key(alias) {
3402                Some("type")
3403            } else if local.fns.contains_key(alias) {
3404                Some("function")
3405            } else if local.capabilities.contains_key(alias) {
3406                Some("capability")
3407            } else if local.services.contains_key(alias) {
3408                Some("service")
3409            } else if local.agents.contains_key(alias) {
3410                Some("agent")
3411            } else {
3412                None
3413            };
3414            if let Some(kind) = conflict_kind {
3415                errors.push_for(alias_file.as_deref(),
3416                    CompileError::new(
3417                        "bynk.consumes.alias_conflict",
3418                        alias_span,
3419                        format!(
3420                            "alias `{alias}` conflicts with a local {kind} of the same name in context `{name}`",
3421                        ),
3422                    )
3423                    .with_note(
3424                        "pick a different alias for the `consumes` clause, or rename the local declaration",
3425                    ),
3426                );
3427            }
3428        }
3429    }
3430    unit_consumes_aliases
3431}
3432
3433/// #2618 (decision C): a public declaration may not name a `private` type of
3434/// its own unit in its signature, since a unit that `uses` it could neither
3435/// name nor build a value of that type. Checked positions: a public `fn`'s
3436/// parameter and return types (a method's too, unless its type is itself
3437/// private, when the method is out of an importer's reach with it), a public
3438/// type's record fields and variant payloads, a public constant's type
3439/// annotation, and a context's `exports` list.
3440/// Each is `bynk.visibility.private_in_public`.
3441///
3442/// A service, agent, capability, provider, actor or event signature is not
3443/// checked: how far those reach is a context's `exports` question, and the
3444/// cross-context structural rule (§6.5) is unchanged.
3445pub fn phase_private_in_public(
3446    parsed: &[ParsedFile],
3447    groups: &BTreeMap<String, Vec<usize>>,
3448    errors: &mut ErrorSink,
3449) {
3450    for (unit, indices) in groups {
3451        let mut private_types: HashSet<String> = HashSet::new();
3452        let mut type_params: HashMap<String, Vec<TypeParam>> = HashMap::new();
3453        for &i in indices {
3454            for item in parsed[i].items() {
3455                if let CommonsItem::Type(t) = item {
3456                    if t.private.is_some() {
3457                        private_types.insert(t.name.name.clone());
3458                    }
3459                    type_params.insert(t.name.name.clone(), t.type_params.clone());
3460                }
3461            }
3462        }
3463        if private_types.is_empty() {
3464            continue;
3465        }
3466        for &i in indices {
3467            let file = parsed[i].identity_path();
3468            let mut report = |at: Span, decl: &str, ty: &str| {
3469                errors.push_for(
3470                    Some(&file),
3471                    CompileError::new(
3472                        "bynk.visibility.private_in_public",
3473                        at,
3474                        format!("public {decl} names `{ty}`, a private type of `{unit}`"),
3475                    )
3476                    .with_note(format!(
3477                        "a unit that uses `{unit}` could neither name nor build a `{ty}`; make `{ty}` public, or mark the declaration `private` too"
3478                    )),
3479                );
3480            };
3481            let first_private = |r: &TypeRef, vars: &HashSet<&str>| -> Option<String> {
3482                let mut names = Vec::new();
3483                type_ref_names(r, vars, &mut names);
3484                names.into_iter().find(|n| private_types.contains(n))
3485            };
3486            for item in parsed[i].items() {
3487                match item {
3488                    CommonsItem::Fn(f) if f.private.is_none() => {
3489                        let (decl, attached) = match &f.name {
3490                            FnName::Free(id) => (format!("function `{}`", id.name), &[][..]),
3491                            FnName::Method {
3492                                type_name,
3493                                method_name,
3494                            } => {
3495                                if private_types.contains(&type_name.name) {
3496                                    continue;
3497                                }
3498                                (
3499                                    format!("method `{}.{}`", type_name.name, method_name.name),
3500                                    type_params
3501                                        .get(&type_name.name)
3502                                        .map(Vec::as_slice)
3503                                        .unwrap_or_default(),
3504                                )
3505                            }
3506                        };
3507                        let vars: HashSet<&str> = f
3508                            .type_params
3509                            .iter()
3510                            .chain(attached)
3511                            .map(|p| p.name.name.as_str())
3512                            .collect();
3513                        let positions = f
3514                            .params
3515                            .iter()
3516                            .map(|p| &p.type_ref)
3517                            .chain(std::iter::once(&f.return_type));
3518                        for r in positions {
3519                            if let Some(ty) = first_private(r, &vars) {
3520                                report(r.span(), &decl, &ty);
3521                            }
3522                        }
3523                    }
3524                    CommonsItem::Type(t) if t.private.is_none() => {
3525                        let vars: HashSet<&str> =
3526                            t.type_params.iter().map(|p| p.name.name.as_str()).collect();
3527                        let decl = format!("type `{}`", t.name.name);
3528                        let positions: Vec<&TypeRef> = match &t.body {
3529                            TypeBody::Record(r) => r.fields.iter().map(|f| &f.type_ref).collect(),
3530                            TypeBody::Sum(s) => s
3531                                .variants
3532                                .iter()
3533                                .flat_map(|v| v.payload.iter().map(|p| &p.type_ref))
3534                                .collect(),
3535                            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => Vec::new(),
3536                        };
3537                        for r in positions {
3538                            if let Some(ty) = first_private(r, &vars) {
3539                                report(r.span(), &decl, &ty);
3540                            }
3541                        }
3542                    }
3543                    // A public constant's annotation is part of what an
3544                    // importer sees, like a public function's signature.
3545                    CommonsItem::Const(c) if c.private.is_none() => {
3546                        if let Some(ty) = first_private(&c.ty, &HashSet::new()) {
3547                            report(c.ty.span(), &format!("constant `{}`", c.name.name), &ty);
3548                        }
3549                    }
3550                    _ => {}
3551                }
3552            }
3553            for e in parsed[i].exports() {
3554                for n in &e.names {
3555                    if private_types.contains(&n.name.name) {
3556                        report(n.name.span, "`exports` list", &n.name.name);
3557                    }
3558                }
3559            }
3560        }
3561    }
3562}
3563
3564/// Phase 6: for each unit, detect when two `uses`-imported commons declare the
3565/// same (non-shadowed) type or function name — an unrenamable conflict at the use
3566/// site. Diagnostics go into `errors`.
3567pub fn phase_uses_name_conflicts(
3568    unit_uses: &HashMap<String, Vec<String>>,
3569    unit_tables: &HashMap<String, UnitTable>,
3570    parsed: &[ParsedFile],
3571    groups: &BTreeMap<String, Vec<usize>>,
3572    errors: &mut ErrorSink,
3573) {
3574    for (name, targets) in unit_uses {
3575        let local = unit_tables.get(name).expect("unit table present");
3576        let mut imported: HashMap<String, String> = HashMap::new();
3577        for t in targets {
3578            // #2618: `private` declarations never come in, so never conflict.
3579            let used = unit_tables
3580                .get(t)
3581                .expect("used unit table present")
3582                .importable();
3583            for type_name in used.types.keys() {
3584                // Unlike the fn and asset loops below, a local service, agent,
3585                // provider or asset does not skip this (#1927, review of
3586                // #1933). It hides an imported type from naming, but the type
3587                // stays composed so its values resolve, and with two used
3588                // commons declaring it, which one the unit's values carry is
3589                // still ambiguous.
3590                if local.types.contains_key(type_name) || local.fns.contains_key(type_name) {
3591                    continue;
3592                }
3593                if let Some(prev) = imported.get(type_name) {
3594                    let site = uses_span_of(parsed, &groups[name], t);
3595                    let span = site.map(|(_, s)| s).unwrap_or_default();
3596                    let file = site.map(|(i, _)| parsed[i].identity_path());
3597                    errors.push_for(file.as_deref(),
3598                        CompileError::new(
3599                            "bynk.uses.name_conflict",
3600                            span,
3601                            format!(
3602                                "`{name}` uses two commons that both declare `{type_name}`: `{prev}` and `{t}`",
3603                            ),
3604                        )
3605                        .with_note(
3606                            "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3607                        ),
3608                    );
3609                } else {
3610                    imported.insert(type_name.clone(), t.clone());
3611                }
3612            }
3613            for fn_name in used.fns.keys() {
3614                // #1925: any local value hides the import (`shadowed_imports`),
3615                // so two used commons declaring it leave nothing ambiguous.
3616                if crate::symbols::local_value_kind(local, fn_name).is_some() {
3617                    continue;
3618                }
3619                if let Some(prev) = imported.get(fn_name) {
3620                    let site = uses_span_of(parsed, &groups[name], t);
3621                    let span = site.map(|(_, s)| s).unwrap_or_default();
3622                    let file = site.map(|(i, _)| parsed[i].identity_path());
3623                    errors.push_for(file.as_deref(),
3624                        CompileError::new(
3625                            "bynk.uses.name_conflict",
3626                            span,
3627                            format!(
3628                                "`{name}` uses two commons that both declare `{fn_name}`: `{prev}` and `{t}`",
3629                            ),
3630                        )
3631                        .with_note(
3632                            "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3633                        ),
3634                    );
3635                } else {
3636                    imported.insert(fn_name.clone(), t.clone());
3637                }
3638            }
3639            // #1883, slice 1a ([DECISION G]): a commons' assets come in
3640            // through `uses` like its functions, and share their namespace.
3641            for asset_name in used.assets.keys() {
3642                // #1925: any local value hides the import, as above.
3643                if crate::symbols::local_value_kind(local, asset_name).is_some() {
3644                    continue;
3645                }
3646                if let Some(prev) = imported.get(asset_name) {
3647                    let site = uses_span_of(parsed, &groups[name], t);
3648                    let span = site.map(|(_, s)| s).unwrap_or_default();
3649                    let file = site.map(|(i, _)| parsed[i].identity_path());
3650                    errors.push_for(file.as_deref(),
3651                        CompileError::new(
3652                            "bynk.uses.name_conflict",
3653                            span,
3654                            format!(
3655                                "`{name}` uses two commons that both declare `{asset_name}`: `{prev}` and `{t}`",
3656                            ),
3657                        )
3658                        .with_note(
3659                            "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3660                        ),
3661                    );
3662                } else {
3663                    imported.insert(asset_name.clone(), t.clone());
3664                }
3665            }
3666            // #2387, slice 1: a commons' embeds come in through `uses` the
3667            // same way, in the same namespace.
3668            for embed_name in used.embeds.keys() {
3669                if crate::symbols::local_value_kind(local, embed_name).is_some() {
3670                    continue;
3671                }
3672                if let Some(prev) = imported.get(embed_name) {
3673                    let site = uses_span_of(parsed, &groups[name], t);
3674                    let span = site.map(|(_, s)| s).unwrap_or_default();
3675                    let file = site.map(|(i, _)| parsed[i].identity_path());
3676                    errors.push_for(file.as_deref(),
3677                        CompileError::new(
3678                            "bynk.uses.name_conflict",
3679                            span,
3680                            format!(
3681                                "`{name}` uses two commons that both declare `{embed_name}`: `{prev}` and `{t}`",
3682                            ),
3683                        )
3684                        .with_note(
3685                            "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3686                        ),
3687                    );
3688                } else {
3689                    imported.insert(embed_name.clone(), t.clone());
3690                }
3691            }
3692            // #2617: and its constants, the same way.
3693            for const_name in used.consts.keys() {
3694                if crate::symbols::local_value_kind(local, const_name).is_some() {
3695                    continue;
3696                }
3697                if let Some(prev) = imported.get(const_name) {
3698                    let site = uses_span_of(parsed, &groups[name], t);
3699                    let span = site.map(|(_, s)| s).unwrap_or_default();
3700                    let file = site.map(|(i, _)| parsed[i].identity_path());
3701                    errors.push_for(file.as_deref(),
3702                        CompileError::new(
3703                            "bynk.uses.name_conflict",
3704                            span,
3705                            format!(
3706                                "`{name}` uses two commons that both declare `{const_name}`: `{prev}` and `{t}`",
3707                            ),
3708                        )
3709                        .with_note(
3710                            "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3711                        ),
3712                    );
3713                } else {
3714                    imported.insert(const_name.clone(), t.clone());
3715                }
3716            }
3717        }
3718    }
3719}
3720
3721/// message-bundles slice 1 (#859): messages-block legality, `@reference`
3722/// cardinality, within-block duplicate codes, and the `uses bynk.locale`
3723/// dependency. Runs here (not in `phase_group`) because it needs `unit_uses`,
3724/// resolved just above.
3725///
3726/// P5.0 (`design/tracks/semantics-in-the-checker.md` §6): relocated verbatim
3727/// from `bynk-emit/src/project/validate.rs`'s `check_messages_bundles` — one
3728/// of the two live editor-diagnostics regressions this slice closes (category
3729/// 2 of `analysis.rs`'s own seven-category accounting). Cross-locale
3730/// completeness (`bynk.messages.incomplete`, only for codes present in the
3731/// reference locale but not this one — a locale-specific-only code is not an
3732/// error, per the "reference is a floor, not a ceiling" convention) and
3733/// cross-locale placeholder-*set* agreement (`bynk.messages.placeholder_mismatch`,
3734/// only for codes present in both — a missing code is `incomplete`'s job, not
3735/// this one's). Two blocks declaring the same locale tag are rejected outright
3736/// (`bynk.resolve.duplicate_message_locale`, PR #875 review) — the emitter
3737/// has no dedup of its own, so a silent last-wins here would let a hard
3738/// `tsc` redeclare error (two colliding `const __messages_<tag>`
3739/// declarations) through instead.
3740pub fn phase_messages_bundles(
3741    parsed: &[ParsedFile],
3742    groups: &BTreeMap<String, Vec<usize>>,
3743    kinds: &BTreeMap<String, UnitKind>,
3744    unit_uses: &HashMap<String, Vec<String>>,
3745    errors: &mut ErrorSink,
3746) {
3747    for (name, indices) in groups {
3748        let mut first_messages: Option<(usize, Span)> = None;
3749        let mut reference_sites: Vec<(usize, Span)> = Vec::new();
3750        let mut reference_block: Option<(usize, &MessagesDecl)> = None;
3751        let mut by_tag: HashMap<&str, (usize, &MessagesDecl)> = HashMap::new();
3752        for &i in indices {
3753            for item in parsed[i].items() {
3754                let CommonsItem::Messages(m) = item else {
3755                    continue;
3756                };
3757                if first_messages.is_none() {
3758                    first_messages = Some((i, m.span));
3759                }
3760                if kinds.get(name) != Some(&UnitKind::Commons) {
3761                    errors.push_for(
3762                        Some(&parsed[i].identity_path()),
3763                        CompileError::new(
3764                            "bynk.messages.outside_commons",
3765                            m.span,
3766                            "`messages` declarations are only allowed inside a commons, not a context or adapter",
3767                        ),
3768                    );
3769                    continue;
3770                }
3771                // #899: the tag is a `LocaleTag` string literal, checked here
3772                // against `LocaleTag`'s own refinement (read from the
3773                // firstparty `bynk.locale.types` source, so the pattern has one
3774                // definition). An invalid tag would otherwise reach `Intl` at
3775                // runtime as `new Intl.PluralRules("xx")`, which throws — the
3776                // opposite of `render`'s totality contract.
3777                if !checker::locale_tag_accepts(&m.tag) {
3778                    let pattern = checker::locale_tag_pattern().unwrap_or("");
3779                    errors.push_for(
3780                        Some(&parsed[i].identity_path()),
3781                        CompileError::new(
3782                            "bynk.messages.invalid_locale_tag",
3783                            m.tag_span,
3784                            format!(
3785                                "\"{}\" is not a valid `LocaleTag` — it must match the pattern `{}`",
3786                                m.tag, pattern
3787                            ),
3788                        ),
3789                    );
3790                }
3791                // message-bundles slice 2 (#874, PR #875 review): two blocks
3792                // declaring the same locale tag are rejected, not
3793                // last-write-wins — the emitter (`emit_messages_bundle`) has no
3794                // dedup of its own and would emit two colliding table entries
3795                // under one object key, a hard `tsc` error. Mirrors
3796                // `bynk.resolve.duplicate_fn`'s own shape: only the *first*
3797                // occurrence seeds `by_tag`, so a third duplicate still reports
3798                // against the original, not the second.
3799                if let Some(&(_, prev)) = by_tag.get(m.tag.as_str()) {
3800                    errors.push_for(
3801                        Some(&parsed[i].identity_path()),
3802                        CompileError::new(
3803                            "bynk.resolve.duplicate_message_locale",
3804                            m.tag_span,
3805                            format!("locale \"{}\" is already declared in this bundle", m.tag),
3806                        )
3807                        .with_label(prev.tag_span, "previously declared here"),
3808                    );
3809                } else {
3810                    by_tag.insert(m.tag.as_str(), (i, m));
3811                }
3812                for ann in &m.annotations {
3813                    if ann.name.name == "reference" {
3814                        reference_sites.push((i, ann.span));
3815                        reference_block = Some((i, m));
3816                    }
3817                }
3818                let mut seen: HashMap<&str, Span> = HashMap::new();
3819                for entry in &m.entries {
3820                    if let Some(prev) = seen.get(entry.code.as_str()) {
3821                        errors.push_for(
3822                            Some(&parsed[i].identity_path()),
3823                            CompileError::new(
3824                                "bynk.resolve.duplicate_message_code",
3825                                entry.code_span,
3826                                format!(
3827                                    "message code \"{}\" is already declared in this block",
3828                                    entry.code
3829                                ),
3830                            )
3831                            .with_label(*prev, "previously declared here"),
3832                        );
3833                    } else {
3834                        seen.insert(entry.code.as_str(), entry.code_span);
3835                    }
3836                    // message-bundles slice 3 (#878): runs unconditionally,
3837                    // once per entry, regardless of `@reference` cardinality
3838                    // — malformed ICU syntax shouldn't wait on cardinality
3839                    // being resolved first.
3840                    check_entry_icu_syntax(entry, Some(&parsed[i].identity_path()), errors);
3841                }
3842            }
3843        }
3844        let Some((first_i, first_span)) = first_messages else {
3845            continue;
3846        };
3847        if kinds.get(name) != Some(&UnitKind::Commons) {
3848            // Already reported above (outside_commons) for every block;
3849            // cardinality/uses checks don't apply to a non-commons unit.
3850            continue;
3851        }
3852        match reference_sites.len() {
3853            0 => {
3854                errors.push_for(
3855                    Some(&parsed[first_i].identity_path()),
3856                    CompileError::new(
3857                        "bynk.messages.missing_reference",
3858                        first_span,
3859                        "a message bundle must have exactly one `@reference` block; none found",
3860                    ),
3861                );
3862            }
3863            1 => {
3864                // message-bundles slice 2 (#874): "the reference" is only
3865                // well-defined here — 0 or 2+ already reported their own
3866                // diagnostic above, and completeness/placeholder-agreement
3867                // against an ambiguous or absent reference would be noise.
3868                let (_, reference) = reference_block
3869                    .expect("reference_sites.len() == 1 implies reference_block is Some");
3870                // Sorted for deterministic diagnostic order — `by_tag`'s
3871                // HashMap iteration is not otherwise stable across runs.
3872                let mut sorted_tags: Vec<&&str> = by_tag.keys().collect();
3873                sorted_tags.sort();
3874                for &&tag in &sorted_tags {
3875                    let &(locale_i, locale_m) = &by_tag[tag];
3876                    if tag == reference.tag.as_str() {
3877                        continue;
3878                    }
3879                    for ref_entry in &reference.entries {
3880                        let Some(locale_entry) =
3881                            locale_m.entries.iter().find(|e| e.code == ref_entry.code)
3882                        else {
3883                            errors.push_for(
3884                                Some(&parsed[locale_i].identity_path()),
3885                                CompileError::new(
3886                                    "bynk.messages.incomplete",
3887                                    locale_m.span,
3888                                    format!(
3889                                        "locale \"{tag}\" is missing code \"{}\", declared by the reference locale \"{}\"",
3890                                        ref_entry.code, reference.tag
3891                                    ),
3892                                ),
3893                            );
3894                            continue;
3895                        };
3896                        let ref_names = icu::placeholder_names(&ref_entry.template);
3897                        let locale_names = icu::placeholder_names(&locale_entry.template);
3898                        if ref_names != locale_names {
3899                            errors.push_for(
3900                                Some(&parsed[locale_i].identity_path()),
3901                                CompileError::new(
3902                                    "bynk.messages.placeholder_mismatch",
3903                                    locale_entry.template_span,
3904                                    format!(
3905                                        "locale \"{tag}\"'s template for code \"{}\" uses placeholders {locale_names:?}, but the reference locale \"{}\"'s uses {ref_names:?}",
3906                                        ref_entry.code, reference.tag
3907                                    ),
3908                                ),
3909                            );
3910                        }
3911                        // message-bundles slice 3 (#878, Decision D): a name
3912                        // present in both templates must also agree on ICU
3913                        // format *kind* (plain/plural/select/number/date) —
3914                        // a UI can't sanely alternate that per locale. A
3915                        // missing name is `placeholder_mismatch`'s job, not
3916                        // this one's; a malformed template's kinds are
3917                        // silently absent from `template_format_kinds`
3918                        // (already reported once by `check_entry_icu_syntax`
3919                        // above, never double-reported here).
3920                        let ref_kinds = icu::template_format_kinds(&ref_entry.template);
3921                        let locale_kinds = icu::template_format_kinds(&locale_entry.template);
3922                        for (pname, ref_kind) in &ref_kinds {
3923                            let Some(locale_kind) = locale_kinds.get(pname) else {
3924                                continue;
3925                            };
3926                            if locale_kind != ref_kind {
3927                                errors.push_for(
3928                                    Some(&parsed[locale_i].identity_path()),
3929                                    CompileError::new(
3930                                        "bynk.messages.format_mismatch",
3931                                        locale_entry.template_span,
3932                                        format!(
3933                                            "locale \"{tag}\"'s placeholder \"{pname}\" in code \"{}\" is formatted as {}, but the reference locale \"{}\"'s is {}",
3934                                            ref_entry.code,
3935                                            locale_kind.as_str(),
3936                                            reference.tag,
3937                                            ref_kind.as_str(),
3938                                        ),
3939                                    ),
3940                                );
3941                            }
3942                        }
3943                    }
3944                }
3945            }
3946            _ => {
3947                let (_, first_ref_span) = reference_sites[0];
3948                for &(i, span) in &reference_sites[1..] {
3949                    errors.push_for(
3950                        Some(&parsed[i].identity_path()),
3951                        CompileError::new(
3952                            "bynk.messages.multiple_reference",
3953                            span,
3954                            "a message bundle must have exactly one `@reference` block; found more than one",
3955                        )
3956                        .with_label(first_ref_span, "first `@reference` here"),
3957                    );
3958                }
3959            }
3960        }
3961        // #2618 review: `private` on a `messages` block never does what it
3962        // suggests, so it warns. Negotiation (`detect_context_message_bundle`,
3963        // symbols.rs) reads the bundle's visibility off its `@reference`
3964        // block alone: a private reference keeps the whole bundle out of
3965        // every context that uses this commons, and `private` on any other
3966        // block of a bundle whose reference is public changes nothing. The
3967        // commons' own `render` uses every block either way. Only a commons
3968        // gets here (a context's or adapter's `messages` block is already
3969        // `bynk.messages.outside_commons`, above), and only with exactly one
3970        // `@reference` (a missing or doubled one is already an error).
3971        if let (Some((_, reference)), [_]) = (reference_block, reference_sites.as_slice()) {
3972            for &i in indices {
3973                for item in parsed[i].items() {
3974                    let CommonsItem::Messages(m) = item else {
3975                        continue;
3976                    };
3977                    let Some(private_span) = m.private else {
3978                        continue;
3979                    };
3980                    let is_reference = std::ptr::eq(m, reference);
3981                    let (message, note) = if is_reference {
3982                        (
3983                            format!(
3984                                "a `private` messages bundle is never negotiated by a context that uses `{name}`"
3985                            ),
3986                            format!(
3987                                "remove `private` so that a context that uses `{name}` negotiates its locale against this bundle; this commons' own `render` reads the bundle either way"
3988                            ),
3989                        )
3990                    } else if reference.private.is_some() {
3991                        // The reference block's own warning covers the bundle.
3992                        continue;
3993                    } else {
3994                        (
3995                            format!(
3996                                "`private` has no effect on this `messages` block: the bundle's `@reference` block is public, so a context that uses `{name}` still negotiates locale \"{}\"",
3997                                m.tag
3998                            ),
3999                            "remove `private`: a bundle's visibility follows its `@reference` block"
4000                                .to_string(),
4001                        )
4002                    };
4003                    errors.push_for(
4004                        Some(&parsed[i].identity_path()),
4005                        CompileError::new(
4006                            "bynk.visibility.private_messages",
4007                            private_span,
4008                            message,
4009                        )
4010                        .with_note(note),
4011                    );
4012                }
4013            }
4014        }
4015        // Locale-negotiation-slice-2 follow-up (#886): the synthetic `render`
4016        // this commons gets (`synthetic_render_fn`, symbols.rs) names
4017        // `LocaleTag`/`Message` by `TypeRef::Named` — real, resolved
4018        // references, not bypassed — so both `bynk.locale` (for `render`
4019        // itself) and `bynk.locale.types` (for the types its signature
4020        // names) must be `uses`d. Kept as one diagnostic, not two: a message
4021        // bundle always needs both together, so splitting the code would
4022        // just be two author-facing fixes for one underlying requirement.
4023        let targets = unit_uses.get(name);
4024        let has_locale_uses =
4025            targets.is_some_and(|targets| targets.iter().any(|t| t == firstparty::LOCALE_UNIT));
4026        let has_locale_types_uses = targets
4027            .is_some_and(|targets| targets.iter().any(|t| t == firstparty::LOCALE_TYPES_UNIT));
4028        if !has_locale_uses || !has_locale_types_uses {
4029            let missing = match (has_locale_uses, has_locale_types_uses) {
4030                (false, false) => "`bynk.locale` and `bynk.locale.types`",
4031                (false, true) => "`bynk.locale`",
4032                (true, false) => "`bynk.locale.types`",
4033                (true, true) => unreachable!("at least one of the two is missing here"),
4034            };
4035            errors.push_for(
4036                Some(&parsed[first_i].identity_path()),
4037                CompileError::new(
4038                    "bynk.messages.missing_locale_dependency",
4039                    first_span,
4040                    format!("a commons declaring `messages` must also `uses` {missing}"),
4041                ),
4042            );
4043        }
4044    }
4045}
4046
4047/// Locale capability track, slice 2 (#882): a context whose direct `uses`
4048/// reaches two or more message-bundle commons has no principled single
4049/// answer for what `Locale.current()` should negotiate against — but this
4050/// is only worth diagnosing when the context actually `consumes bynk {
4051/// Locale }` at all; a context with 2+ bundles that never touches `Locale`
4052/// has nothing ambiguous to resolve.
4053///
4054/// P5.0 (`design/tracks/semantics-in-the-checker.md` §6): relocated verbatim
4055/// from `bynk-emit/src/project/validate.rs`'s `check_locale_bundle_ambiguity`
4056/// — category 3 of `analysis.rs`'s own seven-category accounting, the second
4057/// of this slice's two live editor-diagnostics regressions.
4058pub fn phase_locale_bundle_ambiguity(
4059    parsed: &[ParsedFile],
4060    groups: &BTreeMap<String, Vec<usize>>,
4061    kinds: &BTreeMap<String, UnitKind>,
4062    unit_uses: &HashMap<String, Vec<String>>,
4063    unit_flattened: &HashMap<String, HashMap<String, String>>,
4064    errors: &mut ErrorSink,
4065) {
4066    for (name, indices) in groups {
4067        if kinds.get(name) != Some(&UnitKind::Context) {
4068            continue;
4069        }
4070        let ContextMessageBundle::Many(bundles) =
4071            detect_context_message_bundle(name, unit_uses, groups, kinds, parsed)
4072        else {
4073            continue;
4074        };
4075        let consumes_locale = unit_flattened
4076            .get(name)
4077            .and_then(|m| m.get("Locale"))
4078            .is_some_and(|owner| owner == firstparty::BYNK_UNIT);
4079        if !consumes_locale {
4080            continue;
4081        }
4082        for &i in indices {
4083            for c in parsed[i].consumes() {
4084                if c.target.joined() != firstparty::BYNK_UNIT {
4085                    continue;
4086                }
4087                let Some(locale_ident) = c
4088                    .selected
4089                    .iter()
4090                    .flatten()
4091                    .map(|i| &i.name)
4092                    .find(|id| id.name == "Locale")
4093                else {
4094                    continue;
4095                };
4096                let mut err = CompileError::new(
4097                    "bynk.locale.multiple_message_bundles",
4098                    locale_ident.span,
4099                    format!(
4100                        "context `{name}` uses {} message bundles ({}) — `Locale.current()` has no single bundle to negotiate against",
4101                        bundles.len(),
4102                        bundles.join(", "),
4103                    ),
4104                );
4105                for &j in indices {
4106                    for u in parsed[j].uses() {
4107                        if bundles.contains(&u.target.joined()) {
4108                            err = err
4109                                .with_label(u.span, format!("`{}` used here", u.target.joined()));
4110                        }
4111                    }
4112                }
4113                errors.push_for(Some(&parsed[i].identity_path()), err);
4114            }
4115        }
4116    }
4117}
4118
4119/// A message bundle entry's ICU template, syntax-checked at parse time
4120/// against the ICU MessageFormat grammar `icu.rs` implements. Relocated
4121/// alongside `phase_messages_bundles` (P5.0) — its only caller.
4122fn check_entry_icu_syntax(entry: &MessageEntry, file: Option<&Path>, errors: &mut ErrorSink) {
4123    for (inner_offset, inner) in icu::icu_dispatch_placeholders(&entry.template) {
4124        if let Err(e) = icu::parse_icu_placeholder(inner) {
4125            let decoded_start = inner_offset + e.offset;
4126            let decoded_span = Span::new(decoded_start, decoded_start + e.len);
4127            let raw_span = decoded_span.offset(entry.template_span.start + 1);
4128            errors.push_for(
4129                file,
4130                CompileError::new(
4131                    "bynk.messages.malformed_icu_syntax",
4132                    raw_span,
4133                    e.kind.message(),
4134                ),
4135            );
4136        }
4137    }
4138}
4139
4140/// Events track, slice 0 (spine #936): a `from Events(E)` subscription must
4141/// name a real, declared event — owned either by this context or by a
4142/// context it `consumes` (mirroring `discover_event_subscribers`'s own
4143/// ownership resolution, `project.rs`, which silently drops an unresolvable
4144/// subscription rather than diagnosing it). Runs at the project-wide phase
4145/// (needs `unit_tables` + `unit_consumes` together, unlike the local, per-
4146/// context `check_service_protocols`), alongside the other cross-unit checks
4147/// that need the same two maps.
4148///
4149/// P5.1 (`design/tracks/semantics-in-the-checker.md` §6): relocated verbatim
4150/// from `bynk-emit/src/project/validate.rs`'s `check_event_subscriptions` —
4151/// category 4 of `analysis.rs`'s own seven-category accounting, the third
4152/// live editor-diagnostics regression this track closes.
4153pub fn phase_event_subscriptions(
4154    parsed: &[ParsedFile],
4155    groups: &BTreeMap<String, Vec<usize>>,
4156    kinds: &BTreeMap<String, UnitKind>,
4157    unit_tables: &HashMap<String, UnitTable>,
4158    unit_consumes: &HashMap<String, Vec<String>>,
4159    unit_uses: &HashMap<String, Vec<String>>,
4160    errors: &mut ErrorSink,
4161) {
4162    for (name, indices) in groups {
4163        if kinds.get(name) != Some(&UnitKind::Context) {
4164            continue;
4165        }
4166        let consumed = unit_consumes.get(name).cloned().unwrap_or_default();
4167        for &i in indices {
4168            for item in parsed[i].items() {
4169                let CommonsItem::Service(s) = item else {
4170                    continue;
4171                };
4172                let ServiceProtocol::Events {
4173                    event_type,
4174                    pattern,
4175                    schema_dispatch,
4176                } = &s.protocol
4177                else {
4178                    continue;
4179                };
4180                // Events track, slice 4 (spine #936): `via schema(N)`'s
4181                // legality needs nothing about the subscribed event itself
4182                // (unlike the payload pattern below), so it's checked
4183                // independently of whether the subscription even resolves.
4184                if let Some(dispatch) = schema_dispatch {
4185                    check_schema_dispatch(dispatch, &parsed[i].identity_path(), errors);
4186                }
4187                let TypeRef::Named(id) = event_type else {
4188                    continue;
4189                };
4190                let owner_locally = unit_tables
4191                    .get(name)
4192                    .filter(|t| t.events.contains_key(&id.name))
4193                    .map(|_| name.clone());
4194                let owner_consumed = consumed.iter().find(|c| {
4195                    unit_tables
4196                        .get(*c)
4197                        .is_some_and(|t| t.events.contains_key(&id.name))
4198                });
4199                let owner = owner_locally
4200                    .as_deref()
4201                    .or(owner_consumed.map(String::as_str));
4202                let Some(owner) = owner else {
4203                    errors.push_for(
4204                        Some(&parsed[i].identity_path()),
4205                        CompileError::new(
4206                            "bynk.event.unknown_subscription",
4207                            id.span,
4208                            format!(
4209                                "`{}` is not a declared event in this context or any consumed context",
4210                                id.name
4211                            ),
4212                        )
4213                        .with_note(
4214                            "check the spelling, or add `consumes <context>` for the context whose `event` this names — an unresolvable subscription never receives anything, silently",
4215                        ),
4216                    );
4217                    continue;
4218                };
4219                // Events track, slice 1 (spine #936): once the event itself
4220                // resolves, check the subscription pattern's fields against
4221                // its declared record shape. No pattern is the pattern-less
4222                // form (slice 0) and needs none of this.
4223                let Some(pattern) = pattern else {
4224                    continue;
4225                };
4226                let Some(event_decl) = unit_tables.get(owner).and_then(|t| t.events.get(&id.name))
4227                else {
4228                    continue;
4229                };
4230                check_event_pattern(
4231                    pattern,
4232                    event_decl,
4233                    owner,
4234                    unit_tables,
4235                    unit_uses,
4236                    &parsed[i].identity_path(),
4237                    errors,
4238                );
4239            }
4240        }
4241    }
4242}
4243
4244/// Events track, slice 1 (spine #936): resolve a subscription pattern's
4245/// fields/values against the owning event's declared record shape. `owner`
4246/// is the context that declares `event_decl` (may differ from the
4247/// subscribing context, reached via `consumes`) — a field's own type (e.g. a
4248/// discriminator sum like `Region`) resolves against the *owner's* types
4249/// (locally declared, or pulled in via the owner's own `uses <commons>`),
4250/// mirroring how the field's type is resolved everywhere else the event's
4251/// record shape is used.
4252fn check_event_pattern(
4253    pattern: &EventPattern,
4254    event_decl: &EventDecl,
4255    owner: &str,
4256    unit_tables: &HashMap<String, UnitTable>,
4257    unit_uses: &HashMap<String, Vec<String>>,
4258    identity_path: &std::path::Path,
4259    errors: &mut ErrorSink,
4260) {
4261    let mut seen: HashSet<String> = HashSet::new();
4262    for field in &pattern.fields {
4263        if !seen.insert(field.name.name.clone()) {
4264            errors.push_for(
4265                Some(identity_path),
4266                CompileError::new(
4267                    "bynk.event.pattern_duplicate_field",
4268                    field.name.span,
4269                    format!(
4270                        "field `{}` is matched more than once in this subscription pattern",
4271                        field.name.name
4272                    ),
4273                ),
4274            );
4275            continue;
4276        }
4277        let Some(record_field) = event_decl
4278            .body
4279            .fields
4280            .iter()
4281            .find(|f| f.name.name == field.name.name)
4282        else {
4283            let known: Vec<&str> = event_decl
4284                .body
4285                .fields
4286                .iter()
4287                .map(|f| f.name.name.as_str())
4288                .collect();
4289            errors.push_for(
4290                Some(identity_path),
4291                CompileError::new(
4292                    "bynk.event.pattern_unknown_field",
4293                    field.name.span,
4294                    format!(
4295                        "`{}` has no field named `{}`",
4296                        event_decl.name.name, field.name.name
4297                    ),
4298                )
4299                .with_note(format!(
4300                    "declared fields: {}",
4301                    if known.is_empty() {
4302                        "(none)".to_string()
4303                    } else {
4304                        known.join(", ")
4305                    }
4306                )),
4307            );
4308            continue;
4309        };
4310        check_event_pattern_value(
4311            &field.value,
4312            record_field,
4313            owner,
4314            unit_tables,
4315            unit_uses,
4316            identity_path,
4317            errors,
4318        );
4319    }
4320}
4321
4322/// Events track, slice 4 (spine #936): `via schema(N)`'s `N` must be a
4323/// positive `Int` literal — the identical rule `@schema(N)` already
4324/// enforces (`bynk.event.bad_schema_version`), reused under its own code
4325/// since the two are unrelated syntax positions (an annotation on the
4326/// event's own declaration vs. a clause on a subscriber's header).
4327fn check_schema_dispatch(
4328    dispatch: &SchemaDispatch,
4329    identity_path: &std::path::Path,
4330    errors: &mut ErrorSink,
4331) {
4332    // Each bound is checked on its own (#990); a range's inverted bounds are
4333    // the shared range check's `bynk.types.empty_range_pattern` (#2699).
4334    let (lo, hi) = match &dispatch.pattern {
4335        SchemaVersionPattern::Literal(n) => (Some(*n), Some(*n)),
4336        SchemaVersionPattern::Range(r) => (r.lo, r.hi),
4337        SchemaVersionPattern::Wildcard => return,
4338    };
4339    if lo.into_iter().chain(hi).any(|n| n <= 0) {
4340        errors.push_for(
4341            Some(identity_path),
4342            CompileError::new(
4343                "bynk.event.bad_schema_dispatch",
4344                dispatch.span,
4345                "`via schema(...)`'s version bounds must be positive `Int` literals",
4346            ),
4347        );
4348        return;
4349    }
4350    if let SchemaVersionPattern::Range(r) = &dispatch.pattern
4351        && let Some(err) = crate::checker::empty_range_error(r, "`via schema(...)`")
4352    {
4353        errors.push_for(Some(identity_path), err);
4354    }
4355}
4356
4357/// Resolve one pattern field's matched value against that field's declared
4358/// type — a literal must match the field's base type; a variant must name a
4359/// nullary member of the field's sum type.
4360fn check_event_pattern_value(
4361    value: &EventPatternValue,
4362    record_field: &RecordField,
4363    owner: &str,
4364    unit_tables: &HashMap<String, UnitTable>,
4365    unit_uses: &HashMap<String, Vec<String>>,
4366    identity_path: &std::path::Path,
4367    errors: &mut ErrorSink,
4368) {
4369    match value {
4370        EventPatternValue::Literal {
4371            value: lit, span, ..
4372        } => {
4373            // A base type (`Int`/`String`/`Bool`/…) is its own `TypeRef`
4374            // variant, not `TypeRef::Named` — only a *user*-declared type
4375            // (including a refined/opaque type built on a base) goes through
4376            // `resolve_type_decl`. An earlier version of this match only
4377            // handled the `Named` case, so a plain `orderId: String` field
4378            // (the common case) fell through to "not a literal-kind type",
4379            // caught by `events_workers_wiring.rs`'s patterned fixture.
4380            let base = match &record_field.type_ref {
4381                TypeRef::Base(b, _) => Some(*b),
4382                TypeRef::Named(field_type_name) => {
4383                    resolve_type_decl(unit_tables, unit_uses, owner, &field_type_name.name)
4384                        .and_then(|d| match &d.body {
4385                            TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. } => {
4386                                Some(*base)
4387                            }
4388                            _ => None,
4389                        })
4390                }
4391                _ => None,
4392            };
4393            let Some(base) = base else {
4394                errors.push_for(
4395                    Some(identity_path),
4396                    CompileError::new(
4397                        "bynk.event.pattern_type_mismatch",
4398                        *span,
4399                        format!(
4400                            "field `{}` is not a literal-kind type — a literal pattern value cannot match it",
4401                            record_field.name.name
4402                        ),
4403                    ),
4404                );
4405                return;
4406            };
4407            let kind_matches = matches!(
4408                (lit, base),
4409                (LiteralValue::Int(_), BaseType::Int)
4410                    | (LiteralValue::Str(_), BaseType::String)
4411                    | (LiteralValue::Bool(_), BaseType::Bool)
4412            );
4413            if !kind_matches {
4414                errors.push_for(
4415                    Some(identity_path),
4416                    CompileError::new(
4417                        "bynk.event.pattern_type_mismatch",
4418                        *span,
4419                        format!(
4420                            "this literal does not match the type of field `{}` (`{}`)",
4421                            record_field.name.name,
4422                            type_ref_to_display(&record_field.type_ref)
4423                        ),
4424                    ),
4425                );
4426            }
4427        }
4428        EventPatternValue::Variant {
4429            type_name,
4430            variant,
4431            span,
4432        } => {
4433            let TypeRef::Named(field_type_name) = &record_field.type_ref else {
4434                errors.push_for(
4435                    Some(identity_path),
4436                    CompileError::new(
4437                        "bynk.event.pattern_type_mismatch",
4438                        *span,
4439                        format!(
4440                            "field `{}` is not a sum type — a variant pattern value cannot match it",
4441                            record_field.name.name
4442                        ),
4443                    ),
4444                );
4445                return;
4446            };
4447            if let Some(qualifier) = type_name
4448                && qualifier.name != field_type_name.name
4449            {
4450                errors.push_for(
4451                    Some(identity_path),
4452                    CompileError::new(
4453                        "bynk.event.pattern_type_mismatch",
4454                        qualifier.span,
4455                        format!(
4456                            "field `{}` has type `{}`, not `{}`",
4457                            record_field.name.name, field_type_name.name, qualifier.name
4458                        ),
4459                    ),
4460                );
4461                return;
4462            }
4463            let Some(decl) =
4464                resolve_type_decl(unit_tables, unit_uses, owner, &field_type_name.name)
4465            else {
4466                // The field's own type failed to resolve — a different,
4467                // pre-existing check (ordinary type-reference resolution)
4468                // already reports this; don't double-report it here.
4469                return;
4470            };
4471            let TypeBody::Sum(sum) = &decl.body else {
4472                errors.push_for(
4473                    Some(identity_path),
4474                    CompileError::new(
4475                        "bynk.event.pattern_type_mismatch",
4476                        *span,
4477                        format!(
4478                            "field `{}` has type `{}`, which is not a sum type",
4479                            record_field.name.name, field_type_name.name
4480                        ),
4481                    ),
4482                );
4483                return;
4484            };
4485            let Some(member) = sum.variants.iter().find(|v| v.name.name == variant.name) else {
4486                errors.push_for(
4487                    Some(identity_path),
4488                    CompileError::new(
4489                        "bynk.event.pattern_unknown_variant",
4490                        variant.span,
4491                        format!(
4492                            "`{}` has no variant named `{}`",
4493                            field_type_name.name, variant.name
4494                        ),
4495                    ),
4496                );
4497                return;
4498            };
4499            if !member.payload.is_empty() {
4500                errors.push_for(
4501                    Some(identity_path),
4502                    CompileError::new(
4503                        "bynk.event.pattern_variant_payload",
4504                        variant.span,
4505                        format!(
4506                            "`{}.{}` carries a payload — only a nullary variant may be matched here, since testing the tag alone would silently ignore the payload",
4507                            field_type_name.name, variant.name
4508                        ),
4509                    ),
4510                );
4511            }
4512        }
4513    }
4514}
4515
4516/// Resolve a named type as `owner` sees it: the context's own `types` first,
4517/// then any commons unit it `uses`. Events track slice 1 (spine #936) needs
4518/// this because a pattern field's type (e.g. a discriminator sum) may be
4519/// declared in a commons the event's owning context pulls in with `uses`,
4520/// rather than in the context itself.
4521fn resolve_type_decl<'a>(
4522    unit_tables: &'a HashMap<String, UnitTable>,
4523    unit_uses: &HashMap<String, Vec<String>>,
4524    owner: &str,
4525    name: &str,
4526) -> Option<&'a Arc<TypeDecl>> {
4527    if let Some(t) = unit_tables.get(owner).and_then(|t| t.types.get(name)) {
4528        return Some(t);
4529    }
4530    for used in unit_uses.get(owner).into_iter().flatten() {
4531        if let Some(t) = unit_tables.get(used).and_then(|t| t.types.get(name)) {
4532            return Some(t);
4533        }
4534    }
4535    None
4536}
4537
4538/// Phase 6b: validate each context/adapter's `exports opaque/transparent { … }`
4539/// clauses — every name must be a locally-declared type, with no duplicates
4540/// within a clause or conflicting visibilities across clauses. Returns unit →
4541/// (type → visibility); diagnostics go into `errors` and export references into
4542/// `refs`.
4543pub fn phase_validate_type_exports(
4544    groups: &BTreeMap<String, Vec<usize>>,
4545    kinds: &BTreeMap<String, UnitKind>,
4546    parsed: &[ParsedFile],
4547    unit_tables: &HashMap<String, UnitTable>,
4548    errors: &mut ErrorSink,
4549    refs: &mut RefSink,
4550) -> HashMap<String, HashMap<String, Visibility>> {
4551    let mut exports_visibility: HashMap<String, HashMap<String, Visibility>> = HashMap::new();
4552    for (name, indices) in groups {
4553        let kind = *kinds.get(name).unwrap();
4554        if kind != UnitKind::Context && kind != UnitKind::Adapter {
4555            // Commons may not have exports clauses (parsed grammar prevents it
4556            // at the parser level), but in case any sneak in, skip.
4557            continue;
4558        }
4559        let local = unit_tables.get(name).unwrap();
4560        let mut seen: HashMap<String, (Visibility, Span)> = HashMap::new();
4561        for &i in indices {
4562            refs.enter_file(&parsed[i].identity_path(), name, parsed[i].is_synthetic());
4563            for clause in parsed[i].exports() {
4564                // v0.15: `exports capability { ... }` clauses are validated
4565                // separately (§4.1); 6b handles only type exports.
4566                let ExportKind::Type(clause_vis) = clause.kind else {
4567                    continue;
4568                };
4569                let mut within: HashMap<String, Span> = HashMap::new();
4570                for n in clause.names.iter().map(|e| &e.name) {
4571                    if let Some(prev) = within.get(&n.name) {
4572                        errors.push_for(
4573                            Some(&parsed[i].identity_path()),
4574                            CompileError::new(
4575                                "bynk.exports.duplicate_in_clause",
4576                                n.span,
4577                                format!(
4578                                    "type `{}` appears more than once in this exports clause",
4579                                    n.name
4580                                ),
4581                            )
4582                            .with_label(*prev, "previously listed here"),
4583                        );
4584                        continue;
4585                    }
4586                    within.insert(n.name.clone(), n.span);
4587
4588                    if !local.types.contains_key(&n.name) {
4589                        errors.push_for(Some(&parsed[i].identity_path()),
4590                            CompileError::new(
4591                                "bynk.exports.undeclared_type",
4592                                n.span,
4593                                format!(
4594                                    "exports clause references `{}`, which is not a type declared in context `{}`",
4595                                    n.name, name
4596                                ),
4597                            )
4598                            .with_note(
4599                                "only types declared in the same context can appear in `exports` clauses",
4600                            ),
4601                        );
4602                        continue;
4603                    }
4604                    // v0.25: `exports opaque/transparent { T }` names the type.
4605                    refs.record(n.span, SymbolKind::Type, &n.name);
4606
4607                    if let Some((prev_vis, prev_span)) = seen.get(&n.name) {
4608                        if *prev_vis == clause_vis {
4609                            errors.push_for(
4610                                Some(&parsed[i].identity_path()),
4611                                CompileError::new(
4612                                    "bynk.exports.duplicate_export",
4613                                    n.span,
4614                                    format!("type `{}` is exported more than once", n.name),
4615                                )
4616                                .with_label(*prev_span, "previously exported here"),
4617                            );
4618                        } else {
4619                            errors.push_for(Some(&parsed[i].identity_path()),
4620                                CompileError::new(
4621                                    "bynk.exports.conflicting_visibility",
4622                                    n.span,
4623                                    format!(
4624                                        "type `{}` is exported with conflicting visibilities — pick `opaque` or `transparent`",
4625                                        n.name,
4626                                    ),
4627                                )
4628                                .with_label(*prev_span, "previously exported here"),
4629                            );
4630                        }
4631                        continue;
4632                    }
4633                    seen.insert(n.name.clone(), (clause_vis, n.span));
4634                }
4635            }
4636        }
4637        let mut visibility_map: HashMap<String, Visibility> = HashMap::new();
4638        for (n, (v, _)) in seen {
4639            visibility_map.insert(n, v);
4640        }
4641        exports_visibility.insert(name.clone(), visibility_map);
4642    }
4643    exports_visibility
4644}
4645
4646/// Phase 6b': validate each context/adapter's `exports capability { … }` clauses
4647/// (v0.15 §4.1) — every name must be a capability the unit declares *and*
4648/// provides, with no duplicate exports. Diagnostics go into `errors` and export
4649/// references into `refs`.
4650pub fn phase_validate_capability_exports(
4651    groups: &BTreeMap<String, Vec<usize>>,
4652    kinds: &BTreeMap<String, UnitKind>,
4653    parsed: &[ParsedFile],
4654    unit_tables: &HashMap<String, UnitTable>,
4655    errors: &mut ErrorSink,
4656    refs: &mut RefSink,
4657) {
4658    for (name, indices) in groups {
4659        if kinds.get(name) != Some(&UnitKind::Context)
4660            && kinds.get(name) != Some(&UnitKind::Adapter)
4661        {
4662            continue;
4663        }
4664        let local = unit_tables.get(name).unwrap();
4665        let mut seen: HashMap<String, Span> = HashMap::new();
4666        for &i in indices {
4667            refs.enter_file(&parsed[i].identity_path(), name, parsed[i].is_synthetic());
4668            for clause in parsed[i].exports() {
4669                if !matches!(clause.kind, ExportKind::Capability) {
4670                    continue;
4671                }
4672                for n in clause.names.iter().map(|e| &e.name) {
4673                    if let Some(prev) = seen.get(&n.name) {
4674                        errors.push_for(
4675                            Some(&parsed[i].identity_path()),
4676                            CompileError::new(
4677                                "bynk.exports.duplicate_export",
4678                                n.span,
4679                                format!("capability `{}` is exported more than once", n.name),
4680                            )
4681                            .with_label(*prev, "previously exported here"),
4682                        );
4683                        continue;
4684                    }
4685                    seen.insert(n.name.clone(), n.span);
4686                    if local.capabilities.contains_key(&n.name) {
4687                        // v0.25: `exports capability { Cap }` names the
4688                        // capability.
4689                        refs.record(n.span, SymbolKind::Capability, &n.name);
4690                    }
4691                    if !local.capabilities.contains_key(&n.name) {
4692                        errors.push_for(Some(&parsed[i].identity_path()),
4693                            CompileError::new(
4694                                "bynk.exports.undeclared_capability",
4695                                n.span,
4696                                format!(
4697                                    "`exports capability` references `{}`, which is not a capability declared in context `{}`",
4698                                    n.name, name
4699                                ),
4700                            )
4701                            .with_note(
4702                                "only capabilities declared in the same context can appear in `exports capability` clauses",
4703                            ),
4704                        );
4705                        continue;
4706                    }
4707                    // S4a (#1966): a derived capability is refused as an export
4708                    // in its own right (`bynk.exports.derived_capability`); its
4709                    // provision is implied, so "no provider" would mislead.
4710                    let derived = local
4711                        .capabilities
4712                        .get(&n.name)
4713                        .is_some_and(|c| c.derived.is_some());
4714                    if !derived && !local.providers.contains_key(&n.name) {
4715                        errors.push_for(Some(&parsed[i].identity_path()),
4716                            CompileError::new(
4717                                "bynk.exports.capability_not_provided",
4718                                n.span,
4719                                format!(
4720                                    "exported capability `{}` has no provider in context `{}` — a consumer cannot instantiate it",
4721                                    n.name, name
4722                                ),
4723                            )
4724                            .with_note(format!(
4725                                "add a `provides {} = …` declaration so the capability can be wired into consumers",
4726                                n.name
4727                            )),
4728                        );
4729                    }
4730                }
4731            }
4732        }
4733    }
4734}
4735
4736/// Phase 6c: validate that every (non-external) provider matches its capability
4737/// exactly — each capability op has a provider op, and every provider op has a
4738/// matching capability op with the same parameter and return types. Diagnostics
4739/// go into `errors`.
4740pub fn phase_validate_providers(
4741    unit_tables: &HashMap<String, UnitTable>,
4742    // #696: the merged `UnitTable` has flattened a unit's files away, so provider
4743    // diagnostics need the group's files to recover which one declares each
4744    // provider and attribute the diagnostic to it.
4745    groups: &BTreeMap<String, Vec<usize>>,
4746    parsed: &[ParsedFile],
4747    // #1710: each unit's declarations recovery skipped (`phase_parse`).
4748    broken: &BrokenDeclNames,
4749    errors: &mut ErrorSink,
4750    tys: &Arc<Types>,
4751) {
4752    for (name, table) in unit_tables {
4753        // Map each provided capability to the project-relative path of the file
4754        // that declares its provider — every diagnostic below carries a span into
4755        // that file.
4756        let provider_files: HashMap<&str, PathBuf> = groups
4757            .get(name)
4758            .map(|indices| {
4759                indices
4760                    .iter()
4761                    .flat_map(|&i| {
4762                        parsed[i].items().iter().filter_map(move |item| match item {
4763                            CommonsItem::Provider(p) => {
4764                                Some((p.capability.name.as_str(), parsed[i].identity_path()))
4765                            }
4766                            _ => None,
4767                        })
4768                    })
4769                    .collect()
4770            })
4771            .unwrap_or_default();
4772        for (cap_name, provider) in &table.providers {
4773            let provider_file = provider_files.get(cap_name.as_str()).map(|p| p.as_path());
4774            // v0.17: an external provider has no Bynk body to match against the
4775            // capability — its implementation is the binding, checked by `tsc`.
4776            if provider.external {
4777                continue;
4778            }
4779            let Some(cap) = table.capabilities.get(cap_name) else {
4780                // #1710: a capability recovery skipped is a known name; its
4781                // syntax error is the report, and the provider has nothing to
4782                // be matched against until it's fixed.
4783                if broken.get(name).is_some_and(|b| b.contains(cap_name)) {
4784                    continue;
4785                }
4786                errors.push_for(provider_file,
4787                    CompileError::new(
4788                        "bynk.provider.unknown_capability",
4789                        provider.capability.span,
4790                        format!(
4791                            "provider targets unknown capability `{}` — declare the capability in the same context",
4792                            cap_name
4793                        ),
4794                    ),
4795                );
4796                continue;
4797            };
4798            // #926 (Decision E): a capability op with its own type parameter(s)
4799            // cannot be implemented by a Bynk-bodied provider — the body would
4800            // need `T` rigid through the handler-body checker for a body that
4801            // can only ever return `None` or echo a `T`-typed parameter.
4802            // External providers (checked above) are exempt: TypeScript
4803            // natively supports a generic interface method, so a hand-authored
4804            // binding class implements it directly.
4805            for cap_op in &cap.ops {
4806                if !cap_op.type_params.is_empty() {
4807                    errors.push_for(
4808                        provider_file,
4809                        CompileError::new(
4810                            "bynk.provider.generic_op_requires_external",
4811                            provider.span,
4812                            format!(
4813                                "provider `{}` for capability `{}` has a Bynk body, but operation `{}` declares its own type parameter(s) (`[{}]`) — a generic capability operation requires an external (bodiless) provider",
4814                                provider.provider_name.name,
4815                                cap_name,
4816                                cap_op.name.name,
4817                                cap_op
4818                                    .type_params
4819                                    .iter()
4820                                    .map(|p| p.name.name.as_str())
4821                                    .collect::<Vec<_>>()
4822                                    .join(", "),
4823                            ),
4824                        )
4825                        .with_note(
4826                            "write `provides Cap = Name` with no `{ … }` block, and supply the implementation as a hand-authored class in the adapter's binding file",
4827                        ),
4828                    );
4829                }
4830            }
4831            // 1) Every capability op has a provider op.
4832            for cap_op in &cap.ops {
4833                if !provider.ops.iter().any(|o| o.name.name == cap_op.name.name) {
4834                    errors.push_for(
4835                        provider_file,
4836                        CompileError::new(
4837                            "bynk.provider.missing_operation",
4838                            provider.span,
4839                            format!(
4840                                "provider `{}` for capability `{}` is missing operation `{}`",
4841                                provider.provider_name.name, cap_name, cap_op.name.name
4842                            ),
4843                        ),
4844                    );
4845                }
4846            }
4847            // 2) Every provider op corresponds to a capability op with the
4848            //    same signature (param types and return type).
4849            for prov_op in &provider.ops {
4850                let Some(cap_op) = cap.ops.iter().find(|o| o.name.name == prov_op.name.name) else {
4851                    errors.push_for(provider_file, CompileError::new(
4852                        "bynk.provider.extra_operation",
4853                        prov_op.span,
4854                        format!(
4855                            "provider operation `{}.{}` does not match any operation in capability `{}`",
4856                            provider.provider_name.name, prov_op.name.name, cap_name
4857                        ),
4858                    ));
4859                    continue;
4860                };
4861                if cap_op.params.len() != prov_op.params.len() {
4862                    errors.push_for(provider_file, CompileError::new(
4863                        "bynk.provider.signature_mismatch",
4864                        prov_op.span,
4865                        format!(
4866                            "provider operation `{}.{}` has {} parameter(s), but capability operation expects {}",
4867                            provider.provider_name.name,
4868                            prov_op.name.name,
4869                            prov_op.params.len(),
4870                            cap_op.params.len()
4871                        ),
4872                    ));
4873                    continue;
4874                }
4875                // Resolved-`Ty` equality, not surface-syntax comparison: two
4876                // signatures that spell a type differently (an alias, or a
4877                // generic application written out) but resolve to the same
4878                // `Ty` must not be flagged as a mismatch, and — the bug this
4879                // replaces — a `TypeRef` shape `type_refs_match` didn't cover
4880                // (List/Map/Query/Stream/Connection/…) must not be silently
4881                // treated as *matching* just because it fell through to
4882                // `_ => false` on both sides of an `!`. A Bynk-bodied
4883                // provider op has no type params of its own (checked above),
4884                // so its params/return type resolve with no vars in scope.
4885                let cap_info = build_capability_op_info(cap_op, &table.types, tys);
4886                let no_vars = HashSet::new();
4887                let prov_params: Vec<TyId> = prov_op
4888                    .params
4889                    .iter()
4890                    .map(|p| {
4891                        checker::resolve_type_ref_in(&p.type_ref, &table.types, &no_vars, tys)
4892                            .unwrap_or(tys.intern(Ty::Unit))
4893                    })
4894                    .collect();
4895                let prov_return_ty =
4896                    checker::resolve_type_ref_in(&prov_op.return_type, &table.types, &no_vars, tys)
4897                        .unwrap_or(tys.intern(Ty::Unit));
4898                for (i, (cap_ty, (prov_p, prov_ty))) in cap_info
4899                    .params
4900                    .iter()
4901                    .zip(prov_op.params.iter().zip(prov_params.iter()))
4902                    .enumerate()
4903                {
4904                    if cap_ty != prov_ty {
4905                        errors.push_for(provider_file, CompileError::new(
4906                            "bynk.provider.signature_mismatch",
4907                            prov_p.span,
4908                            format!(
4909                                "provider operation `{}.{}` parameter {} has type `{}`, but capability declares `{}`",
4910                                provider.provider_name.name,
4911                                prov_op.name.name,
4912                                i + 1,
4913                                ts_type_ref_display(&prov_p.type_ref),
4914                                ts_type_ref_display(&cap_op.params[i].type_ref)
4915                            ),
4916                        ));
4917                    }
4918                }
4919                if cap_info.return_ty != prov_return_ty {
4920                    errors.push_for(provider_file, CompileError::new(
4921                        "bynk.provider.signature_mismatch",
4922                        prov_op.return_type.span(),
4923                        format!(
4924                            "provider operation `{}.{}` returns `{}`, but capability declares `{}`",
4925                            provider.provider_name.name,
4926                            prov_op.name.name,
4927                            ts_type_ref_display(&prov_op.return_type),
4928                            ts_type_ref_display(&cap_op.return_type)
4929                        ),
4930                    ));
4931                }
4932            }
4933        }
4934    }
4935}
4936
4937/// v0.19: the lock violation a deployment unit's native-platform set implies
4938/// under the selected `--platform`, if any. Pure — unit-tested below with
4939/// synthetic sets (the conflict arm is not yet reachable end-to-end while
4940/// only one platform ships native capabilities).
4941///
4942/// P5.3 (`design/tracks/semantics-in-the-checker.md` §6): relocated
4943/// verbatim from `bynk-emit/src/project/validate.rs`, alongside
4944/// [`phase_platform_lock`].
4945fn lock_violation(
4946    native: &BTreeMap<Platform, String>,
4947    selected: Platform,
4948) -> Option<LockViolation> {
4949    let mut platforms = native.iter();
4950    let (first, first_unit) = platforms.next()?;
4951    if let Some((second, second_unit)) = platforms.next() {
4952        return Some(LockViolation::Conflict {
4953            a: (*first, first_unit.clone()),
4954            b: (*second, second_unit.clone()),
4955        });
4956    }
4957    if *first != selected {
4958        return Some(LockViolation::Required {
4959            needed: *first,
4960            unit: first_unit.clone(),
4961        });
4962    }
4963    None
4964}
4965
4966/// One deployment unit the platform lock checks (#3562): the contexts that
4967/// deploy together and the union of their native platforms.
4968#[derive(Debug, PartialEq, Eq)]
4969struct LockUnit {
4970    /// The `[deploy.workers]` group's key, for a unit that is one.
4971    group: Option<String>,
4972    /// The contexts in the unit, in the order their `consumes` are looked up.
4973    members: Vec<String>,
4974    /// The unit's native platforms, each with the unit that brings it in.
4975    native: BTreeMap<Platform, String>,
4976}
4977
4978/// The deployment units to check, from each context's native platforms:
4979/// under `workers`, one per `[deploy.workers]` group (the union of its members',
4980/// since they share a Worker) and one per context in no group; under `bundle`,
4981/// the union of everything (the whole program co-locates).
4982fn lock_units(
4983    target: BuildTarget,
4984    per_context: Vec<(String, BTreeMap<Platform, String>)>,
4985    worker_groups: &bynk_project::worker_groups::WorkerGroups,
4986) -> Vec<LockUnit> {
4987    let union_of = |natives: Vec<&BTreeMap<Platform, String>>| {
4988        let mut union = BTreeMap::new();
4989        for native in natives {
4990            for (p, unit) in native {
4991                union.entry(*p).or_insert_with(|| unit.clone());
4992            }
4993        }
4994        union
4995    };
4996    match target {
4997        BuildTarget::Workers => {
4998            let mut units = Vec::new();
4999            for (key, group) in worker_groups {
5000                let found: Vec<_> = per_context
5001                    .iter()
5002                    .filter(|(ctx, _)| group.contexts.contains(ctx))
5003                    .collect();
5004                let native = union_of(found.iter().map(|(_, n)| n).collect());
5005                if !native.is_empty() {
5006                    units.push(LockUnit {
5007                        group: Some(key.clone()),
5008                        members: found.iter().map(|(ctx, _)| ctx.clone()).collect(),
5009                        native,
5010                    });
5011                }
5012            }
5013            let grouped = |ctx: &str| {
5014                worker_groups
5015                    .values()
5016                    .any(|g| g.contexts.iter().any(|c| c == ctx))
5017            };
5018            units.extend(
5019                per_context
5020                    .into_iter()
5021                    .filter(|(ctx, _)| !grouped(ctx))
5022                    .map(|(ctx, native)| LockUnit {
5023                        group: None,
5024                        members: vec![ctx],
5025                        native,
5026                    }),
5027            );
5028            units
5029        }
5030        BuildTarget::Bundle => {
5031            let native = union_of(per_context.iter().map(|(_, n)| n).collect());
5032            match per_context.into_iter().next() {
5033                Some((owner, _)) if !native.is_empty() => vec![LockUnit {
5034                    group: None,
5035                    members: vec![owner],
5036                    native,
5037                }],
5038                _ => Vec::new(),
5039            }
5040        }
5041    }
5042}
5043
5044/// A platform-lock violation (v0.19, `bynk.target.*`).
5045#[derive(Debug, PartialEq, Eq)]
5046enum LockViolation {
5047    /// The deployment unit needs `needed` but another platform is selected.
5048    Required { needed: Platform, unit: String },
5049    /// The deployment unit's closure spans two mutually-exclusive platforms.
5050    Conflict {
5051        a: (Platform, String),
5052        b: (Platform, String),
5053    },
5054}
5055
5056/// v0.15's cross-context capability resolution, relocated alongside
5057/// [`phase_platform_lock`] (P5.3): resolve a `given`/handler capability
5058/// prefix (`ctx.Cap`) against a context's own `consumes`/alias tables. Pure —
5059/// no codegen, no `bynk-emit` dependency of its own — so unlike
5060/// `collect_given_closure` this one **is** shared rather than duplicated:
5061/// `bynk-emit/src/project.rs`'s own copy of this function (and of
5062/// [`handler_cross_caps`]) was deleted in review (#1133) and every one of its
5063/// call sites repointed here — `bynk-emit` already depends on `bynk-check`,
5064/// so there was no dependency direction to route around, and keeping two
5065/// copies only bought two things that could drift out of sync for no reason.
5066pub fn resolve_consume_prefix(
5067    prefix: &str,
5068    consumed: &[String],
5069    aliases: &HashMap<String, String>,
5070) -> Option<String> {
5071    if let Some(q) = aliases.get(prefix) {
5072        return Some(q.clone());
5073    }
5074    if consumed.iter().any(|c| c == prefix) {
5075        return Some(prefix.to_string());
5076    }
5077    None
5078}
5079
5080/// v0.15: the cross-context capabilities a context's **handlers** reference,
5081/// as `deps_key → consumed_context`. Shared with `bynk-emit`, not duplicated
5082/// — see [`resolve_consume_prefix`]'s doc.
5083pub fn handler_cross_caps(
5084    table: &UnitTable,
5085    declaring_unit: &str,
5086    consumed: &[String],
5087    aliases: &HashMap<String, String>,
5088    flattened: &HashMap<String, String>,
5089) -> BTreeMap<String, String> {
5090    let mut out = BTreeMap::new();
5091    for s in table.services.values() {
5092        for h in &s.handlers {
5093            scan_cross_caps(
5094                &mut out,
5095                &h.given,
5096                declaring_unit,
5097                consumed,
5098                aliases,
5099                flattened,
5100            );
5101        }
5102    }
5103    for a in table.agents.values() {
5104        for h in &a.handlers {
5105            scan_cross_caps(
5106                &mut out,
5107                &h.given,
5108                declaring_unit,
5109                consumed,
5110                aliases,
5111                flattened,
5112            );
5113        }
5114    }
5115    out
5116}
5117
5118/// The cross-context capabilities a context's **providers** reference in their
5119/// own `given`, as `deps_key -> consumed_context` (1B.1b, `ComposePlan`). The
5120/// Workers `compose.ts` instantiates these at the top level beside the
5121/// handlers' ([`handler_cross_caps`]); the Bundle root reaches them only
5122/// through a provider's own recursive instantiation.
5123pub fn provider_cross_caps(
5124    table: &UnitTable,
5125    declaring_unit: &str,
5126    consumed: &[String],
5127    aliases: &HashMap<String, String>,
5128    flattened: &HashMap<String, String>,
5129) -> BTreeMap<String, String> {
5130    let mut out = BTreeMap::new();
5131    for p in table.providers.values() {
5132        scan_cross_caps(
5133            &mut out,
5134            &p.given,
5135            declaring_unit,
5136            consumed,
5137            aliases,
5138            flattened,
5139        );
5140    }
5141    out
5142}
5143
5144/// One `given` list's cross-context capabilities, first reference winning.
5145fn scan_cross_caps(
5146    out: &mut BTreeMap<String, String>,
5147    given: &[CapRef],
5148    declaring_unit: &str,
5149    consumed: &[String],
5150    aliases: &HashMap<String, String>,
5151    flattened: &HashMap<String, String>,
5152) {
5153    for c in given {
5154        // Events track, slice 0 (spine #936): `Events.emit` is
5155        // intercepted entirely at the call site (release-at-commit
5156        // buffering) and never calls through a constructed provider —
5157        // there is no `EventsProvider` for compose to build, so the
5158        // first-party `Events` must never become a compose deps entry.
5159        // The canonical first-party rule (1A.33), which also covers a
5160        // capability declared by `bynk` itself.
5161        if firstparty::resolve(c.key(), declaring_unit, flattened)
5162            == Some(firstparty::FirstPartyCap::Events)
5163        {
5164            continue;
5165        }
5166        if let Some(p) = c.prefix() {
5167            if let Some(ctx) = resolve_consume_prefix(&p, consumed, aliases) {
5168                out.entry(c.key().to_string()).or_insert(ctx);
5169            }
5170        } else if let Some(unit) = flattened.get(c.key()) {
5171            // v0.17: a bare flattened capability is provided by the unit it
5172            // was flattened from.
5173            out.entry(c.key().to_string())
5174                .or_insert_with(|| unit.clone());
5175        }
5176    }
5177}
5178
5179/// The `(unit, capability)` pairs a provider capability's `given` closure
5180/// transitively reaches, itself included, recorded into `reached`. P5.3: a pure resolution walk over the
5181/// same graph `bynk-emit`'s `instantiate_provider_ts_expr` walks to build a
5182/// TypeScript instantiation expression — this one builds no TypeScript at
5183/// all, since `bynk-check` must never depend on `bynk-emit`'s codegen
5184/// (`bynk-emit` depends on `bynk-check`, never the reverse). The two walks
5185/// must keep resolving `given` targets identically (prefix → alias/consumes,
5186/// bare → flattened) or `phase_platform_lock`'s native-platform accounting
5187/// could drift from what a real build's compose actually instantiates; a
5188/// reviewer changing one should check the other.
5189fn collect_given_closure(
5190    provider_ctx: &str,
5191    cap: &str,
5192    unit_tables: &HashMap<String, UnitTable>,
5193    unit_consumes: &HashMap<String, Vec<String>>,
5194    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5195    unit_flattened: &HashMap<String, HashMap<String, String>>,
5196    reached: &mut BTreeSet<(String, String)>,
5197) {
5198    // #2355 follow-up: records `(unit, capability)` pairs rather than units,
5199    // so the cross-context agent check can find the provider itself; a pair
5200    // already seen is not walked again.
5201    if !reached.insert((provider_ctx.to_string(), cap.to_string())) {
5202        return;
5203    }
5204    let Some(provider) = unit_tables
5205        .get(provider_ctx)
5206        .and_then(|t| t.providers.get(cap))
5207    else {
5208        return;
5209    };
5210    if provider.given.is_empty() {
5211        return;
5212    }
5213    let consumed = unit_consumes.get(provider_ctx).cloned().unwrap_or_default();
5214    let aliases = unit_consumes_aliases
5215        .get(provider_ctx)
5216        .cloned()
5217        .unwrap_or_default();
5218    let flattened = unit_flattened
5219        .get(provider_ctx)
5220        .cloned()
5221        .unwrap_or_default();
5222    for g in &provider.given {
5223        let target_ctx = match g.prefix() {
5224            Some(p) => resolve_consume_prefix(&p, &consumed, &aliases)
5225                .unwrap_or_else(|| provider_ctx.to_string()),
5226            None => flattened
5227                .get(g.key())
5228                .cloned()
5229                .unwrap_or_else(|| provider_ctx.to_string()),
5230        };
5231        collect_given_closure(
5232            &target_ctx,
5233            g.key(),
5234            unit_tables,
5235            unit_consumes,
5236            unit_consumes_aliases,
5237            unit_flattened,
5238            reached,
5239        );
5240    }
5241}
5242
5243/// v0.19 (decision 0017): the native platforms a context's **in-process
5244/// closure** commits it to: every unit whose provider its compose would
5245/// instantiate — local providers' `given` recursion plus the capabilities its
5246/// handlers reference — mapped through [`firstparty::platform_of`]. Each
5247/// platform carries an exemplar unit for the diagnostic message. Service
5248/// `consumes` edges (RPC under `workers`) do not contribute — only the
5249/// provider-instantiation walk, which is in-process by construction.
5250///
5251/// P5.3: relocated alongside [`phase_platform_lock`], reimplemented on
5252/// [`collect_given_closure`] rather than moved verbatim — see that
5253/// function's doc.
5254fn native_platforms_of_context(
5255    ctx: &str,
5256    table: &UnitTable,
5257    unit_tables: &HashMap<String, UnitTable>,
5258    unit_consumes: &HashMap<String, Vec<String>>,
5259    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5260    unit_flattened: &HashMap<String, HashMap<String, String>>,
5261) -> BTreeMap<Platform, String> {
5262    let mut reached: BTreeSet<(String, String)> = BTreeSet::new();
5263    for cap in table.providers.keys() {
5264        collect_given_closure(
5265            ctx,
5266            cap,
5267            unit_tables,
5268            unit_consumes,
5269            unit_consumes_aliases,
5270            unit_flattened,
5271            &mut reached,
5272        );
5273    }
5274    let consumed = unit_consumes.get(ctx).cloned().unwrap_or_default();
5275    let aliases = unit_consumes_aliases.get(ctx).cloned().unwrap_or_default();
5276    let flattened = unit_flattened.get(ctx).cloned().unwrap_or_default();
5277    for (key, cctx) in handler_cross_caps(table, ctx, &consumed, &aliases, &flattened) {
5278        collect_given_closure(
5279            &cctx,
5280            &key,
5281            unit_tables,
5282            unit_consumes,
5283            unit_consumes_aliases,
5284            unit_flattened,
5285            &mut reached,
5286        );
5287    }
5288    let mut referenced: BTreeSet<String> = reached.into_iter().map(|(unit, _)| unit).collect();
5289    // S4a (#1966): a derived capability reaches its base's platform unit, so
5290    // a context whose only Cloudflare use is a named instance is still locked.
5291    referenced.extend(table.derived.values().map(|d| d.base_unit.clone()));
5292    // #3328 (DECISION I): inbound email is Cloudflare's, whether or not the
5293    // context reaches a capability — the types alone would not lock it.
5294    if table
5295        .services
5296        .values()
5297        .any(|s| matches!(s.protocol, ServiceProtocol::Email { .. }))
5298    {
5299        referenced.insert(crate::firstparty::CLOUDFLARE_UNIT.to_string());
5300    }
5301    let mut out = BTreeMap::new();
5302    for unit in referenced {
5303        if let Some(p) = firstparty::platform_of(&unit) {
5304            out.entry(p).or_insert(unit);
5305        }
5306    }
5307    out
5308}
5309
5310/// v0.19 (decisions 0017/0024): enforce the platform lock per deployment
5311/// unit — each context under `--target workers`, the whole program under
5312/// `bundle` (co-location shares the lock).
5313///
5314/// P5.3 (`design/tracks/semantics-in-the-checker.md` §6): relocated from
5315/// `bynk-emit/src/project/validate.rs`'s `check_platform_lock` — category 5
5316/// of `analysis.rs`'s own seven-category residual-gap accounting ("gap in
5317/// name only": `analyse_project` hardcodes `Platform::default()`
5318/// (Cloudflare) and `BuildTarget::Bundle`, and `bynk.cloudflare` is the only
5319/// platform-native unit that exists, so `lock_violation` can never fire on
5320/// that path regardless of where this function lives — see `analysis.rs`'s
5321/// own doc for why R3.5 still requires the move).
5322#[allow(clippy::too_many_arguments)]
5323pub fn phase_platform_lock(
5324    target: BuildTarget,
5325    selected: Platform,
5326    parsed: &[ParsedFile],
5327    groups: &BTreeMap<String, Vec<usize>>,
5328    kinds: &BTreeMap<String, UnitKind>,
5329    unit_tables: &HashMap<String, UnitTable>,
5330    unit_consumes: &HashMap<String, Vec<String>>,
5331    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5332    unit_flattened: &HashMap<String, HashMap<String, String>>,
5333    worker_groups: &bynk_project::worker_groups::WorkerGroups,
5334    errors: &mut ErrorSink,
5335) {
5336    // In-browser track, slice 2: `browser` is a Bundle-only platform — a browser
5337    // cannot do the Workers wire-call model (Service Bindings, Durable Objects,
5338    // cross-context wire calls). Reject the combination up front, before the
5339    // per-unit native-platform lock below, which is moot for an invalid build.
5340    if selected == Platform::Browser && target == BuildTarget::Workers {
5341        errors.push_for(
5342            None,
5343            CompileError::new(
5344                "bynk.target.browser_bundle_only",
5345                Span::default(),
5346                "`--platform browser` builds only the in-process `Bundle` topology, but `--target workers` was selected; a browser cannot run the Workers wire-call model",
5347            )
5348            .with_note("build the browser target with `--target bundle` (the default)"),
5349        );
5350        return;
5351    }
5352    // v0.104 (real-time track slice 3b): the `from websocket` Workers mapping (the
5353    // Durable Object hibernatable upgrade) is now emitted, so the 3a platform-lock
5354    // that gated it off is removed.
5355    // Per-context native sets, with the context name kept for spans/messages.
5356    let mut per_context: Vec<(String, BTreeMap<Platform, String>)> = Vec::new();
5357    let mut names: Vec<&String> = groups.keys().collect();
5358    names.sort();
5359    for name in names {
5360        if kinds.get(name.as_str()) != Some(&UnitKind::Context) {
5361            continue;
5362        }
5363        let Some(table) = unit_tables.get(name.as_str()) else {
5364            continue;
5365        };
5366        let native = native_platforms_of_context(
5367            name,
5368            table,
5369            unit_tables,
5370            unit_consumes,
5371            unit_consumes_aliases,
5372            unit_flattened,
5373        );
5374        if !native.is_empty() {
5375            per_context.push((name.clone(), native));
5376        }
5377    }
5378    let units = lock_units(target, per_context, worker_groups);
5379    for LockUnit {
5380        group,
5381        members,
5382        native,
5383    } in units
5384    {
5385        let Some(violation) = lock_violation(&native, selected) else {
5386            continue;
5387        };
5388        // `context `a.b``, or, for a `[deploy.workers]` group, `Worker group `key``.
5389        let ctx = match &group {
5390            Some(key) => format!("Worker group `{key}`"),
5391            None => format!("context `{}`", members[0]),
5392        };
5393        let span_for = |unit: &str| {
5394            members
5395                .iter()
5396                .find_map(|m| {
5397                    groups
5398                        .get(m)
5399                        .and_then(|idx| consumes_span_of(parsed, idx, unit))
5400                })
5401                .map(|(_, s)| s)
5402                .unwrap_or_default()
5403        };
5404        match violation {
5405            LockViolation::Required { needed, unit } => {
5406                errors.push_for(
5407                    None,
5408                    CompileError::new(
5409                        "bynk.target.vendor_required",
5410                        span_for(&unit),
5411                        format!(
5412                            "{ctx} uses the platform-native capabilities of `{unit}`, which run only on the `{}` platform, but the build selects `--platform {}`",
5413                            needed.as_str(),
5414                            selected.as_str(),
5415                        ),
5416                    )
5417                    .with_note(
5418                        "build with the matching `--platform`, or remove the platform-native dependency to stay portable",
5419                    ),
5420                );
5421            }
5422            LockViolation::Conflict { a, b } => {
5423                errors.push_for(
5424                    None,
5425                    CompileError::new(
5426                        "bynk.target.vendor_conflict",
5427                        span_for(&a.1),
5428                        format!(
5429                            "one deployment unit (via {ctx}) uses platform-native capabilities from two mutually-exclusive platforms: `{}` (from `{}`) and `{}` (from `{}`)",
5430                            a.0.as_str(),
5431                            a.1,
5432                            b.0.as_str(),
5433                            b.1,
5434                        ),
5435                    )
5436                    .with_note(if group.is_some() {
5437                        "the members of a `[deploy.workers]` group share one Worker: move the conflicting contexts into different groups (or out of any group), or remove one of the platform-native dependencies"
5438                    } else {
5439                        "split the consumers into separate deployment units (`--target workers`), or remove one of the platform-native dependencies"
5440                    }),
5441                );
5442            }
5443        }
5444    }
5445}
5446
5447/// v0.173 (ADR 0196 D1), P5.5 (`design/tracks/semantics-in-the-checker.md`
5448/// §6, §9): warn where a `bynk.Secrets` read names its secret with a computed
5449/// expression. Non-failing — the program is correct, `bynk deploy` simply
5450/// cannot see the name — walked per **file** rather than per unit, since a
5451/// merged `UnitTable` has thrown away which file a call site lives in and
5452/// [`ErrorSink::extend_for`] attributes a diagnostic to a path.
5453///
5454/// Gated on the Workers target because the whole consequence is about `bynk
5455/// deploy`'s plan, which no other target produces; warning a bundle project
5456/// about a deploy plan it will never produce would be noise. Relocated from
5457/// `bynk-driver::project::run_checks` — that call site's own comment claimed
5458/// this "reaches the editor" via `bynk check`/the LSP, which was true only
5459/// while the LSP still called `run_checks`'s `Mode::Analyse` arm; P4.2
5460/// repointed `bynk-ide` at [`crate::analysis::analyse_project`] instead, and
5461/// `bynk-check` cannot depend on `bynk-emit` to reach this code — so the
5462/// claim went stale silently, exactly the "ninth gap" §9 of the design doc
5463/// flagged as a risk rather than a scoped relocation. Wired into
5464/// `analyse_project` at the same relative point `run_checks` calls it,
5465/// mirroring [`phase_platform_lock`]'s own treatment of a build-target-gated
5466/// check: `analyse_project` hardcodes `BuildTarget::Bundle`, so this closes
5467/// the category structurally (R3.5 — the diagnostic now originates in
5468/// `bynk-check`), not observably, the same as categories 1 and 5.
5469pub fn phase_secrets_computed_name(
5470    target: BuildTarget,
5471    parsed: &[ParsedFile],
5472    groups: &BTreeMap<String, Vec<usize>>,
5473    kinds: &BTreeMap<String, UnitKind>,
5474    unit_flattened: &HashMap<String, HashMap<String, String>>,
5475    errors: &mut ErrorSink,
5476) {
5477    if target != BuildTarget::Workers {
5478        return;
5479    }
5480    for (name, indices) in groups {
5481        if kinds.get(name) != Some(&UnitKind::Context) {
5482            continue;
5483        }
5484        let Some(flattened) = unit_flattened.get(name) else {
5485            continue;
5486        };
5487        for &i in indices {
5488            let SourceUnit::Context(ctx) = &parsed[i].unit() else {
5489                continue;
5490            };
5491            // #1976: agent handlers and provider bodies are this Worker's
5492            // reads too, so a computed name in one is warned like any other.
5493            let items = &ctx.items;
5494            let handlers = items.iter().filter_map(|item| match item {
5495                CommonsItem::Service(s) => Some(s.handlers.iter()),
5496                CommonsItem::Agent(a) => Some(a.handlers.iter()),
5497                _ => None,
5498            });
5499            let providers = items.iter().filter_map(|item| match item {
5500                CommonsItem::Provider(p) => Some(p),
5501                _ => None,
5502            });
5503            let (_, mut warnings) = crate::secrets::secret_reads_of(handlers.flatten(), flattened);
5504            warnings.extend(crate::secrets::provider_secret_reads_of(providers, flattened).1);
5505            let rel = parsed[i].identity_path();
5506            errors.extend_for(Some(&rel), warnings);
5507        }
5508    }
5509}
5510
5511/// The project-wide topology checks, in the order their diagnostics appear:
5512/// #1822 (on Workers, a required local capability needs a provider), #3328 (one
5513/// service per email address across the whole project, on every target), #3644 (one
5514/// consuming context per queue) and
5515/// #2306 (on Workers, a WebSocket `on open` and the agent it transfers to share a
5516/// file). One call for the build and the editor path, which both run them.
5517pub fn phase_topology(
5518    target: BuildTarget,
5519    parsed: &[ParsedFile],
5520    groups: &BTreeMap<String, Vec<usize>>,
5521    kinds: &BTreeMap<String, UnitKind>,
5522    unit_tables: &HashMap<String, UnitTable>,
5523    errors: &mut ErrorSink,
5524) {
5525    phase_workers_unprovided_capabilities(target, parsed, groups, kinds, unit_tables, errors);
5526    crate::email::phase_duplicate_addresses(parsed, groups, kinds, errors);
5527    crate::queue_consumers::phase_duplicate_queue_consumers(parsed, groups, kinds, errors);
5528    phase_workers_ws_open_split(target, parsed, groups, kinds, unit_tables, errors);
5529}
5530
5531/// #1822: on the Workers target, a capability a context declares and requires
5532/// (`given`, on a service or agent handler or a provider) needs a provider in
5533/// that context. A Worker's composition root builds every capability its
5534/// handlers are given, so one with no provider left `compose` passing `{}`
5535/// where the capability was required (TS2345): the bundle built and the
5536/// Workers build didn't. On the bundle target the host may supply it through
5537/// `__makeSurface(deps)`, so the check is Workers-only, like
5538/// [`phase_secrets_computed_name`]. A capability from another unit (flattened
5539/// or qualified) is that unit's to provide, and `exports capability` already
5540/// requires its provider (`bynk.exports.capability_not_provided`).
5541pub fn phase_workers_unprovided_capabilities(
5542    target: BuildTarget,
5543    parsed: &[ParsedFile],
5544    groups: &BTreeMap<String, Vec<usize>>,
5545    kinds: &BTreeMap<String, UnitKind>,
5546    unit_tables: &HashMap<String, UnitTable>,
5547    errors: &mut ErrorSink,
5548) {
5549    if target != BuildTarget::Workers {
5550        return;
5551    }
5552    phase_unprovided_capabilities(
5553        &UnprovidedReason::Workers,
5554        parsed,
5555        groups,
5556        kinds,
5557        unit_tables,
5558        errors,
5559    );
5560}
5561
5562/// Why a context's required local capability has to have a provider in it,
5563/// which is what the `bynk.capability.not_provided` message and note say.
5564pub enum UnprovidedReason {
5565    /// #1822: each context is a Worker, which builds every capability its
5566    /// handlers are given.
5567    Workers,
5568    /// A bundle with a composition root: `composeApp` builds every context's
5569    /// deps itself, so the host has no `__makeSurface(deps)` call to supply a
5570    /// capability through. `trigger` is the context that brings the root in,
5571    /// and `because` what it does that needs one (for example "consumes the
5572    /// services of `shop.stock`"). Without this check the gap reached `tsc`
5573    /// as a member missing from a `__makeSurface` argument in `compose.ts`,
5574    /// reported as a compiler bug (`bynk.codegen.tsc_failed`).
5575    BundleComposition { trigger: String, because: String },
5576}
5577
5578/// Whether a bundle's composition root builds this context: `composeApp`
5579/// makes a deps object only to feed a context's `__makeSurface`, so a context
5580/// with no services (agents, capabilities or providers only) is left to the
5581/// host. Shared by the driver's `emit_composition_root` and
5582/// [`phase_unprovided_capabilities`], so the check refuses exactly the
5583/// contexts the root builds.
5584pub fn composed_in_bundle_root(table: &UnitTable) -> bool {
5585    !table.services.is_empty()
5586}
5587
5588/// The shared body of the Workers and bundle-composition checks: each
5589/// context's required local capability (a `given` on a service or agent
5590/// handler, or on a provider) that has no provider, once per capability, at
5591/// its first `given`.
5592pub fn phase_unprovided_capabilities(
5593    reason: &UnprovidedReason,
5594    parsed: &[ParsedFile],
5595    groups: &BTreeMap<String, Vec<usize>>,
5596    kinds: &BTreeMap<String, UnitKind>,
5597    unit_tables: &HashMap<String, UnitTable>,
5598    errors: &mut ErrorSink,
5599) {
5600    for (name, indices) in groups {
5601        if kinds.get(name) != Some(&UnitKind::Context) {
5602            continue;
5603        }
5604        let Some(table) = unit_tables.get(name) else {
5605            continue;
5606        };
5607        if matches!(reason, UnprovidedReason::BundleComposition { .. })
5608            && !composed_in_bundle_root(table)
5609        {
5610            continue;
5611        }
5612        // #1882 review: once per capability, at its first `given`, however
5613        // many handlers require it.
5614        let mut reported: HashSet<String> = HashSet::new();
5615        for &i in indices {
5616            let SourceUnit::Context(ctx) = &parsed[i].unit() else {
5617                continue;
5618            };
5619            let mut givens: Vec<&CapRef> = Vec::new();
5620            for item in &ctx.items {
5621                match item {
5622                    CommonsItem::Service(s) => {
5623                        givens.extend(s.handlers.iter().flat_map(|h| &h.given));
5624                    }
5625                    CommonsItem::Agent(a) => {
5626                        givens.extend(a.handlers.iter().flat_map(|h| &h.given));
5627                    }
5628                    CommonsItem::Provider(p) => givens.extend(&p.given),
5629                    _ => {}
5630                }
5631            }
5632            for cap in givens {
5633                // An exported capability with no provider is already
5634                // `bynk.exports.capability_not_provided` (#1882 review: no
5635                // second error for the same gap).
5636                if cap.context.is_some()
5637                    || !table.capabilities.contains_key(&cap.name.name)
5638                    || table.providers.contains_key(&cap.name.name)
5639                    // S4a (#1966): a derived capability's provision is implied.
5640                    || table.derived.contains_key(&cap.name.name)
5641                    || table.exported_capabilities.contains(&cap.name.name)
5642                    || !reported.insert(cap.name.name.clone())
5643                {
5644                    continue;
5645                }
5646                let cap_name = &cap.name.name;
5647                let error = match reason {
5648                    UnprovidedReason::Workers => CompileError::new(
5649                        "bynk.capability.not_provided",
5650                        cap.span,
5651                        format!(
5652                            "capability `{cap_name}` is required here but has no provider in context `{name}`; a Worker builds every capability its handlers are given"
5653                        ),
5654                    )
5655                    .with_note(format!(
5656                        "add `provides {cap_name} = …` to `{name}`, or build for `--target bundle`, where the host supplies it"
5657                    )),
5658                    UnprovidedReason::BundleComposition { trigger, because } => {
5659                        CompileError::new(
5660                            "bynk.capability.not_provided",
5661                            cap.span,
5662                            format!(
5663                                "capability `{cap_name}` is required here but has no provider in context `{name}`; this program's composition root builds every context, so nothing else can supply it"
5664                            ),
5665                        )
5666                        .with_note(format!(
5667                            "`{trigger}` {because}, so the bundle has a composition root (`composeApp`), which builds `{name}` with the providers it declares"
5668                        ))
5669                        .with_note(format!(
5670                            "add `provides {cap_name} = …` to `{name}`; a test `stub` replaces it in the cases that stub it, but the program still needs one"
5671                        ))
5672                    }
5673                };
5674                errors.push_for(Some(&parsed[i].identity_path()), error);
5675            }
5676        }
5677    }
5678}
5679
5680/// Each unit's resolved calls, by expression: the slice of the checker's
5681/// [`checker::Callee`] map the composition-root predicate reads. The driver
5682/// keeps one per unit for emission; [`crate::analysis`] gathers the same
5683/// slice from the files it checks, so `bynk check` and the editor decide
5684/// whether a bundle has a composition root from the same facts.
5685pub type UnitCallees = HashMap<String, HashMap<ExprId, checker::Callee>>;
5686
5687/// Whether a resolved call is `Events.emit`, the one callee
5688/// [`unit_table_uses_emit`] looks for. `Events.emit[...]` dispatches through
5689/// the ordinary capability-call path (`checker/calls.rs`).
5690pub fn is_events_emit(callee: &checker::Callee) -> bool {
5691    matches!(
5692        callee,
5693        checker::Callee::Capability {
5694            op,
5695            first_party: Some(firstparty::FirstPartyCap::Events),
5696            ..
5697        } if op == "emit"
5698    )
5699}
5700
5701/// Events track, slice 0 (spine #936): does any handler or provider op in
5702/// this unit emit? Reads the checker's own resolved `Callee` for every
5703/// expression in every service handler, agent handler and provider op, not
5704/// the receiver's spelling, so a local type that shadows `Events` does not
5705/// count (`1204_events_emit_shadowed_by_local_type`).
5706///
5707/// `callees` is `None` only for a unit whose own check never ran. Every
5708/// caller runs on an otherwise-clean program, where every unit was checked,
5709/// and a silent `false` would disable the emitter's events wiring with no
5710/// diagnostic, so it is a `debug_assert` rather than a quiet default.
5711pub fn unit_table_uses_emit(
5712    table: &UnitTable,
5713    callees: Option<&HashMap<ExprId, checker::Callee>>,
5714) -> bool {
5715    let Some(callees) = callees else {
5716        debug_assert!(
5717            false,
5718            "unit_table_uses_emit: no Callee map for a checked unit"
5719        );
5720        return false;
5721    };
5722    let bodies = table
5723        .services
5724        .values()
5725        .flat_map(|s| s.handlers.iter().map(|h| &h.body))
5726        .chain(
5727            table
5728                .agents
5729                .values()
5730                .flat_map(|a| a.handlers.iter().map(|h| &h.body)),
5731        )
5732        .chain(
5733            table
5734                .providers
5735                .values()
5736                .flat_map(|p| p.ops.iter().map(|op| &op.body)),
5737        );
5738    let mut stack: Vec<&Expr> = Vec::new();
5739    for body in bodies {
5740        for s in &body.statements {
5741            statement_exprs(s, &mut stack);
5742        }
5743        stack.push(&body.tail);
5744    }
5745    while let Some(e) = stack.pop() {
5746        if callees.get(&e.id).is_some_and(is_events_emit) {
5747            return true;
5748        }
5749        stack.extend(expr_children(e));
5750    }
5751    false
5752}
5753
5754/// The context that makes a bundle emit its composition root (`compose.ts`,
5755/// `composeApp`) and what it does that needs one, phrased to follow the
5756/// context's name, or `None` when the bundle has no root. Shared by the
5757/// driver's `emit_composition_root` and [`phase_bundle_composition_unprovided`]
5758/// (which both `bynk check` and the editor's analysis run), so the check and
5759/// the emitter cannot disagree about whether there is a root: `composeApp`
5760/// builds every context's deps itself, so once there is one the host cannot
5761/// supply a capability through `__makeSurface(deps)`, and a required local
5762/// capability needs a provider, as it does on Workers.
5763pub fn composition_root_trigger(
5764    kinds: &BTreeMap<String, UnitKind>,
5765    unit_consumes: &HashMap<String, Vec<String>>,
5766    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5767    unit_tables: &HashMap<String, UnitTable>,
5768    unit_callees: &UnitCallees,
5769    unit_flattened: &HashMap<String, HashMap<String, String>>,
5770) -> Option<(String, String)> {
5771    // Identify contexts that consume something whose surface has services.
5772    // Sorted, so the context named is the same on every run.
5773    let mut consumers: Vec<(&String, &Vec<String>)> = unit_consumes.iter().collect();
5774    consumers.sort();
5775    for (name, targets) in consumers {
5776        if kinds.get(name) != Some(&UnitKind::Context) {
5777            continue;
5778        }
5779        if let Some(t) = targets.iter().find(|t| {
5780            unit_tables
5781                .get(*t)
5782                .is_some_and(|other| !other.services.is_empty())
5783        }) {
5784            return Some((name.clone(), format!("consumes `{t}`, which has services")));
5785        }
5786    }
5787    // v0.15: also compose when a context uses a consumed context's capability
5788    // (in a handler or in a provider's `given`) — the consumer must instantiate
5789    // the provided capability's provider locally.
5790    for (name, kind) in kinds {
5791        if *kind != UnitKind::Context {
5792            continue;
5793        }
5794        let Some(table) = unit_tables.get(name) else {
5795            continue;
5796        };
5797        let consumed = unit_consumes.get(name).cloned().unwrap_or_default();
5798        let aliases = unit_consumes_aliases.get(name).cloned().unwrap_or_default();
5799        let flattened = unit_flattened.get(name).cloned().unwrap_or_default();
5800        let uses_cross_cap = !handler_cross_caps(table, name, &consumed, &aliases, &flattened)
5801            .is_empty()
5802            || table.providers.values().any(|p| {
5803                p.given.iter().any(|g| {
5804                    g.is_cross_context()
5805                        // v0.18: a bare given flattened from `consumes U
5806                        // { Cap }` is cross-unit too — its provider lives
5807                        // in the consumed unit.
5808                        || (g.prefix().is_none() && flattened.contains_key(g.key()))
5809                })
5810            });
5811        // Events track, slice 0 (spine #936): a context whose handlers emit
5812        // needs its own `__eventsDispatch` closure built by compose
5813        // (§ `discover_event_subscribers`) even when it consumes nothing and
5814        // no other context consumes it — `Events` is filtered out of
5815        // `handler_cross_caps` (there is no `EventsProvider`), so without
5816        // this check a publish-only context would never get a compose entry
5817        // and its service would simply never be called. S4a (#1966): a
5818        // derived capability's instance is its base's platform provider,
5819        // built by compose like a flattened one.
5820        let because = if uses_cross_cap {
5821            "is given a capability another unit provides"
5822        } else if unit_table_uses_emit(table, unit_callees.get(name)) {
5823            "emits events"
5824        } else if !table.derived.is_empty() {
5825            "derives a capability"
5826        } else {
5827            continue;
5828        };
5829        return Some((name.clone(), because.to_string()));
5830    }
5831    None
5832}
5833
5834/// On the bundle target a context's required local capability may be left to
5835/// the host, which supplies it through `__makeSurface(deps)`, but only while
5836/// the bundle has no composition root ([`composition_root_trigger`]):
5837/// `composeApp` builds the deps of every context it composes
5838/// ([`composed_in_bundle_root`]), so once a context brings a root in, a
5839/// capability with no provider is the Workers gap again. Raised at the
5840/// `given` rather than left to `tsc` against `compose.ts`
5841/// (`bynk.codegen.tsc_failed`). Called by the driver's `run_checks` and by
5842/// [`crate::analysis`], after the per-unit checks (it reads `unit_callees`),
5843/// and only on an otherwise-clean program: a unit that failed to check has no
5844/// callee map, and the root is only emitted for a clean one.
5845#[allow(clippy::too_many_arguments)]
5846pub fn phase_bundle_composition_unprovided(
5847    target: BuildTarget,
5848    parsed: &[ParsedFile],
5849    groups: &BTreeMap<String, Vec<usize>>,
5850    kinds: &BTreeMap<String, UnitKind>,
5851    unit_consumes: &HashMap<String, Vec<String>>,
5852    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5853    unit_tables: &HashMap<String, UnitTable>,
5854    unit_callees: &UnitCallees,
5855    unit_flattened: &HashMap<String, HashMap<String, String>>,
5856    errors: &mut ErrorSink,
5857) {
5858    // #3890: the whole-program call checks share this entry point, which both
5859    // pipelines call once the per-unit checks are done: a call the callee's
5860    // `Caller` refinement does not admit, and an `IsContext(…)` name that is no
5861    // context.
5862    crate::caller_admission::phase_caller_admission(
5863        parsed,
5864        groups,
5865        kinds,
5866        unit_tables,
5867        unit_callees,
5868        errors,
5869    );
5870    if target != BuildTarget::Bundle || !errors.is_empty() {
5871        return;
5872    }
5873    let Some((trigger, because)) = composition_root_trigger(
5874        kinds,
5875        unit_consumes,
5876        unit_consumes_aliases,
5877        unit_tables,
5878        unit_callees,
5879        unit_flattened,
5880    ) else {
5881        return;
5882    };
5883    phase_unprovided_capabilities(
5884        &UnprovidedReason::BundleComposition { trigger, because },
5885        parsed,
5886        groups,
5887        kinds,
5888        unit_tables,
5889        errors,
5890    );
5891}
5892
5893/// #2306: on the Workers target, a `from websocket` service's `on open` is hosted
5894/// inside the Durable Object of the agent it transfers the connection to, and
5895/// that method is emitted from the file the *service* and agent share. A context
5896/// split across several files is emitted one file at a time, so a transfer into
5897/// an agent declared in a different file than the service was routed to the
5898/// agent's Durable Object (`compose.ts` forwards the upgrade) but never hosted
5899/// there: the upgrade returned `404`. Reject it at compile time instead. On the
5900/// bundle target the open is an ordinary surface method and the layout works, so
5901/// the check is Workers-only, like [`phase_workers_unprovided_capabilities`].
5902pub fn phase_workers_ws_open_split(
5903    target: BuildTarget,
5904    parsed: &[ParsedFile],
5905    groups: &BTreeMap<String, Vec<usize>>,
5906    kinds: &BTreeMap<String, UnitKind>,
5907    unit_tables: &HashMap<String, UnitTable>,
5908    errors: &mut ErrorSink,
5909) {
5910    if target != BuildTarget::Workers {
5911        return;
5912    }
5913    for (name, indices) in groups {
5914        if kinds.get(name) != Some(&UnitKind::Context) || indices.len() < 2 {
5915            continue;
5916        }
5917        let Some(table) = unit_tables.get(name) else {
5918            continue;
5919        };
5920        let local_agents: HashSet<String> = table.agents.keys().cloned().collect();
5921        for &i in indices {
5922            let SourceUnit::Context(ctx) = &parsed[i].unit() else {
5923                continue;
5924            };
5925            for item in &ctx.items {
5926                let CommonsItem::Service(service) = item else {
5927                    continue;
5928                };
5929                if !matches!(service.protocol, ServiceProtocol::WebSocket { .. }) {
5930                    continue;
5931                }
5932                for open in service
5933                    .handlers
5934                    .iter()
5935                    .filter(|h| matches!(h.kind, HandlerKind::Open))
5936                {
5937                    let crate::websocket::WsOpenShape::One(target_agent) =
5938                        crate::websocket::analyse_open_shape(&open.body, &local_agents)
5939                    else {
5940                        continue; // a missing or ambiguous transfer has its own diagnostic
5941                    };
5942                    let declared_here = ctx.items.iter().any(|it| {
5943                        matches!(it, CommonsItem::Agent(a) if a.name.name == target_agent.agent)
5944                    });
5945                    if declared_here {
5946                        continue;
5947                    }
5948                    errors.push_for(
5949                        Some(&parsed[i].identity_path()),
5950                        CompileError::new(
5951                            "bynk.ws.open_transfer_cross_file",
5952                            open.span,
5953                            format!(
5954                                "this `on open` transfers its `connection` to agent `{}`, which is declared in a different file of context `{name}` than the service `{}`",
5955                                target_agent.agent, service.name.name
5956                            ),
5957                        )
5958                        .with_note(
5959                            "on Workers the open is hosted inside the agent's Durable Object, which is emitted from the file that declares the agent; move the service into the agent's file, or build for `--target bundle`",
5960                        ),
5961                    );
5962                }
5963            }
5964        }
5965    }
5966}
5967
5968/// #2355: whether a bodied provider's ops construct one of its context's own
5969/// agents (`is_agent`). Such a provider takes a `deps` even with no `given`:
5970/// its agent calls hand `this.deps` to the agent's methods, and on Workers the
5971/// agent factory reads the Worker's `env` from it. Syntactic, so the provider
5972/// class, every composer that builds it, and
5973/// [`phase_workers_provider_agent_cross_context`] agree on the answer; a local
5974/// shadowing an agent's name only costs an unused `deps`. It matches the
5975/// construction shape `Agent(key)`, the one the emitter's `agent_construct`
5976/// lowers; a new way to reach an agent must be added here too.
5977pub fn provider_constructs_agent(p: &ProviderDecl, is_agent: impl Fn(&str) -> bool) -> bool {
5978    fn walk(e: &Expr, is_agent: &dyn Fn(&str) -> bool) -> bool {
5979        if let ExprKind::Call { name, .. } = &e.kind
5980            && is_agent(&name.name)
5981        {
5982            return true;
5983        }
5984        expr_children(e).into_iter().any(|c| walk(c, is_agent))
5985    }
5986    p.ops.iter().any(|op| {
5987        let mut top = Vec::new();
5988        for s in &op.body.statements {
5989            statement_exprs(s, &mut top);
5990        }
5991        top.push(&op.body.tail);
5992        top.into_iter().any(|e| walk(e, &is_agent))
5993    })
5994}
5995
5996/// #2959: on the Workers target, the edge (`compose.ts`) addresses the Durable
5997/// Object hosting a WebSocket connection *before* the `on open` body runs, so the
5998/// key of the body's connection transfer must be something it can evaluate on its
5999/// own: a route parameter, a constant of the context (its own, or a public one
6000/// of a commons it `uses`, #2967) or a literal
6001/// ([`crate::websocket::classify_open_key`]). Any other key — a `let`-bound local,
6002/// a field access, a call — used to be emitted as a name `compose.ts` does not
6003/// bind (a `tsc` failure) or replaced by the first route parameter (the upgrade
6004/// silently reached a different instance than the one the body addressed). On the
6005/// bundle target the open is an ordinary surface method that evaluates any key,
6006/// so the check is Workers-only, like [`phase_workers_ws_open_split`].
6007pub fn phase_workers_ws_open_key(
6008    target: BuildTarget,
6009    parsed: &[ParsedFile],
6010    groups: &BTreeMap<String, Vec<usize>>,
6011    kinds: &BTreeMap<String, UnitKind>,
6012    unit_tables: &HashMap<String, UnitTable>,
6013    unit_uses: &HashMap<String, Vec<String>>,
6014    errors: &mut ErrorSink,
6015) {
6016    if target != BuildTarget::Workers {
6017        return;
6018    }
6019    for (name, indices) in groups {
6020        if kinds.get(name) != Some(&UnitKind::Context) {
6021            continue;
6022        }
6023        let Some(table) = unit_tables.get(name) else {
6024            continue;
6025        };
6026        // #2967: the constants visible in the context, a used commons' public
6027        // ones included, as the emitter classifies the key against.
6028        let uses = unit_uses.get(name).map(Vec::as_slice).unwrap_or_default();
6029        let consts = crate::consts::visible_consts(table, uses, |u| unit_tables.get(u));
6030        let local_agents: HashSet<String> = table.agents.keys().cloned().collect();
6031        for &i in indices {
6032            let SourceUnit::Context(ctx) = &parsed[i].unit() else {
6033                continue;
6034            };
6035            for item in &ctx.items {
6036                let CommonsItem::Service(service) = item else {
6037                    continue;
6038                };
6039                if !matches!(service.protocol, ServiceProtocol::WebSocket { .. }) {
6040                    continue;
6041                }
6042                for open in service
6043                    .handlers
6044                    .iter()
6045                    .filter(|h| matches!(h.kind, HandlerKind::Open))
6046                {
6047                    let crate::websocket::WsOpenShape::One(target_agent) =
6048                        crate::websocket::analyse_open_shape(&open.body, &local_agents)
6049                    else {
6050                        continue; // a missing or ambiguous transfer has its own diagnostic
6051                    };
6052                    let key = crate::websocket::classify_open_key(open, target_agent.key, |n| {
6053                        consts.contains_key(n)
6054                    });
6055                    if !matches!(key, crate::websocket::WsOpenKey::Other) {
6056                        continue;
6057                    }
6058                    errors.push_for(
6059                        Some(&parsed[i].identity_path()),
6060                        CompileError::new(
6061                            "bynk.ws.open_transfer_key",
6062                            target_agent.key.span,
6063                            format!(
6064                                "the key of this `on open`'s transfer to agent `{}` is not a route parameter, a constant or a literal, so the Workers upgrade cannot address the agent's Durable Object",
6065                                target_agent.agent
6066                            ),
6067                        )
6068                        .with_note(
6069                            "on Workers the upgrade is routed to the hosting Durable Object before the `on open` body runs; key the agent by a parameter of `on open`, a `const` of the context or of a commons it `uses`, or a literal",
6070                        ),
6071                    );
6072                }
6073            }
6074        }
6075    }
6076}
6077
6078/// #2355 follow-up: on the Workers target, a context may not require a
6079/// capability whose provider, in another context, constructs that context's
6080/// agents. The consumer's composition root builds the provider in-process and
6081/// hands it the consumer's own `env`, which binds only the consumer's Durable
6082/// Object namespaces: `tsc` rejects the build, and strip-only `bynk dev`
6083/// quietly falls back to agent state held in the isolate. The capability can
6084/// be reached through any `given` the consumer's compose instantiates — a
6085/// service or agent handler's, or a local provider's, transitively — so the
6086/// walk is `collect_given_closure`'s, reported once per provider at the
6087/// first `given` that reaches it. On the bundle target the whole program
6088/// shares one process and the agent factory takes only the key, so the check
6089/// is Workers-only, like [`phase_workers_unprovided_capabilities`].
6090#[allow(clippy::too_many_arguments)]
6091pub fn phase_workers_provider_agent_cross_context(
6092    target: BuildTarget,
6093    parsed: &[ParsedFile],
6094    groups: &BTreeMap<String, Vec<usize>>,
6095    kinds: &BTreeMap<String, UnitKind>,
6096    unit_tables: &HashMap<String, UnitTable>,
6097    unit_consumes: &HashMap<String, Vec<String>>,
6098    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
6099    unit_flattened: &HashMap<String, HashMap<String, String>>,
6100    errors: &mut ErrorSink,
6101) {
6102    if target != BuildTarget::Workers {
6103        return;
6104    }
6105    for (name, indices) in groups {
6106        if kinds.get(name) != Some(&UnitKind::Context) {
6107            continue;
6108        }
6109        let consumed = unit_consumes.get(name).cloned().unwrap_or_default();
6110        let aliases = unit_consumes_aliases.get(name).cloned().unwrap_or_default();
6111        let flattened = unit_flattened.get(name).cloned().unwrap_or_default();
6112        let mut reported: HashSet<(String, String)> = HashSet::new();
6113        for &i in indices {
6114            let SourceUnit::Context(ctx) = &parsed[i].unit() else {
6115                continue;
6116            };
6117            let mut givens: Vec<&CapRef> = Vec::new();
6118            for item in &ctx.items {
6119                match item {
6120                    CommonsItem::Service(s) => {
6121                        givens.extend(s.handlers.iter().flat_map(|h| &h.given));
6122                    }
6123                    CommonsItem::Agent(a) => {
6124                        givens.extend(a.handlers.iter().flat_map(|h| &h.given));
6125                    }
6126                    CommonsItem::Provider(p) => givens.extend(&p.given),
6127                    _ => {}
6128                }
6129            }
6130            for cap in givens {
6131                // The same resolution as `collect_given_closure`'s.
6132                let target_ctx = match cap.prefix() {
6133                    Some(p) => resolve_consume_prefix(&p, &consumed, &aliases)
6134                        .unwrap_or_else(|| name.clone()),
6135                    None => flattened
6136                        .get(cap.key())
6137                        .cloned()
6138                        .unwrap_or_else(|| name.clone()),
6139                };
6140                let mut reached: BTreeSet<(String, String)> = BTreeSet::new();
6141                collect_given_closure(
6142                    &target_ctx,
6143                    cap.key(),
6144                    unit_tables,
6145                    unit_consumes,
6146                    unit_consumes_aliases,
6147                    unit_flattened,
6148                    &mut reached,
6149                );
6150                for (unit, key) in reached {
6151                    if unit == *name {
6152                        continue;
6153                    }
6154                    let Some(table) = unit_tables.get(&unit) else {
6155                        continue;
6156                    };
6157                    let Some(provider) = table.providers.get(&key) else {
6158                        continue;
6159                    };
6160                    if provider.external
6161                        || !provider_constructs_agent(provider, |n| table.agents.contains_key(n))
6162                        || !reported.insert((unit.clone(), key.clone()))
6163                    {
6164                        continue;
6165                    }
6166                    errors.push_for(
6167                        Some(&parsed[i].identity_path()),
6168                        CompileError::new(
6169                            "bynk.capability.provider_agent_cross_context",
6170                            cap.span,
6171                            format!(
6172                                "capability `{key}` is provided by `{}` in context `{unit}`, which constructs `{unit}`'s agents; on Workers context `{name}` would build that provider with its own `env`, which has no binding for those agents' Durable Objects",
6173                                provider.provider_name.name
6174                            ),
6175                        )
6176                        .with_note(format!(
6177                            "call a `{unit}` service that uses `{key}` instead, or build for `--target bundle`, where every context shares one process"
6178                        )),
6179                    );
6180                }
6181            }
6182        }
6183    }
6184}
6185
6186/// Phase 7: build each production unit's file-declaration index (which file in
6187/// the unit declares which name), for cross-file lookups in the back half.
6188pub fn phase_file_index(
6189    groups: &BTreeMap<String, Vec<usize>>,
6190    parsed: &[ParsedFile],
6191) -> HashMap<String, FileDeclIndex> {
6192    let mut unit_file_index: HashMap<String, FileDeclIndex> = HashMap::new();
6193    for (name, indices) in groups {
6194        unit_file_index.insert(name.clone(), build_file_decl_index(indices, parsed));
6195    }
6196    unit_file_index
6197}
6198
6199/// v0.29.4: the per-unit facets that the producer phases build as nine parallel
6200/// `HashMap<String, _>`s, all keyed on unit name. Assembling one record per unit
6201/// makes the "all these maps share one keyset" invariant structural: a single
6202/// lookup yields every facet as a field, so the per-column `.unwrap()`s on the
6203/// shared keyset disappear. Fields are total — `exports`/`aliases`/`flattened`
6204/// default to an empty map for a unit with no entry, reproducing the old
6205/// `.unwrap_or(empty)` read semantics without the dance.
6206pub struct UnitInfo {
6207    pub kind: UnitKind,
6208    pub table: UnitTable,
6209    pub uses: Vec<String>,
6210    pub consumes: Vec<String>,
6211    pub flattened: HashMap<String, String>,
6212    pub aliases: HashMap<String, String>,
6213    pub exports: HashMap<String, Visibility>,
6214    pub file_index: FileDeclIndex,
6215    pub files: Vec<usize>,
6216}
6217
6218/// v0.29.4: fold the nine parallel per-unit maps into one `HashMap<String,
6219/// UnitInfo>`. Assembly is driven by the `groups` keyset (the authority), so
6220/// every group yields exactly one record. Facets that are genuinely optional in
6221/// the producer maps (`exports`/`aliases`/`flattened`, and `file_index` for a
6222/// unit with no declarations) default to empty — reproducing the old
6223/// `.unwrap_or(empty)` read semantics as a total field.
6224#[allow(clippy::too_many_arguments)]
6225pub fn assemble_unit_info(
6226    groups: &BTreeMap<String, Vec<usize>>,
6227    kinds: &BTreeMap<String, UnitKind>,
6228    unit_tables: &HashMap<String, UnitTable>,
6229    unit_uses: &HashMap<String, Vec<String>>,
6230    unit_consumes: &HashMap<String, Vec<String>>,
6231    unit_flattened: &HashMap<String, HashMap<String, String>>,
6232    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
6233    exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
6234    unit_file_index: &HashMap<String, FileDeclIndex>,
6235) -> BTreeMap<String, UnitInfo> {
6236    groups
6237        .iter()
6238        .map(|(name, indices)| {
6239            let info = UnitInfo {
6240                kind: *kinds.get(name).unwrap(),
6241                table: unit_tables.get(name).unwrap().clone(),
6242                uses: unit_uses.get(name).cloned().unwrap_or_default(),
6243                consumes: unit_consumes.get(name).cloned().unwrap_or_default(),
6244                flattened: unit_flattened.get(name).cloned().unwrap_or_default(),
6245                aliases: unit_consumes_aliases.get(name).cloned().unwrap_or_default(),
6246                exports: exports_visibility.get(name).cloned().unwrap_or_default(),
6247                file_index: unit_file_index
6248                    .get(name)
6249                    .cloned()
6250                    .unwrap_or_else(|| FileDeclIndex {
6251                        types: HashMap::new(),
6252                        fns: HashMap::new(),
6253                        methods: HashMap::new(),
6254                        agents: HashMap::new(),
6255                        capabilities: HashMap::new(),
6256                    }),
6257                files: indices.clone(),
6258            };
6259            (name.clone(), info)
6260        })
6261        .collect()
6262}
6263
6264/// Phase 8c: collect every method authored anywhere in one unit, keyed by its
6265/// attached type's name — so a type's methods surface in the file that declares
6266/// the type even when the method lives in a sibling file. The collection loop
6267/// has no `continue`s, so it lifts out whole.
6268pub fn collect_unit_methods(
6269    indices: &[usize],
6270    parsed: &[ParsedFile],
6271) -> HashMap<String, Vec<FnDecl>> {
6272    let mut local_methods_for_type: HashMap<String, Vec<FnDecl>> = HashMap::new();
6273    for &j in indices {
6274        for item in parsed[j].items() {
6275            if let CommonsItem::Fn(f) = item
6276                && let FnName::Method { type_name, .. } = &f.name
6277            {
6278                local_methods_for_type
6279                    .entry(type_name.name.clone())
6280                    .or_default()
6281                    .push(f.clone());
6282            }
6283        }
6284    }
6285    local_methods_for_type
6286}
6287
6288/// #2887: the alias the `name_conflict` note suggests for `target`'s export
6289/// `type_name`: the target's last segment, capitalised, then the type
6290/// (`bynk.crypto` + `Digest` → `CryptoDigest`).
6291fn suggest_alias(target: &str, type_name: &str) -> String {
6292    let last = target.rsplit('.').next().unwrap_or(target);
6293    let mut chars = last.chars();
6294    let head: String = chars
6295        .next()
6296        .map(|c| c.to_uppercase().collect())
6297        .unwrap_or_default();
6298    format!("{head}{}{type_name}", chars.as_str())
6299}
6300
6301/// Phase 8b: merge one context's `consumes` exports into the composed symbol
6302/// space, recording visibility metadata in the returned `consumed_types`. The
6303/// per-export `continue`s (missing decl, name conflict) stay internal to the
6304/// loop, which lifts out whole; name conflicts are pushed into `errors` and the
6305/// caller's `group_error_baseline` guard reacts to them after this returns.
6306#[allow(clippy::too_many_arguments)]
6307pub fn merge_consumed_exports(
6308    name: &str,
6309    parsed: &[ParsedFile],
6310    unit_info: &BTreeMap<String, UnitInfo>,
6311    combined_types: &mut HashMap<String, Arc<TypeDecl>>,
6312    combined_methods: &mut HashMap<String, ResolverMethodTable>,
6313    imported_from: &mut HashMap<String, String>,
6314    imported_from_kind: &mut HashMap<String, UnitKind>,
6315    errors: &mut ErrorSink,
6316) -> HashMap<String, ConsumedType> {
6317    // Names visible from `consumes` (read-only types from consumed contexts).
6318    // For each name we track:
6319    // - the type decl, with the consumed context's identity
6320    // - the visibility (opaque/transparent)
6321    // - the owning context's qualified name (for external-construction errors)
6322    let mut consumed_types: HashMap<String, ConsumedType> = HashMap::new();
6323
6324    // Now process `consumes` for contexts: add exported types into the
6325    // symbol table with visibility metadata so the checker can enforce
6326    // construction / inspection rules.
6327    for t in unit_info.get(name).into_iter().flat_map(|i| &i.consumes) {
6328        let used = &unit_info.get(t).expect("consumed unit present").table;
6329        let used_exports = &unit_info[t].exports;
6330        // #2887: the exports of `t` this unit renames (`consumes t { T as U }`),
6331        // original → alias. An aliased export is in scope under the alias only,
6332        // and its declaration (and the references to it in `t`'s other exports)
6333        // take the alias as their name, so it is a type of its own here even
6334        // when a local `T` exists.
6335        let renames: HashMap<String, String> = unit_info[name]
6336            .table
6337            .consumed_type_aliases
6338            .iter()
6339            .filter(|(_, a)| a.target == *t)
6340            .map(|(alias, a)| (a.original.clone(), alias.clone()))
6341            .collect();
6342        for (type_name, vis) in used_exports {
6343            let Some(decl) = used.types.get(type_name) else {
6344                continue;
6345            };
6346            let original = type_name;
6347            let aliased = renames.contains_key(original);
6348            let type_name = renames.get(original).unwrap_or(original);
6349            let decl = &crate::symbols::rename_consumed_decl(decl, type_name, &renames);
6350            // #1927: a local value of the export's name (a function, asset,
6351            // service, agent or provider) takes the emitted module's binding
6352            // as a type of that name would, so it conflicts the same way.
6353            let local_value = crate::symbols::local_value_kind(&unit_info[name].table, type_name)
6354                .map(|(kind, _)| kind)
6355                .filter(|kind| !matches!(*kind, "type" | "event"));
6356            // #3536: a type the braces leave out is not in scope as a name of
6357            // its own, so a declaration of this unit's wins over it, silently.
6358            if unit_info[name]
6359                .table
6360                .unselected_consumed_types
6361                .contains(type_name)
6362                && (combined_types.contains_key(type_name) || local_value.is_some())
6363            {
6364                continue;
6365            }
6366            if combined_types.contains_key(type_name) || local_value.is_some() {
6367                // Name conflict between local/uses and consumed export.
6368                let consumes_site = consumes_span_of(parsed, &unit_info[name].files, t);
6369                let consumes_span = consumes_site.map(|(_, s)| s).unwrap_or_default();
6370                let consumes_file = consumes_site.map(|(i, _)| parsed[i].identity_path());
6371                let in_scope = match local_value {
6372                    Some(kind) => format!("this context declares a {kind} of the same name"),
6373                    None => "a type of the same name is already in scope".to_string(),
6374                };
6375                // An alias clashing with what is in scope, or a bare export
6376                // clashing with one of this unit's aliases: the alias is the
6377                // name to change either way.
6378                let clashes_alias = !aliased
6379                    && unit_info[name]
6380                        .table
6381                        .consumed_type_aliases
6382                        .contains_key(type_name);
6383                if aliased || clashes_alias {
6384                    let what = if aliased {
6385                        format!("aliases an export of `{t}` as `{type_name}`, but {in_scope}")
6386                    } else {
6387                        format!(
6388                            "consumes `{t}` which exports type `{type_name}`, but an alias of the same name is in scope"
6389                        )
6390                    };
6391                    errors.push_for(
6392                        consumes_file.as_deref(),
6393                        CompileError::new(
6394                            "bynk.consumes.type_alias_conflict",
6395                            consumes_span,
6396                            format!("context `{name}` {what}"),
6397                        )
6398                        .with_note("choose an alias no other declaration in this context uses"),
6399                    );
6400                    continue;
6401                }
6402                errors.push_for(consumes_file.as_deref(),
6403                    CompileError::new(
6404                        "bynk.consumes.name_conflict",
6405                        consumes_span,
6406                        format!(
6407                            "context `{name}` consumes `{t}` which exports type `{type_name}`, but {in_scope}",
6408                        ),
6409                    )
6410                    .with_note(format!(
6411                        "alias it so the two no longer share a name: `consumes {t} {{ …, {type_name} as {t_alias} }}`, then write `{t_alias}` for `{t}`'s type",
6412                        t_alias = suggest_alias(t, type_name),
6413                    )),
6414                );
6415                continue;
6416            }
6417            combined_types.insert(type_name.clone(), decl.clone());
6418            imported_from.insert(type_name.clone(), t.clone());
6419            imported_from_kind.insert(type_name.clone(), UnitKind::Context);
6420            consumed_types.insert(
6421                type_name.clone(),
6422                ConsumedType {
6423                    owning_context: t.clone(),
6424                    visibility: *vis,
6425                },
6426            );
6427            // Methods on transparently-exported types: they're emitted in
6428            // the owning context's output, but reading-side methods (like
6429            // user-declared instance methods) are callable from consumers.
6430            // For v0.4, we expose all instance methods on consumed types
6431            // so the checker can resolve method calls; the checker
6432            // separately enforces that constructors (.of/unsafe) aren't
6433            // callable externally.
6434            if let Some(mt) = used.methods.get(original) {
6435                let entry = combined_methods.entry(type_name.clone()).or_default();
6436                for (m, decl) in &mt.instance {
6437                    entry
6438                        .instance
6439                        .entry(m.clone())
6440                        .or_insert_with(|| decl.clone());
6441                }
6442                // We deliberately *don't* import static methods from
6443                // consumed contexts. Static methods can construct new
6444                // values, which is forbidden externally.
6445            }
6446        }
6447    }
6448
6449    consumed_types
6450}
6451
6452/// #1807: close a unit's composed type table over the types its *imported*
6453/// declarations reach.
6454///
6455/// `uses` is one level for naming (ADR 0278): `t.web uses t.model` may not
6456/// write `t.core`'s `Repo`. But `t.model`'s `type Run = { repo: Repo }` still
6457/// carries `Repo` into `t.web`, and the checker resolves that field against
6458/// `t.web`'s table. With `Repo` absent the field's type resolved to nothing,
6459/// and every position it typed went unchecked: `Run { repo: 42 }` compiled,
6460/// and so did `r.repo` read as an `Int`.
6461///
6462/// Each type an imported declaration names is resolved in that declaration's
6463/// own scope: its unit's local types, then its unit's `uses`, the same
6464/// precedence [`compose_unit_symbols`] gives a unit's own names. The walk
6465/// covers type bodies, fn signatures and method signatures, and repeats for
6466/// each type it adds. A type it reaches that this unit's table lacks is added
6467/// with its owning commons as provenance and returned as *hidden*: resolvable
6468/// here, never nameable. The naming gate (`crate::resolver::check_hidden_type_names`)
6469/// rejects a hidden name written in this unit's source.
6470///
6471/// Two cases stop short:
6472/// - A reached type that a context owns is not added. It can only arrive
6473///   through a consumed context's export, so whether it may cross is an
6474///   `exports` question.
6475/// - A reached name that this unit already binds to a *different* unit's
6476///   declaration (its own `type Repo`, say) is `bynk.uses.name_conflict`,
6477///   when the reached type's commons is not one this unit `uses` directly.
6478///   The imported field would otherwise be typed by a declaration the unit
6479///   never chose to shadow. Shadowing a directly used type keeps its existing
6480///   meaning. Provenance is compared by owning unit.
6481///
6482/// #1824: that exemption leaves the same hole open for a directly used
6483/// commons. Such a shadow is recorded rather than reported (see
6484/// [`ShadowedReaches`]), and `crate::shadow_uses` rejects it where the unit's
6485/// own code meets it.
6486///
6487/// Returns each hidden name with its owning commons, which emission needs to
6488/// import it, and the shadows the imported declarations reach.
6489#[allow(clippy::too_many_arguments)]
6490pub fn close_reachable_types(
6491    name: &str,
6492    parsed: &[ParsedFile],
6493    unit_info: &BTreeMap<String, UnitInfo>,
6494    combined_types: &mut HashMap<String, Arc<TypeDecl>>,
6495    combined_fns: &HashMap<String, Arc<FnDecl>>,
6496    combined_methods: &mut HashMap<String, ResolverMethodTable>,
6497    imported_from: &mut HashMap<String, String>,
6498    imported_from_kind: &mut HashMap<String, UnitKind>,
6499    errors: &mut ErrorSink,
6500) -> ReachedTypes {
6501    let mut conflicted: HashSet<String> = HashSet::new();
6502    let mut shadowed = ShadowedReaches::default();
6503    let mut consumed_signatures = consumed_service_seeds(name, unit_info);
6504    // #2617: a used commons' constant names its annotation's types in the
6505    // commons' scope, as an imported function's signature does.
6506    consumed_signatures.extend(used_const_seeds(name, unit_info));
6507    let hidden = close_imported(
6508        unit_info,
6509        combined_types,
6510        combined_fns,
6511        combined_methods,
6512        imported_from,
6513        imported_from_kind,
6514        consumed_signatures,
6515        |r, owner, bound| {
6516            // #1932: a name a consumed signature reaches but this unit already
6517            // binds is the unit's own type receiving the value structurally
6518            // (§6.5), not a conflict.
6519            if r.signature {
6520                return;
6521            }
6522            let bound = bound.unwrap_or(name);
6523            // Shadowing a type of a commons this unit `uses` directly is the
6524            // existing, visible choice (`1697_derived_names_collide` declares
6525            // its own `Message` beside `uses bynk.locale.types`), so only a
6526            // shadow of a type the unit cannot name is a conflict.
6527            let directly_used = unit_info[name].uses.iter().any(|u| u == owner);
6528            // #1824: the directly used case is a conflict only where this
6529            // unit's code meets the imported position, which `shadow_uses`
6530            // decides after checking.
6531            if bound != owner && directly_used {
6532                shadowed.0.insert(
6533                    (r.scope.clone(), r.name.clone()),
6534                    ShadowedType {
6535                        name: r.name.clone(),
6536                        owner: owner.to_string(),
6537                        bound: bound.to_string(),
6538                    },
6539                );
6540            }
6541            if bound != owner && !directly_used && conflicted.insert(r.name.clone()) {
6542                let site = uses_span_of(parsed, &unit_info[name].files, &r.via)
6543                    .or_else(|| consumes_span_of(parsed, &unit_info[name].files, &r.via));
6544                let span = site.map(|(_, s)| s).unwrap_or_default();
6545                let file = site.map(|(i, _)| parsed[i].identity_path());
6546                errors.push_for(
6547                    file.as_deref(),
6548                    CompileError::new(
6549                        "bynk.uses.name_conflict",
6550                        span,
6551                        format!(
6552                            "`{via}` brings in declarations that use type `{t}` from `{owner}`, \
6553                             but `{t}` in `{name}` names `{bound}`'s type",
6554                            via = r.via,
6555                            t = r.name,
6556                        ),
6557                    )
6558                    .with_note(
6559                        "rename one of the two types; the imported declarations cannot be \
6560                         checked against a different type of the same name",
6561                    ),
6562                );
6563            }
6564        },
6565    );
6566    ReachedTypes { hidden, shadowed }
6567}
6568
6569/// #1814: close a test suite's composed view over the types its imported
6570/// declarations reach, as [`close_reachable_types`] closes a unit's table.
6571///
6572/// A suite's view is not a unit's: a unit suite's privileged view and a
6573/// `system` case's harness table each merge their own `imported` units (the
6574/// target's `uses` and consumed contexts; the suite's `uses` and the
6575/// participants) one level deep. A declaration of `imported` that won its
6576/// name in the view (the same `Arc`, first in merge order) seeds the walk, in
6577/// its declaring unit's scope. What the walk adds is returned as hidden, for
6578/// the naming gate and for the test scaffold to import from its owning
6579/// commons.
6580///
6581/// A reached name the view already binds to a different declaration is left
6582/// bound as it is and returned as a [`ViewConflict`]; the caller decides
6583/// which it reports (review of #1814). A `system` harness reports every one:
6584/// its view pairs the suite's own `uses` with the participants, which no
6585/// unit's closure ever sees together. A unit suite reports only those its
6586/// target's closure cannot: a binding to a consumed context's unexported
6587/// type, which only the privileged view merges.
6588pub fn close_view_types(
6589    imported: &[String],
6590    unit_tables: &HashMap<String, UnitTable>,
6591    unit_uses: &HashMap<String, Vec<String>>,
6592    types: &mut HashMap<String, Arc<TypeDecl>>,
6593    fns: &HashMap<String, Arc<FnDecl>>,
6594    methods: &mut HashMap<String, ResolverMethodTable>,
6595    // A `system` harness: also reach what its participants' actors and
6596    // service handlers name ([`harness_seeds`]).
6597    harness: bool,
6598) -> ViewReach {
6599    let mut imported_from: HashMap<String, String> = HashMap::new();
6600    for u in imported {
6601        let Some(t) = unit_tables.get(u) else {
6602            continue;
6603        };
6604        for (n, d) in &t.types {
6605            if types.get(n).is_some_and(|v| Arc::ptr_eq(v, d)) {
6606                imported_from.entry(n.clone()).or_insert_with(|| u.clone());
6607            }
6608        }
6609        for (n, d) in &t.fns {
6610            if fns.get(n).is_some_and(|v| Arc::ptr_eq(v, d)) {
6611                imported_from.entry(n.clone()).or_insert_with(|| u.clone());
6612            }
6613        }
6614    }
6615    let seeds = if harness {
6616        harness_seeds(imported, unit_tables)
6617    } else {
6618        Vec::new()
6619    };
6620    let mut conflicts: Vec<ViewConflict> = Vec::new();
6621    let mut seen: HashSet<String> = HashSet::new();
6622    let hidden = close_imported(
6623        &TableScopes {
6624            tables: unit_tables,
6625            uses: unit_uses,
6626        },
6627        types,
6628        fns,
6629        methods,
6630        &mut imported_from,
6631        &mut HashMap::new(),
6632        seeds,
6633        |r, owner, bound| {
6634            // #3760: a name a participant's handler signature reaches but the
6635            // view already binds receives the value structurally, as for a
6636            // unit's consumed signatures (#1932), so it is not a conflict.
6637            if r.signature {
6638                return;
6639            }
6640            if bound != Some(owner) && seen.insert(r.name.clone()) {
6641                conflicts.push(ViewConflict {
6642                    name: r.name.clone(),
6643                    owner: owner.to_string(),
6644                    bound: bound.map(str::to_string),
6645                    via: r.via.clone(),
6646                });
6647            }
6648        },
6649    );
6650    ViewReach { hidden, conflicts }
6651}
6652
6653/// The extra seeds of a `system` harness's view, each resolved in its
6654/// declaring participant's scope:
6655///
6656/// - #3064: the `identity` types of the participants' actors;
6657/// - #3760: the parameter and return types of their service handlers. A case
6658///   drives those handlers and binds what they return, so a commons type that
6659///   only a handler's signature names (`-> Effect[HttpResult[Note]]`) must
6660///   resolve, or the result is untyped and an `is` test on it is unchecked.
6661///   A signature crosses to the case structurally, as a consumed service's
6662///   does (#1932), so a name the view already binds is not a conflict.
6663///
6664/// Every identity is seeded before any signature. The walk marks a commons
6665/// type visited however it was first reached, so a signature reach that came
6666/// first would swallow the conflict an identity reaching the same type
6667/// reports (review of #3835).
6668fn harness_seeds(imported: &[String], unit_tables: &HashMap<String, UnitTable>) -> Vec<Reached> {
6669    let mut seeds = Vec::new();
6670    let tables = || {
6671        imported
6672            .iter()
6673            .filter_map(|u| Some((u, unit_tables.get(u)?)))
6674    };
6675    for (u, t) in tables() {
6676        let mut actors: Vec<_> = t.actors.iter().collect();
6677        actors.sort_by_key(|(n, _)| n.as_str());
6678        for (_, a) in actors {
6679            if let Some(id) = &a.identity {
6680                let mut names = Vec::new();
6681                type_ref_names(id, &HashSet::new(), &mut names);
6682                push_refs(names, u, u, &mut seeds);
6683            }
6684        }
6685    }
6686    for (u, t) in tables() {
6687        let mut services: Vec<&ServiceDecl> = t.services.values().collect();
6688        services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
6689        for h in services.into_iter().flat_map(|s| &s.handlers) {
6690            let mut names = Vec::new();
6691            for p in &h.params {
6692                type_ref_names(&p.type_ref, &HashSet::new(), &mut names);
6693            }
6694            type_ref_names(&h.return_type, &HashSet::new(), &mut names);
6695            push_refs_with(names, u, u, true, &mut seeds);
6696        }
6697    }
6698    seeds
6699}
6700
6701/// #1814: what [`close_view_types`] found.
6702#[derive(Debug, Clone, Default)]
6703pub struct ViewReach {
6704    /// Each type the closure added, with its owning commons.
6705    pub hidden: BTreeMap<String, String>,
6706    /// Each reached name the view already bound to another declaration, in
6707    /// the walk's order, once per name.
6708    pub conflicts: Vec<ViewConflict>,
6709}
6710
6711/// #1814 review: a type an imported declaration of a suite view names, which
6712/// the view binds to a different declaration of the same name.
6713#[derive(Debug, Clone, PartialEq, Eq)]
6714pub struct ViewConflict {
6715    /// The name both declarations share.
6716    pub name: String,
6717    /// The commons whose declaration the imported one means.
6718    pub owner: String,
6719    /// The unit whose declaration the view binds the name to; `None` for the
6720    /// view's own (a unit suite's target's local type).
6721    pub bound: Option<String>,
6722    /// The imported unit the reaching declaration came from.
6723    pub via: String,
6724}
6725
6726/// #1814: what the reachable-type walk reads of a unit: its declared table,
6727/// its `uses`, and its kind (`None` for a table built without one, which is
6728/// then a scope but never a commons, so nothing it declares is added).
6729/// A unit's own closure reads the assembled [`UnitInfo`]s; a suite view's
6730/// reads the per-unit maps the suite phases carry.
6731trait ScopeTables {
6732    fn scope(&self, unit: &str) -> Option<(&UnitTable, &[String], Option<UnitKind>)>;
6733}
6734
6735impl ScopeTables for BTreeMap<String, UnitInfo> {
6736    fn scope(&self, unit: &str) -> Option<(&UnitTable, &[String], Option<UnitKind>)> {
6737        self.get(unit)
6738            .map(|i| (&i.table, i.uses.as_slice(), Some(i.kind)))
6739    }
6740}
6741
6742/// #1814: [`ScopeTables`] over the suite phases' per-unit maps.
6743struct TableScopes<'a> {
6744    tables: &'a HashMap<String, UnitTable>,
6745    uses: &'a HashMap<String, Vec<String>>,
6746}
6747
6748impl ScopeTables for TableScopes<'_> {
6749    fn scope(&self, unit: &str) -> Option<(&UnitTable, &[String], Option<UnitKind>)> {
6750        let table = self.tables.get(unit)?;
6751        let uses = self.uses.get(unit).map(Vec::as_slice).unwrap_or_default();
6752        Some((table, uses, table.kind))
6753    }
6754}
6755
6756/// #1807: a type name an imported declaration references: resolved in
6757/// `scope` (the declaring unit), and reached through `via` (the `uses` or
6758/// `consumes` target the declaration was imported from, which a conflict
6759/// points at).
6760struct Reached {
6761    name: String,
6762    scope: String,
6763    via: String,
6764    /// #1932: reached from a consumed service's signature (or from a type such
6765    /// a reach added). The value crosses structurally (§6.5), so a name the
6766    /// consumer already binds is its own type receiving it, not a conflict.
6767    signature: bool,
6768}
6769
6770fn push_refs(names: Vec<String>, scope: &str, via: &str, queue: &mut Vec<Reached>) {
6771    push_refs_with(names, scope, via, false, queue);
6772}
6773
6774fn push_refs_with(
6775    names: Vec<String>,
6776    scope: &str,
6777    via: &str,
6778    signature: bool,
6779    queue: &mut Vec<Reached>,
6780) {
6781    queue.extend(names.into_iter().map(|n| Reached {
6782        name: n,
6783        scope: scope.to_string(),
6784        via: via.to_string(),
6785        signature,
6786    }));
6787}
6788
6789/// #1932: the type names the `on call` handlers of every context `name`
6790/// consumes reference, resolved in that context's scope and reached through
6791/// its `consumes`, in a stable order. A consumed service's signature crosses
6792/// the boundary (§6.5), so a commons type in it is reached like one in an
6793/// imported declaration: the consumer resolves it, and emission imports its
6794/// codecs from the declaring commons, whether or not the consumer `uses` it.
6795fn consumed_service_seeds(name: &str, unit_info: &BTreeMap<String, UnitInfo>) -> Vec<Reached> {
6796    let mut out = Vec::new();
6797    let Some(info) = unit_info.get(name) else {
6798        return out;
6799    };
6800    for t in &info.consumes {
6801        let Some(consumed) = unit_info.get(t) else {
6802            continue;
6803        };
6804        let mut services: Vec<&ServiceDecl> = consumed.table.services.values().collect();
6805        services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
6806        for s in services {
6807            // The one `on call` handler a cross-context call reaches
6808            // (`resolver::cross_context_service_for`).
6809            if let Some(h) = s.handlers.iter().find(|h| h.kind == HandlerKind::Call) {
6810                let mut names = Vec::new();
6811                for p in &h.params {
6812                    type_ref_names(&p.type_ref, &HashSet::new(), &mut names);
6813                }
6814                type_ref_names(&h.return_type, &HashSet::new(), &mut names);
6815                push_refs_with(names, t, t, true, &mut out);
6816            }
6817        }
6818    }
6819    out
6820}
6821
6822/// #2617: the type names the constants of every commons `name` uses name in
6823/// their annotations, resolved in that commons' scope, in a stable order. A
6824/// constant the unit hides behind a local declaration, or one its commons
6825/// marks `private`, is not imported, so it reaches nothing.
6826fn used_const_seeds(name: &str, unit_info: &BTreeMap<String, UnitInfo>) -> Vec<Reached> {
6827    let mut out = Vec::new();
6828    let Some(info) = unit_info.get(name) else {
6829        return out;
6830    };
6831    for t in &info.uses {
6832        let Some(used) = unit_info.get(t) else {
6833            continue;
6834        };
6835        let mut consts: Vec<&ConstDecl> = used
6836            .table
6837            .consts
6838            .values()
6839            .filter(|c| c.private.is_none())
6840            .filter(|c| crate::symbols::local_value_kind(&info.table, &c.name.name).is_none())
6841            .collect();
6842        consts.sort_by(|a, b| a.name.name.cmp(&b.name.name));
6843        for c in consts {
6844            let mut names = Vec::new();
6845            type_ref_names(&c.ty, &HashSet::new(), &mut names);
6846            push_refs(names, t, t, &mut out);
6847        }
6848    }
6849    out
6850}
6851
6852/// #1807, #1814: the walk [`close_reachable_types`] and [`close_view_types`]
6853/// share. Seeds from every entry `imported_from` attributes to another unit,
6854/// adds each reached commons type the table lacks (with its methods), and
6855/// calls `on_bound(reached, owner, bound)` for a reached commons type whose
6856/// name the table already binds, `bound` being that binding's provenance
6857/// (`None` for the table's own declaration).
6858#[allow(clippy::too_many_arguments)]
6859fn close_imported<S: ScopeTables + ?Sized>(
6860    scopes: &S,
6861    combined_types: &mut HashMap<String, Arc<TypeDecl>>,
6862    combined_fns: &HashMap<String, Arc<FnDecl>>,
6863    combined_methods: &mut HashMap<String, ResolverMethodTable>,
6864    imported_from: &mut HashMap<String, String>,
6865    imported_from_kind: &mut HashMap<String, UnitKind>,
6866    // #1932: further seeds, each resolved in its own scope (a consumed
6867    // service's signature).
6868    extra_seeds: Vec<Reached>,
6869    mut on_bound: impl FnMut(&Reached, &str, Option<&str>),
6870) -> BTreeMap<String, String> {
6871    let mut queue: Vec<Reached> = Vec::new();
6872    let mut type_names: Vec<&String> = combined_types.keys().collect();
6873    type_names.sort();
6874    for n in type_names {
6875        if let Some(unit) = imported_from.get(n) {
6876            push_refs(
6877                type_decl_ref_names(&combined_types[n]),
6878                unit,
6879                unit,
6880                &mut queue,
6881            );
6882        }
6883    }
6884    let mut fn_names: Vec<&String> = combined_fns.keys().collect();
6885    fn_names.sort();
6886    for n in fn_names {
6887        if let Some(unit) = imported_from.get(n) {
6888            push_refs(
6889                fn_sig_ref_names(&combined_fns[n], &[]),
6890                unit,
6891                unit,
6892                &mut queue,
6893            );
6894        }
6895    }
6896    let mut method_types: Vec<&String> = combined_methods.keys().collect();
6897    method_types.sort();
6898    for t in method_types {
6899        if let Some(unit) = imported_from.get(t) {
6900            let mt = &combined_methods[t];
6901            let attached = combined_types.get(t).map(|d| d.type_params.as_slice());
6902            let mut decls: Vec<&Arc<FnDecl>> =
6903                mt.instance.values().chain(mt.statics.values()).collect();
6904            decls.sort_by_key(|d| d.span.start);
6905            for d in decls {
6906                push_refs(
6907                    fn_sig_ref_names(d, attached.unwrap_or_default()),
6908                    unit,
6909                    unit,
6910                    &mut queue,
6911                );
6912            }
6913        }
6914    }
6915    queue.extend(extra_seeds);
6916    // The walk pops from the back; reverse so names are visited in the
6917    // sorted seeding order and diagnostics come out deterministically.
6918    queue.reverse();
6919
6920    let mut hidden: BTreeMap<String, String> = BTreeMap::new();
6921    let mut visited: HashSet<(String, String)> = HashSet::new();
6922    while let Some(r) = queue.pop() {
6923        if !visited.insert((r.scope.clone(), r.name.clone())) {
6924            continue;
6925        }
6926        let Some(owner) = type_owner_in_scope(&r.scope, &r.name, scopes) else {
6927            continue;
6928        };
6929        // Review of #1813: before the conflict check, so a context-owned
6930        // reach is skipped whether or not this unit binds the name (a
6931        // consumer's own `Money` beside a consumed export's field of the
6932        // exporting context's `Money` is not a conflict).
6933        let Some((owner_table, _, owner_kind)) = scopes.scope(owner) else {
6934            continue;
6935        };
6936        if owner_kind != Some(UnitKind::Commons) {
6937            continue;
6938        }
6939        if combined_types.contains_key(&r.name) {
6940            on_bound(&r, owner, imported_from.get(&r.name).map(String::as_str));
6941            continue;
6942        }
6943        let decl = owner_table.types[&r.name].clone();
6944        push_refs_with(
6945            type_decl_ref_names(&decl),
6946            owner,
6947            &r.via,
6948            r.signature,
6949            &mut queue,
6950        );
6951        combined_types.insert(r.name.clone(), decl.clone());
6952        imported_from.insert(r.name.clone(), owner.to_string());
6953        imported_from_kind.insert(r.name.clone(), UnitKind::Commons);
6954        hidden.insert(r.name.clone(), owner.to_string());
6955        // The reached type's methods come along, as a direct `uses` brings
6956        // them: `r.repo.isValid()` resolves in the declaring scope too.
6957        if let Some(mt) = owner_table.methods.get(&r.name) {
6958            let entry = combined_methods.entry(r.name.clone()).or_default();
6959            let mut decls: Vec<(&String, &Arc<FnDecl>, bool)> = mt
6960                .instance
6961                .iter()
6962                .map(|(m, d)| (m, d, true))
6963                .chain(mt.statics.iter().map(|(m, d)| (m, d, false)))
6964                .collect();
6965            decls.sort_by_key(|(_, d, _)| d.span.start);
6966            for (m, d, is_instance) in decls {
6967                push_refs_with(
6968                    fn_sig_ref_names(d, &decl.type_params),
6969                    owner,
6970                    &r.via,
6971                    r.signature,
6972                    &mut queue,
6973                );
6974                let table = if is_instance {
6975                    &mut entry.instance
6976                } else {
6977                    &mut entry.statics
6978                };
6979                table.entry(m.clone()).or_insert_with(|| d.clone());
6980            }
6981        }
6982    }
6983    hidden
6984}
6985
6986/// What [`close_reachable_types`] finds beyond the unit's composed table.
6987#[derive(Debug, Clone, Default)]
6988pub struct ReachedTypes {
6989    /// Each hidden type name with its owning commons, which emission needs to
6990    /// import it.
6991    pub hidden: BTreeMap<String, String>,
6992    /// #1824: the reached names this unit's own declaration shadows.
6993    pub shadowed: ShadowedReaches,
6994}
6995
6996/// #1824: a type an imported declaration names, which this unit resolves to a
6997/// different declaration of the same name.
6998#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
6999pub struct ShadowedType {
7000    /// The name both declarations share.
7001    pub name: String,
7002    /// The commons whose declaration the imported one means.
7003    pub owner: String,
7004    /// The unit whose declaration the name resolves to here (the unit itself,
7005    /// for its own `type`).
7006    pub bound: String,
7007}
7008
7009/// #1824: the reached type names a unit's own declaration shadows, keyed by
7010/// the declaring unit whose scope resolves the name and the name.
7011///
7012/// Type names are bare strings to the checker, so an imported declaration's
7013/// `Repo` is checked as whatever `Repo` the importing unit binds. When that is
7014/// the unit's own `type Repo`, beside a `uses` of the commons the imported
7015/// declaration means, the checker accepts what the emitted TypeScript rejects.
7016/// `close_reachable_types` records each such reach here; `crate::shadow_uses`
7017/// reports the positions the unit's code fills or reads.
7018#[derive(Debug, Clone, Default)]
7019pub struct ShadowedReaches(HashMap<(String, String), ShadowedType>);
7020
7021impl ShadowedReaches {
7022    /// The reaches in key order, so a rendering of them is the same for two equal
7023    /// values however their `HashMap`s iterate (the language server hashes it).
7024    pub(crate) fn sorted(&self) -> Vec<(&(String, String), &ShadowedType)> {
7025        let mut v: Vec<_> = self.0.iter().collect();
7026        v.sort_by(|a, b| a.0.cmp(b.0));
7027        v
7028    }
7029
7030    /// No imported declaration reaches a shadowed type.
7031    pub fn is_empty(&self) -> bool {
7032        self.0.is_empty()
7033    }
7034
7035    /// The shadowed types `r` names, resolved in `scope` (the unit that
7036    /// declares the position), its type variables `vars` excluded. Sorted, so
7037    /// two positions compare equal when they name the same shadowed types.
7038    pub fn in_type_ref(&self, scope: &str, r: &TypeRef, vars: &[TypeParam]) -> Vec<&ShadowedType> {
7039        let vars: HashSet<&str> = vars.iter().map(|p| p.name.name.as_str()).collect();
7040        let mut names = Vec::new();
7041        type_ref_names(r, &vars, &mut names);
7042        let mut out: Vec<&ShadowedType> = names
7043            .iter()
7044            .filter_map(|n| self.0.get(&(scope.to_string(), n.clone())))
7045            .collect();
7046        out.sort();
7047        out.dedup();
7048        out
7049    }
7050}
7051
7052/// #1807: the unit that owns type `name` as seen from `scope`: `scope` itself
7053/// if it declares `name`, else the first of `scope`'s `uses` that does. This
7054/// is [`compose_unit_symbols`]'s precedence, applied to another unit.
7055fn type_owner_in_scope<'a, S: ScopeTables + ?Sized>(
7056    scope: &'a str,
7057    name: &str,
7058    scopes: &'a S,
7059) -> Option<&'a str> {
7060    let (table, uses, _) = scopes.scope(scope)?;
7061    if table.types.contains_key(name) {
7062        return Some(scope);
7063    }
7064    uses.iter()
7065        .find(|u| {
7066            scopes
7067                .scope(u)
7068                .is_some_and(|(t, _, _)| t.types.contains_key(name))
7069        })
7070        .map(String::as_str)
7071}
7072
7073/// #1807: the type names a type declaration's body references, its own type
7074/// parameters excluded.
7075pub(crate) fn type_decl_ref_names(d: &TypeDecl) -> Vec<String> {
7076    let vars: HashSet<&str> = d.type_params.iter().map(|p| p.name.name.as_str()).collect();
7077    let mut out = Vec::new();
7078    match &d.body {
7079        TypeBody::Record(r) => {
7080            for f in &r.fields {
7081                type_ref_names(&f.type_ref, &vars, &mut out);
7082            }
7083        }
7084        TypeBody::Sum(s) => {
7085            for v in &s.variants {
7086                for p in &v.payload {
7087                    type_ref_names(&p.type_ref, &vars, &mut out);
7088                }
7089            }
7090        }
7091        TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
7092    }
7093    out
7094}
7095
7096/// #1807: the type names a fn's signature references, its own type
7097/// parameters excluded, and for a method its type's (`attached`):
7098/// `fn Box.get(self) -> A` on `type Box[A]` declares no `[A]` of its own.
7099fn fn_sig_ref_names(f: &FnDecl, attached: &[TypeParam]) -> Vec<String> {
7100    let vars: HashSet<&str> = f
7101        .type_params
7102        .iter()
7103        .chain(attached)
7104        .map(|p| p.name.name.as_str())
7105        .collect();
7106    let mut out = Vec::new();
7107    for p in &f.params {
7108        type_ref_names(&p.type_ref, &vars, &mut out);
7109    }
7110    type_ref_names(&f.return_type, &vars, &mut out);
7111    out
7112}
7113
7114/// #1807: every user type name in `r`, outside `vars`. Exhaustive over
7115/// `TypeRef`, so a new compound constructor is a build failure here rather
7116/// than a silently skipped name.
7117pub(crate) fn type_ref_names(r: &TypeRef, vars: &HashSet<&str>, out: &mut Vec<String>) {
7118    match r {
7119        TypeRef::Named(id) => {
7120            if !vars.contains(id.name.as_str()) {
7121                out.push(id.name.clone());
7122            }
7123        }
7124        TypeRef::App { name, args, .. } => {
7125            if !vars.contains(name.name.as_str()) {
7126                out.push(name.name.clone());
7127            }
7128            for a in args {
7129                type_ref_names(a, vars, out);
7130            }
7131        }
7132        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
7133            type_ref_names(a, vars, out);
7134            type_ref_names(b, vars, out);
7135        }
7136        TypeRef::Option(t, _)
7137        | TypeRef::Effect(t, _)
7138        | TypeRef::HttpResult(t, _)
7139        | TypeRef::List(t, _)
7140        | TypeRef::Set(t, _)
7141        | TypeRef::Query(t, _)
7142        | TypeRef::Stream(t, _)
7143        | TypeRef::Connection(t, _)
7144        | TypeRef::History(t, _) => type_ref_names(t, vars, out),
7145        TypeRef::Fn(params, ret, _) => {
7146            for p in params {
7147                type_ref_names(p, vars, out);
7148            }
7149            type_ref_names(ret, vars, out);
7150        }
7151        TypeRef::Base(..)
7152        | TypeRef::QueueResult(_)
7153        | TypeRef::Asset(_)
7154        | TypeRef::RequestHeaders(_)
7155        | TypeRef::RequestQuery(_)
7156        | TypeRef::RequestCookies(_)
7157        | TypeRef::TokenClaims(_)
7158        | TypeRef::BoundaryRejection(_)
7159        | TypeRef::ValidationError(_)
7160        | TypeRef::DecodeError(_)
7161        | TypeRef::Unit(_) => {}
7162    }
7163}
7164
7165/// Phase 8a: compose one unit's symbol space — its local table plus a
7166/// one-level `uses` mixin (commons identity preserved). Returns the combined
7167/// type/fn/method tables and the `imported_from` provenance maps; the mixin
7168/// loop has no `continue`s, so it lifts out whole.
7169#[allow(clippy::type_complexity)]
7170pub fn compose_unit_symbols(
7171    name: &str,
7172    local_table: &UnitTable,
7173    unit_info: &BTreeMap<String, UnitInfo>,
7174) -> (
7175    HashMap<String, Arc<TypeDecl>>,
7176    HashMap<String, Arc<FnDecl>>,
7177    HashMap<String, ResolverMethodTable>,
7178    HashMap<String, String>,
7179    HashMap<String, UnitKind>,
7180) {
7181    // Compose: local + transitive (one level) uses. For commons, mixin
7182    // preserves type identity; for contexts, mixin produces per-context
7183    // nominal types. The resolver doesn't distinguish (the rebranding is
7184    // observable in emission); the symbol table union is the same.
7185    let mut combined_types = local_table.types.clone();
7186    let mut combined_fns = local_table.fns.clone();
7187    let mut combined_methods = local_table.methods.clone();
7188    let mut imported_from: HashMap<String, String> = HashMap::new();
7189    let mut imported_from_kind: HashMap<String, UnitKind> = HashMap::new();
7190
7191    for t in unit_info.get(name).into_iter().flat_map(|i| &i.uses) {
7192        // #2618: an importer never sees a used unit's `private` declarations.
7193        let used = unit_info
7194            .get(t)
7195            .expect("used unit present")
7196            .table
7197            .importable();
7198        for (type_name, decl) in &used.types {
7199            if !combined_types.contains_key(type_name) {
7200                combined_types.insert(type_name.clone(), decl.clone());
7201                imported_from.insert(type_name.clone(), t.clone());
7202                imported_from_kind.insert(type_name.clone(), UnitKind::Commons);
7203            }
7204        }
7205        for (fn_name, decl) in &used.fns {
7206            // #1925: a local declaration of any kind shadows the import, as
7207            // it does in the emitted module ([`shadowed_imports`]).
7208            if !combined_fns.contains_key(fn_name)
7209                && crate::symbols::local_value_kind(local_table, fn_name).is_none()
7210            {
7211                combined_fns.insert(fn_name.clone(), decl.clone());
7212                imported_from.insert(fn_name.clone(), t.clone());
7213                imported_from_kind.insert(fn_name.clone(), UnitKind::Commons);
7214            }
7215        }
7216        // #1883, slice 1b: a used commons' assets are visible here
7217        // (`assets::compose_unit_assets`); record where each came from, so
7218        // the emitter imports its constant from the declaring module. A
7219        // local declaration of the same name, of any kind, wins (#1925).
7220        for asset_name in used.assets.keys() {
7221            if crate::symbols::local_value_kind(local_table, asset_name).is_none()
7222                && !combined_fns.contains_key(asset_name)
7223                && !imported_from.contains_key(asset_name)
7224            {
7225                imported_from.insert(asset_name.clone(), t.clone());
7226                imported_from_kind.insert(asset_name.clone(), UnitKind::Commons);
7227            }
7228        }
7229        // #2387, slice 2: likewise a used commons' embeds.
7230        for embed_name in used.embeds.keys() {
7231            if crate::symbols::local_value_kind(local_table, embed_name).is_none()
7232                && !combined_fns.contains_key(embed_name)
7233                && !imported_from.contains_key(embed_name)
7234            {
7235                imported_from.insert(embed_name.clone(), t.clone());
7236                imported_from_kind.insert(embed_name.clone(), UnitKind::Commons);
7237            }
7238        }
7239        // #2617: and its constants.
7240        for const_name in used.consts.keys() {
7241            if crate::symbols::local_value_kind(local_table, const_name).is_none()
7242                && !combined_fns.contains_key(const_name)
7243                && !imported_from.contains_key(const_name)
7244            {
7245                imported_from.insert(const_name.clone(), t.clone());
7246                imported_from_kind.insert(const_name.clone(), UnitKind::Commons);
7247            }
7248        }
7249        for (type_name, mt) in &used.methods {
7250            let entry = combined_methods.entry(type_name.clone()).or_default();
7251            for (m, decl) in &mt.instance {
7252                entry
7253                    .instance
7254                    .entry(m.clone())
7255                    .or_insert_with(|| decl.clone());
7256            }
7257            for (m, decl) in &mt.statics {
7258                entry
7259                    .statics
7260                    .entry(m.clone())
7261                    .or_insert_with(|| decl.clone());
7262            }
7263        }
7264    }
7265
7266    (
7267        combined_types,
7268        combined_fns,
7269        combined_methods,
7270        imported_from,
7271        imported_from_kind,
7272    )
7273}
7274
7275/// #1925: the `uses`-imported functions and assets that unit `name`'s own
7276/// declarations of another kind shadow, by name. A local declaration wins, as
7277/// in the emitted module, so both compositions leave these out
7278/// ([`compose_unit_symbols`], [`crate::assets::compose_unit_assets`]); the
7279/// resolver and checker report a reference the local declaration cannot answer
7280/// as `bynk.uses.name_conflict` ([`ResolvedCommons::shadowed_import_error`]).
7281/// A same-kind shadow (a local function over an imported one) is ordinary
7282/// shadowing and is not listed. The first `uses` target to declare a name
7283/// decides, as in the compositions.
7284///
7285/// #1927: an imported type a local value hides is listed too, but stays in
7286/// the composed table: an imported declaration that uses it must still check,
7287/// and a value of it may flow through the unit's code. Writing its name is the
7288/// conflict instead ([`crate::resolver::check_shadowed_type_names`]). A local
7289/// type or event over an imported type is #1824's type shadowing, not listed.
7290///
7291/// [`ResolvedCommons::shadowed_import_error`]: crate::resolver::ResolvedCommons::shadowed_import_error
7292pub fn shadowed_imports(
7293    name: &str,
7294    unit_info: &BTreeMap<String, UnitInfo>,
7295) -> HashMap<String, crate::resolver::ShadowedImport> {
7296    let Some(info) = unit_info.get(name) else {
7297        return HashMap::new();
7298    };
7299    shadowed_imports_in(
7300        &info.table,
7301        info.uses
7302            .iter()
7303            .filter_map(|t| unit_info.get(t).map(|u| (t, &u.table))),
7304    )
7305}
7306
7307/// [`shadowed_imports`] over a unit's own table and its `uses` targets'
7308/// tables, in `uses` order — for a caller holding tables rather than
7309/// [`UnitInfo`]s (a suite's view of its target, `crate::test_suites`).
7310pub fn shadowed_imports_in<'a>(
7311    local: &UnitTable,
7312    uses: impl Iterator<Item = (&'a String, &'a UnitTable)>,
7313) -> HashMap<String, crate::resolver::ShadowedImport> {
7314    let mut out = HashMap::new();
7315    for (t, used) in uses {
7316        // #2618: a `private` declaration is never imported, so it hides nothing.
7317        let used = used.importable();
7318        // #1927: an imported type too. A local type or event over it is
7319        // #1824's type shadowing, not this.
7320        let imports = used
7321            .fns
7322            .keys()
7323            .map(|n| (n, "function"))
7324            .chain(used.assets.keys().map(|n| (n, "asset")))
7325            .chain(used.types.keys().map(|n| (n, "type")));
7326        for (n, imported) in imports {
7327            if let Some((kind, local_span)) = crate::symbols::local_value_kind(local, n)
7328                && kind != imported
7329                && !(imported == "type" && kind == "event")
7330            {
7331                let hidden = crate::resolver::ShadowedImport {
7332                    unit: t.clone(),
7333                    imported,
7334                    local: kind,
7335                    local_span,
7336                };
7337                // The first `uses` target to declare a name decides, except
7338                // that a type replaces a function or asset (review of #1933).
7339                // The local value hides both imports, but only the type stays
7340                // composed, so only its entry gates the name: kept second, it
7341                // would let `uses` order decide whether the unit may write it.
7342                match out.entry(n.clone()) {
7343                    std::collections::hash_map::Entry::Vacant(e) => {
7344                        e.insert(hidden);
7345                    }
7346                    std::collections::hash_map::Entry::Occupied(mut e) => {
7347                        if imported == "type" && e.get().imported != "type" {
7348                            e.insert(hidden);
7349                        }
7350                    }
7351                }
7352            }
7353        }
7354    }
7355    out
7356}
7357
7358/// Phase 5c: detect `consumes` cycles. #696: record each `consumes`-clause
7359/// site (file + span) keyed by `(consumer, target)` so a detected cycle
7360/// anchors on the exact clause that forms the closing edge — a real span in
7361/// a real file — and renders with source context. Synthetic units are left
7362/// out so their (snapshot-less) files never claim a diagnostic.
7363pub fn phase_detect_consumes_cycles(
7364    groups: &BTreeMap<String, Vec<usize>>,
7365    parsed: &[ParsedFile],
7366    unit_consumes: &HashMap<String, Vec<String>>,
7367    errors: &mut ErrorSink,
7368) {
7369    let mut consumes_sites: HashMap<(String, String), (PathBuf, Span)> = HashMap::new();
7370    for (name, indices) in groups {
7371        for &i in indices {
7372            if parsed[i].is_synthetic() {
7373                continue;
7374            }
7375            for c in parsed[i].consumes() {
7376                consumes_sites
7377                    .entry((name.clone(), c.target.joined()))
7378                    .or_insert_with(|| (parsed[i].identity_path(), c.span));
7379            }
7380        }
7381    }
7382    let mut cycle_errors: Vec<(Option<PathBuf>, CompileError)> = Vec::new();
7383    detect_consumes_cycles(unit_consumes, &consumes_sites, &mut cycle_errors);
7384    for (path, err) in cycle_errors {
7385        errors.push_for(path.as_deref(), err);
7386    }
7387}
7388
7389#[cfg(test)]
7390mod platform_lock_tests {
7391    use super::{LockViolation, Platform, lock_violation};
7392    use std::collections::BTreeMap;
7393
7394    fn native(entries: &[(Platform, &str)]) -> BTreeMap<Platform, String> {
7395        entries
7396            .iter()
7397            .map(|(p, u)| (*p, (*u).to_string()))
7398            .collect()
7399    }
7400
7401    #[test]
7402    fn empty_closure_imposes_no_lock() {
7403        assert_eq!(lock_violation(&native(&[]), Platform::Node), None);
7404    }
7405
7406    #[test]
7407    fn matching_platform_is_fine() {
7408        let n = native(&[(Platform::Cloudflare, "bynk.cloudflare")]);
7409        assert_eq!(lock_violation(&n, Platform::Cloudflare), None);
7410    }
7411
7412    #[test]
7413    fn mismatched_platform_is_required() {
7414        let n = native(&[(Platform::Cloudflare, "bynk.cloudflare")]);
7415        assert_eq!(
7416            lock_violation(&n, Platform::Node),
7417            Some(LockViolation::Required {
7418                needed: Platform::Cloudflare,
7419                unit: "bynk.cloudflare".to_string(),
7420            })
7421        );
7422    }
7423
7424    // The conflict arm is not yet reachable end-to-end (only one platform
7425    // ships native capabilities until `bynk.aws`); the rule is exercised here
7426    // with a synthetic two-platform set so it does not ship untested
7427    // (proposal v0.19, review call).
7428    #[test]
7429    fn two_platforms_conflict_regardless_of_selection() {
7430        let n = native(&[
7431            (Platform::Cloudflare, "bynk.cloudflare"),
7432            (Platform::Node, "bynk.synthetic"),
7433        ]);
7434        let v = lock_violation(&n, Platform::Cloudflare);
7435        assert_eq!(
7436            v,
7437            Some(LockViolation::Conflict {
7438                a: (Platform::Cloudflare, "bynk.cloudflare".to_string()),
7439                b: (Platform::Node, "bynk.synthetic".to_string()),
7440            })
7441        );
7442    }
7443}
7444
7445#[cfg(test)]
7446mod native_platform_closure_tests {
7447    use super::{HashMap, Platform, UnitTable, native_platforms_of_context};
7448    use bynk_syntax::ast::{CapRef, Ident, ProviderDecl, QualifiedName};
7449    use bynk_syntax::span::Span;
7450    use std::collections::HashMap as StdHashMap;
7451
7452    fn ident(name: &str) -> Ident {
7453        Ident {
7454            name: name.to_string(),
7455            span: Span::default(),
7456        }
7457    }
7458
7459    fn qualified(parts: &[&str]) -> QualifiedName {
7460        QualifiedName {
7461            parts: parts.iter().map(|p| ident(p)).collect(),
7462            span: Span::default(),
7463        }
7464    }
7465
7466    fn given_cap(prefix: Option<&[&str]>, name: &str) -> CapRef {
7467        CapRef {
7468            context: prefix.map(qualified),
7469            name: ident(name),
7470            span: Span::default(),
7471        }
7472    }
7473
7474    fn provider(capability: &str, given: Vec<CapRef>) -> ProviderDecl {
7475        ProviderDecl {
7476            capability: ident(capability),
7477            provider_name: ident(&format!("{capability}Impl")),
7478            given,
7479            ops: Vec::new(),
7480            external: false,
7481            documentation: None,
7482            span: Span::default(),
7483            trivia: Default::default(),
7484        }
7485    }
7486
7487    fn empty_table() -> UnitTable {
7488        UnitTable {
7489            exec_plan: Default::default(),
7490            kind: None,
7491            removed_agents: Vec::new(),
7492            types: StdHashMap::new(),
7493            fns: StdHashMap::new(),
7494            methods: StdHashMap::new(),
7495            capabilities: StdHashMap::new(),
7496            providers: StdHashMap::new(),
7497            services: StdHashMap::new(),
7498            agents: StdHashMap::new(),
7499            actors: StdHashMap::new(),
7500            exported_capabilities: Default::default(),
7501            events: StdHashMap::new(),
7502            flattened_caps: StdHashMap::new(),
7503            consumed_type_aliases: StdHashMap::new(),
7504            unselected_consumed_types: Default::default(),
7505            unlisted_consumed_types: Default::default(),
7506            assets: StdHashMap::new(),
7507            embeds: StdHashMap::new(),
7508            consts: StdHashMap::new(),
7509            derived: StdHashMap::new(),
7510        }
7511    }
7512
7513    /// P5.3 review finding (#1133): nothing in the tree exercised
7514    /// `collect_given_closure`'s recursive arm — every existing fixture that
7515    /// reaches `bynk.cloudflare` does so through a handler's bare `given Kv`
7516    /// (`handler_cross_caps`, depth 0: `provider.given.is_empty()` short-
7517    /// circuits immediately), never through a local provider's own `given`
7518    /// chain. This pins the contract `collect_given_closure`'s own doc
7519    /// states: a context whose *only* path to a platform-native unit is a
7520    /// provider's `given` — `provides Cache = LocalCache given
7521    /// bynk.cloudflare.Kv { … }`, with no handler ever naming `Kv` directly —
7522    /// must still be recognised as native. `bynk-tests/tests/fixtures/negative/
7523    /// 1030_kv_provider_given_wrong_platform` pins the same contract
7524    /// end-to-end through `run_checks`.
7525    #[test]
7526    fn a_providers_given_chain_into_a_platform_native_unit_is_recognised() {
7527        let mut table = empty_table();
7528        table.providers.insert(
7529            "Cache".to_string(),
7530            provider(
7531                "Cache",
7532                vec![given_cap(Some(&["bynk", "cloudflare"]), "Kv")],
7533            ),
7534        );
7535        let mut unit_tables = HashMap::new();
7536        unit_tables.insert("app.web".to_string(), table);
7537        let mut unit_consumes = HashMap::new();
7538        unit_consumes.insert("app.web".to_string(), vec!["bynk.cloudflare".to_string()]);
7539
7540        let native = native_platforms_of_context(
7541            "app.web",
7542            unit_tables.get("app.web").unwrap(),
7543            &unit_tables,
7544            &unit_consumes,
7545            &HashMap::new(),
7546            &HashMap::new(),
7547        );
7548        assert_eq!(
7549            native.get(&Platform::Cloudflare).map(String::as_str),
7550            Some("bynk.cloudflare"),
7551            "a provider's own `given` closure into a platform-native unit must be \
7552             walked recursively, not just a handler's direct `given` — got {native:?}"
7553        );
7554    }
7555
7556    /// A provider whose `given` closure never leaves ordinary (non-native)
7557    /// units contributes nothing — the recursive walk must not manufacture a
7558    /// platform out of thin air.
7559    #[test]
7560    fn a_providers_given_chain_into_an_ordinary_unit_is_not_native() {
7561        let mut table = empty_table();
7562        table.providers.insert(
7563            "Cache".to_string(),
7564            provider("Cache", vec![given_cap(None, "Clock")]),
7565        );
7566        let mut unit_tables = HashMap::new();
7567        unit_tables.insert("app.web".to_string(), table);
7568
7569        let native = native_platforms_of_context(
7570            "app.web",
7571            unit_tables.get("app.web").unwrap(),
7572            &unit_tables,
7573            &HashMap::new(),
7574            &HashMap::new(),
7575            &HashMap::new(),
7576        );
7577        assert!(
7578            native.is_empty(),
7579            "a `given` closure that never reaches a platform-native unit must not \
7580             report one — got {native:?}"
7581        );
7582    }
7583}
7584
7585#[cfg(test)]
7586mod view_closure_tests {
7587    use super::{HashMap, UnitTable, build_unit_table, close_view_types};
7588    use bynk_project::{ParsedFile, UnitKind};
7589    use bynk_syntax::{lexer, parser};
7590    use std::path::PathBuf;
7591
7592    fn table(name: &str, kind: UnitKind, src: &str) -> UnitTable {
7593        let tokens = lexer::tokenize(src).expect("lex");
7594        let unit = parser::parse_unit(&tokens, src).expect("parse");
7595        let path = PathBuf::from(format!("{}.bynk", name.replace('.', "/")));
7596        let pf = ParsedFile::new(path.clone(), path, None, src.to_string(), unit, kind, false);
7597        let mut errors = Vec::new();
7598        build_unit_table(name, kind, &[0], &[pf], &mut errors)
7599    }
7600
7601    /// Review of #1814: a table built without a kind (`UnitTable::default()`,
7602    /// the shape several harnesses build) is still a scope. Its types and its
7603    /// `uses` are searched; only its own declarations, never a commons', are
7604    /// not added. It used to make the scope invisible, so a type reached
7605    /// through it resolved to nothing, silently.
7606    #[test]
7607    fn a_kindless_table_is_still_searched_as_a_scope() {
7608        let core = table(
7609            "t.core",
7610            UnitKind::Commons,
7611            "commons t.core\n\ntype Repo = String where NonEmpty\n",
7612        );
7613        let mut model = table(
7614            "t.model",
7615            UnitKind::Commons,
7616            "commons t.model\n\nuses t.core\n\ntype Run = { repo: Repo }\n",
7617        );
7618        model.kind = None;
7619        let mut types = model.types.clone();
7620        let tables: HashMap<String, UnitTable> =
7621            [("t.core".to_string(), core), ("t.model".to_string(), model)].into();
7622        let uses: HashMap<String, Vec<String>> =
7623            [("t.model".to_string(), vec!["t.core".to_string()])].into();
7624        let reach = close_view_types(
7625            &["t.model".to_string()],
7626            &tables,
7627            &uses,
7628            &mut types,
7629            &HashMap::new(),
7630            &mut HashMap::new(),
7631            false,
7632        );
7633        assert_eq!(
7634            reach.hidden.get("Repo").map(String::as_str),
7635            Some("t.core"),
7636            "{:?}",
7637            reach.hidden
7638        );
7639        assert!(types.contains_key("Repo"));
7640    }
7641
7642    /// Review of #3835: a participant's handler signature reaches a commons
7643    /// type without a conflict (#3760), but that reach must not claim the
7644    /// type first and so swallow the conflict another participant's actor
7645    /// identity reports for it (#3064). The walk marks a commons type visited
7646    /// however it was reached, so identities are seeded before signatures.
7647    #[test]
7648    fn a_signature_reach_does_not_swallow_an_identity_conflict() {
7649        let lib = table(
7650            "t.lib",
7651            UnitKind::Commons,
7652            "commons t.lib\n\ntype X = String where NonEmpty\n\ntype Wrap = { x: X }\n\ntype Id = { x: X }\n",
7653        );
7654        let a = table(
7655            "t.a",
7656            UnitKind::Context,
7657            "context t.a\n\nuses t.lib\n\nservice s {\n  on call() -> Effect[Wrap] by Caller { Effect.pure(Wrap { x: X.unsafe(\"x\") }) }\n}\n",
7658        );
7659        let b = table(
7660            "t.b",
7661            UnitKind::Context,
7662            "context t.b\n\nuses t.lib\n\nactor U { auth = Internal, identity = Id }\n",
7663        );
7664        // The suite's own `X`, a different declaration from `t.lib`'s.
7665        let mine = table(
7666            "t.mine",
7667            UnitKind::Commons,
7668            "commons t.mine\n\ntype X = Int\n",
7669        );
7670        let mut types = mine.types.clone();
7671        let tables: HashMap<String, UnitTable> = [
7672            ("t.lib".to_string(), lib),
7673            ("t.a".to_string(), a),
7674            ("t.b".to_string(), b),
7675            ("t.mine".to_string(), mine),
7676        ]
7677        .into();
7678        let uses: HashMap<String, Vec<String>> = [
7679            ("t.a".to_string(), vec!["t.lib".to_string()]),
7680            ("t.b".to_string(), vec!["t.lib".to_string()]),
7681        ]
7682        .into();
7683        let reach = close_view_types(
7684            &["t.a".to_string(), "t.b".to_string()],
7685            &tables,
7686            &uses,
7687            &mut types,
7688            &HashMap::new(),
7689            &mut HashMap::new(),
7690            true,
7691        );
7692        assert!(
7693            reach
7694                .conflicts
7695                .iter()
7696                .any(|c| c.name == "X" && c.via == "t.b"),
7697            "{:?}",
7698            reach.conflicts
7699        );
7700    }
7701}
7702
7703#[cfg(test)]
7704mod label_attribution_tests {
7705    use super::*;
7706
7707    /// Each label is attributed by the `FileId` its span carries: the error's
7708    /// own file when it shares the primary span's id, has none, or names the
7709    /// error's own path; another registered file by its path; and an
7710    /// unregistered file (a toolchain-injected unit) as unavailable.
7711    #[test]
7712    fn labels_are_attributed_to_the_file_their_span_is_in() {
7713        let (own, sibling, injected) = (FileId(10), FileId(11), FileId(12));
7714        let mut sink = ErrorSink::new();
7715        sink.register_file(own, PathBuf::from("src/app/z_more.bynk"));
7716        sink.register_file(sibling, PathBuf::from("src/app/a_web.bynk"));
7717        let error = CompileError::new(
7718            "bynk.resolve.duplicate_service",
7719            Span::new_in(own, 24, 27),
7720            "service `api` is already declared",
7721        )
7722        .with_label(Span::new_in(own, 0, 1), "same id")
7723        .with_label(Span::new(0, 1), "no id")
7724        .with_label(Span::new_in(sibling, 21, 24), "sibling")
7725        .with_label(Span::new_in(injected, 0, 1), "unregistered");
7726        sink.push_for(Some(Path::new("src/app/z_more.bynk")), error);
7727        let all = sink.into_all();
7728        assert_eq!(
7729            all[0].label_files,
7730            vec![
7731                LabelFile::Primary,
7732                LabelFile::Primary,
7733                LabelFile::Other(PathBuf::from("src/app/a_web.bynk")),
7734                LabelFile::Unavailable,
7735            ]
7736        );
7737    }
7738
7739    /// #3243: attributing against files registered once up front — what the
7740    /// per-unit check loops do — puts an error in the file its span names, and
7741    /// leaves one whose span matches no registered file unattributed.
7742    #[test]
7743    fn extend_attributed_uses_the_files_registered_up_front() {
7744        let known = FileId(40);
7745        let mut sink = ErrorSink::new();
7746        sink.register_file(known, PathBuf::from("src/a.bynk"));
7747        sink.extend_attributed([CompileError::new(
7748            "bynk.resolve.duplicate_service",
7749            Span::new_in(known, 0, 1),
7750            "in a registered file",
7751        )]);
7752        sink.extend_attributed([CompileError::new(
7753            "bynk.resolve.duplicate_service",
7754            Span::new_in(FileId(41), 0, 1),
7755            "in no registered file",
7756        )]);
7757        let all = sink.into_all();
7758        assert_eq!(all[0].source_path.as_deref(), Some(Path::new("src/a.bynk")));
7759        assert_eq!(all[1].source_path, None);
7760    }
7761
7762    /// #1956: a label into a first-party unit carries that unit's reserved
7763    /// `FileId`, so it is attributed to the unit — with its own source — never
7764    /// taken for the error's file.
7765    #[test]
7766    fn a_label_in_a_firstparty_unit_is_attributed_to_that_unit() {
7767        let unit = firstparty::unit("bynk").expect("the `bynk` unit is registered");
7768        let own = FileId(30);
7769        let mut sink = ErrorSink::new();
7770        sink.register_file(own, PathBuf::from("src/app/web.bynk"));
7771        let error = CompileError::new(
7772            "bynk.resolve.missing_field",
7773            Span::new_in(own, 0, 7),
7774            "missing required field `headers` for record `Request`",
7775        )
7776        .with_label(
7777            Span::new_in(firstparty_file_id(unit), 0, 7),
7778            "field declared here",
7779        );
7780        sink.push_for(Some(Path::new("src/app/web.bynk")), error);
7781        assert_eq!(
7782            sink.into_all()[0].label_files,
7783            vec![LabelFile::FirstParty {
7784                identity_path: unit.identity_path,
7785                source: unit.source,
7786            }]
7787        );
7788    }
7789
7790    /// With no file identity on the primary span, a label is still the
7791    /// error's own file when its id names the error's own path.
7792    #[test]
7793    fn a_label_naming_the_errors_own_path_is_primary() {
7794        let own = FileId(20);
7795        let mut sink = ErrorSink::new();
7796        sink.register_file(own, PathBuf::from("src/a.bynk"));
7797        let error = CompileError::new("bynk.test", Span::default(), "msg")
7798            .with_label(Span::new_in(own, 0, 1), "here");
7799        sink.push_for(Some(Path::new("src/a.bynk")), error);
7800        assert_eq!(sink.into_all()[0].label_files, vec![LabelFile::Primary]);
7801    }
7802}
7803
7804/// #1925: a unit's own declaration of another kind shadowing a `uses`-imported
7805/// function or asset, and (#1927) a unit's own value shadowing an imported
7806/// type. A local declaration wins, as in the emitted module; a reference it
7807/// cannot answer, or a written hidden type name, is `bynk.uses.name_conflict`,
7808/// in a function body (the resolver's walk) and a handler body (the
7809/// checker's) alike.
7810#[cfg(test)]
7811mod shadowed_import_tests {
7812    use crate::testkit::analyse;
7813
7814    /// Each imported kind: its declaration in `lib.util`, and an expression
7815    /// using it with the type that expression has.
7816    const IMPORTED: [(&str, &str, &str, &str); 3] = [
7817        (
7818            "function",
7819            "fn thing() -> Int {\n  1\n}\n",
7820            "thing()",
7821            "Int",
7822        ),
7823        (
7824            "asset",
7825            "asset thing = \"assets/x.json\"\n",
7826            "thing.url",
7827            "String",
7828        ),
7829        // #1927: writing an imported type's name (here, constructing one).
7830        (
7831            "type",
7832            "type thing = { n: Int }\n",
7833            "thing { n: 1 }.n",
7834            "Int",
7835        ),
7836    ];
7837
7838    const LOCAL: [(&str, &str); 7] = [
7839        ("function", "fn thing() -> Int {\n  2\n}\n"),
7840        ("asset", "asset thing = \"assets/x.json\"\n"),
7841        ("type", "type thing = { n: Int }\n"),
7842        ("event", "event thing = { n: Int }\n"),
7843        (
7844            "service",
7845            "service thing {\n  on call() -> Effect[Int] by Caller {\n    Effect.pure(1)\n  }\n}\n",
7846        ),
7847        (
7848            "agent",
7849            "agent thing {\n  key id: String\n\n  store hits: Cell[Int]\n\n  on call ping() -> Effect[Int] {\n    1\n  }\n}\n",
7850        ),
7851        (
7852            "provider",
7853            "capability ProbeCap {\n  fn go() -> Effect[Int]\n}\n\nprovides ProbeCap = thing {\n  fn go() -> Effect[Int] {\n    Effect.pure(1)\n  }\n}\n",
7854        ),
7855    ];
7856
7857    #[derive(Clone, Copy, Debug)]
7858    enum Use {
7859        None,
7860        FnBody,
7861        HandlerBody,
7862    }
7863
7864    #[test]
7865    fn every_local_kind_against_every_import_and_use_site() {
7866        for (imported, idecl, expr, ty) in IMPORTED {
7867            for (local, ldecl) in LOCAL {
7868                for at in [Use::None, Use::FnBody, Use::HandlerBody] {
7869                    let using = match at {
7870                        Use::None => String::new(),
7871                        Use::FnBody => format!("fn useIt() -> {ty} {{\n  {expr}\n}}\n"),
7872                        Use::HandlerBody => format!(
7873                            "service user {{\n  on call() -> Effect[{ty}] by Caller {{\n    Effect.pure({expr})\n  }}\n}}\n"
7874                        ),
7875                    };
7876                    let lib = format!("commons lib.util\n\n{idecl}");
7877                    let app = format!("context app\n\nuses lib.util\n\n{ldecl}\n{using}");
7878                    let r = analyse(&[
7879                        ("lib/util.bynk", &lib),
7880                        ("app/main.bynk", &app),
7881                        ("assets/x.json", "{}"),
7882                    ]);
7883                    let cats = r.error_categories();
7884                    let case = format!("local {local} over imported {imported}, used {at:?}");
7885                    let want: Vec<&str> = match at {
7886                        // An unused shadow, and a same-kind one, are legal.
7887                        Use::None => vec![],
7888                        _ if local == imported => vec![],
7889                        // An event is a type: a local one over an imported
7890                        // type is #1824's type shadowing, and answers.
7891                        _ if imported == "type" && local == "event" => vec![],
7892                        // In a function body the resolver reads `thing.url`
7893                        // on a type name as a static member of the type, and
7894                        // rejects it under that code.
7895                        Use::FnBody if imported == "asset" && matches!(local, "type" | "event") => {
7896                            vec!["bynk.resolve.unknown_static_member"]
7897                        }
7898                        // A local agent answers a call in a handler (agent
7899                        // construction), wrongly here: one key, not none.
7900                        // Its diagnostic notes the hidden import.
7901                        Use::HandlerBody if imported == "function" && local == "agent" => {
7902                            vec!["bynk.agent.construction_arity"]
7903                        }
7904                        _ => vec!["bynk.uses.name_conflict"],
7905                    };
7906                    assert_eq!(cats, want, "{case}");
7907                }
7908            }
7909        }
7910    }
7911
7912    /// A local declaration that can answer the reference does: a call to a
7913    /// local agent is the agent, not the hidden import (before #1925 the
7914    /// checker preferred the imported function, against the emitted module).
7915    #[test]
7916    fn a_local_agent_answers_its_own_call() {
7917        let r = analyse(&[
7918            (
7919                "lib/util.bynk",
7920                "commons lib.util\n\nfn thing() -> Int {\n  1\n}\n",
7921            ),
7922            (
7923                "app/main.bynk",
7924                "context app\n\nuses lib.util\n\nagent thing {\n  key id: String\n\n  store hits: Cell[Int]\n\n  on call ping() -> Effect[Int] {\n    1\n  }\n}\n\nservice web {\n  on call() -> Effect[Int] by Caller {\n    let n <- thing(\"k\").ping()\n    Effect.pure(n)\n  }\n}\n",
7925            ),
7926        ]);
7927        r.assert_clean();
7928    }
7929
7930    /// Review of #1926: two used commons declaring one name are no ambiguity
7931    /// when the unit hides both behind its own declaration — an unused
7932    /// shadow stays legal (`phase_uses_name_conflicts` shares the predicate).
7933    #[test]
7934    fn a_local_service_hiding_two_used_imports_is_no_ambiguity() {
7935        let r = analyse(&[
7936            (
7937                "lib/a.bynk",
7938                "commons lib.a\n\nfn thing() -> Int {\n  1\n}\n",
7939            ),
7940            (
7941                "lib/b.bynk",
7942                "commons lib.b\n\nfn thing() -> Int {\n  2\n}\n",
7943            ),
7944            (
7945                "app/main.bynk",
7946                "context app\n\nuses lib.a\nuses lib.b\n\nservice thing {\n  on call() -> Effect[Int] by Caller {\n    Effect.pure(1)\n  }\n}\n",
7947            ),
7948        ]);
7949        r.assert_clean();
7950    }
7951
7952    /// Review of #1926: a bare reference to a local function that hides an
7953    /// imported asset means the function; only a field read (`thing.url`)
7954    /// means the hidden asset.
7955    #[test]
7956    fn a_bare_local_function_keeps_its_own_advice() {
7957        let lib = (
7958            "lib/util.bynk",
7959            "commons lib.util\n\nasset thing = \"assets/x.json\"\n",
7960        );
7961        let file = |body: &str| {
7962            format!(
7963                "context app\n\nuses lib.util\n\nfn thing() -> Int {{\n  1\n}}\n\nfn useIt() -> Int {{\n  {body}\n}}\n"
7964            )
7965        };
7966        let bare = file("thing + 1");
7967        let r = analyse(&[lib, ("app/main.bynk", &bare), ("assets/x.json", "{}")]);
7968        assert_eq!(r.error_categories(), vec!["bynk.resolve.fn_without_call"]);
7969        let read = file("let u = thing.url\n  1");
7970        let r = analyse(&[lib, ("app/main.bynk", &read), ("assets/x.json", "{}")]);
7971        assert_eq!(r.error_categories(), vec!["bynk.uses.name_conflict"]);
7972    }
7973
7974    /// #1927: the sum used across these tests, from a commons, with a
7975    /// function that makes one and one that reads one.
7976    const STATUS_LIB: (&str, &str) = (
7977        "lib/st.bynk",
7978        "commons lib.st\n\ntype Status =\n  | Done\n  | Pending\n  | Failed(reason: String)\n\nfn mk() -> Status {\n  Done\n}\n\nfn isDone(s: Status) -> Bool {\n  match s {\n    Done => true\n    _ => false\n  }\n}\n",
7979    );
7980
7981    /// #1927: a bare variant of a hidden sum emits the sum's name, which the
7982    /// local declaration has taken, so constructing one is the conflict.
7983    /// Matching one is not: a pattern emits the variant's tag alone.
7984    #[test]
7985    fn a_hidden_sums_bare_variant_constructs_only_by_conflict() {
7986        let unit = |body: &str| {
7987            format!("commons app\n\nuses lib.st\n\nfn Status() -> Int {{\n  1\n}}\n\n{body}")
7988        };
7989        let construct = unit("fn f() -> Bool {\n  isDone(Done)\n}\n");
7990        let r = analyse(&[STATUS_LIB, ("app/main.bynk", &construct)]);
7991        assert_eq!(r.error_categories(), vec!["bynk.uses.name_conflict"]);
7992        // A payload variant, constructed by a bare call.
7993        let construct = unit("fn f() -> Bool {\n  isDone(Failed(\"x\"))\n}\n");
7994        let r = analyse(&[STATUS_LIB, ("app/main.bynk", &construct)]);
7995        assert_eq!(r.error_categories(), vec!["bynk.uses.name_conflict"]);
7996        let matched = unit(
7997            "fn f() -> Bool {\n  match mk() {\n    Done => true\n    Failed(r) => false\n    _ => false\n  }\n}\n",
7998        );
7999        let r = analyse(&[STATUS_LIB, ("app/main.bynk", &matched)]);
8000        r.assert_clean();
8001    }
8002
8003    /// #1927: a value of a hidden type flows through the unit's code, and an
8004    /// imported declaration that uses the type still checks; only writing the
8005    /// name is the conflict.
8006    #[test]
8007    fn a_hidden_types_values_still_flow() {
8008        let r = analyse(&[
8009            STATUS_LIB,
8010            (
8011                "app/main.bynk",
8012                "context app\n\nuses lib.st\n\nagent Status {\n  key id: String\n\n  store hits: Cell[Int]\n\n  on call ping() -> Effect[Int] {\n    1\n  }\n}\n\nfn f() -> Bool {\n  let s = mk()\n  isDone(s)\n}\n",
8013            ),
8014        ]);
8015        r.assert_clean();
8016    }
8017
8018    /// #1927: a local asset answers its own `.url`, even beside a hidden
8019    /// imported type of its name.
8020    #[test]
8021    fn a_local_asset_answers_its_own_url_beside_a_hidden_type() {
8022        let r = analyse(&[
8023            STATUS_LIB,
8024            (
8025                "app/main.bynk",
8026                "commons app\n\nuses lib.st\n\nasset Status = \"assets/x.json\"\n\nfn f() -> String {\n  Status.url\n}\n",
8027            ),
8028            ("assets/x.json", "{}"),
8029        ]);
8030        r.assert_clean();
8031    }
8032
8033    /// Review of #1933: two used commons declaring the hidden name as a type
8034    /// and as a function. The local value hides both, and the type still
8035    /// gates the name whichever `uses` comes first.
8036    #[test]
8037    fn a_hidden_type_gates_whatever_the_uses_order() {
8038        let a = ("lib/a.bynk", "commons lib.a\n\ntype Status = { n: Int }\n");
8039        let b = (
8040            "lib/b.bynk",
8041            "commons lib.b\n\nfn Status() -> Int {\n  1\n}\n",
8042        );
8043        for (first, second) in [("lib.a", "lib.b"), ("lib.b", "lib.a")] {
8044            let app = format!(
8045                "context app\n\nuses {first}\nuses {second}\n\nservice Status {{\n  on call() -> Effect[Int] by Caller {{\n    Effect.pure(1)\n  }}\n}}\n\nfn f(s: Status) -> Int {{\n  s.n\n}}\n"
8046            );
8047            let r = analyse(&[a, b, ("app/main.bynk", &app)]);
8048            assert_eq!(
8049                r.error_categories(),
8050                vec!["bynk.uses.name_conflict"],
8051                "uses {first} then {second}"
8052            );
8053        }
8054    }
8055
8056    /// Review of #1933: a local function hiding an imported type answers a
8057    /// bare reference as a function value.
8058    #[test]
8059    fn a_local_function_hiding_a_type_is_a_function_value() {
8060        let r = analyse(&[
8061            (
8062                "lib/util.bynk",
8063                "commons lib.util\n\ntype thing = { n: Int }\n",
8064            ),
8065            (
8066                "app/main.bynk",
8067                "commons app\n\nuses lib.util\n\nfn thing(x: Int) -> Int {\n  x + 1\n}\n\nfn f() -> List[Int] {\n  [1, 2].map(thing)\n}\n",
8068            ),
8069        ]);
8070        r.assert_clean();
8071    }
8072
8073    /// #1927: a local value named like a type a context consumes conflicts at
8074    /// the `consumes` clause, as a local type of that name already does.
8075    #[test]
8076    fn a_local_value_named_like_a_consumed_export_conflicts() {
8077        let r = analyse(&[
8078            (
8079                "shop.bynk",
8080                "context shop\n\nexports transparent { Order }\n\ntype Order = { id: String }\n",
8081            ),
8082            (
8083                "app.bynk",
8084                "context app\n\nconsumes shop\n\nservice Order {\n  on call() -> Effect[Int] by Caller {\n    Effect.pure(1)\n  }\n}\n",
8085            ),
8086        ]);
8087        assert_eq!(r.error_categories(), vec!["bynk.consumes.name_conflict"]);
8088    }
8089
8090    /// The diagnostic names both declarations and where the local one is.
8091    #[test]
8092    fn the_conflict_names_both_declarations() {
8093        let r = analyse(&[
8094            (
8095                "lib/util.bynk",
8096                "commons lib.util\n\nfn thing() -> Int {\n  1\n}\n",
8097            ),
8098            (
8099                "app/main.bynk",
8100                "context app\n\nuses lib.util\n\ntype thing = { n: Int }\n\nfn useIt() -> Int {\n  thing()\n}\n",
8101            ),
8102        ]);
8103        let e = r
8104            .analysis
8105            .errors
8106            .iter()
8107            .find(|e| e.error.category == "bynk.uses.name_conflict")
8108            .expect("a conflict");
8109        assert_eq!(
8110            e.error.message,
8111            "`thing` names this unit's type, which hides the function `thing` from `lib.util`"
8112        );
8113    }
8114
8115    const WITHIN_SVC: &str = "\nservice s {\n  on call() -> Effect[String] by Caller {\n    let r <- Effect.pure(1).within(2.seconds)\n    Effect.pure(\"x\")\n  }\n}\n";
8116
8117    /// #2765: the braces may name a type the target exports, so the form the
8118    /// `timed_out_not_in_scope` note recommends is accepted.
8119    #[test]
8120    fn consumes_bynk_may_select_an_exported_type() {
8121        for consumes in [
8122            "consumes bynk { TimedOut }",
8123            "consumes bynk { Clock, TimedOut }",
8124        ] {
8125            let src = format!("context app\n\n{consumes}\n{WITHIN_SVC}");
8126            let r = analyse(&[("app.bynk", &src)]);
8127            assert!(
8128                r.error_categories().is_empty(),
8129                "{consumes}: {:?}",
8130                r.error_categories()
8131            );
8132        }
8133    }
8134
8135    /// A type repeated in one file is refused, as a repeated capability is.
8136    #[test]
8137    fn a_repeated_type_selection_is_refused() {
8138        let src = format!("context app\n\nconsumes bynk {{ TimedOut, TimedOut }}\n{WITHIN_SVC}");
8139        let r = analyse(&[("app.bynk", &src)]);
8140        assert_eq!(
8141            r.error_categories(),
8142            vec!["bynk.consumes.capability_name_clash"]
8143        );
8144    }
8145
8146    /// A braced name that is neither an exported capability nor an exported
8147    /// type is still refused.
8148    #[test]
8149    fn consumes_bynk_still_refuses_an_unknown_name() {
8150        let r = analyse(&[("app.bynk", "context app\n\nconsumes bynk { NoSuchThing }\n")]);
8151        assert_eq!(
8152            r.error_categories(),
8153            vec!["bynk.given.cross_context_unknown_capability"]
8154        );
8155    }
8156
8157    /// The note recommends only forms that work.
8158    #[test]
8159    fn timed_out_not_in_scope_note_names_the_accepted_form() {
8160        let src = format!("context app\n{WITHIN_SVC}");
8161        let r = analyse(&[("app.bynk", &src)]);
8162        let e = r
8163            .analysis
8164            .errors
8165            .iter()
8166            .find(|e| e.error.category == "bynk.within.timed_out_not_in_scope")
8167            .expect("TimedOut is not in scope without `consumes bynk`");
8168        assert!(
8169            e.error
8170                .notes
8171                .iter()
8172                .any(|n| n.contains("consumes bynk { TimedOut }")),
8173            "{:?}",
8174            e.error.notes
8175        );
8176    }
8177}
8178
8179/// #2887: `consumes U { T as Alias }` renames an exported type in the consuming
8180/// context, so it no longer clashes with a local or `uses` type of that name.
8181#[cfg(test)]
8182mod consumes_alias_tests {
8183    use crate::stability::StabilityPolicy;
8184    use crate::testkit::{Analysed, analyse_with};
8185
8186    const REPORT: (&str, &str) = (
8187        "report.bynk",
8188        "commons report\n\ntype Digest = { total: Int }\n",
8189    );
8190
8191    fn run(files: &[(&str, &str)]) -> Analysed {
8192        analyse_with(files, Some(StabilityPolicy::permissive()))
8193    }
8194
8195    fn app(consumes: &str, body: &str) -> String {
8196        format!("context app\n\nuses report\n{consumes}\n\n{body}\n")
8197    }
8198
8199    const USES_BOTH: &str = "fn empty() -> Digest { Digest { total: 0 } }\n\
8200        fn name(d: CryptoDigest) -> String {\n  match d {\n    Sha256 => \"a\"\n    Sha384 => \"b\"\n    Sha512 => \"c\"\n  }\n}\n\
8201        service hashing {\n  on call() -> Effect[Bytes] by Caller given Crypto {\n    Crypto.digest(CryptoDigest.Sha256, Bytes.fromUtf8(\"x\"))\n  }\n}";
8202
8203    #[test]
8204    fn an_aliased_export_clears_the_clash_and_works_everywhere() {
8205        let src = app(
8206            "consumes bynk.crypto { Crypto, Digest as CryptoDigest }",
8207            USES_BOTH,
8208        );
8209        let a = run(&[REPORT, ("app.bynk", &src)]);
8210        a.assert_clean();
8211        // The unaliased `Digest` is still the commons record.
8212        assert_eq!(a.resolves_to("app.bynk", "Digest {").unit, "report");
8213    }
8214
8215    #[test]
8216    fn an_alias_names_the_real_declaration_for_the_ide() {
8217        // A user adapter as the target, so its declarations are in the index
8218        // (a first-party unit's references are tokens only).
8219        let lib = (
8220            "lib.bynk",
8221            "adapter lib\n\nbinding \"./lib.binding.ts\"\n\nexports transparent { Digest }\n\ntype Digest = enum { Fast, Slow }\n",
8222        );
8223        let src = app(
8224            "consumes lib { Digest as LibDigest }",
8225            "fn pick() -> LibDigest { LibDigest.Fast }\nfn empty() -> Digest { Digest { total: 0 } }",
8226        );
8227        let a = run(&[
8228            REPORT,
8229            lib,
8230            ("lib.binding.ts", "export {};\n"),
8231            ("app.bynk", &src),
8232        ]);
8233        a.assert_clean();
8234        for needle in ["Digest as", "LibDigest {", "LibDigest.Fast"] {
8235            let key = a.resolves_to("app.bynk", needle);
8236            assert_eq!(
8237                (key.unit.as_str(), key.name.as_str()),
8238                ("lib", "Digest"),
8239                "{needle}"
8240            );
8241        }
8242        assert_eq!(a.resolves_to("app.bynk", "Digest { total").unit, "report");
8243    }
8244
8245    /// #3536: braces that list only `Clock` do not bring `Method` in, and no
8246    /// listed capability's signature reaches it, so the unit's own `Method` is
8247    /// not in conflict with the standard library's.
8248    #[test]
8249    fn an_unlisted_export_yields_to_the_units_own_type() {
8250        let src = app(
8251            "consumes bynk { Clock }",
8252            "type Method = | Fetch | Skip\n\nfn pick() -> Method { Fetch }",
8253        );
8254        run(&[REPORT, ("app.bynk", &src)]).assert_clean();
8255    }
8256
8257    /// A type a listed capability's signatures use is still the standard
8258    /// library's, so the unit's own type of that name still conflicts, with a
8259    /// note that names the way out.
8260    #[test]
8261    fn the_unaliased_form_still_clashes_with_a_note_that_names_the_way_out() {
8262        let src = app(
8263            "consumes bynk.crypto { Crypto }",
8264            "fn empty() -> Digest { Digest { total: 0 } }",
8265        );
8266        let a = run(&[REPORT, ("app.bynk", &src)]);
8267        assert_eq!(a.error_categories(), vec!["bynk.consumes.name_conflict"]);
8268        let e = &a.analysis.errors[0].error;
8269        assert!(
8270            e.notes.iter().any(|n| n.contains("Digest as CryptoDigest")),
8271            "{:?}",
8272            e.notes
8273        );
8274    }
8275
8276    #[test]
8277    fn a_refused_alias_does_not_take_over_the_name_it_clashed_with() {
8278        // `Report` is the local type; the clashing alias is refused and must not
8279        // redirect hover or go-to-definition to the module's `Digest`.
8280        let src = "context app\n\nconsumes bynk.crypto { Crypto, Digest as Report }\n\ntype Report = { total: Int }\n\nfn f(r: Report) -> Int { r.total }\n";
8281        let a = run(&[("app.bynk", src)]);
8282        assert_eq!(
8283            a.error_categories(),
8284            vec!["bynk.consumes.type_alias_conflict"]
8285        );
8286        // The unit does not check past the refusal, so the proof is that the
8287        // index neither panics nor files the alias under the module's type:
8288        // the local `Report` stays the one declaration of that name.
8289        let reports: Vec<_> = a
8290            .analysis
8291            .index
8292            .symbols
8293            .keys()
8294            .filter(|k| k.name == "Report" || k.name == "Digest")
8295            .collect();
8296        assert!(
8297            reports
8298                .iter()
8299                .all(|k| k.unit == "app" && k.name == "Report"),
8300            "{reports:?}"
8301        );
8302    }
8303
8304    #[test]
8305    fn the_conflict_note_for_a_context_also_names_the_alias_form() {
8306        // An alias works for a context's type as for an adapter's, so the note
8307        // may recommend it there.
8308        let lib = (
8309            "lib.bynk",
8310            "context lib\n\nexports transparent { Code }\n\ntype Code = enum { A, B }\n",
8311        );
8312        let codes = ("codes.bynk", "commons codes\n\ntype Code = { n: Int }\n");
8313        let app = "context app\n\nuses codes\nconsumes lib\n\nfn one() -> Int { 1 }\n";
8314        let a = run(&[lib, codes, ("app.bynk", app)]);
8315        assert_eq!(a.error_categories(), vec!["bynk.consumes.name_conflict"]);
8316        assert!(
8317            a.analysis.errors[0]
8318                .error
8319                .notes
8320                .iter()
8321                .any(|n| n.contains("Code as LibCode")),
8322            "{:?}",
8323            a.analysis.errors[0].error.notes
8324        );
8325    }
8326
8327    #[test]
8328    fn the_original_name_is_not_in_scope_once_aliased() {
8329        let src = app(
8330            "consumes bynk.crypto { Crypto, Digest as CryptoDigest }",
8331            "fn f(d: Digest) -> Int { 1 }",
8332        );
8333        // `Digest` is the commons record here; handing it where the module's
8334        // enum is expected is a type error, not a silent conflation.
8335        let a = run(&[REPORT, ("app.bynk", &src)]);
8336        a.assert_clean();
8337        let bad = app(
8338            "consumes bynk.crypto { Crypto, Digest as CryptoDigest }",
8339            "service s {\n  on call() -> Effect[Bytes] by Caller given Crypto {\n    Crypto.digest(Digest { total: 1 }, Bytes.fromUtf8(\"x\"))\n  }\n}",
8340        );
8341        let a = run(&[REPORT, ("app.bynk", &bad)]);
8342        assert!(
8343            !a.error_categories().is_empty(),
8344            "the local Digest is not the crypto Digest"
8345        );
8346    }
8347
8348    #[test]
8349    fn an_alias_in_one_file_of_a_split_context_applies_to_the_unit() {
8350        let one = "context app\n\nuses report\nconsumes bynk.crypto { Crypto, Digest as CryptoDigest }\n\nfn empty() -> Digest { Digest { total: 0 } }\n";
8351        let two = "context app\n\nuses report\nconsumes bynk.crypto { Crypto, Digest as CryptoDigest }\n\nfn first() -> CryptoDigest { CryptoDigest.Sha256 }\n";
8352        run(&[REPORT, ("app/one.bynk", one), ("app/two.bynk", two)]).assert_clean();
8353        let disagree =
8354            "context app\n\nuses report\nconsumes bynk.crypto { Crypto, Digest as Other }\n";
8355        let a = run(&[REPORT, ("app/one.bynk", one), ("app/two.bynk", disagree)]);
8356        assert!(
8357            a.error_categories()
8358                .contains(&"bynk.consumes.type_alias_repeated"),
8359            "{:?}",
8360            a.error_categories()
8361        );
8362    }
8363}
8364
8365#[cfg(test)]
8366mod firstparty_injection_tests {
8367    use super::{
8368        ErrorSink, ParsedFile, UnitKind, firstparty, firstparty_file_id, inject_firstparty, lexer,
8369        parser,
8370    };
8371    use bynk_syntax::span::FileId;
8372    use std::collections::BTreeSet;
8373    use std::path::PathBuf;
8374
8375    /// The seven references a project can make to a first-party unit, in a
8376    /// fixed order: `consumes` for the two adapters, `uses` for the commons.
8377    const REFS: [&str; 7] = [
8378        "consumes bynk { Clock }",
8379        "consumes bynk.cloudflare { Kv }",
8380        "uses bynk.map",
8381        "uses bynk.list",
8382        "uses bynk.string",
8383        "uses bynk.locale",
8384        "uses bynk.locale.types",
8385    ];
8386
8387    /// #1956: every injected first-party unit's spans carry its reserved
8388    /// `FileId` — distinct per unit and never `FileId::UNKNOWN` — so a label
8389    /// into one is never taken for the user's file.
8390    #[test]
8391    fn injected_units_carry_their_reserved_file_id() {
8392        let ids: BTreeSet<FileId> = firstparty::UNITS.iter().map(firstparty_file_id).collect();
8393        assert_eq!(ids.len(), firstparty::UNITS.len());
8394        assert!(!ids.contains(&FileId::UNKNOWN));
8395        let mut parsed = project((1 << REFS.len()) - 1);
8396        let injected = inject_firstparty(&mut parsed, &mut ErrorSink::new());
8397        assert!(!injected.is_empty());
8398        for unit in injected {
8399            let pf = parsed
8400                .iter()
8401                .find(|pf| pf.identity_path() == std::path::Path::new(unit.identity_path))
8402                .expect("an injected unit is in `parsed`");
8403            assert_eq!(
8404                pf.unit().span().file,
8405                firstparty_file_id(unit),
8406                "{}",
8407                unit.name
8408            );
8409        }
8410    }
8411
8412    /// A one-file project whose context makes the references `mask` selects.
8413    fn project(mask: u32) -> Vec<ParsedFile> {
8414        let mut uses = String::new();
8415        let mut consumes = String::new();
8416        for (bit, line) in REFS.iter().enumerate() {
8417            if mask & (1 << bit) != 0 {
8418                let into = if line.starts_with("uses") {
8419                    &mut uses
8420                } else {
8421                    &mut consumes
8422                };
8423                into.push_str(line);
8424                into.push('\n');
8425            }
8426        }
8427        let src = format!("context t\n\n{uses}{consumes}\nfn f() -> Int {{ 1 }}\n");
8428        let toks = lexer::tokenize(&src).expect("lexes");
8429        let (unit, _) =
8430            parser::parse_unit_with_warnings_from(&toks, &src, &mut { 0 }).expect("parses");
8431        vec![ParsedFile::synthetic(
8432            PathBuf::from("t.bynk"),
8433            PathBuf::from("t.bynk"),
8434            src,
8435            unit,
8436            UnitKind::Context,
8437        )]
8438    }
8439
8440    /// The units the hand-written injection (before S1, #1945) chose for the
8441    /// references in `mask`, written out from its gates.
8442    fn previous_injection(mask: u32) -> BTreeSet<&'static str> {
8443        let has = |bit: u32| mask & (1 << bit) != 0;
8444        let (bynk, cloudflare) = (has(0), has(1));
8445        let (map, list, string, locale, locale_types) = (has(2), has(3), has(4), has(5), has(6));
8446        let mut out = BTreeSet::new();
8447        let mut add = |cond: bool, name: &'static str| {
8448            if cond {
8449                out.insert(name);
8450            }
8451        };
8452        // Interop I5 (#1972): `bynk.cloudflare` consumes `bynk` for
8453        // `Service`'s `Request`/`Response`, so it brings `bynk` (and so its
8454        // `bynk.locale.types`) with it.
8455        let bynk = bynk || cloudflare;
8456        add(bynk, "bynk");
8457        add(cloudflare, "bynk.cloudflare");
8458        add(map, "bynk.map");
8459        add(list, "bynk.list");
8460        add(locale || string, "bynk.string");
8461        // The `bynk` adapter's own `uses bynk.locale.types`, seen because the
8462        // adapter was injected before the scan ran.
8463        add(locale || locale_types || bynk, "bynk.locale.types");
8464        add(locale, "bynk.locale");
8465        out
8466    }
8467
8468    /// Following the sources' own `uses`/`consumes` injects exactly what the
8469    /// hand-written gates did, for every combination of references.
8470    #[test]
8471    fn the_closure_matches_the_previous_gates_for_every_combination() {
8472        for mask in 0..(1u32 << REFS.len()) {
8473            let mut parsed = project(mask);
8474            let mut errors = ErrorSink::new();
8475            let injected = inject_firstparty(&mut parsed, &mut errors);
8476            assert!(
8477                errors.is_empty(),
8478                "mask {mask:#09b}: a first-party source failed to parse"
8479            );
8480            let names: BTreeSet<&str> = injected.iter().map(|u| u.name).collect();
8481            assert_eq!(names, previous_injection(mask), "mask {mask:#09b}");
8482        }
8483    }
8484
8485    /// Injected units are pushed after the project's own, in ascending
8486    /// `id_block` order — the order the hand-written blocks pushed them in —
8487    /// and the returned entries follow the same order.
8488    #[test]
8489    fn injected_units_are_pushed_in_id_block_order() {
8490        let mut parsed = project((1 << REFS.len()) - 1);
8491        let mut errors = ErrorSink::new();
8492        let injected = inject_firstparty(&mut parsed, &mut errors);
8493        let pushed: Vec<String> = parsed[1..]
8494            .iter()
8495            .map(|pf| pf.unit().name().joined())
8496            .collect();
8497        assert_eq!(
8498            pushed,
8499            [
8500                "bynk",
8501                "bynk.cloudflare",
8502                "bynk.map",
8503                "bynk.list",
8504                "bynk.string",
8505                "bynk.locale.types",
8506                "bynk.locale",
8507            ]
8508        );
8509        let returned: Vec<&str> = injected.iter().map(|u| u.name).collect();
8510        assert_eq!(returned, pushed);
8511        assert!(injected.windows(2).all(|w| w[0].id_block < w[1].id_block));
8512    }
8513
8514    /// A project that references no first-party unit injects nothing.
8515    #[test]
8516    fn nothing_is_injected_unreferenced() {
8517        let mut parsed = project(0);
8518        let injected = inject_firstparty(&mut parsed, &mut ErrorSink::new());
8519        assert!(injected.is_empty());
8520        assert_eq!(parsed.len(), 1);
8521    }
8522
8523    /// The injection names no first-party unit: adding one to the standard
8524    /// library is a `bynk-std` registry entry plus its files (R-6). A per-unit
8525    /// constant reappearing here means a unit is being special-cased again.
8526    #[test]
8527    fn injection_is_registry_driven() {
8528        let src = include_str!("project_model.rs");
8529        let start = src.find("pub fn phase_parse(").expect("phase_parse");
8530        let end = src[start..]
8531            .find("\n/// #1710: for each unit with a file the strict parse rejected")
8532            .map(|rel| start + rel)
8533            .expect("the item after inject_firstparty");
8534        let body = &src[start..end];
8535        for name in firstparty::UNITS.iter().map(|u| u.name) {
8536            assert!(!body.contains(&format!("\"{name}\"")), "names {name}");
8537        }
8538        let per_unit_constant = body
8539            .lines()
8540            .find(|l| l.contains("firstparty::") && (l.contains("_UNIT") || l.contains("_SRC")));
8541        assert_eq!(per_unit_constant, None, "references a per-unit constant");
8542    }
8543
8544    /// A consumer resolves an exported capability's operations against the
8545    /// unit's exported types only, so an operation naming a type the unit
8546    /// declares but does not export types as `()` there, with no diagnostic
8547    /// at the cause (#2634). Every local type an exported capability's
8548    /// signatures name is therefore in an `exports` clause, as is every one a
8549    /// transparent export reached that way carries in a field or variant.
8550    #[test]
8551    fn exported_capability_signatures_name_only_exported_types() {
8552        use bynk_syntax::ast::{
8553            CommonsItem, ExportKind, RecordField, SourceUnit, TypeBody, Visibility,
8554        };
8555        use std::collections::{HashMap, HashSet};
8556        let mut missing = Vec::new();
8557        for unit in firstparty::UNITS
8558            .iter()
8559            .filter(|u| u.kind == firstparty::UnitKind::Adapter)
8560        {
8561            let toks = lexer::tokenize(unit.source).expect("lexes");
8562            let (parsed, _) = parser::parse_unit_with_warnings_from(&toks, unit.source, &mut { 0 })
8563                .expect("parses");
8564            let SourceUnit::Adapter(adapter) = parsed else {
8565                panic!("{} is registered as an adapter", unit.name);
8566            };
8567            let exported = |kind: fn(&ExportKind) -> bool| -> HashSet<&str> {
8568                adapter
8569                    .exports
8570                    .iter()
8571                    .filter(|c| kind(&c.kind))
8572                    .flat_map(|c| c.names.iter().map(|e| e.name.name.as_str()))
8573                    .collect()
8574            };
8575            let types = exported(|k| matches!(k, ExportKind::Type(_)));
8576            let transparent = exported(|k| matches!(k, ExportKind::Type(Visibility::Transparent)));
8577            let capabilities = exported(|k| matches!(k, ExportKind::Capability));
8578            // Each local type with the names its fields and variants carry:
8579            // a consumer reads those through a transparent export, so they
8580            // must resolve there too.
8581            let fields = |fs: &[RecordField], vars: &HashSet<&str>| {
8582                let mut out = Vec::new();
8583                for f in fs {
8584                    super::type_ref_names(&f.type_ref, vars, &mut out);
8585                }
8586                out
8587            };
8588            let local: HashMap<&str, Vec<String>> = adapter
8589                .items
8590                .iter()
8591                .filter_map(|item| match item {
8592                    CommonsItem::Type(t) => {
8593                        let vars = t.type_params.iter().map(|p| p.name.name.as_str()).collect();
8594                        let inner = match &t.body {
8595                            TypeBody::Record(r) => fields(&r.fields, &vars),
8596                            TypeBody::Sum(s) => {
8597                                let mut out = Vec::new();
8598                                for f in s.variants.iter().flat_map(|v| &v.payload) {
8599                                    super::type_ref_names(&f.type_ref, &vars, &mut out);
8600                                }
8601                                for e in &s.embeds {
8602                                    super::type_ref_names(&e.source_type, &vars, &mut out);
8603                                }
8604                                out
8605                            }
8606                            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => Vec::new(),
8607                        };
8608                        Some((t.name.name.as_str(), inner))
8609                    }
8610                    CommonsItem::Event(e) => Some((
8611                        e.name.name.as_str(),
8612                        fields(&e.body.fields, &HashSet::new()),
8613                    )),
8614                    _ => None,
8615                })
8616                .collect();
8617            for item in &adapter.items {
8618                let CommonsItem::Capability(cap) = item else {
8619                    continue;
8620                };
8621                if !capabilities.contains(cap.name.name.as_str()) {
8622                    continue;
8623                }
8624                for op in &cap.ops {
8625                    let vars = op
8626                        .type_params
8627                        .iter()
8628                        .map(|p| p.name.name.as_str())
8629                        .collect();
8630                    let mut names = Vec::new();
8631                    for p in &op.params {
8632                        super::type_ref_names(&p.type_ref, &vars, &mut names);
8633                    }
8634                    super::type_ref_names(&op.return_type, &vars, &mut names);
8635                    // Walk on through transparent exports, keeping the path
8636                    // (`Fetch.send` → `Response` → `Body`) for the message.
8637                    let mut work: Vec<(String, String)> = names
8638                        .into_iter()
8639                        .map(|n| {
8640                            (
8641                                n.clone(),
8642                                format!("`{}.{}` → `{n}`", cap.name.name, op.name.name),
8643                            )
8644                        })
8645                        .collect();
8646                    let mut seen = HashSet::new();
8647                    while let Some((name, path)) = work.pop() {
8648                        let Some(inner) = local.get(name.as_str()) else {
8649                            continue;
8650                        };
8651                        if !seen.insert(name.clone()) {
8652                            continue;
8653                        }
8654                        if !types.contains(name.as_str()) {
8655                            missing.push(format!(
8656                                "{}: {path}, which is not in an `exports` clause",
8657                                unit.name
8658                            ));
8659                        } else if transparent.contains(name.as_str()) {
8660                            work.extend(
8661                                inner.iter().map(|n| (n.clone(), format!("{path} → `{n}`"))),
8662                            );
8663                        }
8664                    }
8665                }
8666            }
8667        }
8668        missing.sort();
8669        missing.dedup();
8670        assert!(missing.is_empty(), "{}", missing.join("\n"));
8671    }
8672}
8673
8674/// #2223: rewrite canonical dependency unit names in `error`'s text to the
8675/// form a person reads (`bynk_project::display_names`).
8676fn display_canonical_names(error: &mut CompileError) {
8677    if error.message.contains('$') {
8678        error.message = bynk_project::display_names(&error.message);
8679    }
8680    for note in &mut error.notes {
8681        if note.contains('$') {
8682            *note = bynk_project::display_names(note);
8683        }
8684    }
8685    for (_, label) in &mut error.labels {
8686        if label.contains('$') {
8687            *label = bynk_project::display_names(label);
8688        }
8689    }
8690}
8691
8692#[cfg(test)]
8693mod metadata_property_tests {
8694    use super::is_metadata_property;
8695
8696    #[test]
8697    fn a_dot_nests_and_each_segment_is_checked() {
8698        assert!(is_metadata_property("category"));
8699        assert!(is_metadata_property("author.name"));
8700        assert!(!is_metadata_property(""));
8701        assert!(!is_metadata_property("a..b"));
8702        assert!(!is_metadata_property(".a"));
8703        assert!(!is_metadata_property("a."));
8704        assert!(!is_metadata_property("$x"));
8705        assert!(!is_metadata_property("a.$x"));
8706        assert!(!is_metadata_property("a\"b"));
8707        assert!(!is_metadata_property(&"x".repeat(513)));
8708    }
8709}
8710
8711/// The deployment units the platform lock checks (#3562): per context under
8712/// `workers`, a `[deploy.workers]` group's members together, the whole program
8713/// under `bundle`.
8714#[cfg(test)]
8715mod lock_unit_tests {
8716    use super::*;
8717    use bynk_project::worker_groups::{WorkerGroup, WorkerGroups};
8718
8719    fn native(platform: Platform, unit: &str) -> BTreeMap<Platform, String> {
8720        BTreeMap::from([(platform, unit.to_string())])
8721    }
8722
8723    fn per_context() -> Vec<(String, BTreeMap<Platform, String>)> {
8724        vec![
8725            (
8726                "a.x".to_string(),
8727                native(Platform::Cloudflare, "bynk.cloudflare"),
8728            ),
8729            ("a.y".to_string(), native(Platform::Node, "bynk.node")),
8730            (
8731                "a.z".to_string(),
8732                native(Platform::Cloudflare, "bynk.cloudflare"),
8733            ),
8734        ]
8735    }
8736
8737    fn group(members: &[&str]) -> WorkerGroups {
8738        WorkerGroups::from([(
8739            "core".to_string(),
8740            WorkerGroup {
8741                contexts: members.iter().map(|m| m.to_string()).collect(),
8742                ..WorkerGroup::default()
8743            },
8744        )])
8745    }
8746
8747    /// Without groups, each context is its own unit, as before.
8748    #[test]
8749    fn workers_without_groups_is_one_unit_per_context() {
8750        let units = lock_units(BuildTarget::Workers, per_context(), &WorkerGroups::new());
8751        assert_eq!(units.len(), 3);
8752        assert!(
8753            units
8754                .iter()
8755                .all(|u| u.group.is_none() && u.members.len() == 1)
8756        );
8757        assert!(units.iter().all(
8758            |u| lock_violation(&u.native, Platform::Cloudflare).is_some()
8759                == (u.members[0] == "a.y")
8760        ));
8761    }
8762
8763    /// A group's members share a Worker, so a Cloudflare-native member and a
8764    /// Node-native one are one unit spanning two platforms.
8765    #[test]
8766    fn a_group_is_one_unit_over_its_members_union() {
8767        let units = lock_units(BuildTarget::Workers, per_context(), &group(&["a.x", "a.y"]));
8768        assert_eq!(units.len(), 2, "{units:?}");
8769        let core = &units[0];
8770        assert_eq!(core.group.as_deref(), Some("core"));
8771        assert_eq!(core.members, ["a.x", "a.y"]);
8772        assert!(matches!(
8773            lock_violation(&core.native, Platform::Cloudflare),
8774            Some(LockViolation::Conflict { .. })
8775        ));
8776        // `a.z`, in no group, stays its own unit, and is fine on Cloudflare.
8777        assert_eq!(units[1].members, ["a.z"]);
8778        assert!(lock_violation(&units[1].native, Platform::Cloudflare).is_none());
8779    }
8780
8781    /// A group whose members need no native platform makes no unit.
8782    #[test]
8783    fn a_group_with_no_native_platforms_is_not_a_unit() {
8784        let units = lock_units(
8785            BuildTarget::Workers,
8786            vec![("a.x".to_string(), BTreeMap::new())],
8787            &group(&["a.x"]),
8788        );
8789        assert!(units.is_empty());
8790    }
8791
8792    /// Under `bundle` the whole program is one unit, owned by the first context,
8793    /// whatever the groups say.
8794    #[test]
8795    fn bundle_is_one_unit_and_ignores_groups() {
8796        let units = lock_units(BuildTarget::Bundle, per_context(), &group(&["a.x", "a.y"]));
8797        assert_eq!(units.len(), 1);
8798        assert_eq!(units[0].group, None);
8799        assert_eq!(units[0].members, ["a.x"]);
8800        assert_eq!(units[0].native.len(), 2);
8801    }
8802}
8803
8804#[cfg(test)]
8805mod cross_caps_first_party_tests {
8806    //! The first-party `Events` skip in `scan_cross_caps` is
8807    //! `firstparty::resolve`, the single definition of bynk's own capabilities
8808    //! (1A.33): a capability flattened from `bynk`, or declared by `bynk`
8809    //! itself, never becomes a compose deps entry.
8810    use super::*;
8811    use bynk_syntax::ast::{CapRef, Ident, ProviderDecl};
8812    use bynk_syntax::span::Span;
8813
8814    fn ident(name: &str) -> Ident {
8815        Ident {
8816            name: name.to_string(),
8817            span: Span::default(),
8818        }
8819    }
8820
8821    fn bare(name: &str) -> CapRef {
8822        CapRef {
8823            context: None,
8824            name: ident(name),
8825            span: Span::default(),
8826        }
8827    }
8828
8829    fn flattened_from(unit: &str, caps: &[&str]) -> HashMap<String, String> {
8830        caps.iter()
8831            .map(|c| (c.to_string(), unit.to_string()))
8832            .collect()
8833    }
8834
8835    fn scan(declaring_unit: &str, flattened: &HashMap<String, String>) -> BTreeMap<String, String> {
8836        let mut out = BTreeMap::new();
8837        scan_cross_caps(
8838            &mut out,
8839            &[bare("Events"), bare("Ledger")],
8840            declaring_unit,
8841            &[],
8842            &HashMap::new(),
8843            flattened,
8844        );
8845        out
8846    }
8847
8848    #[test]
8849    fn a_flattened_bynk_events_is_skipped_and_other_flattened_caps_are_kept() {
8850        let flattened = flattened_from("bynk", &["Events"]);
8851        let mut flattened = flattened;
8852        flattened.insert("Ledger".to_string(), "bank".to_string());
8853        let got = scan("shop", &flattened);
8854        assert_eq!(got.keys().collect::<Vec<_>>(), ["Ledger"]);
8855    }
8856
8857    #[test]
8858    fn an_events_declared_by_bynk_itself_is_skipped_without_being_flattened() {
8859        let mut flattened = HashMap::new();
8860        flattened.insert("Ledger".to_string(), "bank".to_string());
8861        let got = scan("bynk", &flattened);
8862        assert_eq!(got.keys().collect::<Vec<_>>(), ["Ledger"]);
8863    }
8864
8865    #[test]
8866    fn an_events_flattened_from_another_unit_is_not_first_party() {
8867        let flattened = flattened_from("other", &["Events", "Ledger"]);
8868        let got = scan("shop", &flattened);
8869        assert_eq!(got.keys().collect::<Vec<_>>(), ["Events", "Ledger"]);
8870    }
8871
8872    #[test]
8873    fn a_providers_given_skips_a_flattened_bynk_events_too() {
8874        let mut table = UnitTable::default();
8875        table.providers.insert(
8876            "Billing".to_string(),
8877            ProviderDecl {
8878                capability: ident("Billing"),
8879                provider_name: ident("BillingImpl"),
8880                given: vec![bare("Events"), bare("Ledger")],
8881                ops: Vec::new(),
8882                external: false,
8883                documentation: None,
8884                span: Span::default(),
8885                trivia: Default::default(),
8886            },
8887        );
8888        let mut flattened = flattened_from("bynk", &["Events"]);
8889        flattened.insert("Ledger".to_string(), "bank".to_string());
8890        let got = provider_cross_caps(&table, "shop", &[], &HashMap::new(), &flattened);
8891        assert_eq!(got.keys().collect::<Vec<_>>(), ["Ledger"]);
8892    }
8893}