Skip to main content

bynk_ide/
hover.rs

1//! #611 (ADR 0190): hover's resolution ladder, as one pure function.
2//!
3//! #2520: lives in `bynk-ide` so the language server and `bynk mcp` render the
4//! same answer.
5//!
6//! `Backend::hover` is transport — it resolves the cursor position, gathers the
7//! round's tables and the live buffer, and packages the result as an LSP
8//! `Hover`. The *order* the rungs are tried in is the behaviour: #611's gap B was
9//! a fall-through bug, where a rung that resolved the offset correctly but
10//! rendered nothing let a later, name-matching rung answer instead — a
11//! confidently wrong hover. That order lives here, once, so a test can **pin** it
12//! rather than replicate it (a replica agrees with the original only until
13//! someone reorders one of them).
14//!
15//! Two text sources, deliberately: the index rungs read the round's **analysed
16//! snapshot** (the tables' spans index into it), while the lexical rungs read the
17//! **live buffer**, which is what makes hover work mid-edit. They diverge while
18//! the user types, so the ladder keeps them distinct rather than assuming one.
19//!
20//! The rungs, in trial order (see [`hover_content`]'s inline numbering):
21//! 1. the binding index — a resolved symbol reference, described from its
22//!    defining file (a resolved `Service` gets a #855 wire-contract appendix);
23//! 2. a `store` field operation;
24//! 3. a local/param/`self`;
25//! 4. #855: a handler's HEADER (`on`, the method/kind token, the route
26//!    literal) — guarded to that byte range so it cannot shadow rung 1;
27//!    4b. #2460: a doc-comment `[Name]` link — the cursor inside a doc-link
28//!    candidate span previews the link's target, resolved as the link itself
29//!    is (#2454: the attached declaration's own parts first), or says it is
30//!    ambiguous or unresolved;
31//!    guarded to doc-link spans, which hold no index reference, so it cannot
32//!    shadow rung 1;
33//! 5. #1885: a unit name — the header's, or a `uses`/`consumes`/suite target —
34//!    shown with the unit's module doc (lexical, first live-buffer rung);
35//! 6. a top-level declaration by name;
36//! 7. the `key`/`store` contextual keywords and agent-state references;
37//! 8. a handler-position `@cache` annotation;
38//! 9. a `Recv.member` name-receiver access;
39//! 10. a project-wide name scan;
40//! 11. the embedded first-party sources.
41
42use std::collections::HashMap;
43use std::path::{Path, PathBuf};
44
45use bynk_check::checker::Types;
46use bynk_check::index::SymbolKind;
47use bynk_syntax::span::Span;
48
49use crate::index_queries::{DocLinkResolution, resolve_doc_link_in};
50
51/// The analysed round's tables, positioned at the cursor.
52pub struct HoverAnalysis<'a> {
53    pub index: &'a bynk_check::index::ProjectIndex,
54    /// Project-relative path → the analysed text.
55    pub snapshots: &'a HashMap<PathBuf, String>,
56    pub locals: &'a bynk_check::locals::FileLocals,
57    pub expr_types: &'a bynk_check::expr_types::FileExprTypes,
58    /// T3.6b (R4.1): the table `expr_types`' `TyId`s resolve against.
59    pub tys: &'a Types,
60    /// The cursor's file (project-relative) and its offset **into the snapshot**.
61    pub rel: &'a Path,
62    pub offset: usize,
63    /// #2469: the round's capability paths, for the `given`-entry hover.
64    pub capability_paths: &'a bynk_check::capability_paths::FileCapabilityPaths,
65    /// #848: the round's project root — resolves a doc-link's `SiteRef` into
66    /// a `file://` hover-Markdown target.
67    pub project_root: &'a Path,
68    /// #848: qualified unit name → its doc-comment intra-doc-link search
69    /// order, for rung 1's doc-link rewrite.
70    pub doc_scope: &'a HashMap<String, Vec<String>>,
71    /// #855: qualified context/adapter unit name → the combined type table
72    /// and service/agent tables the wire-contract peek needs.
73    pub boundary_info: &'a HashMap<String, crate::ContextBoundaryInfo>,
74    /// #855: how many **real** contexts/adapters this project has — computed
75    /// once per round by the transport with
76    /// `crate::wire_contract::real_context_count`, never re-derived here
77    /// as a bare `boundary_info.len()` (see that function's doc: the
78    /// synthetic toolchain `bynk` capability unit would otherwise count as a
79    /// second "context" and `NoCrossContextReason::SingleContext` would
80    /// almost never fire).
81    pub context_count: usize,
82}
83
84/// Everything the ladder reads.
85pub struct HoverInput<'a> {
86    /// The analysed round; `None` when the file is outside it — the lexical
87    /// rungs still answer from the live buffer.
88    pub analysis: Option<HoverAnalysis<'a>>,
89    /// The **live** buffer and the cursor's offset into it; `None` when the
90    /// document is not open — the index rungs still answer from the snapshot.
91    pub doc: Option<(&'a str, usize)>,
92    /// The cursor's file as the caller knows it: it is excluded from the
93    /// cross-file declaration scan, which looks for the name *elsewhere*.
94    /// `None` (a document with no file path) skips that scan.
95    pub path: Option<&'a Path>,
96    /// Content-ownership track (#1086): a pre-read `(path, content)` map for
97    /// the project's `.bynk` files (the caller's overlay-then-disk sweep) —
98    /// was a bare path list the resolution rungs below read from disk
99    /// themselves. Every rung that reads project files (8's `resolve_label`,
100    /// 9's `describe_symbol_cross_file`) takes this map directly now.
101    pub files: Option<&'a HashMap<PathBuf, String>>,
102}
103
104/// The hover Markdown for the cursor, or `None` when no rung resolves it.
105///
106/// The rung order is the contract; see the module doc. Each rung is tried in
107/// turn and the first `Some` wins.
108pub fn hover_content(input: &HoverInput<'_>) -> Option<String> {
109    if let Some(a) = &input.analysis {
110        let tys = a.tys;
111        // 1. v0.25: binding-index path — a resolved symbol reference, described
112        //    from its *defining* file (names are unique per file, so the per-file
113        //    lookup is exact). Binding-correct: a duplicate name in another unit
114        //    describes the bound declaration, not the first name match.
115        //
116        //    v0.166 (ADR 0191): every `SymbolKind` now has a renderer arm, so a
117        //    resolved key is answered here rather than falling through to a name
118        //    match below. The `Some` guard remains — it is what a new kind added
119        //    without an arm would fall through, silently, which is how
120        //    `Method`/`CapabilityOp` came to render the wrong declaration.
121        if let Some((key, def)) = crate::index_queries::definition_at(a.index, a.rel, a.offset)
122            && let Some(def_text) = a.snapshots.get(&def.path)
123            && let Some(content) = crate::symbols::describe_symbol(def_text, &key.name)
124        {
125            // #848: rewrite any resolvable intra-doc link in the rendered
126            // doc comment into a Markdown link, scoped to `key.unit` (the
127            // declaring unit doc-link resolution searches from).
128            let ctx = crate::index_queries::DocLinkContext {
129                path: &def.path,
130                text: def_text,
131                attached: def.span.start,
132                locals: a.locals.get(&def.path).map_or(&[], |l| l.as_slice()),
133            };
134            let content = crate::doc_link_urls::linkify_doc_links(
135                &content,
136                a.index,
137                a.doc_scope,
138                a.project_root,
139                a.snapshots,
140                &key.unit,
141                Some(&ctx),
142            );
143            // #855: a resolved `Service` symbol (the declaration's own name,
144            // or a cross-context/test-service call site — both record this
145            // kind, see `bynk-check/src/symbols.rs`) gets its wire
146            // contract appended after everything `describe_symbol` already
147            // rendered. This changes only the *tail* of what rung 1 already
148            // returns `Some` for — never whether it answers.
149            let content = if key.kind == SymbolKind::Service {
150                match wire_contract_for_service_key(a, key, &def.path, def_text) {
151                    Some(model) => format!("{content}{}", wire_contract_appendix(&model)),
152                    None => content,
153                }
154            } else {
155                content
156            };
157            return Some(with_capability_path(content, a));
158        }
159        // 1a. #2469: a `given` entry whose capability rung 1 could not describe
160        //    still explains why the declaration needs it.
161        if let Some(section) = capability_path_section(a) {
162            return Some(section);
163        }
164        // 2. #611 (gap C): a `store` field's operation (`items.put(…)`) — a
165        //    structural match on the enclosing agent's declared field, so it
166        //    outranks the locals rung below, which guesses by name in scope.
167        //    Takes `locals` to honour the checker's by-provenance dispatch: a
168        //    local shadowing the field makes this an ordinary value method.
169        if let Some(text) = a.snapshots.get(a.rel)
170            && let Some(content) = crate::symbols::describe_store_op_at(
171                text,
172                a.offset,
173                a.locals.get(a.rel).map_or(&[], |l| l.as_slice()),
174            )
175        {
176            return Some(content);
177        }
178        // 2b. #2839: the `?` of an `Option` — `None` answers `404 NotFound`. Ahead of the locals rung, which
179        //     would otherwise describe the operand the `?` abuts.
180        if let Some(text) = a.snapshots.get(a.rel)
181            && let Some(entries) = a.expr_types.get(a.rel)
182            && let Some(content) =
183                crate::symbols::describe_question_at(text, a.offset, entries, tys)
184        {
185            return Some(content);
186        }
187        // 3. v0.122 (slice 1): a local / parameter → its inferred type, and
188        //    `self` → its receiver/agent type. Both read the retained analysis
189        //    tables and run before the lexical fallback, which knows only
190        //    declarations by name.
191        if let Some(text) = a.snapshots.get(a.rel) {
192            let local = a
193                .locals
194                .get(a.rel)
195                .and_then(|locals| crate::locals_nav::describe_local_at(locals, text, a.offset))
196                .or_else(|| {
197                    let entries = a.expr_types.get(a.rel)?;
198                    crate::symbols::describe_self_at(text, a.offset, entries, tys)
199                });
200            if let Some(content) = local {
201                // #2854: an HTTP handler's typed `query` also lists the keys it
202                // reads off the query string, their types and defaults.
203                if let Some(section) = query_param_section(a, text) {
204                    return Some(format!("{content}\n\n{section}"));
205                }
206                return Some(content);
207            }
208        }
209        // 3a. #2683, #2711: the `within` of `e.within(d)` or the `race` of
210        //     `a.race(b)` on an `Effect`.
211        if let Some(text) = a.snapshots.get(a.rel)
212            && let Some(entries) = a.expr_types.get(a.rel)
213            && let Some(content) =
214                crate::symbols::describe_effect_method_at(text, a.offset, entries, tys)
215        {
216            return Some(content);
217        }
218        // 4. #855: the handler HEADER — the `on` keyword, the HTTP method /
219        //    handler-kind token, and any route string literal. No earlier rung
220        //    (nor any later lexical one) ever answers here today: `GET` lexes
221        //    as a bare `Ident` with no index symbol, and no top-level
222        //    declaration is named after it. Guarded to the header's own byte
223        //    range — from the handler's span start up to (but excluding) its
224        //    first param's span start, or its body's span start with no
225        //    params — which contains only tokens that are never an index
226        //    symbol, so this rung is provably unable to shadow rung 1's
227        //    resolution of, say, a param's *type* name (`client: ClientId`),
228        //    which always sits past that boundary. See `header_handler_at`.
229        if let Some(text) = a.snapshots.get(a.rel)
230            && let Some((service_name, handler)) = header_handler_at(text, a.offset)
231            && let Some((unit, _)) = crate::symbols::own_declaration_name(text)
232            && let Some(info) = a.boundary_info.get(&unit)
233        {
234            let expr_types = a.expr_types.get(a.rel).map(|v| v.as_slice()).unwrap_or(&[]);
235            if let Some(model) = crate::wire_contract::wire_contract_for_service(
236                &unit,
237                text,
238                &service_name,
239                &handler,
240                info,
241                expr_types,
242                tys,
243                a.context_count,
244            ) {
245                return Some(with_cron_schedule(text, a.offset, &model));
246            }
247        }
248        // 4b. #2460: the cursor inside a doc-comment `[Name]` link previews
249        //     its target — `describe_symbol` of the resolved key, exactly as
250        //     hovering the name in code would — or reports it unresolved.
251        //     Doc-link spans are comment text, which no index reference or
252        //     local covers, so this cannot shadow rungs 1-4.
253        if let Some(text) = a.snapshots.get(a.rel)
254            && let Some(content) = doc_link_hover(a, text)
255        {
256            return Some(content);
257        }
258    }
259
260    // The remaining rungs are lexical, over the **live** buffer.
261    let (text, offset) = input.doc?;
262    let Some((name, span)) = identifier_at(text, offset) else {
263        // v0.121 (ADR 0156): the mechanical coverage test requires every
264        // lowercase-initial keyword to have *a* hover path. A bare keyword token
265        // (`requires`, `suite`, …) never resolves as an identifier above, so it
266        // falls here — its one-line `keywords` registry doc, the same text
267        // completion shows. Richer per-declaration hover is `describe_symbol`'s
268        // job, not this fallback's.
269        return crate::symbols::describe_keyword_at(text, offset).map(str::to_string);
270    };
271    // 5. #1885: a unit name — the file's own header name, or a `uses` /
272    //    `consumes` / suite target path — shows the unit's module doc. Guarded
273    //    to those names' byte ranges, which hold only unit-path segments and
274    //    never an index symbol, so it cannot shadow rung 1; and it runs before
275    //    the bare-name rungs below, which would otherwise answer a segment
276    //    (`model` in `uses compat.model`) with any declaration named `model`.
277    //    A context's doc may live in a sibling file, so the search covers the
278    //    project's other files: the caller's content map, or else the analysed
279    //    round's snapshots, in path order so the answer is deterministic.
280    let mut others: Vec<(&PathBuf, &str)> = match (input.files, &input.analysis) {
281        (Some(files), _) => files.iter().map(|(p, t)| (p, t.as_str())).collect(),
282        (None, Some(a)) => a
283            .snapshots
284            .iter()
285            .filter(|(p, _)| p.as_path() != a.rel)
286            .map(|(p, t)| (p, t.as_str()))
287            .collect(),
288        (None, None) => Vec::new(),
289    };
290    others.sort_by(|a, b| a.0.cmp(b.0));
291    // #2223: `money.currency`, where `money` is a dependency alias, is the
292    // dependency's `currency`: describe it from that package's files and say
293    // where it comes from.
294    if let Some(content) = describe_dependency_unit(input, text, span.start, &others) {
295        return Some(content);
296    }
297    let others: Vec<&str> = others.into_iter().map(|(_, t)| t).collect();
298    if let Some(content) =
299        crate::symbols::describe_unit_at(text, span.start, others.iter().copied())
300    {
301        return Some(content);
302    }
303    // 5a. #2137: the contextual `advance` of `advance Clock by <Duration>`.
304    if let Some(content) = crate::symbols::describe_advance_at(text, span.start) {
305        return Some(content);
306    }
307    // 5a. #3191: the contextual `by` of an actor clause (an ordinary `by` name
308    //    keeps its own hover, which resolved above).
309    if let Some(content) = crate::symbols::describe_by_at(text, span.start) {
310        return Some(content);
311    }
312    // 5a. Constrained generics slice 1: the contextual `derives` of a type's
313    //    `derives Ord` clause, and a constraint name in a bound or that clause.
314    if let Some(content) = crate::symbols::describe_derives_at(text, span.start) {
315        return Some(content);
316    }
317    if let Some(content) = crate::symbols::describe_constraint_at(text, span.start) {
318        return Some(content);
319    }
320    // 5a. #2640: the contextual `par` of a `par { … }` binding block.
321    if let Some(content) = crate::symbols::describe_par_at(text, span.start) {
322        return Some(content);
323    }
324    // 5a'. #2618: the contextual `private` modifier before a declaration.
325    if let Some(content) = crate::symbols::describe_private_at(text, span.start) {
326        return Some(content);
327    }
328    // 5a''. #2841: the contextual `fixture` of a suite `fixture` declaration.
329    if let Some(content) = crate::symbols::describe_fixture_at(text, span.start) {
330        return Some(content);
331    }
332    // 5b. #2136: a `schedule` / `message` address in a `system`-tier case,
333    //    which runs through the Worker's own entry point. Neither name is a
334    //    declaration, so this shadows nothing.
335    if let Some(content) =
336        crate::symbols::describe_system_job_address_at(text, span.start, others.iter().copied())
337    {
338        return Some(content);
339    }
340    // 5b. #2134: a suite's or case's `env { … }` clause — the `env` word or an
341    //    entry's name. Guarded to those byte ranges, which hold no index
342    //    symbol, so it cannot shadow rung 1.
343    if let Some(content) = crate::symbols::describe_env_at(text, span.start) {
344        return Some(content);
345    }
346    // 5c'. #2138: `run.id` in a case body that hasn't bound its own `run`.
347    if let Some(content) = crate::symbols::describe_run_id_at(text, span.start) {
348        return Some(content);
349    }
350    // 5c. #2135: a reserved call-site principal (`by Nobody`/`Forged`/`Stale`/`Expired`)
351    //    — no declaration, so nothing below would answer it.
352    if let Some(content) = crate::symbols::describe_reserved_principal_at(text, span.start) {
353        return Some(content);
354    }
355    // 6. A top-level declaration in this file (fast path).
356    if let Some(content) = crate::symbols::describe_symbol(text, &name) {
357        return Some(content);
358    }
359    // 7. v0.137.0 (ADR 0161) + #611 (gap A): the `key`/`store` contextual
360    //    keywords, the agent state fields they declare, and — since #611 — a
361    //    *reference* to one from the agent's body. Single-file-local, so it
362    //    resolves before any project-wide scan.
363    if let Some(content) = crate::symbols::describe_agent_state_at(text, span.start) {
364        return Some(content);
365    }
366    // 8. v0.140 (ADR 0163): a handler-position `@cache` annotation — not a symbol
367    //    and no local, so it resolves here beside the agent state.
368    if let Some(content) = crate::symbols::describe_handler_annotation_at(text, span.start) {
369        return Some(content);
370    }
371    // 8b. #2686: an `@example` after a type's or field's refinement.
372    if let Some(content) = crate::symbols::describe_refinement_example_at(text, span.start) {
373        return Some(content);
374    }
375    // 9. v0.123 (slice 2, DECISION B): a `Recv.member` name-receiver access — a
376    //    capability op (`Clock.now`), a refined/opaque `of`/`unsafe`, or a type
377    //    static — via the same path signature help uses, over the project and the
378    //    embedded surface. Before the cross-file / first-party name scans.
379    //    #1888: a `Sum.Variant` callee hovers as the variant, with its doc.
380    crate::symbols::qualified_callee_at(text, span)
381        .and_then(|callee| {
382            describe_variant_anywhere(text, input.files, |src| {
383                crate::symbols::describe_variant_key(src, &callee)
384            })
385            .or_else(|| {
386                crate::signature_help::resolve_label(&callee, text, input.files).map(|sig| {
387                    // Only the D1 typed-read signature gets the column note, so a
388                    // user's own `select` op never does.
389                    let typed = crate::signature_help::is_typed_read_label(&callee, &sig);
390                    format!(
391                        "```bynk\n{sig}\n```{}",
392                        if typed {
393                            typed_read_columns(&callee, &text[span.end..], text, input.files)
394                        } else {
395                            String::new()
396                        }
397                    )
398                })
399            })
400        })
401        // 10. A project-wide scan (v1.1), then 11. the embedded first-party
402        //    sources (slice 9) — so `uses`/`consumes` names resolve across
403        //    file boundaries (§3.4) and stdlib/surface symbols surface too.
404        //    Content-ownership track (#1086) slice 1: `describe_symbol_cross_file`
405        //    now takes `input.files`'s content map directly — no more deriving
406        //    a path list to hand it.
407        .or_else(|| {
408            input
409                .files
410                .zip(input.path)
411                .and_then(|(content, path)| {
412                    crate::symbols::describe_symbol_cross_file(content, path, &name)
413                })
414                .map(|(_other_path, desc)| desc)
415        })
416        // #1888: a bare variant name (`Circle(r)` in a pattern, `Dot` as a
417        // value) hovers as its variant, after every declaration rung, so a
418        // variant never shadows a type of the same name. Only a name exactly
419        // one sum declares answers.
420        .or_else(|| {
421            describe_variant_anywhere(text, input.files, |src| {
422                crate::symbols::describe_variant_named(src, &name)
423            })
424        })
425        .or_else(|| crate::symbols::describe_firstparty_symbol(&name))
426        // #2620: the ambient `unreachable`/`todo`, last, so a declaration of the
427        // same name (which shadows the built-in) is answered by a rung above.
428        .or_else(|| describe_fault_builtin(&name, &text[span.end..]))
429        // #2867: the `IsoDate` refinement predicate, in a `where` clause.
430        .or_else(|| describe_iso_date_predicate(&name, &text[..span.start]))
431}
432
433/// #3873: hover for the `Cron` predicate name after `where` or `&&`: its rule.
434fn describe_cron_predicate(name: &str, before: &str) -> Option<String> {
435    if name != "Cron" {
436        return None;
437    }
438    let line = before.rsplit('\n').next().unwrap_or(before);
439    (line.contains("where") || line.trim_end().ends_with("&&")).then(|| {
440        "```bynk\nCron\n```\n\nA `String` refinement predicate: the value is a valid Cloudflare \
441         cron schedule. Five fields (`minute hour day-of-month month day-of-week`) separated by \
442         exactly one space; minute `0-59`, hour `0-23`, day of month `1-31` (also `L`, `W`), \
443         month `1-12` or `JAN`-`DEC`, day of week `1-7` with `1` = Sunday, or `SUN`-`SAT` \
444         (also `L`, `#`). `* , - /` work in every field. No seconds, year, `?` or `@daily`. \
445         Schedules run in UTC. Checked at compile time for a literal, and at runtime by `.of`, \
446         `Json.decode` and the HTTP boundary."
447            .to_string()
448    })
449}
450
451/// #3873: on a cron handler's header, with the cursor inside the schedule's
452/// string literal, the schedule's fields are named ahead of the wire contract.
453fn with_cron_schedule(
454    text: &str,
455    offset: usize,
456    model: &crate::wire_contract::WireContractModel,
457) -> String {
458    let contract = wire_contract_standalone(model);
459    match describe_cron_schedule_literal(text, offset) {
460        Some(fields) => format!("{fields}\n\n---\n\n{contract}"),
461        None => contract,
462    }
463}
464
465/// #3873: hover inside the string literal of `on schedule("…")`: the schedule's
466/// five fields, named. `None` off a schedule literal or for an invalid schedule
467/// (the checker reports that one).
468pub(crate) fn describe_cron_schedule_literal(text: &str, offset: usize) -> Option<String> {
469    let line_start = text[..offset].rfind('\n').map_or(0, |i| i + 1);
470    let line_end = text[offset..].find('\n').map_or(text.len(), |i| offset + i);
471    let line = &text[line_start..line_end];
472    let at = offset - line_start;
473    let open = line.find("schedule(\"")? + "schedule(\"".len();
474    let close = open + line[open..].find('"')?;
475    if at < open - 1 || at > close {
476        return None;
477    }
478    let fields = bynk_syntax::cron::describe_fields(&line[open..close])?;
479    let rows: Vec<String> = fields
480        .iter()
481        .map(|(name, text)| format!("- {name}: `{text}`"))
482        .collect();
483    Some(format!(
484        "```bynk\nschedule(\"{}\")\n```\n\nA cron schedule (UTC):\n\n{}",
485        &line[open..close],
486        rows.join("\n")
487    ))
488}
489
490/// #2867: hover for the `IsoDate` predicate name after `where` or `&&`: its rule
491/// and the `Instant` pairing the guide documents.
492fn describe_iso_date_predicate(name: &str, before: &str) -> Option<String> {
493    // #3873: the `Cron` predicate hovers the same way.
494    if name == "Cron" {
495        return describe_cron_predicate(name, before);
496    }
497    if name != "IsoDate" {
498        return None;
499    }
500    let line = before.rsplit('\n').next().unwrap_or(before);
501    (line.contains("where") || line.trim_end().ends_with("&&")).then(|| {
502        "```bynk\nIsoDate\n```\n\nA `String` refinement predicate: the value is a calendar date, \
503         exactly `YYYY-MM-DD` (years 0000 to 9999) and a date that exists \
504         (`2028-02-29` is valid; `2026-02-29` and `2026-13-01` are not). \
505         Checked at compile time for a literal, and at runtime by `.of`, `Json.decode` \
506         and the HTTP boundary. `Instant.fromIso(\"\\(day)T00:00:00Z\")` is always \
507         `Some` for such a value."
508            .to_string()
509    })
510}
511
512/// #2865: a `select[T]` / `firstAs[T]` call's hover names the statement the
513/// compiler writes: `SELECT` then `T`'s fields, quoted, ahead of the literal
514/// tail. Empty for any other callee, or when `T` is not a record found in the
515/// project or the buffer.
516fn typed_read_columns(
517    callee: &str,
518    after: &str,
519    text: &str,
520    files: Option<&HashMap<PathBuf, String>>,
521) -> String {
522    use bynk_syntax::ast::{CommonsItem, SourceUnit, TypeBody};
523    if !(callee.ends_with(".select") || callee.ends_with(".firstAs")) {
524        return String::new();
525    }
526    let Some(row) = after
527        .strip_prefix('[')
528        .and_then(|r| r.split(']').next())
529        .map(str::trim)
530        .filter(|r| !r.is_empty() && r.chars().all(|c| c.is_alphanumeric() || c == '_'))
531    else {
532        return String::new();
533    };
534    let mut cols = None;
535    crate::completion::for_each_unit(text, files, |unit| {
536        let items = match unit {
537            SourceUnit::Commons(c) => &c.items,
538            SourceUnit::Context(c) => &c.items,
539            SourceUnit::Adapter(a) => &a.items,
540            _ => return,
541        };
542        for item in items {
543            if let CommonsItem::Type(t) = item
544                && t.name.name == row
545                && let TypeBody::Record(r) = &t.body
546                && cols.is_none()
547            {
548                cols = Some(
549                    r.fields
550                        .iter()
551                        .map(|f| format!("\"{}\"", f.name.name.replace('"', "\"\"")))
552                        .collect::<Vec<_>>()
553                        .join(", "),
554                );
555            }
556        }
557    });
558    cols.map_or_else(String::new, |c| {
559        format!("\n\nThe compiler writes `SELECT {c}` ahead of the literal.")
560    })
561}
562
563/// #2620: hover for a call to the ambient `unreachable(…)` / `todo(…)`: the
564/// signature (its type is `never returns`) and the registry's one-line doc.
565fn describe_fault_builtin(name: &str, after: &str) -> Option<String> {
566    let info = bynk_syntax::keywords::BUILTIN_FUNCTIONS
567        .iter()
568        .find(|k| k.word == name)?;
569    after.trim_start().starts_with('(').then(|| {
570        format!(
571            "```bynk\n{name}(message: String) -> never returns\n```\n\n{}",
572            info.meaning
573        )
574    })
575}
576
577/// #2469: the shortest path to the capability's use, when the cursor is on a
578/// `given` entry the checker recorded one for.
579fn capability_path_section(a: &HoverAnalysis<'_>) -> Option<String> {
580    crate::capability_path::hover_section(
581        &crate::capability_path::PathView {
582            graphs: a.capability_paths,
583            snapshots: a.snapshots,
584            project_root: a.project_root,
585            rel: a.rel,
586        },
587        a.offset,
588    )
589}
590
591/// Rung 1's content with the capability path appended below the capability's
592/// own description.
593fn with_capability_path(content: String, a: &HoverAnalysis<'_>) -> String {
594    match capability_path_section(a) {
595        Some(section) => format!("{content}\n\n---\n\n{section}"),
596        None => content,
597    }
598}
599
600/// #2223: hover for a `uses`/`consumes` target written `<alias>.<unit>`: the
601/// dependency unit's kind and module doc, from the dependency's own files,
602/// and the package and alias it comes through. `files` are the project's
603/// files with their paths (the content map, or the round's snapshots, which
604/// are relative to the project root).
605fn describe_dependency_unit(
606    input: &HoverInput<'_>,
607    text: &str,
608    offset: usize,
609    files: &[(&PathBuf, &str)],
610) -> Option<String> {
611    let written = crate::symbols::unit_name_at(text, offset)?;
612    // The analysed round knows the project root; read its manifest from the
613    // live content map, so an unsaved alias edit is honoured as the round
614    // honours it.
615    let empty = HashMap::new();
616    let view = match &input.analysis {
617        Some(a) => {
618            crate::packages::DependencyView::for_root(a.project_root, input.files.unwrap_or(&empty))
619        }
620        None => input
621            .files
622            .and_then(crate::packages::DependencyView::from_files),
623    }?;
624    let target = view.resolve(&written)?;
625    let root = input.analysis.as_ref().map(|a| a.project_root);
626    let sources = files.iter().filter(|(p, _)| {
627        let path = match root {
628            Some(r) if p.is_relative() => r.join(p),
629            _ => (*p).clone(),
630        };
631        view.package_of(&path) == Some(&target.package)
632    });
633    let mut out = crate::symbols::describe_unit(sources.map(|(_, t)| *t), &target.unit)?;
634    out.push('\n');
635    out.push_str(&crate::packages::hover_note(&target));
636    out.push('\n');
637    Some(out)
638}
639
640/// #1888: `describe` over the live buffer, then over each other project file
641/// (sorted, as the cross-file declaration scan is), first answer winning.
642fn describe_variant_anywhere(
643    text: &str,
644    files: Option<&HashMap<PathBuf, String>>,
645    describe: impl Fn(&str) -> Option<String>,
646) -> Option<String> {
647    describe(text).or_else(|| {
648        let files = files?;
649        let mut paths: Vec<&PathBuf> = files.keys().collect();
650        paths.sort();
651        paths
652            .into_iter()
653            .map(|p| &files[p])
654            .filter(|src| src.as_str() != text)
655            .find_map(|src| describe(src))
656    })
657}
658
659/// The identifier-ish token covering `offset` — its text and span.
660///
661/// Hole-aware (issue #473): interpolation holes are expanded, so a cursor inside
662/// `"… \(name) …"` lands on the hole's identifier token rather than the opaque
663/// `InterpStr` token. The token-kind filter is wider than `Ident` because the
664/// literal kinds carry hover-worthy names too (`Result`, `Option`, `Effect`).
665pub fn identifier_at(text: &str, offset: usize) -> Option<(String, Span)> {
666    use bynk_syntax::lexer::TokenKind;
667    let tokens = bynk_syntax::lexer::tokenize_expanding_holes(text).ok()?;
668    tokens
669        .iter()
670        .find(|t| {
671            t.span.start <= offset
672                && offset < t.span.end
673                && matches!(
674                    t.kind,
675                    TokenKind::Ident
676                        | TokenKind::Int
677                        | TokenKind::String
678                        | TokenKind::Bool
679                        | TokenKind::Float
680                        | TokenKind::Decimal
681                        | TokenKind::Result
682                        | TokenKind::Option
683                        | TokenKind::Effect
684                )
685        })
686        .map(|t| (text[t.span.start..t.span.end].to_string(), t.span))
687}
688
689// ---------------------------------------------------------------------
690// #855: wire-contract rendering — rung 1's appendix and rung 4's standalone
691// content share the same body renderer ([`wire_contract_body`]); they differ
692// only in what comes before it (an existing `describe_symbol` block, versus
693// nothing).
694// ---------------------------------------------------------------------
695
696/// Resolve a resolved-`Service`-symbol's wire contract, for rung 1's
697/// appendix. A service may declare more than one handler (several HTTP
698/// routes on one service, say); this module has no way to tell *which* one
699/// the author meant by hovering the service's bare name (a declaration site,
700/// or a cross-context/test-service call site — neither carries a handler
701/// selector). Rather than guess, this answers only the unambiguous case: a
702/// service with **exactly one** handler. That covers every worked example in
703/// the issue (a single-route HTTP service, a single-handler `on call`
704/// service) and every #855 fixture; a multi-handler service simply gets no
705/// appendix, which is rung 1's pre-#855 behaviour unchanged — never a wrong
706/// answer, only sometimes an absent one.
707fn wire_contract_for_service_key(
708    a: &HoverAnalysis<'_>,
709    key: &bynk_check::index::SymbolKey,
710    def_path: &Path,
711    def_text: &str,
712) -> Option<crate::wire_contract::WireContractModel> {
713    let tys = a.tys;
714    let info = a.boundary_info.get(&key.unit)?;
715    let svc = info.services.get(&key.name)?;
716    let [handler] = svc.handlers.as_slice() else {
717        return None;
718    };
719    let expr_types = a
720        .expr_types
721        .get(def_path)
722        .map(|v| v.as_slice())
723        .unwrap_or(&[]);
724    crate::wire_contract::wire_contract_for_service(
725        &key.unit,
726        def_text,
727        &key.name,
728        handler,
729        info,
730        expr_types,
731        tys,
732        a.context_count,
733    )
734}
735
736/// Locate the `Handler` (and its owning service's name) whose **header**
737/// contains `offset` — the `on` keyword, the handler-kind/HTTP-method token,
738/// and any route string literal, but *none* of its params or body. Mirrors
739/// `crate::wire_contract::wire_contract_at`'s re-parse-and-find-the-
740/// enclosing-handler convention; duplicated (rather than reused) because the
741/// guard below needs the raw `Handler`'s param/body spans, which
742/// `wire_contract_at`'s return value (a `WireContractModel`, not an AST node)
743/// does not carry.
744fn header_handler_at(text: &str, offset: usize) -> Option<(String, bynk_syntax::ast::Handler)> {
745    use bynk_syntax::ast::{CommonsItem, SourceUnit};
746    let tokens = bynk_syntax::lexer::tokenize(text).ok()?;
747    let (parsed, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
748    let items: &[CommonsItem] = match parsed.as_ref()? {
749        SourceUnit::Context(c) => &c.items,
750        SourceUnit::Adapter(a) => &a.items,
751        SourceUnit::Commons(_) | SourceUnit::Suite(_) => return None,
752    };
753    for item in items {
754        let CommonsItem::Service(s) = item else {
755            continue;
756        };
757        for h in &s.handlers {
758            // The safety property: this range holds only `on`, the
759            // kind/method token, and the route literal — never a param name,
760            // a type name, or anything else an earlier rung (or a later
761            // lexical one) could already resolve. See the module doc and
762            // rung 4's own comment.
763            let prefix_end = h
764                .params
765                .first()
766                .map(|p| p.span.start)
767                .unwrap_or(h.body.span.start);
768            if h.span.start <= offset && offset < prefix_end {
769                return Some((s.name.name.clone(), h.clone()));
770            }
771        }
772    }
773    None
774}
775
776/// #2854: when the cursor is on the `query` parameter (or a use of it) of an
777/// `on http` handler whose type is a record, the keys the router reads off the
778/// query string: each field's type, and whether it is required, optional, or
779/// defaulted (with the default). Empty for the raw `RequestQuery` view and for
780/// anything that is not that parameter.
781fn query_param_section(a: &HoverAnalysis<'_>, text: &str) -> Option<String> {
782    use bynk_syntax::ast::{CommonsItem, SourceUnit, TypeBody, TypeRef};
783    let word_start = text[..a.offset]
784        .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
785        .map_or(0, |i| i + 1);
786    let word_end = a.offset
787        + text[a.offset..]
788            .find(|c: char| !(c.is_alphanumeric() || c == '_'))
789            .unwrap_or(text.len() - a.offset);
790    // #3277: `cookies` reads the same way, from the `Cookie` header.
791    let word = &text[word_start..word_end];
792    let heading = match word {
793        "query" => {
794            "**Query string** — decoded and validated before the handler runs; unknown keys are ignored."
795        }
796        "cookies" => {
797            "**Cookies** — parsed from the `Cookie` header, decoded and validated before the handler runs; unknown cookies are ignored."
798        }
799        _ => return None,
800    };
801    let (unit, _) = crate::symbols::own_declaration_name(text)?;
802    let info = a.boundary_info.get(&unit)?;
803    let tokens = bynk_syntax::lexer::tokenize(text).ok()?;
804    let (parsed, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
805    let items: &[CommonsItem] = match parsed.as_ref()? {
806        SourceUnit::Context(c) => &c.items,
807        SourceUnit::Adapter(a) => &a.items,
808        SourceUnit::Commons(_) | SourceUnit::Suite(_) => return None,
809    };
810    let handler = items.iter().find_map(|item| {
811        let CommonsItem::Service(s) = item else {
812            return None;
813        };
814        s.handlers.iter().find(|h| {
815            matches!(
816                bynk_model::lower_handler_kind_ir(&h.kind),
817                bynk_model::IrHandlerKind::Http { .. }
818            ) && h.span.start <= a.offset
819                && a.offset < h.span.end
820        })
821    })?;
822    let param = handler.params.iter().find(|p| p.name.name == word)?;
823    let TypeRef::Named(id) = &param.type_ref else {
824        return None;
825    };
826    let Some(TypeBody::Record(record)) = info.types.get(&id.name).map(|t| &t.body) else {
827        return None;
828    };
829    let key = if word == "cookies" { "cookie" } else { "key" };
830    let mut out = format!("{heading}\n\n| {key} | type | |\n|---|---|---|\n");
831    for f in &record.fields {
832        let note = match (&f.type_ref, &f.init) {
833            (_, Some(init)) => format!("default `{}`", bynk_fmt::expr_to_string(init)),
834            (TypeRef::Option(..), None) => "optional".to_string(),
835            (TypeRef::List(..), None) => "repeatable, required".to_string(),
836            _ => "required".to_string(),
837        };
838        let note = match (&f.type_ref, &f.init) {
839            (TypeRef::List(..), Some(_)) => format!("repeatable, {note}"),
840            _ => note,
841        };
842        // #3343: a field renamed by `@name` is read under its wire name.
843        let key_name = match f.wire_name() {
844            Some(w) => format!("{w}` (field `{}", f.name.name),
845            None => f.name.name.clone(),
846        };
847        out.push_str(&format!(
848            "| `{}` | `{}` | {} |\n",
849            key_name,
850            bynk_check::context_checks::ts_type_ref_display(&f.type_ref),
851            note
852        ));
853    }
854    Some(out)
855}
856
857/// The Markdown facts shared by rung 1's appendix and rung 4's standalone
858/// render: the request envelope (all three cases), the cross-context
859/// contract form + hash (`on call` only), and — HTTP handlers only — the
860/// reachable response status set.
861fn wire_contract_body(model: &crate::wire_contract::WireContractModel) -> String {
862    use crate::wire_contract::{BoundaryKind, Envelope};
863
864    let mut out = String::new();
865    if let BoundaryKind::Http { method, path } = &model.kind {
866        out.push_str(&format!("`{} {}`\n\n", method.as_str(), path));
867    }
868
869    out.push_str("**Request:** ");
870    match &model.envelope {
871        Envelope::Empty => out.push_str("no body — the handler never reads it.\n\n"),
872        Envelope::Bare { param, .. } => out.push_str(&format!(
873            "the request body **is** the value of `{param}` — not wrapped in an object.\n\n"
874        )),
875        Envelope::Raw {
876            param,
877            content_type,
878        } => out.push_str(&format!(
879            "the request body is the raw octets of `{param}` — not JSON, not base64 — sent as \
880             `{content_type}`.\n\n"
881        )),
882        Envelope::Keyed { params } => {
883            let names: Vec<&str> = params.iter().map(|(n, _)| n.as_str()).collect();
884            out.push_str(&format!(
885                "an object keyed by `{}`, in declaration order.\n\n",
886                names.join("`, `")
887            ));
888        }
889    }
890
891    if let Some(contract) = &model.contract {
892        out.push_str(&format!(
893            "**Cross-context contract** (hash `{}`) — change any of this and \
894             already-deployed callers get a 409:\n\n```\n{}\n```\n\n",
895            contract.hash,
896            // #2087: each qualified key shown as its declaration's name.
897            bynk_check::symbols::display_type_names_in(&contract.normal_form)
898        ));
899    }
900
901    if !model.responses.is_empty() {
902        out.push_str("**Responses:**\n\n");
903        for r in &model.responses {
904            out.push_str(&format!("- `{} {}`\n", r.status, r.variant));
905        }
906        out.push('\n');
907    }
908
909    out
910}
911
912/// Rung 1's wire-contract appendix — separated from whatever
913/// `describe_symbol` already rendered by a rule, so it reads as a distinct
914/// section rather than a continuation of the declaration's own doc comment.
915fn wire_contract_appendix(model: &crate::wire_contract::WireContractModel) -> String {
916    format!(
917        "\n\n---\n\n**Wire contract**\n\n{}",
918        wire_contract_body(model)
919    )
920}
921
922/// Rung 4's standalone render — hovering the header *is* the question, so
923/// this is the whole answer, headed by the service/handler name rather than
924/// appended after one.
925fn wire_contract_standalone(model: &crate::wire_contract::WireContractModel) -> String {
926    format!(
927        "**Wire contract** — `{}`\n\n{}",
928        model.service,
929        wire_contract_body(model)
930    )
931}
932
933/// #2460: hover for a cursor inside a doc-comment `[Name]` link, or `None`
934/// when the cursor is not in one (or the file has no unit to scope from).
935///
936/// Resolves exactly as the link itself does (`resolve_doc_link_in`, with the
937/// declaration the comment is attached to as context, #2454), so the preview
938/// and the click-through can never disagree: an own field or parameter
939/// previews, and a unit-qualified name previews.
940fn doc_link_hover(a: &HoverAnalysis<'_>, text: &str) -> Option<String> {
941    // The span test is the real guard and the cheap one; the unit lookup only
942    // runs for a cursor already inside a link.
943    let link = crate::symbols::doc_link_spans_attached(text)
944        .into_iter()
945        .find(|l| l.span.start <= a.offset && a.offset < l.span.end)?;
946    let name = link.name;
947    let owner_unit = crate::symbols::doc_link_unit(text)?;
948    let ctx = link
949        .attached
950        .map(|attached| crate::index_queries::DocLinkContext {
951            path: a.rel,
952            text,
953            attached,
954            locals: a.locals.get(a.rel).map_or(&[], |l| l.as_slice()),
955        });
956    let resolution = resolve_doc_link_in(a.index, a.doc_scope, &owner_unit, &name, ctx.as_ref());
957    let resolved = match resolution {
958        DocLinkResolution::Resolved(resolved) => Some(resolved),
959        DocLinkResolution::Ambiguous { unit, kinds } => {
960            let kinds: Vec<String> = kinds.iter().map(|k| format!("{k:?}")).collect();
961            return Some(format!(
962                "Ambiguous doc link `{name}` in `{unit}` (matches: {})",
963                kinds.join(", ")
964            ));
965        }
966        DocLinkResolution::Unresolved => None,
967    };
968    if let Some(resolved) = &resolved {
969        let def_text = a.snapshots.get(&resolved.def.path);
970        match (&resolved.key, def_text) {
971            (Some(key), Some(def_text)) => {
972                if let Some(content) = crate::symbols::describe_symbol(def_text, &key.name) {
973                    // The target's own doc links resolve from the target.
974                    let target_ctx = crate::index_queries::DocLinkContext {
975                        path: &resolved.def.path,
976                        text: def_text,
977                        attached: resolved.def.span.start,
978                        locals: a
979                            .locals
980                            .get(&resolved.def.path)
981                            .map_or(&[], |l| l.as_slice()),
982                    };
983                    return Some(crate::doc_link_urls::linkify_doc_links(
984                        &content,
985                        a.index,
986                        a.doc_scope,
987                        a.project_root,
988                        a.snapshots,
989                        &key.unit,
990                        Some(&target_ctx),
991                    ));
992                }
993            }
994            // No index key: a parameter, which is a local binding — described
995            // from the locals table, as hovering it in code would.
996            (None, Some(def_text)) => {
997                let described = a.locals.get(&resolved.def.path).and_then(|locals| {
998                    crate::locals_nav::describe_local_at(locals, def_text, resolved.def.span.start)
999                });
1000                return Some(described.unwrap_or_else(|| format!("parameter `{name}`")));
1001            }
1002            _ => {}
1003        }
1004        // The link resolves (the click-through opens it) but its target has
1005        // no richer rendering: never report it unresolved.
1006        return Some(match &resolved.key {
1007            Some(key) => format!("`{}` — {:?} in `{}`", key.name, key.kind, key.unit),
1008            None => format!("parameter `{name}`"),
1009        });
1010    }
1011    // Nothing resolved (the ambiguous case returned above).
1012    let searched = a
1013        .doc_scope
1014        .get(&owner_unit)
1015        .map_or_else(|| owner_unit.clone(), |s| s.join(", "));
1016    Some(format!(
1017        "Unresolved doc link `{name}` — searched: {searched}"
1018    ))
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023
1024    /// #3873: `Cron` hovers with its rule inside a `where` clause only, and the
1025    /// schedule literal of `on schedule("…")` names its fields.
1026    #[test]
1027    fn cron_predicate_and_schedule_literal_hover() {
1028        let src = "commons demo.m\n\ntype S = String where Cron\n";
1029        let h = hover_at(src, "Cron", 0).expect("`Cron` hovers");
1030        assert!(h.contains("cron schedule"), "{h}");
1031        let elsewhere = hover_at("commons demo.m\n\nfn Cron() -> Int { 1 }\n", "Cron", 0);
1032        assert!(!elsewhere.is_some_and(|h| h.contains("refinement predicate")));
1033
1034        let line = "  on schedule(\"0 2 * * MON-FRI\") () -> Effect[Result[(), String]] {";
1035        let at = line.find("2 *").unwrap();
1036        let h = describe_cron_schedule_literal(line, at).expect("fields named");
1037        assert!(
1038            h.contains("- minute: `0`") && h.contains("- day of week: `MON-FRI`"),
1039            "{h}"
1040        );
1041        assert!(describe_cron_schedule_literal(line, 0).is_none());
1042        let bad = "  on schedule(\"61 * * * *\") () -> Effect[Result[(), String]] {";
1043        assert!(describe_cron_schedule_literal(bad, 16).is_none());
1044    }
1045    use super::*;
1046
1047    fn hover_at(src: &str, needle: &str, nth: usize) -> Option<String> {
1048        let offset = src.match_indices(needle).nth(nth).unwrap().0;
1049        hover_content(&HoverInput {
1050            analysis: None,
1051            doc: Some((src, offset)),
1052            path: None,
1053            files: None,
1054        })
1055    }
1056
1057    /// #2868: a function that declares `given` hovers with it, at the
1058    /// declaration and at a call.
1059    #[test]
1060    fn a_given_fn_hovers_with_its_capabilities() {
1061        let src = "context demo.m\n\ncapability Logger {\n  fn error(m: String) -> Effect[()]\n}\n\nfn warn(what: String) -> Effect[()] given Logger {\n  Logger.error(what)\n}\n\nservice s {\n  on call() -> Effect[()] by Caller given Logger {\n    warn(\"x\")\n  }\n}\n";
1062        for nth in [0, 1] {
1063            let h = hover_at(src, "warn", nth).expect("`warn` hovers");
1064            assert!(
1065                h.contains("fn warn(what: String) -> Effect[()] given Logger")
1066                    || h.contains("warn(what: String) -> Effect[()] given Logger"),
1067                "{h}"
1068            );
1069        }
1070    }
1071
1072    /// #2620: the ambient fault built-ins hover with their signature and doc; a
1073    /// declaration of the same name shadows the built-in.
1074    #[test]
1075    fn fault_builtins_hover_unless_shadowed() {
1076        let src = "commons demo.m\n\nfn f(n: Int) -> Int { if n > 0 { n } else { unreachable(\"never\") } }\n";
1077        let h = hover_at(src, "unreachable", 0).expect("`unreachable` hovers");
1078        assert!(
1079            h.contains("unreachable(message: String) -> never returns"),
1080            "{h}"
1081        );
1082        let shadowed =
1083            "commons demo.m\n\nfn todo(n: Int) -> Int { n }\n\nfn g() -> Int { todo(1) }\n";
1084        let h = hover_at(shadowed, "todo", 1).expect("the user's `todo` hovers");
1085        assert!(!h.contains("never returns"), "{h}");
1086    }
1087
1088    /// #2867: `IsoDate` hovers with its rule inside a `where` clause only.
1089    #[test]
1090    fn iso_date_predicate_hovers_in_where() {
1091        let src = "commons demo.m\n\ntype Day = String where IsoDate\n";
1092        let h = hover_at(src, "IsoDate", 0).expect("`IsoDate` hovers");
1093        assert!(h.contains("YYYY-MM-DD") && h.contains("2028-02-29"), "{h}");
1094        let elsewhere = "commons demo.m\n\nfn IsoDate() -> Int { 1 }\n";
1095        let h = hover_at(elsewhere, "IsoDate", 0);
1096        assert!(
1097            h.as_deref().is_none_or(|h| !h.contains("calendar date")),
1098            "{h:?}"
1099        );
1100    }
1101
1102    /// #2863: the built-in `DecodeError` hovers with its fields.
1103    #[test]
1104    fn json_error_hovers_with_its_fields() {
1105        let src = "commons demo.m\n\nfn f(s: String) -> Result[Int, DecodeError] { Json.decode[Int](s) }\n";
1106        let h = hover_at(src, "DecodeError", 0).expect("`DecodeError` hovers");
1107        assert!(
1108            h.contains("`kind`") && h.contains("`path`") && h.contains("`message`"),
1109            "{h}"
1110        );
1111    }
1112
1113    /// #3147: the case-only `D1.peek` hovers with its signature.
1114    #[test]
1115    fn d1_peek_hovers_with_its_signature() {
1116        let src = "suite shop.orders as system\n\ncase \"c\" {\n  let db = D1.peek(shop.orders.Orders)\n  expect true\n}\n";
1117        let h = hover_at(src, "peek", 0).expect("`peek` hovers");
1118        assert!(h.contains("peek(<participant>.<Capability>)"), "{h}");
1119    }
1120
1121    /// #2866: the built-in `ValidationError` hovers with its fields, not `value`.
1122    #[test]
1123    fn validation_error_hovers_with_its_fields() {
1124        let src = "commons demo.m\n\ntype Age = Int where self >= 0\n\nfn f(n: Int) -> Result[Age, ValidationError] { Age.of(n) }\n";
1125        let h = hover_at(src, "ValidationError", 0).expect("`ValidationError` hovers");
1126        assert!(h.contains("`field`") && h.contains("`message`"), "{h}");
1127        assert!(!h.contains("`value`"), "{h}");
1128    }
1129
1130    /// Constrained generics slice 1: `derives` and the constraint names it and
1131    /// a bound carry each hover; an `Ord` lookalike elsewhere does not.
1132    #[test]
1133    fn derives_and_constraint_names_hover() {
1134        let src = "commons demo.m\n\ntype P = Int derives Ord\n\nfn top[T: Ord](xs: List[T]) -> Option[T] { None }\n\nfn same[T: Eq](a: T) -> T { a }\n";
1135        let kw = hover_at(src, "derives", 0).expect("`derives` hovers");
1136        assert!(kw.contains("declaration order"), "{kw}");
1137        // `Ord` in the clause and in the bound; `Eq` in a bound.
1138        for nth in 0..2 {
1139            let ord = hover_at(src, "Ord", nth).expect("`Ord` hovers");
1140            assert!(ord.contains("constraint Ord"), "{ord}");
1141        }
1142        assert!(hover_at(src, "Eq", 0).unwrap().contains("constraint Eq"));
1143        // The type's own hover shows the clause.
1144        assert!(hover_at(src, "P =", 0).unwrap().contains("derives Ord"));
1145        // A generic's hover shows its bound.
1146        assert!(
1147            hover_at(src, "top", 0)
1148                .unwrap()
1149                .contains("fn top[T: Ord](xs: List[T])")
1150        );
1151    }
1152}