Skip to main content

bynk_ide/
index_queries.rs

1//! v0.25 (ADR 0053): pure queries over the project binding index.
2//!
3//! Everything here is a pure function over [`ProjectIndex`] + analysed
4//! snapshot texts — the unit-testable core behind `textDocument/references`
5//! and `rename`/`prepareRename`. Transport-side handlers in `main.rs` only
6//! convert positions and package results.
7//!
8//! Rename is validated two ways, both correct-by-construction:
9//! 1. **Collisions** — apply the edits to an overlay, re-run
10//!    `diagnose_project`, refuse if a new diagnostic appears
11//!    ([`no_new_diagnostics`]).
12//! 2. **Capture/escape** — re-analysis alone misses silent re-binding
13//!    (declared fns shadow fn-typed locals in call position), so the
14//!    re-built index must equal the pre-index *modulo the rename*
15//!    ([`index_unchanged_modulo_rename`]).
16
17use std::collections::{BTreeMap, HashMap};
18use std::path::{Path, PathBuf};
19
20use crate::symbols::is_dot_preceded;
21use bynk_check::checker::{Ty, TyId, Types};
22use bynk_check::index::{ProjectIndex, SiteRef, SymbolKey, SymbolKind};
23use bynk_check::locals::{FileLocals, LocalBinding, LocalKind};
24use bynk_syntax::ast::BaseType;
25use bynk_syntax::lexer;
26use bynk_syntax::span::Span;
27
28/// Definition first, then references — the `references` surface.
29pub fn sites_for<'a>(
30    index: &'a ProjectIndex,
31    path: &Path,
32    offset: usize,
33    include_declaration: bool,
34) -> Option<Vec<&'a SiteRef>> {
35    let (key, _) = index.symbol_at(path, offset)?;
36    let mut sites = index.sites(key);
37    if !include_declaration && !sites.is_empty() {
38        sites.remove(0); // definition is always first.
39    }
40    Some(sites)
41}
42
43/// The definition site for the symbol at the cursor (an index-backed,
44/// binding-correct go-to-definition).
45pub fn definition_at<'a>(
46    index: &'a ProjectIndex,
47    path: &Path,
48    offset: usize,
49) -> Option<(&'a SymbolKey, &'a SiteRef)> {
50    let (key, _) = index.symbol_at(path, offset)?;
51    let entry = index.symbols.get(key)?;
52    Some((key, entry.def.as_ref()?))
53}
54
55/// `prepareRename`: the renameable range under the cursor, or `None` for
56/// out-of-scope symbols (locals, unit names) —
57/// the request is refused rather than falling through to a partial rename.
58pub fn prepare_rename<'a>(
59    index: &'a ProjectIndex,
60    path: &Path,
61    offset: usize,
62) -> Option<(&'a SymbolKey, &'a SiteRef)> {
63    index.symbol_at(path, offset)
64}
65
66/// v0.26 rider (ADR 0055): `workspace/symbol` — every index definition whose
67/// name contains the query, case-insensitive (an empty query lists all),
68/// sorted by (name, unit) for a stable order.
69pub fn workspace_symbols<'a>(
70    index: &'a ProjectIndex,
71    query: &str,
72) -> Vec<(&'a SymbolKey, &'a SiteRef)> {
73    let q = query.to_lowercase();
74    let mut out: Vec<_> = index
75        .symbols
76        .iter()
77        .filter(|(k, e)| !e.call_only && (q.is_empty() || k.name.to_lowercase().contains(&q)))
78        .filter_map(|(k, e)| e.def.as_ref().map(|d| (k, d)))
79        .collect();
80    out.sort_by(|a, b| (&a.0.name, &a.0.unit).cmp(&(&b.0.name, &b.0.unit)));
81    out
82}
83
84/// v0.33 (ADR 0066): `codeLens` — one reference-count lens per top-level
85/// definition in `path`, as `(def site, reference sites)`. The count is
86/// `refs.len()`; the reference sites feed the `showReferences` action. Sorted
87/// by definition position (a stable, top-to-bottom lens order).
88pub fn code_lenses<'a>(index: &'a ProjectIndex, path: &Path) -> Vec<(&'a SiteRef, &'a [SiteRef])> {
89    let mut out: Vec<(&SiteRef, &[SiteRef])> = index
90        .symbols
91        .values()
92        .filter(|e| !e.call_only)
93        .filter_map(|e| {
94            let def = e.def.as_ref()?;
95            (def.path == path).then_some((def, e.refs.as_slice()))
96        })
97        .collect();
98    out.sort_by_key(|(def, _)| (def.span.start, def.span.end));
99    out
100}
101
102/// v0.127 (editor-currency slice 6): a provider-count lens per `capability`
103/// definition in `path`, as `(capability def, provider def sites)`. The count is
104/// `providers.len()`; the provider sites feed the same `showReferences` peek the
105/// reference lens uses. Reuses the `implementations` relation (the `impls_of`
106/// edge behind go-to-implementation), so a capability with no provider yields no
107/// lens. Sorted by definition position, alongside the reference lenses.
108pub fn capability_provider_lenses<'a>(
109    index: &'a ProjectIndex,
110    path: &Path,
111) -> Vec<(&'a SiteRef, Vec<&'a SiteRef>)> {
112    let mut out: Vec<(&SiteRef, Vec<&SiteRef>)> = index
113        .symbols
114        .iter()
115        .filter(|(key, _)| key.kind == SymbolKind::Capability)
116        .filter_map(|(key, entry)| {
117            let def = entry.def.as_ref()?;
118            if def.path != path {
119                return None;
120            }
121            let providers = implementations(index, key);
122            (!providers.is_empty()).then_some((def, providers))
123        })
124        .collect();
125    out.sort_by_key(|(def, _)| (def.span.start, def.span.end));
126    out
127}
128
129/// v0.129 (#259): a refinement-family lens per refined/opaque `Type` definition
130/// in `path`, as `(type def, base, family def sites)` — every refined/opaque type
131/// (and plain alias) declared over the same builtin `base`, across the project.
132/// The family includes the type itself, so a lens is emitted only for a family of
133/// **≥ 2** (a lone refinement has nothing to navigate to — no lens, mirroring
134/// `capability_provider_lenses`). Sorted by definition position, alongside the
135/// reference lenses.
136pub fn refinement_family_lenses<'a>(
137    index: &'a ProjectIndex,
138    path: &Path,
139) -> Vec<(&'a SiteRef, BaseType, Vec<&'a SiteRef>)> {
140    let mut out: Vec<(&SiteRef, BaseType, Vec<&SiteRef>)> = index
141        .symbols
142        .iter()
143        .filter(|(key, _)| key.kind == SymbolKind::Type)
144        .filter_map(|(key, entry)| {
145            let def = entry.def.as_ref()?;
146            if def.path != path {
147                return None;
148            }
149            let base = index.refined_base(key)?;
150            let mut family: Vec<&SiteRef> = index
151                .refinements_over(base)
152                .filter_map(|e| index.symbols.get(&e.ty)?.def.as_ref())
153                .collect();
154            family.sort_by_key(|d| (d.path.clone(), d.span.start, d.span.end));
155            family.dedup();
156            (family.len() >= 2).then_some((def, base, family))
157        })
158        .collect();
159    out.sort_by_key(|(def, _, _)| (def.span.start, def.span.end));
160    out
161}
162
163/// v0.34 (ADR 0067): one end of a call-hierarchy relation — the related
164/// symbol (`key` + its definition site) and the call sites linking it to the
165/// queried symbol. For incoming calls `key` is a caller and `sites` are where
166/// it calls the queried symbol; for outgoing, `key` is a callee and `sites`
167/// are where the queried symbol calls it. The sites double as the LSP
168/// `fromRanges` (identical for both directions).
169pub struct CallRelation<'a> {
170    pub key: &'a SymbolKey,
171    pub def: &'a SiteRef,
172    pub sites: Vec<&'a SiteRef>,
173}
174
175/// v0.34 (ADR 0067): `prepareCallHierarchy` — the symbol under the cursor and
176/// its definition site (the goto-def resolution; an item is anchored on the
177/// definition). `None` for out-of-scope positions.
178pub fn prepare_call_hierarchy<'a>(
179    index: &'a ProjectIndex,
180    path: &Path,
181    offset: usize,
182) -> Option<(&'a SymbolKey, &'a SiteRef)> {
183    // #3582: also a service handler's `on` keyword.
184    let (key, _) = index.call_symbol_at(path, offset)?;
185    Some((key, index.symbols.get(key)?.def.as_ref()?))
186}
187
188/// Group `edges` by the key returned by `pick`, attach each grouped symbol's
189/// definition, and collect the call sites — the shared core of incoming and
190/// outgoing calls. Groups with no indexed definition are dropped (defensive;
191/// every call-edge endpoint is an index symbol by construction). Groups are
192/// ordered by definition position for a stable, top-to-bottom listing.
193fn group_calls<'a>(
194    index: &'a ProjectIndex,
195    edges: impl Iterator<Item = &'a bynk_check::index::CallEdge>,
196    pick: impl Fn(&'a bynk_check::index::CallEdge) -> &'a SymbolKey,
197) -> Vec<CallRelation<'a>> {
198    let mut by_key: BTreeMap<&SymbolKey, Vec<&SiteRef>> = BTreeMap::new();
199    for edge in edges {
200        by_key.entry(pick(edge)).or_default().push(&edge.site);
201    }
202    let mut out: Vec<CallRelation<'a>> = by_key
203        .into_iter()
204        .filter_map(|(key, mut sites)| {
205            let def = index.symbols.get(key)?.def.as_ref()?;
206            sites.sort();
207            Some(CallRelation { key, def, sites })
208        })
209        .collect();
210    out.sort_by_key(|r| (r.def.path.clone(), r.def.span.start, r.def.span.end));
211    out
212}
213
214/// v0.34 (ADR 0067): `callHierarchy/incomingCalls` — the callers of `key`,
215/// each with the call sites at which it calls `key`.
216pub fn incoming_calls<'a>(index: &'a ProjectIndex, key: &SymbolKey) -> Vec<CallRelation<'a>> {
217    group_calls(index, index.calls_into(key), |e| &e.caller)
218}
219
220/// v0.34 (ADR 0067): `callHierarchy/outgoingCalls` — what `key` calls, each
221/// with the call sites within `key` at which the callee is called.
222pub fn outgoing_calls<'a>(index: &'a ProjectIndex, key: &SymbolKey) -> Vec<CallRelation<'a>> {
223    group_calls(index, index.calls_from(key), |e| &e.callee)
224}
225
226/// v0.35 (ADR 0068): `textDocument/implementation` — the definition sites of
227/// every provider implementing the capability `key`, sorted by definition
228/// position. Empty for a non-capability or unknown key (the request then falls
229/// through; goto-def still serves the reverse, provider → capability).
230pub fn implementations<'a>(index: &'a ProjectIndex, key: &SymbolKey) -> Vec<&'a SiteRef> {
231    let mut defs: Vec<&SiteRef> = index
232        .impls_of(key)
233        .filter_map(|e| index.symbols.get(&e.provider)?.def.as_ref())
234        .collect();
235    defs.sort_by_key(|d| (d.path.clone(), d.span.start, d.span.end));
236    defs.dedup();
237    defs
238}
239
240/// The unit a source file belongs to, read off the first index symbol defined
241/// in it. `None` for a file that defines nothing.
242pub fn unit_of_file<'a>(index: &'a ProjectIndex, path: &Path) -> Option<&'a str> {
243    index
244        .symbols
245        .iter()
246        .find(|(_, e)| e.def.as_ref().is_some_and(|d| d.path == path))
247        .map(|(k, _)| k.unit.as_str())
248}
249
250/// Whether the refine edge's representation is visible to a request made from
251/// `from_unit`: always for a refined type or alias, only inside the declaring
252/// unit for an `opaque` one.
253fn representation_visible(edge: &bynk_check::index::RefineEdge, from_unit: Option<&str>) -> bool {
254    !edge.opaque || from_unit == Some(edge.ty.unit.as_str())
255}
256
257/// What `prepareTypeHierarchy` resolved the cursor to.
258pub enum HierarchyTarget<'a> {
259    /// A refined/opaque/alias type, with its definition site.
260    Type(&'a SymbolKey, &'a SiteRef),
261    /// A primitive written where a type is, such as `Int` in `type Qty = Int
262    /// where …` or in a field type, anchored at that occurrence.
263    Primitive(BaseType, SiteRef),
264}
265
266/// `textDocument/prepareTypeHierarchy`: the refined/opaque/alias type under the
267/// cursor, or the primitive named by the token under it (#2530) — a
268/// declaration's base, a field or parameter type, anywhere it is written. `text`
269/// is `path`'s analysed snapshot. `None` for any other position, including a
270/// record or sum, which has no base.
271pub fn prepare_type_hierarchy<'a>(
272    index: &'a ProjectIndex,
273    path: &Path,
274    text: &str,
275    offset: usize,
276) -> Option<HierarchyTarget<'a>> {
277    if let Some((key, def)) = definition_at(index, path, offset) {
278        return index
279            .refined_base(key)
280            .map(|_| HierarchyTarget::Type(key, def));
281    }
282    // Pick the token by its name: with the cursor on the first character of a
283    // built-in glued to punctuation (`List<Int>`, `x:Int`) the preceding token
284    // also touches `offset`. `Int`, `String` and `Bool` lex as keywords, the
285    // rest as identifiers, so the kind is not checked.
286    let tok = lexer::tokenize_expanding_holes(text)
287        .ok()?
288        .into_iter()
289        .find(|t| {
290            t.span.start <= offset
291                && offset <= t.span.end
292                && BaseType::from_name(&text[t.span.start..t.span.end]).is_some()
293        })?;
294    // A member name (`x.Int`) is not the built-in type.
295    if is_dot_preceded(text, tok.span.start) {
296        return None;
297    }
298    let base = BaseType::from_name(&text[tok.span.start..tok.span.end])?;
299    Some(HierarchyTarget::Primitive(
300        base,
301        SiteRef {
302            path: path.to_path_buf(),
303            span: Span::new(tok.span.start, tok.span.end),
304        },
305    ))
306}
307
308/// `typeHierarchy/supertypes` of a refined/opaque type: its builtin base and
309/// where the declaration writes it — the only supertype Bynk has (a base is
310/// always a primitive, never another declared type). `None` when the type has
311/// no base, or it is `opaque` and the request does not come from the declaring
312/// unit.
313pub fn type_supertype<'a>(
314    index: &'a ProjectIndex,
315    key: &SymbolKey,
316    from_unit: Option<&str>,
317) -> Option<(BaseType, &'a SiteRef)> {
318    let edge = index.refinements.iter().find(|e| &e.ty == key)?;
319    representation_visible(edge, from_unit).then_some((edge.base, &edge.base_site))
320}
321
322/// `typeHierarchy/subtypes` of a primitive: every refined, opaque or alias type
323/// declared over `base` across the project, sorted by definition position.
324/// An `opaque` type is listed only to requests from its declaring unit.
325pub fn type_subtypes<'a>(
326    index: &'a ProjectIndex,
327    base: BaseType,
328    from_unit: Option<&str>,
329) -> Vec<(&'a SymbolKey, &'a SiteRef)> {
330    let mut out: Vec<_> = index
331        .refinements_over(base)
332        .filter(|e| representation_visible(e, from_unit))
333        .filter_map(|e| Some((&e.ty, index.symbols.get(&e.ty)?.def.as_ref()?)))
334        .collect();
335    out.sort_by_key(|(_, d)| (d.path.clone(), d.span.start, d.span.end));
336    out
337}
338
339/// Slice 6: `textDocument/typeDefinition` — the definition site(s) of the type
340/// named `name` (a `Type` symbol). The checker's `Ty::Named.name` and the index
341/// both use bare names, so this is a bare-name match; a name shared across units
342/// yields several locations (the LSP-conventional resolution — the client lets
343/// the user choose). Sorted by definition position.
344pub fn type_definitions_named<'a>(index: &'a ProjectIndex, name: &str) -> Vec<&'a SiteRef> {
345    let mut defs: Vec<&SiteRef> = index
346        .symbols
347        .iter()
348        .filter(|(k, _)| k.kind == SymbolKind::Type && k.name == name)
349        .filter_map(|(_, e)| e.def.as_ref())
350        .collect();
351    defs.sort_by_key(|d| (d.path.clone(), d.span.start, d.span.end));
352    defs.dedup();
353    defs
354}
355
356/// #848: the flat compound-name member kinds (`"Owner.member"`, built by
357/// `bynk-emit`'s `assemble_index`). A dotted doc-link name matches these
358/// verbatim — never split into owner/member.
359pub const DOC_LINK_MEMBER_KINDS: &[SymbolKind] = &[
360    SymbolKind::Field,
361    SymbolKind::Method,
362    SymbolKind::CapabilityOp,
363    SymbolKind::Handler,
364];
365
366/// #848: the top-level kinds a *bare* doc-link name matches.
367pub const DOC_LINK_BARE_KINDS: &[SymbolKind] = &[
368    SymbolKind::Type,
369    SymbolKind::Fn,
370    SymbolKind::Capability,
371    SymbolKind::Service,
372    SymbolKind::Agent,
373    SymbolKind::Provider,
374    SymbolKind::Actor,
375    SymbolKind::Asset,
376    SymbolKind::Embed,
377    SymbolKind::Const,
378];
379
380/// #2454: the declaration a doc comment is attached to, as far as link
381/// resolution needs it: `attached` is the byte offset of its name in `path`
382/// (`bynk_ide::symbols::DocLinkSpan::attached`), and `locals` that file's
383/// local bindings, from which a fn / handler / op's parameters are read, and
384/// `text` that file's analysed source, which bounds the parameter list.
385pub struct DocLinkContext<'a> {
386    pub path: &'a Path,
387    pub text: &'a str,
388    pub attached: usize,
389    pub locals: &'a [LocalBinding],
390}
391
392/// #2454: a resolved doc link — the definition site, and its index key when
393/// it has one (a parameter is a local binding, not an indexed symbol).
394#[derive(Debug, Clone, PartialEq, Eq)]
395pub struct ResolvedDocLink {
396    pub def: SiteRef,
397    pub key: Option<SymbolKey>,
398}
399
400/// #2531: the outcome of [`resolve_doc_link_in`].
401#[derive(Debug, Clone, PartialEq, Eq)]
402pub enum DocLinkResolution {
403    Resolved(ResolvedDocLink),
404    /// More than one declaration matched in the first scope unit that has any
405    /// (so nothing is guessed): that `unit`, and the kinds that matched.
406    Ambiguous {
407        unit: String,
408        kinds: Vec<SymbolKind>,
409    },
410    Unresolved,
411}
412
413impl DocLinkResolution {
414    /// The resolution, if there is one; ambiguous and unresolved are both `None`.
415    pub fn resolved(self) -> Option<ResolvedDocLink> {
416        match self {
417            Self::Resolved(r) => Some(r),
418            _ => None,
419        }
420    }
421}
422
423/// #2454, #2531: the one doc-link resolver. A candidate resolves in order:
424///
425/// 1. the attached declaration's **own parts** — a record's fields, a
426///    capability's ops, an agent's handlers, a type's methods (the index's
427///    `"Owner.member"` entries), and a fn / handler / op's parameters;
428/// 2. the unit scope (see the scope walk above);
429/// 3. a **unit-qualified** name (`window.decide`, `a.b.Name`): the last
430///    segment as a top-level declaration of the unit named by the rest,
431///    whether or not that unit is in scope.
432///
433/// An own part shadows a unit-level name of the same spelling. A dotted name
434/// still tries `Owner.member` (step 2) before the unit-qualified reading, so
435/// every link that resolved before resolves to the same target. With no
436/// `ctx` step 1 is skipped. When nothing resolves, the result says whether
437/// the unit-scope walk was [`Ambiguous`](DocLinkResolution::Ambiguous) or the
438/// name simply [`Unresolved`](DocLinkResolution::Unresolved).
439pub fn resolve_doc_link_in(
440    index: &ProjectIndex,
441    doc_scope: &HashMap<String, Vec<String>>,
442    owner_unit: &str,
443    name: &str,
444    ctx: Option<&DocLinkContext<'_>>,
445) -> DocLinkResolution {
446    if let Some(ctx) = ctx
447        && !name.contains('.')
448        && let Some(hit) = resolve_own_part(index, ctx, name)
449    {
450        return DocLinkResolution::Resolved(hit);
451    }
452    let matches = doc_link_matches(index, doc_scope, owner_unit, name);
453    if let Some([(key, def)]) = matches.as_deref() {
454        return DocLinkResolution::Resolved(ResolvedDocLink {
455            def: (*def).clone(),
456            key: Some((*key).clone()),
457        });
458    }
459    if let Some((unit, last)) = name.rsplit_once('.')
460        && let Some((key, def)) = unique_hit(index, unit, last, DOC_LINK_BARE_KINDS)
461    {
462        return DocLinkResolution::Resolved(ResolvedDocLink {
463            def: def.clone(),
464            key: Some(key),
465        });
466    }
467    match matches.as_deref() {
468        Some(hits) if hits.len() > 1 => DocLinkResolution::Ambiguous {
469            unit: hits[0].0.unit.clone(),
470            kinds: hits.iter().map(|(k, _)| k.kind).collect(),
471        },
472        _ => DocLinkResolution::Unresolved,
473    }
474}
475
476/// The one definition of `name` among `kinds` in `unit`; `None` for none or
477/// for more than one (never a guess).
478fn unique_hit<'a>(
479    index: &'a ProjectIndex,
480    unit: &str,
481    name: &str,
482    kinds: &[SymbolKind],
483) -> Option<(SymbolKey, &'a SiteRef)> {
484    let mut hit = None;
485    let mut count = 0usize;
486    for &kind in kinds {
487        let key = SymbolKey {
488            unit: unit.to_string(),
489            kind,
490            name: name.to_string(),
491        };
492        if let Some(def) = index.symbols.get(&key).and_then(|e| e.def.as_ref()) {
493            count += 1;
494            hit = Some((key, def));
495        }
496    }
497    if count == 1 { hit } else { None }
498}
499
500/// #848, #2460: the unit-scope walk behind [`resolve_doc_link_in`] (#2531),
501/// private so nothing resolves without context. It resolves one intra-doc-link
502/// candidate name (from `bynk_ide::symbols::scan_doc_link_candidates`) against
503/// `owner_unit`'s doc-link scope order in `doc_scope` — the unit itself, then
504/// its `uses` targets, then its `consumes` targets (mirrors
505/// `bynk_check::index::IndexBuilder::qualify_with`'s bare-name qualification).
506///
507/// A `name` containing `.` matches the flat compound member kinds
508/// (`DOC_LINK_MEMBER_KINDS`, private below) verbatim; otherwise it matches the
509/// bare top-level kinds (`DOC_LINK_BARE_KINDS`). Every definition `name` matches
510/// in the **first** scope-order unit that has any is returned: one entry is a
511/// resolution; more is ambiguous (no `kind@` disambiguation — convention-only
512/// resolution), never a guess, even if a later unit would answer unambiguously;
513/// `None` is nothing matching anywhere. Synthetic (first-party) units are never
514/// in `index.symbols` (their defs are dropped at assembly), so a name that only
515/// matches through one — e.g. `Clock.now` — comes back `None` like any other
516/// unresolved name.
517fn doc_link_matches<'a>(
518    index: &'a ProjectIndex,
519    doc_scope: &HashMap<String, Vec<String>>,
520    owner_unit: &str,
521    name: &str,
522) -> Option<Vec<(&'a SymbolKey, &'a SiteRef)>> {
523    let kinds: &[SymbolKind] = if name.contains('.') {
524        DOC_LINK_MEMBER_KINDS
525    } else {
526        DOC_LINK_BARE_KINDS
527    };
528    let scope = doc_scope.get(owner_unit)?;
529    for unit in scope {
530        let hits: Vec<_> = kinds
531            .iter()
532            .filter_map(|&kind| {
533                let key = SymbolKey {
534                    unit: unit.clone(),
535                    kind,
536                    name: name.to_string(),
537                };
538                let (k, entry) = index.symbols.get_key_value(&key)?;
539                Some((k, entry.def.as_ref()?))
540            })
541            .collect();
542        if !hits.is_empty() {
543            return Some(hits);
544        }
545    }
546    None
547}
548
549/// #2456: one doc-link mention in a source file that resolves to a definition
550/// (see [`doc_link_mentions`]).
551#[derive(Debug, Clone, PartialEq, Eq)]
552pub struct DocLinkMention {
553    /// The file (project-relative, as in `snapshots`) holding the mention.
554    pub path: PathBuf,
555    /// The whole link construct, e.g. `[the limiter][Limiter]` or `` [`Limiter`] ``.
556    pub span: Span,
557    /// The link's target name text, e.g. `Limiter` or `Limiter.decide`. Display
558    /// text and backticks are not part of it.
559    pub name: String,
560    /// The span of exactly [`Self::name`] inside the link — the text a rename
561    /// rewrites. The label of `[text][Name]`, the inside of `` [`Name`] ``.
562    pub name_span: Span,
563}
564
565/// #2456: every doc-link mention in `snapshots` that resolves (through
566/// [`resolve_doc_link_in`], with the declaration each comment is attached to
567/// as context, so a bare `[field]` in its own record's doc counts) to the
568/// definition at `target`. `locals` is the round's per-file local bindings.
569///
570/// This is the reverse of [`resolve_doc_link_in`]: rename uses it to rewrite the
571/// mention, and it is the lookup that find-references and document-highlight
572/// are meant to report doc-link mentions through (#2457). `target` is a definition site, as held in
573/// `SymbolEntry::def`.
574///
575/// Only files whose doc-link scope contains the defining unit are scanned, and a
576/// file whose text does not contain the name's last segment is skipped before
577/// it is tokenised. A suite file has no own unit name and is skipped, matching
578/// `textDocument/documentLink`. Mentions come back in file then source order.
579pub fn doc_link_mentions(
580    index: &ProjectIndex,
581    doc_scope: &HashMap<String, Vec<String>>,
582    snapshots: &HashMap<PathBuf, String>,
583    locals: &FileLocals,
584    target: &SiteRef,
585) -> Vec<DocLinkMention> {
586    doc_link_mentions_of(index, doc_scope, snapshots, locals, &[target])
587}
588
589/// [`doc_link_mentions`] over several definitions at once: a mention is kept when
590/// it resolves to any of `targets`. Rename uses it to also catch `[Type.member]`
591/// links when the owning type is renamed.
592pub fn doc_link_mentions_of(
593    index: &ProjectIndex,
594    doc_scope: &HashMap<String, Vec<String>>,
595    snapshots: &HashMap<PathBuf, String>,
596    locals: &FileLocals,
597    targets: &[&SiteRef],
598) -> Vec<DocLinkMention> {
599    // The defining units and name segments the targets can be spelt with.
600    let mut units: Vec<&str> = Vec::new();
601    let mut segments: Vec<&str> = Vec::new();
602    for t in targets {
603        if let Some((k, _)) = index.symbol_at(&t.path, t.span.start) {
604            units.push(k.unit.as_str());
605            segments.extend(k.name.split('.'));
606        }
607    }
608    if units.is_empty() {
609        return Vec::new();
610    }
611    let mut paths: Vec<&PathBuf> = snapshots.keys().collect();
612    paths.sort();
613    let mut out = Vec::new();
614    for path in paths {
615        let text = &snapshots[path];
616        if !segments.iter().any(|s| text.contains(s)) {
617            continue;
618        }
619        let Some(owner_unit) = crate::symbols::doc_link_unit(text) else {
620            continue;
621        };
622        let Some(scope) = doc_scope.get(&owner_unit) else {
623            continue;
624        };
625        // A unit-qualified link (`[unit.Name]`) reaches outside the scope list,
626        // so a scope miss only rules the file out when no link is qualified.
627        if !units.iter().any(|u| scope.iter().any(|s| s == u)) && !text.contains('.') {
628            continue;
629        }
630        for link in crate::symbols::doc_link_spans_attached(text) {
631            let (name, span) = (link.name, link.span);
632            let ctx = link.attached.map(|attached| DocLinkContext {
633                path,
634                text,
635                attached,
636                locals: locals.get(path).map_or(&[][..], Vec::as_slice),
637            });
638            let Some(resolved) =
639                resolve_doc_link_in(index, doc_scope, &owner_unit, &name, ctx.as_ref()).resolved()
640            else {
641                continue;
642            };
643            if !targets.contains(&&resolved.def) {
644                continue;
645            }
646            // The name is the last thing in the construct: before the closing
647            // `]`, or before `` `] `` in the code-span form.
648            let tail = if text[..span.end].ends_with("`]") {
649                2
650            } else {
651                1
652            };
653            let Some(name_start) = span.end.checked_sub(tail + name.len()) else {
654                continue;
655            };
656            if text.get(name_start..name_start + name.len()) != Some(name.as_str()) {
657                continue;
658            }
659            out.push(DocLinkMention {
660                path: path.clone(),
661                span,
662                name_span: Span::new(name_start, name_start + name.len()),
663                name,
664            });
665        }
666    }
667    out
668}
669
670/// #2458: one name a doc link could be completed to.
671#[derive(Debug, Clone, PartialEq, Eq)]
672pub struct DocLinkSuggestion {
673    /// The text to insert: the whole name, or just the member segment when
674    /// completing after `Owner.`.
675    pub label: String,
676    /// The full link name `resolve_doc_link_in` would be given.
677    pub name: String,
678    /// The symbol kind; `None` for a parameter (a local binding, not indexed).
679    pub kind: Option<SymbolKind>,
680    /// The unit that declares it.
681    pub unit: String,
682}
683
684/// #2458: the names a doc link in `owner_unit` could resolve, **in resolution
685/// order** — the single place completion defines that order:
686///
687/// 1. the attached declaration's own parts (`ctx`): a record's fields, a
688///    capability's ops, an agent's handlers, a type's methods, then a fn /
689///    handler / op's parameters;
690/// 2. the unit scope — the same `doc_scope` list `resolve_doc_link_in` walks (so a
691///    change to scope order or contents flows through), by position in that
692///    list and then by name.
693///
694/// A name is kept only when `resolve_doc_link_in` resolves it to that very
695/// declaration, so suggestions and resolution agree. A bare name that does not
696/// (shadowed by an own part or an earlier unit) is instead offered as
697/// `unit.Name` when that qualified form resolves to it; one ambiguous within
698/// its unit has no resolving form and is left out.
699///
700/// With `owner: Some("Type")` it offers that owner's members (`Type.member`,
701/// labelled by the member segment) from the unit scope only, then — when the
702/// text names a project unit (#2525) — that unit's top-level names.
703pub fn doc_link_suggestions(
704    index: &ProjectIndex,
705    doc_scope: &HashMap<String, Vec<String>>,
706    owner_unit: &str,
707    owner: Option<&str>,
708    ctx: Option<&DocLinkContext<'_>>,
709) -> Vec<DocLinkSuggestion> {
710    let Some(scope) = doc_scope.get(owner_unit) else {
711        return Vec::new();
712    };
713    let mut out = Vec::new();
714    if owner.is_none()
715        && let Some(ctx) = ctx
716    {
717        own_part_suggestions(index, doc_scope, owner_unit, ctx, &mut out);
718    }
719    let kinds: &[SymbolKind] = if owner.is_some() {
720        DOC_LINK_MEMBER_KINDS
721    } else {
722        DOC_LINK_BARE_KINDS
723    };
724    let prefix = owner.map(|o| format!("{o}."));
725    let mut found: Vec<(usize, &SymbolKey)> = index
726        .symbols
727        .iter()
728        .filter(|(k, e)| e.def.is_some() && kinds.contains(&k.kind))
729        .filter(|(k, _)| match &prefix {
730            Some(p) => k
731                .name
732                .strip_prefix(p.as_str())
733                .is_some_and(|m| !m.contains('.')),
734            None => !k.name.contains('.'),
735        })
736        .filter_map(|(k, _)| Some((scope.iter().position(|u| *u == k.unit)?, k)))
737        .collect();
738    found.sort_by(|a, b| (a.0, &a.1.name, a.1.kind).cmp(&(b.0, &b.1.name, b.1.kind)));
739    for (_, key) in found {
740        let resolves_to = |name: &str| {
741            resolve_doc_link_in(index, doc_scope, owner_unit, name, ctx)
742                .resolved()
743                .and_then(|r| r.key)
744                .is_some_and(|k| k == *key)
745        };
746        let (label, name) = if resolves_to(&key.name) {
747            let label = match &prefix {
748                Some(p) => key.name[p.len()..].to_string(),
749                None => key.name.clone(),
750            };
751            (label, key.name.clone())
752        } else if prefix.is_none() && resolves_to(&format!("{}.{}", key.unit, key.name)) {
753            // #2458 (decision C): the bare name reaches something else, so
754            // offer the form that reaches this one.
755            let qualified = format!("{}.{}", key.unit, key.name);
756            (qualified.clone(), qualified)
757        } else {
758            continue;
759        };
760        out.push(DocLinkSuggestion {
761            label,
762            name,
763            kind: Some(key.kind),
764            unit: key.unit.clone(),
765        });
766    }
767    if let Some(unit) = owner {
768        unit_prefix_suggestions(index, doc_scope, owner_unit, unit, ctx, &mut out);
769    }
770    out
771}
772
773/// #2525: after `[unit.` (or `[a.b.`), the top-level linkable names of the
774/// project unit named exactly `unit`, in scope or not — the names step 3 of
775/// [`resolve_doc_link_in`] resolves. Each is offered by its last segment and
776/// kept only when `unit.Name` resolves to that very declaration. Runs after
777/// the `Owner.` members, which resolution also reads first.
778fn unit_prefix_suggestions(
779    index: &ProjectIndex,
780    doc_scope: &HashMap<String, Vec<String>>,
781    owner_unit: &str,
782    unit: &str,
783    ctx: Option<&DocLinkContext<'_>>,
784    out: &mut Vec<DocLinkSuggestion>,
785) {
786    let mut found: Vec<&SymbolKey> = index
787        .symbols
788        .iter()
789        .filter(|(k, e)| {
790            e.def.is_some()
791                && k.unit == unit
792                && DOC_LINK_BARE_KINDS.contains(&k.kind)
793                && !k.name.contains('.')
794        })
795        .map(|(k, _)| k)
796        .collect();
797    found.sort_by(|a, b| (&a.name, a.kind).cmp(&(&b.name, b.kind)));
798    for key in found {
799        let qualified = format!("{unit}.{}", key.name);
800        let resolves = resolve_doc_link_in(index, doc_scope, owner_unit, &qualified, ctx)
801            .resolved()
802            .and_then(|r| r.key)
803            .is_some_and(|k| k == *key);
804        if resolves {
805            out.push(DocLinkSuggestion {
806                label: key.name.clone(),
807                name: qualified,
808                kind: Some(key.kind),
809                unit: key.unit.clone(),
810            });
811        }
812    }
813}
814
815/// Tier 1 of [`doc_link_suggestions`]: the attached declaration's members (by
816/// source position), then its parameters. Each is checked against
817/// [`resolve_doc_link_in`], so a parameter a same-named field would shadow is
818/// not offered.
819fn own_part_suggestions(
820    index: &ProjectIndex,
821    doc_scope: &HashMap<String, Vec<String>>,
822    owner_unit: &str,
823    ctx: &DocLinkContext<'_>,
824    out: &mut Vec<DocLinkSuggestion>,
825) {
826    let resolves_at = |name: &str, def: &SiteRef| {
827        resolve_doc_link_in(index, doc_scope, owner_unit, name, Some(ctx))
828            .resolved()
829            .is_some_and(|r| r.def == *def)
830    };
831    if let Some(owner) = attached_owner(index, ctx) {
832        let prefix = format!("{}.", owner.name);
833        let mut members: Vec<_> = index
834            .symbols
835            .iter()
836            .filter(|(k, _)| k.unit == owner.unit && DOC_LINK_MEMBER_KINDS.contains(&k.kind))
837            .filter_map(|(k, e)| {
838                let member = k.name.strip_prefix(prefix.as_str())?;
839                (!member.contains('.')).then_some((member, k, e.def.as_ref()?))
840            })
841            .collect();
842        members.sort_by_key(|(m, k, d)| (d.span.start, *m, k.kind));
843        for (member, key, def) in members {
844            if resolves_at(member, def) {
845                out.push(DocLinkSuggestion {
846                    label: member.to_string(),
847                    name: member.to_string(),
848                    kind: Some(key.kind),
849                    unit: key.unit.clone(),
850                });
851            }
852        }
853    }
854    let mut params: Vec<_> = attached_params(ctx).collect();
855    params.sort_by_key(|b| b.def_span.start);
856    for param in params {
857        let def = SiteRef {
858            path: ctx.path.to_path_buf(),
859            span: param.def_span,
860        };
861        if resolves_at(&param.name, &def) {
862            out.push(DocLinkSuggestion {
863                label: param.name.clone(),
864                name: param.name.clone(),
865                kind: None,
866                unit: owner_unit.to_string(),
867            });
868        }
869    }
870}
871
872/// #2455: whether any unit in `owner_unit`'s doc-link scope declares a
873/// top-level symbol named `owner` (the part of a doc-link name before any `.`).
874/// A project declaration shadows a first-party name of the same spelling, so
875/// the first-party fallback must not run when this is true — even if
876/// `resolve_doc_link_in` declined (ambiguous, or a member miss).
877pub fn doc_link_owner_declared(
878    index: &ProjectIndex,
879    doc_scope: &HashMap<String, Vec<String>>,
880    owner_unit: &str,
881    owner: &str,
882) -> bool {
883    doc_scope.get(owner_unit).is_some_and(|scope| {
884        scope.iter().any(|unit| {
885            DOC_LINK_BARE_KINDS.iter().any(|&kind| {
886                let key = SymbolKey {
887                    unit: unit.clone(),
888                    kind,
889                    name: owner.to_string(),
890                };
891                index.symbols.get(&key).is_some_and(|e| e.def.is_some())
892            })
893        })
894    })
895}
896
897/// The byte range of the `( … )` parameter list that follows the declaration
898/// name at `attached`: `None` when a `{` or `=` comes first (a record, agent or
899/// capability has no parameters) or the parentheses are unbalanced.
900fn param_header(text: &str, attached: usize) -> Option<std::ops::Range<usize>> {
901    let rest = text.get(attached..)?;
902    let open = rest.find(['(', '{', '='])?;
903    if !rest[open..].starts_with('(') {
904        return None;
905    }
906    let mut depth = 0usize;
907    for (i, c) in rest[open..].char_indices() {
908        match c {
909            '(' => depth += 1,
910            ')' => {
911                depth -= 1;
912                if depth == 0 {
913                    return Some(attached + open..attached + open + i);
914                }
915            }
916            _ => {}
917        }
918    }
919    None
920}
921
922/// The index entry for the declaration whose name sits at `ctx.attached`.
923fn attached_owner<'a>(index: &'a ProjectIndex, ctx: &DocLinkContext<'_>) -> Option<&'a SymbolKey> {
924    let at = |d: &SiteRef| d.path == ctx.path && d.span.start == ctx.attached;
925    index
926        .symbols
927        .iter()
928        .find(|(_, e)| e.def.as_ref().is_some_and(at))
929        .map(|(k, _)| k)
930}
931
932/// The `Param` bindings inside the attached declaration's parenthesised header.
933fn attached_params<'a>(ctx: &'a DocLinkContext<'_>) -> impl Iterator<Item = &'a LocalBinding> {
934    let header = param_header(ctx.text, ctx.attached);
935    ctx.locals.iter().filter(move |b| {
936        b.kind == LocalKind::Param
937            && header
938                .as_ref()
939                .is_some_and(|h| b.def_span.start >= h.start && b.def_span.end <= h.end)
940    })
941}
942
943/// #2459: the names [`resolve_doc_link_in`] resolves as the attached
944/// declaration's own parts (member and parameter names, bare), for the
945/// did-you-mean candidates of the unresolved-link hint. Only names that
946/// resolve (a name defined as two member kinds is ambiguous, so never one).
947pub fn own_part_names(index: &ProjectIndex, ctx: &DocLinkContext<'_>) -> Vec<String> {
948    let mut names = Vec::new();
949    if let Some(owner) = attached_owner(index, ctx) {
950        let prefix = format!("{}.", owner.name);
951        names.extend(
952            index
953                .symbols
954                .iter()
955                .filter(|(k, e)| {
956                    k.unit == owner.unit
957                        && e.def.is_some()
958                        && DOC_LINK_MEMBER_KINDS.contains(&k.kind)
959                })
960                .filter_map(|(k, _)| k.name.strip_prefix(&prefix))
961                .map(str::to_string),
962        );
963    }
964    names.extend(attached_params(ctx).map(|b| b.name.clone()));
965    names.sort();
966    names.dedup();
967    names.retain(|n| resolve_own_part(index, ctx, n).is_some());
968    names
969}
970
971/// Step 1 of [`resolve_doc_link_in`]: `name` as a member or parameter of the
972/// declaration whose name sits at `ctx.attached`.
973fn resolve_own_part(
974    index: &ProjectIndex,
975    ctx: &DocLinkContext<'_>,
976    name: &str,
977) -> Option<ResolvedDocLink> {
978    let owner = attached_owner(index, ctx)?;
979    let member = format!("{}.{name}", owner.name);
980    if let Some((key, def)) = unique_hit(index, &owner.unit, &member, DOC_LINK_MEMBER_KINDS) {
981        return Some(ResolvedDocLink {
982            def: def.clone(),
983            key: Some(key),
984        });
985    }
986    // The declaration's parameters (see `attached_params`): a lambda's sit in
987    // the body, past the header, so a declaration with no parameters of its own
988    // never claims one.
989    let param = attached_params(ctx).find(|b| b.name == name)?;
990    Some(ResolvedDocLink {
991        def: SiteRef {
992            path: ctx.path.to_path_buf(),
993            span: param.def_span,
994        },
995        key: None,
996    })
997}
998
999/// The user-declared type a value's type points at, for go-to-type-definition:
1000/// a `Named` directly, or the element of a single-parameter container
1001/// (`Option`/`Effect`/`List`/`HttpResult`) unwrapped to it. Built-in, function,
1002/// actor, and two-parameter (`Result`/`Map`) types have no single
1003/// type-declaration target and yield `None`.
1004pub fn named_type_target(ty: TyId, tys: &Types) -> Option<String> {
1005    match &*tys.get(ty) {
1006        Ty::Named { name, .. } => Some(name.clone()),
1007        Ty::Option(t) | Ty::Effect(t) | Ty::List(t) | Ty::HttpResult(t) => {
1008            named_type_target(*t, tys)
1009        }
1010        _ => None,
1011    }
1012}
1013
1014/// v0.26 rider (ADR 0055): `documentHighlight` — the symbol-at-cursor's
1015/// occurrences within that same file (the `references` query, file-scoped).
1016/// The index does not distinguish read from write references, so the LSP
1017/// layer omits the highlight `kind`.
1018pub fn document_highlights<'a>(
1019    index: &'a ProjectIndex,
1020    path: &Path,
1021    offset: usize,
1022) -> Option<Vec<&'a SiteRef>> {
1023    let sites = sites_for(index, path, offset, true)?;
1024    Some(sites.into_iter().filter(|s| s.path == path).collect())
1025}
1026
1027/// A planned rename: every name-segment edit, grouped per file, spans
1028/// ascending. The definition site is edited along with every reference.
1029#[derive(Debug, Clone)]
1030pub struct RenamePlan {
1031    pub key: SymbolKey,
1032    pub new_name: String,
1033    pub edits: BTreeMap<PathBuf, Vec<Span>>,
1034}
1035
1036/// Build the rename plan for the symbol at the cursor. Errors are
1037/// human-readable strings surfaced as LSP request failures.
1038pub fn plan_rename(
1039    index: &ProjectIndex,
1040    path: &Path,
1041    offset: usize,
1042    new_name: &str,
1043) -> Result<RenamePlan, String> {
1044    validate_new_name(new_name)?;
1045    let (key, _) = index.symbol_at(path, offset).ok_or_else(|| {
1046        "no renameable symbol at the cursor — types, fns, methods, record fields, \
1047         capability ops, capabilities, services, agents and providers rename; \
1048         local bindings and unit names are not yet supported"
1049            .to_string()
1050    })?;
1051    if key_segment(&key.name) == new_name {
1052        return Err(format!("`{new_name}` is already the symbol's name"));
1053    }
1054    let mut edits: BTreeMap<PathBuf, Vec<Span>> = BTreeMap::new();
1055    for site in index.sites(key) {
1056        edits.entry(site.path.clone()).or_default().push(site.span);
1057    }
1058    for spans in edits.values_mut() {
1059        spans.sort();
1060        spans.dedup();
1061    }
1062    Ok(RenamePlan {
1063        key: key.clone(),
1064        new_name: new_name.to_string(),
1065        edits,
1066    })
1067}
1068
1069/// #2456: extend `plan` with the doc links that resolved to the renamed symbol
1070/// before the rename, across every file in `snapshots`. A link to the symbol
1071/// itself has its last segment rewritten (`[Limiter]`, `[Limiter.decide]` when
1072/// `decide` is renamed); when a type-like symbol is renamed, a link to one of
1073/// its members has its owner segment rewritten (`[Limiter.decide]` when
1074/// `Limiter` is). Display text and backticks are untouched, and a link that
1075/// resolves to some other definition of the same name is left alone.
1076pub fn add_doc_link_edits(
1077    plan: &mut RenamePlan,
1078    index: &ProjectIndex,
1079    doc_scope: &HashMap<String, Vec<String>>,
1080    snapshots: &HashMap<PathBuf, String>,
1081    locals: &FileLocals,
1082) {
1083    let Some(entry) = index.symbols.get(&plan.key) else {
1084        return;
1085    };
1086    let Some(def) = entry.def.as_ref() else {
1087        return;
1088    };
1089    let own = doc_link_mentions(index, doc_scope, snapshots, locals, def);
1090    let seg_len = key_segment(&plan.key.name).len();
1091    let mut extra: Vec<(PathBuf, Span)> = own
1092        .iter()
1093        .map(|m| {
1094            (
1095                m.path.clone(),
1096                Span::new(m.name_span.end - seg_len, m.name_span.end),
1097            )
1098        })
1099        .collect();
1100    if !plan.key.name.contains('.') {
1101        let prefix = format!("{}.", plan.key.name);
1102        let members: Vec<&SiteRef> = index
1103            .symbols
1104            .iter()
1105            .filter(|(k, _)| k.unit == plan.key.unit && k.name.starts_with(&prefix))
1106            .filter_map(|(_, e)| e.def.as_ref())
1107            .collect();
1108        let owner_len = plan.key.name.len();
1109        for m in doc_link_mentions_of(index, doc_scope, snapshots, locals, &members) {
1110            // A bare `[member]` (in its owner's own doc) spells no owner; a
1111            // dotted one names it just before the member segment.
1112            let Some((before, member)) = m.name.rsplit_once('.') else {
1113                continue;
1114            };
1115            let end = m.name_span.end - member.len() - 1;
1116            if !before.ends_with(&plan.key.name) || end < owner_len {
1117                continue;
1118            }
1119            extra.push((m.path.clone(), Span::new(end - owner_len, end)));
1120        }
1121    }
1122    for (path, span) in extra {
1123        let spans = plan.edits.entry(path).or_default();
1124        // Spans order by file id first, so a doc-link span must carry the id its
1125        // file's index spans already have for the per-file list to sort by offset.
1126        let file = spans.first().map(|s| s.file).unwrap_or(span.file);
1127        spans.push(Span::new_in(file, span.start, span.end));
1128    }
1129    for spans in plan.edits.values_mut() {
1130        spans.sort();
1131        spans.dedup();
1132    }
1133}
1134
1135/// #2456 (decision C): after a rename, every doc link must resolve to the same
1136/// definition it did before — modulo the rename itself. `post_*` describe the
1137/// re-analysed project with the edits applied, `post_texts` the edited sources.
1138/// A link that now resolves elsewhere, stops resolving, or starts resolving is
1139/// a silent re-binding, reported like any other.
1140pub fn doc_links_rebound(
1141    pre: (&ProjectIndex, &HashMap<String, Vec<String>>, &FileLocals),
1142    post: (&ProjectIndex, &HashMap<String, Vec<String>>, &FileLocals),
1143    pre_texts: &HashMap<PathBuf, String>,
1144    post_texts: &HashMap<PathBuf, String>,
1145    plan: &RenamePlan,
1146) -> Result<(), String> {
1147    let renamed = renamed_key_name(&plan.key.name, &plan.new_name);
1148    let owner_prefix = format!("{}.", plan.key.name);
1149    let expect = |k: &SymbolKey| -> SymbolKey {
1150        let mut k = k.clone();
1151        if k == plan.key {
1152            k.name = renamed.clone();
1153        } else if k.unit == plan.key.unit
1154            && !plan.key.name.contains('.')
1155            && k.name.starts_with(&owner_prefix)
1156        {
1157            k.name = format!("{}.{}", plan.new_name, &k.name[owner_prefix.len()..]);
1158        }
1159        k
1160    };
1161    // What every doc link in `text` resolves to, as a definition: its index
1162    // key, or for a parameter (no key) the site.
1163    let resolve_all =
1164        |(index, scope, locals): (&ProjectIndex, &HashMap<String, Vec<String>>, &FileLocals),
1165         path: &PathBuf,
1166         text: &str|
1167         -> Option<Vec<(String, Option<ResolvedDocLink>)>> {
1168            let owner = crate::symbols::doc_link_unit(text)?;
1169            Some(
1170                crate::symbols::doc_link_spans_attached(text)
1171                    .into_iter()
1172                    .map(|link| {
1173                        let ctx = link.attached.map(|attached| DocLinkContext {
1174                            path,
1175                            text,
1176                            attached,
1177                            locals: locals.get(path).map_or(&[][..], Vec::as_slice),
1178                        });
1179                        let r = resolve_doc_link_in(index, scope, &owner, &link.name, ctx.as_ref())
1180                            .resolved();
1181                        (link.name, r)
1182                    })
1183                    .collect(),
1184            )
1185        };
1186    let mut paths: Vec<&PathBuf> = pre_texts.keys().collect();
1187    paths.sort();
1188    for path in paths {
1189        let (Some(before), Some(after)) = (
1190            resolve_all(pre, path, &pre_texts[path]),
1191            resolve_all(post, path, &post_texts[path]),
1192        ) else {
1193            continue;
1194        };
1195        debug_assert_eq!(
1196            before.len(),
1197            after.len(),
1198            "a rename edit never adds or removes a link"
1199        );
1200        if before.len() != after.len() {
1201            continue;
1202        }
1203        for ((name, was), (_, now)) in before.iter().zip(&after) {
1204            // Compare by key; a parameter has none, so it is compared by whether
1205            // it is still a parameter (its site shifts with the edits).
1206            let was_key = was.as_ref().map(|r| r.key.as_ref().map(&expect));
1207            let now_key = now.as_ref().map(|r| r.key.clone());
1208            if was_key != now_key {
1209                return Err(format!(
1210                    "renaming `{}` to `{}` would change what the doc link `[{name}]` in {} resolves to — refused",
1211                    plan.key.name,
1212                    plan.new_name,
1213                    path.display()
1214                ));
1215            }
1216        }
1217    }
1218    Ok(())
1219}
1220
1221/// A new name must lex as exactly one identifier (keywords lex as their own
1222/// token kinds, so they fail this check).
1223pub fn validate_new_name(name: &str) -> Result<(), String> {
1224    let err = || format!("`{name}` is not a valid Bynk identifier");
1225    let tokens = bynk_syntax::lexer::tokenize(name).map_err(|_| err())?;
1226    match tokens.as_slice() {
1227        [t] if matches!(t.kind, bynk_syntax::lexer::TokenKind::Ident)
1228            && t.span.start == 0
1229            && t.span.end == name.len() =>
1230        {
1231            Ok(())
1232        }
1233        _ => Err(err()),
1234    }
1235}
1236
1237/// Apply one file's edits (spans ascending) to its snapshot text.
1238pub fn apply_edits(text: &str, spans: &[Span], new_name: &str) -> String {
1239    let mut out = String::with_capacity(text.len());
1240    let mut last = 0;
1241    for s in spans {
1242        out.push_str(&text[last..s.start]);
1243        out.push_str(new_name);
1244        last = s.end;
1245    }
1246    out.push_str(&text[last..]);
1247    out
1248}
1249
1250/// The post-edit position of a pre-edit site — rename edits shift spans
1251/// within edited files. An edited span maps to the new name's span.
1252pub fn remap_site(site: &SiteRef, plan: &RenamePlan) -> SiteRef {
1253    let Some(spans) = plan.edits.get(&site.path) else {
1254        return site.clone();
1255    };
1256    // The edit replaces the member segment only (`"m"` of `"Type.m"`), so the
1257    // length delta is against that segment, not the whole compound key name.
1258    let delta = plan.new_name.len() as isize - key_segment(&plan.key.name).len() as isize;
1259    let shift: isize = spans.iter().filter(|s| s.end <= site.span.start).count() as isize * delta;
1260    let start = (site.span.start as isize + shift) as usize;
1261    let end = if spans.binary_search(&site.span).is_ok() {
1262        start + plan.new_name.len()
1263    } else {
1264        (site.span.end as isize + shift) as usize
1265    };
1266    SiteRef {
1267        path: site.path.clone(),
1268        span: Span::new_in(site.span.file, start, end),
1269    }
1270}
1271
1272/// Validator (2): the re-built index must equal the pre-index modulo the
1273/// rename — every other symbol's reference set identical (after remapping
1274/// shifted spans), the renamed symbol's sites exactly the edited ones.
1275/// Catches silent re-binding (capture/escape) that produces no diagnostic.
1276pub fn index_unchanged_modulo_rename(
1277    pre: &ProjectIndex,
1278    post: &ProjectIndex,
1279    plan: &RenamePlan,
1280) -> bool {
1281    // v0.36 (ADR 0069): a member key carries a compound name (`"Type.method"`),
1282    // but the edit replaces only the member segment — so the post-rename key is
1283    // the prefix plus the new segment, not the bare new name.
1284    let target = renamed_key_name(&plan.key.name, &plan.new_name);
1285    // #2456: renaming a type-like symbol also re-keys its members
1286    // (`Type.member` -> `New.member`), which the post-index carries.
1287    if plan.key.name.contains('.') {
1288        return pre.equals_modulo_rename(post, &plan.key, &target, |s| remap_site(s, plan));
1289    }
1290    let prefix = format!("{}.", plan.key.name);
1291    let mut rekeyed = pre.clone();
1292    rekeyed.symbols = pre
1293        .symbols
1294        .iter()
1295        .map(|(k, e)| {
1296            let mut k = k.clone();
1297            if k.unit == plan.key.unit && k.name.starts_with(&prefix) {
1298                k.name = format!("{}.{}", plan.new_name, &k.name[prefix.len()..]);
1299            }
1300            (k, e.clone())
1301        })
1302        .collect();
1303    rekeyed.equals_modulo_rename(post, &plan.key, &target, |s| remap_site(s, plan))
1304}
1305
1306/// The post-rename value of a (possibly compound) key name: for a member key
1307/// `"Type.method"`, replace the segment after the last `.`; for a bare name,
1308/// the new name as-is.
1309fn renamed_key_name(old: &str, new_segment: &str) -> String {
1310    match old.rfind('.') {
1311        Some(i) => format!("{}.{new_segment}", &old[..i]),
1312        None => new_segment.to_string(),
1313    }
1314}
1315
1316/// The member segment of a (possibly compound) key name — the text the rename
1317/// actually edits (every site span covers exactly this).
1318fn key_segment(name: &str) -> &str {
1319    name.rsplit('.').next().unwrap_or(name)
1320}
1321
1322/// Validator (1): refuse when the edited project carries a diagnostic the
1323/// original did not — compared as per-(file, category) counts, robust to
1324/// span shifts. Removals are tolerated; additions refuse.
1325pub fn no_new_diagnostics(
1326    pre: &[(PathBuf, String)],
1327    post: &[(PathBuf, String)],
1328) -> Result<(), String> {
1329    let mut budget: HashMap<(&Path, &str), isize> = HashMap::new();
1330    for (p, c) in pre {
1331        *budget.entry((p.as_path(), c.as_str())).or_default() += 1;
1332    }
1333    for (p, c) in post {
1334        let n = budget.entry((p.as_path(), c.as_str())).or_default();
1335        *n -= 1;
1336        if *n < 0 {
1337            return Err(format!(
1338                "rename would introduce `{c}` in {} — refused",
1339                p.display()
1340            ));
1341        }
1342    }
1343    Ok(())
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348    /// Context-free resolution, as the unit-scope tests read it.
1349    fn resolve_doc_link(
1350        index: &ProjectIndex,
1351        scope: &HashMap<String, Vec<String>>,
1352        unit: &str,
1353        name: &str,
1354    ) -> Option<SiteRef> {
1355        resolve_doc_link_in(index, scope, unit, name, None)
1356            .resolved()
1357            .map(|r| r.def)
1358    }
1359
1360    /// #2530: a built-in is offered wherever it is written, including with the
1361    /// cursor on its first character right after punctuation, and not as a
1362    /// member name.
1363    #[test]
1364    fn prepare_type_hierarchy_resolves_a_built_in_by_its_token() {
1365        let index = ProjectIndex::default();
1366        let path = Path::new("a.bynk");
1367        let text = "fn f(a: List<Int>, b:String, c: x.Bool) -> Int { 1 }\n";
1368        let at = |needle: &str| text.find(needle).unwrap();
1369        let prepared = |offset: usize| match prepare_type_hierarchy(&index, path, text, offset) {
1370            Some(HierarchyTarget::Primitive(base, site)) => Some((base, site.span.start)),
1371            _ => None,
1372        };
1373        // A parameter type's argument, cursor on `I` after `<`.
1374        assert_eq!(prepared(at("Int>")), Some((BaseType::Int, at("Int>"))));
1375        // No space after the colon; cursor mid-token too.
1376        assert_eq!(
1377            prepared(at("String")),
1378            Some((BaseType::String, at("String")))
1379        );
1380        assert_eq!(
1381            prepared(at("String") + 2),
1382            Some((BaseType::String, at("String")))
1383        );
1384        // The return type.
1385        assert_eq!(prepared(at("Int {")), Some((BaseType::Int, at("Int {"))));
1386        // A member name, a non-built-in and punctuation offer nothing.
1387        assert_eq!(prepared(at("Bool")), None);
1388        assert_eq!(prepared(at("List")), None);
1389        assert_eq!(prepared(at("<Int")), None);
1390    }
1391
1392    use super::*;
1393    use bynk_check::index::{SymbolEntry, SymbolKind};
1394
1395    fn site(path: &str, start: usize, end: usize) -> SiteRef {
1396        SiteRef {
1397            path: PathBuf::from(path),
1398            span: Span::new(start, end),
1399        }
1400    }
1401
1402    fn key(unit: &str, kind: SymbolKind, name: &str) -> SymbolKey {
1403        SymbolKey {
1404            unit: unit.into(),
1405            kind,
1406            name: name.into(),
1407        }
1408    }
1409
1410    fn index_with(entries: Vec<(SymbolKey, SiteRef, Vec<SiteRef>)>) -> ProjectIndex {
1411        let mut index = ProjectIndex::default();
1412        for (k, def, refs) in entries {
1413            index.symbols.insert(
1414                k,
1415                SymbolEntry {
1416                    def: Some(def),
1417                    refs,
1418                    ..Default::default()
1419                },
1420            );
1421        }
1422        index
1423    }
1424
1425    #[test]
1426    fn new_name_validation() {
1427        assert!(validate_new_name("Money2").is_ok());
1428        assert!(validate_new_name("snake_case").is_ok());
1429        assert!(validate_new_name("fn").is_err(), "keyword");
1430        assert!(validate_new_name("two words").is_err());
1431        assert!(validate_new_name("1abc").is_err());
1432        assert!(validate_new_name("a.b").is_err());
1433        assert!(validate_new_name("").is_err());
1434    }
1435
1436    #[test]
1437    fn apply_and_remap_agree() {
1438        // text: "fn helper(x: Int) -> Int { helper(x) }"
1439        //        3..9 def                  27..33 ref
1440        let text = "fn helper(x: Int) -> Int { helper(x) }";
1441        let k = key("demo.a", SymbolKind::Fn, "helper");
1442        let index = index_with(vec![(
1443            k.clone(),
1444            site("a.bynk", 3, 9),
1445            vec![site("a.bynk", 27, 33)],
1446        )]);
1447        let plan = plan_rename(&index, Path::new("a.bynk"), 4, "do_it").unwrap();
1448        let edited = apply_edits(text, &plan.edits[Path::new("a.bynk")], "do_it");
1449        assert_eq!(edited, "fn do_it(x: Int) -> Int { do_it(x) }");
1450
1451        // Remap maps both old sites onto the new spellings.
1452        for (old, expected) in [
1453            (site("a.bynk", 3, 9), "do_it"),
1454            (site("a.bynk", 27, 33), "do_it"),
1455        ] {
1456            let new = remap_site(&old, &plan);
1457            assert_eq!(&edited[new.span.range()], expected);
1458        }
1459        // An unedited later site shifts by the accumulated delta.
1460        let unrelated = site("a.bynk", 34, 35); // `x` argument
1461        let new = remap_site(&unrelated, &plan);
1462        assert_eq!(&edited[new.span.range()], "x");
1463    }
1464
1465    #[test]
1466    fn references_listing_orders_definition_first() {
1467        let k = key("demo.a", SymbolKind::Type, "Money");
1468        let index = index_with(vec![(
1469            k,
1470            site("a.bynk", 5, 10),
1471            vec![site("b.bynk", 1, 6), site("a.bynk", 20, 25)],
1472        )]);
1473        let all = sites_for(&index, Path::new("b.bynk"), 3, true).unwrap();
1474        assert_eq!(all.len(), 3);
1475        assert_eq!(all[0].path, PathBuf::from("a.bynk"));
1476        assert_eq!(all[0].span, Span::new(5, 10));
1477        let without_decl = sites_for(&index, Path::new("b.bynk"), 3, false).unwrap();
1478        assert_eq!(without_decl.len(), 2);
1479    }
1480
1481    #[test]
1482    fn rename_refuses_unindexed_positions_and_same_name() {
1483        let k = key("demo.a", SymbolKind::Fn, "helper");
1484        let index = index_with(vec![(k, site("a.bynk", 3, 9), vec![])]);
1485        assert!(plan_rename(&index, Path::new("a.bynk"), 100, "x").is_err());
1486        assert!(plan_rename(&index, Path::new("a.bynk"), 4, "helper").is_err());
1487    }
1488
1489    #[test]
1490    fn index_equality_detects_escape() {
1491        // Pre: `helper` has no references; some other symbol unchanged.
1492        let helper = key("demo.a", SymbolKind::Fn, "helper");
1493        let money = key("demo.a", SymbolKind::Type, "Money");
1494        let pre = index_with(vec![
1495            (helper.clone(), site("a.bynk", 3, 9), vec![]),
1496            (money.clone(), site("a.bynk", 50, 55), vec![]),
1497        ]);
1498        let plan = plan_rename(&pre, Path::new("a.bynk"), 4, "shadow").unwrap();
1499
1500        // Post (honest): def renamed in place, still no refs.
1501        let honest = index_with(vec![
1502            (
1503                key("demo.a", SymbolKind::Fn, "shadow"),
1504                site("a.bynk", 3, 9),
1505                vec![],
1506            ),
1507            (money.clone(), site("a.bynk", 50, 55), vec![]),
1508        ]);
1509        assert!(index_unchanged_modulo_rename(&pre, &honest, &plan));
1510
1511        // Post (escape): a site that used to bind elsewhere now resolves to
1512        // the renamed symbol — an extra reference appears.
1513        let escape = index_with(vec![
1514            (
1515                key("demo.a", SymbolKind::Fn, "shadow"),
1516                site("a.bynk", 3, 9),
1517                vec![site("a.bynk", 70, 76)],
1518            ),
1519            (money, site("a.bynk", 50, 55), vec![]),
1520        ]);
1521        assert!(!index_unchanged_modulo_rename(&pre, &escape, &plan));
1522    }
1523
1524    #[test]
1525    fn method_rename_edits_the_member_segment_and_remaps_the_compound_key() {
1526        // v0.36: a method key is compound (`"Counter.bump"`), but the edit
1527        // touches only the `bump` segment — so the plan's new name is the bare
1528        // segment, the post key is `"Counter.increment"`, and the span delta is
1529        // against the segment length (4), not the compound length (12).
1530        let bump = key("demo.a", SymbolKind::Method, "Counter.bump");
1531        let other = key("demo.a", SymbolKind::Type, "Counter");
1532        let pre = index_with(vec![
1533            (other.clone(), site("a.bynk", 0, 5), vec![]),
1534            // def `bump` at 11..15, one call at 40..44.
1535            (
1536                bump.clone(),
1537                site("a.bynk", 11, 15),
1538                vec![site("a.bynk", 40, 44)],
1539            ),
1540        ]);
1541
1542        // Cursor on the def segment; rename to a longer name.
1543        let plan = plan_rename(&pre, Path::new("a.bynk"), 12, "increment").unwrap();
1544        assert_eq!(plan.key.name, "Counter.bump");
1545        assert_eq!(plan.new_name, "increment");
1546        // Renaming to the same segment is refused (segment-aware, not key-aware).
1547        assert!(plan_rename(&pre, Path::new("a.bynk"), 12, "bump").is_err());
1548
1549        // Honest post: the compound key becomes `Counter.increment`; the def
1550        // grows in place (11..20) and the call shifts by +5 (45..54).
1551        let post = index_with(vec![
1552            (other, site("a.bynk", 0, 5), vec![]),
1553            (
1554                key("demo.a", SymbolKind::Method, "Counter.increment"),
1555                site("a.bynk", 11, 20),
1556                vec![site("a.bynk", 45, 54)],
1557            ),
1558        ]);
1559        assert!(
1560            index_unchanged_modulo_rename(&pre, &post, &plan),
1561            "compound key remaps to Counter.increment and segment-based delta lines the spans up"
1562        );
1563    }
1564
1565    #[test]
1566    fn workspace_symbols_filters_and_orders() {
1567        let index = index_with(vec![
1568            (
1569                key("demo.a", SymbolKind::Type, "Money"),
1570                site("a.bynk", 5, 10),
1571                vec![],
1572            ),
1573            (
1574                key("demo.b", SymbolKind::Fn, "moneyMaker"),
1575                site("b.bynk", 3, 13),
1576                vec![],
1577            ),
1578            (
1579                key("demo.a", SymbolKind::Fn, "helper"),
1580                site("a.bynk", 40, 46),
1581                vec![],
1582            ),
1583        ]);
1584        // Case-insensitive substring match.
1585        let hits = workspace_symbols(&index, "money");
1586        assert_eq!(
1587            hits.iter()
1588                .map(|(k, _)| k.name.as_str())
1589                .collect::<Vec<_>>(),
1590            vec!["Money", "moneyMaker"]
1591        );
1592        // Empty query lists everything, (name, unit)-ordered.
1593        assert_eq!(workspace_symbols(&index, "").len(), 3);
1594        assert!(workspace_symbols(&index, "nothing").is_empty());
1595    }
1596
1597    #[test]
1598    fn document_highlights_are_file_scoped() {
1599        let k = key("demo.a", SymbolKind::Type, "Money");
1600        let index = index_with(vec![(
1601            k,
1602            site("a.bynk", 5, 10),
1603            vec![site("b.bynk", 1, 6), site("a.bynk", 20, 25)],
1604        )]);
1605        // From a.bynk: the definition + the in-file reference, not b.bynk's.
1606        let highlights = document_highlights(&index, Path::new("a.bynk"), 7).unwrap();
1607        assert_eq!(highlights.len(), 2);
1608        assert!(highlights.iter().all(|s| s.path == Path::new("a.bynk")));
1609        // No symbol at the cursor → None.
1610        assert!(document_highlights(&index, Path::new("a.bynk"), 100).is_none());
1611    }
1612
1613    #[test]
1614    fn diagnostic_budget_allows_removals_refuses_additions() {
1615        let pre = vec![
1616            (PathBuf::from("a.bynk"), "bynk.x".to_string()),
1617            (PathBuf::from("a.bynk"), "bynk.x".to_string()),
1618        ];
1619        let same = pre.clone();
1620        assert!(no_new_diagnostics(&pre, &same).is_ok());
1621        assert!(no_new_diagnostics(&pre, &pre[..1]).is_ok());
1622        let mut more = pre.clone();
1623        more.push((PathBuf::from("b.bynk"), "bynk.resolve.duplicate_fn".into()));
1624        assert!(no_new_diagnostics(&pre, &more).is_err());
1625    }
1626
1627    #[test]
1628    fn code_lenses_count_references_per_definition_in_the_file() {
1629        let index = index_with(vec![
1630            // `foo` defined in a.bynk with two references.
1631            (
1632                key("u", SymbolKind::Fn, "foo"),
1633                site("a.bynk", 3, 6),
1634                vec![site("a.bynk", 20, 23), site("b.bynk", 4, 7)],
1635            ),
1636            // `Bar` defined in a.bynk with no references (a 0-ref lens).
1637            (
1638                key("u", SymbolKind::Type, "Bar"),
1639                site("a.bynk", 40, 43),
1640                vec![],
1641            ),
1642            // `qux` defined in another file — no lens for a.bynk.
1643            (
1644                key("u", SymbolKind::Fn, "qux"),
1645                site("b.bynk", 0, 3),
1646                vec![],
1647            ),
1648        ]);
1649        let lenses = code_lenses(&index, Path::new("a.bynk"));
1650        assert_eq!(lenses.len(), 2, "two a.bynk defs get lenses");
1651        // Sorted by def position: foo (3..6) before Bar (40..43).
1652        assert_eq!((lenses[0].0.span.start, lenses[0].1.len()), (3, 2));
1653        assert_eq!((lenses[1].0.span.start, lenses[1].1.len()), (40, 0));
1654        assert!(code_lenses(&index, Path::new("c.bynk")).is_empty());
1655    }
1656
1657    #[test]
1658    fn call_hierarchy_groups_incoming_and_outgoing_by_symbol() {
1659        use bynk_check::index::CallEdge;
1660        // `a` and `b` both call `c`; `a` calls `c` twice. So `c`'s incoming
1661        // groups by caller (a with two sites, b with one), and `a`'s outgoing
1662        // is the single callee `c`.
1663        let mut index = index_with(vec![
1664            (key("u", SymbolKind::Fn, "a"), site("f.bynk", 3, 4), vec![]),
1665            (
1666                key("u", SymbolKind::Fn, "b"),
1667                site("f.bynk", 40, 41),
1668                vec![],
1669            ),
1670            (
1671                key("u", SymbolKind::Fn, "c"),
1672                site("f.bynk", 80, 81),
1673                vec![],
1674            ),
1675        ]);
1676        let edge = |caller: &str, cs: usize, ce: usize| CallEdge {
1677            caller: key("u", SymbolKind::Fn, caller),
1678            callee: key("u", SymbolKind::Fn, "c"),
1679            site: site("f.bynk", cs, ce),
1680        };
1681        index.calls = vec![edge("a", 10, 11), edge("a", 20, 21), edge("b", 50, 51)];
1682
1683        let into_c = incoming_calls(&index, &key("u", SymbolKind::Fn, "c"));
1684        // Sorted by caller def position: a (3) before b (40).
1685        assert_eq!(into_c.len(), 2);
1686        assert_eq!(
1687            (into_c[0].key.name.as_str(), into_c[0].sites.len()),
1688            ("a", 2)
1689        );
1690        assert_eq!(
1691            (into_c[1].key.name.as_str(), into_c[1].sites.len()),
1692            ("b", 1)
1693        );
1694
1695        let from_a = outgoing_calls(&index, &key("u", SymbolKind::Fn, "a"));
1696        assert_eq!(from_a.len(), 1);
1697        assert_eq!(
1698            (from_a[0].key.name.as_str(), from_a[0].sites.len()),
1699            ("c", 2)
1700        );
1701
1702        // `c` calls nothing; an unknown key yields nothing.
1703        assert!(outgoing_calls(&index, &key("u", SymbolKind::Fn, "c")).is_empty());
1704        assert!(incoming_calls(&index, &key("u", SymbolKind::Fn, "ghost")).is_empty());
1705    }
1706
1707    #[test]
1708    fn implementations_lists_provider_defs_for_a_capability() {
1709        use bynk_check::index::ImplEdge;
1710        // `Cap` is provided by `P1` and `P2`; `Other` (a capability) has none.
1711        let mut index = index_with(vec![
1712            (
1713                key("u", SymbolKind::Capability, "Cap"),
1714                site("a.bynk", 10, 13),
1715                vec![],
1716            ),
1717            (
1718                key("u", SymbolKind::Provider, "P1"),
1719                site("a.bynk", 50, 52),
1720                vec![],
1721            ),
1722            (
1723                key("u", SymbolKind::Provider, "P2"),
1724                site("b.bynk", 5, 7),
1725                vec![],
1726            ),
1727            (
1728                key("u", SymbolKind::Capability, "Other"),
1729                site("a.bynk", 80, 85),
1730                vec![],
1731            ),
1732        ]);
1733        let edge = |provider: &str, file: &str, s: usize, e: usize| ImplEdge {
1734            capability: key("u", SymbolKind::Capability, "Cap"),
1735            provider: key("u", SymbolKind::Provider, provider),
1736            site: site(file, s, e),
1737        };
1738        index.impls = vec![edge("P1", "a.bynk", 30, 33), edge("P2", "b.bynk", 20, 23)];
1739
1740        // Provider defs, sorted by position: P1 (a.bynk:50) before P2 (b.bynk:5).
1741        let impls = implementations(&index, &key("u", SymbolKind::Capability, "Cap"));
1742        assert_eq!(impls.len(), 2);
1743        assert_eq!(
1744            (&impls[0].path, impls[0].span.start),
1745            (&PathBuf::from("a.bynk"), 50)
1746        );
1747        assert_eq!(
1748            (&impls[1].path, impls[1].span.start),
1749            (&PathBuf::from("b.bynk"), 5)
1750        );
1751
1752        // A capability with no providers, and an unknown key, yield nothing.
1753        assert!(implementations(&index, &key("u", SymbolKind::Capability, "Other")).is_empty());
1754        assert!(implementations(&index, &key("u", SymbolKind::Capability, "Ghost")).is_empty());
1755    }
1756
1757    #[test]
1758    fn capability_provider_lenses_pair_a_capability_with_its_providers() {
1759        use bynk_check::index::ImplEdge;
1760        // `Cap` (defined in a.bynk) is provided by `P1`/`P2`; `Other` (a.bynk)
1761        // has no provider — so no lens; `Elsewhere` lives in b.bynk — no a.bynk lens.
1762        let mut index = index_with(vec![
1763            (
1764                key("u", SymbolKind::Capability, "Cap"),
1765                site("a.bynk", 10, 13),
1766                vec![],
1767            ),
1768            (
1769                key("u", SymbolKind::Provider, "P1"),
1770                site("a.bynk", 50, 52),
1771                vec![],
1772            ),
1773            (
1774                key("u", SymbolKind::Provider, "P2"),
1775                site("b.bynk", 5, 7),
1776                vec![],
1777            ),
1778            (
1779                key("u", SymbolKind::Capability, "Other"),
1780                site("a.bynk", 80, 85),
1781                vec![],
1782            ),
1783            (
1784                key("u", SymbolKind::Capability, "Elsewhere"),
1785                site("b.bynk", 90, 99),
1786                vec![],
1787            ),
1788        ]);
1789        index.impls = vec![
1790            ImplEdge {
1791                capability: key("u", SymbolKind::Capability, "Cap"),
1792                provider: key("u", SymbolKind::Provider, "P1"),
1793                site: site("a.bynk", 30, 33),
1794            },
1795            ImplEdge {
1796                capability: key("u", SymbolKind::Capability, "Cap"),
1797                provider: key("u", SymbolKind::Provider, "P2"),
1798                site: site("b.bynk", 20, 23),
1799            },
1800        ];
1801
1802        let lenses = capability_provider_lenses(&index, Path::new("a.bynk"));
1803        // Only `Cap` qualifies: `Other` has no providers, `Elsewhere` is off-file.
1804        assert_eq!(lenses.len(), 1);
1805        assert_eq!(lenses[0].0.span.start, 10);
1806        assert_eq!(lenses[0].1.len(), 2, "Cap has two providers");
1807        // Off-file query and a provider-less file yield nothing.
1808        assert!(capability_provider_lenses(&index, Path::new("c.bynk")).is_empty());
1809    }
1810
1811    #[test]
1812    fn refinement_family_lenses_group_refined_types_by_builtin_base() {
1813        use bynk_check::index::RefineEdge;
1814        // Email/UserId (a.bynk) + Slug (b.bynk) refine String — a family of 3;
1815        // Age refines Int alone (no family); Order is a record (no base).
1816        let mut index = index_with(vec![
1817            (
1818                key("u", SymbolKind::Type, "Email"),
1819                site("a.bynk", 10, 15),
1820                vec![],
1821            ),
1822            (
1823                key("u", SymbolKind::Type, "UserId"),
1824                site("a.bynk", 40, 46),
1825                vec![],
1826            ),
1827            (
1828                key("u", SymbolKind::Type, "Slug"),
1829                site("b.bynk", 5, 9),
1830                vec![],
1831            ),
1832            (
1833                key("u", SymbolKind::Type, "Age"),
1834                site("a.bynk", 70, 73),
1835                vec![],
1836            ),
1837            (
1838                key("u", SymbolKind::Type, "Order"),
1839                site("a.bynk", 90, 95),
1840                vec![],
1841            ),
1842        ]);
1843        let refine = |name: &str, base: BaseType| RefineEdge {
1844            base,
1845            opaque: false,
1846            base_site: site("a.bynk", 0, 0),
1847            ty: key("u", SymbolKind::Type, name),
1848        };
1849        index.refinements = vec![
1850            refine("Email", BaseType::String),
1851            refine("UserId", BaseType::String),
1852            refine("Slug", BaseType::String),
1853            refine("Age", BaseType::Int),
1854        ];
1855
1856        let lenses = refinement_family_lenses(&index, Path::new("a.bynk"));
1857        // Email + UserId qualify (the String family has 3 members, ≥ 2). `Age` is
1858        // alone over Int — no lens. `Order` has no base. `Slug` is off-file.
1859        assert_eq!(lenses.len(), 2);
1860        // Sorted by def position: Email (10) before UserId (40).
1861        assert_eq!(
1862            (lenses[0].0.span.start, lenses[0].1),
1863            (10, BaseType::String)
1864        );
1865        assert_eq!(lenses[0].2.len(), 3, "the String family spans 3 types");
1866        assert_eq!(lenses[1].0.span.start, 40);
1867        // Off-file query yields nothing.
1868        assert!(refinement_family_lenses(&index, Path::new("c.bynk")).is_empty());
1869    }
1870
1871    #[test]
1872    fn type_definitions_named_collects_type_defs_by_bare_name() {
1873        // Two units each declare an `Order` type; a fn shares the name.
1874        let index = index_with(vec![
1875            (
1876                key("a", SymbolKind::Type, "Order"),
1877                site("a.bynk", 10, 15),
1878                vec![],
1879            ),
1880            (
1881                key("b", SymbolKind::Type, "Order"),
1882                site("b.bynk", 4, 9),
1883                vec![],
1884            ),
1885            (
1886                key("a", SymbolKind::Fn, "Order"),
1887                site("a.bynk", 40, 45),
1888                vec![],
1889            ),
1890        ]);
1891        // Both `Type` defs (not the fn), sorted by position.
1892        let defs = type_definitions_named(&index, "Order");
1893        assert_eq!(defs.len(), 2);
1894        assert_eq!(
1895            (&defs[0].path, defs[0].span.start),
1896            (&PathBuf::from("a.bynk"), 10)
1897        );
1898        assert_eq!(
1899            (&defs[1].path, defs[1].span.start),
1900            (&PathBuf::from("b.bynk"), 4)
1901        );
1902        // An unknown type name yields nothing.
1903        assert!(type_definitions_named(&index, "Nope").is_empty());
1904    }
1905
1906    fn doc_scope_with(entries: Vec<(&str, Vec<&str>)>) -> HashMap<String, Vec<String>> {
1907        entries
1908            .into_iter()
1909            .map(|(unit, scope)| {
1910                (
1911                    unit.to_string(),
1912                    scope.into_iter().map(String::from).collect(),
1913                )
1914            })
1915            .collect()
1916    }
1917
1918    #[test]
1919    fn doc_link_suggestions_follow_resolution_order() {
1920        let index = index_with(vec![
1921            (
1922                key("window", SymbolKind::Fn, "decide"),
1923                site("w.bynk", 1, 7),
1924                vec![],
1925            ),
1926            (
1927                key("ratelimit", SymbolKind::Type, "Zed"),
1928                site("r.bynk", 1, 4),
1929                vec![],
1930            ),
1931            (
1932                key("ratelimit", SymbolKind::Agent, "Limiter"),
1933                site("r.bynk", 9, 16),
1934                vec![],
1935            ),
1936            (
1937                key("platform", SymbolKind::Capability, "Clock2"),
1938                site("p.bynk", 1, 7),
1939                vec![],
1940            ),
1941        ]);
1942        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit", "window", "platform"])]);
1943        let got = doc_link_suggestions(&index, &scope, "ratelimit", None, None);
1944        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
1945        assert_eq!(names, ["Limiter", "Zed", "decide", "Clock2"]);
1946    }
1947
1948    #[test]
1949    fn doc_link_suggestions_drop_ambiguous_names_and_qualify_shadowed_ones() {
1950        let index = index_with(vec![
1951            (
1952                key("ratelimit", SymbolKind::Type, "Dup"),
1953                site("r.bynk", 1, 4),
1954                vec![],
1955            ),
1956            (
1957                key("ratelimit", SymbolKind::Fn, "Dup"),
1958                site("r.bynk", 9, 12),
1959                vec![],
1960            ),
1961            (
1962                key("ratelimit", SymbolKind::Type, "Shared"),
1963                site("r.bynk", 20, 26),
1964                vec![],
1965            ),
1966            (
1967                key("window", SymbolKind::Type, "Shared"),
1968                site("w.bynk", 1, 7),
1969                vec![],
1970            ),
1971        ]);
1972        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit", "window"])]);
1973        let got = doc_link_suggestions(&index, &scope, "ratelimit", None, None);
1974        // `Dup` is ambiguous in its unit (no form resolves); `Shared` resolves
1975        // bare to `ratelimit`'s, and `window`'s is offered qualified.
1976        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
1977        assert_eq!(names, ["Shared", "window.Shared"], "{got:?}");
1978        assert_eq!(got[1].unit, "window");
1979    }
1980
1981    #[test]
1982    fn doc_link_suggestions_offer_own_fields_first_and_shadow_unit_names() {
1983        let index = index_with(vec![
1984            (
1985                key("u", SymbolKind::Type, "View"),
1986                site("u.bynk", 10, 14),
1987                vec![],
1988            ),
1989            (
1990                key("u", SymbolKind::Field, "View.remaining"),
1991                site("u.bynk", 30, 39),
1992                vec![],
1993            ),
1994            (
1995                key("u", SymbolKind::Field, "View.id"),
1996                site("u.bynk", 20, 22),
1997                vec![],
1998            ),
1999            (
2000                key("u", SymbolKind::Fn, "id"),
2001                site("u.bynk", 90, 92),
2002                vec![],
2003            ),
2004        ]);
2005        let scope = doc_scope_with(vec![("u", vec!["u"])]);
2006        let ctx = DocLinkContext {
2007            path: Path::new("u.bynk"),
2008            text: "",
2009            attached: 10,
2010            locals: &[],
2011        };
2012        let got = doc_link_suggestions(&index, &scope, "u", None, Some(&ctx));
2013        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
2014        // Fields in source order, then the unit scope; the fn `id` is shadowed
2015        // by the field, so it is offered qualified.
2016        assert_eq!(names, ["id", "remaining", "View", "u.id"], "{got:?}");
2017        assert_eq!(got[0].kind, Some(SymbolKind::Field));
2018        // Every offered name resolves, in this context, to what was offered.
2019        for s in &got {
2020            assert!(
2021                resolve_doc_link_in(&index, &scope, "u", &s.name, Some(&ctx))
2022                    .resolved()
2023                    .is_some()
2024            );
2025        }
2026        // Without a context there are no own parts and `id` is the fn.
2027        let got = doc_link_suggestions(&index, &scope, "u", None, None);
2028        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
2029        assert_eq!(names, ["View", "id"]);
2030    }
2031
2032    #[test]
2033    fn doc_link_suggestions_offer_a_fns_parameters_first() {
2034        let text = "fn f(order: Int, n: Int) -> Int { xs.fold(0, (acc, x) => acc + x) }\n";
2035        let at = |needle: &str| text.find(needle).unwrap();
2036        let span = |n: &str| (at(n), at(n) + n.len());
2037        let body = (at("{"), text.len());
2038        let index = index_with(vec![
2039            (key("u", SymbolKind::Fn, "f"), site("u.bynk", 3, 4), vec![]),
2040            (
2041                key("u", SymbolKind::Fn, "order"),
2042                site("u.bynk", 200, 205),
2043                vec![],
2044            ),
2045        ]);
2046        let scope = doc_scope_with(vec![("u", vec!["u"])]);
2047        let locals = vec![
2048            ctx_locals("n", (at("n:"), at("n:") + 1), body),
2049            ctx_locals("order", span("order"), body),
2050            ctx_locals("acc", span("acc"), (body.0 + 20, body.1)),
2051        ];
2052        let ctx = DocLinkContext {
2053            path: Path::new("u.bynk"),
2054            text,
2055            attached: 3,
2056            locals: &locals,
2057        };
2058        let got = doc_link_suggestions(&index, &scope, "u", None, Some(&ctx));
2059        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
2060        // Source order; the lambda's `acc` is not a parameter of `f`; the
2061        // unit-level `order` is shadowed by the parameter, so is qualified.
2062        assert_eq!(names, ["order", "n", "f", "u.order"], "{got:?}");
2063        assert_eq!(got[0].kind, None);
2064    }
2065
2066    #[test]
2067    fn doc_link_suggestions_after_an_owner_offer_its_members() {
2068        let index = index_with(vec![
2069            (
2070                key("ratelimit", SymbolKind::Field, "RateView.remaining"),
2071                site("r.bynk", 1, 9),
2072                vec![],
2073            ),
2074            (
2075                key("ratelimit", SymbolKind::Field, "RateView.limit"),
2076                site("r.bynk", 12, 17),
2077                vec![],
2078            ),
2079            (
2080                key("ratelimit", SymbolKind::Field, "Other.x"),
2081                site("r.bynk", 20, 21),
2082                vec![],
2083            ),
2084        ]);
2085        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit"])]);
2086        let got = doc_link_suggestions(&index, &scope, "ratelimit", Some("RateView"), None);
2087        let labels: Vec<_> = got.iter().map(|s| s.label.as_str()).collect();
2088        assert_eq!(labels, ["limit", "remaining"]);
2089        assert!(doc_link_suggestions(&index, &scope, "nope", None, None).is_empty());
2090    }
2091
2092    #[test]
2093    fn doc_link_suggestions_after_a_unit_prefix_offer_its_names() {
2094        let index = index_with(vec![
2095            (
2096                key("a.b", SymbolKind::Fn, "decide"),
2097                site("b.bynk", 5, 11),
2098                vec![],
2099            ),
2100            (
2101                key("a.b", SymbolKind::Type, "Verdict"),
2102                site("b.bynk", 20, 27),
2103                vec![],
2104            ),
2105            (
2106                key("a.b", SymbolKind::Field, "Verdict.reason"),
2107                site("b.bynk", 30, 36),
2108                vec![],
2109            ),
2110            (
2111                key("u", SymbolKind::Fn, "other"),
2112                site("u.bynk", 1, 6),
2113                vec![],
2114            ),
2115        ]);
2116        // `a.b` is not in `u`'s scope: unit-qualified links resolve anyway.
2117        let scope = doc_scope_with(vec![("u", vec!["u"])]);
2118        let got = doc_link_suggestions(&index, &scope, "u", Some("a.b"), None);
2119        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
2120        assert_eq!(names, ["a.b.Verdict", "a.b.decide"]);
2121        assert_eq!(got[0].label, "Verdict");
2122        assert!(doc_link_suggestions(&index, &scope, "u", Some("zz"), None).is_empty());
2123    }
2124
2125    #[test]
2126    fn doc_link_suggestions_after_a_unit_prefix_follow_resolution() {
2127        let index = index_with(vec![
2128            // `dup` is a type and a fn in the unit: ambiguous, so no form resolves.
2129            (
2130                key("a.b", SymbolKind::Type, "dup"),
2131                site("b.bynk", 1, 4),
2132                vec![],
2133            ),
2134            (
2135                key("a.b", SymbolKind::Fn, "dup"),
2136                site("b.bynk", 10, 13),
2137                vec![],
2138            ),
2139            (
2140                key("a.b", SymbolKind::Fn, "decide"),
2141                site("b.bynk", 20, 26),
2142                vec![],
2143            ),
2144            // `View` is both an in-scope owner and a unit.
2145            (
2146                key("u", SymbolKind::Field, "View.total"),
2147                site("u.bynk", 1, 6),
2148                vec![],
2149            ),
2150            (
2151                key("View", SymbolKind::Fn, "build"),
2152                site("v.bynk", 1, 6),
2153                vec![],
2154            ),
2155        ]);
2156        let scope = doc_scope_with(vec![("u", vec!["u"])]);
2157        let got = doc_link_suggestions(&index, &scope, "u", Some("a.b"), None);
2158        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
2159        assert_eq!(names, ["a.b.decide"]);
2160        let got = doc_link_suggestions(&index, &scope, "u", Some("View"), None);
2161        let names: Vec<_> = got.iter().map(|s| s.name.as_str()).collect();
2162        assert_eq!(names, ["View.total", "View.build"]);
2163    }
2164
2165    #[test]
2166    fn resolve_doc_link_finds_a_bare_local_hit() {
2167        let index = index_with(vec![(
2168            key("ratelimit", SymbolKind::Agent, "Limiter"),
2169            site("ratelimit.bynk", 10, 17),
2170            vec![],
2171        )]);
2172        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit"])]);
2173        let def = resolve_doc_link(&index, &scope, "ratelimit", "Limiter").unwrap();
2174        assert_eq!(def.path, PathBuf::from("ratelimit.bynk"));
2175    }
2176
2177    #[test]
2178    fn resolve_doc_link_finds_a_dotted_local_hit() {
2179        let index = index_with(vec![(
2180            key("ratelimit", SymbolKind::Field, "RateView.remaining"),
2181            site("ratelimit.bynk", 20, 29),
2182            vec![],
2183        )]);
2184        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit"])]);
2185        let def = resolve_doc_link(&index, &scope, "ratelimit", "RateView.remaining").unwrap();
2186        assert_eq!(def.path, PathBuf::from("ratelimit.bynk"));
2187    }
2188
2189    #[test]
2190    fn resolve_doc_link_follows_the_uses_chain() {
2191        // `decide` isn't declared in `ratelimit`, only in `window`, which
2192        // `ratelimit` `uses` — the scope order (built the same way
2193        // `doc_scope` is assembled) puts `window` after the local unit.
2194        let index = index_with(vec![(
2195            key("window", SymbolKind::Fn, "decide"),
2196            site("window.bynk", 5, 11),
2197            vec![],
2198        )]);
2199        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit", "window"])]);
2200        let def = resolve_doc_link(&index, &scope, "ratelimit", "decide").unwrap();
2201        assert_eq!(def.path, PathBuf::from("window.bynk"));
2202    }
2203
2204    #[test]
2205    fn resolve_doc_link_finds_an_asset_through_uses() {
2206        // #1883: an asset is a bare top-level name like a fn.
2207        let index = index_with(vec![(
2208            key("page", SymbolKind::Asset, "style"),
2209            site("page.bynk", 5, 10),
2210            vec![],
2211        )]);
2212        let scope = doc_scope_with(vec![("board", vec!["board", "page"])]);
2213        let def = resolve_doc_link(&index, &scope, "board", "style").unwrap();
2214        assert_eq!(def.path, PathBuf::from("page.bynk"));
2215    }
2216
2217    #[test]
2218    fn resolve_doc_link_finds_an_embed_through_uses() {
2219        // #2387: an embed is a bare top-level name like an asset.
2220        let index = index_with(vec![(
2221            key("page", SymbolKind::Embed, "shell"),
2222            site("page.bynk", 5, 10),
2223            vec![],
2224        )]);
2225        let scope = doc_scope_with(vec![("board", vec!["board", "page"])]);
2226        let def = resolve_doc_link(&index, &scope, "board", "shell").unwrap();
2227        assert_eq!(def.path, PathBuf::from("page.bynk"));
2228    }
2229
2230    #[test]
2231    fn resolve_doc_link_follows_the_consumes_chain_after_uses() {
2232        let index = index_with(vec![(
2233            key("platform", SymbolKind::Capability, "Clock"),
2234            site("platform.bynk", 0, 5),
2235            vec![],
2236        )]);
2237        // `uses` targets come before `consumes` targets in scope order; a name
2238        // only found via `consumes` still resolves, just later in the search.
2239        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit", "window", "platform"])]);
2240        let def = resolve_doc_link(&index, &scope, "ratelimit", "Clock").unwrap();
2241        assert_eq!(def.path, PathBuf::from("platform.bynk"));
2242    }
2243
2244    #[test]
2245    fn resolve_doc_link_is_none_when_nothing_in_scope_matches() {
2246        let index = index_with(vec![(
2247            key("ratelimit", SymbolKind::Agent, "Limiter"),
2248            site("ratelimit.bynk", 10, 17),
2249            vec![],
2250        )]);
2251        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit"])]);
2252        assert!(resolve_doc_link(&index, &scope, "ratelimit", "Nope").is_none());
2253    }
2254
2255    #[test]
2256    fn resolve_doc_link_is_none_for_a_synthetic_unit_never_in_scope() {
2257        // A synthetic (first-party) unit's symbols never make it into
2258        // `index.symbols` at all (their defs are dropped at assembly), so a
2259        // name that only exists through one comes back unresolved even
2260        // though `bynk` is a `consumes` target in scope.
2261        let index = ProjectIndex::default();
2262        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit", "bynk"])]);
2263        assert!(resolve_doc_link(&index, &scope, "ratelimit", "Clock.now").is_none());
2264    }
2265
2266    #[test]
2267    fn doc_link_owner_declared_sees_a_shadowing_project_declaration() {
2268        let index = index_with(vec![(
2269            key("window", SymbolKind::Type, "Clock"),
2270            site("window.bynk", 0, 5),
2271            vec![],
2272        )]);
2273        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit", "bynk", "window"])]);
2274        assert!(doc_link_owner_declared(
2275            &index,
2276            &scope,
2277            "ratelimit",
2278            "Clock"
2279        ));
2280        assert!(!doc_link_owner_declared(&index, &scope, "ratelimit", "Kv"));
2281    }
2282
2283    #[test]
2284    fn resolve_doc_link_is_none_when_the_owner_unit_has_no_scope_entry() {
2285        let index = ProjectIndex::default();
2286        let scope = doc_scope_with(vec![]);
2287        assert!(resolve_doc_link(&index, &scope, "ratelimit", "Limiter").is_none());
2288    }
2289
2290    #[test]
2291    fn resolve_doc_link_never_guesses_an_ambiguous_first_matching_unit() {
2292        // Two different candidate kinds share the bare name `Order` in the
2293        // *first* scope-order unit — even though a later unit in scope order
2294        // would resolve unambiguously, the ambiguity in the first matching
2295        // unit wins: unresolved, never a guess.
2296        let index = index_with(vec![
2297            (
2298                key("ratelimit", SymbolKind::Type, "Order"),
2299                site("ratelimit.bynk", 10, 15),
2300                vec![],
2301            ),
2302            (
2303                key("ratelimit", SymbolKind::Fn, "Order"),
2304                site("ratelimit.bynk", 40, 45),
2305                vec![],
2306            ),
2307            (
2308                key("window", SymbolKind::Type, "Order"),
2309                site("window.bynk", 0, 5),
2310                vec![],
2311            ),
2312        ]);
2313        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit", "window"])]);
2314        assert!(resolve_doc_link(&index, &scope, "ratelimit", "Order").is_none());
2315    }
2316
2317    #[test]
2318    fn doc_link_matches_reports_every_kind_in_the_first_matching_unit() {
2319        let index = index_with(vec![
2320            (
2321                key("ratelimit", SymbolKind::Type, "Order"),
2322                site("ratelimit.bynk", 10, 15),
2323                vec![],
2324            ),
2325            (
2326                key("ratelimit", SymbolKind::Fn, "Order"),
2327                site("ratelimit.bynk", 40, 45),
2328                vec![],
2329            ),
2330        ]);
2331        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit"])]);
2332        let kinds = |name| {
2333            doc_link_matches(&index, &scope, "ratelimit", name)
2334                .map(|m| m.iter().map(|(k, _)| k.kind).collect::<Vec<_>>())
2335        };
2336        assert_eq!(kinds("Order"), Some(vec![SymbolKind::Type, SymbolKind::Fn]));
2337        assert_eq!(kinds("Nope"), None);
2338    }
2339
2340    #[test]
2341    fn resolve_doc_link_in_reports_ambiguous_and_still_tries_unit_qualified() {
2342        let index = index_with(vec![
2343            (
2344                key("ratelimit", SymbolKind::Type, "Order"),
2345                site("ratelimit.bynk", 10, 15),
2346                vec![],
2347            ),
2348            (
2349                key("ratelimit", SymbolKind::Fn, "Order"),
2350                site("ratelimit.bynk", 40, 45),
2351                vec![],
2352            ),
2353            (
2354                key("other", SymbolKind::Type, "Order"),
2355                site("other.bynk", 1, 6),
2356                vec![],
2357            ),
2358        ]);
2359        let scope = doc_scope_with(vec![("ratelimit", vec!["ratelimit"])]);
2360        assert_eq!(
2361            resolve_doc_link_in(&index, &scope, "ratelimit", "Order", None),
2362            DocLinkResolution::Ambiguous {
2363                unit: "ratelimit".into(),
2364                kinds: vec![SymbolKind::Type, SymbolKind::Fn],
2365            }
2366        );
2367        assert_eq!(
2368            resolve_doc_link_in(&index, &scope, "ratelimit", "Nope", None),
2369            DocLinkResolution::Unresolved
2370        );
2371        let hit = resolve_doc_link_in(&index, &scope, "ratelimit", "other.Order", None)
2372            .resolved()
2373            .unwrap();
2374        assert_eq!(hit.def.path, PathBuf::from("other.bynk"));
2375    }
2376
2377    #[test]
2378    fn named_type_target_unwraps_single_param_containers() {
2379        use bynk_check::checker::{NamedKind, Types};
2380        use bynk_syntax::ast::BaseType;
2381        let tys = &Types::new();
2382        let order = || {
2383            tys.intern(Ty::Named {
2384                name: "Order".into(),
2385                kind: NamedKind::Record,
2386                args: Vec::new(),
2387            })
2388        };
2389        let target = |t| named_type_target(t, tys);
2390        assert_eq!(target(order()).as_deref(), Some("Order"));
2391        assert_eq!(
2392            target(tys.intern(Ty::Option(order()))).as_deref(),
2393            Some("Order")
2394        );
2395        // Nested single-param containers unwrap all the way.
2396        let effect = tys.intern(Ty::Effect(order()));
2397        assert_eq!(
2398            target(tys.intern(Ty::List(effect))).as_deref(),
2399            Some("Order")
2400        );
2401        // Built-in, two-parameter, and unit types have no single target.
2402        assert_eq!(target(tys.intern(Ty::Base(BaseType::Int))), None);
2403        assert_eq!(target(tys.intern(Ty::Result(order(), order()))), None);
2404        assert_eq!(target(tys.intern(Ty::Unit)), None);
2405    }
2406
2407    fn ctx_locals(name: &str, def: (usize, usize), scope: (usize, usize)) -> LocalBinding {
2408        LocalBinding {
2409            name: name.to_string(),
2410            def_span: Span::new(def.0, def.1),
2411            kind: LocalKind::Param,
2412            ty: "Int".to_string(),
2413            scope: Span::new(scope.0, scope.1),
2414        }
2415    }
2416
2417    #[test]
2418    fn resolve_doc_link_in_prefers_an_own_field_over_a_unit_name() {
2419        // `id` is both `View`'s field and a unit-level fn: inside `View`'s doc
2420        // the field wins; with no context the fn does.
2421        let index = index_with(vec![
2422            (
2423                key("u", SymbolKind::Type, "View"),
2424                site("u.bynk", 10, 14),
2425                vec![],
2426            ),
2427            (
2428                key("u", SymbolKind::Field, "View.id"),
2429                site("u.bynk", 20, 22),
2430                vec![],
2431            ),
2432            (
2433                key("u", SymbolKind::Fn, "id"),
2434                site("u.bynk", 90, 92),
2435                vec![],
2436            ),
2437        ]);
2438        let scope = doc_scope_with(vec![("u", vec!["u"])]);
2439        let ctx = DocLinkContext {
2440            path: Path::new("u.bynk"),
2441            text: "",
2442            attached: 10,
2443            locals: &[],
2444        };
2445        let hit = resolve_doc_link_in(&index, &scope, "u", "id", Some(&ctx))
2446            .resolved()
2447            .unwrap();
2448        assert_eq!(hit.def.span.start, 20);
2449        assert_eq!(hit.key.unwrap().kind, SymbolKind::Field);
2450        let hit = resolve_doc_link_in(&index, &scope, "u", "id", None)
2451            .resolved()
2452            .unwrap();
2453        assert_eq!(hit.def.span.start, 90);
2454    }
2455
2456    #[test]
2457    fn resolve_doc_link_in_finds_a_parameter_but_not_a_lambdas() {
2458        let text = "fn f(order: Int) -> Int { xs.fold(0, (acc, x) => acc + x) }\n\
2459                    fn total() -> Int { xs.fold(0, (acc, x) => acc + x) }\n";
2460        let at = |needle: &str, from: usize| from + text[from..].find(needle).unwrap();
2461        let (f, total) = (at("f(", 0), at("total", 0));
2462        let span = |start: usize, n: &str| (start, start + n.len());
2463        let order = span(at("order", 0), "order");
2464        let lambda = |from: usize| {
2465            let acc = at("acc", from);
2466            let x = at("x)", acc);
2467            (span(acc, "acc"), span(x, "x"))
2468        };
2469        let (acc1, x1) = lambda(f);
2470        let (acc2, x2) = lambda(total);
2471        let body1 = (at("{", f), at("}", f) + 1);
2472        let body2 = (at("{", total), at("}", total) + 1);
2473        let index = index_with(vec![
2474            (
2475                key("u", SymbolKind::Fn, "f"),
2476                site("u.bynk", f, f + 1),
2477                vec![],
2478            ),
2479            (
2480                key("u", SymbolKind::Fn, "total"),
2481                site("u.bynk", total, total + 5),
2482                vec![],
2483            ),
2484        ]);
2485        let scope = doc_scope_with(vec![("u", vec!["u"])]);
2486        let locals = vec![
2487            ctx_locals("order", order, body1),
2488            ctx_locals("acc", acc1, (body1.0 + 20, body1.1)),
2489            ctx_locals("x", x1, (body1.0 + 20, body1.1)),
2490            ctx_locals("acc", acc2, (body2.0 + 20, body2.1)),
2491            ctx_locals("x", x2, (body2.0 + 20, body2.1)),
2492        ];
2493        let ctx = |attached| DocLinkContext {
2494            path: Path::new("u.bynk"),
2495            text,
2496            attached,
2497            locals: &locals,
2498        };
2499        let hit = resolve_doc_link_in(&index, &scope, "u", "order", Some(&ctx(f)))
2500            .resolved()
2501            .unwrap();
2502        assert_eq!(hit.def.span, Span::new(order.0, order.1));
2503        assert!(hit.key.is_none());
2504        // A lambda's binder is not the fn's parameter, with or without parameters of its own.
2505        assert!(
2506            resolve_doc_link_in(&index, &scope, "u", "x", Some(&ctx(f)))
2507                .resolved()
2508                .is_none()
2509        );
2510        assert!(
2511            resolve_doc_link_in(&index, &scope, "u", "x", Some(&ctx(total)))
2512                .resolved()
2513                .is_none()
2514        );
2515        assert!(
2516            resolve_doc_link_in(&index, &scope, "u", "acc", Some(&ctx(total)))
2517                .resolved()
2518                .is_none()
2519        );
2520        // Another declaration's parameter is not this one's.
2521        assert!(
2522            resolve_doc_link_in(&index, &scope, "u", "order", Some(&ctx(total)))
2523                .resolved()
2524                .is_none()
2525        );
2526    }
2527
2528    #[test]
2529    fn resolve_doc_link_in_reads_a_unit_qualified_name_outside_scope() {
2530        let index = index_with(vec![
2531            (
2532                key("a.b", SymbolKind::Fn, "decide"),
2533                site("b.bynk", 5, 11),
2534                vec![],
2535            ),
2536            (
2537                key("u", SymbolKind::Field, "View.decide"),
2538                site("u.bynk", 20, 26),
2539                vec![],
2540            ),
2541        ]);
2542        let scope = doc_scope_with(vec![("u", vec!["u"])]);
2543        let hit = resolve_doc_link_in(&index, &scope, "u", "a.b.decide", None)
2544            .resolved()
2545            .unwrap();
2546        assert_eq!(hit.def.path, PathBuf::from("b.bynk"));
2547        // `Owner.member` is still read first.
2548        let hit = resolve_doc_link_in(&index, &scope, "u", "View.decide", None)
2549            .resolved()
2550            .unwrap();
2551        assert_eq!(hit.def.path, PathBuf::from("u.bynk"));
2552        assert!(
2553            resolve_doc_link_in(&index, &scope, "u", "zz.decide", None)
2554                .resolved()
2555                .is_none()
2556        );
2557    }
2558}