Skip to main content

bynk_check/
analysis.rs

1//! The project-level analysis entry point (P4.1, #1115): discovery
2//! (`bynk-project`) → parse → resolve → check, returning the `bynk-ide`-facing
3//! analogue of `bynk-emit`'s `ProjectAnalysis` — without ever emitting.
4//!
5//! `bynk-ide` is repointed at [`analyse_project`] as of P4.2 (#1122) —
6//! `bynk_driver::project::analyse_project_with` was no longer reachable from
7//! `bynk-ide` from that point on (it had no `bynk-emit` dependency left).
8//! This entry point is what every real caller uses; #1541 deleted
9//! `analyse_project_with` and its single-tree wrapper `analyse_project`
10//! outright once nothing but `bynk-check/tests/differential_analysis.rs`'s
11//! own comparison still called them — that fixture is now a golden test of
12//! this entry point alone, not a differential against the retired one.
13//!
14//! ## The residual gap
15//!
16//! This entry point was diagnostically faithful to `bynk-emit`'s
17//! `run_checks`'s `Mode::Analyse` arm **minus seven categories** of
18//! whole-project checking at P4.2 (recorded on the tracking issue's own
19//! scope-correction comments, not silently assumed). Categories 2, 3, 4 and 6
20//! closed at P5.0/P5.1/P5.2 (`design/tracks/semantics-in-the-checker.md` §6)
21//! — [`crate::project_model::phase_messages_bundles`]/
22//! [`crate::project_model::phase_locale_bundle_ambiguity`]/
23//! [`crate::project_model::phase_event_subscriptions`]/
24//! [`crate::project_model::phase_function_type_boundaries`] are now called
25//! from [`analyse_project`] at the same points `run_checks` calls them.
26//! Categories 1 and 5 closed at P5.3, structurally rather than observably —
27//! both were already unreachable from the editor before P4.2 even shipped,
28//! so porting them changed nothing observable. Category 7 closed at P5.4, the
29//! last of the seven and the one this doc comment's own author flagged as
30//! needing more care (§9 of the design doc) — see below. All seven
31//! categories are now closed:
32//!
33//! 1. ~~Schema-registry reconciliation~~ — **closed at P5.3**.
34//!    [`crate::schema_registry::reconcile`] is now called from
35//!    [`analyse_project`], right after [`crate::project_model::phase_validate_providers`]
36//!    (the same relative point `run_checks` calls it). Unreachable on this
37//!    path until #2081, which gave [`analyse_project`] a `schema_lock`
38//!    argument: the LSP pre-reads `bynk.schema.lock` and passes it in, so a
39//!    non-additive change now reaches the editor as it reaches `bynk check`.
40//! 2. ~~`messages` bundle validation~~ — **closed at P5.0**, see above.
41//! 3. ~~Locale bundle ambiguity~~ — **closed at P5.0**, see above.
42//! 4. ~~Event-subscription validation~~ — **closed at P5.1**, see above.
43//! 5. ~~Platform-lock enforcement~~ — **closed at P5.3**.
44//!    [`crate::project_model::phase_platform_lock`] is now called from
45//!    [`analyse_project`], right after the per-unit compose/check loop (the
46//!    same relative point `run_checks` calls it, gated the same way on a
47//!    clean error sink so far). Still unreachable on this path, for the same
48//!    reason as before the relocation: `analyse_project` hardcodes
49//!    `Platform::default()` (Cloudflare) and `BuildTarget::Bundle`, and
50//!    `bynk.cloudflare` is the only platform-native unit that exists
51//!    (`firstparty::platform_of`) — so `lock_violation` can never find a
52//!    native platform disagreeing with the selected one, for any project, on
53//!    this path. No fixture can observe this category regressing (or
54//!    improving) because it never fired through this path to begin with, both
55//!    before and after this relocation.
56//! 6. ~~Function-type-boundary checks~~ — **closed at P5.2**. Formerly reached,
57//!    in `bynk-emit`, only through `phase_group`'s optional boundary-check
58//!    hook (`Some` from `run_checks`, `None` here); the hook is gone —
59//!    [`crate::project_model::phase_group`] now calls
60//!    [`crate::project_model::phase_function_type_boundaries`] directly, at
61//!    the exact point the hook used to fire, so both callers see it in the
62//!    same diagnostic-ordering position as before.
63//! 7. ~~Test/integration-suite processing~~
64//!    (`process_tests`/`process_integration_tests`) — **closed at P5.4**.
65//!    Unlike categories 2-6, these run *unconditionally* in `run_checks`, in
66//!    `Mode::Analyse` too, and push into the same shared error sink (`bynk-emit`'s own
67//!    `check_project_reports_a_test_body_error_past_an_earlier_structural_error`
68//!    pins a `bynk.types.let_annotation_mismatch` originating inside a
69//!    `suite`/`test integration` body). The two functions were emission-coupled
70//!    (`Document`, `RunnableTest`, `ImportExt`, `contracts`, a shared
71//!    `emitted_barrels` set) deeply enough that P5.4 split them at the
72//!    check/emit boundary rather than porting the whole thing: their checking
73//!    half relocated to [`crate::test_suites::phase_test_bodies`]/
74//!    [`crate::test_suites::phase_integration_bodies`], now called from
75//!    [`analyse_project`] right after the per-unit compose/check loop (the
76//!    same relative point `run_checks` calls the originals, unconditionally —
77//!    unlike categories 2-6, neither is gated on a clean error sink), while
78//!    emission itself stays in `bynk-driver::project::tests_emit`, which now
79//!    calls the relocated checking phase too rather than duplicating it. Both
80//!    functions still take `&mut RefSink`, so every binding edge inside a
81//!    `.bynk` suite file is populated here again too — go-to-definition
82//!    inside a test file works through this entry point once more.
83//!
84//! Emission itself is orthogonal rather than a gap: this entry point never
85//! emits, by construction (it has no `BuildTarget`/`ImportExt`/`contracts`
86//! concept at all), so there is no diagnostic-agreement question to ask of it.
87//!
88//! A fixture that exercises none of the seven categories above saw identical
89//! diagnostics from this entry point and from `analyse_project_with` while
90//! both existed — that is why `bynk-check/tests/differential_analysis.rs`'s
91//! clean/broken golden cases still avoid all seven (#1541 retired the
92//! comparison, not the fixture shape). A third case
93//! (`new_entry_point_reports_a_test_bodys_own_type_error`, renamed from
94//! `new_entry_point_omits_test_body_diagnostics` at #1541) pinned category
95//! 7's divergence directly; now that P5.4 closed it, that test pins parity
96//! with what `analyse_project_with` used to report instead (see its own doc
97//! comment).
98//!
99//! ## Two sites outside the seven-category accounting
100//!
101//! `bynk-check/src/analysis.rs`'s own seven categories were `run_checks`'s
102//! whole-project checks; two more registered diagnostics were still
103//! constructed in `bynk-emit` and outside that accounting, found and closed
104//! at P5.5 (`design/tracks/semantics-in-the-checker.md` §6, §9):
105//!
106//! - `bynk.project.schema_registry_corrupt` — a malformed on-disk
107//!   `bynk.schema.lock`. [`crate::schema_registry::parse_or_diagnose`] now
108//!   constructs it. Reachable from this entry point since #2081, under the
109//!   caller's `SchemaLock::On`, same as category 1.
110//! - `bynk.secrets.computed_name` — see
111//!   [`crate::project_model::phase_secrets_computed_name`]'s own doc. Unlike
112//!   the seven categories (scoped and confirmed live gaps or confirmed
113//!   gap-in-name-only by this settling pass), this one's reachability from
114//!   *this* entry point was still open at settling time — §9 named it a risk
115//!   rather than a scoped item. It resolved the same way categories 1 and 5
116//!   did: gap-in-name-only, since `run_checks`'s own gate
117//!   (`target == BuildTarget::Workers`) can never pass against this entry
118//!   point's hardcoded `BuildTarget::Bundle`.
119
120use std::collections::{BTreeMap, HashMap, HashSet};
121use std::path::{Path, PathBuf};
122use std::sync::Arc;
123
124use crate::capability_paths::FileCapabilityPaths;
125use crate::check_pipeline::{
126    CrossContextViewsCache, check_file_core, prepare_unit_check_ctx, record_analyse_types,
127};
128use crate::checker::Types;
129use crate::expr_types::{ExprTypeSink, FileExprTypes};
130use crate::firstparty::Platform;
131use crate::hints::{FileHints, HintSink};
132use crate::index::{ProjectIndex, RefSink};
133use crate::locals::{FileLocals, LocalsSink};
134use crate::project_model::{
135    self, ErrorSink, UnitInfo, assemble_unit_info, close_reachable_types, collect_unit_methods,
136    compose_unit_symbols, merge_consumed_exports, normalize_service_defaults,
137};
138use crate::requirements::{FileRequirements, RequirementSink};
139use crate::symbols::{ConsumedType, assemble_index, build_cross_context_info};
140use bynk_project::{AttributedError, ParsedFile, Roots, SchemaLock, UnitKind};
141use bynk_syntax::ast::{AgentDecl, ServiceDecl, TypeDecl};
142
143/// #846: the per-unit slice of resolution the sequence-diagram classifier
144/// needs — see [`ProjectAnalysis::sequence_info`]. Moved verbatim (Decision
145/// C, #1115) from `bynk-emit/src/project/diagnostics.rs`.
146#[derive(Debug, Clone, Default)]
147pub struct ContextSequenceInfo {
148    pub cross_context: crate::resolver::CrossContextInfo,
149    pub agents: HashMap<String, Arc<AgentDecl>>,
150}
151
152/// #855: the per-unit slice of resolution the wire-contract peek needs —
153/// see [`ProjectAnalysis::boundary_info`]. A sibling of
154/// [`ContextSequenceInfo`], not a field on it: that struct is named and
155/// documented for #846, and this is a separate retained table serving a
156/// separate query (hover/panel over a single handler's boundary, not the
157/// sequence-diagram classifier). Moved verbatim (Decision C, #1115).
158#[derive(Debug, Clone, Default)]
159pub struct ContextBoundaryInfo {
160    /// `contract_types_for` (#2073): the unit's own declared types, the types
161    /// of every commons it `uses` and those of the contexts it consumes — the
162    /// same table `own_contract_hashes` hashes through, so the peek's hash and
163    /// the emitted `X-Bynk-Contract` constant cannot disagree.
164    pub types: HashMap<String, Arc<TypeDecl>>,
165    pub services: HashMap<String, ServiceDecl>,
166    pub agents: HashMap<String, Arc<AgentDecl>>,
167    /// #3386: the unit's actors, so a document can describe the credential a route needs.
168    pub actors: HashMap<String, bynk_syntax::ast::ActorDecl>,
169}
170
171/// v0.24: the analyse-mode result — every discovered file's analysed text
172/// snapshot (positions must convert against the text that was analysed, not
173/// a newer buffer) plus the attributed diagnostics. Moved verbatim (Decision
174/// C, #1115) from `bynk-emit/src/project/diagnostics.rs`; `bynk-emit`
175/// re-exports this type at its old path (`bynk_driver::project::ProjectAnalysis`)
176/// so `bynk-ide`'s existing destructuring needs no field-by-field rewrite.
177pub struct ProjectAnalysis {
178    /// `(project-relative source path, analysed text)` for every file read,
179    /// including clean files (the LSP needs them to clear diagnostics).
180    pub snapshots: Vec<(PathBuf, String)>,
181    pub errors: Vec<AttributedError>,
182    /// v0.25 (ADR 0053): the project-wide binding index. Empty when the
183    /// pipeline bails before resolution (discovery/parse failures).
184    pub index: ProjectIndex,
185    /// v0.27 (ADR 0056): per-file inferred-type inlay hints — `(binding-name
186    /// span, label)`, span-ordered, harvested from the checker's binding
187    /// sites. Empty for files the pipeline never type-checked.
188    pub hints: FileHints,
189    /// v0.30.2 (ADR 0063): per-file expression types — `(expr span, Ty)`,
190    /// for `.`-member completion's and signature help's receiver typing.
191    /// Recorded at every per-file exit of the check, clean or not: a file
192    /// with errors still carries the best-effort partial types the checker
193    /// computed for its other expressions (ADR 0094, which lifted ADR 0063's
194    /// clean-file ceiling — see [`record_analyse_types`]).
195    /// Empty for files the pipeline never type-checked and for synthetic
196    /// files (muted).
197    pub expr_types: FileExprTypes,
198    /// T3.6b (R4.1): the intern table every `TyId` in `expr_types` resolves
199    /// against — one table shared across the whole analysis.
200    pub ty_intern: Arc<Types>,
201    /// v0.31 (ADR 0064): per-file local bindings with their scope ranges —
202    /// `let`/`let <-`, fn/handler/lambda params — for the scope-at-offset
203    /// query backing locals completion + navigation. Synthetic files muted.
204    pub locals: FileLocals,
205    /// v0.99: per-file capability-requirement ledger — every
206    /// capability-consuming site (direct call, store op), covered or not,
207    /// with its provenance. Empty for files the pipeline never type-checked,
208    /// and for synthetic/test files (muted).
209    pub requirements: FileRequirements,
210    /// #2469: per-file capability paths — for each `given` entry, the shortest
211    /// chain to the capability's use, and the facts the full set is computed
212    /// from on demand. Muted like `requirements`.
213    pub capability_paths: FileCapabilityPaths,
214    /// Slice 6b (ADR 0095): qualified unit name → the project source file(s)
215    /// that comprise it, in discovery order. Excludes synthetic
216    /// (toolchain-injected) units; empty when the pipeline bails before the
217    /// checker.
218    pub unit_sources: HashMap<String, Vec<PathBuf>>,
219    /// #846: qualified context/adapter unit name → the cross-context and
220    /// agent tables needed to classify a handler call as a lifeline for the
221    /// sequence-diagram query. Only contexts/adapters have an entry; empty
222    /// when the pipeline bails before the checker.
223    pub sequence_info: HashMap<String, ContextSequenceInfo>,
224    /// #3583: event emitters/subscribers, each handler's resolved `given`, and the
225    /// suites' `stub`s, for `bynk/architectureModel`'s `events` and `uses` sections.
226    pub architecture_facts: crate::architecture_facts::ArchitectureFacts,
227    /// #855: qualified context/adapter unit name → the combined type table
228    /// and per-context service/agent tables the wire-contract peek needs.
229    /// Only contexts/adapters have an entry; empty when the pipeline bails
230    /// before the checker.
231    pub boundary_info: HashMap<String, ContextBoundaryInfo>,
232    /// #848: qualified unit name → its doc-comment intra-doc-link search
233    /// order — itself first, then its `uses` targets, then its `consumes`
234    /// targets, in that order. Empty when the pipeline bails before the
235    /// checker.
236    pub doc_scope: HashMap<String, Vec<String>>,
237    /// #2467: what the contract-diff view lists. See [`ContractDiff`].
238    pub contract_diff: ContractDiff,
239}
240
241/// #2467: the boundary changes since `bynk.schema.lock`, and the contract
242/// hashes the project provides now, for the editor's "Show Contract Diff".
243///
244/// `changes` is [`crate::schema_registry::diff_against_lock`], a report of
245/// the verdicts the lock reconciliation itself reaches, never a second
246/// classifier. It is empty under [`SchemaLock::Off`] and when the lock is
247/// corrupt (the corruption is already a diagnostic).
248///
249/// `services` is each context's own `on call` contract hash per service
250/// ([`crate::contract::own_contract_hashes`], what the deploy gate compares
251/// with the ledger). Hashes say *whether* a contract moved, not whether the
252/// move is breaking; `ProvidedContracts::shapes` carries the structure the
253/// compatibility classifier (`contract_compat`, #2485) needs for that.
254#[derive(Debug, Clone, Default, PartialEq, Eq)]
255pub struct ContractDiff {
256    /// What reading `bynk.schema.lock` gave.
257    pub lock: LockState,
258    pub changes: Vec<crate::schema_registry::BoundaryChange>,
259    /// Qualified context name → what it provides now.
260    pub services: std::collections::BTreeMap<String, ProvidedContracts>,
261}
262
263/// What the analysis found when it read `bynk.schema.lock`.
264#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
265pub enum LockState {
266    /// No lock (`SchemaLock::Off`): nothing to compare with.
267    #[default]
268    Absent,
269    /// A lock that does not parse (already reported as
270    /// `bynk.project.schema_registry_corrupt`).
271    Unreadable,
272    Read,
273}
274
275/// One context's own `on call` contracts.
276#[derive(Debug, Clone, Default, PartialEq, Eq)]
277pub struct ProvidedContracts {
278    /// The context's Worker, as `bynk.deploy.lock` keys it: its directory
279    /// ([`bynk_project::worker_layout::WorkerLayout::dir`]), the group's key for
280    /// a member.
281    pub worker: String,
282    /// Service → contract hash.
283    pub hashes: std::collections::BTreeMap<String, String>,
284    /// #2485: service → the structured shape behind that hash
285    /// ([`crate::contract_compat::ServiceShape::to_text`]), so a changed hash
286    /// can be classified as compatible or breaking against the shape the
287    /// ledger recorded.
288    pub shapes: std::collections::BTreeMap<String, String>,
289}
290
291/// The `ProjectAnalysis` shape for every "bailed before the checker ran"
292/// exit — discovery/file-conflict/parse failures. Factored out so the three
293/// early-return sites in [`analyse_project`] agree by construction, the same
294/// role `RunChecks::Bailed` plays in `bynk-emit`'s `run_checks`.
295fn bailed(
296    errors: ErrorSink,
297    snapshots: Vec<(PathBuf, String)>,
298    mut hints: HintSink,
299    mut locals: LocalsSink,
300    mut exprs: ExprTypeSink,
301    mut requirements: RequirementSink,
302    tys: &Arc<Types>,
303) -> ProjectAnalysis {
304    ProjectAnalysis {
305        snapshots,
306        // ADR 0117: the LSP renders warnings alongside errors (severity is
307        // applied downstream), so analyse surfaces the full diagnostic list.
308        errors: errors.into_all(),
309        index: ProjectIndex::default(),
310        hints: hints.take_files(),
311        locals: locals.take_files(),
312        expr_types: exprs.take_files(),
313        ty_intern: Arc::clone(tys),
314        capability_paths: requirements.take_paths(),
315        requirements: requirements.take_files(),
316        unit_sources: HashMap::new(),
317        sequence_info: HashMap::new(),
318        architecture_facts: Default::default(),
319        boundary_info: HashMap::new(),
320        doc_scope: HashMap::new(),
321        contract_diff: ContractDiff::default(),
322    }
323}
324
325/// What [`check_file_core`] reads for every file of one unit, bundled: the unit's
326/// composed symbol space and prelude. [`crate::check_pipeline::file_check_digest`]
327/// hashes the same list.
328struct UnitCheckInputs<'a> {
329    name: &'a str,
330    kind: UnitKind,
331    unit_info: &'a BTreeMap<String, UnitInfo>,
332    combined_types: &'a HashMap<String, Arc<TypeDecl>>,
333    combined_fns: &'a HashMap<String, Arc<bynk_syntax::ast::FnDecl>>,
334    combined_methods: &'a HashMap<String, crate::resolver::MethodTable>,
335    local_names: &'a HashSet<String>,
336    local_methods_for_type: &'a HashMap<String, Vec<bynk_syntax::ast::FnDecl>>,
337    consumed_types: &'a HashMap<String, ConsumedType>,
338    imported_from: &'a HashMap<String, String>,
339    ctx: &'a crate::check_pipeline::UnitCheckCtx,
340    tys: &'a Arc<Types>,
341}
342
343/// A hash of what a unit's files say, folded into each file's digest.
344fn unit_files_digest(indices: &[usize], parsed: &[ParsedFile]) -> u64 {
345    use std::hash::{Hash, Hasher};
346    let mut h = std::collections::hash_map::DefaultHasher::new();
347    for &i in indices {
348        parsed[i].identity_path().hash(&mut h);
349        parsed[i].source().hash(&mut h);
350    }
351    h.finish()
352}
353
354/// One file's output: replayed from `memo` when its digest is unchanged, checked
355/// (and kept) otherwise. Without a memo it is just the check.
356fn check_or_replay(
357    memo: Option<&mut crate::memo::AnalysisMemo>,
358    unit_files_digest: Option<u64>,
359    inputs: &UnitCheckInputs<'_>,
360    pf: &ParsedFile,
361) -> crate::memo::FileRecord {
362    let (Some(memo), Some(unit_files_digest)) = (memo, unit_files_digest) else {
363        return check_one_file(inputs, pf);
364    };
365    let digest = crate::check_pipeline::file_check_digest(
366        inputs.name,
367        inputs.kind,
368        pf,
369        unit_files_digest,
370        inputs.unit_info,
371        inputs.combined_types,
372        inputs.combined_fns,
373        inputs.combined_methods,
374        inputs.local_names,
375        inputs.local_methods_for_type,
376        inputs.consumed_types,
377        inputs.imported_from,
378        inputs.ctx,
379        memo.decls_mut(),
380    );
381    let path = pf.identity_path();
382    if let Some(record) = memo.lookup(&path, digest) {
383        return record;
384    }
385    let record = check_one_file(inputs, pf);
386    memo.store(path, digest, record.clone());
387    record
388}
389
390/// Check one file into its own scratch sinks (#3243 S2.3), returning everything it
391/// produced. Today's per-file unit of work; the memo keeps these between rounds.
392fn check_one_file(inputs: &UnitCheckInputs<'_>, pf: &ParsedFile) -> crate::memo::FileRecord {
393    let mut errors = ErrorSink::new();
394    let mut refs = RefSink::new();
395    let mut hints = HintSink::new();
396    let mut locals = LocalsSink::new();
397    let mut exprs = ExprTypeSink::new();
398    let mut requirements = RequirementSink::new();
399    let typed = check_file_core(
400        inputs.name,
401        inputs.kind,
402        pf,
403        inputs.unit_info,
404        inputs.combined_types,
405        inputs.combined_fns,
406        inputs.combined_methods,
407        inputs.local_names,
408        inputs.local_methods_for_type,
409        inputs.consumed_types,
410        inputs.imported_from,
411        inputs.ctx,
412        &mut errors,
413        &mut refs,
414        &mut hints,
415        &mut locals,
416        &mut exprs,
417        &mut requirements,
418        inputs.tys,
419    )
420    .map(|crate::check_pipeline::FileCheckResult { typed, .. }| {
421        // This entry point never emits — every clean file's exit is the
422        // Analyse-mode one (record best-effort/final types, move on to the next
423        // file). Mirrors `check_unit_files`'s own `mode == Mode::Analyse`
424        // clean-path branch.
425        record_analyse_types(
426            &mut exprs,
427            &pf.identity_path(),
428            pf.is_synthetic(),
429            &typed.expr_types,
430        );
431        Arc::new(typed)
432    });
433    crate::memo::FileRecord {
434        errors,
435        refs,
436        hints,
437        locals,
438        exprs,
439        requirements,
440        typed,
441    }
442}
443
444/// The `bynk-check`-native discovery→parse→resolve→check entry point (P4.1,
445/// #1115) — see this module's own doc comment for the residual-gap
446/// accounting against `bynk-emit`'s now-deleted (#1541) `analyse_project_with`.
447/// Mirrored its call shape exactly where the two overlapped:
448/// `BuildTarget::Bundle`-equivalent (this entry point has no build target at
449/// all — it never emits), `Platform::default()`.
450///
451/// `schema_lock` (#2081) is `bynk.schema.lock`'s content, pre-read by the
452/// caller exactly as `bynk check` pre-reads it (this crate reads no lock from
453/// disk). Under [`SchemaLock::On`] every event is reconciled against it and a
454/// non-additive change, a corrupt lock or a mismatched `@schema(N)` is
455/// reported as the build reports it; under [`SchemaLock::Off`] reconciliation
456/// is skipped. Nothing is written either way.
457///
458/// Identity is project-relative (ADR 0198): a file's `source_path` here is
459/// unique across `include` roots, same as `analyse_project_with` used to be.
460pub fn analyse_project(
461    roots: &Roots,
462    overlay: &HashMap<PathBuf, String>,
463    schema_lock: &SchemaLock,
464) -> ProjectAnalysis {
465    // S3 (#1963): the project's `[unstable]` opt-in, read the way the build
466    // reads it, so the editor and `bynk` agree about every file.
467    let policy =
468        crate::stability::StabilityPolicy::for_project(Some(roots.project_root()), overlay);
469    analyse_project_with_policy(roots, overlay, policy, schema_lock)
470}
471
472/// [`analyse_project`] under a given [`crate::stability::StabilityPolicy`] —
473/// how a test treats a shipped item as experimental, since none is yet.
474pub fn analyse_project_with_policy(
475    roots: &Roots,
476    overlay: &HashMap<PathBuf, String>,
477    policy: crate::stability::StabilityPolicy,
478    schema_lock: &SchemaLock,
479) -> ProjectAnalysis {
480    analyse_project_inner(roots, overlay, policy, schema_lock, None)
481}
482
483/// [`analyse_project`] reusing `memo` (#3243 S2.3b): the language server's entry
484/// point, via [`crate::memo::analyse_project_memoised`].
485pub(crate) fn analyse_project_cached(
486    roots: &Roots,
487    overlay: &HashMap<PathBuf, String>,
488    schema_lock: &SchemaLock,
489    memo: &mut crate::memo::AnalysisMemo,
490) -> ProjectAnalysis {
491    let policy =
492        crate::stability::StabilityPolicy::for_project(Some(roots.project_root()), overlay);
493    memo.begin_round();
494    let analysis = analyse_project_inner(roots, overlay, policy, schema_lock, Some(&mut *memo));
495    memo.end_round();
496    analysis
497}
498
499/// The per-context tables the editor queries resolve against: the sequence
500/// view's cross-context info and the wire-contract peek's boundary info, plus
501/// each context's provided contracts recorded on `contract_diff`.
502fn per_unit_infos(
503    kinds: &BTreeMap<String, UnitKind>,
504    unit_tables: &HashMap<String, crate::symbols::UnitTable>,
505    unit_consumes: &HashMap<String, Vec<String>>,
506    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
507    unit_uses: &HashMap<String, Vec<String>>,
508    unit_flattened: &HashMap<String, HashMap<String, String>>,
509    (layout, contract_diff): (
510        &bynk_project::worker_layout::WorkerLayout,
511        &mut ContractDiff,
512    ),
513) -> (
514    HashMap<String, ContextSequenceInfo>,
515    HashMap<String, ContextBoundaryInfo>,
516) {
517    let mut sequence_info: HashMap<String, ContextSequenceInfo> = HashMap::new();
518    let mut boundary_info: HashMap<String, ContextBoundaryInfo> = HashMap::new();
519    for (name, kind) in kinds {
520        if !matches!(kind, UnitKind::Context | UnitKind::Adapter) {
521            continue;
522        }
523        let Some(table) = unit_tables.get(name) else {
524            continue;
525        };
526        let mut cross_context = build_cross_context_info(
527            name,
528            unit_consumes,
529            unit_consumes_aliases,
530            unit_uses,
531            unit_tables,
532        );
533        cross_context.flattened_caps = unit_flattened.get(name).cloned().unwrap_or_default();
534        // Both infos share the table's `Arc`'d agents (#3243: no deep clone per info).
535        let agents: HashMap<String, Arc<AgentDecl>> = table.agents.clone();
536        sequence_info.insert(
537            name.clone(),
538            ContextSequenceInfo {
539                cross_context,
540                agents: agents.clone(),
541            },
542        );
543        let contract_types =
544            crate::symbols::contract_types_for(name, unit_tables, unit_uses, unit_consumes).0;
545        // Recorded even when empty: a context that dropped its last `on call`
546        // service still has a Worker whose live contracts it no longer provides.
547        contract_diff.services.insert(
548            name.clone(),
549            ProvidedContracts {
550                worker: layout.dir(name),
551                hashes: crate::contract::own_contract_hashes(table, &contract_types),
552                shapes: crate::contract_compat::own_contract_shapes(table, &contract_types),
553            },
554        );
555        boundary_info.insert(
556            name.clone(),
557            ContextBoundaryInfo {
558                // #2073: the table `own_contract_hashes` hashes through.
559                types: contract_types,
560                services: table.services.clone(),
561                agents,
562                actors: table.actors.clone(),
563            },
564        );
565    }
566    (sequence_info, boundary_info)
567}
568
569/// The callees of a unit's checked files that later passes read (events emits, cross-context
570/// service calls and agent calls), merged into the project-wide accumulator.
571fn retain_unit_callees(
572    unit_callees: &mut project_model::UnitCallees,
573    name: &str,
574    checked: &[Arc<crate::checker::TypedCommons>],
575) {
576    unit_callees.entry(name.to_string()).or_default().extend(
577        checked
578            .iter()
579            .flat_map(|t| &t.callees)
580            .filter(|(_, c)| {
581                project_model::is_events_emit(c)
582                    || matches!(
583                        c,
584                        crate::checker::Callee::Cross { .. } | crate::checker::Callee::Agent { .. }
585                    )
586            })
587            .map(|(id, c)| (*id, c.clone())),
588    );
589    #[cfg(test)]
590    crate::testkit::note_callees(name, checked.iter().flat_map(|t| &t.callees));
591}
592
593fn analyse_project_inner(
594    roots: &Roots,
595    overlay: &HashMap<PathBuf, String>,
596    policy: crate::stability::StabilityPolicy,
597    schema_lock: &SchemaLock,
598    mut memo: Option<&mut crate::memo::AnalysisMemo>,
599) -> ProjectAnalysis {
600    let tys = &match memo.as_deref() {
601        Some(m) => Arc::clone(m.types()),
602        None => Arc::new(Types::new()),
603    };
604    // #2223: a manifest-backed project's path dependencies are walked too.
605    let packages = matches!(roots, Roots::Split { .. });
606    let mut trees = roots.trees();
607    if packages {
608        trees.extend(bynk_project::dependency_trees(
609            roots.project_root(),
610            overlay,
611        ));
612    }
613    let excludes = roots.excludes();
614    let policy = Arc::new(policy);
615
616    let mut errors = ErrorSink::new();
617    for err in policy.manifest_diagnostics() {
618        errors.push_for(Some(Path::new(crate::stability::MANIFEST)), err);
619    }
620    let mut refs = RefSink::new();
621    let mut hints = HintSink::new();
622    let mut locals = LocalsSink::new();
623    let mut requirements = RequirementSink::new();
624    let mut exprs = ExprTypeSink::new();
625    let mut snapshots: Vec<(PathBuf, String)> = Vec::new();
626
627    crate::phase_timing::begin(crate::phase_timing::Level::File);
628    // -- 1. Discovery. --
629    let file_lists = match project_model::phase_discovery(&trees, &excludes, &mut errors) {
630        Ok(files) => files,
631        Err(()) => return bailed(errors, snapshots, hints, locals, exprs, requirements, tys),
632    };
633    if project_model::check_discovered_files(&trees, &file_lists, &mut errors).is_err() {
634        return bailed(errors, snapshots, hints, locals, exprs, requirements, tys);
635    }
636
637    // -- 2. Parse. --
638    let (mut parsed, injected, broken) =
639        match project_model::phase_parse(&trees, &file_lists, overlay, &mut errors, &mut snapshots)
640        {
641            Ok(out) => out,
642            Err(()) => return bailed(errors, snapshots, hints, locals, exprs, requirements, tys),
643        };
644
645    crate::phase_timing::mark(crate::phase_timing::Level::Unit);
646    // -- 2a. #2223: fold the project's path dependencies in. --
647    if packages {
648        crate::packages::apply_graph(
649            Some(roots.project_root()),
650            overlay,
651            &mut parsed,
652            true,
653            &mut errors,
654        );
655    }
656
657    // -- 2b. Normalize service-level `by`/`given` defaults (v0.155). --
658    normalize_service_defaults(&mut parsed);
659    // #3243: `parsed` is final here. Register its files once, so the per-unit
660    // attribution below does not re-register every file for every unit.
661    errors.register_parsed(&parsed);
662
663    // -- 3. Group. P5.2: closes category 6 of this module's own residual-gap
664    //       accounting (see doc comment above) — `phase_group` now also
665    //       confines function types to non-boundary positions directly, at
666    //       the point its old optional hook used to fire. --
667    let (groups, kinds, test_groups, integration_groups, _adapter_bindings, _npm_deps) =
668        project_model::phase_group(
669            &parsed,
670            &trees,
671            Platform::default(),
672            &injected,
673            overlay,
674            &mut errors,
675        );
676    // #2207: `[package] exports` names only commons and adapters this project
677    // declares, read the way the build reads it.
678    for err in crate::exports::manifest_diagnostics(Some(roots.project_root()), overlay, &kinds) {
679        errors.push_for(Some(Path::new(crate::stability::MANIFEST)), err);
680    }
681
682    // #3562: `[deploy.workers]` groups name only contexts the project declares,
683    // read the way the build reads them.
684    for err in
685        crate::worker_groups::manifest_diagnostics(Some(roots.project_root()), overlay, &kinds)
686    {
687        errors.push_for(Some(Path::new(crate::stability::MANIFEST)), err);
688    }
689
690    // -- 4. Per-unit combined symbol tables. --
691    // -- 4-5. Symbol tables, `uses` resolution, and (#3445) the constants named by
692    //         literal-only annotation arguments, resolved ahead of every reader. --
693    let (unit_tables, unit_uses) = project_model::phase_tables_uses_consts(
694        &groups,
695        &kinds,
696        &mut parsed,
697        &policy,
698        &mut errors,
699        &mut refs,
700    );
701
702    // -- 5b. `consumes` resolution. --
703    let (unit_consumes, unit_flattened, unit_type_aliases) = project_model::phase_resolve_consumes(
704        &groups,
705        &kinds,
706        &parsed,
707        &unit_tables,
708        &policy,
709        &mut errors,
710        &mut refs,
711    );
712    let mut unit_tables = unit_tables;
713    crate::symbols::record_flattened_caps(&mut unit_tables, &unit_flattened, &unit_type_aliases);
714    // The editor reads the groups as a Workers build does.
715    let layout =
716        bynk_project::worker_layout::WorkerLayout::for_project(roots.project_root(), overlay);
717    crate::project_model::phase_resolve_derived(
718        &groups,
719        &kinds,
720        &parsed,
721        &layout,
722        &mut unit_tables,
723        &mut errors,
724    );
725    let unit_tables = unit_tables;
726
727    // -- 5b'. `consumes` aliases. --
728    let unit_consumes_aliases =
729        project_model::phase_consumes_aliases(&groups, &kinds, &parsed, &unit_tables, &mut errors);
730
731    // -- 5b''. v0.173 (ADR 0196 D1), P5.5 (`design/tracks/semantics-in-the-checker.md`
732    //          §6, §9): warn where a `bynk.Secrets` read names its secret with
733    //          a computed expression — closes the "ninth gap" that §9 flagged
734    //          as unresolved risk rather than a scoped relocation. Mirrors
735    //          `run_checks`'s own call at the same relative point. Gated on
736    //          the Workers target, same as `run_checks`; this entry point
737    //          hardcodes `BuildTarget::Bundle` (inherited from the
738    //          now-deleted `analyse_project_with`'s own hardcoding, see this
739    //          function's doc comment), so the call
740    //          closes the category structurally (R3.5 — the diagnostic now
741    //          originates in `bynk-check`), not observably, the same as
742    //          categories 1 and 5. --
743    project_model::phase_secrets_computed_name(
744        project_model::BuildTarget::Bundle,
745        &parsed,
746        &groups,
747        &kinds,
748        &unit_flattened,
749        &mut errors,
750    );
751    // #1822, #3328, #2306: the project-wide topology checks.
752    project_model::phase_topology(
753        project_model::BuildTarget::Bundle,
754        &parsed,
755        &groups,
756        &kinds,
757        &unit_tables,
758        &mut errors,
759    );
760    // #2959: Workers-only as well.
761    project_model::phase_workers_ws_open_key(
762        project_model::BuildTarget::Bundle,
763        &parsed,
764        &groups,
765        &kinds,
766        &unit_tables,
767        &unit_uses,
768        &mut errors,
769    );
770    // #2355 follow-up: Workers-only as well.
771    project_model::phase_workers_provider_agent_cross_context(
772        project_model::BuildTarget::Bundle,
773        &parsed,
774        &groups,
775        &kinds,
776        &unit_tables,
777        &unit_consumes,
778        &unit_consumes_aliases,
779        &unit_flattened,
780        &mut errors,
781    );
782
783    crate::phase_timing::mark(crate::phase_timing::Level::Project);
784    // -- 5c. `consumes` cycles. --
785    project_model::phase_detect_consumes_cycles(&groups, &parsed, &unit_consumes, &mut errors);
786
787    // -- 6. `uses` name-conflict detection. --
788    project_model::phase_uses_name_conflicts(
789        &unit_uses,
790        &unit_tables,
791        &parsed,
792        &groups,
793        &mut errors,
794    );
795    // -- 6.1. #2618: a public signature naming a private type. --
796    project_model::phase_private_in_public(&parsed, &groups, &mut errors);
797
798    // -- 6a0. #1883, slice 1b: every declared asset names a file in the
799    //         `assets/` folder, listed from disk as discovery already reads
800    //         it. An unreadable folder skips the check rather than flagging
801    //         every asset in the editor.
802    let available_assets = bynk_project::assets::list_asset_files(roots.project_root()).ok();
803    crate::assets::phase_asset_files(&parsed, available_assets.as_ref(), &mut errors);
804    // #2387, slice 2: likewise every declared embed names a file in `embeds/`.
805    let available_embeds = bynk_project::assets::list_embed_files(roots.project_root()).ok();
806    crate::embeds::phase_embed_files(&parsed, available_embeds.as_ref(), &mut errors);
807    // #2841: and every suite `fixture` names a file in `fixtures/`.
808    let available_fixtures = bynk_project::assets::list_fixture_files(roots.project_root()).ok();
809    crate::fixtures::phase_fixture_files(&parsed, available_fixtures.as_ref(), &mut errors);
810    crate::assets::phase_asset_routes(&parsed, &groups, (&kinds, &layout), &unit_uses, &mut errors);
811    // #3070: the D1 migrations' schemas, which literal D1 SQL is prepared
812    // against below, as `bynk check` does. A throwaway sink: the migrations'
813    // own file diagnostics are not (yet) an editor surface.
814    let d1_sql = if bynk_project::read_check_config(roots.project_root(), overlay).d1_sql {
815        bynk_project::assets::AssetFolder::migrations_on_disk(roots.project_root())
816            .ok()
817            .and_then(|folder| {
818                let layout = bynk_project::worker_layout::WorkerLayout::for_project(
819                    roots.project_root(),
820                    overlay,
821                );
822                let mut scratch = ErrorSink::new();
823                let migrations = crate::d1_migrations::phase_d1_migrations(
824                    Some(&folder),
825                    &crate::d1_migrations::declared_databases(&kinds, &unit_tables, &layout),
826                    &mut scratch,
827                );
828                // Its `migration_invalid` warning is keyed to a path the editor has
829                // no document for, so it stays in the scratch sink too.
830                crate::d1_sql::D1Sql::build(&migrations, &layout, &mut scratch)
831            })
832    } else {
833        None
834    };
835
836    // -- 6a'. message-bundles slice 1 (#859): messages-block legality,
837    //         @reference cardinality, within-block duplicate codes, and the
838    //         `uses bynk.locale` dependency. P5.0: closes category 2 of this
839    //         module's own residual-gap accounting. --
840    project_model::phase_messages_bundles(&parsed, &groups, &kinds, &unit_uses, &mut errors);
841
842    // -- 6a''. Locale capability track, slice 2 (#882): a context reaching
843    //          two or more message-bundle commons while consuming `Locale`
844    //          has no single bundle to negotiate against. P5.0: closes
845    //          category 3. --
846    project_model::phase_locale_bundle_ambiguity(
847        &parsed,
848        &groups,
849        &kinds,
850        &unit_uses,
851        &unit_flattened,
852        &mut errors,
853    );
854
855    // -- 6a'''. Events track, slice 0 (spine #936): a `from Events(E)`
856    //           subscription must name a real, declared event — needs
857    //           `unit_tables` + `unit_consumes` together, so it runs here
858    //           rather than in the per-context `check_service_protocols`.
859    //           P5.1: closes category 4. --
860    project_model::phase_event_subscriptions(
861        &parsed,
862        &groups,
863        &kinds,
864        &unit_tables,
865        &unit_consumes,
866        &unit_uses,
867        &mut errors,
868    );
869
870    // -- 6b. Type exports. --
871    let exports_visibility = project_model::phase_validate_type_exports(
872        &groups,
873        &kinds,
874        &parsed,
875        &unit_tables,
876        &mut errors,
877        &mut refs,
878    );
879
880    // -- 6b'. Capability exports. --
881    project_model::phase_validate_capability_exports(
882        &groups,
883        &kinds,
884        &parsed,
885        &unit_tables,
886        &mut errors,
887        &mut refs,
888    );
889
890    // -- 6c. Provider matching. --
891    project_model::phase_validate_providers(
892        &unit_tables,
893        &groups,
894        &parsed,
895        &broken,
896        &mut errors,
897        tys,
898    );
899
900    // -- 6d. Events track, slice 3c (#980): schema-registry reconciliation,
901    //        at the same point `run_checks` calls it and with the same two
902    //        arms. #2081: the caller (the LSP) now pre-reads
903    //        `bynk.schema.lock` and hands it in, so a non-additive change, a
904    //        corrupt lock or a mismatched `@schema(N)` reaches the editor as
905    //        it reaches `bynk check`. `Off` (no lock, or a caller with none)
906    //        skips the sweep entirely rather than reconciling against an
907    //        empty registry, which can report nothing — closing review
908    //        #1133's cost note about paying for it on every keystroke. The
909    //        reconciled registry is discarded: analysis never writes. --
910    let mut contract_diff = ContractDiff::default();
911    if let SchemaLock::On { existing } = schema_lock {
912        match crate::schema_registry::parse_or_diagnose(existing.as_deref(), roots.project_root()) {
913            Ok(existing_reg) => {
914                // #2467: the same registry, reported as a diff (read-only).
915                contract_diff.lock = LockState::Read;
916                contract_diff.changes = crate::schema_registry::diff_against_lock(
917                    &existing_reg,
918                    &unit_tables,
919                    &unit_uses,
920                );
921                let mut schema_errors: Vec<bynk_syntax::error::CompileError> = Vec::new();
922                let (mut updated, _) = crate::schema_registry::reconcile(
923                    &existing_reg,
924                    &unit_tables,
925                    &mut schema_errors,
926                );
927                errors.extend_for(None, schema_errors);
928                // State-migrations S0 (#2204): agent state shapes, as
929                // `run_checks` reconciles them.
930                let mut agent_errors: Vec<bynk_syntax::error::CompileError> = Vec::new();
931                crate::schema_registry::reconcile_agents(
932                    &existing_reg,
933                    &mut updated,
934                    &unit_tables,
935                    &unit_uses,
936                    &mut agent_errors,
937                );
938                errors.extend_attributed_by_span(&parsed, agent_errors);
939            }
940            Err(err) => {
941                contract_diff.lock = LockState::Unreadable;
942                errors.push_for(None, err)
943            }
944        }
945    }
946
947    // No bail gate: this entry point never bails after discovery (mirrors
948    // `Mode::Analyse` — independent unit groups resolve/check past another
949    // group's errors).
950
951    crate::phase_timing::mark(crate::phase_timing::Level::Unit);
952    // -- 7. Per-unit file index. --
953    let unit_file_index = project_model::phase_file_index(&groups, &parsed);
954
955    // -- 7b. Assemble per-unit info. --
956    let unit_info = assemble_unit_info(
957        &groups,
958        &kinds,
959        &unit_tables,
960        &unit_uses,
961        &unit_consumes,
962        &unit_flattened,
963        &unit_consumes_aliases,
964        &exports_visibility,
965        &unit_file_index,
966    );
967
968    // -- 8. For each unit, compose the symbol space and resolve+check every
969    //       file. Test/integration processing is the residual gap after this
970    //       loop — see this module's own doc comment. Category 5
971    //       (platform-lock) closes right after, below the loop, at the same
972    //       relative point `run_checks` calls it (after its own per-unit
973    //       checking, gated on a clean error sink so far). --
974    // #1702 review: `uses` targets first, so a generic callee's compared type
975    // parameters are known before an importer's calls are checked.
976    crate::checker::reset_compared_cache();
977    // #2719: the needs-context set, extended unit by unit in dependency order.
978    let mut exec_plan = crate::exec_plan::ExecPlan::default();
979    // #3229: one set of cross-context views for the whole project, not one per unit.
980    let views = CrossContextViewsCache::default();
981    // Each unit's `Events.emit` calls, for the bundle's composition-root check
982    // below, as `run_checks` keeps them in its own `unit_callees`; and its
983    // service and agent calls, for the architecture facts (model-diagrams
984    // slice 5).
985    let mut unit_callees = project_model::UnitCallees::new();
986    for name in project_model::uses_first_order(unit_info.keys(), &unit_uses) {
987        let info = &unit_info[name];
988        let kind = info.kind;
989        let indices = info.files.as_slice();
990        let local_table = &info.table;
991        let group_error_baseline = errors.len();
992
993        let (
994            mut combined_types,
995            combined_fns,
996            mut combined_methods,
997            mut imported_from,
998            mut imported_from_kind,
999        ) = compose_unit_symbols(name, local_table, &unit_info);
1000        let consumed_types = merge_consumed_exports(
1001            name,
1002            &parsed,
1003            &unit_info,
1004            &mut combined_types,
1005            &mut combined_methods,
1006            &mut imported_from,
1007            &mut imported_from_kind,
1008            &mut errors,
1009        );
1010        // #1807: close over the types the imported declarations reach.
1011        let reached_types = close_reachable_types(
1012            name,
1013            &parsed,
1014            &unit_info,
1015            &mut combined_types,
1016            &combined_fns,
1017            &mut combined_methods,
1018            &mut imported_from,
1019            &mut imported_from_kind,
1020            &mut errors,
1021        );
1022
1023        if errors.len() > group_error_baseline {
1024            continue;
1025        }
1026
1027        let local_names: HashSet<String> = local_table.types.keys().cloned().collect();
1028        let local_methods_for_type = collect_unit_methods(indices, &parsed);
1029        let mut ctx = prepare_unit_check_ctx(
1030            name,
1031            kind,
1032            &broken,
1033            &unit_info,
1034            &views,
1035            &combined_types,
1036            &imported_from_kind,
1037            &reached_types,
1038            &policy,
1039        );
1040        ctx.d1_sql = d1_sql.clone();
1041
1042        crate::phase_timing::mark(crate::phase_timing::Level::Definition);
1043        let mut checked: Vec<Arc<crate::checker::TypedCommons>> = Vec::new();
1044        // #3243 S2.3b: what the unit's files say, for the digest of each (a
1045        // diagnostic's label can point into a sibling).
1046        let unit_files_digest = memo.as_ref().map(|_| unit_files_digest(indices, &parsed));
1047        let inputs = UnitCheckInputs {
1048            name,
1049            kind,
1050            unit_info: &unit_info,
1051            combined_types: &combined_types,
1052            combined_fns: &combined_fns,
1053            combined_methods: &combined_methods,
1054            local_names: &local_names,
1055            local_methods_for_type: &local_methods_for_type,
1056            consumed_types: &consumed_types,
1057            imported_from: &imported_from,
1058            ctx: &ctx,
1059            tys,
1060        };
1061        for &i in indices {
1062            let record =
1063                check_or_replay(memo.as_deref_mut(), unit_files_digest, &inputs, &parsed[i]);
1064            let crate::memo::FileRecord {
1065                errors: file_errors,
1066                refs: file_refs,
1067                hints: file_hints,
1068                locals: file_locals,
1069                exprs: file_exprs,
1070                requirements: file_requirements,
1071                typed,
1072            } = record;
1073            errors.absorb(file_errors);
1074            refs.absorb(file_refs);
1075            hints.absorb(file_hints);
1076            locals.absorb(file_locals);
1077            exprs.absorb(file_exprs);
1078            requirements.absorb(file_requirements);
1079            checked.extend(typed);
1080        }
1081        crate::phase_timing::mark(crate::phase_timing::Level::Unit);
1082        retain_unit_callees(&mut unit_callees, name, &checked);
1083        // #2719: the unit's needs-context set, and the calls that would carry
1084        // the execution context where none exists.
1085        let plan_errors = exec_plan.extend(&checked.iter().map(|t| &**t).collect::<Vec<_>>());
1086        errors.extend_attributed(plan_errors);
1087    }
1088
1089    // P5.4 (`design/tracks/semantics-in-the-checker.md` §6): test/
1090    // integration-suite processing — closes category 7 of this module's own
1091    // residual-gap accounting, the last of the seven. Mirrors `run_checks`'s
1092    // own call shape: both run unconditionally (unlike categories 2-6 above,
1093    // `run_checks` never gates these on a clean error sink), right after its
1094    // own per-unit `check_unit_files` loop and before platform-lock — the
1095    // same relative point this loop just occupied. Neither function's
1096    // returned "ready for emission" map is needed here — this entry point
1097    // never emits — only the diagnostic/`RefSink` side effects matter, so
1098    // both are discarded. Diagnostics are file-unattributed (`extend_for(None,
1099    // ...)`), matching `run_checks`'s own `#696`-noted gap (attributing them
1100    // means threading a file through many internal push sites — out of scope
1101    // here, same as there).
1102    crate::phase_timing::mark(crate::phase_timing::Level::Definition);
1103    let mut test_errors: Vec<bynk_syntax::error::CompileError> = Vec::new();
1104    let _ready_tests = crate::test_suites::phase_test_bodies(
1105        &test_groups,
1106        &parsed,
1107        &kinds,
1108        &unit_tables,
1109        &exports_visibility,
1110        &unit_consumes,
1111        &unit_consumes_aliases,
1112        &unit_uses,
1113        &broken,
1114        &mut test_errors,
1115        &mut refs,
1116        &mut locals,
1117        tys,
1118        d1_sql.as_deref(),
1119    );
1120    errors.extend_attributed_by_span(&parsed, test_errors);
1121
1122    let mut integration_errors: Vec<bynk_syntax::error::CompileError> = Vec::new();
1123    let _ready_integration = crate::test_suites::phase_integration_bodies(
1124        &integration_groups,
1125        &parsed,
1126        &kinds,
1127        &unit_tables,
1128        &unit_consumes,
1129        &unit_consumes_aliases,
1130        &unit_uses,
1131        &broken,
1132        &mut integration_errors,
1133        &mut refs,
1134        tys,
1135        d1_sql.as_deref(),
1136    );
1137    errors.extend_attributed_by_span(&parsed, integration_errors);
1138
1139    phase_clean_program_checks(
1140        &parsed,
1141        &groups,
1142        &kinds,
1143        &unit_tables,
1144        &unit_consumes,
1145        &unit_consumes_aliases,
1146        &unit_flattened,
1147        &unit_callees,
1148        &mut errors,
1149    );
1150
1151    crate::phase_timing::mark(crate::phase_timing::Level::Project);
1152    // -- Assemble the `ProjectAnalysis`. Mirrored the now-deleted
1153    //    `analyse_project_with`'s own `RunChecks::Checked` arm exactly. --
1154    let index = assemble_index(
1155        &parsed,
1156        &unit_uses,
1157        &unit_consumes,
1158        &unit_type_aliases,
1159        std::mem::take(&mut refs),
1160    );
1161
1162    let mut unit_sources: HashMap<String, Vec<PathBuf>> = HashMap::new();
1163    for pf in &parsed {
1164        if pf.is_synthetic() {
1165            continue;
1166        }
1167        unit_sources
1168            .entry(pf.unit().name().joined())
1169            .or_default()
1170            .push(pf.identity_path());
1171    }
1172
1173    let (sequence_info, boundary_info) = per_unit_infos(
1174        &kinds,
1175        &unit_tables,
1176        &unit_consumes,
1177        &unit_consumes_aliases,
1178        &unit_uses,
1179        &unit_flattened,
1180        (&layout, &mut contract_diff),
1181    );
1182
1183    let architecture_facts =
1184        crate::architecture_facts::architecture_facts(&crate::architecture_facts::FactInputs {
1185            parsed: &parsed,
1186            groups: &groups,
1187            test_groups: &test_groups,
1188            kinds: &kinds,
1189            unit_tables: &unit_tables,
1190            unit_consumes: &unit_consumes,
1191            unit_consumes_aliases: &unit_consumes_aliases,
1192            unit_flattened: &unit_flattened,
1193            callees: &unit_callees,
1194        });
1195
1196    let mut doc_scope: HashMap<String, Vec<String>> = HashMap::new();
1197    for name in unit_sources.keys() {
1198        let mut scope = vec![name.clone()];
1199        scope.extend(unit_uses.get(name).cloned().unwrap_or_default());
1200        scope.extend(unit_consumes.get(name).cloned().unwrap_or_default());
1201        doc_scope.insert(name.clone(), scope);
1202    }
1203
1204    crate::phase_timing::finish();
1205    ProjectAnalysis {
1206        snapshots,
1207        errors: errors.into_all(),
1208        index,
1209        hints: hints.take_files(),
1210        locals: locals.take_files(),
1211        expr_types: exprs.take_files(),
1212        ty_intern: Arc::clone(tys),
1213        capability_paths: requirements.take_paths(),
1214        requirements: requirements.take_files(),
1215        unit_sources,
1216        sequence_info,
1217        architecture_facts,
1218        boundary_info,
1219        doc_scope,
1220        contract_diff,
1221    }
1222}
1223
1224/// The whole-program checks that run after the per-unit checks, each only on an
1225/// otherwise-clean program, at the point `run_checks` runs them.
1226#[allow(clippy::too_many_arguments)]
1227fn phase_clean_program_checks(
1228    parsed: &[ParsedFile],
1229    groups: &BTreeMap<String, Vec<usize>>,
1230    kinds: &BTreeMap<String, UnitKind>,
1231    unit_tables: &HashMap<String, crate::symbols::UnitTable>,
1232    unit_consumes: &HashMap<String, Vec<String>>,
1233    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
1234    unit_flattened: &HashMap<String, HashMap<String, String>>,
1235    unit_callees: &project_model::UnitCallees,
1236    errors: &mut ErrorSink,
1237) {
1238    // On the bundle target, a context's required capability with no provider
1239    // once the bundle has a composition root (`compose.ts`), at the same point
1240    // `run_checks` raises it and on the same otherwise-clean program. Unlike
1241    // the Workers form, this one is live here: this entry point analyses as
1242    // `BuildTarget::Bundle`.
1243    project_model::phase_bundle_composition_unprovided(
1244        project_model::BuildTarget::Bundle,
1245        parsed,
1246        groups,
1247        kinds,
1248        unit_consumes,
1249        unit_consumes_aliases,
1250        unit_tables,
1251        unit_callees,
1252        unit_flattened,
1253        errors,
1254    );
1255
1256    // v0.19 (decisions 0017/0024), P5.3: platform-lock enforcement — closes
1257    // category 5 of this module's own residual-gap accounting. Inherited from
1258    // the now-deleted `analyse_project_with`'s own hardcoded
1259    // `Platform::default()` (Cloudflare) and `BuildTarget::Bundle`:
1260    // `bynk.cloudflare` is the only
1261    // platform-native unit that exists, and it matches the default
1262    // selection, so `lock_violation` can never fire here, for any project
1263    // (see `bynk-lsp/tests/analysis_residual_gap.rs`'s
1264    // `platform_lock_diagnostic_stays_absent`) — this call closes the
1265    // category structurally (R3.5), not observably.
1266    //
1267    // Cost (review #1133): a full provider-closure walk per context, same
1268    // shape as `run_checks`'s own gate, for a diagnostic that is provably
1269    // dead here. `collect_given_closure` is also unmemoised — a
1270    // diamond-shaped provider graph re-walks shared subtrees, so this is
1271    // worse than linear in the closure's depth, not just wasted. Same
1272    // trade-off and same "worth profiling if it ever shows up" note as the
1273    // schema-registry reconciliation in
1274    // [`analyse_project_inner`].
1275    if errors.is_empty() {
1276        project_model::phase_platform_lock(
1277            project_model::BuildTarget::Bundle,
1278            Platform::default(),
1279            parsed,
1280            groups,
1281            kinds,
1282            unit_tables,
1283            unit_consumes,
1284            unit_consumes_aliases,
1285            unit_flattened,
1286            &bynk_project::worker_groups::WorkerGroups::new(),
1287            errors,
1288        );
1289    }
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294    use crate::testkit::analyse;
1295
1296    const MONEY: &str = "commons demo.money\n\ntype Cents = Int where NonNegative\n";
1297
1298    const PAYMENT: &str = "context demo.payment\n\n\
1299exports transparent { Receipt }\n\n\
1300type Receipt = { id: String }\n\n\
1301service authorise {\n  on call(id: String) -> Effect[Result[Receipt, Int]] by Caller {\n    Ok(Receipt { id: id })\n  }\n}\n";
1302
1303    const CHECKOUT: &str = "context demo.checkout\n\n\
1304uses demo.money\n\nconsumes demo.payment\n\n\
1305fn price() -> Cents { 100 }\n\n\
1306service pay {\n  on call(id: String) -> Effect[Result[Receipt, Int]] by Caller {\n    demo.payment.authorise(id)\n  }\n}\n";
1307
1308    #[test]
1309    fn a_consuming_context_checks_clean_against_its_uses_and_consumes() {
1310        let a = analyse(&[
1311            ("demo/money.bynk", MONEY),
1312            ("demo/payment.bynk", PAYMENT),
1313            ("demo/checkout.bynk", CHECKOUT),
1314        ]);
1315        a.assert_clean();
1316        assert_eq!(
1317            a.type_at("demo/checkout.bynk", "demo.payment.authorise(id)"),
1318            "Effect[Result[Receipt, Int]]"
1319        );
1320    }
1321
1322    #[test]
1323    fn doc_scope_is_the_unit_then_its_uses_then_its_consumes() {
1324        let a = analyse(&[
1325            ("demo/money.bynk", MONEY),
1326            ("demo/payment.bynk", PAYMENT),
1327            ("demo/checkout.bynk", CHECKOUT),
1328        ]);
1329        assert_eq!(
1330            a.analysis.doc_scope["demo.checkout"],
1331            ["demo.checkout", "demo.money", "demo.payment"]
1332        );
1333        assert_eq!(a.analysis.doc_scope["demo.money"], ["demo.money"]);
1334    }
1335
1336    #[test]
1337    fn unit_sources_name_each_unit_s_own_files_and_no_synthetic_unit() {
1338        let a = analyse(&[("demo/money.bynk", MONEY), ("demo/payment.bynk", PAYMENT)]);
1339        let mut units: Vec<&str> = a.analysis.unit_sources.keys().map(String::as_str).collect();
1340        units.sort();
1341        assert_eq!(units, ["demo.money", "demo.payment"]);
1342        assert!(a.analysis.unit_sources["demo.money"][0].ends_with("demo/money.bynk"));
1343    }
1344
1345    #[test]
1346    fn sequence_and_boundary_info_cover_contexts_only() {
1347        let a = analyse(&[
1348            ("demo/money.bynk", MONEY),
1349            ("demo/payment.bynk", PAYMENT),
1350            ("demo/checkout.bynk", CHECKOUT),
1351        ]);
1352        for info in [
1353            a.analysis.sequence_info.keys().collect::<Vec<_>>(),
1354            a.analysis.boundary_info.keys().collect::<Vec<_>>(),
1355        ] {
1356            let mut units: Vec<&str> = info.into_iter().map(String::as_str).collect();
1357            units.sort();
1358            assert_eq!(units, ["demo.checkout", "demo.payment"]);
1359        }
1360    }
1361
1362    #[test]
1363    fn a_broken_unit_does_not_stop_an_independent_unit_from_checking() {
1364        let a = analyse(&[
1365            ("demo/money.bynk", MONEY),
1366            (
1367                "demo/broken.bynk",
1368                "commons demo.broken\n\nfn f() -> Int { \"not an int\" }\n",
1369            ),
1370            (
1371                "demo/fine.bynk",
1372                "commons demo.fine\n\nuses demo.money\n\nfn price() -> Cents { 100 }\n",
1373            ),
1374        ]);
1375        assert!(
1376            a.analysis.errors.iter().all(|e| e
1377                .source_path
1378                .as_deref()
1379                .is_some_and(|p| p.ends_with("demo/broken.bynk"))),
1380            "only the broken unit reports:\n{}",
1381            a.render()
1382        );
1383        assert_eq!(a.type_at("demo/fine.bynk", "100"), "Cents");
1384    }
1385
1386    #[test]
1387    fn every_file_read_is_snapshotted_clean_or_not() {
1388        let a = analyse(&[
1389            ("demo/money.bynk", MONEY),
1390            (
1391                "demo/broken.bynk",
1392                "commons demo.broken\n\nfn f() -> Int { \"x\" }\n",
1393            ),
1394        ]);
1395        let mut paths: Vec<&std::path::Path> = a
1396            .analysis
1397            .snapshots
1398            .iter()
1399            .map(|(p, _)| p.as_path())
1400            .collect();
1401        paths.sort();
1402        assert_eq!(paths.len(), 2, "{paths:?}");
1403        assert!(paths[0].ends_with("demo/broken.bynk") && paths[1].ends_with("demo/money.bynk"));
1404    }
1405}