Skip to main content

bynk_check/
index.rs

1//! v0.25: the project-wide binding index (ADR 0053).
2//!
3//! [`RefSink`] collects use→def edges at the resolution sites themselves —
4//! the resolver's reference walk, the checker's capability/service call
5//! dispatch, and the project driver's clause wiring — mirroring v0.24's
6//! `ErrorSink` collection-point pattern. The project pass then qualifies
7//! bare names per unit and assembles a [`ProjectIndex`]: every in-scope
8//! symbol's definition site plus all of its reference sites, binding-correct
9//! (never name-matched).
10//!
11//! In-scope symbol kinds this increment: top-level types, free `fn`s,
12//! capabilities, services, agents, and providers. Instance methods, record
13//! fields, capability op names, and local bindings are deferred (no edges
14//! are recorded for them).
15
16use std::collections::{HashMap, HashSet};
17use std::path::{Path, PathBuf};
18
19use bynk_syntax::ast::BaseType;
20use bynk_syntax::span::Span;
21
22/// The kind half of a symbol's structural key.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
24pub enum SymbolKind {
25    Type,
26    Fn,
27    Capability,
28    Service,
29    Agent,
30    Provider,
31    /// v0.36 (ADR 0069): an instance method, keyed by the compound name
32    /// `"Type.method"` in the type's defining unit. The first parent-scoped
33    /// index kind (see the v0.36 members slice).
34    Method,
35    /// v0.36 (ADR 0069, slice 2): a record field, keyed by `"Type.field"`.
36    Field,
37    /// v0.36 (ADR 0069, slice 2): a capability operation, keyed by `"Cap.op"`.
38    CapabilityOp,
39    /// v0.45: an actor declaration — a boundary contract consumed by a
40    /// handler's `by` clause.
41    Actor,
42    /// (ADR 0069 follow-on, #304): an agent handler, keyed by the compound
43    /// name `"Agent.handler"`. #3582: a service's callable handlers too — an
44    /// `on call` handler keyed `"service.call"` and an `on http` route keyed
45    /// `"service.POST /orders"` (method and path). Those are *call-only*
46    /// symbols (see [`SymbolEntry::call_only`]): they exist so call hierarchy
47    /// has a callee, and stay out of tokens, lenses, rename and workspace
48    /// symbols.
49    Handler,
50    /// A `messages <tag> { ... }` bundle, keyed by its `tag` (message-bundles
51    /// track, slice 1).
52    Messages,
53    /// #1883: an `asset name = "path"` declaration — a value of type `Asset`,
54    /// keyed by its name in the declaring unit.
55    Asset,
56    /// #2387: an `embed name = "path"` declaration — a `String` constant
57    /// holding a project file's text, keyed by its name in the declaring unit.
58    Embed,
59    /// #2617: a `const Name: Type = …` declaration — a value of its annotated
60    /// type, keyed by its name in the declaring unit.
61    Const,
62}
63
64impl SymbolKey {
65    /// #3582: how call hierarchy names a `Handler` symbol. An HTTP route is
66    /// named by method and path (`POST /orders`, as the sequence and
67    /// wire-contract models label it); any other handler keeps its key name.
68    pub fn handler_display_name(&self) -> &str {
69        match self.name.split_once('.') {
70            Some((_, route)) if self.kind == SymbolKind::Handler && route.contains(' ') => route,
71            _ => &self.name,
72        }
73    }
74}
75
76impl SymbolKind {
77    pub fn display(self) -> &'static str {
78        match self {
79            SymbolKind::Type => "type",
80            SymbolKind::Fn => "fn",
81            SymbolKind::Capability => "capability",
82            SymbolKind::Service => "service",
83            SymbolKind::Agent => "agent",
84            SymbolKind::Provider => "provider",
85            SymbolKind::Method => "method",
86            SymbolKind::Field => "field",
87            SymbolKind::CapabilityOp => "operation",
88            SymbolKind::Actor => "actor",
89            SymbolKind::Handler => "handler",
90            SymbolKind::Messages => "messages",
91            SymbolKind::Asset => "asset",
92            SymbolKind::Embed => "embed",
93            SymbolKind::Const => "constant",
94        }
95    }
96}
97
98/// Structural symbol identity (no `DefId` plumbing): the defining unit's
99/// qualified name, the declaration kind, and the declared name. Top-level
100/// names are unique within a unit, so the key is unambiguous.
101#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
102pub struct SymbolKey {
103    pub unit: String,
104    pub kind: SymbolKind,
105    pub name: String,
106}
107
108/// One recorded use→def edge, in collection-point context.
109///
110/// `unit: None` means the name resolved through the recording namespace's
111/// merged tables (local declarations + `uses` imports) and is qualified at
112/// assembly; `Some` means the resolution site already knew the defining
113/// unit (cross-context capability/service references, flattened caps).
114#[derive(Debug, Clone)]
115pub struct RefEdge {
116    /// The name-segment span (for dotted `B.Cap`, just `Cap`).
117    pub span: Span,
118    pub kind: SymbolKind,
119    pub name: String,
120    pub unit: Option<String>,
121    /// Project-relative file the span is an offset into (collection point).
122    pub file: PathBuf,
123    /// The unit whose merged namespace resolves a bare (`unit: None`) name.
124    /// For test/integration files this is the *target* unit.
125    pub namespace: Option<String>,
126    /// Display name of the enclosing top-level declaration, when known
127    /// (`"f"`, `"T.m"`, a service/provider name). Used at assembly to
128    /// re-attribute spans to the file that declares the owner — sibling-file
129    /// methods and unit-level handler tables are processed under a different
130    /// file than the one their spans index into.
131    pub owner: Option<String>,
132    /// v0.35 (ADR 0068): set only on the `Cap` of a `provides Cap = Provider`
133    /// clause (never on a `given Cap` dependency). With `owner` the provider,
134    /// this marks a capability→provider implementation edge — distinguishing
135    /// the provided capability from the provider's own `given` deps, which are
136    /// also capability refs owned by the same provider.
137    pub provides: bool,
138}
139
140/// Collection-point sink for use→def edges (the `ErrorSink` analogue).
141/// The pipeline sets the ambient file/namespace before each per-file phase;
142/// resolution sites only supply the span and target. A sink left in its
143/// default state (no file) discards edges — the single-file entry points
144/// resolve without recording.
145#[derive(Debug, Default, Clone)]
146pub struct RefSink {
147    pub edges: Vec<RefEdge>,
148    /// Synthetic namespaces (integration-test harness roots) → their `uses`
149    /// resolution order, merged with the project's `uses` table at assembly.
150    pub extra_uses: HashMap<String, Vec<String>>,
151    file: Option<PathBuf>,
152    namespace: Option<String>,
153    owner: Option<String>,
154    /// Set while processing synthetic (toolchain-injected) files: edges are
155    /// discarded — first-party units are not user-editable and out of index.
156    muted: bool,
157}
158
159impl RefSink {
160    pub fn new() -> Self {
161        Self::default()
162    }
163
164    /// Declare a synthetic namespace's `uses` resolution order (integration
165    /// harness roots are not project units, so the project's `uses` table
166    /// has no entry for them).
167    pub fn declare_namespace(&mut self, namespace: &str, uses: Vec<String>) {
168        self.extra_uses.insert(namespace.to_string(), uses);
169    }
170
171    /// Append everything `other` recorded (#3243 S2.3), in order.
172    pub fn absorb(&mut self, other: RefSink) {
173        self.edges.extend(other.edges);
174        self.extra_uses.extend(other.extra_uses);
175    }
176
177    /// Enter a per-file recording context. `namespace` is the unit whose
178    /// merged tables resolve bare names in this file (the file's own unit,
179    /// or a test file's target unit).
180    pub fn enter_file(&mut self, file: &Path, namespace: &str, muted: bool) {
181        self.file = Some(file.to_path_buf());
182        self.namespace = Some(namespace.to_string());
183        self.owner = None;
184        self.muted = muted;
185    }
186
187    /// Set the enclosing top-level declaration for subsequent edges.
188    pub fn set_owner(&mut self, owner: impl Into<String>) {
189        self.owner = Some(owner.into());
190    }
191
192    pub fn clear_owner(&mut self) {
193        self.owner = None;
194    }
195
196    /// Record an edge whose defining unit is found at assembly.
197    pub fn record(&mut self, span: Span, kind: SymbolKind, name: &str) {
198        self.push(span, kind, name, None, false);
199    }
200
201    /// Record an edge whose defining unit the resolution site already knows.
202    pub fn record_in_unit(&mut self, span: Span, kind: SymbolKind, name: &str, unit: &str) {
203        self.push(span, kind, name, Some(unit.to_string()), false);
204    }
205
206    /// v0.35 (ADR 0068): record the `Cap` of a `provides Cap = Provider` clause
207    /// — a capability reference also flagged as an implementation edge (the
208    /// owner is the provider). `unit` is `Some` for a cross-context provided
209    /// capability, `None` when it resolves at assembly.
210    pub fn record_provides(&mut self, span: Span, name: &str, unit: Option<&str>) {
211        self.push(
212            span,
213            SymbolKind::Capability,
214            name,
215            unit.map(str::to_string),
216            true,
217        );
218    }
219
220    fn push(
221        &mut self,
222        span: Span,
223        kind: SymbolKind,
224        name: &str,
225        unit: Option<String>,
226        provides: bool,
227    ) {
228        if self.muted {
229            return;
230        }
231        let Some(file) = &self.file else {
232            return; // single-file mode: no recording context.
233        };
234        self.edges.push(RefEdge {
235            span,
236            kind,
237            name: name.to_string(),
238            unit,
239            file: file.clone(),
240            namespace: self.namespace.clone(),
241            owner: self.owner.clone(),
242            provides,
243        });
244    }
245}
246
247/// One occurrence of a symbol: the file (project-relative) and the
248/// name-segment span within that file's analysed snapshot.
249#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
250pub struct SiteRef {
251    pub path: PathBuf,
252    pub span: Span,
253}
254
255/// v0.28 (ADR 0057): the Bynk-specific semantic-token modifiers recorded on
256/// a symbol at assemble time. `refined` only when a refinement is present —
257/// `type Age = Int` parses as `Refined { refinement: None }` and is a plain
258/// alias, carrying neither; `opaque` is orthogonal, so `opaque B where …`
259/// carries both. `platform_native` when the declaring unit is a platform
260/// adapter (`firstparty::platform_of` is `Some`).
261#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
262pub struct SymbolModifiers {
263    pub refined: bool,
264    pub opaque: bool,
265    pub platform_native: bool,
266}
267
268/// A symbol's definition site plus every reference site.
269#[derive(Debug, Clone, Default)]
270pub struct SymbolEntry {
271    /// The declaration's name span. `None` only transiently during assembly;
272    /// symbols without a located definition are dropped from the index.
273    pub def: Option<SiteRef>,
274    /// Sorted, deduplicated. Does not include the definition site.
275    pub refs: Vec<SiteRef>,
276    /// v0.28 (ADR 0057): semantic-token modifiers, set from the declaration.
277    pub modifiers: SymbolModifiers,
278    /// #3582: a service handler (`on call` / `on http`) — a symbol that exists
279    /// only as a call-hierarchy callee. Its definition (the `on` keyword) resolves
280    /// only through [`ProjectIndex::call_symbol_at`]; [`ProjectIndex::symbol_at`]
281    /// skips it (its call-site refs share a span with the `Service` ref), and
282    /// tokens, lenses and workspace symbols skip the symbol altogether.
283    pub call_only: bool,
284}
285
286/// v0.34 (ADR 0067): one resolved caller→callee call edge — a reference
287/// (`callee`) occurring inside a known top-level declaration (`caller`), at
288/// `site` (the callee-name span, in the caller's file). The backing data for
289/// call hierarchy: incoming calls group edges by `callee`, outgoing by
290/// `caller`. v0.36 (ADR 0069): `Fn` and `Method` callees/callers. #304:
291/// `CapabilityOp` and agent `Handler` callees/callers too — every index
292/// symbol capable of holding a call site is now a callee. #3582: service
293/// cross-context dispatch is covered as well — a `pay.charge(…)` call (plain or
294/// through a `consumes … as` alias) is an edge from the calling owner to the
295/// consumed service's `on call` `Handler` symbol, in addition to the
296/// service-level `Service` reference that Find References reads.
297#[derive(Debug, Clone, PartialEq, Eq)]
298pub struct CallEdge {
299    pub caller: SymbolKey,
300    pub callee: SymbolKey,
301    pub site: SiteRef,
302}
303
304/// v0.35 (ADR 0068): one capability→provider implementation edge — a `provides
305/// Cap = P` clause records a `Capability` reference (`capability`) whose
306/// enclosing owner is the provider (`provider`), at `site` (the capability-name
307/// span in the `provides` clause). The backing data for implementation
308/// navigation: `implementation` on a capability returns its providers' defs.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct ImplEdge {
311    pub capability: SymbolKey,
312    pub provider: SymbolKey,
313    pub site: SiteRef,
314}
315
316/// v0.129 (#259): one refined/opaque-type → builtin-base edge. A `type Email =
317/// String where …`, a plain alias `type UserId = String`, or an `opaque String`
318/// all record the builtin `base` they are declared over. The backing data for
319/// **refinement families** — every type over the same base. `ty` is the refined
320/// type's own key; its def site is `symbols[ty].def`. Unlike [`ImplEdge`] this
321/// needs no ref-resolution (the base is a builtin, the key is the def itself), so
322/// it is captured straight at the type-def walk.
323#[derive(Debug, Clone, PartialEq, Eq)]
324pub struct RefineEdge {
325    pub base: BaseType,
326    pub ty: SymbolKey,
327    /// Whether `ty` is `opaque` — its representation is hidden outside its
328    /// declaring unit, which the type hierarchy honours.
329    pub opaque: bool,
330    /// Where the base type is written in the declaration (`Int` in `type Qty =
331    /// Int where …`) — the anchor for a type-hierarchy item on the primitive.
332    pub base_site: SiteRef,
333}
334
335/// v0.28 (ADR 0057): one reference to a first-party (`bynk.*`) symbol.
336/// Tokens-only: first-party defs point at synthetic files not on disk, so
337/// these sites are **never** read by definition/rename/workspace-symbol —
338/// the v0.25 exclusion of synthetic units from `symbols` stands untouched.
339#[derive(Debug, Clone, PartialEq, Eq)]
340pub struct ForeignRef {
341    pub site: SiteRef,
342    pub kind: SymbolKind,
343    pub modifiers: SymbolModifiers,
344}
345
346/// The project-wide binding index: every in-scope symbol's definition and
347/// references, keyed structurally. Built by the v0.24 project pass in
348/// analyse mode; empty in build mode.
349#[derive(Debug, Clone, Default)]
350pub struct ProjectIndex {
351    pub symbols: HashMap<SymbolKey, SymbolEntry>,
352    /// v0.28 (ADR 0057): references to first-party symbols, sorted by
353    /// (path, span), deduplicated — read only by the semantic-tokens
354    /// producer (see [`ForeignRef`]).
355    pub foreign_refs: Vec<ForeignRef>,
356    /// v0.34 (ADR 0067): caller→callee call edges (see [`CallEdge`] for which
357    /// kinds are covered), sorted by (caller, callee, site). The
358    /// call-hierarchy graph.
359    pub calls: Vec<CallEdge>,
360    /// v0.35 (ADR 0068): capability→provider implementation edges, sorted by
361    /// (capability, provider, site). The implementation-nav graph (see
362    /// [`ImplEdge`]).
363    pub impls: Vec<ImplEdge>,
364    /// v0.129 (#259): refined/opaque-type → builtin-base edges, sorted by
365    /// (base name, type key). The refinement-family graph (see [`RefineEdge`]).
366    pub refinements: Vec<RefineEdge>,
367}
368
369impl ProjectIndex {
370    /// The symbol whose definition or reference name-segment contains
371    /// `offset` within `path`. Spans are half-open; name segments never
372    /// overlap, so the first hit is the only hit.
373    pub fn symbol_at(&self, path: &Path, offset: usize) -> Option<(&SymbolKey, &SiteRef)> {
374        self.symbol_at_impl(path, offset, false)
375    }
376
377    /// #3582: [`symbol_at`](Self::symbol_at), but a call-only service handler's
378    /// definition (its `on` keyword) resolves too. Call hierarchy only.
379    pub fn call_symbol_at(&self, path: &Path, offset: usize) -> Option<(&SymbolKey, &SiteRef)> {
380        self.symbol_at_impl(path, offset, true)
381    }
382
383    fn symbol_at_impl(
384        &self,
385        path: &Path,
386        offset: usize,
387        include_call_only: bool,
388    ) -> Option<(&SymbolKey, &SiteRef)> {
389        for (key, entry) in &self.symbols {
390            if entry.call_only && !include_call_only {
391                continue;
392            }
393            if let Some(def) = &entry.def
394                && def.path == path
395                && def.span.range().contains(&offset)
396            {
397                return Some((key, def));
398            }
399            if entry.call_only {
400                continue; // its refs duplicate the `Service` ref's span
401            }
402            for site in &entry.refs {
403                if site.path == path && site.span.range().contains(&offset) {
404                    return Some((key, site));
405                }
406            }
407        }
408        None
409    }
410
411    /// Definition + references for `key`, definition first.
412    pub fn sites(&self, key: &SymbolKey) -> Vec<&SiteRef> {
413        let Some(entry) = self.symbols.get(key) else {
414            return Vec::new();
415        };
416        entry.def.iter().chain(entry.refs.iter()).collect()
417    }
418
419    /// v0.34 (ADR 0067): call edges whose callee is `key` — its callers.
420    pub fn calls_into<'a>(&'a self, key: &SymbolKey) -> impl Iterator<Item = &'a CallEdge> {
421        let key = key.clone();
422        self.calls.iter().filter(move |e| e.callee == key)
423    }
424
425    /// v0.34 (ADR 0067): call edges whose caller is `key` — what it calls.
426    pub fn calls_from<'a>(&'a self, key: &SymbolKey) -> impl Iterator<Item = &'a CallEdge> {
427        let key = key.clone();
428        self.calls.iter().filter(move |e| e.caller == key)
429    }
430
431    /// v0.35 (ADR 0068): impl edges whose capability is `key` — its providers.
432    pub fn impls_of<'a>(&'a self, key: &SymbolKey) -> impl Iterator<Item = &'a ImplEdge> {
433        let key = key.clone();
434        self.impls.iter().filter(move |e| e.capability == key)
435    }
436
437    /// v0.129 (#259): the builtin base a `Type` `key` refines (a refined/opaque
438    /// type or plain alias), or `None` for a record/sum/unknown key.
439    pub fn refined_base(&self, key: &SymbolKey) -> Option<BaseType> {
440        self.refinements
441            .iter()
442            .find(|e| &e.ty == key)
443            .map(|e| e.base)
444    }
445
446    /// v0.129 (#259): the refine edges over builtin `base` — its refinement
447    /// family (every refined/opaque type, and plain alias, declared over it).
448    pub fn refinements_over(&self, base: BaseType) -> impl Iterator<Item = &RefineEdge> {
449        self.refinements.iter().filter(move |e| e.base == base)
450    }
451
452    /// Structural equality after mapping `self`'s sites through `remap`
453    /// and renaming `from` to `to_name` — the rename capture/escape
454    /// validator. `remap` converts a pre-edit site to its post-edit
455    /// position (rename edits shift spans within edited files).
456    pub fn equals_modulo_rename(
457        &self,
458        post: &ProjectIndex,
459        from: &SymbolKey,
460        to_name: &str,
461        mut remap: impl FnMut(&SiteRef) -> SiteRef,
462    ) -> bool {
463        if self.symbols.len() != post.symbols.len() {
464            return false;
465        }
466        for (key, entry) in &self.symbols {
467            let expect_key = if key == from {
468                SymbolKey {
469                    unit: key.unit.clone(),
470                    kind: key.kind,
471                    name: to_name.to_string(),
472                }
473            } else {
474                key.clone()
475            };
476            let Some(post_entry) = post.symbols.get(&expect_key) else {
477                return false;
478            };
479            let expect_def = entry.def.as_ref().map(&mut remap);
480            if expect_def != post_entry.def {
481                return false;
482            }
483            let mut expect_refs: Vec<SiteRef> = entry.refs.iter().map(&mut remap).collect();
484            expect_refs.sort();
485            let mut post_refs = post_entry.refs.clone();
486            post_refs.sort();
487            if expect_refs != post_refs {
488                return false;
489            }
490        }
491        true
492    }
493}
494
495/// Assembles the index from per-file declaration walks plus the sink's
496/// edges. Built by the project pass, which alone knows unit membership,
497/// `uses` targets, and which file declares each top-level item.
498#[derive(Debug, Default)]
499pub struct IndexBuilder {
500    /// (unit, kind, name) → definition site + modifiers.
501    defs: HashMap<SymbolKey, (SiteRef, SymbolModifiers)>,
502    /// v0.28 (ADR 0057): first-party (`bynk.*`) symbols — kind + modifiers
503    /// only, no usable def site (synthetic files are not on disk). Edges
504    /// qualifying here route into [`ProjectIndex::foreign_refs`].
505    first_party_defs: HashMap<SymbolKey, SymbolModifiers>,
506    /// #3582: keys registered through [`IndexBuilder::add_call_only_def`].
507    call_only: HashSet<SymbolKey>,
508    /// (unit, owner display name) → declaring file, for span re-attribution.
509    /// Includes methods (`"T.m"`), which are not index symbols.
510    owner_files: HashMap<(String, String), PathBuf>,
511    /// v0.34 (ADR 0067): (unit, owner display name) → the owner's symbol key,
512    /// for resolving a call edge's caller. Populated by every `add_def`, so
513    /// any index symbol capable of enclosing a call site (`Fn`, `Method`,
514    /// `Service`, `Agent`, `Provider`, …) is a valid caller; an owner
515    /// registered only via `add_owner` (attribution-only, no symbol) is not.
516    owner_keys: HashMap<(String, String), SymbolKey>,
517    /// unit → `uses` targets, resolution order.
518    uses: HashMap<String, Vec<String>>,
519    /// unit → `consumes` targets — bare names can also resolve to a consumed
520    /// unit's exported types (the consumer's merged table layers them after
521    /// `uses` imports).
522    consumes: HashMap<String, Vec<String>>,
523    /// #2887: unit → alias → the consumed unit and the exported type the alias
524    /// (`consumes U { T as Alias }`) names, so a reference to the alias reaches
525    /// the real declaration.
526    type_aliases: HashMap<String, HashMap<String, (String, String)>>,
527    /// v0.129 (#259): refined/opaque-type → builtin-base edges, accumulated at
528    /// the type-def walk (no ref-resolution needed). Assembled in [`build`].
529    refinements: Vec<RefineEdge>,
530}
531
532impl IndexBuilder {
533    pub fn add_def(
534        &mut self,
535        unit: &str,
536        kind: SymbolKind,
537        name: &str,
538        site: SiteRef,
539        modifiers: SymbolModifiers,
540    ) {
541        self.owner_files
542            .insert((unit.to_string(), name.to_string()), site.path.clone());
543        let key = SymbolKey {
544            unit: unit.to_string(),
545            kind,
546            name: name.to_string(),
547        };
548        self.owner_keys
549            .insert((unit.to_string(), name.to_string()), key.clone());
550        self.defs.insert(key, (site, modifiers));
551    }
552
553    /// #3582: register a service handler as a call-only symbol (see
554    /// [`SymbolEntry::call_only`]). Like a leaf def it takes over no owner entry:
555    /// the enclosing owner of a call inside it stays the service.
556    pub fn add_call_only_def(&mut self, unit: &str, name: &str, site: SiteRef) {
557        let key = SymbolKey {
558            unit: unit.to_string(),
559            kind: SymbolKind::Handler,
560            name: name.to_string(),
561        };
562        self.call_only.insert(key.clone());
563        self.defs.insert(key, (site, SymbolModifiers::default()));
564    }
565
566    /// #1883: register a symbol that can never enclose a call site (an
567    /// `asset`) — its def only, with no owner entry. Owners are keyed by
568    /// (unit, name) without the kind, so registering one here would let an
569    /// asset take over a same-named service's or agent's owner entry and
570    /// re-attribute that owner's refs to the asset's file.
571    pub fn add_leaf_def(
572        &mut self,
573        unit: &str,
574        kind: SymbolKind,
575        name: &str,
576        site: SiteRef,
577        modifiers: SymbolModifiers,
578    ) {
579        let key = SymbolKey {
580            unit: unit.to_string(),
581            kind,
582            name: name.to_string(),
583        };
584        self.defs.insert(key, (site, modifiers));
585    }
586
587    /// v0.129 (#259): record that the `Type` `name` in `unit` is declared over
588    /// builtin `base` (a refined/opaque type or plain alias) — its refinement
589    /// family membership. The def site is looked up from `symbols` at query time,
590    /// so only the (key, base) pairing is stored here.
591    pub fn add_refinement(
592        &mut self,
593        unit: &str,
594        name: &str,
595        base: BaseType,
596        opaque: bool,
597        base_site: SiteRef,
598    ) {
599        self.refinements.push(RefineEdge {
600            base,
601            opaque,
602            base_site,
603            ty: SymbolKey {
604                unit: unit.to_string(),
605                kind: SymbolKind::Type,
606                name: name.to_string(),
607            },
608        });
609    }
610
611    /// v0.28 (ADR 0057): register a first-party symbol for the second
612    /// qualification pass — kind + modifiers only, no def site.
613    pub fn add_first_party_def(
614        &mut self,
615        unit: &str,
616        kind: SymbolKind,
617        name: &str,
618        modifiers: SymbolModifiers,
619    ) {
620        self.first_party_defs.insert(
621            SymbolKey {
622                unit: unit.to_string(),
623                kind,
624                name: name.to_string(),
625            },
626            modifiers,
627        );
628    }
629
630    /// Register a non-symbol owner (a method) for attribution only.
631    pub fn add_owner(&mut self, unit: &str, owner: &str, path: &Path) {
632        self.owner_files
633            .insert((unit.to_string(), owner.to_string()), path.to_path_buf());
634    }
635
636    pub fn set_uses(&mut self, uses: HashMap<String, Vec<String>>) {
637        self.uses = uses;
638    }
639
640    pub fn set_consumes(&mut self, consumes: HashMap<String, Vec<String>>) {
641        self.consumes = consumes;
642    }
643
644    pub fn set_type_aliases(
645        &mut self,
646        type_aliases: HashMap<String, HashMap<String, (String, String)>>,
647    ) {
648        self.type_aliases = type_aliases;
649    }
650
651    /// Qualify, attribute, dedupe, and assemble.
652    pub fn build(self, edges: Vec<RefEdge>) -> ProjectIndex {
653        let mut index = ProjectIndex::default();
654        for (key, (def, modifiers)) in &self.defs {
655            index.symbols.insert(
656                key.clone(),
657                SymbolEntry {
658                    def: Some(def.clone()),
659                    refs: Vec::new(),
660                    modifiers: *modifiers,
661                    call_only: self.call_only.contains(key),
662                },
663            );
664        }
665        let mut seen: HashSet<(PathBuf, Span, SymbolKey)> = HashSet::new();
666        let mut foreign_seen: HashSet<(PathBuf, Span, SymbolKind)> = HashSet::new();
667        let mut calls: Vec<CallEdge> = Vec::new();
668        let mut impls: Vec<ImplEdge> = Vec::new();
669        for edge in edges {
670            // Re-attribute to the owner's declaring file when the owner
671            // lives in a different file than the collection point: sibling-
672            // file methods and unit-level handler tables are processed under
673            // a file other than the one their spans index into. The owner is
674            // declared in the *namespace* unit (the unit being processed).
675            let path = edge
676                .owner
677                .as_ref()
678                .zip(edge.namespace.as_ref())
679                .and_then(|(o, ns)| self.owner_files.get(&(ns.clone(), o.clone())))
680                .cloned()
681                .unwrap_or_else(|| edge.file.clone());
682            let Some(key) = self.qualify(&edge) else {
683                // v0.28 (ADR 0057): second pass — a positive match against
684                // the first-party defs routes into the tokens-only side
685                // table; genuinely unresolved targets stay dropped.
686                if let Some(key) =
687                    self.qualify_with(&edge, |k| self.first_party_defs.contains_key(k))
688                    && foreign_seen.insert((path.clone(), edge.span, key.kind))
689                {
690                    index.foreign_refs.push(ForeignRef {
691                        site: SiteRef {
692                            path,
693                            span: edge.span,
694                        },
695                        kind: key.kind,
696                        modifiers: self.first_party_defs[&key],
697                    });
698                }
699                continue;
700            };
701            let entry = index.symbols.entry(key.clone()).or_default();
702            let Some(def) = &entry.def else {
703                continue;
704            };
705            let site = SiteRef {
706                path,
707                span: edge.span,
708            };
709            // The definition's own name span is not also a reference.
710            if site == *def {
711                continue;
712            }
713            if seen.insert((site.path.clone(), site.span, key.clone())) {
714                // v0.34 (ADR 0067): a `Fn` call inside a known top-level owner
715                // is a call edge. The caller resolves via `owner_keys` exactly
716                // as the file re-attribution above resolves `owner_files`.
717                // v0.36 (ADR 0069): methods are call targets too, now that they
718                // are `add_def`'d index symbols (and callers, since `add_def`
719                // populates `owner_keys` for `"T.m"` owners).
720                // #304: `CapabilityOp` (ADR 0069 scoped it out; reversed — the
721                // resulting reference-count/incoming-call mismatch was more
722                // confusing than the edge it withheld) and agent `Handler`
723                // (new this increment) join for the same reason methods did:
724                // both are `add_def`'d index symbols with a ref already
725                // recorded at the correct owner.
726                if matches!(
727                    key.kind,
728                    SymbolKind::Fn
729                        | SymbolKind::Method
730                        | SymbolKind::CapabilityOp
731                        | SymbolKind::Handler
732                ) && let Some(caller) = edge
733                    .owner
734                    .as_ref()
735                    .zip(edge.namespace.as_ref())
736                    .and_then(|(o, ns)| self.owner_keys.get(&(ns.clone(), o.clone())))
737                {
738                    calls.push(CallEdge {
739                        caller: caller.clone(),
740                        callee: key.clone(),
741                        site: site.clone(),
742                    });
743                }
744                // v0.35 (ADR 0068): a `provides Cap = Provider` clause — a
745                // provides-flagged `Capability` ref whose owner is the provider.
746                // The flag distinguishes it from the provider's `given` deps,
747                // which are also capability refs owned by the same provider.
748                if edge.provides
749                    && let Some(provider) = edge
750                        .owner
751                        .as_ref()
752                        .zip(edge.namespace.as_ref())
753                        .and_then(|(o, ns)| self.owner_keys.get(&(ns.clone(), o.clone())))
754                    && provider.kind == SymbolKind::Provider
755                {
756                    impls.push(ImplEdge {
757                        capability: key.clone(),
758                        provider: provider.clone(),
759                        site: site.clone(),
760                    });
761                }
762                entry.refs.push(site);
763            }
764        }
765        for entry in index.symbols.values_mut() {
766            entry.refs.sort();
767        }
768        index.symbols.retain(|_, e| e.def.is_some());
769        index.foreign_refs.sort_by(|a, b| a.site.cmp(&b.site));
770        calls.sort_by(|a, b| (&a.caller, &a.callee, &a.site).cmp(&(&b.caller, &b.callee, &b.site)));
771        index.calls = calls;
772        impls.sort_by(|a, b| {
773            (&a.capability, &a.provider, &a.site).cmp(&(&b.capability, &b.provider, &b.site))
774        });
775        index.impls = impls;
776        // v0.129 (#259): refinement families — keep edges whose type survived as
777        // an index symbol (a real def), sorted by (base name, type key) so the
778        // family listing is deterministic.
779        let mut refinements: Vec<RefineEdge> = self
780            .refinements
781            .into_iter()
782            .filter(|e| index.symbols.contains_key(&e.ty))
783            .collect();
784        refinements.sort_by(|a, b| (a.base.name(), &a.ty).cmp(&(b.base.name(), &b.ty)));
785        index.refinements = refinements;
786        index
787    }
788
789    fn qualify(&self, edge: &RefEdge) -> Option<SymbolKey> {
790        self.qualify_with(edge, |k| self.defs.contains_key(k))
791    }
792
793    /// The merged-table qualification against an arbitrary def set: a
794    /// site-known unit is looked up directly; a bare name layers local
795    /// first, then `uses` imports, then consumed units' exported types —
796    /// first hit wins, matching the pipeline's `or_insert` merge priority.
797    fn qualify_with(&self, edge: &RefEdge, has: impl Fn(&SymbolKey) -> bool) -> Option<SymbolKey> {
798        if let Some(unit) = &edge.unit {
799            let key = SymbolKey {
800                unit: unit.clone(),
801                kind: edge.kind,
802                name: edge.name.clone(),
803            };
804            return has(&key).then_some(key);
805        }
806        let ns = edge.namespace.as_ref()?;
807        let local = SymbolKey {
808            unit: ns.clone(),
809            kind: edge.kind,
810            name: edge.name.clone(),
811        };
812        if has(&local) {
813            return Some(local);
814        }
815        for target in self.uses.get(ns).into_iter().flatten() {
816            let imported = SymbolKey {
817                unit: target.clone(),
818                kind: edge.kind,
819                name: edge.name.clone(),
820            };
821            if has(&imported) {
822                return Some(imported);
823            }
824        }
825        // #2887: a consumed type renamed in this unit is its alias here only.
826        // After the unit's own and `uses` names: an alias that collides with
827        // one is refused, and the name still means the declaration it clashed
828        // with.
829        if edge.kind == SymbolKind::Type
830            && let Some((target, original)) = self
831                .type_aliases
832                .get(ns)
833                .and_then(|aliases| aliases.get(&edge.name))
834        {
835            let key = SymbolKey {
836                unit: target.clone(),
837                kind: edge.kind,
838                name: original.clone(),
839            };
840            return has(&key).then_some(key);
841        }
842        for target in self.consumes.get(ns).into_iter().flatten() {
843            let imported = SymbolKey {
844                unit: target.clone(),
845                kind: edge.kind,
846                name: edge.name.clone(),
847            };
848            if has(&imported) {
849                return Some(imported);
850            }
851        }
852        None
853    }
854}