Skip to main content

bynk_ide/
symbols.rs

1//! Symbol lookups for hover and go-to-definition.
2//!
3//! Single-file lookups walk the parsed AST. Cross-file lookups (v1.1; LSP
4//! spec §3.4 cross-file requirement) iterate the project's `.bynk` sources
5//! to find a declaration in any unit the user might be referencing — used
6//! when the open file lacks the symbol the user clicked on (typically
7//! because the name was imported via `uses` or made available via
8//! `consumes`).
9
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12
13use bynk_syntax::ast::*;
14use bynk_syntax::lexer::tokenize;
15use bynk_syntax::parser::parse_unit_with_recovery;
16use bynk_syntax::span::Span;
17
18/// #2834: a suite's helper `fn`s as declarations, so they hover and
19/// go-to-definition like any `fn`; #3066: and its own `type`s and `const`s.
20/// Empty for every other unit.
21fn suite_fn_items(unit: &SourceUnit) -> Vec<CommonsItem> {
22    match unit {
23        SourceUnit::Suite(s) => s
24            .fns
25            .iter()
26            .cloned()
27            .map(CommonsItem::Fn)
28            .chain(s.types.iter().cloned().map(CommonsItem::Type))
29            .chain(s.consts.iter().cloned().map(CommonsItem::Const))
30            .collect(),
31        _ => Vec::new(),
32    }
33}
34
35/// Return the source span of the declaration named `name` in the given
36/// source text. Returns `None` if no declaration matches.
37///
38/// The name of each item comes from [`CommonsItem::name`] rather than a list of
39/// arms here: that `match` is exhaustive, so a variant this lookup does not
40/// handle cannot compile, and a new one is answered the day it is added. The
41/// arms it replaces omitted `Actor`, and a `_ => {}` catch-all swallowed it —
42/// so go-to-definition on the `User` in `by u: User` found nothing whenever the
43/// index rung above it had not resolved the offset (an unanalysed or mid-edit
44/// buffer, a file outside the analysed project).
45///
46/// Note this deliberately matches a **method** by its bare name — `fn
47/// Stored.retitle` answers to `retitle` — because go-to-definition from a bare
48/// identifier depends on it. `describe_item` guards on `FnName::Free` instead
49/// and the two therefore disagree on what a bare name means, which ADR 0191 D2
50/// records as intended rather than as drift.
51pub fn find_declaration_span(source: &str, name: &str) -> Option<Span> {
52    let tokens = tokenize(source).ok()?;
53    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
54    let unit = unit?;
55    let suite_fns = suite_fn_items(&unit);
56    let items: &[CommonsItem] = match &unit {
57        SourceUnit::Commons(c) => &c.items,
58        SourceUnit::Context(c) => &c.items,
59        SourceUnit::Adapter(a) => &a.items,
60        SourceUnit::Suite(_) => &suite_fns,
61    };
62    // #2841: a suite's fixture is a declaration too.
63    if let SourceUnit::Suite(suite) = &unit
64        && let Some(f) = suite.fixtures.iter().find(|f| f.name.name == name)
65    {
66        return Some(f.name.span);
67    }
68    items
69        .iter()
70        .filter_map(CommonsItem::name)
71        .find(|ident| ident.name == name)
72        .map(|ident| ident.span)
73}
74
75/// Build a Markdown summary of a named declaration suitable for an LSP
76/// hover response. Returns `None` if no declaration matches.
77pub fn describe_symbol(source: &str, name: &str) -> Option<String> {
78    let tokens = tokenize(source).ok()?;
79    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
80    let unit = unit?;
81    let suite_fns = suite_fn_items(&unit);
82    let items: &[CommonsItem] = match &unit {
83        SourceUnit::Commons(c) => &c.items,
84        SourceUnit::Context(c) => &c.items,
85        SourceUnit::Adapter(a) => &a.items,
86        SourceUnit::Suite(_) => &suite_fns,
87    };
88    // S4a (#1966): a derived capability is rendered with its base, which the
89    // unit selects in a `consumes U { Base }`.
90    if let SourceUnit::Context(ctx) = &unit
91        && let Some(c) = items.iter().find_map(|item| match item {
92            CommonsItem::Capability(c) if c.name.name == name && c.derived.is_some() => Some(c),
93            _ => None,
94        })
95        && let Some(d) = &c.derived
96    {
97        let base_unit = ctx.consumes.iter().find_map(|cd| {
98            cd.selected
99                .as_ref()?
100                .iter()
101                .any(|s| s.name.name == d.base.name)
102                .then(|| cd.target.joined())
103        });
104        let base = base_unit
105            .as_deref()
106            .and_then(|u| crate::completion::embedded_capability(u, &d.base.name));
107        return Some(describe_derived_capability(
108            c,
109            base_unit.as_deref(),
110            base.as_ref(),
111        ));
112    }
113    // #2841: a suite's fixture.
114    if let SourceUnit::Suite(suite) = &unit
115        && let Some(f) = suite.fixtures.iter().find(|f| f.name.name == name)
116    {
117        return Some(describe_fixture(f));
118    }
119    for item in items {
120        if let Some(summary) = describe_item(item, name) {
121            return Some(summary);
122        }
123    }
124    None
125}
126
127/// v0.121 (ADR 0156): the reserved-keyword doc for the token at `offset` in
128/// `source`, if the cursor sits on one — matched by source text against
129/// `bynk_syntax::keywords::KEYWORDS`, independent of the token's `TokenKind`
130/// (unlike the identifier-only lexical hover fallback above). This is hover's
131/// floor for the mechanical coverage test: every lowercase-initial keyword
132/// gets at least this, even where `describe_symbol` has no richer path for it
133/// (e.g. the testing-track clause keywords — `requires`/`ensures`/`suite`/…).
134pub fn describe_keyword_at(source: &str, offset: usize) -> Option<&'static str> {
135    let tokens = tokenize(source).ok()?;
136    let word = tokens
137        .iter()
138        .find(|t| t.span.start <= offset && offset < t.span.end)
139        .map(|t| &source[t.span.start..t.span.end])?;
140    bynk_syntax::keywords::KEYWORDS
141        .iter()
142        .find(|k| k.word == word)
143        .map(|k| k.meaning)
144}
145
146/// v0.137.0 (ADR 0161): hover for the `key`/`store` *contextual* keywords and
147/// the agent state fields they introduce. Both are lexed as `Ident`s (not
148/// reserved `KEYWORDS`), and the fields they declare are neither `let`/param
149/// locals nor top-level declarations — so neither the keyword fallback nor the
150/// `describe_symbol`/locals paths in the hover handler reach them. This closes
151/// that gap: for the cursor on the `key`/`store` keyword *or* on the field name
152/// it declares, render the field's signature (type, and a `store` field's
153/// `@indexed`/`@bounded`/… annotations) followed by the contextual-keyword doc.
154///
155/// #611 (gap A): a *reference* to a state field inside the agent's body — a
156/// bare read (`lastSeq + 1`), a `:=` write target, an invariant subject, a store
157/// op's receiver (`items.put(…)`) — renders the same hover as its declaration.
158/// State fields are absent from the project index and are not `let`/param
159/// locals, so a reference resolved nowhere before this. The hover handler tries
160/// the locals path first, so a local shadowing a field name still hovers as the
161/// local — matching the checker, which dispatches a store op only on a bare
162/// ident that is *not* in the value scope.
163///
164/// `None` when the cursor is not on an agent's `key`/`store` keyword, its
165/// state-field name, or a reference to one within the agent.
166pub fn describe_agent_state_at(source: &str, offset: usize) -> Option<String> {
167    let tokens = tokenize(source).ok()?;
168    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
169    let unit = unit?;
170    let items: &[CommonsItem] = match &unit {
171        SourceUnit::Commons(c) => &c.items,
172        SourceUnit::Context(c) => &c.items,
173        SourceUnit::Adapter(a) => &a.items,
174        SourceUnit::Suite(_) => &[],
175    };
176    // State-migrations S3 (#2248): `removed agent Old`, on the `removed`
177    // keyword or the class name.
178    if let SourceUnit::Context(c) = &unit {
179        for r in &c.removed_agents {
180            if span_covers(r.keyword, offset) || span_covers(r.name.span, offset) {
181                return Some(format!(
182                    "```bynk\nremoved agent {}\n```\n\nThe agent class `{}` is gone: its stored \
183                     data is deleted at the next deploy, which needs `--confirm-delete \
184                     <context>.{}`.",
185                    r.name.name, r.name.name, r.name.name
186                ));
187            }
188        }
189    }
190    for item in items {
191        let CommonsItem::Agent(a) = item else {
192            continue;
193        };
194        // State-migrations S3 (#2248): `agent New replaces Old` — on the
195        // `replaces` keyword or the old name.
196        if let Some(old) = &a.replaces {
197            let on_kw = preceding_ident_span(&tokens, source, old.span, "replaces")
198                .is_some_and(|s| span_covers(s, offset));
199            if on_kw || span_covers(old.span, offset) {
200                return Some(format!(
201                    "```bynk\nagent {} replaces {}\n```\n\nRenames the agent class `{}` to `{}`: \
202                     its stored data and schema history move to `{}`.",
203                    a.name.name, old.name, old.name, a.name.name, a.name.name
204                ));
205            }
206        }
207        // `key <name>: <type>` — the cursor on the field name, or on the `key`
208        // keyword token immediately preceding it.
209        let on_key_kw = preceding_ident_span(&tokens, source, a.key_name.span, "key")
210            .is_some_and(|s| span_covers(s, offset));
211        if on_key_kw || span_covers(a.key_name.span, offset) {
212            return Some(key_hover(a));
213        }
214        // `store <name>: <kind> <annotations>` — the parser sets each field's
215        // span to start at its `store` keyword, so the keyword span is derivable
216        // without re-scanning.
217        for f in &a.store_fields {
218            let store_kw = Span {
219                file: f.span.file,
220                start: f.span.start,
221                end: f.span.start + "store".len(),
222            };
223            let on_store_kw = source.get(store_kw.start..store_kw.end) == Some("store")
224                && span_covers(store_kw, offset);
225            if on_store_kw || span_covers(f.name.span, offset) {
226                return Some(store_field_hover(f));
227            }
228        }
229        // State-migrations S2 (#2224): the contextual `migrate` keyword (its
230        // span starts each step) and `drop` (each drop item's keyword span).
231        for m in &a.migrations {
232            if span_covers(m.keyword, offset)
233                && source.get(m.keyword.start..m.keyword.end) == Some("migrate")
234            {
235                return Some(migrate_hover(m));
236            }
237            for item in &m.items {
238                if let MigrateItem::Drop(d) = item
239                    && span_covers(d.keyword, offset)
240                {
241                    return Some(format!(
242                        "```bynk\ndrop {}\n```\n\nDiscards the stored value of `{}` on purpose: \
243                         a removed field the step doesn't read, or a changed `Set`, `Log` or \
244                         `Cache` field, which starts afresh.",
245                        d.field.name, d.field.name
246                    ));
247                }
248            }
249        }
250        // #611: a reference to `key`/`store` state from within this agent.
251        if !in_state_scope(a, offset) {
252            continue;
253        }
254        let Some((name, name_span)) = ident_at(&tokens, source, offset) else {
255            continue;
256        };
257        // State is referenced by **bare** name, so a member of another value
258        // (`p.items`) is not a state reference even when the names coincide.
259        if is_dot_preceded(source, name_span.start) {
260            continue;
261        }
262        if name == a.key_name.name {
263            return Some(key_hover(a));
264        }
265        if let Some(f) = a.store_fields.iter().find(|f| f.name.name == name) {
266            return Some(store_field_hover(f));
267        }
268    }
269    None
270}
271
272/// #706, #2135, #2864: the reserved call-site principals of a test case — each with
273/// what the `system` driver sends for it. Not declarations: `by <name>` names
274/// one of these, never an actor.
275pub const RESERVED_PRINCIPALS: &[(&str, &str)] = &[
276    (
277        "Nobody",
278        "Sends no credential — no `Authorization` header on a Bearer or `Oidc` route, no session cookie on a `SignedCookie` route, no signature headers on a `Signature` route — so the real seam refuses it (`Rejected(Unauthorized)`). `system` tier only.",
279    ),
280    (
281        "Forged",
282        "Signs a `Signature` route's request, or a Bearer route's token (a valid `sub`, a future `exp`), with a secret the seam does not hold, sends a `SignedCookie` route a well-formed cookie signed with a key the seam does not hold, or sends an `Oidc` route a token signed by a key its JWKS does not publish, so the real seam refuses it (`Rejected(Unauthorized)`). `system` tier only.",
283    ),
284    (
285        "Stale",
286        "Signs a `Signature` route's request correctly, timestamped `tolerance + 60` seconds in the past, so the real seam refuses it as a replay (`Rejected(Unauthorized)`). Needs an actor with `timestamp` and `tolerance`. `system` tier only.",
287    ),
288    (
289        "Expired",
290        "Sends a Bearer or `Oidc` route's token, or a `SignedCookie` route's cookie, correctly signed, with a valid `sub` and an expiry one hour in the past, so the real seam refuses it (`Rejected(Unauthorized)`). Needs a `Bearer`, `SignedCookie` or `Oidc` actor. `system` tier only.",
291    ),
292    (
293        "WrongIssuer",
294        "Sends an `Oidc` route a token correctly signed by the test issuer and unexpired, whose `iss` is not the actor's issuer, so the real seam refuses it (`Rejected(Unauthorized)`). Needs an `Oidc` actor. `system` tier only.",
295    ),
296    (
297        "WrongAudience",
298        "Sends an `Oidc` route a token correctly signed by the test issuer and unexpired, whose `aud` is not the actor's audience, so the real seam refuses it (`Rejected(Unauthorized)`). Needs an `Oidc` actor. `system` tier only.",
299    ),
300    (
301        "WrongAlgorithm",
302        "Sends an `Oidc` route two tokens that are otherwise valid, one with `alg: none` and one `HS256`-signed with the JWKS public key as the HMAC secret, so the real seam refuses both (`Rejected(Unauthorized)`); the case reads the first one it admits, if any. Needs an `Oidc` actor. `system` tier only.",
303    ),
304    (
305        "NoSubject",
306        "Sends an `Oidc` route two tokens that are correctly signed by the test issuer and unexpired, one with an empty `sub` and one with no `sub` claim, so the real seam refuses both before the handler runs (`Rejected(Unauthorized)`), whatever the identity's refinement. Needs an `Oidc` actor. `system` tier only.",
307    ),
308];
309
310/// #2135: hover for a reserved principal (`Nobody`, `Forged`, `Stale`,
311/// `Expired`, `WrongIssuer`, `WrongAudience`, `WrongAlgorithm`, `NoSubject`) in a
312/// call-site `by` clause: what the driver sends. `None` when the cursor is not
313/// on one of those names right after `by`.
314pub fn describe_reserved_principal_at(source: &str, offset: usize) -> Option<String> {
315    let tokens = tokenize(source).ok()?;
316    let (name, span) = ident_at(&tokens, source, offset)?;
317    let (_, doc) = RESERVED_PRINCIPALS.iter().find(|(n, _)| *n == name)?;
318    preceding_ident_span(&tokens, source, span, "by")
319        .map(|_| format!("```bynk\nby {name}\n```\n\n{doc}"))
320}
321
322/// #2134: the contextual `env` word's one-line doc, shown when hovering it.
323pub const ENV_KEYWORD_DOC: &str = "The variables and secrets a suite's participants see (`env { NAME = \"value\" … }`): on each Worker's `env` at `system`, and what the `Secrets` double answers at `unit`/`integration`. A case's `env` layers over its suite's, name by name.";
324
325/// #2134: hover for a suite's or case's `env { … }` clause — on the `env`
326/// word, its doc ([`ENV_KEYWORD_DOC`]); on an entry's name, the entry and
327/// where it applies: "variable given to every participant (suite)", or
328/// "(case, overrides suite)" for a case entry its suite also gives. `env` is
329/// lexed as an identifier, so neither the keyword fallback nor the
330/// declaration rungs reach it. `None` when the cursor is on neither.
331pub fn describe_env_at(source: &str, offset: usize) -> Option<String> {
332    let tokens = tokenize(source).ok()?;
333    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
334    let SourceUnit::Suite(suite) = unit? else {
335        return None;
336    };
337    let on_kw = |e: &EnvClause| {
338        span_covers(
339            Span {
340                file: e.span.file,
341                start: e.span.start,
342                end: e.span.start + "env".len(),
343            },
344            offset,
345        )
346    };
347    let suite_gives = |name: &str| {
348        suite
349            .envs
350            .iter()
351            .flat_map(|e| e.entries.iter())
352            .any(|x| x.name.name == name)
353    };
354    let render = |entry: &EnvEntry, scope: &str| {
355        let value = match &entry.value.kind {
356            ExprKind::StrLit(v) => format!("{v:?}"),
357            // #2956: a fixture of the suite, by name.
358            ExprKind::Ident(id) => id.name.clone(),
359            _ => "…".to_string(),
360        };
361        format!(
362            "```bynk\n{} = {value}\n```\n\nvariable given to every participant ({scope})",
363            entry.name.name
364        )
365    };
366    for e in &suite.envs {
367        if on_kw(e) {
368            return Some(ENV_KEYWORD_DOC.to_string());
369        }
370        if let Some(entry) = e.entries.iter().find(|x| span_covers(x.name.span, offset)) {
371            return Some(render(entry, "suite"));
372        }
373    }
374    for case in &suite.cases {
375        for e in &case.envs {
376            if on_kw(e) {
377                return Some(ENV_KEYWORD_DOC.to_string());
378            }
379            if let Some(entry) = e.entries.iter().find(|x| span_covers(x.name.span, offset)) {
380                let scope = if suite_gives(&entry.name.name) {
381                    "case, overrides suite"
382                } else {
383                    "case"
384                };
385                return Some(render(entry, scope));
386            }
387        }
388    }
389    None
390}
391
392/// #611: true when `offset` sits where an agent's `key`/`store` state is
393/// referenceable by bare name — a handler body, or an invariant/transition
394/// predicate. Deliberately narrower than the agent's own span: the declaration
395/// region names things that are *not* state references, and a store annotation
396/// argument (`@indexed(by: id)`) names a field of the **stored value**, which
397/// must not masquerade as a same-named `key`/`store` field.
398fn in_state_scope(a: &AgentDecl, offset: usize) -> bool {
399    a.handlers.iter().any(|h| span_covers(h.body.span, offset))
400        || a.invariants
401            .iter()
402            .any(|i| span_covers(i.predicate.span, offset))
403        || a.transitions
404            .iter()
405            .any(|t| span_covers(t.predicate.span, offset))
406}
407
408/// Hover for a `migrate from N` step (state-migrations S2, #2224).
409fn migrate_hover(m: &MigrateDecl) -> String {
410    let old = m
411        .old
412        .as_ref()
413        .map(|o| format!(" ({}: {})", o.name.name, type_ref_str(&o.type_ref)))
414        .unwrap_or_default();
415    format!(
416        "```bynk\nmigrate from {}{old}\n```\n\nA migration step: carries a stored record from \
417         schema version {} to the agent's current shape when it next loads.",
418        m.from, m.from
419    )
420}
421
422/// The hover for an agent's `key` field — its declaration and every reference.
423fn key_hover(a: &AgentDecl) -> String {
424    let sig = format!("key {}: {}", a.key_name.name, type_ref_str(&a.key_type));
425    render_state_hover(&sig, "key")
426}
427
428/// The hover for a `store` field — its declaration and every reference.
429fn store_field_hover(f: &StoreField) -> String {
430    let mut sig = format!("store {}: {}", f.name.name, store_kind_str(&f.kind));
431    for ann in &f.annotations {
432        sig.push(' ');
433        sig.push_str(&bynk_fmt::annotation_to_string(ann));
434    }
435    render_state_hover(&sig, "store")
436}
437
438/// #611: hover for a `store` field's operation — the `<op>` of a
439/// `<field>.<op>(…)` call on an agent's `store` field (`items.put(id, item)`).
440/// Store operations are checked but never indexed and are not value-receiver
441/// methods, so `qualified_callee_at` (name-receivers only) never reaches them
442/// and they resolved nowhere. Renders the operation's signature from the
443/// enumerable [`bynk_check::store_ops`] registry — generic in the kind's
444/// key/value/element type — over the field's declared kind, which grounds it.
445///
446/// `locals` guards the receiver the way the checker's dispatch does: a store op
447/// is a bare ident receiver that is *not* in the value scope, so a local
448/// shadowing the field name makes this an ordinary value method, not a store op.
449/// `None` when the cursor is not on a store operation of the enclosing agent.
450pub fn describe_store_op_at(
451    source: &str,
452    offset: usize,
453    locals: &[bynk_check::locals::LocalBinding],
454) -> Option<String> {
455    let tokens = tokenize(source).ok()?;
456    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
457    let unit = unit?;
458    let items: &[CommonsItem] = match &unit {
459        SourceUnit::Commons(c) => &c.items,
460        SourceUnit::Context(c) => &c.items,
461        SourceUnit::Adapter(a) => &a.items,
462        SourceUnit::Suite(_) => &[],
463    };
464    // The cursor must sit on the `<op>` of a `<recv>.<op>` access.
465    let (op, op_span) = ident_at(&tokens, source, offset)?;
466    let (recv, recv_start) = receiver_segment_at(source, op_span)?;
467    // The checker dispatches a store op on a **bare** ident receiver only, so a
468    // qualified one is not one: `p.items.contains(…)` is an ordinary value method
469    // on a record field that merely shares a store field's name.
470    if is_dot_preceded(source, recv_start) {
471        return None;
472    }
473    // A local of the receiver's name shadows the store field (the same
474    // by-provenance dispatch) — then this is a value method, not a store op.
475    if bynk_check::locals::locals_at(locals, recv_start)
476        .iter()
477        .any(|b| b.name == recv)
478    {
479        return None;
480    }
481    for item in items {
482        let CommonsItem::Agent(a) = item else {
483            continue;
484        };
485        if !in_state_scope(a, offset) {
486            continue;
487        }
488        let f = a.store_fields.iter().find(|f| f.name.name == recv)?;
489        let sig = bynk_check::store_ops::ops_for(&f.kind.head.name)
490            .iter()
491            .find(|o| o.name == op)?
492            .signature;
493        return Some(format!(
494            "```bynk\n{sig}\n```\n\nA `{}` store operation on `store {}: {}` — the field's \
495             declared kind grounds the operation's type parameters.",
496            f.kind.head.name,
497            f.name.name,
498            store_kind_str(&f.kind),
499        ));
500    }
501    None
502}
503
504/// The identifier token covering `offset` — its text and span — if the cursor is
505/// on one.
506fn ident_at<'a>(
507    tokens: &[bynk_syntax::lexer::Token],
508    source: &'a str,
509    offset: usize,
510) -> Option<(&'a str, Span)> {
511    tokens
512        .iter()
513        .find(|t| t.kind == bynk_syntax::lexer::TokenKind::Ident && span_covers(t.span, offset))
514        .and_then(|t| Some((source.get(t.span.start..t.span.end)?, t.span)))
515}
516
517/// The receiver segment of a `<recv>.<member>` access whose member sits at
518/// `member_span`: the identifier run immediately before the dot, and the offset
519/// it starts at. `None` when the member is not dot-preceded. Shared by every
520/// caller that reads a receiver off the line prefix, so the extraction has one
521/// definition rather than a copy per call site — delegates the actual boundary
522/// scan to `completion::ident_ending_at`.
523fn receiver_segment_at(text: &str, member_span: Span) -> Option<(&str, usize)> {
524    let before = text.get(..member_span.start)?.strip_suffix('.')?;
525    crate::completion::ident_ending_at(before, before.len())
526}
527
528/// True when the identifier starting at `start` is itself the member of a
529/// further access (the `items` of `p.items`) rather than a bare name.
530pub(crate) fn is_dot_preceded(text: &str, start: usize) -> bool {
531    // A `..` is a rest marker (`[x, ..rest]`, `T { f, .. }`), not a member
532    // access, so the name after it is a fresh binding.
533    text[..start].ends_with('.') && !text[..start].ends_with("..")
534}
535
536/// #596: the storage-kind vocabulary a bare receiver is eligible for at
537/// completion's `<recv>.` position — `recv_end` is the offset just past the
538/// receiver identifier (where its dot sat before
539/// `completion::value_receiver_rewrite` dropped it, so `source` here is that
540/// rewritten buffer). Mirrors `describe_store_op_at`'s by-provenance receiver
541/// check (not shadowed by a local, inside the declaring agent's state scope),
542/// but starts from the receiver's own end offset rather than walking back from
543/// an operation token, since completion fires before any member name is
544/// typed — and the rewrite's postcondition already guarantees a bare,
545/// non-dot-qualified name reaches here, so unlike `describe_store_op_at` there
546/// is no further `is_dot_preceded` check to make.
547///
548/// Returns the field's storage-kind head (`"Map"`, `"Cache"`, `"Set"`,
549/// `"Cell"`, `"Log"`) and, for a `Map`, whether its value type is a held
550/// `Connection` (v0.158, ADR 0184: `.entries`/`.keys`/`.values` are refused on
551/// one) — enough for the completion layer to look up each kind's registry
552/// without re-parsing.
553pub fn store_field_kind_at(
554    source: &str,
555    recv_end: usize,
556    locals: &[bynk_check::locals::LocalBinding],
557) -> Option<(String, bool)> {
558    let (recv, recv_start) = crate::completion::ident_ending_at(source, recv_end)?;
559    if bynk_check::locals::locals_at(locals, recv_start)
560        .iter()
561        .any(|b| b.name == recv)
562    {
563        return None;
564    }
565    let tokens = tokenize(source).ok()?;
566    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
567    let unit = unit?;
568    let items: &[CommonsItem] = match &unit {
569        SourceUnit::Commons(c) => &c.items,
570        SourceUnit::Context(c) => &c.items,
571        SourceUnit::Adapter(a) => &a.items,
572        SourceUnit::Suite(_) => &[],
573    };
574    for item in items {
575        let CommonsItem::Agent(a) = item else {
576            continue;
577        };
578        if !in_state_scope(a, recv_end) {
579            continue;
580        }
581        if let Some(f) = a.store_fields.iter().find(|f| f.name.name == recv) {
582            let held = f.kind.head.name == "Map"
583                && f.kind.args.len() == 2
584                && matches!(f.kind.args[1], TypeRef::Connection(..));
585            return Some((f.kind.head.name.clone(), held));
586        }
587    }
588    None
589}
590
591/// v0.140 (ADR 0163): hover for a handler-position annotation (`@cache`). Handler
592/// annotations are not symbols and declare no local, so they miss both the
593/// `describe_symbol` and locals paths — this closes the gap. For the cursor
594/// anywhere within a handler's `@cache( … )` annotation, render the formatted
595/// annotation followed by a prose description of `@cache` and its fields. `None`
596/// when the cursor is not inside a handler annotation.
597pub fn describe_handler_annotation_at(source: &str, offset: usize) -> Option<String> {
598    let tokens = tokenize(source).ok()?;
599    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
600    let unit = unit?;
601    let items: &[CommonsItem] = match &unit {
602        SourceUnit::Commons(c) => &c.items,
603        SourceUnit::Context(c) => &c.items,
604        SourceUnit::Adapter(a) => &a.items,
605        SourceUnit::Suite(_) => &[],
606    };
607    for item in items {
608        let (handlers, service_cap): (&[Handler], Option<i64>) = match item {
609            CommonsItem::Service(s) => (&s.handlers, s.limits.as_ref().and_then(|l| l.max_body())),
610            CommonsItem::Agent(a) => (&a.handlers, None),
611            _ => continue,
612        };
613        for h in handlers {
614            for ann in &h.annotations {
615                if span_covers(ann.span, offset) {
616                    return Some(render_handler_annotation_hover(ann, h, service_cap));
617                }
618            }
619        }
620    }
621    None
622}
623
624/// #2686: hover for an `@example` after a type declaration's or record field's
625/// refinement: the example and the refinement it has to satisfy. `None`
626/// elsewhere.
627pub fn describe_refinement_example_at(source: &str, offset: usize) -> Option<String> {
628    let tokens = tokenize(source).ok()?;
629    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
630    let items: &[CommonsItem] = match unit.as_ref()? {
631        SourceUnit::Commons(c) => &c.items,
632        SourceUnit::Context(c) => &c.items,
633        SourceUnit::Adapter(a) => &a.items,
634        SourceUnit::Suite(_) => &[],
635    };
636    let render = |r: &bynk_syntax::ast::Refinement| -> Option<String> {
637        let ann = r
638            .annotations
639            .iter()
640            .find(|a| a.name.name == "example" && span_covers(a.span, offset))?;
641        let value = ann
642            .args
643            .first()
644            .map(|a| bynk_fmt::expr_to_string(&a.value))
645            .unwrap_or_default();
646        Some(format!(
647            "**`@example({value})`** — the value `Val` uses where it cannot generate one; checked against `{}`. Test-only: it changes neither the type nor its wire format.",
648            bynk_syntax::print::refinement_to_string(r)
649        ))
650    };
651    for item in items {
652        let CommonsItem::Type(t) = item else { continue };
653        match &t.body {
654            bynk_syntax::ast::TypeBody::Refined { refinement, .. }
655            | bynk_syntax::ast::TypeBody::Opaque { refinement, .. } => {
656                if let Some(h) = refinement.as_ref().and_then(render) {
657                    return Some(h);
658                }
659            }
660            bynk_syntax::ast::TypeBody::Record(rec) => {
661                for f in &rec.fields {
662                    if let Some(h) = f.refinement.as_ref().and_then(render) {
663                        return Some(h);
664                    }
665                }
666            }
667            bynk_syntax::ast::TypeBody::Sum(_) => {}
668        }
669    }
670    None
671}
672
673/// #2137 (ADR 0156): hover for the contextual `advance` keyword of an
674/// `advance Clock by <Duration>` statement. `None` anywhere else, so an
675/// ordinary identifier named `advance` keeps its own hover.
676pub fn describe_advance_at(source: &str, offset: usize) -> Option<String> {
677    let tokens = tokenize(source).ok()?;
678    let idx = tokens
679        .iter()
680        .position(|t| t.span.start <= offset && offset < t.span.end)?;
681    let text = |i: usize| tokens.get(i).map(|t| &source[t.span.start..t.span.end]);
682    if text(idx)? != "advance"
683        || tokens.get(idx + 1)?.kind != bynk_syntax::lexer::TokenKind::Ident
684        || text(idx + 2)? != "by"
685    {
686        return None;
687    }
688    Some(
689        "```bynk\nadvance Clock by <Duration>\n```\n\nMoves the test harness's clock forward. Each case's clock starts at the epoch; at `unit` and `integration` the `Clock` double reads it, and at `system` every participant's first-party `Clock` does. It governs `Clock` only: JWT expiry, the `Signature` tolerance and Durable Object alarms keep wall-clock time."
690            .to_string(),
691    )
692}
693
694/// #3191 (ADR 0161): hover for the contextual `by` where it is a clause word —
695/// a handler's or service header's actor clause, a call's actor clause, or the
696/// `by` of `advance Clock by <Duration>`. `None` where `by` is an ordinary name
697/// (a parameter, a binding, a field), which keeps that name's own hover.
698pub fn describe_by_at(source: &str, offset: usize) -> Option<String> {
699    let tokens = tokenize(source).ok()?;
700    let idx = tokens
701        .iter()
702        .position(|t| t.span.start <= offset && offset < t.span.end)?;
703    let text = |i: usize| tokens.get(i).map(|t| &source[t.span.start..t.span.end]);
704    if text(idx)? != "by" || tokens.get(idx)?.kind != bynk_syntax::lexer::TokenKind::Ident {
705        return None;
706    }
707    let advance = idx >= 2
708        && text(idx - 2) == Some("advance")
709        && tokens.get(idx - 1)?.kind == bynk_syntax::lexer::TokenKind::Ident;
710    let start = tokens[idx].span.start;
711    let line_start = source[..start].rfind('\n').map_or(0, |i| i + 1);
712    let prefix = format!("{}by ", &source[line_start..start]);
713    // A clause word is followed by the name it governs; a `by` that ends the
714    // expression (`{ by }`) is a reference.
715    let named = tokens.get(idx + 1).map(|t| t.kind) == Some(bynk_syntax::lexer::TokenKind::Ident);
716    if !(advance || named && crate::completion::is_by_clause_position(&prefix)) {
717        return None;
718    }
719    let (shape, doc) = if advance {
720        (
721            "advance Clock by <Duration>",
722            "The amount to move the test harness's clock forward by.",
723        )
724    } else {
725        (
726            "by <name>: <Actor>",
727            "Names the actor a handler consumes, after the return type or on a service header — or, at a call, the principal it is made as (`let r <- f() by User(\"bob\")`). Outside these positions `by` is an ordinary name.",
728        )
729    };
730    Some(format!("```bynk\n{shape}\n```\n\n{doc}"))
731}
732
733/// Constrained generics slice 1 (ADR 0156): hover for the contextual `derives`
734/// keyword of a type declaration's `derives Ord` clause. `None` anywhere else,
735/// so an ordinary identifier named `derives` keeps its own hover.
736pub fn describe_derives_at(source: &str, offset: usize) -> Option<String> {
737    let tokens = tokenize(source).ok()?;
738    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
739    let items: &[CommonsItem] = match unit.as_ref()? {
740        SourceUnit::Commons(c) => &c.items,
741        SourceUnit::Context(c) => &c.items,
742        SourceUnit::Adapter(a) => &a.items,
743        SourceUnit::Suite(_) => return None,
744    };
745    items.iter().find_map(|item| match item {
746        CommonsItem::Type(t) if t.derives_kw.is_some_and(|k| k.start <= offset && offset < k.end) => {
747            Some(
748                "```bynk\ntype Priority = enum { Low, High } derives Ord\n```\n\nOpts the type into a constraint. `derives Ord` orders the type by declaration order: a record compares field by field, then a sum by variant, so reordering the declaration changes the order. Every field must itself be orderable. `Eq`, `Key` and `Codable` are automatic and are not derived."
749                    .to_string(),
750            )
751        }
752        _ => None,
753    })
754}
755
756/// The doc for a constraint name (`Eq`, `Ord`, `Key`, `Codable`), shown on hover wherever one
757/// appears in a bound or a `derives` clause.
758fn constraint_doc(name: &str) -> Option<&'static str> {
759    match name {
760        "Eq" => Some(
761            "```bynk\nconstraint Eq\n```\n\nValues of the type compare with `==` and `!=`. Declare it on a type parameter (`T: Eq`) to compare its values inside the function. Every type that can be compared is `Eq` automatically.",
762        ),
763        "Ord" => Some(
764            "```bynk\nconstraint Ord\n```\n\nValues of the type are ordered: they compare with `<`, `<=`, `>` and `>=`, and can be sorted. Declare it on a type parameter (`T: Ord`) to order its values inside the function; `Ord` implies `Eq`. A type opts in with `derives Ord`, which orders it by declaration order.",
765        ),
766        "Key" => Some(
767            "```bynk\nconstraint Key\n```\n\nValues of the type can key a `Map` or be a `Set` member, and group under `distinct` and `groupBy`. Declare it on a type parameter (`K: Key`) to use it that way inside the function; `Key` implies `Eq`. Strings, ints, bytes, `Option` and `List` of a key, and records, sums and enums made of keys are `Key` automatically; a `Float` never is.",
768        ),
769        "Codable" => Some(
770            "```bynk\nconstraint Codable\n```\n\nValues of the type encode and decode with `Json`. Declare it on a type parameter (`T: Codable`) to call `Json.encode` and `Json.decode[T]` inside the function, or to pass the value to a `Codable` parameter of a capability operation, which encodes it at the call site so the provider receives plain JSON. Every type `Json.decode` accepts is `Codable` automatically; `()`, functions, `Effect`, streams and the HTTP result types are not.",
771        ),
772        _ => None,
773    }
774}
775
776/// Constrained generics slice 1: hover for a constraint name in a bound
777/// (`T: Ord`, `where A: Eq`) or a `derives` clause. `None` for any other
778/// identifier, so a type that happens to be named `Ord` keeps its own hover.
779pub fn describe_constraint_at(source: &str, offset: usize) -> Option<String> {
780    let span = constraint_token_spans(source)
781        .into_iter()
782        .find(|s| s.start <= offset && offset < s.end)?;
783    constraint_doc(&source[span.start..span.end]).map(str::to_string)
784}
785
786/// #2640 (ADR 0156): hover for the contextual `par` keyword of a `par { … }`
787/// binding block. `None` anywhere else, so an ordinary identifier named `par`
788/// keeps its own hover.
789pub fn describe_par_at(source: &str, offset: usize) -> Option<String> {
790    let tokens = tokenize(source).ok()?;
791    let idx = tokens
792        .iter()
793        .position(|t| t.span.start <= offset && offset < t.span.end)?;
794    let text = |i: usize| tokens.get(i).map(|t| &source[t.span.start..t.span.end]);
795    if text(idx)? != "par" || tokens.get(idx + 1)?.kind != bynk_syntax::lexer::TokenKind::LBrace {
796        return None;
797    }
798    Some(
799        "```bynk\npar {\n  let a <- first()\n  let b <- second()\n}\n```\n\nIssues every effect in the block, in source order, before awaiting any of them, and completes when all have settled. The names bound inside are in scope after the closing brace; no binding may mention a name a sibling binds. If any effect faults, the block waits for the rest, then raises the first fault in source order. Holds only `let x <- e` and `do e`."
800            .to_string(),
801    )
802}
803
804/// #2841: a hover for the contextual `fixture` keyword under the cursor: an
805/// identifier spelled `fixture` followed by a name and `=`, the one position a
806/// suite body reads it as a declaration. `None` anywhere else.
807pub fn describe_fixture_at(source: &str, offset: usize) -> Option<String> {
808    use bynk_syntax::lexer::TokenKind;
809    let tokens = tokenize(source).ok()?;
810    let idx = tokens
811        .iter()
812        .position(|t| t.span.start <= offset && offset < t.span.end)?;
813    let t = tokens.get(idx)?;
814    if t.kind != TokenKind::Ident
815        || &source[t.span.start..t.span.end] != "fixture"
816        || tokens.get(idx + 1)?.kind != TokenKind::Ident
817        || tokens.get(idx + 2)?.kind != TokenKind::Eq
818    {
819        return None;
820    }
821    let doc = bynk_syntax::keywords::CONTEXTUAL_KEYWORDS
822        .iter()
823        .find(|k| k.word == "fixture")
824        .map(|k| k.meaning)
825        .unwrap_or_default();
826    Some(format!("```bynk\nfixture\n```\n\n{doc}"))
827}
828
829/// #2618: a hover for the contextual `private` modifier under the cursor:
830/// an identifier spelled `private` immediately before a `fn`, `type`,
831/// `messages`, `asset`, `embed` or `const` keyword, the one position the parser reads
832/// it as the modifier. `None` anywhere else, where `private` is an ordinary
833/// name.
834pub fn describe_private_at(source: &str, offset: usize) -> Option<String> {
835    use bynk_syntax::lexer::TokenKind;
836    let tokens = tokenize(source).ok()?;
837    let idx = tokens
838        .iter()
839        .position(|t| t.span.start <= offset && offset < t.span.end)?;
840    let t = tokens.get(idx)?;
841    if t.kind != TokenKind::Ident || &source[t.span.start..t.span.end] != "private" {
842        return None;
843    }
844    let next = tokens.get(idx + 1)?.kind;
845    if !matches!(
846        next,
847        TokenKind::Fn
848            | TokenKind::Type
849            | TokenKind::Messages
850            | TokenKind::Asset
851            | TokenKind::Embed
852            | TokenKind::Const
853    ) {
854        return None;
855    }
856    let doc = bynk_syntax::keywords::CONTEXTUAL_KEYWORDS
857        .iter()
858        .find(|k| k.word == "private")
859        .map(|k| k.meaning)
860        .unwrap_or_default();
861    Some(format!("```bynk\nprivate\n```\n\n{doc}"))
862}
863
864/// #2138: the doc `run.id` shows on hover and in completion.
865pub const RUN_ID_DOC: &str = "**`run.id`** — this test run's identity, a `String`. In process it is always `\"local\"`; each `bynk test --against` run gets a fresh one, so a key built from it (`\"order-\\(run.id)\"`) doesn't collide with an earlier run's data on a shared deployment.";
866
867/// #2138: whether the `run` identifier starting at `run_start` in `source`
868/// is the test run's `run` — inside a suite's `case` body, with no binder of
869/// its own in scope there. #2175: the scope is the checker's: a `let` earlier
870/// in any enclosing block, a lambda parameter, a `match` arm's pattern, or an
871/// `is <pattern>` test's bindings all shadow it. #2181: an `is` test binds
872/// where the checker says it does (`bynk_check::narrowing`): in an `if`'s
873/// `then` block when the condition holds, in its `else` block when it fails
874/// (`if !(v is Some(run)) { … } else { run.id }`), and on the right of `&&`
875/// and `implies` (`v is Some(run) && run.id == "x"`).
876pub fn is_test_run_receiver(source: &str, run_start: usize) -> bool {
877    let Ok(tokens) = tokenize(source) else {
878        return false;
879    };
880    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
881    let Some(SourceUnit::Suite(suite)) = unit else {
882        return false;
883    };
884    let Some(case) = suite.cases.iter().find(|c| span_covers(c.span, run_start)) else {
885        return false;
886    };
887    run_bound_in_block(&case.body, run_start, &mut Vec::new()) != Some(true)
888}
889
890/// Whether the `run` at `at` is bound by a binder in scope, if `at` is in
891/// `block`; `bound` holds the names bound around it.
892fn run_bound_in_block(block: &Block, at: usize, bound: &mut Vec<String>) -> Option<bool> {
893    let mark = bound.len();
894    let mut found = None;
895    for stmt in &block.statements {
896        let mut exprs = Vec::new();
897        statement_exprs(stmt, &mut exprs);
898        found = exprs
899            .into_iter()
900            .find_map(|e| run_bound_in_expr(e, at, bound));
901        if found.is_some() {
902            break;
903        }
904        // A `let`'s own value doesn't see its name; what follows does.
905        if let Statement::Let(l) | Statement::EffectLet(l) = stmt {
906            bound.push(l.name.name.clone());
907        }
908        // #2640: a `par` block's names enter scope after its closing brace.
909        if let Statement::Par(p) = stmt {
910            bound.extend(p.statements.iter().filter_map(|s| match s {
911                Statement::EffectLet(l) => Some(l.name.name.clone()),
912                _ => None,
913            }));
914        }
915    }
916    let found = found.or_else(|| run_bound_in_expr(&block.tail, at, bound));
917    bound.truncate(mark);
918    found
919}
920
921fn run_bound_in_expr(e: &Expr, at: usize, bound: &mut Vec<String>) -> Option<bool> {
922    if !span_covers(e.span, at) {
923        return None;
924    }
925    let mark = bound.len();
926    let found = match &e.kind {
927        ExprKind::Ident(id) if id.span.start == at && id.name == "run" => {
928            Some(bound.iter().any(|n| n == "run"))
929        }
930        ExprKind::Block(b) => run_bound_in_block(b, at, bound),
931        ExprKind::Lambda(l) => {
932            bound.extend(l.params.iter().map(|p| p.name.name.clone()));
933            run_bound_in_expr(&l.body, at, bound)
934        }
935        ExprKind::If {
936            cond,
937            then_block,
938            else_block,
939        } => run_bound_in_expr(cond, at, bound)
940            .or_else(|| {
941                let inner = bound.len();
942                bound.extend(is_bound_names(cond, true));
943                let r = run_bound_in_block(then_block, at, bound);
944                bound.truncate(inner);
945                r
946            })
947            .or_else(|| {
948                let inner = bound.len();
949                bound.extend(is_bound_names(cond, false));
950                let r = run_bound_in_block(else_block, at, bound);
951                bound.truncate(inner);
952                r
953            }),
954        // The left side's `is` bindings reach the right side.
955        ExprKind::BinOp(BinOp::And | BinOp::Implies, lhs, rhs) => run_bound_in_expr(lhs, at, bound)
956            .or_else(|| {
957                bound.extend(is_bound_names(lhs, true));
958                run_bound_in_expr(rhs, at, bound)
959            }),
960        ExprKind::Match { discriminant, arms } => run_bound_in_expr(discriminant, at, bound)
961            .or_else(|| {
962                arms.iter()
963                    .find(|a| span_covers(a.span, at))
964                    .and_then(|arm| {
965                        bound.extend(
966                            arm.pattern
967                                .bound_names()
968                                .into_iter()
969                                .map(|id| id.name.clone()),
970                        );
971                        arm.guard
972                            .as_ref()
973                            .and_then(|g| run_bound_in_expr(g, at, bound))
974                            .or_else(|| match &arm.body {
975                                MatchBody::Expr(body) => run_bound_in_expr(body, at, bound),
976                                MatchBody::Block(b) => run_bound_in_block(b, at, bound),
977                            })
978                    })
979            }),
980        _ => expr_children(e)
981            .into_iter()
982            .find_map(|c| run_bound_in_expr(c, at, bound)),
983    };
984    bound.truncate(mark);
985    found
986}
987
988/// The names `cond`'s `is <pattern>` tests bind when it evaluates to
989/// `when_true`, by the checker's own rule.
990fn is_bound_names(cond: &Expr, when_true: bool) -> Vec<String> {
991    bynk_check::narrowing::matched_is_tests(cond, when_true)
992        .into_iter()
993        .filter_map(|test| match &test.kind {
994            ExprKind::Is { pattern, .. } => Some(pattern.bound_names()),
995            _ => None,
996        })
997        .flatten()
998        .map(|id| id.name.clone())
999        .collect()
1000}
1001
1002/// #2138 (ADR 0156): hover for `run.id` in a `case` body — on either the
1003/// `run` or the `id`. `None` anywhere else, and where the case binds its own
1004/// `run`, so an ordinary value keeps its own hover.
1005pub fn describe_run_id_at(source: &str, offset: usize) -> Option<String> {
1006    // A character scan, not the token stream: `run.id` is often inside a
1007    // string interpolation (`"order-\(run.id)"`), which lexes as one token.
1008    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
1009    let offset = offset.min(source.len());
1010    let start = source[..offset]
1011        .char_indices()
1012        .rev()
1013        .take_while(|(_, c)| is_ident(*c))
1014        .last()
1015        .map_or(offset, |(i, _)| i);
1016    let end = source[start..]
1017        .char_indices()
1018        .find(|(_, c)| !is_ident(*c))
1019        .map_or(source.len(), |(i, _)| start + i);
1020    let ends_ident = |rest: &str| !rest.starts_with(is_ident);
1021    let run = match &source[start..end] {
1022        "run" if source[end..].strip_prefix(".id").is_some_and(ends_ident) => start,
1023        "id" if source[..start].ends_with("run.") => start - "run.".len(),
1024        _ => return None,
1025    };
1026    if source[..run].ends_with(|c: char| is_ident(c) || c == '.') {
1027        return None; // `x.run.id` or `myrun.id`: not the test run
1028    }
1029    is_test_run_receiver(source, run).then(|| RUN_ID_DOC.to_string())
1030}
1031
1032/// #2136 (ADR 0156): hover for the `schedule` / `message` address name in a
1033/// `system`-tier case (`sweeper.schedule(…)`, `deliveries.message(m)`), which
1034/// runs the handler through the participant Worker's own `scheduled` / `queue`
1035/// entry point rather than in process. `None` anywhere else, including the
1036/// same address at `unit` or `integration`, and a `.schedule` / `.message`
1037/// whose receiver is not a `cron` / `queue` service of the suite's target (a
1038/// record field named `message`, say). The target's declaration is looked up
1039/// in `source` and `others` (the project's other files).
1040pub fn describe_system_job_address_at<'s>(
1041    source: &'s str,
1042    offset: usize,
1043    others: impl IntoIterator<Item = &'s str>,
1044) -> Option<String> {
1045    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
1046    let start = source[..offset.min(source.len())]
1047        .char_indices()
1048        .rev()
1049        .take_while(|(_, c)| is_ident(*c))
1050        .last()
1051        .map_or(offset, |(i, _)| i);
1052    let end = source[start..]
1053        .char_indices()
1054        .find(|(_, c)| !is_ident(*c))
1055        .map_or(source.len(), |(i, _)| start + i);
1056    let name = &source[start..end];
1057    if !source[..start].ends_with('.') || !matches!(name, "schedule" | "message") {
1058        return None;
1059    }
1060    let tokens = tokenize(source).ok()?;
1061    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1062    let SourceUnit::Suite(suite) = unit? else {
1063        return None;
1064    };
1065    let case = suite.cases.iter().find(|c| span_covers(c.span, start))?;
1066    if case.tier.or(suite.tier) != Some(TestTier::System) {
1067        return None;
1068    }
1069    // The receiver: the identifier right before the `.`.
1070    let before = &source[..start - 1];
1071    let receiver = &before[before
1072        .char_indices()
1073        .rev()
1074        .take_while(|(_, c)| is_ident(*c))
1075        .last()
1076        .map_or(before.len(), |(i, _)| i)..];
1077    let target = suite.target.joined();
1078    // `ServiceProtocol` rather than the model's `ProtocolIr`, under M-1's domain
1079    // clause (the system-model ADR, crate-hygiene B1, #2939). The buffers here
1080    // are re-parsed with recovery and never checked, and `ProtocolIr` needs a
1081    // checked program.
1082    let is_job_service = std::iter::once(source).chain(others).any(|src| {
1083        let Ok(tokens) = tokenize(src) else {
1084            return false;
1085        };
1086        let (unit, _errs) = parse_unit_with_recovery(&tokens, src);
1087        let Some(SourceUnit::Context(ctx)) = unit else {
1088            return false;
1089        };
1090        ctx.name.joined() == target
1091            && ctx.items.iter().any(|item| {
1092                matches!(item, CommonsItem::Service(svc)
1093                if svc.name.name == receiver
1094                    && match name {
1095                        "schedule" => matches!(svc.protocol, ServiceProtocol::Cron),
1096                        _ => matches!(svc.protocol, ServiceProtocol::Queue { .. }),
1097                    })
1098            })
1099    });
1100    if !is_job_service {
1101        return None;
1102    }
1103    Some(if name == "schedule" {
1104        "**`svc.schedule(\"<expr>\", at: Instant)`** at `system` — runs the cron handler through the Worker's `scheduled` entry, with `{ cron, scheduledTime: at }`, and yields the handler's own `Result`.".to_string()
1105    } else {
1106        "**`q.message(m)`** at `system` — delivers `m` through the Worker's `queue` entry, after a JSON round trip, and yields `Ack` or `Retry(reason)` as the consumer acknowledged or retried it.".to_string()
1107    })
1108}
1109
1110/// v0.140 (ADR 0163): the spans to classify as `decorator` semantic tokens — each
1111/// handler annotation's `@name` (the `@` through the name) and its argument labels
1112/// (`maxAge:`, `scope:`). Parsed from `source`; empty when it carries no handler
1113/// annotations. Feeds the semantic-tokens producer, which is otherwise a
1114/// parse-free index read, so the parse lives here beside the hover parse.
1115pub fn handler_annotation_token_spans(source: &str) -> Vec<Span> {
1116    let Ok(tokens) = tokenize(source) else {
1117        return Vec::new();
1118    };
1119    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1120    let Some(unit) = unit else {
1121        return Vec::new();
1122    };
1123    let items: &[CommonsItem] = match &unit {
1124        SourceUnit::Commons(c) => &c.items,
1125        SourceUnit::Context(c) => &c.items,
1126        SourceUnit::Adapter(a) => &a.items,
1127        SourceUnit::Suite(_) => &[],
1128    };
1129    let mut spans = Vec::new();
1130    // #2686: `@example` after a type declaration's or record field's refinement.
1131    fn push_refinement(spans: &mut Vec<Span>, r: &Option<bynk_syntax::ast::Refinement>) {
1132        for ann in r.iter().flat_map(|r| &r.annotations) {
1133            spans.push(Span {
1134                file: ann.span.file,
1135                start: ann.span.start,
1136                end: ann.name.span.end,
1137            });
1138        }
1139    }
1140    for item in items {
1141        if let CommonsItem::Type(t) = item {
1142            match &t.body {
1143                bynk_syntax::ast::TypeBody::Refined { refinement, .. }
1144                | bynk_syntax::ast::TypeBody::Opaque { refinement, .. } => {
1145                    push_refinement(&mut spans, refinement)
1146                }
1147                bynk_syntax::ast::TypeBody::Record(r) => {
1148                    for f in &r.fields {
1149                        push_refinement(&mut spans, &f.refinement);
1150                    }
1151                }
1152                bynk_syntax::ast::TypeBody::Sum(_) => {}
1153            }
1154            continue;
1155        }
1156        let handlers: &[Handler] = match item {
1157            CommonsItem::Service(s) => &s.handlers,
1158            CommonsItem::Agent(a) => &a.handlers,
1159            _ => continue,
1160        };
1161        for h in handlers {
1162            for ann in &h.annotations {
1163                // The `@name` — from the annotation's leading `@` through its name.
1164                spans.push(Span {
1165                    file: ann.span.file,
1166                    start: ann.span.start,
1167                    end: ann.name.span.end,
1168                });
1169                // Each argument label (`maxAge:`, `scope:`).
1170                for arg in &ann.args {
1171                    if let Some(label) = &arg.label {
1172                        spans.push(label.span);
1173                    }
1174                }
1175            }
1176        }
1177    }
1178    spans
1179}
1180
1181/// #2842: one `expect … matches snapshot "<name>"` claim of a suite: the case
1182/// it is in, its name, the claim's `matches snapshot "<name>"` span, and the
1183/// spans of the two contextual words.
1184pub struct SnapshotSite {
1185    pub case: String,
1186    pub name: String,
1187    pub clause: Span,
1188    pub words: [Span; 2],
1189}
1190
1191/// Every snapshot claim in a suite's cases, in source order. Empty for any
1192/// other unit, and for a source that does not parse.
1193pub fn snapshot_sites(source: &str) -> Vec<SnapshotSite> {
1194    let Ok(tokens) = tokenize(source) else {
1195        return Vec::new();
1196    };
1197    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1198    let Some(SourceUnit::Suite(suite)) = unit else {
1199        return Vec::new();
1200    };
1201    let mut out = Vec::new();
1202    for case in &suite.cases {
1203        for e in bynk_check::test_suites::snapshot_expects(&case.body) {
1204            let Some(clause) = &e.snapshot else { continue };
1205            // The words are the first two identifier tokens of the clause.
1206            let words: Vec<Span> = tokens
1207                .iter()
1208                .filter(|t| {
1209                    t.kind == bynk_syntax::lexer::TokenKind::Ident
1210                        && t.span.start >= clause.span.start
1211                        && t.span.end <= clause.span.end
1212                })
1213                .take(2)
1214                .map(|t| t.span)
1215                .collect();
1216            let [matches, snapshot] = words[..] else {
1217                continue;
1218            };
1219            out.push(SnapshotSite {
1220                case: case.name.clone(),
1221                name: clause.name.clone(),
1222                clause: clause.span,
1223                words: [matches, snapshot],
1224            });
1225        }
1226    }
1227    out
1228}
1229
1230/// #2842: the contextual `matches` and `snapshot` of every snapshot claim, for
1231/// the `keyword` semantic token (an editor grammar that matches by spelling
1232/// cannot tell them from a binding of the same name).
1233pub fn snapshot_keyword_spans(source: &str) -> Vec<Span> {
1234    snapshot_sites(source)
1235        .into_iter()
1236        .flat_map(|s| s.words)
1237        .collect()
1238}
1239
1240/// #2842: the project-relative file (`snapshots/….snap.json`) that holds the
1241/// snapshots of the suite file at `rel`.
1242pub fn snapshot_file_for(rel: &Path) -> String {
1243    bynk_project::snapshots::snapshot_path(rel)
1244}
1245
1246/// #2842 (ADR 0156): hover for a snapshot claim: the snapshot the file under
1247/// `snapshots/` holds for it, or that none is recorded yet. `stored` is that
1248/// file's text (`None` when it does not exist). `None` away from a claim.
1249pub fn describe_snapshot_at(source: &str, offset: usize, stored: Option<&str>) -> Option<String> {
1250    let site = snapshot_sites(source)
1251        .into_iter()
1252        .find(|s| s.clause.start <= offset && offset < s.clause.end)?;
1253    let recorded = stored
1254        .and_then(|text| serde_json::from_str::<serde_json::Value>(text).ok())
1255        .and_then(|v| v.get(&site.case)?.get(&site.name).cloned());
1256    let head = format!(
1257        "```bynk\nexpect <value> matches snapshot \"{}\"\n```\n\nCompares the value's canonical JSON (`Json.encode`, keys sorted) with the snapshot stored for case `\"{}\"`.",
1258        site.name, site.case
1259    );
1260    Some(match recorded {
1261        Some(value) => {
1262            let pretty = serde_json::to_string_pretty(&value).unwrap_or_default();
1263            format!("{head}\n\nStored:\n\n```json\n{pretty}\n```")
1264        }
1265        None => format!(
1266            "{head}\n\nNot yet recorded: `bynk test --update-snapshots` writes it, and a run without the flag fails until it does."
1267        ),
1268    })
1269}
1270
1271/// #2618: the span of every `private` modifier on the unit's declarations
1272/// (and, #2841, every suite `fixture` keyword), for the `keyword` semantic token.
1273/// `private` is contextual, so an editor
1274/// grammar that matches keywords by spelling cannot tell the modifier from a
1275/// binding named `private`; the parse can.
1276pub fn private_modifier_token_spans(source: &str) -> Vec<Span> {
1277    let Ok(tokens) = tokenize(source) else {
1278        return Vec::new();
1279    };
1280    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1281    let Some(unit) = unit else {
1282        return Vec::new();
1283    };
1284    let items: &[CommonsItem] = match &unit {
1285        SourceUnit::Commons(c) => &c.items,
1286        SourceUnit::Context(c) => &c.items,
1287        SourceUnit::Adapter(a) => &a.items,
1288        SourceUnit::Suite(_) => &[],
1289    };
1290    let mut spans: Vec<Span> = items.iter().filter_map(CommonsItem::private_span).collect();
1291    // #2841: and each suite `fixture` keyword — contextual as well.
1292    if let SourceUnit::Suite(s) = &unit {
1293        spans.extend(
1294            s.fixtures
1295                .iter()
1296                .map(|f| Span::new(f.span.start, f.span.start + "fixture".len())),
1297        );
1298    }
1299    spans
1300}
1301
1302/// #2837: the span of every reserved word written as a name, with whether it
1303/// names a method (called, or declared with `fn T.name(`) rather than a field.
1304/// A keyword admitted as a label (`{ type: String }`) or as a member on the
1305/// `.`'s line (`a.type`, `Sorted.from(xs)`) is lexed as a keyword, so a client
1306/// that colours by spelling shows it as one; a `property` or `method` token
1307/// says what it is. The index already tokens a field's declaration and uses;
1308/// the caller keeps the index's token where both have one.
1309///
1310/// Wider than the parser: it does not know the file parses, so it also tokens
1311/// a keyword in broken code that the parser would refuse (a `foo.` then a
1312/// keyword on the same line, say). Harmless for a colour, wrong for nothing else.
1313///
1314/// Lexical, so it needs no parse: the two admitting contexts are the same
1315/// token shapes the parser tests. A keyword label opens an entry
1316/// (`{`, `,` or `(` before it) and a member shares a line with its `.`.
1317pub fn keyword_name_token_spans(source: &str) -> Vec<(Span, bool)> {
1318    use bynk_syntax::lexer::TokenKind;
1319    use bynk_syntax::parser::is_reserved_keyword;
1320    let Ok(tokens) = tokenize(source) else {
1321        return Vec::new();
1322    };
1323    let mut out = Vec::new();
1324    for (i, t) in tokens.iter().enumerate() {
1325        if !is_reserved_keyword(t.kind) {
1326            continue;
1327        }
1328        let prev = i.checked_sub(1).map(|j| &tokens[j]);
1329        let next = tokens.get(i + 1).map(|n| n.kind);
1330        match prev {
1331            Some(p)
1332                if p.kind == TokenKind::Dot && !source[p.span.end..t.span.start].contains('\n') =>
1333            {
1334                out.push((t.span, next == Some(TokenKind::LParen)));
1335            }
1336            Some(p)
1337                if matches!(
1338                    p.kind,
1339                    TokenKind::LBrace | TokenKind::Comma | TokenKind::LParen
1340                ) && next == Some(TokenKind::Colon) =>
1341            {
1342                out.push((t.span, false));
1343            }
1344            _ => {}
1345        }
1346    }
1347    out
1348}
1349
1350/// Constrained generics slice 0: the span of every constraint name in a bound
1351/// — a type parameter's (`T: Eq` on a `fn`, `type` or capability operation)
1352/// and a method's `where A: Eq` entries — so the editor can classify them as
1353/// `interface` tokens.
1354pub fn constraint_token_spans(source: &str) -> Vec<Span> {
1355    let Ok(tokens) = tokenize(source) else {
1356        return Vec::new();
1357    };
1358    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1359    let Some(unit) = unit else {
1360        return Vec::new();
1361    };
1362    let items: &[CommonsItem] = match &unit {
1363        SourceUnit::Commons(c) => &c.items,
1364        SourceUnit::Context(c) => &c.items,
1365        SourceUnit::Adapter(a) => &a.items,
1366        SourceUnit::Suite(_) => &[],
1367    };
1368    let mut spans = Vec::new();
1369    fn params(tps: &[TypeParam], spans: &mut Vec<Span>) {
1370        for tp in tps {
1371            spans.extend(tp.bounds.iter().map(|b| b.span));
1372        }
1373    }
1374    for item in items {
1375        match item {
1376            CommonsItem::Fn(f) => params(&f.type_params, &mut spans),
1377            CommonsItem::Type(t) => {
1378                params(&t.type_params, &mut spans);
1379                // Constrained generics slice 1: `derives Ord` names constraints too.
1380                spans.extend(t.derives.iter().map(|d| d.span));
1381            }
1382            CommonsItem::Capability(c) => {
1383                for op in &c.ops {
1384                    params(&op.type_params, &mut spans);
1385                }
1386            }
1387            _ => {}
1388        }
1389        if let CommonsItem::Fn(f) = item {
1390            for wb in &f.where_bounds {
1391                spans.extend(wb.bounds.iter().map(|b| b.span));
1392            }
1393        }
1394    }
1395    spans
1396}
1397
1398/// The `Cache-Control` value a well-formed `@cache` emits. It is the same
1399/// reading `bynk_model::lower_route_cache_ir` makes, but taken per annotation
1400/// over a parse, so it stays on the AST under M-1's domain clause (the
1401/// system-model ADR, crate-hygiene B1, #2939).
1402///
1403/// Annotation hover must answer on a buffer that doesn't certify. There the
1404/// model's reading differs on three cases the checker rejects:
1405/// - a second `@cache`: the model reads the first, while hover reads the
1406///   hovered one
1407/// - `@cache` off `GET`: the model gives `None`
1408/// - fractional seconds: the model truncates
1409///
1410/// `None` when `maxAge` is missing or not a whole-second `Duration` literal
1411/// (the checker flags those).
1412fn cache_control_of(ann: &Annotation) -> Option<String> {
1413    let mut max_age_secs = None;
1414    let mut scope = "private";
1415    let mut immutable = false;
1416    for arg in &ann.args {
1417        match (arg.label.as_ref().map(|l| l.name.as_str()), &arg.value.kind) {
1418            (Some("maxAge"), ExprKind::DurationLit { millis, .. })
1419                if *millis > 0 && millis % 1000 == 0 =>
1420            {
1421                max_age_secs = Some(millis / 1000);
1422            }
1423            (Some("scope"), ExprKind::Ident(id)) if id.name == "public" => scope = "public",
1424            (Some("immutable"), ExprKind::BoolLit(b)) => immutable = *b,
1425            _ => {}
1426        }
1427    }
1428    let secs = max_age_secs?;
1429    let suffix = if immutable { ", immutable" } else { "" };
1430    Some(format!("{scope}, max-age={secs}{suffix}"))
1431}
1432
1433/// The formatted annotation in a code block, plus a prose description for the
1434/// closed handler-annotation set. `@cache`, `@limit` (v0.142) and `@raw` carry prose; any
1435/// other name (a typo the checker will flag) still hovers as its formatted form so
1436/// the surface is never silent.
1437fn render_handler_annotation_hover(
1438    ann: &Annotation,
1439    handler: &Handler,
1440    service_cap: Option<i64>,
1441) -> String {
1442    let sig = bynk_fmt::annotation_to_string(ann);
1443    if ann.name.name == "cache" {
1444        let emitted = match cache_control_of(ann) {
1445            Some(header) => format!("\n\nEmits `Cache-Control: {header}`."),
1446            None => String::new(),
1447        };
1448        return format!(
1449            "```bynk\n{sig}\n```\n\n\
1450             **`@cache`** — cache this `GET` read. A `GET` returning `Ok` (or a `Raw` body \
1451             of at most 1 MiB) already carries a synthesised weak `ETag`, and `RawTagged` \
1452             carries the handler's own; a matching `If-None-Match` is answered \
1453             `304 Not Modified`. `@cache` adds a `Cache-Control` freshness window on top.\n\n\
1454             - **`maxAge`** — the freshness window, a `Duration` (e.g. `5.minutes`), lowered to \
1455             `Cache-Control: max-age`.\n\
1456             - **`scope`** — `public` or `private` (default `private`; a shared cache stores the \
1457             response only when `public`).\n\
1458             - **`immutable`** — `true` promises the response at this URL never changes, so \
1459             caches do not revalidate it within `maxAge` (default `false`).{emitted}"
1460        );
1461    }
1462    // v0.142 (ADR 0165): `@limit` caps the request body size on a write route.
1463    if ann.name.name == "limit" {
1464        return format!(
1465            "```bynk\n{sig}\n```\n\n\
1466             **`@limit`** — cap the request body size on this `POST`/`PUT`/`PATCH` route. A \
1467             request whose body exceeds the `maxBody` byte ceiling is answered `413 Payload Too \
1468             Large`, synthesised before the body is read.\n\n\
1469             - **`maxBody`** — the maximum request body size in bytes, a positive `Int`."
1470        );
1471    }
1472    // #2858: `@json` picks how this route's response body writes `Option`.
1473    if ann.name.name == "json" {
1474        let mode = match handler.json_options() {
1475            Some(JsonOptions::Plain) => "`plain` — `Some(v)` is written `v`, `None` is `null`",
1476            Some(JsonOptions::Tagged) => {
1477                "`tagged` — `{\"kind\": \"Some\", \"value\": v}` / `{\"kind\": \"None\"}`"
1478            }
1479            None => "not a valid mode (`bynk.http.json_invalid_arg`)",
1480        };
1481        return format!(
1482            "```bynk\n{sig}\n```\n\n\
1483             **`@json`** — choose how this route's response body writes `Option`, overriding the \
1484             service's `json {{ }}` section. A Bynk client reads either form; plain JSON is what \
1485             `curl | jq` and other non-Bynk clients expect. `Option[Option[T]]` is refused in a \
1486             plain route (`bynk.json.nested_option_plain`).\n\n\
1487             - **`options`** — `tagged` (the default) or `plain`. This route: {mode}."
1488        );
1489    }
1490    // `@raw` takes the request body as the octets sent, under a declared media type.
1491    if ann.name.name == "raw" {
1492        let cap = match handler.limit_max_body().or(service_cap) {
1493            Some(bytes) => format!("{bytes} bytes (from `@limit` or the service `limits`)"),
1494            None => "none — a `@raw` route needs one (`bynk.http.raw_body_unbounded`)".to_string(),
1495        };
1496        let content_type = match handler.raw_content_type() {
1497            Some("*/*") => "any".to_string(),
1498            Some(ct) => format!("`{ct}`"),
1499            None => "—".to_string(),
1500        };
1501        return format!(
1502            "```bynk\n{sig}\n```\n\n\
1503             **`@raw`** — take this route's `body: Bytes` as the raw request body: the octets as \
1504             sent, with no JSON and no base64. Type it `Stream[Bytes]` instead to receive it as \
1505             it arrives, read once and counted against the cap as it is read. Any other \
1506             `Content-Type` is answered `415 Unsupported Media Type`.\n\n\
1507             - **`contentType`** — the media type accepted: {content_type}.\n\
1508             - **Effective body cap** — {cap}."
1509        );
1510    }
1511    // #3276: `@form` decodes the `body` record from a urlencoded form.
1512    if ann.name.name == "form" {
1513        let cap = match handler.limit_max_body().or(service_cap) {
1514            Some(bytes) => format!("{bytes} bytes (from `@limit` or the service `limits`)"),
1515            None => "none (add `@limit` or `limits { maxBody }` to bound it)".to_string(),
1516        };
1517        return format!(
1518            "```bynk\n{sig}\n```\n\n\
1519             **`@form`** — decode this route's `body` record from an \
1520             `application/x-www-form-urlencoded` form, with the same refinements, defaults and \
1521             `Option`s as a JSON body. Any other `Content-Type` is answered `415 Unsupported \
1522             Media Type`; a bad field is a `400` naming `body.<field>`.\n\n\
1523             - **Fields** — a `String`, `Int`, `Bool`, `Decimal`, an enum or a refined or opaque \
1524             type over one, optionally in an `Option` or a `List` (a repeated key). An unchecked \
1525             checkbox sends nothing, so give a `Bool` a default.\n\
1526             - **Empty values** — `name=` is absent for an `Option` or a non-`String` field, and `\"\"` \
1527             for a `String`.\n\
1528             - **Effective body cap** — {cap}."
1529        );
1530    }
1531    // #3276: `@multipart` decodes the `body` record from `multipart/form-data`.
1532    if ann.name.name == "multipart" {
1533        let cap = match handler.limit_max_body().or(service_cap) {
1534            Some(bytes) => format!("{bytes} bytes (from `@limit` or the service `limits`)"),
1535            None => "none — a `@multipart` route needs one (`bynk.http.multipart_body_unbounded`)"
1536                .to_string(),
1537        };
1538        return format!(
1539            "```bynk\n{sig}\n```\n\n\
1540             **`@multipart`** — decode this route's `body` record from a `multipart/form-data` \
1541             body, buffered whole under the body cap. Text parts follow the same rules as a \
1542             [`@form`] body; a part with a filename is a `File` (`filename`, `contentType`, \
1543             `bytes`), both client-controlled. Any other `Content-Type` is a `415`, a body \
1544             that is not multipart a `400` `MalformedForm`, and a part over `maxFile` (or more \
1545             than `maxParts`) a `413`.\n\n\
1546             - **Effective body cap** — {cap}."
1547        );
1548    }
1549    format!("```bynk\n{sig}\n```")
1550}
1551
1552/// True when `offset` falls within `span` (half-open, as hover offsets are).
1553fn span_covers(span: Span, offset: usize) -> bool {
1554    span.start <= offset && offset < span.end
1555}
1556
1557/// The span of the token immediately preceding the token that begins at
1558/// `name_span`, if that preceding token's source text is exactly `kw` — used to
1559/// locate a contextual keyword (`key`) that the AST records only by its effect,
1560/// not with a span of its own.
1561fn preceding_ident_span(
1562    tokens: &[bynk_syntax::lexer::Token],
1563    source: &str,
1564    name_span: Span,
1565    kw: &str,
1566) -> Option<Span> {
1567    let idx = tokens
1568        .iter()
1569        .position(|t| t.span.start == name_span.start)?;
1570    let prev = tokens.get(idx.checked_sub(1)?)?;
1571    (source.get(prev.span.start..prev.span.end) == Some(kw)).then_some(prev.span)
1572}
1573
1574/// A code-block field signature followed by the contextual keyword's one-line
1575/// doc from [`bynk_syntax::keywords::CONTEXTUAL_KEYWORDS`].
1576fn render_state_hover(sig: &str, contextual_kw: &str) -> String {
1577    let doc = bynk_syntax::keywords::CONTEXTUAL_KEYWORDS
1578        .iter()
1579        .find(|k| k.word == contextual_kw)
1580        .map(|k| k.meaning)
1581        .unwrap_or_default();
1582    format!("```bynk\n{sig}\n```\n\n{doc}")
1583}
1584
1585/// v0.122 (editor-currency slice 1): a hover summary for `self` under the
1586/// cursor — `self: <Type>`. `self` is a reserved keyword (never an `Ident`, so
1587/// it does not flow through `locals_nav`), but a `self` *use* is a typed
1588/// expression, so its type is in `expr_types` at the token's span. For a method
1589/// the type is the receiver's name; for an agent handler the checker gives
1590/// `self` a synthetic record type `__<Agent>Self` (to resolve `self.<key>`),
1591/// which is un-synthesised here to `<Agent>`. `None` when the cursor is not on
1592/// the `self` keyword or its type is unknown (no `expr_types` entry for it —
1593/// on a broken buffer ADR 0094's partial types usually still carry one; when
1594/// they don't, this degrades to the keyword doc).
1595pub fn describe_self_at(
1596    text: &str,
1597    offset: usize,
1598    expr_types: &[(Span, bynk_check::checker::TyId)],
1599    tys: &bynk_check::checker::Types,
1600) -> Option<String> {
1601    let tokens = tokenize(text).ok()?;
1602    let on_self = tokens.iter().any(|t| {
1603        t.span.start <= offset && offset < t.span.end && &text[t.span.start..t.span.end] == "self"
1604    });
1605    if !on_self {
1606        return None;
1607    }
1608    let ty = bynk_check::expr_types::type_at_offset(expr_types, offset, tys)?;
1609    let display = ty.display(tys);
1610    let name = display
1611        .strip_prefix("__")
1612        .and_then(|s| s.strip_suffix("Self"))
1613        .unwrap_or(&display);
1614    Some(format!("```bynk\nself: {name}\n```"))
1615}
1616
1617/// #2683, #2711, #3437: hover on the `within` of `e.within(d)`, the `race` of
1618/// `a.race(b)` or the `detach` of `e.detach()`, where the receiver is an `Effect`: its signature and what it
1619/// does and does not do. The kernel methods have no declaration to read a doc
1620/// from, so these are written here; the receiver's type keeps a user type's own
1621/// `within` or `race` method from being described as them.
1622pub fn describe_effect_method_at(
1623    text: &str,
1624    offset: usize,
1625    expr_types: &[(Span, bynk_check::checker::TyId)],
1626    tys: &bynk_check::checker::Types,
1627) -> Option<String> {
1628    let tokens = tokenize(text).ok()?;
1629    let tok = tokens.iter().find(|t| {
1630        t.span.start <= offset
1631            && offset < t.span.end
1632            && matches!(
1633                &text[t.span.start..t.span.end],
1634                "within" | "race" | "detach"
1635            )
1636    })?;
1637    let word = &text[tok.span.start..tok.span.end];
1638    let before = text[..tok.span.start].trim_end();
1639    let after = text[tok.span.end..].trim_start();
1640    if !before.ends_with('.') || !after.starts_with('(') {
1641        return None;
1642    }
1643    let dot = before.len() - 1;
1644    let recv = bynk_check::expr_types::type_at_offset(expr_types, dot.checked_sub(1)?, tys)?;
1645    if !matches!(&*tys.get(recv), bynk_check::checker::Ty::Effect(_)) {
1646        return None;
1647    }
1648    if word == "detach" {
1649        return Some(
1650            "```bynk\ndetach() -> Effect[()]\n```\n\n\
1651             Stops waiting for the effect: returns once the effect has been handed to the \
1652             runtime, not once it has finished. The effect is already running (an effect starts \
1653             where its expression is evaluated), so `detach` never starts or delays it.\n\n\
1654             **A failure is reported, never lost.** A fault goes to the platform's exception \
1655             path; an `Err` (when `T` is a `Result`) is logged as one structured record naming \
1656             the site and the error's type and variant, but not its payload. Detaching is \
1657             best-effort: it is not retried, and the platform may cut it short after the \
1658             response.\n\n\
1659             Only where an execution context exists, as `within`: not in an agent handler."
1660                .to_string(),
1661        );
1662    }
1663    if word == "race" {
1664        return Some(
1665            "```bynk\nrace(other: Effect[T]) -> Effect[T]\n```\n\n\
1666             Takes whichever of the two effects succeeds first. A side that faults does not \
1667             win while the other may still succeed; if both fault, the first fault in source \
1668             order is raised, with the other attached as `suppressed`. A same-instant tie goes \
1669             to the receiver.\n\n\
1670             **The loser is not cancelled.** It is handed to the platform's `waitUntil` and \
1671             runs to completion, so its side effects still happen: use `race` for idempotent \
1672             work such as a read, not a write. Use `FetchOptions.timeout` when work must \
1673             actually stop.\n\n\
1674             Only in a service handler's body (lambdas included): an agent handler or a \
1675             function has no execution context to hand the loser to."
1676                .to_string(),
1677        );
1678    }
1679    Some(
1680        "```bynk\nwithin(d: Duration) -> Effect[Result[T, TimedOut]]\n```\n\n\
1681         Bounds how long the effect may take. If it settles within `d` the result is `Ok`; \
1682         if `d` passes first it is `Err(TimedOut { after: d })` and the handler moves on.\n\n\
1683         **The effect is not cancelled.** It is handed to the platform's `waitUntil` and may \
1684         still complete after the handler has returned, so its side effects can still happen. \
1685         Use `FetchOptions.timeout` when the work must actually stop.\n\n\
1686         Only in a service handler's body (lambdas included): an agent handler or a function \
1687         has no execution context to hand the effect to."
1688            .to_string(),
1689    )
1690}
1691
1692/// #2839: hover on the `?` of an `Option` value. An `Option` is only liftable
1693/// by `?` inside a handler returning `HttpResult` (ADR 0177), so an `Option`
1694/// operand means `None` answers `404 NotFound`: the hover says so, and points
1695/// at `let … else` for any other status. A `?` on a `Result` is not described.
1696pub fn describe_question_at(
1697    text: &str,
1698    offset: usize,
1699    expr_types: &[(Span, bynk_check::checker::TyId)],
1700    tys: &bynk_check::checker::Types,
1701) -> Option<String> {
1702    let tokens = tokenize(text).ok()?;
1703    let tok = tokens.iter().find(|t| {
1704        t.span.start <= offset && offset < t.span.end && &text[t.span.start..t.span.end] == "?"
1705    })?;
1706    let before = text[..tok.span.start].trim_end();
1707    let operand =
1708        bynk_check::expr_types::type_at_offset(expr_types, before.len().checked_sub(1)?, tys)?;
1709    if !matches!(&*tys.get(operand), bynk_check::checker::Ty::Option(_)) {
1710        return None;
1711    }
1712    Some(
1713        "```bynk\n? : None → 404 NotFound\n```\n\n\
1714         On an `Option` in an `HttpResult` handler, `?` yields the value for `Some` and \
1715         answers `404 NotFound` for `None`. That is right for \"the thing you asked for is not \
1716         there\", but a missing or malformed request input is a `400`: write \
1717         `let Some(x) = e else { BadRequest(\"…\") }` to answer another status."
1718            .to_string(),
1719    )
1720}
1721
1722/// v0.123 (editor-currency slice 2, DECISION B): if the identifier at
1723/// `ident_span` is the member of an `Upper.member` name-receiver access
1724/// (`Clock.now`, `Email.of`), return the full `Recv.member` callee for
1725/// [`crate::signature_help::resolve_label`] to resolve to its signature — the
1726/// same resolution completion and signature help perform, no new index.
1727/// `None` for a bare identifier or a lowercase (value-receiver) method, which
1728/// `resolve_label` does not handle.
1729pub fn qualified_callee_at(text: &str, ident_span: Span) -> Option<String> {
1730    let (recv, _) = receiver_segment_at(text, ident_span)?;
1731    if !recv.chars().next()?.is_uppercase() {
1732        return None;
1733    }
1734    let member = text.get(ident_span.start..ident_span.end)?;
1735    Some(format!("{recv}.{member}"))
1736}
1737
1738/// Describe a symbol declared in the embedded first-party sources — the `bynk`
1739/// and `bynk.cloudflare` adapters and the `bynk.list`/`bynk.map`/`bynk.string`
1740/// stdlib. Hover and completion-doc resolution otherwise walk only the project's
1741/// files (`walk_bynk_files`), so stdlib/surface symbols had no surfaced signature
1742/// or doc; this is the fallback after the project scan. Any `---` doc block on a
1743/// first-party declaration rides along (via `describe_fn`/`describe_type`/…),
1744/// once the sources carry one.
1745pub fn describe_firstparty_symbol(name: &str) -> Option<String> {
1746    // The single first-party source list (`bynk-check::firstparty`), so a new
1747    // first-party commons is hoverable without a second edit here (#901).
1748    bynk_check::firstparty::FIRSTPARTY_SOURCES
1749        .iter()
1750        .find_map(|(unit, src)| {
1751            describe_symbol(src, name).map(|d| d + &firstparty_notes(unit, name))
1752        })
1753}
1754
1755/// Standard-library S3 (#1963): what hover adds about a first-party item's
1756/// stability: that it is experimental (no compatibility promise, and an
1757/// `[unstable] allow` to use), and that an enum is extensible (a `match` on it
1758/// needs a wildcard). Empty for a stable, closed item.
1759pub fn firstparty_notes(unit: &str, name: &str) -> String {
1760    let mut out = String::new();
1761    let path = format!("{unit}.{name}");
1762    if bynk_check::firstparty::stability_of(&path)
1763        == Some(bynk_check::firstparty::Stability::Experimental)
1764    {
1765        out.push_str(&format!(
1766            "\n\n**Experimental**: it may change or disappear in any release. To use it, add `\"{path}\"` to `[unstable] allow` in `bynk.toml`."
1767        ));
1768    }
1769    if bynk_check::firstparty::is_extensible(unit, name) {
1770        out.push_str(
1771            "\n\n**Extensible**: it may gain variants in a minor release, so a `match` on it needs a wildcard arm.",
1772        );
1773    }
1774    out
1775}
1776
1777/// Slice 6b: the `(unit name, name span)` of every `uses`/`consumes` target in
1778/// the source — the clickable ranges for document links. The link's target file
1779/// is resolved by the handler through the unit→source map (ADR 0095); this only
1780/// finds the spans, so it works on the live buffer regardless of the map.
1781pub fn unit_reference_spans(source: &str) -> Vec<(String, Span)> {
1782    let Ok(tokens) = tokenize(source) else {
1783        return Vec::new();
1784    };
1785    let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
1786        return Vec::new();
1787    };
1788    let mut out: Vec<(String, Span)> = Vec::new();
1789    // A suite links its target (the unit under test) plus any `uses` clauses,
1790    // mirroring the `uses`/`consumes` links on the other unit kinds (#609).
1791    let (uses, consumes): (&[UsesDecl], &[ConsumesDecl]) = match &unit {
1792        SourceUnit::Commons(c) => (&c.uses, &[]),
1793        SourceUnit::Context(c) => (&c.uses, &c.consumes),
1794        SourceUnit::Adapter(a) => (&a.uses, &a.consumes),
1795        SourceUnit::Suite(s) => {
1796            out.push((s.target.joined(), s.target.span));
1797            (&s.uses, &[])
1798        }
1799    };
1800    for u in uses {
1801        out.push((u.target.joined(), u.target.span));
1802    }
1803    for c in consumes {
1804        out.push((c.target.joined(), c.target.span));
1805    }
1806    out
1807}
1808
1809/// #1885: the qualified unit name under `offset`, when the cursor sits on the
1810/// file's own unit-header name or on a `uses`/`consumes` (or a suite's) target
1811/// path — the positions where hover shows a unit's module doc.
1812///
1813/// The match is on the name's byte range (`start..=end`), never on `Span`
1814/// equality, so it holds for a buffer re-parsed with `FileId::UNKNOWN`. Every
1815/// segment of a dotted path answers with the whole name: the cursor on
1816/// `model` in `uses compat.model` names `compat.model`, not a `model`.
1817pub fn unit_name_at(source: &str, offset: usize) -> Option<String> {
1818    let own = own_declaration_name(source);
1819    own.into_iter()
1820        .chain(unit_reference_spans(source))
1821        .find(|(_, span)| span.start <= offset && offset <= span.end)
1822        .map(|(name, _)| name)
1823}
1824
1825/// #1885: hover Markdown for the unit `name` — a fenced `<kind> <name>` line,
1826/// followed by its module doc when one of its files carries one.
1827///
1828/// `sources` are the texts to search: every file of the project the caller
1829/// can see (a multi-file context's doc may live in a sibling of the file the
1830/// cursor is in). A file that declares `name` as a `commons`, `context` or
1831/// `adapter` contributes; `suite` files never do, since a suite's own doc is
1832/// not its target's. At most one file of a unit carries a module doc
1833/// (`bynk.project.duplicate_module_doc`); should a broken project have more,
1834/// the first one in `sources` order is shown. `None` when no source declares
1835/// `name`.
1836pub fn describe_unit<'s>(sources: impl IntoIterator<Item = &'s str>, name: &str) -> Option<String> {
1837    let mut kind: Option<&'static str> = None;
1838    let mut doc: Option<String> = None;
1839    for source in sources {
1840        let Ok(tokens) = tokenize(source) else {
1841            continue;
1842        };
1843        let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
1844            continue;
1845        };
1846        if matches!(unit, SourceUnit::Suite(_)) || unit.name().joined() != name {
1847            continue;
1848        }
1849        kind.get_or_insert(unit.kind_name());
1850        if doc.is_none() {
1851            doc = unit.module_doc().map(str::to_string);
1852        }
1853        if doc.is_some() {
1854            break;
1855        }
1856    }
1857    let kind = kind?;
1858    let mut out = format!("```bynk\n{kind} {name}\n```\n");
1859    if let Some(doc) = doc {
1860        out.push('\n');
1861        out.push_str(&doc);
1862        out.push('\n');
1863    }
1864    Some(out)
1865}
1866
1867/// #1885: the module-doc hover for the unit name under `offset` in `text` (see
1868/// [`unit_name_at`]), resolved against `text` itself, then `others` (the
1869/// project's other files), then the embedded first-party sources (so
1870/// `consumes bynk.cloudflare` still names its unit). `None` when the cursor is
1871/// not on a unit name, or no source declares it.
1872pub fn describe_unit_at<'s>(
1873    text: &'s str,
1874    offset: usize,
1875    others: impl IntoIterator<Item = &'s str>,
1876) -> Option<String> {
1877    let name = unit_name_at(text, offset)?;
1878    let firstparty = bynk_check::firstparty::FIRSTPARTY_SOURCES
1879        .iter()
1880        .map(|(_, src)| *src);
1881    describe_unit(std::iter::once(text).chain(others).chain(firstparty), &name)
1882}
1883
1884/// #848: one intra-doc-link candidate scanned from doc-comment text — a
1885/// `[Name]` shortcut, a `` [`Name`] `` code-span-wrapped shortcut, or a
1886/// `[text][Name]` full reference. `span` is the byte range (into the text the
1887/// scanner was given) of the whole construct to rewrite when `name` resolves;
1888/// `display` is the link text to keep (`Name` for a shortcut, the code span
1889/// including backticks for the code-span form, `text` for a full reference).
1890#[derive(Debug, Clone, PartialEq, Eq)]
1891pub struct DocLinkCandidate {
1892    pub name: String,
1893    pub span: std::ops::Range<usize>,
1894    pub display: String,
1895}
1896
1897/// #848: is `s` shaped like a doc-link candidate name — a bare identifier, or
1898/// identifiers joined by `.` (an `Owner.member` or `unit.path.Name`
1899/// reference)? Every segment must be an identifier, so ordinary bracketed
1900/// prose (`[note]`, `[sic]`, `[e.g.]`) is never a candidate.
1901fn is_doc_link_name(s: &str) -> bool {
1902    fn is_ident(part: &str) -> bool {
1903        let mut chars = part.chars();
1904        matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
1905            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1906    }
1907    s.split('.').all(is_ident)
1908}
1909
1910/// #848: fenced-code-block byte ranges (paired ` ``` ` lines only — doc
1911/// comments are free text, not guaranteed well-formed Markdown, so a `~~~`
1912/// fence or an unterminated one just gets a best-effort range to end of text)
1913/// and the set of `[label]: destination`-shaped reference-definition labels,
1914/// both found in `text` line by line. [`scan_doc_link_candidates`] excludes
1915/// both: fenced content is never scanned for candidates, and a label with an
1916/// author-defined reference keeps its ordinary Markdown meaning instead of
1917/// becoming an intra-doc link.
1918fn doc_link_prepass(text: &str) -> (Vec<(usize, usize)>, std::collections::HashSet<String>) {
1919    let mut fenced = Vec::new();
1920    let mut defined = std::collections::HashSet::new();
1921    let mut in_fence = false;
1922    let mut fence_start = 0usize;
1923    let mut pos = 0usize;
1924    loop {
1925        let line_end = text[pos..]
1926            .find('\n')
1927            .map(|i| pos + i + 1)
1928            .unwrap_or(text.len());
1929        let line = &text[pos..line_end];
1930        let trimmed = line.trim_start();
1931        if trimmed.starts_with("```") {
1932            if in_fence {
1933                fenced.push((fence_start, line_end));
1934                in_fence = false;
1935            } else {
1936                fence_start = pos;
1937                in_fence = true;
1938            }
1939        } else if !in_fence {
1940            // A reference definition (`[label]: url`) — CommonMark allows up
1941            // to 3 leading spaces.
1942            let indent = line.len() - trimmed.len();
1943            if indent <= 3
1944                && let Some(rest) = trimmed.strip_prefix('[')
1945                && let Some(close) = rest.find(']')
1946            {
1947                let label = &rest[..close];
1948                if let Some(after_colon) = rest[close + 1..].strip_prefix(':')
1949                    && !label.is_empty()
1950                    && !after_colon.trim().is_empty()
1951                {
1952                    defined.insert(label.to_string());
1953                }
1954            }
1955        }
1956        if line_end >= text.len() {
1957            break;
1958        }
1959        pos = line_end;
1960    }
1961    if in_fence {
1962        fenced.push((fence_start, text.len()));
1963    }
1964    (fenced, defined)
1965}
1966
1967/// #848: scans the bracket construct starting at `text[start]` (which must be
1968/// `[`) for one of the recognised intra-doc-link forms. `None` when the
1969/// bracket isn't well-formed, is an explicit-URL link (`[text](url)`), is a
1970/// collapsed reference (`[text][]` — out of scope), names something that
1971/// isn't identifier-shaped, or names an author-defined reference label.
1972fn scan_bracket_candidate(
1973    text: &str,
1974    start: usize,
1975    defined: &std::collections::HashSet<String>,
1976) -> Option<DocLinkCandidate> {
1977    let bytes = text.as_bytes();
1978    debug_assert_eq!(bytes[start], b'[');
1979    // `` [`Name`] `` — a code-span-wrapped shortcut.
1980    if bytes.get(start + 1) == Some(&b'`') {
1981        let inner_start = start + 2;
1982        let close_tick = text[inner_start..].find('`')? + inner_start;
1983        if bytes.get(close_tick + 1) != Some(&b']') {
1984            return None;
1985        }
1986        let name = &text[inner_start..close_tick];
1987        if !is_doc_link_name(name) || defined.contains(name) {
1988            return None;
1989        }
1990        return Some(DocLinkCandidate {
1991            name: name.to_string(),
1992            span: start..close_tick + 2,
1993            display: text[start + 1..close_tick + 1].to_string(),
1994        });
1995    }
1996    let inner_start = start + 1;
1997    let close = text[inner_start..].find(']')? + inner_start;
1998    let inner = &text[inner_start..close];
1999    let after = close + 1;
2000    match bytes.get(after) {
2001        // `[text](url)` — an explicit URL, unchanged Markdown.
2002        Some(b'(') => None,
2003        // A reference-definition line reached mid-scan (pass 1 already
2004        // excludes true line-start ones) — never a candidate.
2005        Some(b':') => None,
2006        // `[text][label]` — a full reference.
2007        Some(b'[') => {
2008            let label_start = after + 1;
2009            let label_close = text[label_start..].find(']')? + label_start;
2010            let label = &text[label_start..label_close];
2011            // `[text][]` (collapsed reference) is out of scope this increment.
2012            if label.is_empty() || !is_doc_link_name(label) || defined.contains(label) {
2013                return None;
2014            }
2015            Some(DocLinkCandidate {
2016                name: label.to_string(),
2017                span: start..label_close + 1,
2018                display: inner.to_string(),
2019            })
2020        }
2021        // `[Name]` — a shortcut.
2022        _ => {
2023            if !is_doc_link_name(inner) || defined.contains(inner) {
2024                return None;
2025            }
2026            Some(DocLinkCandidate {
2027                name: inner.to_string(),
2028                span: start..after,
2029                display: inner.to_string(),
2030            })
2031        }
2032    }
2033}
2034
2035/// #848: every intra-doc-link candidate in `text`, in order. `[text](url)`,
2036/// an author-defined `[label]: url` reference, fenced-code-block content, and
2037/// non-identifier bracket content (`[note]`) are excluded — see
2038/// `scan_bracket_candidate` and `doc_link_prepass` (private below).
2039pub fn scan_doc_link_candidates(text: &str) -> Vec<DocLinkCandidate> {
2040    let (fenced, defined) = doc_link_prepass(text);
2041    let in_fenced = |i: usize| fenced.iter().any(|&(s, e)| i >= s && i < e);
2042    let bytes = text.as_bytes();
2043    let mut out = Vec::new();
2044    let mut i = 0usize;
2045    while i < bytes.len() {
2046        if bytes[i] != b'[' || in_fenced(i) {
2047            i += 1;
2048            continue;
2049        }
2050        match scan_bracket_candidate(text, i, &defined) {
2051            Some(cand) => {
2052                i = cand.span.end;
2053                out.push(cand);
2054            }
2055            None => i += 1,
2056        }
2057    }
2058    out
2059}
2060
2061/// #848: the `(candidate name, absolute source span)` of every intra-doc-link
2062/// candidate inside every `DocBlock` token in `source` — the clickable
2063/// ranges for doc-comment document links, mirroring [`unit_reference_spans`]'s
2064/// role for `uses`/`consumes` targets. Spans are computed against the raw,
2065/// unstripped doc-block body (`bynk_syntax::lexer::doc_block_body_range`),
2066/// not the common-indent-stripped `doc_block_content` text — that stripping
2067/// is not offset-preserving, so a span-based caller must avoid it. Only
2068/// tokenizes (not a full parse), so links still surface even when the rest of
2069/// the file has a parse error elsewhere, as long as tokenization succeeds.
2070pub fn doc_link_spans(source: &str) -> Vec<(String, Span)> {
2071    doc_link_spans_attached(source)
2072        .into_iter()
2073        .map(|l| (l.name, l.span))
2074        .collect()
2075}
2076
2077/// #2454: one intra-doc-link candidate with the declaration its doc comment
2078/// is attached to. `attached` is the byte offset of that declaration's name
2079/// (the first identifier after the doc comment) — the key a resolver matches
2080/// against an index definition site — or `None` when no identifier follows.
2081#[derive(Debug, Clone, PartialEq, Eq)]
2082pub struct DocLinkSpan {
2083    pub name: String,
2084    pub span: Span,
2085    pub attached: Option<usize>,
2086}
2087
2088/// #2454: [`doc_link_spans`] plus the declaration each doc block precedes.
2089pub fn doc_link_spans_attached(source: &str) -> Vec<DocLinkSpan> {
2090    let Ok(tokens) = tokenize(source) else {
2091        return Vec::new();
2092    };
2093    let mut out = Vec::new();
2094    for (i, t) in tokens.iter().enumerate() {
2095        // #1888: a `--|` doc line links too, one line at a time.
2096        let range = match t.kind {
2097            bynk_syntax::lexer::TokenKind::DocBlock => {
2098                bynk_syntax::lexer::doc_block_body_range(source, t.span)
2099            }
2100            bynk_syntax::lexer::TokenKind::DocLine => {
2101                Some(bynk_syntax::lexer::doc_line_text_range(source, t.span))
2102            }
2103            _ => None,
2104        };
2105        let Some(range) = range else {
2106            continue;
2107        };
2108        // #2569: a method `fn T.m(..)` is defined (and indexed) at `m`, so
2109        // that is where its doc attaches — the panel's offset is its entry
2110        // span's, which is the name.
2111        let attached = tokens[i + 1..]
2112            .iter()
2113            .position(|n| n.kind == bynk_syntax::lexer::TokenKind::Ident)
2114            .map(|p| {
2115                let rest = &tokens[i + 1 + p..];
2116                match rest {
2117                    [_, dot, name, ..]
2118                        if dot.kind == bynk_syntax::lexer::TokenKind::Dot
2119                            && name.kind == bynk_syntax::lexer::TokenKind::Ident
2120                            && p > 0
2121                            && tokens[i + p].kind == bynk_syntax::lexer::TokenKind::Fn =>
2122                    {
2123                        name.span.start
2124                    }
2125                    _ => rest[0].span.start,
2126                }
2127            });
2128        for cand in scan_doc_link_candidates(&source[range.clone()]) {
2129            out.push(DocLinkSpan {
2130                name: cand.name,
2131                span: Span::new(range.start + cand.span.start, range.start + cand.span.end),
2132                attached,
2133            });
2134        }
2135    }
2136    out
2137}
2138
2139/// #2454: the unit whose scope a file's doc links resolve in — its own
2140/// declared name, or a suite's *target* unit (a suite declares no unit of
2141/// its own, so [`own_declaration_name`] is `None` for it).
2142pub fn doc_link_unit(source: &str) -> Option<String> {
2143    let tokens = tokenize(source).ok()?;
2144    let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
2145        return None;
2146    };
2147    Some(unit.name().joined())
2148}
2149
2150/// #2458: where a doc comment's cursor sits inside an unfinished `[…` link.
2151#[derive(Debug, Clone, PartialEq, Eq)]
2152pub struct DocLinkCompletionContext {
2153    /// The `Owner` of an `[Owner.` prefix, when the cursor is past a dot.
2154    pub owner: Option<String>,
2155    /// The identifier text typed so far (after the `[` or the last `.`).
2156    pub partial: String,
2157    /// Offset the completion replaces from (`cursor - partial.len()`).
2158    pub replace_start: usize,
2159    /// Offset the completion replaces to: the cursor, extended over any
2160    /// identifier characters that follow it (`[Rat|eView]`), so accepting an
2161    /// item replaces the whole word rather than duplicating its tail.
2162    pub replace_end: usize,
2163    /// Whether a `]` already follows the replaced word, so the item need not add one.
2164    pub closed: bool,
2165    /// The byte offset of the name of the declaration this doc block is
2166    /// attached to (as `DocLinkSpan::attached`), when one follows.
2167    pub attached: Option<usize>,
2168}
2169
2170/// #2458: the doc-link completion context at `offset`, or `None` when the
2171/// cursor is not inside a `---` / `--|` doc comment (or is in a fenced code
2172/// block, or after a `[` already closed or broken by a non-identifier
2173/// character). This is the strict gate for the server-wide `[` trigger: code
2174/// outside doc ranges never yields a context. Tokenizes only; `None` if the
2175/// source does not tokenize.
2176pub fn doc_link_context(source: &str, offset: usize) -> Option<DocLinkCompletionContext> {
2177    let tokens = tokenize(source).ok()?;
2178    let (range, attached) = tokens.iter().enumerate().find_map(|(i, t)| {
2179        let range = match t.kind {
2180            bynk_syntax::lexer::TokenKind::DocBlock => {
2181                bynk_syntax::lexer::doc_block_body_range(source, t.span)
2182            }
2183            bynk_syntax::lexer::TokenKind::DocLine => {
2184                Some(bynk_syntax::lexer::doc_line_text_range(source, t.span))
2185            }
2186            _ => None,
2187        }?;
2188        (range.start <= offset && offset <= range.end).then(|| {
2189            let attached = tokens[i + 1..]
2190                .iter()
2191                .find(|n| n.kind == bynk_syntax::lexer::TokenKind::Ident)
2192                .map(|n| n.span.start);
2193            (range, attached)
2194        })
2195    })?;
2196    let body = &source[range.start..range.end];
2197    let (fenced, _) = doc_link_prepass(body);
2198    let rel = offset - range.start;
2199    if fenced.iter().any(|&(s, e)| rel >= s && rel < e) {
2200        return None;
2201    }
2202    let before = &body[..rel];
2203    let line_start = before.rfind('\n').map_or(0, |i| i + 1);
2204    let open = before[line_start..].rfind('[')? + line_start;
2205    let typed = &before[open + 1..];
2206    if !typed
2207        .chars()
2208        .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
2209    {
2210        return None;
2211    }
2212    let (owner, partial) = match typed.rfind('.') {
2213        Some(i) if i > 0 => (Some(typed[..i].to_string()), &typed[i + 1..]),
2214        Some(_) => return None,
2215        None => (None, typed),
2216    };
2217    let tail = source[offset..range.end]
2218        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
2219        .unwrap_or(range.end - offset);
2220    let replace_end = offset + tail;
2221    Some(DocLinkCompletionContext {
2222        owner,
2223        partial: partial.to_string(),
2224        replace_start: offset - partial.len(),
2225        replace_end,
2226        closed: source[replace_end..].starts_with(']'),
2227        attached,
2228    })
2229}
2230
2231/// #302: the source's own declared qualified name and its span — the
2232/// rewrite target when the file backing this unit is renamed. `None` for a
2233/// `suite` (its `SourceUnit::name()` is its *target*'s name, not one of its
2234/// own; nothing else addresses a suite by name) or on a parse bail.
2235pub fn own_declaration_name(source: &str) -> Option<(String, Span)> {
2236    let tokens = tokenize(source).ok()?;
2237    let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
2238        return None;
2239    };
2240    if matches!(unit, SourceUnit::Suite(_)) {
2241        return None;
2242    }
2243    let name = unit.name();
2244    Some((name.joined(), name.span))
2245}
2246
2247fn describe_item(item: &CommonsItem, name: &str) -> Option<String> {
2248    match item {
2249        CommonsItem::Type(t) if t.name.name == name => Some(describe_type(t)),
2250        // v0.166 (#616): a bare key names a *free* function. A method's identity
2251        // is its compound `"Type.method"` key (below); matching one by its bare
2252        // method name answered with whichever type declared it first, so
2253        // `g.bump()` and even `fn Gauge.bump`'s own declaration rendered
2254        // `Counter.bump`. `signature_help::resolve_label` guards its free-fn path
2255        // the same way.
2256        CommonsItem::Fn(f) if matches!(f.name, FnName::Free(_)) && f.name.ident().name == name => {
2257            Some(describe_fn(f))
2258        }
2259        CommonsItem::Capability(c) if c.name.name == name => Some(describe_capability(c)),
2260        CommonsItem::Service(s) if s.name.name == name => Some(describe_service(s)),
2261        CommonsItem::Agent(a) if a.name.name == name => Some(describe_agent(a)),
2262        CommonsItem::Provider(p) if p.provider_name.name == name => Some(describe_provider(p)),
2263        // v0.166 (#616): an actor, keyed by its plain name — the `Actor` index
2264        // kind ADR 0190 filed as the clearest evidence that the renderer, not the
2265        // ladder, is where these were missing. `by u: User` resolved here and
2266        // rendered nothing.
2267        CommonsItem::Actor(a) if a.name.name == name => Some(describe_actor(a)),
2268        // message-bundles slice 1 (#859): a messages block, keyed by its tag —
2269        // the same top-level, plain-name convention as Capability/Service/
2270        // Agent above.
2271        CommonsItem::Messages(m) if m.tag == name => Some(describe_messages(m)),
2272        // #1883: an asset's hover and docs.
2273        CommonsItem::Asset(a) if a.name.name == name => Some(describe_asset(a)),
2274        // #2387, slice 1: an embed's hover and docs.
2275        CommonsItem::Embed(e) if e.name.name == name => Some(describe_embed(e)),
2276        // #2617: a constant's hover and docs.
2277        CommonsItem::Const(c) if c.name.name == name => Some(describe_const(c)),
2278        // #972 (Events slice 3a): an event, keyed by its plain name — the same
2279        // top-level convention as the arms above. Reuses `describe_type` via
2280        // the synthetic `TypeDecl` `as_type_decl` already builds for every
2281        // other event-as-type consumer (exports/consumes/construction).
2282        CommonsItem::Event(e) if e.name.name == name => Some(describe_event(e)),
2283        // #611 (gap B): a record field, keyed `"Type.field"` by the index — the
2284        // checker records construction labels and field accesses as `Field` refs,
2285        // so hover resolves the key but had no arm to render it and fell through
2286        // to the locals path, which name-matches in scope (a `title:` label bound
2287        // to a same-named handler param). Top-level names carry no `.`, so the
2288        // compound key can only match here.
2289        CommonsItem::Type(t) => {
2290            let (owner, field) = name.rsplit_once('.')?;
2291            if t.name.name != owner {
2292                return None;
2293            }
2294            let TypeBody::Record(r) = &t.body else {
2295                return None;
2296            };
2297            r.fields
2298                .iter()
2299                .find(|f| f.name.name == field)
2300                .map(|f| describe_record_field(t, f))
2301        }
2302        // #972 (Events slice 3a): an event field, keyed `"Event.field"` —
2303        // mirrors the `CommonsItem::Type` arm above via the same synthetic
2304        // `TypeDecl`, so a defaulted event field's hover also renders its
2305        // `= <expr>`.
2306        CommonsItem::Event(e) => {
2307            let (owner, field) = name.rsplit_once('.')?;
2308            if e.name.name != owner {
2309                return None;
2310            }
2311            let synthetic = e.as_type_decl();
2312            e.body
2313                .fields
2314                .iter()
2315                .find(|f| f.name.name == field)
2316                .map(|f| describe_record_field(&synthetic, f))
2317        }
2318        // v0.166 (#616): a method, keyed `"Type.method"` (ADR 0069). `display()`
2319        // renders exactly that key, so the compound name matches the one method
2320        // it names — the type prefix is what disambiguates `Counter.bump` from
2321        // `Gauge.bump`.
2322        CommonsItem::Fn(f) => (f.name.display() == name).then(|| describe_fn(f)),
2323        // v0.166 (#616): a capability operation, keyed `"Cap.op"` (ADR 0069).
2324        CommonsItem::Capability(c) => {
2325            let (owner, op) = name.rsplit_once('.')?;
2326            if c.name.name != owner {
2327                return None;
2328            }
2329            c.ops
2330                .iter()
2331                .find(|o| o.name.name == op)
2332                .map(|o| describe_capability_op(c, o))
2333        }
2334        // #304: an agent handler, keyed `"Agent.handler"` — the checker
2335        // records a dispatch call (`agentInstance.handler(...)`) as this
2336        // compound key, mirroring the method/field/op convention above.
2337        CommonsItem::Agent(a) => {
2338            let (owner, handler) = name.rsplit_once('.')?;
2339            if a.name.name != owner {
2340                return None;
2341            }
2342            a.handlers
2343                .iter()
2344                .find(|h| h.method_name.as_ref().is_some_and(|n| n.name == handler))
2345                .map(|h| describe_agent_handler(a, h, handler))
2346        }
2347        _ => None,
2348    }
2349}
2350
2351/// v0.166 (#616): an actor as declared — the `auth` scheme with its config, the
2352/// `identity` type, or the refinement form's base and claim predicate.
2353/// Mirrors `bynk-fmt`'s `format_actor`, as [`describe_agent`] mirrors an agent.
2354///
2355/// #847: `pub(crate)` so the documentation-view aggregator ([`crate::documentation`])
2356/// renders each declaration through the *same* signature+doc assembly hover uses,
2357/// rather than a parallel renderer that could drift from it.
2358pub(crate) fn describe_actor(a: &ActorDecl) -> String {
2359    let mut out = String::from("```bynk\n");
2360    match &a.refinement {
2361        // `actor Admin = User where hasClaim("admin")` (ADR 0091).
2362        Some(r) => out.push_str(&format!(
2363            "actor {} = {} where {}",
2364            a.name.name,
2365            r.base.name,
2366            bynk_fmt::expr_to_string(&r.predicate)
2367        )),
2368        None => {
2369            // An absent `auth` is the `None` scheme, which is how it parses.
2370            let auth = a.auth.as_ref().map_or("None", |i| i.name.as_str());
2371            out.push_str(&format!("actor {} {{ auth = {auth}", a.name.name));
2372            if !a.auth_config.is_empty() {
2373                let args: Vec<String> = a
2374                    .auth_config
2375                    .iter()
2376                    .map(|arg| match &arg.value {
2377                        // The parser resolves escapes at lex time, so the stored
2378                        // value is *unescaped* — re-escape it through the
2379                        // formatter's own escaper, or a `"` in the config renders
2380                        // as invalid Bynk inside the fence below.
2381                        SchemeArgValue::Str(s) => {
2382                            format!("{} = \"{}\"", arg.key.name, bynk_fmt::escape_string(s))
2383                        }
2384                        SchemeArgValue::Int(n) => format!("{} = {n}", arg.key.name),
2385                        SchemeArgValue::Duration { value, unit, .. } => {
2386                            format!("{} = {value}.{}", arg.key.name, unit.name())
2387                        }
2388                        SchemeArgValue::Ident(id) => format!("{} = {id}", arg.key.name),
2389                    })
2390                    .collect();
2391                out.push_str(&format!("({})", args.join(", ")));
2392            }
2393            if let Some(id) = &a.identity {
2394                out.push_str(&format!(", identity = {}", type_ref_str(id)));
2395            }
2396            out.push_str(" }");
2397        }
2398    }
2399    out.push_str("\n```\n");
2400    if let Some(doc) = &a.documentation {
2401        out.push('\n');
2402        out.push_str(doc);
2403        out.push('\n');
2404    }
2405    out
2406}
2407
2408/// #926: an op's own `[T, …]` type parameters, rendered for hover — `""` when
2409/// the op is non-generic. Shared by [`describe_capability_op`] and
2410/// [`describe_capability`] so the two signature renderings can't drift.
2411fn capability_op_type_params_str(op: &CapabilityOp) -> String {
2412    if op.type_params.is_empty() {
2413        return String::new();
2414    }
2415    let names: Vec<&str> = op
2416        .type_params
2417        .iter()
2418        .map(|tp| tp.name.name.as_str())
2419        .collect();
2420    format!("[{}]", names.join(", "))
2421}
2422
2423/// v0.166 (#616): a capability operation as declared, attributed to the
2424/// capability that owns it. Mirrors how [`describe_capability`] renders the same
2425/// op within the capability body, as [`describe_record_field`] does for a field.
2426pub(crate) fn describe_capability_op(c: &CapabilityDecl, op: &CapabilityOp) -> String {
2427    let params: Vec<String> = op
2428        .params
2429        .iter()
2430        .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2431        .collect();
2432    let mut out = format!(
2433        "```bynk\nfn {}{}({}) -> {}\n```\n\nAn operation of capability `{}`.\n",
2434        op.name.name,
2435        capability_op_type_params_str(op),
2436        params.join(", "),
2437        type_ref_str(&op.return_type),
2438        c.name.name
2439    );
2440    // #3458: a typed read decodes the provider's reply at the call site, so
2441    // say what a reply that does not decode means: the policy the operation declares.
2442    if let Some(policy) = bynk_check::checker::codable::typed_read_policy(op) {
2443        out.push_str(match policy {
2444            bynk_check::checker::codable::ReplyPolicy::Miss => {
2445                "\nA typed read: the type argument is explicit, and a reply that does not decode is a miss (the call returns `None` and a warning is logged).\n"
2446            }
2447            bynk_check::checker::codable::ReplyPolicy::Fault => {
2448                "\nA typed read: the type argument is explicit, and a reply that does not decode faults.\n"
2449            }
2450        });
2451    }
2452    if let Some(doc) = &op.documentation {
2453        out.push('\n');
2454        out.push_str(doc);
2455        out.push('\n');
2456    }
2457    out
2458}
2459
2460/// #304: an agent handler as declared, attributed to the agent that owns it —
2461/// its dispatch name, params, and return type. Mirrors [`describe_capability_op`].
2462pub(crate) fn describe_agent_handler(a: &AgentDecl, h: &Handler, handler_name: &str) -> String {
2463    let params: Vec<String> = h
2464        .params
2465        .iter()
2466        .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2467        .collect();
2468    let mut out = format!(
2469        "```bynk\nfn {}({}) -> {}\n```\n\nA handler of agent `{}`.\n",
2470        handler_name,
2471        params.join(", "),
2472        type_ref_str(&h.return_type),
2473        a.name.name
2474    );
2475    if let Some(doc) = &h.documentation {
2476        out.push('\n');
2477        out.push_str(doc);
2478        out.push('\n');
2479    }
2480    out
2481}
2482
2483/// #847: a service handler as declared, attributed to the service that owns it —
2484/// its route/protocol (`on GET("/x")`, `on call`, …) with the typed params and
2485/// return type. The documentation-view counterpart to [`describe_agent_handler`]:
2486/// a service handler has no compound index key (its route, not a dispatch name,
2487/// identifies it — see `bynk-lsp/src/sequence_request.rs`), so hover never
2488/// describes one on its own; the doc page is the first surface that renders each
2489/// individually, and it does so through the same fenced-signature + doc-prose
2490/// shape every other `describe_*` uses.
2491pub(crate) fn describe_service_handler(s: &ServiceDecl, h: &Handler) -> String {
2492    let params: Vec<String> = h
2493        .params
2494        .iter()
2495        .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2496        .collect();
2497    let mut out = format!(
2498        "```bynk\n{}({}) -> {}\n```\n\nA handler of service `{}`.\n",
2499        handler_line(h),
2500        params.join(", "),
2501        type_ref_str(&h.return_type),
2502        s.name.name
2503    );
2504    if let Some(doc) = &h.documentation {
2505        out.push('\n');
2506        out.push_str(doc);
2507        out.push('\n');
2508    }
2509    out
2510}
2511
2512/// #611: a record field as declared — its type and any `where` refinement —
2513/// attributed to the record that owns it. Mirrors how [`describe_type`] renders
2514/// the same field within the record body.
2515///
2516/// #1888: a documented field shows its own doc in place of the generic
2517/// "A field of `T`." line.
2518pub(crate) fn describe_record_field(t: &TypeDecl, f: &RecordField) -> String {
2519    let mut sig = format!("{}: {}", f.name.name, type_ref_str(&f.type_ref));
2520    if let Some(r) = &f.refinement {
2521        sig.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2522    }
2523    // #972 (Events slice 3a): render a field default the same way the
2524    // formatter does — `= <expr>` — so a subscriber-visible default is not
2525    // silently dropped from hover.
2526    if let Some(init) = &f.init {
2527        sig.push_str(&format!(" = {}", bynk_fmt::expr_to_string(init)));
2528    }
2529    format!(
2530        "```bynk\n{sig}\n```\n\n{}",
2531        member_prose(&f.documentation, || format!(
2532            "A field of `{}`.",
2533            t.name.name
2534        ))
2535    )
2536}
2537
2538/// #1888: a member's doc, trailing whitespace trimmed, or `fallback` when it
2539/// has none.
2540fn member_prose(doc: &Option<Doc>, fallback: impl FnOnce() -> String) -> String {
2541    match doc {
2542        Some(d) => d.trim_end().to_string(),
2543        None => fallback(),
2544    }
2545}
2546
2547/// #1888: a sum variant as declared, `| Name(field: Type, …)`, attributed to
2548/// its sum unless it carries its own doc, which shows in its place. A payload
2549/// field's doc follows, one line of the list per documented field.
2550pub(crate) fn describe_variant(t: &TypeDecl, v: &Variant) -> String {
2551    let mut sig = format!("| {}", v.name.name);
2552    if !v.payload.is_empty() {
2553        let parts: Vec<String> = v
2554            .payload
2555            .iter()
2556            .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2557            .collect();
2558        sig.push_str(&format!("({})", parts.join(", ")));
2559    }
2560    let mut out = format!(
2561        "```bynk\n{sig}\n```\n\n{}",
2562        member_prose(&v.documentation, || format!(
2563            "A variant of `{}`.",
2564            t.name.name
2565        ))
2566    );
2567    for p in &v.payload {
2568        if let Some(doc) = &p.documentation {
2569            out.push_str(&format!("\n\n`{}`: {}", p.name.name, doc.trim_end()));
2570        }
2571    }
2572    out
2573}
2574
2575/// #1888: one payload field of a sum variant, attributed to its variant
2576/// unless it carries its own doc.
2577pub(crate) fn describe_variant_field(t: &TypeDecl, v: &Variant, p: &VariantField) -> String {
2578    format!(
2579        "```bynk\n{}: {}\n```\n\n{}",
2580        p.name.name,
2581        type_ref_str(&p.type_ref),
2582        member_prose(&p.documentation, || format!(
2583            "A field of `{}.{}`.",
2584            t.name.name, v.name.name
2585        ))
2586    )
2587}
2588
2589/// #1888: every sum variant declared in `source`'s unit, with its sum.
2590fn with_sum_variants<R>(
2591    source: &str,
2592    mut f: impl FnMut(&TypeDecl, &Variant) -> Option<R>,
2593) -> Option<R> {
2594    let tokens = tokenize(source).ok()?;
2595    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
2596    let items: &[CommonsItem] = match unit.as_ref()? {
2597        SourceUnit::Commons(c) => &c.items,
2598        SourceUnit::Context(c) => &c.items,
2599        SourceUnit::Adapter(a) => &a.items,
2600        SourceUnit::Suite(_) => &[],
2601    };
2602    for item in items {
2603        if let CommonsItem::Type(t) = item
2604            && let TypeBody::Sum(s) = &t.body
2605        {
2606            for v in &s.variants {
2607                if let Some(r) = f(t, v) {
2608                    return Some(r);
2609                }
2610            }
2611        }
2612    }
2613    None
2614}
2615
2616/// #1888: the hover for a sum variant named by a qualified key,
2617/// `"Shape.Circle"`, declared in `source`; `None` when no sum there has it.
2618pub fn describe_variant_key(source: &str, key: &str) -> Option<String> {
2619    let (owner, name) = key.rsplit_once('.')?;
2620    with_sum_variants(source, |t, v| {
2621        (t.name.name == owner && v.name.name == name).then(|| describe_variant(t, v))
2622    })
2623}
2624
2625/// #1888: the hover for a sum variant named bare, as a pattern or a
2626/// constructor names it (`Circle(r)`), when exactly one sum in `source`
2627/// declares a variant of that name; `None` otherwise, so an ambiguous name
2628/// answers nothing rather than the wrong variant.
2629pub fn describe_variant_named(source: &str, name: &str) -> Option<String> {
2630    let mut found: Vec<String> = Vec::new();
2631    with_sum_variants::<()>(source, |t, v| {
2632        if v.name.name == name {
2633            found.push(describe_variant(t, v));
2634        }
2635        None
2636    });
2637    (found.len() == 1).then(|| found.remove(0))
2638}
2639
2640pub(crate) fn describe_type(t: &TypeDecl) -> String {
2641    let mut out = String::new();
2642    out.push_str("```bynk\n");
2643    // v0.157 (ADR 0183): render `[A, B]` type parameters on a generic type.
2644    let params = if t.type_params.is_empty() {
2645        String::new()
2646    } else {
2647        let names: Vec<String> = t
2648            .type_params
2649            .iter()
2650            .map(|tp| bound_str(&tp.name.name, &tp.bounds))
2651            .collect();
2652        format!("[{}]", names.join(", "))
2653    };
2654    // #2618: the unit-private modifier, as written.
2655    if t.private.is_some() {
2656        out.push_str("private ");
2657    }
2658    out.push_str(&format!("type {}{} = ", t.name.name, params));
2659    match &t.body {
2660        // v0.123 (slice 2): render the refined/opaque `where` predicate (was
2661        // collapsed to the bare base) via the formatter's own renderer.
2662        TypeBody::Refined {
2663            base, refinement, ..
2664        } => {
2665            out.push_str(base.name());
2666            if let Some(r) = refinement {
2667                out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2668            }
2669        }
2670        TypeBody::Opaque {
2671            base, refinement, ..
2672        } => {
2673            out.push_str(&format!("opaque {}", base.name()));
2674            if let Some(r) = refinement {
2675                out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2676            }
2677        }
2678        // Record fields, one per line (was collapsed to `record`).
2679        TypeBody::Record(r) => {
2680            if r.fields.is_empty() {
2681                out.push_str("{}");
2682            } else {
2683                out.push_str("{\n");
2684                for f in &r.fields {
2685                    out.push_str(&format!("\t{}: {}", f.name.name, type_ref_str(&f.type_ref)));
2686                    if let Some(r) = &f.refinement {
2687                        out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2688                    }
2689                    // #972 (Events slice 3a): an event field's default,
2690                    // reachable here via `EventDecl::as_type_decl`'s
2691                    // synthetic `TypeDecl`.
2692                    if let Some(init) = &f.init {
2693                        out.push_str(&format!(" = {}", bynk_fmt::expr_to_string(init)));
2694                    }
2695                    out.push_str(",\n");
2696                }
2697                out.push('}');
2698            }
2699        }
2700        // Sum variants, with payloads (was collapsed to `sum`).
2701        TypeBody::Sum(s) => {
2702            out.push_str("enum {\n");
2703            for v in &s.variants {
2704                out.push_str(&format!("\t{}", v.name.name));
2705                if !v.payload.is_empty() {
2706                    let parts: Vec<String> = v
2707                        .payload
2708                        .iter()
2709                        .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2710                        .collect();
2711                    out.push_str(&format!("({})", parts.join(", ")));
2712                }
2713                out.push_str(",\n");
2714            }
2715            out.push('}');
2716        }
2717    }
2718    // Constrained generics slice 1: the `derives` clause, after the body.
2719    if !t.derives.is_empty() {
2720        let names: Vec<&str> = t.derives.iter().map(|d| d.name.as_str()).collect();
2721        out.push_str(&format!(" derives {}", names.join(" + ")));
2722    }
2723    out.push_str("\n```\n");
2724    if let Some(doc) = &t.documentation {
2725        out.push('\n');
2726        out.push_str(doc);
2727        out.push('\n');
2728    }
2729    out
2730}
2731
2732/// Events slice 3b (#978): additively render an event's `@schema(N)` (or any
2733/// future event annotation) into its hover, the same rendering
2734/// `store_field_hover` already uses. `describe_type`'s signature is shared
2735/// with every ordinary type's hover, so this post-processes its output for
2736/// the one synthetic-`TypeDecl` caller that has annotations to show, rather
2737/// than widening that signature. A no-op when the event declares none —
2738/// absent-annotation hover stays byte-identical to before this slice.
2739fn describe_event(e: &EventDecl) -> String {
2740    let base = describe_type(&e.as_type_decl());
2741    if e.annotations.is_empty() {
2742        return base;
2743    }
2744    let annotations: String = e
2745        .annotations
2746        .iter()
2747        .map(|a| format!(" {}", bynk_fmt::annotation_to_string(a)))
2748        .collect();
2749    let from = format!("type {} = ", e.name.name);
2750    let to = format!("type {}{annotations} = ", e.name.name);
2751    base.replacen(&from, &to, 1)
2752}
2753
2754/// `[T: Eq, U]`, or empty for a non-generic function: the declared bounds, so
2755/// hover shows what a caller must satisfy (constrained generics slice 0).
2756pub(crate) fn fn_type_params_str(f: &FnDecl) -> String {
2757    if f.type_params.is_empty() {
2758        return String::new();
2759    }
2760    let ps: Vec<String> = f
2761        .type_params
2762        .iter()
2763        .map(|tp| bound_str(&tp.name.name, &tp.bounds))
2764        .collect();
2765    format!("[{}]", ps.join(", "))
2766}
2767
2768/// #2868: ` given Logger, Orders`, or empty for a function with no `given`. It
2769/// follows the return type, ahead of any `where`, as in the source.
2770pub(crate) fn fn_given_str(f: &FnDecl) -> String {
2771    if f.given.is_empty() {
2772        return String::new();
2773    }
2774    let names: Vec<String> = f.given.iter().map(|g| g.display_name()).collect();
2775    format!(" given {}", names.join(", "))
2776}
2777
2778/// ` where A: Eq`, or empty without a `where` clause.
2779pub(crate) fn fn_where_str(f: &FnDecl) -> String {
2780    if f.where_bounds.is_empty() {
2781        return String::new();
2782    }
2783    let ps: Vec<String> = f
2784        .where_bounds
2785        .iter()
2786        .map(|wb| bound_str(&wb.param.name, &wb.bounds))
2787        .collect();
2788    format!(" where {}", ps.join(", "))
2789}
2790
2791fn bound_str(name: &str, bounds: &[Ident]) -> String {
2792    if bounds.is_empty() {
2793        return name.to_string();
2794    }
2795    let names: Vec<&str> = bounds.iter().map(|b| b.name.as_str()).collect();
2796    format!("{name}: {}", names.join(" + "))
2797}
2798
2799pub(crate) fn describe_fn(f: &FnDecl) -> String {
2800    let mut out = String::new();
2801    out.push_str("```bynk\n");
2802    // #2618: the unit-private modifier, as written.
2803    if f.private.is_some() {
2804        out.push_str("private ");
2805    }
2806    out.push_str("fn ");
2807    out.push_str(&f.name.display());
2808    out.push_str(&fn_type_params_str(f));
2809    out.push('(');
2810    let mut parts: Vec<String> = Vec::new();
2811    if f.has_self {
2812        parts.push("self".into());
2813    }
2814    for p in &f.params {
2815        parts.push(format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)));
2816    }
2817    out.push_str(&parts.join(", "));
2818    out.push_str(") -> ");
2819    out.push_str(&type_ref_str(&f.return_type));
2820    out.push_str(&fn_given_str(f));
2821    out.push_str(&fn_where_str(f));
2822    // v0.123 (slice 2): the contract clauses (v0.115), beneath the signature —
2823    // rendered through the formatter's own predicate renderer.
2824    for c in &f.requires {
2825        out.push_str(&format!(
2826            "\n\trequires {}: {}",
2827            c.name.name,
2828            bynk_fmt::expr_to_string(&c.predicate)
2829        ));
2830    }
2831    for c in &f.ensures {
2832        out.push_str(&format!(
2833            "\n\tensures {}: {}",
2834            c.name.name,
2835            bynk_fmt::expr_to_string(&c.predicate)
2836        ));
2837    }
2838    out.push_str("\n```\n");
2839    if let Some(doc) = &f.documentation {
2840        out.push('\n');
2841        out.push_str(doc);
2842        out.push('\n');
2843    }
2844    out
2845}
2846
2847pub(crate) fn describe_capability(c: &CapabilityDecl) -> String {
2848    let mut out = String::new();
2849    // S4a (#1966): a derived capability has no body of its own to render.
2850    if c.derived.is_some() {
2851        return describe_derived_capability(c, None, None);
2852    }
2853    out.push_str("```bynk\ncapability ");
2854    out.push_str(&c.name.name);
2855    out.push_str(" {\n");
2856    for op in &c.ops {
2857        out.push_str("\tfn ");
2858        out.push_str(&op.name.name);
2859        out.push_str(&capability_op_type_params_str(op));
2860        out.push('(');
2861        let parts: Vec<String> = op
2862            .params
2863            .iter()
2864            .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2865            .collect();
2866        out.push_str(&parts.join(", "));
2867        out.push_str(") -> ");
2868        out.push_str(&type_ref_str(&op.return_type));
2869        out.push('\n');
2870    }
2871    out.push_str("}\n```\n");
2872    if let Some(doc) = &c.documentation {
2873        out.push('\n');
2874        out.push_str(doc);
2875        out.push('\n');
2876    }
2877    out
2878}
2879
2880/// S4a (#1966): a derived capability (`capability Sessions = Kv`): its
2881/// declaration, that it is a distinct instance of its base (in `base_unit`,
2882/// when known), and the base's operations, when its declaration is at hand.
2883pub(crate) fn describe_derived_capability(
2884    c: &CapabilityDecl,
2885    base_unit: Option<&str>,
2886    base: Option<&CapabilityDecl>,
2887) -> String {
2888    let Some(d) = &c.derived else {
2889        return describe_capability(c);
2890    };
2891    let mut out = format!("```bynk\ncapability {} = {}", c.name.name, d.base.name);
2892    for a in &d.annotations {
2893        out.push_str(" @");
2894        out.push_str(&a.name.name);
2895    }
2896    let from = base_unit.map_or(String::new(), |u| format!(" (`{u}`)"));
2897    // L7 (#2414): an `EdgeCache` instance owns no storage: it switches the
2898    // Worker's edge cache on.
2899    let what = if d.base.name == "EdgeCache" {
2900        "this context's Worker's edge cache"
2901    } else {
2902        "its own storage"
2903    };
2904    out.push_str(&format!(
2905        "\n```\n\nA distinct instance of `{}`{from}: {what}, with `{}`'s operations",
2906        d.base.name, d.base.name
2907    ));
2908    match base {
2909        Some(b) if !b.ops.is_empty() => {
2910            out.push_str(":\n\n```bynk\n");
2911            for op in &b.ops {
2912                let params: Vec<String> = op
2913                    .params
2914                    .iter()
2915                    .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2916                    .collect();
2917                out.push_str(&format!(
2918                    "fn {}{}({}) -> {}\n",
2919                    op.name.name,
2920                    capability_op_type_params_str(op),
2921                    params.join(", "),
2922                    type_ref_str(&op.return_type)
2923                ));
2924            }
2925            out.push_str("```\n");
2926        }
2927        _ => out.push_str(".\n"),
2928    }
2929    // P3 (#2342): a rate limiter's emitted stanza, and how it counts.
2930    if d.base.name == "RateLimit" {
2931        let number = |name: &str| {
2932            d.annotations
2933                .iter()
2934                .find(|a| a.name.name == name)
2935                .and_then(|a| a.args.first())
2936                .and_then(|arg| match &arg.value.kind {
2937                    ExprKind::IntLit { value, .. } => Some(*value),
2938                    ExprKind::DurationLit { millis, .. } => Some(millis / 1000),
2939                    _ => None,
2940                })
2941        };
2942        if let (Some(limit), Some(period)) = (number("limit"), number("period")) {
2943            out.push_str(&format!(
2944                "\nEmits `[[ratelimits]]` with `simple = {{ limit = {limit}, period = {period} }}`: {limit} calls per key every {period} seconds. Counting is approximate (per Cloudflare location, eventually consistent).\n"
2945            ));
2946        }
2947    }
2948    // P2 (#2578): a queue producer's emitted stanza, and the queue it names.
2949    if d.base.name == "Queue"
2950        && let Some(queue) = d
2951            .annotations
2952            .iter()
2953            .find(|a| a.name.name == "name")
2954            .and_then(|a| a.args.first())
2955            .and_then(|arg| match &arg.value.kind {
2956                ExprKind::StrLit(s) => Some(s.clone()),
2957                _ => None,
2958            })
2959    {
2960        out.push_str(&format!(
2961            "\nEmits `[[queues.producers]]` sending to queue `{queue}` (environment-qualified by `bynk deploy`). Bodies are JSON text, normally `Json.encode(value)`.\n"
2962        ));
2963    }
2964    // P3b (#2582): an Analytics Engine dataset, named by deploy, not source.
2965    if d.base.name == "Analytics" {
2966        out.push_str("\nEmits `[[analytics_engine_datasets]]`: the dataset is named for the context and the capability in snake case (`shop.cart`'s `Signups` writes to `shop_cart_signups`), environment-qualified by `bynk deploy`, and created on the first write.\n");
2967    }
2968    // P4a (#2602): a D1 database, named by deploy and minted on first deploy.
2969    if d.base.name == "D1" {
2970        out.push_str("\nEmits `[[d1_databases]]`: the database is named for the context and the capability (`shop.cart`'s `Orders` is `shop-cart-orders`), environment-qualified, created by `bynk deploy`, which records its id.\n");
2971    }
2972    // #3301: an account-level secret, linked by deploy and never created.
2973    if d.base.name == "StoredSecret" {
2974        out.push_str("\nEmits `[[secrets_store_secrets]]`: a distinct instance of `StoredSecret`, reading the secret in the Secrets Store the declaration names. `bynk deploy` links it (it resolves the store's id and checks the secret exists, and creates neither) and fails when either is missing.\n");
2975    }
2976    // #3480: an AI Search instance, linked by deploy and never created.
2977    if d.base.name == "AiSearch" {
2978        out.push_str("\nEmits `[[ai_search]]`: a distinct instance of `AiSearch`, querying the AI Search instance `@instance` names, in every environment. `bynk deploy` links it (it looks the instance up and records it, and creates nothing) and fails when it is missing; `bynk dev` proxies it to the deployed instance.\n");
2979    }
2980    // #3513 A: a client certificate, linked by deploy and never uploaded.
2981    if d.base.name == "MtlsCertificate" {
2982        out.push_str("\nEmits `[[mtls_certificates]]`: a distinct instance of `MtlsCertificate`, whose `send` presents the account's client certificate `@certificate` names to the origin the URL names, in every environment. `bynk deploy` links it by name and never uploads it: the private key never reaches Bynk. `bynk dev` runs it on Cloudflare, once you allow it with `[dev] mtls`.\n");
2983    }
2984    // #3302: outbound email, restricted by its annotations.
2985    if d.base.name == "Email" {
2986        out.push_str("\nEmits `[[send_email]]`, keyed by `name`, with the instance's `@to`, `@allowedRecipients` and `@allowedSenders` as `destination_address`, `allowed_destination_addresses` and `allowed_sender_addresses`. `bynk deploy` checks each `@allowedSenders` domain has Email Sending enabled on the account, and never configures one. A call that breaks a platform limit or sets a reserved header faults before it is sent.\n");
2987    }
2988    // Hyperdrive H1 (#3318): a Postgres database through Hyperdrive.
2989    if d.base.name == "Postgres" {
2990        out.push_str("\nEmits `[[hyperdrive]]` with a placeholder `id`: a distinct instance of `Postgres`, reading the database behind the Hyperdrive configuration at `env.<binding>.connectionString`. `bynk deploy` makes the configuration from the connection string in the environment variable `[deploy.hyperdrive.<Capability>] connection_env` names in `bynk.toml` (or adopts one named by `config_id`) and fills in the `id`; `bynk dev` reads the local string from `[dev.hyperdrive.<Capability>] connection_env`. Each statement opens and closes its own connection.\n");
2991    }
2992    // Hyperdrive H5 (#3322): a MySQL database through Hyperdrive.
2993    if d.base.name == "MySql" {
2994        out.push_str("\nEmits `[[hyperdrive]]` with a placeholder `id` (as `Postgres` does), reading the MySQL database behind the Hyperdrive configuration through mysql2. `@tls(\"required\" | \"verify-ca\" | \"verify-identity\")` is how Hyperdrive secures its connection to the database (default `required`); `bynk deploy` sends it with the config it makes. Statements take `?` placeholders bound from `MySqlValue`s. Each statement opens and closes its own connection.\n");
2995    }
2996    if d.base.name == "EdgeCache" {
2997        out.push_str("\nEmits `[cache] enabled = true`: a `@cache` route's `2xx` is cached at Cloudflare's edge, and every other `GET` or `HEAD` answer is `no-store`.\n");
2998    }
2999    if let Some(doc) = &c.documentation {
3000        out.push('\n');
3001        out.push_str(doc);
3002        out.push('\n');
3003    }
3004    out
3005}
3006
3007/// message-bundles slice 1 (#859): a message bundle's tag, its annotations
3008/// (`@reference`, unresolved cardinality shown as-is — that's a checker
3009/// concern, not hover's), and its declared codes.
3010pub(crate) fn describe_messages(m: &MessagesDecl) -> String {
3011    let mut out = String::new();
3012    out.push_str("```bynk\n");
3013    // #2618: the unit-private modifier, as written.
3014    if m.private.is_some() {
3015        out.push_str("private ");
3016    }
3017    out.push_str("messages ");
3018    out.push('"');
3019    out.push_str(&m.tag);
3020    out.push('"');
3021    for ann in &m.annotations {
3022        out.push(' ');
3023        out.push_str(&bynk_fmt::annotation_to_string(ann));
3024    }
3025    out.push_str(" {\n");
3026    for entry in &m.entries {
3027        // message-bundles slice 3 (#878): name any non-plain (plural/
3028        // select/number/date) placeholders inline, so an author can tell
3029        // at a glance which codes carry ICU dispatch without expanding the
3030        // (elided) template text itself.
3031        let icu_kinds: Vec<String> = bynk_check::icu::template_format_kinds(&entry.template)
3032            .into_iter()
3033            .map(|(name, kind)| (name.to_string(), kind.as_str()))
3034            .filter(|(_, kind)| *kind != "plain")
3035            .map(|(name, kind)| format!("{name}: {kind}"))
3036            .collect();
3037        if icu_kinds.is_empty() {
3038            out.push_str(&format!("\t\"{}\" => …\n", entry.code));
3039        } else {
3040            out.push_str(&format!(
3041                "\t\"{}\" => …  // {}\n",
3042                entry.code,
3043                icu_kinds.join(", ")
3044            ));
3045        }
3046    }
3047    out.push_str("}\n```\n");
3048    if let Some(doc) = &m.documentation {
3049        out.push('\n');
3050        out.push_str(doc);
3051        out.push('\n');
3052    }
3053    out
3054}
3055
3056/// #1883, slice 1a: an `asset` declaration's markdown — the declaration
3057/// itself, the rule that it is public, then its doc.
3058/// #2387, slice 1: an embed's hover and docs. An embed is private: its file's
3059/// text is compiled into the code as a `String`, never served.
3060pub(crate) fn describe_embed(e: &EmbedDecl) -> String {
3061    let mut out = format!(
3062        "```bynk\n{}embed {} = \"{}\"\n```\n\nPrivate: the file's text, compiled into the code as a `String`; never served.\n",
3063        if e.private.is_some() { "private " } else { "" },
3064        e.name.name,
3065        bynk_fmt::escape_string(&e.path)
3066    );
3067    if let Some(doc) = &e.documentation {
3068        out.push('\n');
3069        out.push_str(doc);
3070        out.push('\n');
3071    }
3072    out
3073}
3074
3075/// #2841: a fixture's hover: the declaration as written, then what it is. The
3076/// file's size is not here: hover reads the source alone, not the folder.
3077pub(crate) fn describe_fixture(f: &FixtureDecl) -> String {
3078    let mut out = format!(
3079        "```bynk\nfixture {} = \"{}\"\n```\n\nTest-only: the file's text as a `String` for this suite's cases; never deployed.\n",
3080        f.name.name,
3081        bynk_fmt::escape_string(&f.path)
3082    );
3083    if let Some(doc) = &f.documentation {
3084        out.push('\n');
3085        out.push_str(doc);
3086        out.push('\n');
3087    }
3088    out
3089}
3090
3091/// #2617: a constant's hover and docs — the declaration as written (its type
3092/// and initialiser), then its doc.
3093pub(crate) fn describe_const(c: &ConstDecl) -> String {
3094    let mut out = format!(
3095        "```bynk\n{}const {}: {} = {}\n```\n",
3096        // The unit-private modifier, as written.
3097        if c.private.is_some() { "private " } else { "" },
3098        c.name.name,
3099        type_ref_str(&c.ty),
3100        bynk_fmt::expr_to_string(&c.init)
3101    );
3102    if let Some(doc) = &c.documentation {
3103        out.push('\n');
3104        out.push_str(doc);
3105        out.push('\n');
3106    }
3107    out
3108}
3109
3110pub(crate) fn describe_asset(a: &AssetDecl) -> String {
3111    let at =
3112        a.at.as_ref()
3113            .map(|(p, _)| format!(" at \"{}\"", bynk_fmt::escape_string(p)))
3114            .unwrap_or_default();
3115    // #1883: where it is served. The editor lists the `assets/` folder but
3116    // never reads its bytes, so a content-hashed URL shows its shape with
3117    // `<hash>` in place of the content hash — from the same function the
3118    // build uses, so the two cannot drift.
3119    let served = match &a.at {
3120        Some((p, _)) => format!("Served at `{p}`."),
3121        None => format!(
3122            "Served at `{}` (content-hashed, cached as immutable).",
3123            bynk_check::assets::served_path_with_hash(
3124                &bynk_project::assets::normalise_asset_path(&a.path),
3125                "<hash>"
3126            )
3127        ),
3128    };
3129    let mut out = format!(
3130        "```bynk\n{}asset {} = \"{}\"{at}\n```\n\n{served} Public: served by the platform, never by the Worker.\n",
3131        if a.private.is_some() { "private " } else { "" },
3132        a.name.name,
3133        bynk_fmt::escape_string(&a.path)
3134    );
3135    if let Some(doc) = &a.documentation {
3136        out.push('\n');
3137        out.push_str(doc);
3138        out.push('\n');
3139    }
3140    out
3141}
3142
3143/// v0.123 (slice 2): the `from <protocol>` header suffix for a service, or the
3144/// empty string for a plain `on call` service.
3145///
3146/// This matches the AST's `ServiceProtocol` rather than the model's
3147/// `ProtocolIr`, under M-1's domain clause (the system-model ADR,
3148/// crate-hygiene B1, #2939):
3149/// - It renders the protocol as the user spelled it (`type_ref_str`), which
3150///   makes it a printer, like `bynk-fmt`'s `format_service`.
3151/// - Hover and the documentation page hold only a recovering parse, while
3152///   `ProtocolIr` resolves its frame and event types and needs a checked
3153///   program.
3154fn service_protocol_suffix(p: &ServiceProtocol) -> String {
3155    match p {
3156        ServiceProtocol::Call => String::new(),
3157        ServiceProtocol::Http => " from http".to_string(),
3158        ServiceProtocol::Cron => " from cron".to_string(),
3159        ServiceProtocol::Queue { name } => format!(" from queue(\"{name}\")"),
3160        ServiceProtocol::Email { address } => format!(" from email(\"{address}\")"),
3161        ServiceProtocol::WebSocket { .. } => " from websocket".to_string(),
3162        // Events track slice 1 (spine #936): a subscription pattern is not
3163        // rendered in this short suffix, matching how WebSocket's in/out
3164        // types are also omitted here — this is a one-line summary label,
3165        // not a full re-render of the header.
3166        ServiceProtocol::Events { event_type, .. } => {
3167            format!(" from Events({})", type_ref_str(event_type))
3168        }
3169    }
3170}
3171
3172/// v0.131: a one-line summary of a `cors { }` policy for hover — the origins
3173/// (always present), then `credentials`/`maxAge` when set.
3174fn cors_summary(cors: &CorsPolicy) -> String {
3175    let mut parts = vec![format!("origins: {:?}", cors.origins())];
3176    if cors.credentials() {
3177        parts.push("credentials: true".to_string());
3178    }
3179    if let Some(secs) = cors.max_age_secs() {
3180        parts.push(format!("maxAge: {secs}s"));
3181    }
3182    parts.join(", ")
3183}
3184
3185/// v0.141: a one-line summary of a `security { }` policy for hover — `nosniff`
3186/// (default on, shown when off) and `hsts` (when opted in).
3187fn security_summary(security: &SecurityPolicy) -> String {
3188    let mut parts = Vec::new();
3189    if !security.nosniff() {
3190        parts.push("nosniff: false".to_string());
3191    }
3192    if let Some(secs) = security.hsts_max_age_secs() {
3193        parts.push(format!("hsts: {secs}s"));
3194    }
3195    if parts.is_empty() {
3196        // The default posture (nosniff on, no HSTS) with an empty block.
3197        "nosniff".to_string()
3198    } else {
3199        parts.join(", ")
3200    }
3201}
3202
3203/// v0.142 (ADR 0165): a one-line summary of a `limits { }` policy for hover — the
3204/// `maxBody` byte ceiling when set.
3205fn limits_summary(limits: &LimitsPolicy) -> String {
3206    match limits.max_body() {
3207        Some(bytes) => format!("maxBody: {bytes} bytes"),
3208        None => "maxBody".to_string(),
3209    }
3210}
3211
3212/// v0.123 (slice 2): the `on …` line for a handler — its route/protocol shape.
3213/// Read from the system model's [`bynk_model::IrHandlerKind`] (M-1, crate-hygiene
3214/// B1, #2939), which `bynk_model::lower_handler_kind_ir` builds from any parse.
3215pub(crate) fn handler_line(h: &Handler) -> String {
3216    use bynk_model::IrHandlerKind;
3217    match bynk_model::lower_handler_kind_ir(&h.kind) {
3218        IrHandlerKind::Call => "on call".to_string(),
3219        IrHandlerKind::Http { method, path } => format!("on {}(\"{}\")", method.as_str(), path),
3220        IrHandlerKind::Cron { expr } => format!("on schedule(\"{expr}\")"),
3221        IrHandlerKind::Message => "on message".to_string(),
3222        IrHandlerKind::Open => "on open".to_string(),
3223        IrHandlerKind::Close => "on close".to_string(),
3224        IrHandlerKind::Event => "on event".to_string(),
3225        IrHandlerKind::Rejected => "on rejected".to_string(),
3226    }
3227}
3228
3229pub(crate) fn describe_service(s: &ServiceDecl) -> String {
3230    // v0.123 (slice 2): the protocol header and a line per route (was a bare
3231    // handler count).
3232    let mut out = format!(
3233        "```bynk\nservice {}{} {{\n",
3234        s.name.name,
3235        service_protocol_suffix(&s.protocol)
3236    );
3237    // v0.131: the CORS policy, if any, renders as a `cors { … }` header line
3238    // summarising the origins (the load-bearing field).
3239    if let Some(cors) = &s.cors {
3240        out.push_str(&format!("\tcors {{ {} }}\n", cors_summary(cors)));
3241    }
3242    // v0.141: the security-headers policy, if declared, renders similarly.
3243    if let Some(security) = &s.security {
3244        out.push_str(&format!(
3245            "\tsecurity {{ {} }}\n",
3246            security_summary(security)
3247        ));
3248    }
3249    // v0.142 (ADR 0165): the request-limits policy, if declared, renders similarly.
3250    if let Some(limits) = &s.limits {
3251        out.push_str(&format!("\tlimits {{ {} }}\n", limits_summary(limits)));
3252    }
3253    // #2858: the response-JSON policy, if declared, renders its mode.
3254    if let Some(json) = &s.json {
3255        let mode = match json.options() {
3256            JsonOptions::Plain => "plain",
3257            JsonOptions::Tagged => "tagged",
3258        };
3259        out.push_str(&format!("\tjson {{ options: {mode} }}\n"));
3260    }
3261    for h in &s.handlers {
3262        // #2858: a route whose response `Option`s are plain JSON says so.
3263        let plain = if effective_json_options(s.json.as_ref(), h) == JsonOptions::Plain {
3264            "  // plain JSON"
3265        } else {
3266            ""
3267        };
3268        out.push_str(&format!("\t{}{plain}\n", handler_line(h)));
3269    }
3270    out.push_str("}\n```\n");
3271    if let Some(doc) = &s.documentation {
3272        out.push('\n');
3273        out.push_str(doc);
3274        out.push('\n');
3275    }
3276    out
3277}
3278
3279/// v0.123 (slice 2): a store field's kind — `Cell[Int]`, `Map[K, V]`, or a bare
3280/// head with no type args.
3281fn store_kind_str(k: &StoreKind) -> String {
3282    if k.args.is_empty() {
3283        k.head.name.clone()
3284    } else {
3285        let args: Vec<String> = k.args.iter().map(type_ref_str).collect();
3286        format!("{}[{}]", k.head.name, args.join(", "))
3287    }
3288}
3289
3290pub(crate) fn describe_agent(a: &AgentDecl) -> String {
3291    // v0.123 (slice 2): the store fields plus the `invariant`/`transition` step
3292    // invariants (v0.116), was a bare store-field count.
3293    let mut out = format!(
3294        "```bynk\nagent {} {{\n\tkey {}: {}\n",
3295        a.name.name,
3296        a.key_name.name,
3297        type_ref_str(&a.key_type),
3298    );
3299    for f in &a.store_fields {
3300        out.push_str(&format!(
3301            "\tstore {}: {}\n",
3302            f.name.name,
3303            store_kind_str(&f.kind)
3304        ));
3305    }
3306    for inv in &a.invariants {
3307        out.push_str(&format!(
3308            "\tinvariant {}: {}\n",
3309            inv.name.name,
3310            bynk_fmt::expr_to_string(&inv.predicate)
3311        ));
3312    }
3313    for tr in &a.transitions {
3314        out.push_str(&format!(
3315            "\ttransition {}: {}\n",
3316            tr.name.name,
3317            bynk_fmt::expr_to_string(&tr.predicate)
3318        ));
3319    }
3320    out.push_str("}\n```\n");
3321    if let Some(doc) = &a.documentation {
3322        out.push('\n');
3323        out.push_str(doc);
3324        out.push('\n');
3325    }
3326    out
3327}
3328
3329pub(crate) fn describe_provider(p: &ProviderDecl) -> String {
3330    let mut out = format!(
3331        "```bynk\nprovides {} = {}\n```\n",
3332        p.capability.name, p.provider_name.name
3333    );
3334    if let Some(doc) = &p.documentation {
3335        out.push('\n');
3336        out.push_str(doc);
3337        out.push('\n');
3338    }
3339    out
3340}
3341
3342/// A cross-file declaration lookup result: the path of the file containing
3343/// the declaration, the declaration's source span, and the full source
3344/// text of that file (returned because callers need it to convert the
3345/// span to an LSP range and to build hover content).
3346pub struct CrossFileSymbol {
3347    pub path: PathBuf,
3348    pub span: Span,
3349    pub source: String,
3350}
3351
3352/// The project's files, in the same deterministic order
3353/// `bynk_project::discover_bynk_files` produces (sorted by path) —
3354/// `HashMap` iteration order is unspecified, and "the first hit wins" only
3355/// means something if that order is stable and reproducible.
3356fn sorted_paths(files: &HashMap<PathBuf, String>) -> Vec<&PathBuf> {
3357    let mut paths: Vec<&PathBuf> = files.keys().collect();
3358    paths.sort();
3359    paths
3360}
3361
3362/// Find `name`'s declaration in any project file other than `current_path`.
3363/// Content-ownership track (#1086) slice 1: `files` is a pre-read
3364/// `(path, content)` map (the caller's overlay-then-disk sweep) rather than
3365/// bare paths this function used to read from disk itself. Returns the
3366/// first hit, in path-sorted order (see `sorted_paths`); `None` if the name
3367/// is not found anywhere in the project.
3368///
3369/// Caller is responsible for trying the open file's local symbol table
3370/// first; this function intentionally skips `current_path` so the local
3371/// path remains the fast path.
3372pub fn find_declaration_cross_file(
3373    files: &HashMap<PathBuf, String>,
3374    current_path: &Path,
3375    name: &str,
3376) -> Option<CrossFileSymbol> {
3377    for path in sorted_paths(files) {
3378        if path.as_path() == current_path {
3379            continue;
3380        }
3381        let source = &files[path];
3382        if let Some(span) = find_declaration_span(source, name) {
3383            return Some(CrossFileSymbol {
3384                path: path.clone(),
3385                span,
3386                source: source.clone(),
3387            });
3388        }
3389    }
3390    None
3391}
3392
3393/// Markdown hover content for `name` from any project file other than
3394/// `current_path`, plus the path of the file that contributed it. See
3395/// `find_declaration_cross_file`'s doc for the content-ownership-track
3396/// shape of `files`. Returns `None` if the name is not declared anywhere in
3397/// the project.
3398pub fn describe_symbol_cross_file(
3399    files: &HashMap<PathBuf, String>,
3400    current_path: &Path,
3401    name: &str,
3402) -> Option<(PathBuf, String)> {
3403    for path in sorted_paths(files) {
3404        if path.as_path() == current_path {
3405            continue;
3406        }
3407        let source = &files[path];
3408        if let Some(desc) = describe_symbol(source, name) {
3409            return Some((path.clone(), desc));
3410        }
3411    }
3412    None
3413}
3414
3415pub fn type_ref_str(t: &TypeRef) -> String {
3416    match t {
3417        // v0.20a: function types render in Bynk surface syntax.
3418        TypeRef::Fn(params, ret, _) => {
3419            let lhs = match params.len() {
3420                0 => "()".to_string(),
3421                1 if !matches!(params[0], TypeRef::Fn(..)) => type_ref_str(&params[0]),
3422                _ => format!(
3423                    "({})",
3424                    params
3425                        .iter()
3426                        .map(type_ref_str)
3427                        .collect::<Vec<_>>()
3428                        .join(", ")
3429                ),
3430            };
3431            format!("{lhs} -> {}", type_ref_str(ret))
3432        }
3433        TypeRef::Base(b, _) => b.name().to_string(),
3434        TypeRef::Named(id) => id.name.clone(),
3435        TypeRef::Result(a, b, _) => format!("Result[{}, {}]", type_ref_str(a), type_ref_str(b)),
3436        TypeRef::Option(t, _) => format!("Option[{}]", type_ref_str(t)),
3437        TypeRef::Effect(t, _) => format!("Effect[{}]", type_ref_str(t)),
3438        TypeRef::HttpResult(t, _) => format!("HttpResult[{}]", type_ref_str(t)),
3439        TypeRef::QueueResult(_) => "QueueResult".to_string(),
3440        TypeRef::Asset(_) => "Asset".to_string(),
3441        TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
3442        TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
3443        TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
3444        TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
3445        TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
3446        // v0.20b: the built-in collection types.
3447        TypeRef::List(t, _) => format!("List[{}]", type_ref_str(t)),
3448        TypeRef::Set(t, _) => format!("Set[{}]", type_ref_str(t)),
3449        TypeRef::Query(t, _) => format!("Query[{}]", type_ref_str(t)),
3450        TypeRef::Stream(t, _) => format!("Stream[{}]", type_ref_str(t)),
3451        TypeRef::Connection(t, _) => format!("Connection[{}]", type_ref_str(t)),
3452        TypeRef::History(t, _) => format!("History[{}]", type_ref_str(t)),
3453        TypeRef::Map(k, v, _) => format!("Map[{}, {}]", type_ref_str(k), type_ref_str(v)),
3454        TypeRef::ValidationError(_) => "ValidationError".to_string(),
3455        TypeRef::DecodeError(_) => "DecodeError".to_string(),
3456        TypeRef::Unit(_) => "()".to_string(),
3457        // v0.157 (ADR 0183): a user generic-type application, as written.
3458        TypeRef::App { name, args, .. } => format!(
3459            "{}[{}]",
3460            name.name,
3461            args.iter().map(type_ref_str).collect::<Vec<_>>().join(", ")
3462        ),
3463    }
3464}
3465
3466#[cfg(test)]
3467mod tests {
3468    /// #3458: hover on a typed read says what a reply that does not decode means,
3469    /// read off the operation's declared policy; any other operation says nothing.
3470    #[test]
3471    fn hover_on_a_typed_read_names_its_failure_policy() {
3472        use bynk_syntax::ast::{CommonsItem, SourceUnit};
3473        let src = "context bynk.t\n\ncapability Store {\n  fn find[T: Codable](k: String) -> Effect[Option[T]] @onUndecodable(miss)\n  fn need[T: Codable](k: String) -> Effect[T]\n  fn size() -> Effect[Int]\n}\n";
3474        let toks = bynk_syntax::lexer::tokenize(src).expect("lexes");
3475        let SourceUnit::Context(ctx) = bynk_syntax::parser::parse_unit(&toks, src).expect("parses")
3476        else {
3477            panic!("a context");
3478        };
3479        let Some(CommonsItem::Capability(cap)) = ctx.items.first() else {
3480            panic!("a capability");
3481        };
3482        let hover = |op: &str| {
3483            let op = cap.ops.iter().find(|o| o.name.name == op).expect("op");
3484            describe_capability_op(cap, op)
3485        };
3486        assert!(hover("find").contains("is a miss"), "{}", hover("find"));
3487        assert!(hover("need").contains("faults"), "{}", hover("need"));
3488        assert!(!hover("size").contains("typed read"), "{}", hover("size"));
3489    }
3490
3491    #[test]
3492    fn hover_on_an_example_names_the_refinement() {
3493        let src = "commons c\n\ntype Code = String where Matches(\"[A-Z]{3}\") @example(\"ABC\")\n";
3494        let at = src.find("example").unwrap();
3495        let h = describe_refinement_example_at(src, at).expect("hover");
3496        assert!(
3497            h.contains("@example(\"ABC\")") && h.contains("Matches"),
3498            "{h}"
3499        );
3500        assert!(describe_refinement_example_at(src, 3).is_none());
3501    }
3502
3503    /// #2683: hover on `within` names its signature and the abandoned-effect
3504    /// caveat, and only when the receiver is an `Effect`.
3505    #[test]
3506    fn within_hovers_on_an_effect_receiver_only() {
3507        use bynk_check::checker::{Ty, Types};
3508        use bynk_syntax::ast::BaseType;
3509        let tys = Types::new();
3510        let int = tys.intern(Ty::Base(BaseType::Int));
3511        let effect = tys.intern(Ty::Effect(int));
3512        let src = "let r <- p.quote(1).within(2.seconds)\n";
3513        let dot = src.find(".within").unwrap();
3514        let at = src.find("within").unwrap() + 1;
3515        let on_effect = [(Span::new(8, dot), effect)];
3516        let hover = describe_effect_method_at(src, at, &on_effect, &tys).expect("within hovers");
3517        assert!(
3518            hover.contains("within(d: Duration) -> Effect[Result[T, TimedOut]]"),
3519            "{hover}"
3520        );
3521        assert!(hover.contains("not cancelled"), "{hover}");
3522        assert!(hover.contains("waitUntil"), "{hover}");
3523        // A receiver that is not an `Effect` is a user's own `within`.
3524        let on_int = [(Span::new(8, dot), int)];
3525        assert!(describe_effect_method_at(src, at, &on_int, &tys).is_none());
3526        // Elsewhere on the line is not `within`.
3527        assert!(describe_effect_method_at(src, 0, &on_effect, &tys).is_none());
3528
3529        // #2711: `race` hovers the same way, with the loser caveat.
3530        let src = "let r <- p.get(1).race(p.get(2))\n";
3531        let dot = src.find(".race").unwrap();
3532        let at = src.find("race").unwrap() + 1;
3533        let on_effect = [(Span::new(8, dot), effect)];
3534        let hover = describe_effect_method_at(src, at, &on_effect, &tys).expect("race hovers");
3535        assert!(
3536            hover.contains("race(other: Effect[T]) -> Effect[T]"),
3537            "{hover}"
3538        );
3539        assert!(hover.contains("loser is not cancelled"), "{hover}");
3540        assert!(hover.contains("idempotent"), "{hover}");
3541        let on_int = [(Span::new(8, dot), int)];
3542        assert!(describe_effect_method_at(src, at, &on_int, &tys).is_none());
3543
3544        // #3437: `detach` says it stops waiting, and that a failure is reported.
3545        let src = "do p.get(1).detach()\n";
3546        let dot = src.find(".detach").unwrap();
3547        let at = src.find("detach").unwrap() + 1;
3548        let on_effect = [(Span::new(3, dot), effect)];
3549        let hover = describe_effect_method_at(src, at, &on_effect, &tys).expect("detach hovers");
3550        assert!(hover.contains("detach() -> Effect[()]"), "{hover}");
3551        assert!(hover.contains("not once it has finished"), "{hover}");
3552        assert!(hover.contains("reported, never lost"), "{hover}");
3553        let on_int = [(Span::new(3, dot), int)];
3554        assert!(describe_effect_method_at(src, at, &on_int, &tys).is_none());
3555    }
3556
3557    /// A constant's hover shows its `private` modifier as written, and the
3558    /// modifier itself hovers before `const` as before the other kinds.
3559    #[test]
3560    fn private_const_hover_shows_the_modifier() {
3561        let src = "commons m\n\nprivate const MaxRetries: Int = 3\n\nconst Shown: Int = 1\n";
3562        let tokens = tokenize(src).unwrap();
3563        let (Some(SourceUnit::Commons(c)), _) = parse_unit_with_recovery(&tokens, src) else {
3564            panic!("a commons");
3565        };
3566        let hidden = describe_item(&c.items[0], "MaxRetries").unwrap();
3567        assert!(
3568            hidden.starts_with("```bynk\nprivate const MaxRetries: Int = 3\n"),
3569            "{hidden}"
3570        );
3571        let shown = describe_item(&c.items[1], "Shown").unwrap();
3572        assert!(shown.starts_with("```bynk\nconst Shown"), "{shown}");
3573        assert!(describe_private_at(src, src.find("private").unwrap()).is_some());
3574    }
3575
3576    /// #2640: `par` hovers only as the head of a `par { … }` block.
3577    #[test]
3578    fn par_hover_is_for_the_block_keyword_only() {
3579        let block =
3580            "fn f() -> Effect[Int] {\n  par {\n    let a <- g()\n  }\n  Effect.pure(a)\n}\n";
3581        let at = block.find("par").unwrap();
3582        assert!(describe_par_at(block, at).unwrap().contains("par {"));
3583        let ident = "fn f(par: Int) -> Int {\n  par\n}\n";
3584        assert!(describe_par_at(ident, ident.find("par").unwrap()).is_none());
3585        assert!(describe_par_at(ident, ident.rfind("par").unwrap()).is_none());
3586    }
3587
3588    use super::*;
3589
3590    /// #3328: a `from email` service's header reads back as the author wrote
3591    /// it, whatever the address.
3592    #[test]
3593    fn email_service_header_renders_its_address() {
3594        let p = ServiceProtocol::Email {
3595            address: "*@shop.example".to_string(),
3596        };
3597        assert_eq!(
3598            service_protocol_suffix(&p),
3599            " from email(\"*@shop.example\")"
3600        );
3601    }
3602
3603    /// #2136: the `system` cron/queue hover answers only when the receiver is
3604    /// a `cron` / `queue` service of the suite's target, not a record field
3605    /// named `message`, and not at a lower tier.
3606    #[test]
3607    fn system_job_hover_needs_a_job_service_receiver() {
3608        const CTX: &str = "context cr.jobs\n\ntype Envelope = { message: String }\n\nservice sweeper from cron {\n  on schedule(\"*/5 * * * *\") () -> Effect[Result[(), String]] {\n    Ok(())\n  }\n}\n\nservice deliveries from queue(\"d\") {\n  on message(e: Envelope) -> Effect[QueueResult] {\n    Ack\n  }\n}\n";
3609        let suite = |tier: &str| {
3610            format!(
3611                "suite cr.jobs{tier} {{\n  case \"c\" {{\n    let e = Envelope {{ message: \"hi\" }}\n    let m = e.message\n    let r <- deliveries.message(e)\n    let s <- sweeper.schedule(\"*/5 * * * *\")\n    expect m == \"hi\"\n  }}\n}}\n"
3612            )
3613        };
3614        let at = |src: &str, needle: &str| {
3615            src.find(needle).expect("needle is in the suite") + needle.len() - "message".len()
3616        };
3617        let system = suite(" as system");
3618        let field = at(&system, "e.message");
3619        assert!(describe_system_job_address_at(&system, field, [CTX]).is_none());
3620        let queue = at(&system, "deliveries.message");
3621        let hover =
3622            describe_system_job_address_at(&system, queue, [CTX]).expect("queue address hovers");
3623        assert!(hover.contains("`queue` entry"), "{hover}");
3624        let cron = system.find("sweeper.schedule").expect("cron address") + "sweeper.".len();
3625        let hover =
3626            describe_system_job_address_at(&system, cron, [CTX]).expect("cron address hovers");
3627        assert!(hover.contains("`scheduled` entry"), "{hover}");
3628        let unit = suite("");
3629        let queue = at(&unit, "deliveries.message");
3630        assert!(describe_system_job_address_at(&unit, queue, [CTX]).is_none());
3631    }
3632
3633    /// #2138: `run.id` hovers in a case body, on either half, but not where
3634    /// the case binds its own `run`, nor outside a suite.
3635    #[test]
3636    fn run_id_hovers_only_as_the_test_run() {
3637        let src = "suite rid.orders {\n  case \"a\" {\n    expect run.id == \"local\"\n  }\n  case \"b\" {\n    let run = Wrapper { id: \"x\" }\n    expect run.id == \"x\"\n  }\n}\n";
3638        let first = src.find("run.id").expect("first run.id");
3639        assert!(describe_run_id_at(src, first).is_some());
3640        assert!(describe_run_id_at(src, first + "run.".len()).is_some());
3641        let shadowed = src.rfind("run.id").expect("second run.id");
3642        assert!(describe_run_id_at(src, shadowed).is_none());
3643        let interp = "suite rid.orders as system {\n  case \"a\" {\n    let r <- api.POST(\"/o/:id\", \"o-\\(run.id)\") by Visitor\n    expect r is Ok(true)\n  }\n}\n";
3644        assert!(describe_run_id_at(interp, interp.find("run.id").expect("run.id")).is_some());
3645        let ctx = "context rid.orders\n\nfn f(run: Wrapper) -> String {\n  run.id\n}\n";
3646        assert!(describe_run_id_at(ctx, ctx.find("run.id").expect("run.id")).is_none());
3647    }
3648
3649    /// #2175: the shadowing check follows the checker's scopes — a `let`
3650    /// in a nested block, a lambda parameter, a `match` pattern and an
3651    /// `if … is` binding each shadow `run`; outside their scope it is the
3652    /// test run again.
3653    #[test]
3654    fn run_id_hover_respects_nested_binders() {
3655        let src = "suite rid.orders {\n  case \"a\" {\n    let w = Wrapper { id: \"x\" }\n    let a = if true {\n      let run = w\n      run.id\n    } else { \"\" }\n    let f = (run: Wrapper) => run.id\n    let m = match Some(w) { Some(run) => run.id, None => \"\" }\n    let i = if Some(w) is Some(run) { run.id } else { \"\" }\n    let j = Some(w) is Some(run) && run.id == \"x\"\n    let k = if !(Some(w) is Some(run)) { \"\" } else { run.id }\n    expect run.id == \"local\"\n  }\n}\n";
3656        let starts: Vec<usize> = src.match_indices("run.id").map(|(i, _)| i).collect();
3657        assert_eq!(starts.len(), 7, "{src}");
3658        for &shadowed in &starts[..6] {
3659            assert!(
3660                describe_run_id_at(src, shadowed).is_none(),
3661                "shadowed at {shadowed}: {}",
3662                &src[shadowed.saturating_sub(30)..shadowed + 6]
3663            );
3664        }
3665        assert!(describe_run_id_at(src, starts[6]).is_some(), "the test run");
3666    }
3667
3668    /// #2135: hover on a reserved principal after `by` says what it sends;
3669    /// the same name elsewhere is not one.
3670    #[test]
3671    fn hover_describes_reserved_principals() {
3672        let src = "suite pay.hooks as system {\n\tcase \"c\" {\n\t\tlet r <- webhooks.POST(\"/h\", \"x\") by Forged\n\t\tlet Stale = 1\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3673        let forged = describe_reserved_principal_at(src, src.find("Forged").unwrap()).unwrap();
3674        assert!(
3675            forged.contains("by Forged") && forged.contains("does not hold"),
3676            "{forged}"
3677        );
3678        assert!(describe_reserved_principal_at(src, src.find("Stale").unwrap()).is_none());
3679        let src = "suite pay.api as system {\n\tcase \"c\" {\n\t\tlet r <- api.GET(\"/a\") by Expired\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3680        let expired = describe_reserved_principal_at(src, src.find("Expired").unwrap()).unwrap();
3681        assert!(
3682            expired.contains("by Expired") && expired.contains("one hour in the past"),
3683            "{expired}"
3684        );
3685        let src = "suite ci.api as system {\n\tcase \"c\" {\n\t\tlet r <- api.GET(\"/a\") by WrongIssuer\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3686        let wrong = describe_reserved_principal_at(src, src.find("WrongIssuer").unwrap()).unwrap();
3687        assert!(
3688            wrong.contains("by WrongIssuer") && wrong.contains("`iss` is not the actor's"),
3689            "{wrong}"
3690        );
3691        // #3225: the algorithm and subject principals.
3692        let src = "suite ci.api as system {\n\tcase \"c\" {\n\t\tlet r <- api.GET(\"/a\") by WrongAlgorithm\n\t\tlet s <- api.GET(\"/a\") by NoSubject\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3693        let alg = describe_reserved_principal_at(src, src.find("WrongAlgorithm").unwrap()).unwrap();
3694        assert!(
3695            alg.contains("by WrongAlgorithm")
3696                && alg.contains("`alg: none`")
3697                && alg.contains("`HS256`"),
3698            "{alg}"
3699        );
3700        let sub = describe_reserved_principal_at(src, src.find("NoSubject").unwrap()).unwrap();
3701        assert!(
3702            sub.contains("by NoSubject")
3703                && sub.contains("empty `sub`")
3704                && sub.contains("no `sub` claim"),
3705            "{sub}"
3706        );
3707    }
3708
3709    /// #2134: hover on an `env` clause's word and entry names says where the
3710    /// entry applies.
3711    #[test]
3712    fn hover_describes_env_entries() {
3713        let src = "suite shop.pay {\n\tenv {\n\t\tA = \"x\"\n\t}\n\n\tcase \"c\" {\n\t\tenv { A = \"y\"\n\t\t\tB = \"z\" }\n\t\texpect true\n\t}\n}\n";
3714        let at = |needle: &str| src.find(needle).unwrap();
3715        assert_eq!(
3716            describe_env_at(src, at("env")).as_deref(),
3717            Some(ENV_KEYWORD_DOC)
3718        );
3719        let suite_a = describe_env_at(src, at("A = \"x\"")).unwrap();
3720        assert!(suite_a.contains("A = \"x\""), "{suite_a}");
3721        assert!(suite_a.ends_with("(suite)"), "{suite_a}");
3722        let case_a = describe_env_at(src, at("A = \"y\"")).unwrap();
3723        assert!(case_a.ends_with("(case, overrides suite)"), "{case_a}");
3724        let case_b = describe_env_at(src, at("B = ")).unwrap();
3725        assert!(case_b.ends_with("(case)"), "{case_b}");
3726        assert!(describe_env_at(src, at("expect")).is_none());
3727    }
3728
3729    /// S3 (#1963): hover on a first-party extensible enum says a `match` on it
3730    /// needs a wildcard; a closed one, and a stable one, say nothing extra.
3731    #[test]
3732    fn hover_marks_an_extensible_first_party_enum() {
3733        let fetch_error = describe_firstparty_symbol("FetchError").expect("FetchError hovers");
3734        assert!(fetch_error.contains("**Extensible**"), "{fetch_error}");
3735        assert!(
3736            !fetch_error.contains("**Experimental**"),
3737            "nothing ships experimental"
3738        );
3739        assert!(
3740            describe_firstparty_symbol("Method")
3741                .unwrap()
3742                .contains("**Extensible**")
3743        );
3744        let closed = describe_firstparty_symbol("Request").expect("Request hovers");
3745        assert!(
3746            !closed.contains("**Extensible**"),
3747            "a closed first-party type is not marked extensible"
3748        );
3749        assert_eq!(
3750            firstparty_notes("app.user", "FetchError"),
3751            "",
3752            "a user's own enum"
3753        );
3754    }
3755
3756    /// Content-ownership track (#1086) slice 1: `find_declaration_cross_file`/
3757    /// `describe_symbol_cross_file` take a pre-read `(path, content)` map
3758    /// rather than bare paths they used to read from disk themselves, so the
3759    /// tests below build that map directly — a synthetic root plus a
3760    /// `(relative_path, contents)` list, no real filesystem I/O needed at all.
3761    fn project_files(root: &Path, files: &[(&str, &str)]) -> HashMap<PathBuf, String> {
3762        files
3763            .iter()
3764            .map(|(rel, contents)| (root.join(rel), (*contents).to_string()))
3765            .collect()
3766    }
3767
3768    #[test]
3769    fn receiver_segment_survives_a_multibyte_char_before_the_receiver() {
3770        // A multi-byte non-identifier char before the receiver used to make the
3771        // `i + 1` byte offset land mid-codepoint → panic on slice (#715),
3772        // reached from hover on a `recv.member` access inside a string literal.
3773        let text = "\"€p.items"; // member `items` sits after the dot
3774        let member_start = text.rfind("items").unwrap();
3775        let (recv, start) =
3776            receiver_segment_at(text, Span::new(member_start, text.len())).expect("receiver");
3777        assert_eq!(recv, "p");
3778        assert_eq!(&text[start..start + recv.len()], "p");
3779    }
3780
3781    #[test]
3782    fn cross_file_definition_resolves_into_sibling_file() {
3783        let root = PathBuf::from("/synthetic/cross_file_definition");
3784        let files = project_files(
3785            &root,
3786            &[
3787                (
3788                    "a.bynk",
3789                    "commons demo.a\n\ntype Foo = Int where Positive\n",
3790                ),
3791                (
3792                    "b.bynk",
3793                    "commons demo.b\n\nuses demo.a\n\ntype Bar = Int where NonNegative\n",
3794                ),
3795            ],
3796        );
3797        let current = root.join("b.bynk");
3798        let found = find_declaration_cross_file(&files, &current, "Foo")
3799            .expect("Foo should resolve into a.bynk");
3800        let expected = root.join("a.bynk");
3801        assert_eq!(found.path, expected);
3802        assert!(
3803            found.source.contains("type Foo = Int where Positive"),
3804            "source returned does not contain Foo declaration"
3805        );
3806    }
3807
3808    #[test]
3809    fn cross_file_definition_skips_current_file() {
3810        let root = PathBuf::from("/synthetic/cross_file_skip_current");
3811        let files = project_files(
3812            &root,
3813            &[(
3814                "only.bynk",
3815                "commons demo.only\n\ntype Foo = Int where Positive\n",
3816            )],
3817        );
3818        let current = root.join("only.bynk");
3819        // The only file containing Foo is current; cross-file must skip it.
3820        assert!(find_declaration_cross_file(&files, &current, "Foo").is_none());
3821    }
3822
3823    #[test]
3824    fn cross_file_hover_returns_markdown_summary() {
3825        let root = PathBuf::from("/synthetic/cross_file_hover");
3826        let files = project_files(
3827            &root,
3828            &[
3829                (
3830                    "money.bynk",
3831                    "commons demo.money\n\n\
3832                     ---\n\
3833                     Amount in minor units of currency.\n\
3834                     ---\n\
3835                     type Money = Int where NonNegative\n",
3836                ),
3837                (
3838                    "orders.bynk",
3839                    "commons demo.orders\n\nuses demo.money\n\ntype OrderId = Int where Positive\n",
3840                ),
3841            ],
3842        );
3843        let current = root.join("orders.bynk");
3844        let (other_path, desc) = describe_symbol_cross_file(&files, &current, "Money")
3845            .expect("Money should produce hover content");
3846        assert_eq!(other_path, root.join("money.bynk"));
3847        assert!(desc.contains("type Money"));
3848        assert!(
3849            desc.contains("Amount in minor units"),
3850            "hover should include the doc block"
3851        );
3852    }
3853
3854    #[test]
3855    fn cross_file_returns_none_for_unknown_name() {
3856        let root = PathBuf::from("/synthetic/cross_file_none");
3857        let files = project_files(
3858            &root,
3859            &[(
3860                "a.bynk",
3861                "commons demo.a\n\ntype Foo = Int where Positive\n",
3862            )],
3863        );
3864        let current = root.join("a.bynk");
3865        assert!(find_declaration_cross_file(&files, &current, "DoesNotExist").is_none());
3866        assert!(describe_symbol_cross_file(&files, &current, "DoesNotExist").is_none());
3867    }
3868
3869    #[test]
3870    fn first_party_symbols_describe_their_signature_and_doc() {
3871        // Slice 9: stdlib/surface symbols live in the embedded sources, not the
3872        // project — the hover/completion-doc fallback finds them there, signature
3873        // and `---` doc block alike.
3874        let reverse = describe_firstparty_symbol("reverse").expect("`bynk.list.reverse` described");
3875        assert!(
3876            reverse.contains("reverse") && reverse.contains("List"),
3877            "{reverse}"
3878        );
3879        assert!(
3880            reverse.contains("reverse order"),
3881            "doc block surfaced: {reverse}"
3882        );
3883        // The `bynk` adapter surface too (a capability, exercising the adapter path).
3884        let clock = describe_firstparty_symbol("Clock").expect("`bynk`-surface `Clock`");
3885        assert!(
3886            clock.contains("wall-clock"),
3887            "capability doc surfaced: {clock}"
3888        );
3889        // #901: the whole locale surface hovered as nothing before
3890        // `bynk.locale`/`bynk.locale.types` reached the shared source list. A
3891        // type from the leaf, and a fn from the value-level commons.
3892        let locale_tag = describe_firstparty_symbol("LocaleTag")
3893            .expect("`bynk.locale.types.LocaleTag` described");
3894        assert!(
3895            locale_tag.contains("LocaleTag") && locale_tag.contains("Matches"),
3896            "{locale_tag}"
3897        );
3898        let render = describe_firstparty_symbol("render").expect("`bynk.locale.render` described");
3899        assert!(
3900            render.contains("render") && render.contains("LocaleTag"),
3901            "{render}"
3902        );
3903        let with_text =
3904            describe_firstparty_symbol("withText").expect("`bynk.locale.withText` described");
3905        assert!(with_text.contains("withText"), "{with_text}");
3906        // A name in no first-party source yields nothing (the fallback no-ops).
3907        assert!(describe_firstparty_symbol("DoesNotExist").is_none());
3908    }
3909
3910    /// #3481: hovering `Idempotency`, or one of its operations, names the provider
3911    /// each platform selects: D1-backed on Cloudflare, in-memory on Node and in the
3912    /// browser. The text is static and names both, so it needs no project platform.
3913    #[test]
3914    fn idempotency_hover_names_the_provider_for_each_platform() {
3915        let capability = describe_firstparty_symbol("Idempotency").expect("`Idempotency` hovers");
3916        assert!(capability.contains("D1-backed"), "{capability}");
3917        assert!(capability.contains("Cloudflare"), "{capability}");
3918        assert!(
3919            capability.contains("`<worker>-idempotency`"),
3920            "{capability}"
3921        );
3922        assert!(
3923            capability.contains("in-memory") && capability.contains("Node and in the browser"),
3924            "{capability}"
3925        );
3926        for op in ["dedup", "remember", "claim"] {
3927            let hover =
3928                describe_firstparty_symbol(&format!("Idempotency.{op}")).unwrap_or_default();
3929            assert!(
3930                hover.contains("D1-backed on Cloudflare")
3931                    && hover.contains("in-memory on Node and in the browser"),
3932                "`{op}`: {hover}"
3933            );
3934        }
3935    }
3936
3937    #[test]
3938    fn unit_reference_spans_finds_uses_and_consumes_targets() {
3939        // Slice 6b: the clickable ranges for document links — `uses`/`consumes`
3940        // unit names, with spans covering the name (resolution is the handler's).
3941        let src = "context app.main\n  uses billing.charge\n  consumes platform.time\n";
3942        let spans = unit_reference_spans(src);
3943        let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
3944        assert!(names.contains(&"billing.charge"), "{names:?}");
3945        assert!(names.contains(&"platform.time"), "{names:?}");
3946        // The span covers exactly the unit name (so the link underlines it).
3947        let (_, span) = spans.iter().find(|(n, _)| n == "billing.charge").unwrap();
3948        assert_eq!(&src[span.start..span.end], "billing.charge");
3949    }
3950
3951    #[test]
3952    fn unit_reference_spans_links_the_suite_target() {
3953        // #609: the `suite <target>` header links to the unit under test, and any
3954        // `uses` clauses the fragment brings in link like the other unit kinds.
3955        let src = "suite todos\n  uses billing.charge\n";
3956        let spans = unit_reference_spans(src);
3957        let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
3958        assert!(names.contains(&"todos"), "{names:?}");
3959        assert!(names.contains(&"billing.charge"), "{names:?}");
3960        // The span covers exactly the target name (so the link underlines it).
3961        let (_, span) = spans.iter().find(|(n, _)| n == "todos").unwrap();
3962        assert_eq!(&src[span.start..span.end], "todos");
3963    }
3964
3965    #[test]
3966    fn doc_link_context_is_some_only_inside_a_doc_range() {
3967        let src = "---\nSee [Rat\n---\nfn f() -> Int { [1, 2] }\n";
3968        let at = src.find("Rat").unwrap() + 3;
3969        let ctx = doc_link_context(src, at).expect("in doc");
3970        assert_eq!(ctx.partial, "Rat");
3971        assert_eq!(ctx.owner, None);
3972        assert_eq!(ctx.replace_start, at - 3);
3973        assert!(!ctx.closed);
3974        assert_eq!(ctx.attached, Some(src.find("f()").unwrap()));
3975        let code = src.find("[1").unwrap() + 1;
3976        assert_eq!(doc_link_context(src, code), None);
3977    }
3978
3979    #[test]
3980    fn doc_link_context_splits_an_owner_prefix_and_sees_a_closer() {
3981        let src = "---\nSee [RateView.re]\n---\nfn f() -> Int { 1 }\n";
3982        let at = src.find(".re").unwrap() + 3;
3983        let ctx = doc_link_context(src, at).unwrap();
3984        assert_eq!(ctx.owner.as_deref(), Some("RateView"));
3985        assert_eq!(ctx.partial, "re");
3986        assert!(ctx.closed);
3987    }
3988
3989    #[test]
3990    fn doc_link_context_replaces_the_rest_of_a_word_under_the_cursor() {
3991        let src = "---\nSee [RateView] here\n---\nfn f() -> Int { 1 }\n";
3992        let at = src.find("Rat").unwrap() + 3;
3993        let ctx = doc_link_context(src, at).unwrap();
3994        assert_eq!(ctx.partial, "Rat");
3995        assert_eq!(&src[ctx.replace_start..ctx.replace_end], "RateView");
3996        assert!(ctx.closed);
3997    }
3998
3999    #[test]
4000    fn doc_link_context_is_none_in_a_fenced_block_and_after_a_bare_dot() {
4001        let fenced = "---\n```\nlet v = xs[\n```\n---\nfn f() -> Int { 1 }\n";
4002        let at = fenced.find("xs[").unwrap() + 3;
4003        assert_eq!(doc_link_context(fenced, at), None);
4004        let dot = "---\nSee [.foo\n---\nfn f() -> Int { 1 }\n";
4005        let at = dot.find(".foo").unwrap() + 4;
4006        assert_eq!(doc_link_context(dot, at), None);
4007    }
4008
4009    #[test]
4010    fn doc_link_context_is_none_after_a_closed_or_broken_bracket() {
4011        let src = "---\nSee [Done] and x\n---\nfn f() -> Int { 1 }\n";
4012        let at = src.find(" and").unwrap() + 4;
4013        assert_eq!(doc_link_context(src, at), None);
4014    }
4015
4016    #[test]
4017    fn doc_link_context_works_on_a_doc_line() {
4018        let src = "--| See [Li\nfn f() -> Int { 1 }\n";
4019        let at = src.find("Li").unwrap() + 2;
4020        assert_eq!(doc_link_context(src, at).unwrap().partial, "Li");
4021    }
4022
4023    #[test]
4024    fn scan_doc_link_candidates_finds_a_bare_shortcut() {
4025        let cands = scan_doc_link_candidates("See [Limiter] for details.");
4026        assert_eq!(cands.len(), 1);
4027        assert_eq!(cands[0].name, "Limiter");
4028        assert_eq!(cands[0].display, "Limiter");
4029        assert_eq!(
4030            &"See [Limiter] for details."[cands[0].span.clone()],
4031            "[Limiter]"
4032        );
4033    }
4034
4035    #[test]
4036    fn scan_doc_link_candidates_finds_a_dotted_shortcut() {
4037        let cands = scan_doc_link_candidates("See [RateView.remaining].");
4038        assert_eq!(cands.len(), 1);
4039        assert_eq!(cands[0].name, "RateView.remaining");
4040    }
4041
4042    #[test]
4043    fn scan_doc_link_candidates_finds_a_code_span_shortcut() {
4044        let text = "The [`RateView.remaining`] field is never negative.";
4045        let cands = scan_doc_link_candidates(text);
4046        assert_eq!(cands.len(), 1);
4047        assert_eq!(cands[0].name, "RateView.remaining");
4048        assert_eq!(cands[0].display, "`RateView.remaining`");
4049        assert_eq!(&text[cands[0].span.clone()], "[`RateView.remaining`]");
4050    }
4051
4052    #[test]
4053    fn scan_doc_link_candidates_finds_a_full_reference() {
4054        let cands = scan_doc_link_candidates("See [the limiter][Limiter] for details.");
4055        assert_eq!(cands.len(), 1);
4056        assert_eq!(cands[0].name, "Limiter");
4057        assert_eq!(cands[0].display, "the limiter");
4058    }
4059
4060    #[test]
4061    fn scan_doc_link_candidates_leaves_an_explicit_url_untouched() {
4062        let cands = scan_doc_link_candidates("See [Limiter](https://example.com).");
4063        assert!(cands.is_empty(), "{cands:?}");
4064    }
4065
4066    #[test]
4067    fn scan_doc_link_candidates_leaves_an_author_defined_reference_untouched() {
4068        let text = "See [foo] for details.\n\n[foo]: https://example.com\n";
4069        let cands = scan_doc_link_candidates(text);
4070        assert!(cands.is_empty(), "{cands:?}");
4071    }
4072
4073    #[test]
4074    fn scan_doc_link_candidates_ignores_non_identifier_bracket_content() {
4075        let cands = scan_doc_link_candidates("See [see note] and [1] below.");
4076        assert!(cands.is_empty(), "{cands:?}");
4077    }
4078
4079    #[test]
4080    fn scan_doc_link_candidates_ignores_fenced_code_block_content() {
4081        let text = "Example:\n```\n[Bracket, Syntax]\n[label]: not-a-real-def\n```\nSee [Limiter].";
4082        let cands = scan_doc_link_candidates(text);
4083        assert_eq!(cands.len(), 1);
4084        assert_eq!(cands[0].name, "Limiter");
4085    }
4086
4087    #[test]
4088    fn scan_doc_link_candidates_does_not_recognise_the_collapsed_reference_form() {
4089        // `[label][]` (CommonMark's "collapsed reference") is deliberately out
4090        // of scope this increment — use the shortcut form `[label]` instead.
4091        let cands = scan_doc_link_candidates("See [Limiter][].");
4092        assert!(cands.is_empty(), "{cands:?}");
4093    }
4094
4095    #[test]
4096    fn doc_link_spans_reports_absolute_offsets_in_an_indented_doc_block() {
4097        let src = "context app.main\n  ---\n  See [Limiter] here.\n  ---\n  service api {}\n";
4098        let spans = doc_link_spans(src);
4099        assert_eq!(spans.len(), 1);
4100        let (name, span) = &spans[0];
4101        assert_eq!(name, "Limiter");
4102        assert_eq!(&src[span.start..span.end], "[Limiter]");
4103    }
4104
4105    /// #1888: a `--|` doc line links too, at its absolute offset.
4106    #[test]
4107    fn doc_link_spans_finds_links_in_doc_lines() {
4108        let src = "--- Wraps a [Foo].\n--- And a [Bar].\ntype Baz = Int\n";
4109        let spans = doc_link_spans(src);
4110        let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
4111        assert_eq!(names, vec!["Foo", "Bar"]);
4112        assert_eq!(&src[spans[1].1.start..spans[1].1.end], "[Bar]");
4113    }
4114
4115    #[test]
4116    fn doc_link_spans_finds_links_across_multiple_doc_blocks() {
4117        let src = "---\nSee [Foo].\n---\ntype Foo = Int\n\n---\nSee [Bar].\n---\ntype Bar = Int\n";
4118        let spans = doc_link_spans(src);
4119        let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
4120        assert_eq!(names, vec!["Foo", "Bar"]);
4121    }
4122
4123    #[test]
4124    fn own_declaration_name_finds_context_and_commons_names() {
4125        // #302: the rename target when a unit's own file moves.
4126        let src = "context app.main\n  uses billing.charge\n";
4127        let (name, span) = own_declaration_name(src).expect("context has its own name");
4128        assert_eq!(name, "app.main");
4129        assert_eq!(&src[span.start..span.end], "app.main");
4130
4131        let src = "commons app.util\n\ntype Foo = Int where Positive\n";
4132        let (name, _) = own_declaration_name(src).expect("commons has its own name");
4133        assert_eq!(name, "app.util");
4134    }
4135
4136    #[test]
4137    fn own_declaration_name_none_for_suites() {
4138        // A suite's `SourceUnit::name()` is its *target*'s name, not its own —
4139        // nothing `uses`/`consumes` a suite by name, so renaming its file
4140        // needs no declaration rewrite.
4141        let src = "suite todos\n";
4142        assert!(own_declaration_name(src).is_none());
4143    }
4144
4145    // v0.123 (slice 2): hover renders the real shape of each declaration —
4146    // record fields, sum variants, the refined `where`, the opaque base.
4147    #[test]
4148    fn describe_type_renders_fields_variants_and_refinements() {
4149        let record = describe_symbol(
4150            "commons demo.m\n\ntype Order = {\n  id: OrderId,\n  total: Money,\n}\n",
4151            "Order",
4152        )
4153        .unwrap();
4154        assert!(record.contains("type Order = {"), "{record}");
4155        assert!(record.contains("id: OrderId"), "{record}");
4156        assert!(record.contains("total: Money"), "{record}");
4157
4158        let sum = describe_symbol(
4159            "commons demo.m\n\ntype Status = enum { Pending, Shipped }\n",
4160            "Status",
4161        )
4162        .unwrap();
4163        assert!(sum.contains("enum {"), "{sum}");
4164        assert!(sum.contains("Pending") && sum.contains("Shipped"), "{sum}");
4165
4166        let refined = describe_symbol(
4167            "commons demo.m\n\ntype Email = String where NonEmpty\n",
4168            "Email",
4169        )
4170        .unwrap();
4171        assert!(
4172            refined.contains("type Email = String where NonEmpty"),
4173            "{refined}"
4174        );
4175
4176        let opaque =
4177            describe_symbol("commons demo.m\n\ntype Token = opaque String\n", "Token").unwrap();
4178        assert!(opaque.contains("type Token = opaque String"), "{opaque}");
4179    }
4180
4181    // v0.123 (slice 2): a function's `requires`/`ensures` contracts render
4182    // beneath its signature.
4183    #[test]
4184    fn describe_fn_renders_contracts() {
4185        let src = "commons demo.m\n\nfn discount(p: Int, pct: Int) -> Int\n  requires p_nonneg: p >= 0\n  ensures never_negative: result >= 0\n{\n  p\n}\n";
4186        let out = describe_symbol(src, "discount").unwrap();
4187        assert!(
4188            out.contains("fn discount(p: Int, pct: Int) -> Int"),
4189            "{out}"
4190        );
4191        assert!(out.contains("requires p_nonneg: p >= 0"), "{out}");
4192        assert!(out.contains("ensures never_negative: result >= 0"), "{out}");
4193    }
4194
4195    // Constrained generics slice 0: hover shows a generic's declared bounds and
4196    // a method's `where` clause.
4197    #[test]
4198    fn describe_fn_renders_bounds_and_where() {
4199        let src = "commons demo.m\n\ntype Box[A] = { value: A }\n\nfn same[T: Eq, U](a: T, b: T, u: U) -> Bool { a == b }\n\nfn Box.has(self, x: A) -> Bool where A: Eq { self.value == x }\n";
4200        let out = describe_symbol(src, "same").unwrap();
4201        assert!(
4202            out.contains("fn same[T: Eq, U](a: T, b: T, u: U) -> Bool"),
4203            "{out}"
4204        );
4205        let method = describe_symbol(src, "Box.has").unwrap();
4206        assert!(
4207            method.contains("fn Box.has(self, x: A) -> Bool where A: Eq"),
4208            "{method}"
4209        );
4210        let ty =
4211            describe_symbol("commons demo.m\n\ntype Pair[T: Eq] = { a: T }\n", "Pair").unwrap();
4212        assert!(ty.contains("type Pair[T: Eq] = "), "{ty}");
4213    }
4214
4215    // Constrained generics slice 0: every constraint name in a bound is a token
4216    // span — a `fn`'s, a `type`'s and a method's `where` entries — and a bare
4217    // parameter has none.
4218    #[test]
4219    fn constraint_token_spans_cover_every_bound() {
4220        let src = "commons demo.m\n\ntype P[T: Eq] = { a: T }\n\nfn f[T: Eq + Eq, U](a: T, u: U) -> T { a }\n\nfn P.g(self) -> Int where T: Eq { 0 }\n";
4221        let names: Vec<&str> = constraint_token_spans(src)
4222            .into_iter()
4223            .map(|s| &src[s.start..s.end])
4224            .collect();
4225        assert_eq!(names, ["Eq", "Eq", "Eq", "Eq"]);
4226        assert!(constraint_token_spans("commons m\n\nfn f[T](a: T) -> T { a }\n").is_empty());
4227    }
4228
4229    // Constrained generics slice 1: a type's hover shows its `derives` clause,
4230    // a generic's signature its `Ord` bounds.
4231    #[test]
4232    fn describe_renders_derives_and_ord_bounds() {
4233        let src = "commons demo.m\n\ntype Priority = enum { Low, High } derives Ord\n\ntype Row = { a: Int } derives Ord\n\nfn top[T: Ord](xs: List[T]) -> Option[T] { None }\n\nfn both[T: Eq + Ord](a: T) -> T { a }\n\nfn Box.big(self, x: A) -> Bool where A: Ord { true }\n";
4234        let p = describe_symbol(src, "Priority").unwrap();
4235        assert!(p.contains("} derives Ord\n```"), "{p}");
4236        assert!(
4237            describe_symbol(src, "Row")
4238                .unwrap()
4239                .contains("} derives Ord")
4240        );
4241        assert!(
4242            describe_symbol(src, "top")
4243                .unwrap()
4244                .contains("fn top[T: Ord](xs: List[T]) -> Option[T]")
4245        );
4246        assert!(
4247            describe_symbol(src, "both")
4248                .unwrap()
4249                .contains("fn both[T: Eq + Ord](a: T)")
4250        );
4251        assert!(
4252            describe_symbol(src, "Box.big")
4253                .unwrap()
4254                .contains("-> Bool where A: Ord")
4255        );
4256        // No clause, no `derives`.
4257        let plain = describe_symbol("commons demo.m\n\ntype R = { a: Int }\n", "R").unwrap();
4258        assert!(!plain.contains("derives"), "{plain}");
4259    }
4260
4261    // Constrained generics slice 1: `derives` hovers as a keyword only in a
4262    // type's clause; a name that merely reads `derives` does not.
4263    #[test]
4264    fn describe_derives_at_is_the_clause_only() {
4265        let src =
4266            "commons demo.m\n\ntype P = Int derives Ord\n\nfn f(derives: Int) -> Int { derives }\n";
4267        let at = src.find("derives").unwrap();
4268        let doc = describe_derives_at(src, at).expect("hover on `derives`");
4269        assert!(
4270            doc.contains("derives Ord") && doc.contains("declaration order"),
4271            "{doc}"
4272        );
4273        assert!(describe_derives_at(src, at + 2).is_some());
4274        assert!(describe_derives_at(src, src.find("Ord").unwrap()).is_none());
4275        assert!(describe_derives_at(src, src.rfind("derives").unwrap()).is_none());
4276        assert!(describe_derives_at(src, src.find("(derives").unwrap() + 1).is_none());
4277    }
4278
4279    // Constrained generics slice 1: hover on a constraint name in a bound or a
4280    // `derives` clause explains it; a lookalike elsewhere does not.
4281    #[test]
4282    fn describe_constraint_at_explains_bounds_and_derives() {
4283        let src = "commons demo.m\n\ntype P = Int derives Ord\n\nfn f[T: Eq + Ord](a: T) -> T { a }\n\nfn Box.g(self, x: A) -> Bool where A: Ord { true }\n";
4284        let eq = describe_constraint_at(src, src.find("Eq").unwrap()).unwrap();
4285        assert!(eq.contains("constraint Eq") && eq.contains("=="), "{eq}");
4286        for (i, _) in src.match_indices("Ord") {
4287            let ord = describe_constraint_at(src, i + 1).expect("Ord hover");
4288            assert!(
4289                ord.contains("constraint Ord") && ord.contains("implies `Eq`"),
4290                "{ord}"
4291            );
4292        }
4293        assert!(describe_constraint_at(src, src.find("Int").unwrap()).is_none());
4294        assert!(describe_constraint_at(src, src.find("fn f").unwrap()).is_none());
4295    }
4296
4297    // Constrained generics slice 1: `derives Ord` names are constraint tokens.
4298    #[test]
4299    fn constraint_token_spans_cover_derives() {
4300        let src =
4301            "commons demo.m\n\ntype P = Int derives Ord\n\ntype Q[T: Ord] = { a: T } derives Ord\n";
4302        let names: Vec<&str> = constraint_token_spans(src)
4303            .into_iter()
4304            .map(|s| &src[s.start..s.end])
4305            .collect();
4306        assert_eq!(names, ["Ord", "Ord", "Ord"]);
4307        let first = constraint_token_spans(src)[0];
4308        assert!(
4309            src[..first.start].ends_with("derives "),
4310            "derives clause is the first span"
4311        );
4312    }
4313
4314    // v0.123 (slice 2): a service renders its protocol header and route lines.
4315    #[test]
4316    fn describe_service_renders_routes() {
4317        let src = "context demo.app\n\nservice greeter {\n  on call(name: String) -> Effect[String] by Caller {\n    Effect.pure(name)\n  }\n}\n";
4318        let out = describe_symbol(src, "greeter").unwrap();
4319        assert!(out.contains("service greeter {"), "{out}");
4320        assert!(out.contains("on call"), "{out}");
4321    }
4322
4323    // v0.123 (slice 2): an agent renders its store fields and the
4324    // `invariant`/`transition` step invariants.
4325    #[test]
4326    fn describe_agent_renders_store_and_invariants() {
4327        let src = "context demo.app\n\nagent Counter {\n  key id: String\n  store count: Cell[Int] = 0\n  invariant non_negative: count >= 0\n  transition monotonic: new.count >= old.count\n  on call bump() -> Effect[Result[(), String]] {\n    Ok(())\n  }\n}\n";
4328        let out = describe_symbol(src, "Counter").unwrap();
4329        assert!(out.contains("agent Counter {"), "{out}");
4330        assert!(out.contains("key id: String"), "{out}");
4331        assert!(out.contains("store count: Cell[Int]"), "{out}");
4332        assert!(out.contains("invariant non_negative: count >= 0"), "{out}");
4333        assert!(
4334            out.contains("transition monotonic: new.count >= old.count"),
4335            "{out}"
4336        );
4337    }
4338
4339    // v0.123 (slice 2, DECISION B): the `Recv.member` detection that feeds
4340    // capability-op call-site hover through `resolve_label`.
4341    #[test]
4342    fn qualified_callee_detects_upper_receiver_only() {
4343        let text = "  let t = Clock.now()";
4344        let now = text.find("now").unwrap();
4345        assert_eq!(
4346            qualified_callee_at(text, Span::new(now, now + 3)).as_deref(),
4347            Some("Clock.now")
4348        );
4349        // A lowercase (value) receiver is not our case — resolve_label can't
4350        // resolve it anyway.
4351        let text2 = "  xs.fold(0)";
4352        let fold = text2.find("fold").unwrap();
4353        assert!(qualified_callee_at(text2, Span::new(fold, fold + 4)).is_none());
4354        // A bare identifier (no receiver) → None.
4355        let text3 = "  total";
4356        assert!(qualified_callee_at(text3, Span::new(2, 7)).is_none());
4357    }
4358
4359    // v0.137.0 (ADR 0161): hover for the `key`/`store` contextual keywords and
4360    // the agent state fields they introduce — on the keyword or on the field
4361    // name alike, with a `store` field's annotations rendered.
4362    #[test]
4363    fn describe_agent_state_covers_key_store_keywords_and_fields() {
4364        let src = "context demo.app\n\nagent Sessions {\n  key id: String\n  store items: Map[String, Int] @indexed( by: id ) @bounded( 10000 )\n  on call read() -> Effect[Int] {\n    Effect.pure(0)\n  }\n}\n";
4365
4366        // The `key` keyword and the key field name both render `key id: String`
4367        // plus the contextual-keyword doc.
4368        let at_key_kw = src.find("key id").unwrap();
4369        let key_kw = describe_agent_state_at(src, at_key_kw).expect("hover on `key`");
4370        assert!(key_kw.contains("key id: String"), "{key_kw}");
4371        assert!(key_kw.contains("identity field"), "doc line: {key_kw}");
4372        let at_key_name = src.find("id: String").unwrap();
4373        let key_name = describe_agent_state_at(src, at_key_name).expect("hover on the key field");
4374        assert_eq!(key_kw, key_name, "keyword and name hover match");
4375
4376        // The `store` keyword and the store field name both render the field
4377        // signature — kind and annotations — plus the doc.
4378        let at_store_kw = src.find("store items").unwrap();
4379        let store_kw = describe_agent_state_at(src, at_store_kw).expect("hover on `store`");
4380        assert!(
4381            store_kw.contains("store items: Map[String, Int]"),
4382            "{store_kw}"
4383        );
4384        assert!(
4385            store_kw.contains("@indexed(by: id)"),
4386            "annotation: {store_kw}"
4387        );
4388        assert!(
4389            store_kw.contains("@bounded(10000)"),
4390            "annotation: {store_kw}"
4391        );
4392        assert!(
4393            store_kw.contains("persisted agent-state"),
4394            "doc line: {store_kw}"
4395        );
4396        let at_store_name = src.find("items:").unwrap();
4397        let store_name =
4398            describe_agent_state_at(src, at_store_name).expect("hover on the store field");
4399        assert_eq!(store_kw, store_name, "keyword and name hover match");
4400
4401        // Not on a `key`/`store` keyword or state-field name → no hover (the
4402        // agent name, and the store kind, both fall through to other paths).
4403        assert!(describe_agent_state_at(src, src.find("Sessions").unwrap()).is_none());
4404        assert!(describe_agent_state_at(src, src.find("Map").unwrap()).is_none());
4405        // The word `id` inside `by: id` is an annotation argument, not the key
4406        // field's declaration — it must not masquerade as the key field.
4407        assert!(describe_agent_state_at(src, src.find("by: id").unwrap() + 4).is_none());
4408    }
4409
4410    /// #611 (gap A): the reference half of the test above. Hover on a `key`/
4411    /// `store` field *use* inside the agent body — the case that resolved
4412    /// nowhere: state fields are absent from the project index and are not
4413    /// `let`/param locals, so every earlier hover path misses them.
4414    const TODOS: &str = "context demo.todos\n\
4415        \n\
4416        agent Todos {\n\
4417        \x20 key owner: String\n\
4418        \n\
4419        \x20 store items:   Map[String, Int]\n\
4420        \x20 store lastSeq: Cell[Int]\n\
4421        \n\
4422        \x20 invariant nonneg: lastSeq >= 0\n\
4423        \n\
4424        \x20 on call add(n: Int) -> Effect[()] {\n\
4425        \x20   let next = lastSeq + 1\n\
4426        \x20   let _ <- items.put(owner, next)\n\
4427        \x20   lastSeq := next\n\
4428        \x20   Effect.pure(())\n\
4429        \x20 }\n\
4430        }\n";
4431
4432    #[test]
4433    fn describe_agent_state_covers_references_in_handler_bodies() {
4434        let src = TODOS;
4435        let at = |needle: &str| src.find(needle).expect("needle is in the fixture");
4436
4437        // Every reference renders exactly what the declaration renders.
4438        let store_decl = describe_agent_state_at(src, at("store lastSeq")).unwrap();
4439        assert!(
4440            store_decl.contains("store lastSeq: Cell[Int]"),
4441            "{store_decl}"
4442        );
4443        for (what, needle) in [
4444            ("a bare read", "lastSeq + 1"),
4445            ("a `:=` write target", "lastSeq := next"),
4446            ("an invariant subject", "lastSeq >= 0"),
4447        ] {
4448            let hover = describe_agent_state_at(src, at(needle))
4449                .unwrap_or_else(|| panic!("no hover on {what}"));
4450            assert_eq!(hover, store_decl, "{what} hovers as its declaration");
4451        }
4452        // A store op's receiver — the `items` half of `items.put(…)`.
4453        let recv = describe_agent_state_at(src, at("items.put")).expect("hover on the receiver");
4454        assert_eq!(
4455            recv,
4456            describe_agent_state_at(src, at("store items")).unwrap()
4457        );
4458
4459        // The `key` field is referenceable the same way.
4460        let key_decl = describe_agent_state_at(src, at("key owner")).unwrap();
4461        let key_ref = describe_agent_state_at(src, at("owner, next")).expect("hover on `owner`");
4462        assert_eq!(key_ref, key_decl);
4463        assert!(key_ref.contains("key owner: String"), "{key_ref}");
4464
4465        // A name that is not state, and a state-shaped name outside the agent's
4466        // reference scope, both fall through to the other hover paths.
4467        assert!(describe_agent_state_at(src, at("next = lastSeq")).is_none());
4468        assert!(describe_agent_state_at(src, at("Effect.pure")).is_none());
4469    }
4470
4471    /// #611 (gap C): hover on a `store` field's operation renders the registry
4472    /// signature over the field's declared kind.
4473    #[test]
4474    fn describe_store_op_renders_the_operation_signature() {
4475        let src = TODOS;
4476        let at_put = src
4477            .find("put(owner")
4478            .expect("the store op is in the fixture");
4479        let put = describe_store_op_at(src, at_put, &[]).expect("hover on `items.put`");
4480        assert!(put.contains("put(key: K, value: V) -> Effect[()]"), "{put}");
4481        // The field's declared kind grounds `K`/`V`, so it rides along.
4482        assert!(put.contains("store items: Map[String, Int]"), "{put}");
4483
4484        // A local shadowing the receiver makes this an ordinary value method,
4485        // not a store op — mirroring the checker's by-provenance dispatch.
4486        let shadow = [bynk_check::locals::LocalBinding {
4487            name: "items".into(),
4488            def_span: Span::new(0, 5),
4489            kind: bynk_check::locals::LocalKind::Let,
4490            ty: "Map[String, Int]".into(),
4491            scope: Span::new(0, src.len()),
4492        }];
4493        assert!(describe_store_op_at(src, at_put, &shadow).is_none());
4494
4495        // An operation the kind does not have, a receiver that is not a store
4496        // field, and a non-member identifier all fall through.
4497        let cell_put = src.replace("items.put(owner, next)", "lastSeq.put(owner, next)");
4498        assert!(
4499            describe_store_op_at(&cell_put, cell_put.find("put(owner").unwrap(), &[]).is_none(),
4500            "a `Cell` has no `put`"
4501        );
4502        assert!(describe_store_op_at(src, src.find("pure(()").unwrap(), &[]).is_none());
4503        assert!(describe_store_op_at(src, src.find("next = lastSeq").unwrap(), &[]).is_none());
4504    }
4505
4506    /// A store op binds a **bare** ident receiver. A *qualified* receiver
4507    /// (`p.items.put(…)`) is an ordinary value method on a record field that
4508    /// merely shares a store field's name — the same class of confidently-wrong
4509    /// hover as gap B, and invisible to the index (which does not cover value
4510    /// methods), so nothing upstream would catch it.
4511    #[test]
4512    fn a_qualified_receiver_is_not_a_store_op_or_a_state_reference() {
4513        let src = "context demo.todos\n\
4514            \n\
4515            type Inner = { put: Int }\n\
4516            type Payload = { items: Inner, lastSeq: Int }\n\
4517            \n\
4518            agent Todos {\n\
4519            \x20 key owner: String\n\
4520            \x20 store items:   Map[String, Int]\n\
4521            \x20 store lastSeq: Cell[Int]\n\
4522            \n\
4523            \x20 on call add(p: Payload) -> Effect[()] {\n\
4524            \x20   let a = p.items.put\n\
4525            \x20   let b = p.lastSeq\n\
4526            \x20   Effect.pure(())\n\
4527            \x20 }\n\
4528            }\n";
4529        // `p.items.put` — the `put` is a field of `Inner`, not the store op.
4530        let at_put = src.find("put\n").expect("the qualified member");
4531        assert!(describe_store_op_at(src, at_put, &[]).is_none());
4532        // …and the `items` in `p.items` is a field of `Payload`, not the store
4533        // field — the same root cause, in the state-reference pass.
4534        let at_items = src.find("p.items").unwrap() + "p.".len();
4535        assert!(describe_agent_state_at(src, at_items).is_none());
4536        let at_seq = src.find("p.lastSeq").unwrap() + "p.".len();
4537        assert!(describe_agent_state_at(src, at_seq).is_none());
4538
4539        // The bare forms in the same body still resolve.
4540        let bare = src.find("store items").unwrap();
4541        assert!(describe_agent_state_at(src, bare).is_some());
4542    }
4543
4544    /// #611 (gap B): the index resolves a record-construction field label / field
4545    /// access to a `Field` key (`"Stored.title"`); hover must render it rather
4546    /// than fall through to the locals path, which name-matches in scope and
4547    /// bound `title:` to a same-named handler param.
4548    #[test]
4549    fn describe_symbol_renders_a_resolved_record_field() {
4550        let src = "context demo.todos\n\n\
4551            type Title = String where NonEmpty\n\n\
4552            type Stored = {\n\
4553            \x20 seq:   Int where NonNegative,\n\
4554            \x20 title: Title,\n\
4555            }\n";
4556        let title = describe_symbol(src, "Stored.title").expect("hover on `Stored.title`");
4557        assert!(title.contains("title: Title"), "{title}");
4558        assert!(title.contains("A field of `Stored`"), "{title}");
4559        // A field refinement rides along, as it does in the record body.
4560        let seq = describe_symbol(src, "Stored.seq").expect("hover on `Stored.seq`");
4561        assert!(seq.contains("seq: Int where NonNegative"), "{seq}");
4562
4563        // The bare type name still renders the type, not a field.
4564        assert!(
4565            describe_symbol(src, "Stored")
4566                .unwrap()
4567                .contains("type Stored")
4568        );
4569        // An unknown field, an unknown owner, and a non-record owner yield none.
4570        assert!(describe_symbol(src, "Stored.nope").is_none());
4571        assert!(describe_symbol(src, "Nope.title").is_none());
4572        assert!(describe_symbol(src, "Title.title").is_none());
4573    }
4574
4575    // #972 (Events slice 3a): an event's own hover and its per-field hover
4576    // both render a declared default, mirroring an ordinary record's hover
4577    // (above) — this is the arm that was entirely missing before this slice
4578    // (no `CommonsItem::Event` case at all), not just a formatting gap.
4579    #[test]
4580    fn describe_symbol_renders_an_event_and_its_defaulted_field() {
4581        let src = "context demo.orders\n\n\
4582            type Region = enum { Domestic, International }\n\n\
4583            event PaymentConfirmed = {\n\
4584            \x20 orderId: String,\n\
4585            \x20 region: Region = Region.Domestic,\n\
4586            }\n";
4587        let whole = describe_symbol(src, "PaymentConfirmed").expect("hover on the event itself");
4588        assert!(whole.contains("type PaymentConfirmed = {"), "{whole}");
4589        assert!(whole.contains("orderId: String"), "{whole}");
4590        assert!(
4591            whole.contains("region: Region = Region.Domestic"),
4592            "{whole}"
4593        );
4594
4595        let field = describe_symbol(src, "PaymentConfirmed.region")
4596            .expect("hover on `PaymentConfirmed.region`");
4597        assert!(
4598            field.contains("region: Region = Region.Domestic"),
4599            "{field}"
4600        );
4601        assert!(field.contains("A field of `PaymentConfirmed`"), "{field}");
4602
4603        // The non-defaulted field renders with no trailing `= ...`.
4604        let order_id = describe_symbol(src, "PaymentConfirmed.orderId")
4605            .expect("hover on `PaymentConfirmed.orderId`");
4606        assert!(order_id.contains("orderId: String"), "{order_id}");
4607        assert!(!order_id.contains('='), "{order_id}");
4608
4609        assert!(describe_symbol(src, "PaymentConfirmed.nope").is_none());
4610        assert!(describe_symbol(src, "Nope.region").is_none());
4611    }
4612
4613    // Events slice 3b (#978): a declared `@schema(N)` renders in the
4614    // event's own hover, additively — an event with none (the test above)
4615    // stays byte-identical.
4616    #[test]
4617    fn describe_symbol_renders_an_events_schema_annotation() {
4618        let src = "context demo.orders\n\n\
4619            event PaymentConfirmed @schema(2) = {\n\
4620            \x20 orderId: String,\n\
4621            }\n";
4622        let whole = describe_symbol(src, "PaymentConfirmed").expect("hover on the event itself");
4623        assert!(
4624            whole.contains("type PaymentConfirmed @schema(2) = {"),
4625            "{whole}"
4626        );
4627        assert!(whole.contains("orderId: String"), "{whole}");
4628    }
4629
4630    /// v0.166 (#616): the actor arm — both declaration forms. The reference-offset
4631    /// fixture in `hover_references.rs` covers the `Bearer` form against real
4632    /// analysis output; the schemes without config and ADR 0091's refinement form
4633    /// are declared by no example project, so they are pinned here.
4634    #[test]
4635    fn describe_symbol_renders_an_actor_in_both_forms() {
4636        let src = "context demo.auth\n\n\
4637            type UserId = String where NonEmpty\n\n\
4638            ---\n\
4639            A signed-in user.\n\
4640            ---\n\
4641            actor User { auth = Bearer(secret = \"AUTH_JWT_SECRET\"), identity = UserId }\n\n\
4642            actor Public { auth = None }\n\n\
4643            actor Worker { auth = Internal }\n\n\
4644            actor Admin = User where hasClaim(\"admin\")\n";
4645
4646        let user = describe_symbol(src, "User").expect("hover on `User`");
4647        assert!(
4648            user.contains(
4649                "actor User { auth = Bearer(secret = \"AUTH_JWT_SECRET\"), identity = UserId }"
4650            ),
4651            "{user}"
4652        );
4653        // The doc block rides along, as it does for every other declaration.
4654        assert!(user.contains("A signed-in user."), "{user}");
4655
4656        // A scheme with no config and no identity renders neither.
4657        let public = describe_symbol(src, "Public").expect("hover on `Public`");
4658        assert!(
4659            public.contains("actor Public { auth = None }") && !public.contains("identity"),
4660            "{public}"
4661        );
4662        assert!(
4663            describe_symbol(src, "Worker")
4664                .unwrap()
4665                .contains("actor Worker { auth = Internal }")
4666        );
4667
4668        // ADR 0091's refinement form renders its base and claim predicate.
4669        let admin = describe_symbol(src, "Admin").expect("hover on `Admin`");
4670        assert!(
4671            admin.contains("actor Admin = User where hasClaim(\"admin\")"),
4672            "{admin}"
4673        );
4674
4675        assert!(describe_symbol(src, "Nobody").is_none());
4676    }
4677
4678    /// v0.166 (#616, review): the actor arm claims to mirror `bynk-fmt`'s
4679    /// `format_actor`, so it must escape a scheme-config string the same way.
4680    /// `SchemeArgValue::Str` holds the value *unescaped* — the parser resolves
4681    /// `\"`/`\\`/`\n`/`\t` at lex time — so rendering it raw put invalid Bynk
4682    /// inside a ```bynk fence. Pinned against the formatter's own output rather
4683    /// than a hand-written expectation: a copy would agree only until one moved.
4684    #[test]
4685    fn describe_symbol_escapes_an_actors_scheme_config() {
4686        let src = "context demo.auth\n\n\
4687            actor User { auth = Bearer(secret = \"a\\\"b\\\\c\") }\n";
4688        let hover = describe_symbol(src, "User").expect("hover on `User`");
4689        assert!(
4690            hover.contains("actor User { auth = Bearer(secret = \"a\\\"b\\\\c\") }"),
4691            "the config value must round-trip escaped:\n{hover}"
4692        );
4693
4694        // The fenced declaration is exactly what the formatter emits for it.
4695        let formatted = bynk_fmt::format_source(src, &bynk_fmt::FormatOptions::default())
4696            .expect("the fixture formats");
4697        let actor_line = formatted
4698            .lines()
4699            .find(|l| l.starts_with("actor User"))
4700            .expect("the actor line");
4701        assert!(
4702            hover.contains(actor_line),
4703            "hover:\n{hover}\nfmt: {actor_line}"
4704        );
4705    }
4706
4707    /// v0.166 (#616): the capability-op arm, keyed `"Cap.op"` (ADR 0069) —
4708    /// attributed to its owner, as a field is to its record.
4709    #[test]
4710    fn describe_symbol_renders_a_capability_operation() {
4711        let src = "context demo.svc\n\n\
4712            capability Logger {\n\
4713            \x20 ---\n\
4714            \x20 Record a line.\n\
4715            \x20 ---\n\
4716            \x20 fn info(message: String) -> Effect[()]\n\
4717            }\n\n\
4718            capability Clock {\n\
4719            \x20 fn now() -> Effect[Int]\n\
4720            }\n";
4721
4722        let info = describe_symbol(src, "Logger.info").expect("hover on `Logger.info`");
4723        assert!(
4724            info.contains("fn info(message: String) -> Effect[()]"),
4725            "{info}"
4726        );
4727        assert!(
4728            info.contains("An operation of capability `Logger`"),
4729            "{info}"
4730        );
4731        assert!(info.contains("Record a line."), "{info}");
4732
4733        // A no-arg op on another capability — the owner is what disambiguates.
4734        let now = describe_symbol(src, "Clock.now").expect("hover on `Clock.now`");
4735        assert!(now.contains("fn now() -> Effect[Int]"), "{now}");
4736
4737        // The bare capability name still renders the capability itself.
4738        assert!(
4739            describe_symbol(src, "Logger")
4740                .unwrap()
4741                .contains("capability Logger")
4742        );
4743        // An unknown op, and an op read against the wrong owner, yield none.
4744        assert!(describe_symbol(src, "Logger.nope").is_none());
4745        assert!(describe_symbol(src, "Clock.info").is_none());
4746    }
4747
4748    #[test]
4749    fn describe_symbol_renders_a_messages_bundle() {
4750        // message-bundles slice 1 (#859): describe_item's Messages arm — a
4751        // silent hover gap before this slice (the wildcard fell through to
4752        // "no hover" for a construct that didn't exist yet).
4753        let src = "commons app.bundle\n\n\
4754            ---\n\
4755            The English reference bundle.\n\
4756            ---\n\
4757            messages \"en\" @reference {\n\
4758            \x20 \"greeting\" => \"Hello, {name}!\"\n\
4759            \x20 \"farewell\" => \"Bye\"\n\
4760            }\n";
4761
4762        let info = describe_symbol(src, "en").expect("hover on the `en` messages tag");
4763        assert!(info.contains("messages \"en\" @reference {"), "{info}");
4764        assert!(info.contains("\"greeting\" => …"), "{info}");
4765        assert!(info.contains("\"farewell\" => …"), "{info}");
4766        assert!(info.contains("The English reference bundle."), "{info}");
4767    }
4768
4769    /// v0.166 (#616, ADR 0191 D2): a bare key names a *free* function. Matching a
4770    /// method on its bare name answered with whichever type declared it first —
4771    /// `Gauge.bump`'s own declaration rendered `Counter.bump` — and silently
4772    /// outranked the index's real answer.
4773    #[test]
4774    fn describe_symbol_keys_methods_by_their_compound_name_only() {
4775        let src = "context demo.shop\n\n\
4776            type Counter = { count: Int }\n\
4777            type Gauge = { level: Int }\n\n\
4778            fn Counter.bump(self) -> Counter { Counter { count: self.count + 1 } }\n\n\
4779            fn Gauge.bump(self) -> Gauge { Gauge { level: self.level + 1 } }\n\n\
4780            fn free(n: Int) -> Int { n }\n";
4781
4782        // The type prefix is the identity: each compound key renders its own.
4783        let counter = describe_symbol(src, "Counter.bump").expect("hover on `Counter.bump`");
4784        assert!(
4785            counter.contains("fn Counter.bump(self) -> Counter") && !counter.contains("Gauge"),
4786            "{counter}"
4787        );
4788        let gauge = describe_symbol(src, "Gauge.bump").expect("hover on `Gauge.bump`");
4789        assert!(
4790            gauge.contains("fn Gauge.bump(self) -> Gauge") && !gauge.contains("Counter"),
4791            "{gauge}"
4792        );
4793
4794        // A bare `bump` names no method: it is a guess between the two, and the
4795        // index's compound key is what resolves them.
4796        assert!(describe_symbol(src, "bump").is_none());
4797        // A free function is still keyed by its bare name.
4798        assert!(
4799            describe_symbol(src, "free")
4800                .unwrap()
4801                .contains("fn free(n: Int) -> Int")
4802        );
4803        assert!(describe_symbol(src, "Counter.nope").is_none());
4804    }
4805
4806    // v0.122 (slice 1): `self` hover renders its receiver/agent type, reading
4807    // the type from `expr_types` and un-synthesising the agent-self record.
4808    #[test]
4809    fn describe_self_renders_receiver_and_unwraps_agent() {
4810        use bynk_check::checker::{NamedKind, Ty, Types};
4811        let text = "self";
4812        let tys = &Types::new();
4813        let span = Span::new(0, 4);
4814        // A method receiver — a plain named type renders verbatim.
4815        let account = vec![(
4816            span,
4817            tys.intern(Ty::Named {
4818                name: "Account".into(),
4819                kind: NamedKind::Record,
4820                args: Vec::new(),
4821            }),
4822        )];
4823        assert_eq!(
4824            describe_self_at(text, 0, &account, tys).as_deref(),
4825            Some("```bynk\nself: Account\n```")
4826        );
4827        // An agent handler — the synthetic `__CounterSelf` record un-synthesises
4828        // to the agent name.
4829        let agent = vec![(
4830            span,
4831            tys.intern(Ty::Named {
4832                name: "__CounterSelf".into(),
4833                kind: NamedKind::Record,
4834                args: Vec::new(),
4835            }),
4836        )];
4837        assert_eq!(
4838            describe_self_at(text, 0, &agent, tys).as_deref(),
4839            Some("```bynk\nself: Counter\n```")
4840        );
4841        // Not on the `self` keyword — a different token yields nothing, even
4842        // when a type sits at the offset.
4843        let other = "total";
4844        assert!(
4845            describe_self_at(
4846                other,
4847                0,
4848                &[(
4849                    Span::new(0, 5),
4850                    tys.intern(Ty::Named {
4851                        name: "Int".into(),
4852                        kind: NamedKind::Record,
4853                        args: Vec::new(),
4854                    }),
4855                )],
4856                tys
4857            )
4858            .is_none()
4859        );
4860    }
4861
4862    const CACHE_SVC: &str = "context api\nservice api from http {\n  @cache(maxAge: 5.minutes, scope: public)\n  on GET(\"/x\") () -> Effect[HttpResult[String]] by v: Visitor {\n    Ok(\"y\")\n  }\n}\n";
4863
4864    #[test]
4865    fn an_edge_cache_hovers_with_its_stanza() {
4866        // L7 (#2414): what declaring the instance switches on.
4867        let src =
4868            "context a\nconsumes bynk.cloudflare { EdgeCache }\ncapability Edge = EdgeCache\n";
4869        let tokens = tokenize(src).unwrap();
4870        let (unit, _) = parse_unit_with_recovery(&tokens, src);
4871        let Some(SourceUnit::Context(ctx)) = unit else {
4872            panic!("a context")
4873        };
4874        let decl = ctx
4875            .items
4876            .iter()
4877            .find_map(|i| match i {
4878                CommonsItem::Capability(c) => Some(c),
4879                _ => None,
4880            })
4881            .unwrap();
4882        let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4883        assert!(hover.contains("Emits `[cache] enabled = true`"), "{hover}");
4884        assert!(!hover.contains("its own storage"), "{hover}");
4885    }
4886
4887    #[test]
4888    fn a_queue_producer_hovers_with_its_stanza() {
4889        // P2 (#2578): the queue it sends to, as the stanza names it.
4890        let src = "context a\nconsumes bynk.cloudflare { Queue }\ncapability OrderEvents = Queue @name(\"order-events\")\n";
4891        let tokens = tokenize(src).unwrap();
4892        let (unit, _) = parse_unit_with_recovery(&tokens, src);
4893        let Some(SourceUnit::Context(ctx)) = unit else {
4894            panic!("a context")
4895        };
4896        let decl = ctx
4897            .items
4898            .iter()
4899            .find_map(|i| match i {
4900                CommonsItem::Capability(c) => Some(c),
4901                _ => None,
4902            })
4903            .unwrap();
4904        let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4905        assert!(
4906            hover.contains("Emits `[[queues.producers]]` sending to queue `order-events`"),
4907            "{hover}"
4908        );
4909    }
4910
4911    #[test]
4912    fn an_analytics_dataset_hovers_with_its_stanza() {
4913        // P3b (#2582): how the dataset is named, since the source never says.
4914        let src =
4915            "context a\nconsumes bynk.cloudflare { Analytics }\ncapability Signups = Analytics\n";
4916        let tokens = tokenize(src).unwrap();
4917        let (unit, _) = parse_unit_with_recovery(&tokens, src);
4918        let Some(SourceUnit::Context(ctx)) = unit else {
4919            panic!("a context")
4920        };
4921        let decl = ctx
4922            .items
4923            .iter()
4924            .find_map(|i| match i {
4925                CommonsItem::Capability(c) => Some(c),
4926                _ => None,
4927            })
4928            .unwrap();
4929        let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4930        assert!(
4931            hover.contains("Emits `[[analytics_engine_datasets]]`")
4932                && hover.contains("shop_cart_signups"),
4933            "{hover}"
4934        );
4935    }
4936
4937    #[test]
4938    fn a_rate_limiter_hovers_with_its_stanza() {
4939        // P3 (#2342): the emitted limit and window, and the counting caveat.
4940        let src = "context a\nconsumes bynk.cloudflare { RateLimit }\ncapability LoginLimit = RateLimit @limit(20) @period(1.minute)\n";
4941        let tokens = tokenize(src).unwrap();
4942        let (unit, _) = parse_unit_with_recovery(&tokens, src);
4943        let Some(SourceUnit::Context(ctx)) = unit else {
4944            panic!("a context")
4945        };
4946        let decl = ctx
4947            .items
4948            .iter()
4949            .find_map(|i| match i {
4950                CommonsItem::Capability(c) => Some(c),
4951                _ => None,
4952            })
4953            .unwrap();
4954        let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4955        assert!(
4956            hover.contains(
4957                "`simple = { limit = 20, period = 60 }`: 20 calls per key every 60 seconds"
4958            ),
4959            "{hover}"
4960        );
4961        assert!(hover.contains("approximate"), "{hover}");
4962    }
4963
4964    #[test]
4965    fn hover_on_cache_annotation_describes_it() {
4966        // Offset on the `cache` name token.
4967        let offset = CACHE_SVC.find("cache").unwrap() + 1;
4968        let hover = describe_handler_annotation_at(CACHE_SVC, offset).expect("hovers @cache");
4969        assert!(hover.contains("`@cache`"), "names the annotation: {hover}");
4970        assert!(hover.contains("maxAge"), "documents maxAge: {hover}");
4971        assert!(hover.contains("scope"), "documents scope: {hover}");
4972        assert!(hover.contains("immutable"), "documents immutable: {hover}");
4973        assert!(
4974            hover.contains("Emits `Cache-Control: public, max-age=300`."),
4975            "shows the emitted header: {hover}"
4976        );
4977        // Off the annotation (on the `Ok` body) — no annotation hover.
4978        let ok_offset = CACHE_SVC.find("Ok(").unwrap() + 1;
4979        assert!(describe_handler_annotation_at(CACHE_SVC, ok_offset).is_none());
4980    }
4981
4982    #[test]
4983    fn hover_on_immutable_cache_shows_the_directive() {
4984        let svc = "context api\nservice api from http {\n  @cache(maxAge: 365.days, scope: public, immutable: true)\n  on GET(\"/x\") () -> Effect[HttpResult[String]] by v: Visitor {\n    Ok(\"y\")\n  }\n}\n";
4985        let hover = describe_handler_annotation_at(svc, svc.find("cache").unwrap() + 1)
4986            .expect("hovers @cache");
4987        assert!(
4988            hover.contains("Emits `Cache-Control: public, max-age=31536000, immutable`."),
4989            "{hover}"
4990        );
4991    }
4992
4993    #[test]
4994    fn hover_on_form_annotation_shows_the_decoding_rule_and_effective_cap() {
4995        let svc = "context api\ntype Q = { q: String }\nservice api from http {\n  limits { maxBody: 4096 }\n  @form\n  on POST(\"/s\") (body: Q) -> Effect[HttpResult[String]] by v: Visitor {\n    Ok(body.q)\n  }\n}\n";
4996        let hover = describe_handler_annotation_at(svc, svc.find("form").unwrap() + 1)
4997            .expect("hovers @form");
4998        assert!(hover.contains("`@form`"), "names the annotation: {hover}");
4999        assert!(
5000            hover.contains("application/x-www-form-urlencoded"),
5001            "{hover}"
5002        );
5003        assert!(
5004            hover.contains("`415"),
5005            "says the other-type answer: {hover}"
5006        );
5007        assert!(
5008            hover.contains("4096 bytes"),
5009            "shows the service cap: {hover}"
5010        );
5011    }
5012
5013    #[test]
5014    fn hover_on_multipart_annotation_shows_the_rules_and_effective_cap() {
5015        let svc = "context api\nconsumes bynk { File }\ntype Q = { f: File }\nservice api from http {\n  limits { maxBody: 4096 }\n  @multipart\n  on POST(\"/s\") (body: Q) -> Effect[HttpResult[String]] by v: Visitor {\n    Ok(\"x\")\n  }\n}\n";
5016        let hover = describe_handler_annotation_at(svc, svc.find("multipart").unwrap() + 1)
5017            .expect("hovers @multipart");
5018        assert!(
5019            hover.contains("`@multipart`"),
5020            "names the annotation: {hover}"
5021        );
5022        assert!(hover.contains("multipart/form-data"), "{hover}");
5023        assert!(hover.contains("MalformedForm"), "{hover}");
5024        assert!(
5025            hover.contains("4096 bytes"),
5026            "shows the service cap: {hover}"
5027        );
5028    }
5029
5030    #[test]
5031    fn hover_on_raw_annotation_shows_content_type_and_effective_cap() {
5032        let svc = "context api\nservice api from http {\n  limits { maxBody: 1000 }\n  @raw(contentType: \"image/png\")\n  on POST(\"/a\") (body: Bytes) -> Effect[HttpResult[String]] by v: Visitor {\n    Ok(\"y\")\n  }\n  @raw(contentType: \"*/*\")\n  @limit(maxBody: 50)\n  on POST(\"/b\") (body: Bytes) -> Effect[HttpResult[String]] by v: Visitor {\n    Ok(\"y\")\n  }\n}\n";
5033        let first =
5034            describe_handler_annotation_at(svc, svc.find("raw").unwrap() + 1).expect("hovers @raw");
5035        assert!(first.contains("`image/png`"), "names the type: {first}");
5036        assert!(first.contains("1000 bytes"), "service cap: {first}");
5037        let second = describe_handler_annotation_at(svc, svc.rfind("raw").unwrap() + 1)
5038            .expect("hovers @raw");
5039        assert!(second.contains("any"), "wildcard: {second}");
5040        assert!(second.contains("50 bytes"), "the route's own cap: {second}");
5041    }
5042
5043    #[test]
5044    fn annotation_token_spans_cover_name_and_labels() {
5045        let spans = handler_annotation_token_spans(CACHE_SVC);
5046        // `@cache` + the two argument labels `maxAge`/`scope`.
5047        assert_eq!(spans.len(), 3, "{spans:?}");
5048        let texts: Vec<&str> = spans.iter().map(|s| &CACHE_SVC[s.start..s.end]).collect();
5049        assert_eq!(texts, ["@cache", "maxAge", "scope"]);
5050        // A service with no annotations yields nothing.
5051        let plain = "context api\nservice api from http {\n  on GET(\"/x\") () -> Effect[HttpResult[String]] by v: Visitor { Ok(\"y\") }\n}\n";
5052        assert!(handler_annotation_token_spans(plain).is_empty());
5053    }
5054
5055    #[test]
5056    fn scan_doc_link_candidates_accepts_a_multi_segment_unit_path() {
5057        let cands = scan_doc_link_candidates("See [a.b.Name] and [e.g.] and [x. y].");
5058        let names: Vec<_> = cands.iter().map(|c| c.name.as_str()).collect();
5059        assert_eq!(names, ["a.b.Name"]);
5060    }
5061
5062    #[test]
5063    fn doc_link_spans_attached_reports_the_next_identifier() {
5064        let src = "--- the [x] param\nfn f(x: Int) -> Int { x }\n";
5065        let links = doc_link_spans_attached(src);
5066        assert_eq!(links.len(), 1);
5067        assert_eq!(links[0].attached, Some(src.find("f(").unwrap()));
5068    }
5069
5070    #[test]
5071    fn doc_link_spans_attached_puts_a_method_at_its_name() {
5072        let src = "--- the [x] param\nfn Box.plus(self, x: Int) -> Int { x }\n";
5073        let links = doc_link_spans_attached(src);
5074        assert_eq!(links[0].attached, Some(src.find("plus").unwrap()));
5075    }
5076
5077    #[test]
5078    fn doc_link_unit_names_a_suites_target() {
5079        let src = "suite window\n";
5080        assert_eq!(own_declaration_name(src), None);
5081        assert_eq!(doc_link_unit(src).as_deref(), Some("window"));
5082    }
5083}
5084
5085#[cfg(test)]
5086mod snapshot_tests {
5087    use super::*;
5088
5089    const SUITE: &str = "suite shape\n\ncase \"reads\" {\n  expect read(1) matches snapshot \"first\"\n  let matches = 1\n}\n";
5090
5091    /// #2842: the contextual words are keyword tokens only inside a claim.
5092    #[test]
5093    fn the_words_of_a_claim_are_keyword_spans() {
5094        let words: Vec<&str> = snapshot_keyword_spans(SUITE)
5095            .into_iter()
5096            .map(|s| &SUITE[s.start..s.end])
5097            .collect();
5098        assert_eq!(words, ["matches", "snapshot"]);
5099    }
5100
5101    #[test]
5102    fn hover_shows_the_stored_snapshot_or_says_it_is_missing() {
5103        let at = SUITE.find("snapshot \"first\"").unwrap();
5104        let stored = r#"{"reads":{"first":{"id":"a"}}}"#;
5105        let with = describe_snapshot_at(SUITE, at, Some(stored)).expect("hovers");
5106        assert!(
5107            with.contains("Stored:") && with.contains("\"id\": \"a\""),
5108            "{with}"
5109        );
5110        let without = describe_snapshot_at(SUITE, at, None).expect("hovers");
5111        assert!(without.contains("Not yet recorded"), "{without}");
5112        // A binding named `matches` is an ordinary name.
5113        let other = SUITE.rfind("matches").unwrap();
5114        assert!(describe_snapshot_at(SUITE, other, None).is_none());
5115    }
5116}