bynk_ide/lib.rs
1//! Bynk's IDE/LSP analysis surface.
2//!
3//! The non-bailing diagnostics the language server consumes — single-file
4//! ([`diagnose`]) and whole-project ([`diagnose_project_with`], with
5//! [`diagnose_project`] the single-tree convenience) — plus the result
6//! types ([`Diagnostic`], [`FileDiagnostics`], [`ProjectDiagnostics`]). These
7//! are *queries* over the captured tables produced during analysis (the binding
8//! index, inlay hints, expression types, locals — all in `bynk-check`); the
9//! project analysis itself ([`bynk_check::analysis::analyse_project`]) is the
10//! non-bailing counterpart to `compile_project`.
11//!
12//! Extracted from `bynkc` as slice 5 of the crate-decomposition track over
13//! `bynk-syntax` + `bynk-check` + `bynk-emit` (P4.2, #1122: this crate no
14//! longer depends on `bynk-emit` at all — it reaches `bynk-check` and
15//! `bynk-project` directly). Behaviour is unchanged; the
16//! language server (`bynk-lsp`) depends on this crate directly instead of the
17//! whole compiler.
18
19// The README's `rust` examples are compiled (and, unless marked `no_run`, run)
20// as doctests, so they cannot rot (#1645). `cfg(doctest)` keeps this item out of
21// every build and out of the docs.rs front page, which the `//!` docs above own.
22#[cfg(doctest)]
23#[doc = include_str!("../README.md")]
24struct ReadmeDoctests;
25
26use std::collections::HashMap;
27use std::path::{Path, PathBuf};
28
29use bynk_check::{checker, expr_types, hints, index, locals, requirements, resolver};
30use bynk_syntax::error::{CompileError, Severity};
31use bynk_syntax::{ast, lexer, parser};
32
33/// #855: same rationale as [`ContextSequenceInfo`] above — a plain
34/// re-export, since `ContextBoundaryInfo`'s fields are already
35/// IDE-appropriate as-is.
36pub use bynk_check::analysis::ContextBoundaryInfo;
37/// #846: re-exported rather than left as a raw `bynk_check::analysis` path —
38/// `bynk-lsp` links `bynk-ide`/`bynk-check`/`bynk-syntax` directly and
39/// deliberately does not depend on `bynk-emit` (the whole-compiler crate);
40/// see `bynk-lsp/Cargo.toml`'s dependency comment. Unlike `Roots`/
41/// `AnalysisRoots` (which the IDE layer re-shapes because the raw type
42/// carries build-only concerns), `ContextSequenceInfo`'s fields are already
43/// IDE-appropriate as-is, so this is a plain re-export rather than a lowering.
44pub use bynk_check::analysis::ContextSequenceInfo;
45pub use bynk_check::architecture_facts::{ArchitectureFacts, DeliveryKind, MemberKind};
46pub use bynk_project::LabelFile;
47/// #2081: how a caller hands [`diagnose_project_with`] the project's
48/// `bynk.schema.lock` (ADR 0321's type, shared with the build).
49pub use bynk_project::SchemaLock;
50/// #2207: a workspace root groups projects and isn't one itself, so the
51/// language server never analyses it as a project.
52pub use bynk_project::is_workspace_root;
53
54pub mod agent_effects;
55/// #2220: the agent state model lives in `bynk-check`, shared with the
56/// checker; re-exported here so existing paths keep working.
57pub use bynk_check::agent_state;
58pub mod architecture;
59pub mod capability_path;
60pub mod completion;
61pub mod doc_link_urls;
62pub mod documentation;
63mod duration_completion;
64pub mod first_party_docs;
65pub mod hover;
66pub mod index_queries;
67pub mod locals_nav;
68pub mod packages;
69pub mod sequence;
70pub mod signature_help;
71pub mod symbols;
72pub mod wire_contract;
73
74/// One diagnostic produced from a recovery-mode compile of a single file.
75#[derive(Debug, Clone)]
76pub struct Diagnostic {
77 pub error: CompileError,
78 pub severity: Severity,
79 /// The file each of `error.labels` lies in, index for index, as
80 /// [`bynk_project::AttributedError::label_files`] says — a label in a
81 /// sibling file belongs to that file's URI, not this diagnostic's. Empty
82 /// (every label in this file) for a single-file diagnosis.
83 pub label_files: Vec<LabelFile>,
84}
85
86impl Diagnostic {
87 /// The file `error.labels[index]` lies in.
88 pub fn label_file(&self, index: usize) -> &LabelFile {
89 self.label_files.get(index).unwrap_or(&LabelFile::Primary)
90 }
91}
92
93/// Best-effort single-file compilation that always returns diagnostics.
94///
95/// Used by the LSP server: lex → parse-with-recovery → resolve → check, with
96/// each phase accumulating its diagnostics. The returned `SourceUnit` is
97/// `Some` whenever the parser produced one (which is true for any file with a
98/// recognisable header, even if individual items failed). Resolve and check
99/// run only when both the lexer and parser produced a unit; their errors are
100/// added to the same diagnostic list.
101///
102/// The TypeScript output is intentionally not produced here — the LSP only
103/// needs diagnostics; the CLI uses `compile` / `compile_project`.
104pub fn diagnose(source: &str) -> Vec<Diagnostic> {
105 let mut diagnostics = Vec::new();
106 // #2807: the lexer recovers past a bad character or literal, so one lexical
107 // error no longer blanks the file's other diagnostics.
108 let (tokens, lex_errors) = lexer::tokenize_recovering(source);
109 let parser::Recovered {
110 units,
111 errors: parse_errors,
112 broken_decl_names,
113 } = parser::parse_units_recovering(&tokens, source);
114 let parse_errors = lexer::without_lex_echoes(&lex_errors, &tokens, parse_errors);
115 for e in lex_errors {
116 diagnostics.push(Diagnostic {
117 severity: Severity::for_error(&e),
118 error: e,
119 label_files: Vec::new(),
120 });
121 }
122 let unit_opt = units.into_iter().next();
123 for e in parse_errors {
124 diagnostics.push(Diagnostic {
125 severity: Severity::for_error(&e),
126 error: e,
127 label_files: Vec::new(),
128 });
129 }
130 let Some(unit) = unit_opt else {
131 return diagnostics;
132 };
133 // Resolution and checking are only well-defined for self-contained
134 // commons units in single-file mode — contexts go through compile_project
135 // which has the cross-file machinery. Match the same restriction here.
136 if let ast::SourceUnit::Commons(mut c) = unit {
137 // #3445: constants named by literal-only annotation arguments, resolved.
138 bynk_check::annotation_consts::resolve_single_file(&mut c);
139 let push = |diagnostics: &mut Vec<Diagnostic>, errs: Vec<CompileError>| {
140 diagnostics.extend(errs.into_iter().map(|e| Diagnostic {
141 severity: Severity::for_error(&e),
142 error: e,
143 label_files: Vec::new(),
144 }));
145 };
146 // #1663 (Decision A): a resolve error no longer stops the checker. It
147 // still checks every declaration; its diagnostics in a declaration the
148 // resolver rejected are echoes and are dropped.
149 let item_spans: Vec<_> = c.items.iter().map(|i| i.span()).collect();
150 let (resolved, resolve_errors) = resolver::resolve_recovering(c);
151 if resolve_errors.is_empty()
152 && let Err(errs) = resolver::resolve_file(&resolved)
153 {
154 push(&mut diagnostics, errs);
155 }
156 // #1663 (Decision B): an unknown name that is a declaration the parser
157 // skipped is not reported again; it still rejects its declaration.
158 let (shown, _hidden) =
159 resolver::split_broken_decl_echoes(resolve_errors.clone(), &broken_decl_names);
160 push(&mut diagnostics, shown);
161 // ADR 0117: a clean check may still carry non-failing warnings
162 // (`Ok` now), so surface those too — not only the `Err` path.
163 // #1710: the checker reports some echoes of a skipped declaration
164 // under its own codes (a method, a capability, an actor), so its
165 // diagnostics are split the same way.
166 let unechoed = |errs| resolver::split_broken_decl_echoes(errs, &broken_decl_names).0;
167 match checker::check(resolved) {
168 Ok(typed) => push(&mut diagnostics, unechoed(typed.warnings)),
169 Err(errs) => push(
170 &mut diagnostics,
171 unechoed(resolver::without_resolve_echoes(
172 errs,
173 &resolve_errors,
174 &item_spans,
175 )),
176 ),
177 }
178 }
179 diagnostics
180}
181
182/// Per-file diagnostics from a whole-project analysis.
183/// v0.24 (ADR 0052): `text` is the **analysed snapshot** — positions must
184/// convert against it, not a newer buffer (the analyse→publish window is real).
185pub struct FileDiagnostics {
186 /// Project-root-relative source path.
187 pub source_path: PathBuf,
188 /// The exact text that was analysed (overlay or disk).
189 pub text: String,
190 pub diagnostics: Vec<Diagnostic>,
191}
192
193/// v0.24: the result of [`diagnose_project`]. Every discovered file appears
194/// in `files` — clean files with an empty list — so a consumer can clear
195/// stale diagnostics. `unattributed` holds project-level diagnostics with
196/// no single owning file (group/cycle/directory validations).
197pub struct ProjectDiagnostics {
198 pub files: Vec<FileDiagnostics>,
199 pub unattributed: Vec<Diagnostic>,
200 /// v0.25 (ADR 0053): the project-wide binding index — every in-scope
201 /// symbol's definition and reference sites, spans against the analysed
202 /// snapshots in `files`.
203 pub index: index::ProjectIndex,
204 /// v0.27 (ADR 0056): per-file inferred-type inlay hints — `(binding-name
205 /// span, label)`, span-ordered, spans against the analysed snapshots.
206 pub hints: hints::FileHints,
207 /// v0.30.2 (ADR 0063): per-file expression types — `(expr span, Ty)`,
208 /// for `.`-member completion's receiver typing. A file with errors still
209 /// carries the best-effort partial types of its other expressions
210 /// (ADR 0094, which lifted ADR 0063's clean-file ceiling).
211 pub expr_types: expr_types::FileExprTypes,
212 /// T3.6b (R4.1): the intern table `expr_types`' `TyId`s resolve against —
213 /// one per analysis, shared across every unit it checked.
214 pub ty_intern: std::sync::Arc<bynk_check::checker::Types>,
215 /// v0.31 (ADR 0064): per-file local bindings with scope ranges, for the
216 /// scope-at-offset query backing locals completion + navigation.
217 pub locals: locals::FileLocals,
218 /// v0.99: per-file capability-requirement ledger — every capability-consuming
219 /// site with its provenance, driving the ghost `given` inlay hint and hover.
220 pub requirements: requirements::FileRequirements,
221 /// #2469: per-file capability paths behind the `given` hover and the
222 /// "Show capability path" action.
223 pub capability_paths: bynk_check::capability_paths::FileCapabilityPaths,
224 /// Slice 6b (ADR 0095): qualified unit name → its project source file(s),
225 /// in discovery order — the unit→file map backing document links and
226 /// consumed-context navigation. Synthetic units excluded; empty on a bail.
227 pub unit_sources: HashMap<String, Vec<PathBuf>>,
228 /// #846: qualified context/adapter unit name → the cross-context/agent
229 /// tables the sequence-diagram query classifies handler calls against.
230 /// See `bynk_check::analysis::ProjectAnalysis::sequence_info`.
231 pub sequence_info: HashMap<String, ContextSequenceInfo>,
232 /// #3583: see `bynk_check::analysis::ProjectAnalysis::architecture_facts`.
233 pub architecture_facts: bynk_check::architecture_facts::ArchitectureFacts,
234 /// #855: qualified context/adapter unit name → the combined type table
235 /// and service/agent tables the wire-contract peek resolves a handler's
236 /// boundary shape and cross-context hash against.
237 /// See `bynk_check::analysis::ProjectAnalysis::boundary_info`.
238 pub boundary_info: HashMap<String, ContextBoundaryInfo>,
239 /// #848: qualified unit name → its doc-comment intra-doc-link search
240 /// order — itself first, then its `uses` targets, then its `consumes`
241 /// targets. See `bynk_check::analysis::ProjectAnalysis::doc_scope`.
242 pub doc_scope: HashMap<String, Vec<String>>,
243 /// #2467: the boundary changes since `bynk.schema.lock` and the contract
244 /// hashes provided now. See `bynk_check::analysis::ContractDiff`.
245 pub contract_diff: bynk_check::analysis::ContractDiff,
246}
247
248/// Slice A: which trees a project's analysis walks.
249///
250/// `bynk-ide` owns this rather than re-exporting `bynk_project::Roots`:
251/// this crate is the IDE-facing published surface, and `Roots` carries
252/// `tests_prefix` semantics an IDE caller has no business knowing. The lowering
253/// is a few lines and it is the seam where the LSP's needs and the compiler's
254/// can diverge later without a break.
255#[derive(Debug, Clone)]
256pub enum AnalysisRoots {
257 /// One tree, walked as a single root, with no manifest consulted — the
258 /// pre-slice-A behaviour and what [`diagnose_project`] still means.
259 SingleTree(PathBuf),
260 /// A manifest-backed project rooted here: `bynk.toml`'s `[paths]
261 /// include`/`exclude` decide the trees, exactly as `bynk` reads them.
262 /// Mirrors `bynk-driver`'s `project_options` — the compiler's own choice.
263 Project(PathBuf),
264}
265
266impl AnalysisRoots {
267 /// Content-ownership track (#1086) slice 2: `overlay` threads into
268 /// `try_read_project_paths_with` (already overlay-aware, already `pub`)
269 /// instead of the disk-only `read_project_paths`, so an unsaved edit to
270 /// `bynk.toml` itself — not just to the `.bynk` sources it names — is
271 /// visible to the `Project` variant's manifest read. Mirrors `343b2482`'s
272 /// CLI-side fix (`bynk-driver`'s `project_options`) on the LSP side.
273 ///
274 /// `discover_files` (below) threads `overlay` straight through now (slice
275 /// 5 correction, below) — both it and `diagnose_project_with` need the
276 /// same real-or-overlaid `bynk.toml` content to resolve the same roots.
277 ///
278 /// Content-ownership track (#1086) slice 5 correction (found only under
279 /// implementation): reading `bynk.toml` through `overlay` alone used to
280 /// still reach the real on-disk manifest on a miss, because `bynk-emit`'s
281 /// `read_source` fell back to a real disk read. Slice 5 deleted that
282 /// fallback — but R2.3 forbids this crate from touching the filesystem
283 /// itself to restore it here, so it does **not** grow a fallback of its
284 /// own; every caller (`bynk-lsp`'s `sweep_project_content`,
285 /// `bynk-testkit::read_project_sources`) now reads `bynk.toml` itself,
286 /// above the driver boundary, and includes it in the `overlay`/content
287 /// map it hands in — the same "process edge constructs `Sources`" R2.3
288 /// already requires of every `.bynk` file. `lower` stays exactly what its
289 /// slice-2 doc above describes: caller's overlay, nothing else.
290 fn lower(&self, overlay: &HashMap<PathBuf, String>) -> bynk_project::Roots {
291 match self {
292 AnalysisRoots::SingleTree(root) => bynk_project::Roots::Single(root.clone()),
293 AnalysisRoots::Project(root) => bynk_project::Roots::Split {
294 project_root: root.clone(),
295 paths: bynk_project::try_read_project_paths_with(root, overlay)
296 .unwrap_or_else(|_| bynk_project::ProjectPaths::conventional(root)),
297 },
298 }
299 }
300
301 /// The project root every analysed `source_path` is relative to. For
302 /// `SingleTree` that is the tree itself (identity ≡ tree-relative, ADR
303 /// 0198).
304 pub fn project_root(&self) -> &Path {
305 match self {
306 AnalysisRoots::SingleTree(r) | AnalysisRoots::Project(r) => r,
307 }
308 }
309}
310
311/// Slice A: the `.bynk` files these roots contain — the same discovery
312/// `compile_project` performs, `exclude` and the `out`/`node_modules` caches
313/// honoured. For enumerating a project's units without analysing it.
314///
315/// `overlay` is consulted only for `bynk.toml` itself (via `lower`) — an
316/// `AnalysisRoots::Project`'s `[paths] include`/`exclude` decide what gets
317/// walked, so the caller must include a real-or-overlaid manifest entry for
318/// a non-conventional layout to enumerate correctly (content-ownership
319/// track (#1086) slice 5: this crate stays disk-free per R2.3, so it cannot
320/// fall back to reading `bynk.toml` itself on a miss).
321pub fn discover_files(roots: &AnalysisRoots, overlay: &HashMap<PathBuf, String>) -> Vec<PathBuf> {
322 bynk_project::discover_project_files(&roots.lower(overlay))
323}
324
325/// #302: the qualified name a file moved from `old_rel` to `new_rel` should
326/// now declare, preserving whichever single-file/multi-file arrangement
327/// `old_rel` used to satisfy against `old_name` — for the LSP's
328/// `workspace/willRenameFiles` handler.
329pub fn renamed_unit_name(old_rel: &Path, old_name: &str, new_rel: &Path) -> Option<String> {
330 bynk_project::renamed_unit_name(old_rel, old_name, new_rel)
331}
332
333/// v0.24 (ADR 0052): non-bailing, overlay-aware, file-attributed project
334/// diagnostics — the LSP analysis entry point, distinct from
335/// `compile_project` (which bails and emits). `overlay` maps
336/// canonicalised absolute paths to buffer text layered over disk reads.
337///
338/// Slice A: this is the **single-tree convenience** over
339/// [`diagnose_project_with`] — it walks `root` as one tree and consults no
340/// manifest, which is what every caller handing in a fixture root already
341/// means. A manifest-backed project wants
342/// `diagnose_project_with(&AnalysisRoots::Project(root), …)`.
343///
344/// #2081: it passes [`SchemaLock::Off`], so it never reconciles events
345/// against `bynk.schema.lock`. Every caller is a test or a test kit; the
346/// language server calls [`diagnose_project_with`] with the lock it read.
347pub fn diagnose_project(root: &Path, overlay: &HashMap<PathBuf, String>) -> ProjectDiagnostics {
348 diagnose_project_with(
349 &AnalysisRoots::SingleTree(root.to_path_buf()),
350 overlay,
351 &SchemaLock::Off,
352 )
353}
354
355/// Slice A: project diagnostics over manifest-resolved roots — the LSP analyses
356/// exactly the files `bynk` compiles, from the same manifest, through the same
357/// discovery.
358///
359/// Every path in the result is **project-relative** (ADR 0198), so a file is
360/// named uniquely across `include` roots.
361///
362/// `schema_lock` (#2081) is the project's `bynk.schema.lock`, read by the
363/// caller (this crate reads no disk): under [`SchemaLock::On`] events are
364/// reconciled against it, read-only, so a non-additive change is reported as
365/// `bynk check` reports it; [`SchemaLock::Off`] skips that.
366pub fn diagnose_project_with(
367 roots: &AnalysisRoots,
368 overlay: &HashMap<PathBuf, String>,
369 schema_lock: &SchemaLock,
370) -> ProjectDiagnostics {
371 diagnostics_of(bynk_check::analysis::analyse_project(
372 &roots.lower(overlay),
373 overlay,
374 schema_lock,
375 ))
376}
377
378/// [`diagnose_project_with`] reusing what `memo` kept from the previous round
379/// (#3243 S2.3b): the language server's entry point, one memo per project. The
380/// answer is exactly [`diagnose_project_with`]'s.
381pub fn diagnose_project_memoised(
382 roots: &AnalysisRoots,
383 overlay: &HashMap<PathBuf, String>,
384 schema_lock: &SchemaLock,
385 memo: &mut bynk_check::memo::AnalysisMemo,
386) -> ProjectDiagnostics {
387 diagnostics_of(bynk_check::memo::analyse_project_memoised(
388 &roots.lower(overlay),
389 overlay,
390 schema_lock,
391 memo,
392 ))
393}
394
395fn diagnostics_of(analysis: bynk_check::analysis::ProjectAnalysis) -> ProjectDiagnostics {
396 // #43: destructured (not `analysis.field`-by-field) so that a field added
397 // to `ProjectAnalysis` without a matching update *here* is a compile
398 // error (an unmentioned field in a struct pattern), not a silently
399 // stale `ProjectDiagnostics` — the fields below are one-for-one
400 // identical between the two types precisely because this site can't
401 // forget one.
402 let bynk_check::analysis::ProjectAnalysis {
403 snapshots,
404 errors,
405 index,
406 hints,
407 expr_types,
408 ty_intern,
409 locals,
410 requirements,
411 capability_paths,
412 unit_sources,
413 sequence_info,
414 architecture_facts,
415 boundary_info,
416 doc_scope,
417 contract_diff,
418 } = analysis;
419 let mut by_file: HashMap<PathBuf, Vec<Diagnostic>> = HashMap::new();
420 let mut unattributed = Vec::new();
421 for ae in errors {
422 let d = Diagnostic {
423 severity: Severity::for_error(&ae.error),
424 error: ae.error,
425 label_files: ae.label_files,
426 };
427 match ae.source_path {
428 Some(p) => by_file.entry(p).or_default().push(d),
429 None => unattributed.push(d),
430 }
431 }
432 let files = snapshots
433 .into_iter()
434 .map(|(source_path, text)| FileDiagnostics {
435 diagnostics: by_file.remove(&source_path).unwrap_or_default(),
436 source_path,
437 text,
438 })
439 .collect();
440 // Anything attributed to a path without a snapshot (defensive — should
441 // not happen) still surfaces rather than vanishing.
442 for (_, ds) in by_file {
443 unattributed.extend(ds);
444 }
445 ProjectDiagnostics {
446 files,
447 unattributed,
448 index,
449 hints,
450 requirements,
451 capability_paths,
452 expr_types,
453 ty_intern,
454 locals,
455 unit_sources,
456 sequence_info,
457 architecture_facts,
458 boundary_info,
459 doc_scope,
460 contract_diff,
461 }
462}
463
464#[cfg(test)]
465mod testkit {
466 //! In-process test helpers for this crate's own inline `#[cfg(test)]`
467 //! modules (content-ownership track, #1086, slice 4).
468 //!
469 //! This crate cannot depend on the cross-crate `bynk-testkit` (that crate
470 //! depends on `bynk-ide`, so a dev-dependency back onto it would cycle —
471 //! Cargo would instantiate two separate copies of this very crate, making
472 //! `crate::AnalysisRoots` and `bynk_ide::AnalysisRoots` distinct,
473 //! non-interchangeable types; found the hard way in slice 3, not
474 //! foreseen). So this mirrors `bynk-testkit::read_project_sources`
475 //! directly against `crate::discover_files`, the same production
476 //! discovery both use.
477 //!
478 //! An inline module, not `bynk-ide/src/testkit.rs` as a separate
479 //! `#[cfg(test)]`-gated file: `fs_below_driver`'s probe
480 //! (`xtask/src/greenfield_status.rs`) only recognises an inline
481 //! `#[cfg(test)] mod name { … }` block as test-scope — a whole file gated
482 //! by its *declaration* (`#[cfg(test)] mod testkit;` in a different file)
483 //! isn't a pattern it looks for, so a separate file's `std::fs` calls read
484 //! as production usage and moved `fs_below_driver`'s `bynk-ide` count
485 //! from 0 back to 1 (found by running `cargo xtask greenfield-status`
486 //! after the first version of this module, not anticipated).
487
488 use std::collections::HashMap;
489 use std::path::{Path, PathBuf};
490
491 /// A complete `(path, content)` map for `roots` — the direct replacement
492 /// for `diagnose_project(&root, &HashMap::new())`'s reliance on
493 /// `bynk-emit`'s disk fallback. Keyed by the literal discovered path, not
494 /// canonicalised — matching `bynk-testkit`'s own convention, itself
495 /// matching `bynk-driver`'s production `sources_for_roots` (canonicalising
496 /// broke a project-consistency check the hard way in slice 3 — see
497 /// `bynk-testkit/src/lib.rs`'s doc).
498 pub(crate) fn read_project_sources(roots: &crate::AnalysisRoots) -> HashMap<PathBuf, String> {
499 // Only ever called with `SingleTree` (below), which consults no
500 // manifest — an empty overlay is correct, not a stand-in fallback.
501 crate::discover_files(roots, &HashMap::new())
502 .into_iter()
503 .filter_map(|p| {
504 let content = std::fs::read_to_string(&p).ok()?;
505 Some((p, content))
506 })
507 .collect()
508 }
509
510 /// `diagnose_project(root, &HashMap::new())`, with a complete sources map
511 /// instead of relying on `bynk-emit`'s disk fallback to fill it in.
512 pub(crate) fn diagnose_project(root: &Path) -> crate::ProjectDiagnostics {
513 let sources = read_project_sources(&crate::AnalysisRoots::SingleTree(root.to_path_buf()));
514 crate::diagnose_project(root, &sources)
515 }
516}