Skip to main content

bynk_check/
check_pipeline.rs

1//! The shared per-unit/per-file resolve-check core, used by both
2//! `bynk-emit`'s `check_unit_files` (`Mode::Build` and `Mode::Analyse`) and
3//! this crate's own [`crate::analysis::analyse_project`].
4//!
5//! P4.1 (#1115), the same `extract, don't duplicate` move as
6//! [`crate::project_model`]: `check_unit_files`'s per-file body is identical
7//! for both modes except for four `record_analyse_types` call sites (the
8//! error-path exits) and the final "Analyse mode always stops here, Build
9//! mode falls through to `certify`+`emit_unit`" branch. This module owns
10//! everything up to (not including) that branch — [`check_file_core`]
11//! returns `Some(TypedCommons)` only on the fully-clean, non-blocked path, so
12//! a caller that wants to emit knows exactly when it may. The four
13//! error-path recordings are unconditional here now (previously gated on
14//! `mode == Mode::Analyse`) — behaviour-preserving for the `Mode::Build`
15//! caller, which never took that branch anyway (`mode == Mode::Analyse`
16//! gated it), and whose `exprs` sink `compile_project`'s `ProjectOutput`
17//! never exposes.
18//!
19//! What stayed in `bynk-emit`: `Mode` itself (meaningless here — this
20//! crate's own entry point has exactly one behaviour), `certify`+`emit_unit`
21//! (real emission), and the decision of *whether* to record the clean-path
22//! types (each caller does that itself with the `Some(TypedCommons)` this
23//! module hands back — `bynk-emit`'s `Mode::Build` caller skips it,
24//! `Mode::Analyse` and this crate's own entry point both call
25//! [`record_analyse_types`]).
26
27use std::collections::{BTreeMap, HashMap, HashSet};
28use std::path::Path;
29use std::sync::Arc;
30
31use crate::checker::{self, TypedCommons, Types};
32use crate::context_checks::{
33    check_context_constraints, check_context_declarations, check_handler_constraints,
34};
35use crate::expr_types::ExprTypeSink;
36use crate::hints::HintSink;
37use crate::index::RefSink;
38use crate::locals::LocalsSink;
39use crate::project_model::{ErrorSink, UnitInfo};
40use crate::requirements::RequirementSink;
41use crate::resolver::{self, MethodTable as ResolverMethodTable, ResolvedCommons};
42use crate::symbols::{ConsumedType, UnitTable, build_cross_context_info, combined_types_for};
43use bynk_project::{ParsedFile, UnitKind};
44use bynk_syntax::ast::{CommonsItem, ExprId, FnName, TypeDecl};
45
46/// Record a file's (possibly partial) expression types into the Analyse-mode
47/// sink. Called at every per-file exit in the check loop so `.`-member
48/// completion and signature help get the receiver's type even when a later
49/// check phase errors for the file (ADR 0094). A no-op-shaped wrapper,
50/// factored out so the four error-path exits (now unconditional, see this
51/// module's own doc comment) and every clean-path caller share one call.
52pub fn record_analyse_types(
53    exprs: &mut ExprTypeSink,
54    source_path: &Path,
55    synthetic: bool,
56    types: &HashMap<ExprId, checker::TypedExpr>,
57) {
58    exprs.enter_file(source_path, synthetic);
59    exprs.record_file(types);
60}
61
62/// The four parallel per-project maps `build_cross_context_info`/
63/// `combined_types_for` need (their own general, map-based signature — see
64/// [`UnitCheckCtx`]'s own doc comment for why the per-file core materialises
65/// them from `unit_info` rather than changing that signature).
66type CrossContextViews = (
67    HashMap<String, UnitTable>,
68    HashMap<String, Vec<String>>,
69    HashMap<String, Vec<String>>,
70    HashMap<String, HashMap<String, String>>,
71);
72
73/// The project's `CrossContextViews`, built at most once and shared by every
74/// context/adapter unit's [`UnitCheckCtx`] (#3229).
75///
76/// The views deep-clone every unit's table, bodies included, so building them
77/// once per unit made a check cost units × project size: quadratic, and about
78/// 85% of a 200-context `bynk check` (clone plus drop). `unit_info` is fixed for
79/// the whole per-unit loop, so every unit's views were identical copies. Create
80/// one cache per project, before the loop, and pass it to every
81/// [`prepare_unit_check_ctx`]; it is filled on first use, so a project with no
82/// context or adapter never pays for the clone.
83#[derive(Default)]
84pub struct CrossContextViewsCache(std::cell::OnceCell<Arc<CrossContextViews>>);
85
86impl CrossContextViewsCache {
87    fn get(&self, unit_info: &BTreeMap<String, UnitInfo>) -> Arc<CrossContextViews> {
88        let views = self
89            .0
90            .get_or_init(|| {
91                let unit_tables = unit_info
92                    .iter()
93                    .map(|(n, i)| (n.clone(), i.table.clone()))
94                    .collect();
95                let unit_uses = unit_info
96                    .iter()
97                    .map(|(n, i)| (n.clone(), i.uses.clone()))
98                    .collect();
99                let unit_consumes = unit_info
100                    .iter()
101                    .map(|(n, i)| (n.clone(), i.consumes.clone()))
102                    .collect();
103                let unit_consumes_aliases = unit_info
104                    .iter()
105                    .map(|(n, i)| (n.clone(), i.aliases.clone()))
106                    .collect();
107                Arc::new((unit_tables, unit_uses, unit_consumes, unit_consumes_aliases))
108            })
109            .clone();
110        // The cache is built for one `unit_info` and reused for the whole
111        // per-unit loop; a different map would silently get the first one's views.
112        // This catches a map of a different size, not a same-sized different one.
113        debug_assert_eq!(
114            views.0.len(),
115            unit_info.len(),
116            "CrossContextViewsCache reused with a unit_info of a different size (it is built for one map)"
117        );
118        views
119    }
120}
121
122/// v0.29.4: `build_cross_context_info` (and its `combined_types_for` helper)
123/// is a general map-based function — the test-emission path calls it with
124/// *synthetic* harness maps, not `unit_info` — so it keeps its parallel-map
125/// signature. The per-file core only has `unit_info`, so this materialises
126/// the four views that one call needs, once per unit ahead of the file loop
127/// — but only for a context/adapter, `build_cross_context_info`'s only
128/// caller. `UnitTable` owns every declaration body in the unit, so for every
129/// other unit kind (including the seven injected first-party commons) this
130/// would otherwise be a whole-project deep clone, performed and discarded,
131/// once per unit.
132pub struct UnitCheckCtx {
133    cross_context_views: Option<Arc<CrossContextViews>>,
134    /// #907: the exact set of type names `emit_context_rebrands` rebrands for
135    /// this unit — names brought in via `uses` of a *commons* specifically
136    /// (not a local declaration, and not a type surfaced via `consumes`,
137    /// which `imported_from_kind` tags `UnitKind::Context` in
138    /// `merge_consumed_exports` and which the emitter never rebrands).
139    pub uses_commons_type_names: HashSet<String>,
140    /// #1710: the declarations recovery skipped in the files this unit can see
141    /// (its own, and the units it `uses` and `consumes`). A reference to one is
142    /// a known name, not an unknown one (#1663's Decision B), so its
143    /// unknown-name echo is not reported. One level of `uses`, matching
144    /// `compose_unit_symbols`. A suite sees its target's skipped names because
145    /// it carries its target's unit name; it is in no unit's `uses`/`consumes`.
146    pub visible_broken_names: Vec<String>,
147    /// #1807: the types this unit's table carries only because an imported
148    /// declaration reaches them (`close_reachable_types`), each with its
149    /// owning commons. Resolvable, never nameable: the naming gate
150    /// (`resolver::check_hidden_type_names`) runs beside the resolver.
151    pub hidden_types: BTreeMap<String, String>,
152    /// #1824: the reached types this unit's own declarations shadow, which
153    /// `shadow_uses` checks the unit's bodies against.
154    pub shadowed: crate::project_model::ShadowedReaches,
155    /// S3 (#1963): the project's `[unstable]` policy, one per project.
156    pub policy: Arc<crate::stability::StabilityPolicy>,
157    /// #2618: the `private` declarations of the commons this unit `uses`,
158    /// which it cannot see; a reference to one is reported as
159    /// `bynk.visibility.private_item` rather than as an unknown name
160    /// (`resolver::rewrite_private_references`).
161    pub private_imports: HashMap<String, resolver::PrivateImport>,
162    /// #3070: the schemas the project's D1 migrations build, which each
163    /// literal D1 statement is prepared against. `None` when the project has no
164    /// migrations or the check is off.
165    pub d1_sql: Option<Arc<crate::d1_sql::D1Sql>>,
166}
167
168/// Build the per-unit prelude [`check_file_core`] shares across every file
169/// in the unit — see [`UnitCheckCtx`]'s own doc comment.
170#[allow(clippy::too_many_arguments)]
171pub fn prepare_unit_check_ctx(
172    name: &str,
173    kind: UnitKind,
174    broken: &crate::project_model::BrokenDeclNames,
175    unit_info: &BTreeMap<String, UnitInfo>,
176    views: &CrossContextViewsCache,
177    combined_types: &HashMap<String, Arc<TypeDecl>>,
178    imported_from_kind: &HashMap<String, UnitKind>,
179    reached_types: &crate::project_model::ReachedTypes,
180    policy: &Arc<crate::stability::StabilityPolicy>,
181) -> UnitCheckCtx {
182    let cross_context_views = if kind == UnitKind::Context || kind == UnitKind::Adapter {
183        Some(views.get(unit_info))
184    } else {
185        None
186    };
187    let uses_commons_type_names: HashSet<String> = imported_from_kind
188        .keys()
189        .filter(|n| {
190            crate::resolver::compute_is_uses_commons_type(imported_from_kind, combined_types, n)
191        })
192        .cloned()
193        .collect();
194    let visible_broken_names: Vec<String> = std::iter::once(name)
195        .chain(
196            unit_info
197                .get(name)
198                .into_iter()
199                .flat_map(|i| i.uses.iter().chain(i.consumes.iter()).map(String::as_str)),
200        )
201        .filter_map(|u| broken.get(u))
202        .flatten()
203        .cloned()
204        .collect();
205    UnitCheckCtx {
206        cross_context_views,
207        uses_commons_type_names,
208        visible_broken_names,
209        hidden_types: reached_types.hidden.clone(),
210        shadowed: reached_types.shadowed.clone(),
211        policy: policy.clone(),
212        private_imports: unit_info
213            .get(name)
214            .map(|info| {
215                resolver::private_imports_in(
216                    &info.table,
217                    info.uses
218                        .iter()
219                        .filter_map(|t| unit_info.get(t).map(|u| (t, &u.table))),
220                )
221            })
222            .unwrap_or_default(),
223        d1_sql: None,
224    }
225}
226
227/// A hasher that `Debug` output can be streamed into, so a value is hashed
228/// without first being rendered to a `String`.
229struct DebugHasher(std::collections::hash_map::DefaultHasher);
230
231impl std::fmt::Write for DebugHasher {
232    fn write_str(&mut self, s: &str) -> std::fmt::Result {
233        use std::hash::Hash;
234        s.hash(&mut self.0);
235        Ok(())
236    }
237}
238
239impl DebugHasher {
240    fn feed(&mut self, label: &str, value: &dyn std::fmt::Debug) {
241        use std::fmt::Write;
242        use std::hash::Hash;
243        label.hash(&mut self.0);
244        let _ = write!(self, "{value:?}");
245    }
246
247    /// A map in key order: `HashMap` iteration order is per-instance, so two
248    /// equal maps must not hash differently.
249    fn feed_map<'a, K: Ord + std::fmt::Debug + 'a, V: std::fmt::Debug + 'a>(
250        &mut self,
251        label: &str,
252        entries: impl IntoIterator<Item = (&'a K, &'a V)>,
253    ) {
254        let mut entries: Vec<_> = entries.into_iter().collect();
255        entries.sort_by(|a, b| a.0.cmp(b.0));
256        self.feed(label, &entries);
257    }
258
259    fn feed_set<'a, T: Ord + std::fmt::Debug + 'a>(
260        &mut self,
261        label: &str,
262        items: impl IntoIterator<Item = &'a T>,
263    ) {
264        let mut items: Vec<_> = items.into_iter().collect();
265        items.sort();
266        self.feed(label, &items);
267    }
268}
269
270/// One type's methods as digests: its name, then instance and static `(name, digest)`.
271type MethodDigests<'a> = (&'a String, Vec<(&'a String, u64)>, Vec<(&'a String, u64)>);
272
273/// The digest of each distinct shared declaration, computed once per analysis
274/// round (#3243). Units share their `uses` targets' declarations as `Arc`s, so
275/// the same few types and functions are part of hundreds of files' digests;
276/// rendering each of them once per file was most of the digest's cost.
277///
278/// Keyed by address, so an address must never be reused for another declaration
279/// while an entry for it exists. That is guaranteed by construction, not by
280/// argument: each entry **holds a clone of the `Arc`** it was computed from, so
281/// the allocation cannot be freed, and its address cannot be handed to a new
282/// declaration, for as long as the cache lives (one refcount bump per distinct
283/// declaration). Even a temporary `Arc` built and dropped mid-round cannot be
284/// followed by a stale hash. The cache is also never kept across rounds: the
285/// memo drops it when the round ends (and asserts it is empty when the next
286/// begins), so it does not keep a round's declarations alive, and the parse
287/// cache's fresh declarations are never confused with an earlier round's.
288#[derive(Default)]
289pub struct DeclDigests {
290    types: HashMap<usize, (Arc<TypeDecl>, u64)>,
291    fns: HashMap<usize, (Arc<bynk_syntax::ast::FnDecl>, u64)>,
292}
293
294impl DeclDigests {
295    /// How many distinct declarations have been hashed.
296    pub(crate) fn len(&self) -> usize {
297        self.types.len() + self.fns.len()
298    }
299}
300
301fn debug_digest(value: &dyn std::fmt::Debug) -> u64 {
302    use std::hash::Hasher;
303    let mut h = DebugHasher(std::collections::hash_map::DefaultHasher::new());
304    h.feed("decl", value);
305    h.0.finish()
306}
307
308impl DeclDigests {
309    fn ty(&mut self, decl: &Arc<TypeDecl>) -> u64 {
310        self.types
311            .entry(Arc::as_ptr(decl) as usize)
312            .or_insert_with(|| (Arc::clone(decl), debug_digest(&**decl)))
313            .1
314    }
315
316    fn func(&mut self, decl: &Arc<bynk_syntax::ast::FnDecl>) -> u64 {
317        self.fns
318            .entry(Arc::as_ptr(decl) as usize)
319            .or_insert_with(|| (Arc::clone(decl), debug_digest(&**decl)))
320            .1
321    }
322
323    /// A map of type declarations as `(name, digest)` in key order.
324    fn type_map<'a>(
325        &mut self,
326        entries: impl IntoIterator<Item = (&'a String, &'a Arc<TypeDecl>)>,
327    ) -> Vec<(&'a String, u64)> {
328        let mut v: Vec<_> = entries.into_iter().map(|(k, d)| (k, self.ty(d))).collect();
329        v.sort_by(|a, b| a.0.cmp(b.0));
330        v
331    }
332
333    /// Each type's instance and static methods as `(name, digest)`, in key order.
334    fn methods<'a>(
335        &mut self,
336        methods: &'a HashMap<String, ResolverMethodTable>,
337    ) -> Vec<MethodDigests<'a>> {
338        crate::symbols::sorted_methods(methods)
339            .into_iter()
340            .map(|(name, instance, statics)| {
341                let instance = instance
342                    .into_iter()
343                    .map(|(n, d)| (n, self.func(d)))
344                    .collect();
345                let statics = statics
346                    .into_iter()
347                    .map(|(n, d)| (n, self.func(d)))
348                    .collect();
349                (name, instance, statics)
350            })
351            .collect()
352    }
353
354    fn fn_map<'a>(
355        &mut self,
356        entries: impl IntoIterator<Item = (&'a String, &'a Arc<bynk_syntax::ast::FnDecl>)>,
357    ) -> Vec<(&'a String, u64)> {
358        let mut v: Vec<_> = entries
359            .into_iter()
360            .map(|(k, d)| (k, self.func(d)))
361            .collect();
362        v.sort_by(|a, b| a.0.cmp(b.0));
363        v
364    }
365}
366
367/// #3243 S2.3b: a digest of **everything [`check_file_core`] reads**, so a file's
368/// checked output can be kept from one language-server round to the next and
369/// replayed when this value is unchanged.
370///
371/// It is a content hash (rendered `Debug`, which includes every span and
372/// `FileId`), not a pointer: the parse cache hands out freshly built decls each
373/// round, so identity does not survive. Span-inclusive on purpose: a diagnostic
374/// may carry a label that points into another file at an offset, and an
375/// upstream edit that moves a declaration moves that offset.
376///
377/// The unit's own table is not rendered: `phase_symbol_tables` builds it from
378/// the unit's own files, whose text is hashed (`unit_files_digest`), so only the
379/// parts filled in from other units are taken
380/// (`UnitTable::cross_unit_facts`).
381///
382/// **Adding an input to `check_file_core` or to [`UnitCheckCtx`] means adding it
383/// here.** [`UnitCheckCtx`] and [`UnitTable`] are destructured exhaustively, so a
384/// new field of either is a compile error until it is classified;
385/// `check_file_core`'s own parameters are the same list as this function's.
386#[allow(clippy::too_many_arguments)]
387pub fn file_check_digest(
388    name: &str,
389    kind: UnitKind,
390    pf: &ParsedFile,
391    unit_files_digest: u64,
392    unit_info: &BTreeMap<String, UnitInfo>,
393    combined_types: &HashMap<String, Arc<TypeDecl>>,
394    combined_fns: &HashMap<String, Arc<bynk_syntax::ast::FnDecl>>,
395    combined_methods: &HashMap<String, ResolverMethodTable>,
396    local_names: &HashSet<String>,
397    local_methods_for_type: &HashMap<String, Vec<bynk_syntax::ast::FnDecl>>,
398    consumed_types: &HashMap<String, ConsumedType>,
399    imported_from: &HashMap<String, String>,
400    ctx: &UnitCheckCtx,
401    decls: &mut DeclDigests,
402) -> u64 {
403    use std::hash::{Hash, Hasher};
404    let mut h = DebugHasher(std::collections::hash_map::DefaultHasher::new());
405    // The file, and the unit's other files: a label may point into a sibling.
406    h.feed(
407        "file",
408        &(
409            pf.identity_path(),
410            pf.abs_path(),
411            pf.kind(),
412            pf.is_synthetic(),
413        ),
414    );
415    pf.source().hash(&mut h.0);
416    h.feed("unit", &(name, kind));
417    unit_files_digest.hash(&mut h.0);
418    // The composed symbol space.
419    h.feed("types", &decls.type_map(combined_types.iter()));
420    h.feed("fns", &decls.fn_map(combined_fns.iter()));
421    let methods = decls.methods(combined_methods);
422    h.feed("methods", &methods);
423    h.feed_set("local_names", local_names.iter());
424    h.feed_map("local_methods", local_methods_for_type.iter());
425    h.feed_map("consumed", consumed_types.iter());
426    h.feed_map("imported_from", imported_from.iter());
427    // What `check_file_core` reads of `unit_info`.
428    if let Some(info) = unit_info.get(name) {
429        h.feed_map("flattened", info.flattened.iter());
430        h.feed("cross_unit_facts", &info.table.cross_unit_facts());
431    }
432    h.feed_map(
433        "assets",
434        crate::assets::compose_unit_assets(name, unit_info).iter(),
435    );
436    h.feed_map(
437        "embeds",
438        crate::embeds::compose_unit_embeds(name, unit_info).iter(),
439    );
440    h.feed_map(
441        "consts",
442        crate::consts::compose_unit_consts(name, unit_info).iter(),
443    );
444    h.feed_map(
445        "shadowed_imports",
446        crate::project_model::shadowed_imports(name, unit_info).iter(),
447    );
448    // The unit's prelude. Exhaustive: a new field must be named here.
449    let UnitCheckCtx {
450        cross_context_views,
451        uses_commons_type_names,
452        visible_broken_names,
453        hidden_types,
454        shadowed,
455        policy,
456        private_imports,
457        d1_sql,
458    } = ctx;
459    if let Some((unit_tables, unit_uses, unit_consumes, unit_consumes_aliases)) =
460        cross_context_views.as_deref()
461    {
462        // `check_file_core` reads the views only through these two derivations.
463        let mut cci = build_cross_context_info(
464            name,
465            unit_consumes,
466            unit_consumes_aliases,
467            unit_uses,
468            unit_tables,
469        );
470        cci.flattened_caps = unit_info[name].flattened.clone();
471        // The consumed type tables are the bulk of it, and are shared `Arc`s:
472        // digest them once per round and render the rest.
473        let consumed = std::mem::take(&mut cci.consumed_types);
474        let mut by_unit: Vec<_> = consumed
475            .iter()
476            .map(|(unit, types)| (unit, decls.type_map(types.iter())))
477            .collect();
478        by_unit.sort_by(|a, b| a.0.cmp(b.0));
479        h.feed("consumed_types", &by_unit);
480        // Maps of maps: its own `Debug` would print hash order.
481        h.feed("cross_context", &crate::oracle::cross_context(&cci));
482        h.feed(
483            "subscriber_types",
484            &decls.type_map(combined_types_for(name, unit_tables, unit_uses).iter()),
485        );
486    }
487    h.feed_set("uses_commons_type_names", uses_commons_type_names.iter());
488    h.feed("visible_broken_names", visible_broken_names);
489    h.feed("hidden_types", hidden_types);
490    h.feed("shadowed", &shadowed.sorted());
491    h.feed("policy", &**policy);
492    h.feed_map("private_imports", private_imports.iter());
493    // `D1Sql`'s `Debug` prints only database names; its content hash covers
494    // every migration the check read the schemas from.
495    h.feed("d1_sql", &d1_sql.as_ref().map(|d| d.digest()));
496    h.0.finish()
497}
498
499/// The clean-path output of [`check_file_core`]: the typed, fully-checked
500/// unit plus the per-file cross-context info that produced it — a
501/// `Mode::Build` caller needs both to reach `certify`+`emit_unit` (`emit_unit`
502/// takes `cross_context_for_file` as its own argument, so this avoids making
503/// the caller recompute it from `ctx`/`unit_info` a second time).
504pub struct FileCheckResult {
505    pub typed: TypedCommons,
506    pub cross_context: resolver::CrossContextInfo,
507}
508
509/// The shared resolve+check+context-checks core for one file, factored out
510/// of `check_unit_files` (see this module's own doc comment). Returns
511/// `Some(FileCheckResult)` only on the fully-clean, non-blocked path — the
512/// signal a `Mode::Build` caller uses to know it may proceed to
513/// `certify`+`emit_unit`. Every error/blocked exit records best-effort
514/// partial types unconditionally (see [`record_analyse_types`]) and returns
515/// `None`.
516#[allow(clippy::too_many_arguments)]
517pub fn check_file_core(
518    name: &str,
519    kind: UnitKind,
520    pf: &ParsedFile,
521    unit_info: &BTreeMap<String, UnitInfo>,
522    combined_types: &HashMap<String, Arc<TypeDecl>>,
523    combined_fns: &HashMap<String, Arc<bynk_syntax::ast::FnDecl>>,
524    combined_methods: &HashMap<String, ResolverMethodTable>,
525    local_names: &HashSet<String>,
526    local_methods_for_type: &HashMap<String, Vec<bynk_syntax::ast::FnDecl>>,
527    consumed_types: &HashMap<String, ConsumedType>,
528    imported_from: &HashMap<String, String>,
529    ctx: &UnitCheckCtx,
530    errors: &mut ErrorSink,
531    refs: &mut RefSink,
532    hints: &mut HintSink,
533    locals: &mut LocalsSink,
534    exprs: &mut ExprTypeSink,
535    requirements: &mut RequirementSink,
536    tys: &Arc<Types>,
537) -> Option<FileCheckResult> {
538    let mut emit_items: Vec<CommonsItem> = Vec::new();
539    let types_in_this_file: HashSet<String> = pf
540        .items()
541        .iter()
542        .filter_map(|it| match it {
543            CommonsItem::Type(t) => Some(t.name.name.clone()),
544            // Events track, slice 0 (spine #936): an `event` shares the
545            // `types` namespace, so a multi-file context's method dispatch
546            // treats its name the same as a `type`'s.
547            CommonsItem::Event(e) => Some(e.name.name.clone()),
548            _ => None,
549        })
550        .collect();
551    for item in pf.items() {
552        match item {
553            CommonsItem::Type(t) => {
554                emit_items.push(CommonsItem::Type(t.clone()));
555            }
556            CommonsItem::Fn(f) => match &f.name {
557                FnName::Free(_) => emit_items.push(CommonsItem::Fn(f.clone())),
558                FnName::Method { type_name, .. } => {
559                    if types_in_this_file.contains(&type_name.name) {
560                        emit_items.push(CommonsItem::Fn(f.clone()));
561                    }
562                }
563            },
564            CommonsItem::Capability(c) => {
565                emit_items.push(CommonsItem::Capability(c.clone()));
566            }
567            CommonsItem::Provider(p) => {
568                emit_items.push(CommonsItem::Provider(p.clone()));
569            }
570            CommonsItem::Service(s) => {
571                emit_items.push(CommonsItem::Service(s.clone()));
572            }
573            CommonsItem::Agent(a) => {
574                emit_items.push(CommonsItem::Agent(a.clone()));
575            }
576            CommonsItem::Actor(a) => {
577                // Actors emit no standalone TS, but are carried so the
578                // emitter can read their schemes for the verification seam.
579                emit_items.push(CommonsItem::Actor(a.clone()));
580            }
581            CommonsItem::Messages(m) => {
582                emit_items.push(CommonsItem::Messages(m.clone()));
583            }
584            CommonsItem::Event(e) => {
585                emit_items.push(CommonsItem::Event(e.clone()));
586            }
587            CommonsItem::Asset(a) => {
588                emit_items.push(CommonsItem::Asset(a.clone()));
589            }
590            CommonsItem::Embed(e) => {
591                emit_items.push(CommonsItem::Embed(e.clone()));
592            }
593            CommonsItem::Const(c) => {
594                emit_items.push(CommonsItem::Const(c.clone()));
595            }
596        }
597    }
598    for type_name in &types_in_this_file {
599        if let Some(methods) = local_methods_for_type.get(type_name) {
600            for m in methods {
601                let already = emit_items.iter().any(|it| match it {
602                    CommonsItem::Fn(existing) => match &existing.name {
603                        FnName::Method {
604                            type_name: t,
605                            method_name: n,
606                        } => match &m.name {
607                            FnName::Method {
608                                type_name: t2,
609                                method_name: n2,
610                            } => t.name == t2.name && n.name == n2.name,
611                            _ => false,
612                        },
613                        _ => false,
614                    },
615                    _ => false,
616                });
617                if !already {
618                    emit_items.push(CommonsItem::Fn(m.clone()));
619                }
620            }
621        }
622    }
623
624    // Synthesize a "Commons-shaped" view of this file's items so we can
625    // drive the existing resolver/checker without duplication.
626    let synthetic_commons = pf.as_synthetic_commons(emit_items);
627
628    // Cross-context info (v0.6) for contexts: consumed contexts, aliases,
629    // services, and types. Computed once below; reused for the resolver,
630    // checker, and (in `bynk-emit`) the emitter. v0.18: adapters get it too,
631    // so an external provider's `given` resolves against the adapter's
632    // flattened consumed capabilities (spec §4.5).
633    let cross_context_for_file =
634        if let Some((unit_tables, unit_uses, unit_consumes, unit_consumes_aliases)) =
635            ctx.cross_context_views.as_deref()
636        {
637            let mut cci = build_cross_context_info(
638                name,
639                unit_consumes,
640                unit_consumes_aliases,
641                unit_uses,
642                unit_tables,
643            );
644            cci.flattened_caps = unit_info[name].flattened.clone();
645            cci
646        } else {
647            resolver::CrossContextInfo::default()
648        };
649
650    // Events slice 3a (#972): this unit's own local + direct-`uses` types
651    // (deliberately narrower than `combined_types`, which also merges
652    // `consumes`) — the same view `emit_consumed_context_helpers` (#973)
653    // builds for a *subscriber* regenerating this unit's own event codecs
654    // cross-context. `check_context_declarations` uses it to validate an
655    // event field default is constructible in that narrower view, not just
656    // this unit's own wider one.
657    let subscriber_visible_types: HashMap<String, Arc<TypeDecl>> =
658        if let Some((unit_tables, unit_uses, _, _)) = ctx.cross_context_views.as_deref() {
659            combined_types_for(name, unit_tables, unit_uses)
660        } else {
661            HashMap::new()
662        };
663
664    // `ResolvedCommons::new` derives `local_type_names`/`event_type_names`
665    // from this unit's own pre-merge table (`unit_info[name].table`), not
666    // `combined_types` (already local+uses+consumes merged) — same
667    // distinction the caller's `local_names` exists for. `Events.emit[E]`
668    // additionally needs "is this specifically an event" on top of
669    // owner-only emission (an ordinary local type must not pass as an emit
670    // target just because it's locally declared), hence the separate
671    // `events` table. Both are empty for a unit absent from `unit_info`.
672    let empty_types = HashMap::new();
673    let empty_events = HashMap::new();
674    let local_table = unit_info.get(name).map(|i| &i.table);
675    let local_types = local_table.map(|t| &t.types).unwrap_or(&empty_types);
676    let local_events = local_table.map(|t| &t.events).unwrap_or(&empty_events);
677    let empty_fns = HashMap::new();
678    let local_fns = local_table.map(|t| &t.fns).unwrap_or(&empty_fns);
679
680    let resolved = ResolvedCommons::new(
681        Arc::new(synthetic_commons),
682        combined_types.clone(),
683        local_types,
684        combined_fns.clone(),
685        combined_methods.clone(),
686        HashMap::new(),
687        local_events,
688        cross_context_for_file.clone(),
689        // ADR 0116 D6: provenance for the `bynk.list` deprecation lint.
690        imported_from.clone(),
691        kind == UnitKind::Context,
692        ctx.uses_commons_type_names.clone(),
693    )
694    .with_local_fns(local_fns)
695    // #1883, slice 1a: this unit's assets plus its `uses`d commons' ([DECISION G]).
696    .with_assets(crate::assets::compose_unit_assets(name, unit_info))
697    // #2387, slice 1: likewise this unit's embeds and its `uses`d commons'.
698    .with_embeds(crate::embeds::compose_unit_embeds(name, unit_info))
699    // #2617: likewise this unit's constants and its `uses`d commons'.
700    .with_consts(crate::consts::compose_unit_consts(name, unit_info))
701    // #1925: imports hidden behind a local declaration of another kind.
702    .with_shadowed_imports(crate::project_model::shadowed_imports(name, unit_info))
703    // S3 (#1963): which names in scope are a first-party extensible enum,
704    // decided here, where the unit's full provenance is known.
705    .with_extensible_enums(extensible_names(imported_from))
706    // #3536: the first-party types this unit's braces leave out.
707    .with_unselected_types(unit_info[name].table.unselected_names())
708    // S3 (#1963): the project's policy, and this unit's blocked imports. A
709    // first-party unit's own bodies are the library's business, never the
710    // project's opt-in, so they check under a policy that blocks nothing.
711    .with_stability(if pf.is_synthetic() {
712        crate::stability::UnitStability {
713            policy: Arc::new(crate::stability::StabilityPolicy::permissive()),
714            blocked_imports: HashMap::new(),
715        }
716    } else {
717        crate::stability::UnitStability {
718            policy: ctx.policy.clone(),
719            blocked_imports: ctx.policy.blocked_imports(imported_from),
720        }
721    });
722    refs.enter_file(&pf.identity_path(), name, pf.is_synthetic());
723    // v0.27: synthetic and test/integration files record no hints — neither
724    // surfaces in an editor (the `assemble_index` rule).
725    hints.enter_file(
726        &pf.identity_path(),
727        pf.is_synthetic() || matches!(pf.kind(), UnitKind::Test | UnitKind::Integration),
728    );
729    // v0.31: locals serve completion/navigation in test files too — only
730    // synthetic (toolchain-injected) files are muted.
731    locals.enter_file(&pf.identity_path(), pf.is_synthetic());
732    // v0.99: capability requirements follow the inlay-hint muting rule —
733    // synthetic and test/integration files surface none in an editor.
734    requirements.enter_file(
735        &pf.identity_path(),
736        pf.is_synthetic() || matches!(pf.kind(), UnitKind::Test | UnitKind::Integration),
737    );
738    // #1663 (Decision A): a resolve error no longer stops the file before the
739    // checker. Every declaration is still checked; the checker's diagnostics
740    // in a declaration the resolver rejected are its echoes and are dropped
741    // (`without_resolve_echoes`), and the file still fails here.
742    let mut resolve_errors = resolver::resolve_file_record(&resolved, refs).err();
743    // #1807: a hidden type written in this file is an unknown type, and is a
744    // resolve error like any other (Decision A drops the checker's echoes).
745    let hidden_named =
746        resolver::check_hidden_type_names(&resolved.commons.items, &ctx.hidden_types);
747    if !hidden_named.is_empty() {
748        resolve_errors
749            .get_or_insert_with(Vec::new)
750            .extend(hidden_named);
751    }
752    // #1927: a `uses`-imported type a local value hides may not be written
753    // either, and its errors are resolve errors the same way.
754    let shadowed_named = resolver::check_shadowed_type_names(
755        &resolved.commons.items,
756        &resolved.shadowed_imports,
757        &resolved.types,
758    );
759    if !shadowed_named.is_empty() {
760        resolve_errors
761            .get_or_insert_with(Vec::new)
762            .extend(shadowed_named);
763    }
764    check_unselected_imports(&resolved, pf, &unit_info[name], errors);
765    let item_spans: Vec<bynk_syntax::span::Span> =
766        resolved.commons.items.iter().map(|i| i.span()).collect();
767    // The unit's own span is this file's, even when it has no items of its own
768    // (only methods on a sibling file's type, or only `uses`).
769    let own_file = resolved.commons.span.file;
770    // The unit's own span can carry no file identity; an item's always does.
771    requirements.set_file_id(
772        item_spans
773            .iter()
774            .map(|sp| sp.file)
775            .find(|f| *f != bynk_syntax::span::FileId::UNKNOWN)
776            .unwrap_or(own_file),
777    );
778    let rc = checker::check_record_in(resolved, tys, refs, hints, locals, requirements);
779    if let Some(resolve_errors) = &resolve_errors {
780        // #1710: a reference to a declaration recovery skipped (here or in a
781        // file this unit can see) is a known name; its echo isn't reported. It
782        // still counts as a resolve error below (Decision A).
783        let (shown, _hidden) =
784            resolver::split_broken_decl_echoes(resolve_errors.clone(), &ctx.visible_broken_names);
785        errors.extend_for(
786            Some(&pf.identity_path()),
787            resolver::rewrite_private_references(shown, &ctx.private_imports),
788        );
789    }
790    // Every diagnostic past the resolver goes out through this: the checker's
791    // errors and warnings, and the declaration stages' (`ours`, below).
792    // Decision A drops the checker's follow-ons inside a declaration the
793    // resolver rejected; #1710 then drops echoes of a declaration recovery
794    // skipped (a method, a capability, an actor, a consumed context's service)
795    // that this unit can see. The checker reports those under its own codes,
796    // in any unit kind, so the split runs here, not only in the stages.
797    let unechoed = |errs: Vec<bynk_syntax::CompileError>| {
798        let errs = match &resolve_errors {
799            Some(r) => resolver::without_resolve_echoes(errs, r, &item_spans),
800            None => errs,
801        };
802        resolver::rewrite_private_references(
803            resolver::split_broken_decl_echoes(errs, &ctx.visible_broken_names).0,
804            &ctx.private_imports,
805        )
806    };
807    // #1663: the declaration stages walk the whole unit's handlers, so a file's
808    // pass also meets another file's faults — and attributes them to this
809    // file, at a position in the wrong source. That file's own pass reports
810    // them; here, keep only this file's diagnostics (or unlocated ones), and
811    // decide whether a stage failed this file from those alone.
812    let ours = |errs: Vec<bynk_syntax::CompileError>| -> Vec<bynk_syntax::CompileError> {
813        unechoed(
814            errs.into_iter()
815                .filter(|e| e.span.file == own_file || e.span == bynk_syntax::span::Span::default())
816                .collect(),
817        )
818    };
819    // #1663: whether this file has already failed (a resolve or type error).
820    // The later stages still check its other declarations; the file returns
821    // no result at the end.
822    let mut failed = resolve_errors.is_some();
823    let typed = match rc.result {
824        Ok(t) => {
825            // v0.89 (ADR 0117): a unit that checks clean may still carry
826            // non-failing warnings — push them into the (severity-aware)
827            // sink, where they are classified as warnings and never gate.
828            if !t.warnings.is_empty() {
829                errors.extend_for(Some(&pf.identity_path()), unechoed(t.warnings.clone()));
830            }
831            t
832        }
833        Err(errs) => {
834            errors.extend_for(Some(&pf.identity_path()), unechoed(errs));
835            // #1663 (Decision A): a type error in one declaration must not
836            // hide the next stage's checks of the others (a service handler's
837            // body is typed in `check_context_declarations`).
838            failed = true;
839            // ADR 0094: the program as checked so far carries the
840            // best-effort types of every expression that did check. It is
841            // not recorded here: checking goes on, and whichever exit below
842            // the file reaches records it once, with the handler bodies
843            // `check_context_declarations` types in the meantime.
844            rc.typed_despite_errors?
845        }
846    };
847
848    // Run the context-specific checks: forbidden construction, private-type
849    // references.
850    if kind == UnitKind::Context {
851        let context_check_errs = ours(check_context_constraints(
852            &typed,
853            consumed_types,
854            local_names,
855            tys,
856        ));
857        if !context_check_errs.is_empty() {
858            errors.extend_for(Some(&pf.identity_path()), context_check_errs);
859            record_analyse_types(
860                exprs,
861                &pf.identity_path(),
862                pf.is_synthetic(),
863                &typed.expr_types,
864            );
865            return None;
866        }
867    }
868
869    // v0.5: check capability/provider/service/agent declarations. v0.18:
870    // adapters run these too — an external provider's `given` resolves
871    // through the same path as a bodied provider's (the service/agent
872    // checks are vacuous for adapters, which have none).
873    let mut typed = typed;
874    let unit_table_owned = unit_info.get(name).map(|i| i.table.clone());
875    if (kind == UnitKind::Context || kind == UnitKind::Adapter)
876        && let Some(table) = unit_table_owned.as_ref()
877    {
878        let decl_errs = ours(check_context_declarations(
879            &mut typed,
880            table,
881            &cross_context_for_file,
882            kind == UnitKind::Context,
883            &ctx.uses_commons_type_names,
884            &subscriber_visible_types,
885            refs,
886            hints,
887            locals,
888            requirements,
889            tys,
890        ));
891        if !decl_errs.is_empty() {
892            // ADR 0117: a warning-severity declaration diagnostic (e.g. the
893            // `@indexed` hygiene hints) must not block emission — only an
894            // error does. Partition first, then gate on error severity
895            // alone.
896            let blocks_emission = decl_errs.iter().any(|e| {
897                matches!(
898                    bynk_syntax::Severity::for_error(e),
899                    bynk_syntax::Severity::Error
900                )
901            });
902            errors.extend_for(Some(&pf.identity_path()), decl_errs);
903            if blocks_emission {
904                // ADR 0094: handler bodies are typed here — surface their
905                // best-effort types even when a declaration check (e.g. a
906                // service/agent wiring error) fails for the file.
907                record_analyse_types(
908                    exprs,
909                    &pf.identity_path(),
910                    pf.is_synthetic(),
911                    &typed.expr_types,
912                );
913                return None;
914            }
915            // Warnings only: the declarations are valid — fall through.
916        }
917    }
918
919    // #1700: the context constraints again, over the handler and provider
920    // bodies `check_context_declarations` has just typed.
921    if kind == UnitKind::Context {
922        let handler_errs = ours(check_handler_constraints(
923            &typed,
924            consumed_types,
925            local_names,
926            tys,
927        ));
928        if !handler_errs.is_empty() {
929            errors.extend_for(Some(&pf.identity_path()), handler_errs);
930            record_analyse_types(
931                exprs,
932                &pf.identity_path(),
933                pf.is_synthetic(),
934                &typed.expr_types,
935            );
936            return None;
937        }
938    }
939
940    // #1824: a value crossing between this unit's code and an imported
941    // position that names a type the unit shadows. Last, over every body the
942    // stages above have typed.
943    let shadow_errs = ours(crate::shadow_uses::check_shadowed_uses(
944        &typed,
945        &crate::shadow_uses::ShadowScope {
946            unit: name,
947            shadowed: &ctx.shadowed,
948            combined_types,
949            combined_fns,
950            combined_methods,
951            imported_from,
952        },
953    ));
954    if !shadow_errs.is_empty() {
955        errors.extend_for(Some(&pf.identity_path()), shadow_errs);
956        failed = true;
957    }
958
959    // #3070: each literal D1 statement of this context, prepared against the
960    // schema its binding's migrations build.
961    if kind == UnitKind::Context
962        && let (Some(d1_sql), Some(table)) = (&ctx.d1_sql, unit_table_owned.as_ref())
963    {
964        let sql_errs = ours(d1_sql.check_unit(name, table, &typed.callees, Some(pf.source())));
965        if !sql_errs.is_empty() {
966            errors.extend_for(Some(&pf.identity_path()), sql_errs);
967            failed = true;
968        }
969    }
970
971    // #1663: every stage has now checked past the earlier errors; the file
972    // still fails on them.
973    if failed {
974        record_analyse_types(
975            exprs,
976            &pf.identity_path(),
977            pf.is_synthetic(),
978            &typed.expr_types,
979        );
980        return None;
981    }
982    Some(FileCheckResult {
983        typed,
984        cross_context: cross_context_for_file,
985    })
986}
987
988/// S3 (#1963): which of the names in scope are a first-party extensible enum.
989fn extensible_names(imported_from: &HashMap<String, String>) -> HashSet<String> {
990    imported_from
991        .iter()
992        .filter(|(n, unit)| crate::firstparty::is_extensible(unit, n))
993        .map(|(n, _)| n.clone())
994        .collect()
995}
996
997/// #3536: naming a type, capability or service this file's own `consumes` does
998/// not bring in is an error, with a fix that edits this file. The standard library's own units are not the user's code to
999/// migrate.
1000fn check_unselected_imports(
1001    resolved: &ResolvedCommons,
1002    pf: &ParsedFile,
1003    info: &crate::project_model::UnitInfo,
1004    errors: &mut ErrorSink,
1005) {
1006    if crate::firstparty::is_first_party_unit(&resolved.commons.name) {
1007        return;
1008    }
1009    let consumed: std::collections::BTreeSet<String> = info.consumes.iter().cloned().collect();
1010    let file = resolver::FileConsumes {
1011        consumed: &consumed,
1012        aliases: &info.table.consumed_type_aliases,
1013        clauses: pf.consumes(),
1014        insert_at: new_consumes_position(pf),
1015    };
1016    errors.extend_for(
1017        Some(&pf.identity_path()),
1018        resolver::check_unselected_type_names(&resolved.commons.items, resolved, &file),
1019    );
1020    errors.extend_for(
1021        Some(&pf.identity_path()),
1022        resolver::check_unselected_capabilities(&resolved.commons.items, &info.flattened, &file),
1023    );
1024    let prefixes: std::collections::BTreeMap<String, String> = info
1025        .consumes
1026        .iter()
1027        .map(|u| (u.clone(), u.clone()))
1028        .chain(info.aliases.iter().map(|(a, u)| (a.clone(), u.clone())))
1029        .collect();
1030    errors.extend_for(
1031        Some(&pf.identity_path()),
1032        resolver::check_unconsumed_unit_calls(&resolved.commons.items, &prefixes, &file),
1033    );
1034}
1035
1036/// Where a `consumes` line the file lacks is inserted ([`resolver::new_consumes_position`]).
1037fn new_consumes_position(pf: &ParsedFile) -> Option<(usize, String)> {
1038    let last = pf
1039        .uses()
1040        .iter()
1041        .map(|u| u.span.end)
1042        .chain(pf.consumes().iter().map(|c| c.span.end))
1043        .max();
1044    use bynk_syntax::ast::{CommonsForm, SourceUnit};
1045    let (name_end, form) = match pf.unit() {
1046        SourceUnit::Context(c) => (c.name.span.end, c.form),
1047        SourceUnit::Adapter(a) => (a.name.span.end, a.form),
1048        _ => return None,
1049    };
1050    resolver::new_consumes_position(pf.source(), last, name_end, form == CommonsForm::Brace)
1051}
1052
1053#[cfg(test)]
1054mod tests {
1055    use super::{Arc, BTreeMap, CrossContextViewsCache, DeclDigests};
1056    use crate::testkit::analyse;
1057
1058    /// #3243 S2.4a: the digest cache is keyed by address, so it must keep every
1059    /// `Arc` it hashed alive: a dropped declaration's address could otherwise be
1060    /// reused by a new one and be handed the old hash.
1061    #[test]
1062    fn the_declaration_digests_keep_what_they_hashed_alive() {
1063        let source = "commons shapes\n\ntype Id = String where NonEmpty\n";
1064        let tokens = bynk_syntax::lexer::tokenize(source).expect("lexes");
1065        let commons = bynk_syntax::parser::parse(&tokens, source).expect("parses");
1066        let decl = commons
1067            .items
1068            .iter()
1069            .find_map(|i| match i {
1070                bynk_syntax::ast::CommonsItem::Type(t) => Some(t.clone()),
1071                _ => None,
1072            })
1073            .expect("a type");
1074        let temporary = Arc::new(decl);
1075        let weak = Arc::downgrade(&temporary);
1076        let mut digests = DeclDigests::default();
1077        let first = digests.ty(&temporary);
1078        // The caller's handle goes away, as a temporary `Arc` built mid-round would.
1079        drop(temporary);
1080        assert!(
1081            weak.upgrade().is_some(),
1082            "the cache must still hold the declaration its address is keyed by"
1083        );
1084        assert_eq!(digests.len(), 1);
1085        // Only dropping the cache (the end of the round) releases it.
1086        drop(digests);
1087        assert!(weak.upgrade().is_none());
1088        let _ = first;
1089    }
1090
1091    /// #3229: every unit shares one set of views; a per-unit rebuild deep-cloned
1092    /// the whole project once per context, which made a check quadratic.
1093    #[test]
1094    fn the_cross_context_views_are_built_once_and_shared() {
1095        let cache = CrossContextViewsCache::default();
1096        let unit_info = BTreeMap::new();
1097        let first = cache.get(&unit_info);
1098        let second = cache.get(&unit_info);
1099        assert!(Arc::ptr_eq(&first, &second));
1100    }
1101
1102    const PAYMENT: &str = "context shop.payment\n\nservice charge {\n  on call(n: Int) -> Effect[Int] by Caller {\n    Effect.pure(n)\n  }\n}\n";
1103
1104    fn consumer(name: &str, arg: &str) -> String {
1105        format!(
1106            "context shop.{name}\n\nconsumes shop.payment\n\nservice place {{\n  on call() -> Effect[Int] by Caller {{\n    let n <- shop.payment.charge({arg})\n    Effect.pure(n)\n  }}\n}}\n"
1107        )
1108    }
1109
1110    /// #3239 review: every context resolves its `consumes` through the one shared
1111    /// set of views, so two consumers of the same context both check, and a
1112    /// mistake in one is reported without disturbing the other.
1113    #[test]
1114    fn two_consumers_of_one_context_share_the_views_without_interference() {
1115        let ok = analyse(&[
1116            ("shop/payment.bynk", PAYMENT),
1117            ("shop/orders.bynk", &consumer("orders", "1")),
1118            ("shop/billing.bynk", &consumer("billing", "2")),
1119        ]);
1120        ok.assert_clean();
1121
1122        let broken = analyse(&[
1123            ("shop/payment.bynk", PAYMENT),
1124            ("shop/orders.bynk", &consumer("orders", "1")),
1125            ("shop/billing.bynk", &consumer("billing", "\"two\"")),
1126        ]);
1127        let errors = &broken.analysis.errors;
1128        assert!(
1129            !errors.is_empty(),
1130            "a wrongly typed cross-context call in one consumer must be reported"
1131        );
1132        // Every error is in the consumer that made the call; the other consumer
1133        // and the context they share stay clean.
1134        assert!(
1135            errors.iter().all(|e| e
1136                .source_path
1137                .as_deref()
1138                .is_some_and(|p| p.ends_with("billing.bynk"))),
1139            "errors must be attributed to billing.bynk only: {:?}",
1140            errors.iter().map(|e| &e.source_path).collect::<Vec<_>>()
1141        );
1142    }
1143
1144    #[test]
1145    fn a_file_with_a_type_error_still_records_its_other_expression_types() {
1146        // ADR 0094: completion and signature help need a receiver's type even
1147        // when another declaration in the same file fails to check.
1148        let a = analyse(&[(
1149            "demo.bynk",
1150            "commons demo\n\nfn good(s: String) -> Int { s.length() }\n\nfn bad() -> Int { \"x\" }\n",
1151        )]);
1152        assert!(
1153            !a.error_categories().is_empty(),
1154            "the fixture must fail to check"
1155        );
1156        assert_eq!(a.type_at("demo.bynk", "s.length()"), "Int");
1157    }
1158
1159    #[test]
1160    fn a_call_to_a_declaration_that_failed_to_parse_is_not_an_unknown_name() {
1161        // #1710: a broken declaration stays a known name, so its callers report
1162        // nothing extra; only the parse error itself is reported.
1163        let a = analyse(&[(
1164            "demo.bynk",
1165            "commons demo\n\nfn broken() -> Int { 1 + }\n\nfn user() -> Int { broken() }\n",
1166        )]);
1167        assert!(
1168            !a.error_categories().is_empty(),
1169            "the parse error is reported"
1170        );
1171        assert!(
1172            !a.categories().contains(&"bynk.resolve.unknown_function"),
1173            "a broken declaration's caller must not report it unknown:\n{}",
1174            a.render()
1175        );
1176    }
1177
1178    #[test]
1179    fn a_clean_file_s_types_are_recorded_on_the_clean_path() {
1180        let a = analyse(&[(
1181            "demo.bynk",
1182            "commons demo\n\nfn f(s: String) -> Int { s.length() }\n",
1183        )]);
1184        a.assert_clean();
1185        assert_eq!(a.type_at("demo.bynk", "s.length()"), "Int");
1186    }
1187}