Skip to main content

bynk_lsp/
documentation_request.rs

1//! #847: `bynk/documentationModel` — the documentation-view custom LSP request.
2//!
3//! The second custom request in this server (after #846's `bynk/sequenceModel`),
4//! and the same posture: no `workspace/*/refresh` nudge exists for a custom
5//! method and none is needed — Tier 1 is on-demand, the client re-issues the
6//! request each time "Bynk: Show Documentation" fires (Decision D).
7//!
8//! Unlike `bynk/sequenceModel`, the request carries **no cursor position**: a
9//! documentation page is the *whole unit's* declarations, so the params are a
10//! bare `TextDocumentIdentifier`. The page was file-scoped (Decision A) until
11//! #1885, which merges every file of a multi-file unit
12//! ([`documentation_model_for`]). The wire shape is a plain serde mirror of
13//! [`bynk_ide::documentation::DocModel`], each `Span` lowered to an LSP `Range`
14//! against the committed snapshot text of the file it is in — the same
15//! convention `sequence_request`/`SerKey` use — with a per-entry `uri` naming
16//! that file (the `{uri, range}` pattern `architecture_request` uses).
17
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20
21use bynk_ide::documentation;
22use tower_lsp::lsp_types::Url;
23
24/// The `bynk/documentationModel` request payload. A bare text-document
25/// identifier — no cursor position (the page is the whole unit).
26///
27/// `rename_all = "camelCase"` is load-bearing: the client sends the LSP wire
28/// name `textDocument`, so the field must deserialize from camelCase, not the
29/// Rust `text_document`. (Without it, every request fails with a missing-field
30/// error — a wire-shape bug no direct `documentation_model_for` test would
31/// catch, only a deserialize test; see `documentation_request.rs`'s params
32/// test.)
33#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct DocumentationModelParams {
36    pub text_document: tower_lsp::lsp_types::TextDocumentIdentifier,
37}
38
39// -- Wire shape: a plain serde mirror of `bynk_ide::documentation::DocModel`,
40// -- `Span` lowered to `Range` against the committed snapshot text.
41
42#[derive(Debug, Clone, serde::Serialize)]
43pub struct WireDocModel {
44    #[serde(rename = "unitName")]
45    pub unit_name: String,
46    #[serde(rename = "unitKind")]
47    pub unit_kind: &'static str,
48    #[serde(rename = "unitDoc")]
49    pub unit_doc: Option<String>,
50    /// #2462: as [`WireDocEntry::links`], for `unit_doc`.
51    #[serde(rename = "unitLinks")]
52    pub unit_links: Vec<WireDocLink>,
53    #[serde(rename = "unitRange")]
54    pub unit_range: tower_lsp::lsp_types::Range,
55    pub entries: Vec<WireDocEntry>,
56}
57
58/// #2462: where a click on an intra-doc link goes. Resolved server-side by
59/// `resolve_doc_link_in`, so the webview only routes the click.
60#[derive(Debug, Clone, PartialEq, serde::Serialize)]
61#[serde(tag = "kind", rename_all = "camelCase")]
62pub enum WireDocLink {
63    /// The target is documented on this page: scroll to `entries[entry]`.
64    Entry { entry: usize },
65    /// Open the declaration in the editor.
66    Source {
67        uri: Url,
68        range: tower_lsp::lsp_types::Range,
69    },
70    /// An external page (opened through the host's http(s) gate): a
71    /// first-party name's entry in the Book (#2455).
72    External { href: String },
73}
74
75/// #2462: what resolving the intra-doc links on a page needs — the round's
76/// index and doc-link scope (the inputs `resolve_doc_link_in` takes).
77#[derive(Clone, Copy)]
78pub struct DocLinkContext<'a> {
79    pub index: &'a bynk_check::index::ProjectIndex,
80    pub doc_scope: &'a HashMap<String, Vec<String>>,
81    /// #2523: the round's per-file local bindings, from which a link in a
82    /// fn / handler / op's doc reads its parameters.
83    pub locals: &'a bynk_check::locals::FileLocals,
84}
85
86#[derive(Debug, Clone, serde::Serialize)]
87pub struct WireDocEntry {
88    pub name: String,
89    pub kind: &'static str,
90    pub depth: u32,
91    pub markdown: String,
92    /// #2462: the resolved targets of the intra-doc links in `markdown`;
93    /// each is spelled in the Markdown as `[text](#bynk-doc-link-N)`, `N`
94    /// indexing this list.
95    pub links: Vec<WireDocLink>,
96    pub documented: bool,
97    pub range: tower_lsp::lsp_types::Range,
98    /// #1885: the document `range` is in. Always sent: the page is merged
99    /// across a unit's files, so an entry may live in a file other than the
100    /// requested one (and a one-file unit's entries simply all name it).
101    pub uri: tower_lsp::lsp_types::Url,
102}
103
104/// #1885: the wire page for the document at `rel` (project-relative), merged
105/// across every file of its unit. The unit's files come from the round's
106/// `unit_sources` (qualified name → project-relative paths) and their text
107/// from `snapshots`; each entry's range is lowered against *its own* file and
108/// carries that file's `file://` URI, so click-to-code opens the right one.
109/// An entry whose file has no snapshot or no URI is dropped rather than sent
110/// with a wrong location. `None` for a `suite`, a file with no header, or a
111/// `rel` with no snapshot.
112pub fn documentation_model_for(
113    rel: &Path,
114    snapshots: &HashMap<PathBuf, String>,
115    unit_sources: &HashMap<String, Vec<PathBuf>>,
116    project_root: &Path,
117    links: Option<DocLinkContext<'_>>,
118) -> Option<WireDocModel> {
119    let text = snapshots.get(rel)?;
120    let siblings: Vec<(&Path, &str)> = bynk_ide::symbols::own_declaration_name(text)
121        .and_then(|(name, _)| unit_sources.get(&name))
122        .into_iter()
123        .flatten()
124        .filter_map(|p| snapshots.get(p).map(|t| (p.as_path(), t.as_str())))
125        .collect();
126    let model = documentation::documentation_model_merged((rel, text.as_str()), siblings)?;
127    // Each entry's range is lowered once, against the snapshot of the file
128    // its span is in. `placed` keeps the model entry's `(file, span)` beside
129    // its wire entry, which is where an in-page link target is looked up.
130    let mut placed: Vec<(PathBuf, bynk_syntax::span::Span)> = Vec::new();
131    let mut entries: Vec<WireDocEntry> = Vec::new();
132    for e in &model.entries {
133        let file = e.file.as_deref().unwrap_or(rel);
134        let Some(file_text) = snapshots.get(file) else {
135            continue;
136        };
137        let Ok(uri) = Url::from_file_path(project_root.join(file)) else {
138            continue;
139        };
140        placed.push((file.to_path_buf(), e.span));
141        entries.push(WireDocEntry {
142            name: e.name.clone(),
143            kind: e.kind,
144            depth: e.depth,
145            markdown: e.markdown.clone(),
146            links: Vec::new(),
147            documented: e.documented,
148            range: crate::position::span_to_range(file_text, e.span),
149            uri,
150        });
151    }
152    let mut unit_doc = model.unit_doc;
153    let mut unit_links = Vec::new();
154    if let Some(ctx) = links {
155        let linker = Linker {
156            ctx,
157            owner_unit: &model.unit_name,
158            snapshots,
159            project_root,
160            placed: &placed,
161        };
162        for (e, (file, span)) in entries.iter_mut().zip(&placed) {
163            let (markdown, links) = linker.linkify(
164                &e.markdown,
165                file,
166                Some(attached_offset(snapshots, file, span.start)),
167            );
168            e.markdown = markdown;
169            e.links = links;
170        }
171        if let Some(doc) = &unit_doc {
172            let (markdown, links) = linker.linkify(doc, rel, None);
173            unit_doc = Some(markdown);
174            unit_links = links;
175        }
176    }
177    Some(WireDocModel {
178        unit_name: model.unit_name,
179        unit_kind: model.unit_kind,
180        unit_doc,
181        unit_links,
182        unit_range: crate::position::span_to_range(text, model.unit_span),
183        entries,
184    })
185}
186
187/// #2523: the offset the editor attaches a doc comment at — the first
188/// identifier at or after the entry's span start (a handler's span starts at
189/// `on`, not at a name).
190fn attached_offset(snapshots: &HashMap<PathBuf, String>, file: &Path, start: usize) -> usize {
191    snapshots
192        .get(file)
193        .and_then(|text| bynk_syntax::lexer::tokenize(text).ok())
194        .and_then(|tokens| {
195            tokens
196                .iter()
197                .find(|t| t.span.start >= start && t.kind == bynk_syntax::lexer::TokenKind::Ident)
198                .map(|t| t.span.start)
199        })
200        .unwrap_or(start)
201}
202
203/// #2462: rewrites a block of Markdown's resolvable intra-doc links.
204struct Linker<'a> {
205    ctx: DocLinkContext<'a>,
206    owner_unit: &'a str,
207    snapshots: &'a HashMap<PathBuf, String>,
208    project_root: &'a Path,
209    /// `(file, name span)` per wire entry, index-aligned with the page.
210    placed: &'a [(PathBuf, bynk_syntax::span::Span)],
211}
212
213impl Linker<'_> {
214    /// Rewrite each resolvable candidate in `markdown` to
215    /// `[text](#bynk-doc-link-N)` and return the targets, `N`-indexed. An
216    /// unresolved candidate is left as authored (the render-only decision of
217    /// #848). The resolution is `resolve_doc_link_in`'s — the same as hover and
218    /// `documentLink`.
219    ///
220    /// #2523: `file` / `attached` are the declaration the doc is attached to
221    /// (its file and the byte offset of its name; `None` for a unit's lede, which
222    /// has no own parts and may come from a sibling file), so its own fields and
223    /// parameters link as they do in the editor.
224    fn linkify(
225        &self,
226        markdown: &str,
227        file: &Path,
228        attached: Option<usize>,
229    ) -> (String, Vec<WireDocLink>) {
230        let dc = self
231            .snapshots
232            .get(file)
233            .zip(attached)
234            .map(|(text, attached)| crate::index_queries::DocLinkContext {
235                path: file,
236                text: text.as_str(),
237                attached,
238                locals: self.ctx.locals.get(file).map_or(&[], |l| l.as_slice()),
239            });
240        let mut out = String::with_capacity(markdown.len());
241        let mut links = Vec::new();
242        let mut last = 0;
243        for cand in bynk_ide::symbols::scan_doc_link_candidates(markdown) {
244            let Some(target) = self.resolve(&cand.name, dc.as_ref()) else {
245                continue;
246            };
247            out.push_str(&markdown[last..cand.span.start]);
248            out.push_str(&format!(
249                "[{}](#bynk-doc-link-{})",
250                cand.display,
251                links.len()
252            ));
253            links.push(target);
254            last = cand.span.end;
255        }
256        out.push_str(&markdown[last..]);
257        (out, links)
258    }
259
260    /// The project's own declaration first; only when the project has none of
261    /// that spelling, the first-party Book entry (`doc_link_url`, which keeps
262    /// a project declaration shadowing a first-party name).
263    fn resolve(
264        &self,
265        name: &str,
266        dc: Option<&crate::index_queries::DocLinkContext<'_>>,
267    ) -> Option<WireDocLink> {
268        if let Some(hit) = crate::index_queries::resolve_doc_link_in(
269            self.ctx.index,
270            self.ctx.doc_scope,
271            self.owner_unit,
272            name,
273            dc,
274        )
275        .resolved()
276        {
277            return self.target(&hit.def);
278        }
279        let url = crate::symbols::doc_link_url(
280            self.ctx.index,
281            self.ctx.doc_scope,
282            self.project_root,
283            self.snapshots,
284            self.owner_unit,
285            name,
286            dc,
287        )?;
288        matches!(url.scheme(), "http" | "https").then(|| WireDocLink::External {
289            href: url.to_string(),
290        })
291    }
292
293    /// An in-page anchor when the page documents the declaration (decision A
294    /// of #2462), else the declaration in the editor.
295    fn target(&self, def: &bynk_check::index::SiteRef) -> Option<WireDocLink> {
296        if let Some(entry) = self
297            .placed
298            .iter()
299            .position(|(file, span)| *file == def.path && span.start == def.span.start)
300        {
301            return Some(WireDocLink::Entry { entry });
302        }
303        let text = self.snapshots.get(&def.path)?;
304        Some(WireDocLink::Source {
305            uri: Url::from_file_path(self.project_root.join(&def.path)).ok()?,
306            range: crate::position::span_to_range(text, def.span),
307        })
308    }
309}