Skip to main content

bynk_ide/
capability_path.rs

1//! #2469: the hover face of the checker's capability paths
2//! ([`bynk_check::capability_paths`]), shared by the language server and
3//! `bynk mcp` (#2520).
4//!
5//! Hovering a `given` entry shows the **shortest** chain from the declaration to
6//! the capability's use, each step a link to source. The language server's "Show
7//! capability path" code action reads the same [`PathView`].
8
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11
12use bynk_check::capability_paths::{CapabilityGraph, FileCapabilityPaths, PathStep};
13use bynk_syntax::span::{FileId, LineIndex, Span};
14use url::Url;
15
16/// The round's tables, positioned on one file.
17pub struct PathView<'a> {
18    pub graphs: &'a FileCapabilityPaths,
19    /// Project-relative path → analysed text, which the spans index into.
20    pub snapshots: &'a HashMap<PathBuf, String>,
21    pub project_root: &'a Path,
22    /// The cursor's file (project-relative).
23    pub rel: &'a Path,
24}
25
26impl PathView<'_> {
27    /// The graph for the cursor's file.
28    pub fn graph(&self) -> Option<&CapabilityGraph> {
29        self.graphs.get(self.rel)
30    }
31
32    /// The project-relative file a span lies in. A unit's declarations can span
33    /// several files, so a step may live in a sibling; each graph records the
34    /// checker's id for its own file, which maps ids back to paths. An id no
35    /// graph owns yields `None` (the step is dropped rather than linked to the
36    /// wrong file); a span with no file identity belongs to the cursor's file.
37    pub fn file_of(&self, id: FileId) -> Option<&Path> {
38        if id == FileId::UNKNOWN {
39            return Some(self.rel);
40        }
41        self.graphs
42            .iter()
43            .find(|(_, g)| g.file == id)
44            .map(|(p, _)| p.as_path())
45    }
46
47    pub fn text_of(&self, span: Span) -> Option<(&Path, &str)> {
48        let path = self.file_of(span.file)?;
49        Some((path, self.snapshots.get(path)?.as_str()))
50    }
51
52    /// `file://` target of `span`, with the `#L<line>,<column>` fragment VS Code's
53    /// opener reads (as intra-doc links do — `doc_link_urls::doc_link_target`).
54    pub fn link(&self, span: Span) -> Option<Url> {
55        let (path, text) = self.text_of(span)?;
56        let mut url = crate::doc_link_urls::file_url(&self.project_root.join(path))?;
57        let (line, character) = LineIndex::new(text).utf16_line_col(text, span.start);
58        url.set_fragment(Some(&format!("L{},{}", line + 1, character + 1)));
59        Some(url)
60    }
61
62    pub fn step_label(&self, step: &PathStep, capability: &str) -> String {
63        match step {
64            PathStep::Call { agent, handler, .. } => format!("{agent}.{handler}"),
65            PathStep::Use { source, .. } => source.reason(capability),
66        }
67    }
68}
69
70/// One step as a Markdown list line: the label as a link when it resolves.
71fn step_line(view: &PathView<'_>, n: usize, step: &PathStep, capability: &str) -> String {
72    let label = view.step_label(step, capability);
73    let body = match (step, view.link(step.site())) {
74        (PathStep::Call { .. }, Some(url)) => format!("calls [`{label}`]({url})"),
75        (PathStep::Call { .. }, None) => format!("calls `{label}`"),
76        (PathStep::Use { .. }, Some(url)) => format!("[{label}]({url})"),
77        (PathStep::Use { .. }, None) => label,
78    };
79    format!("{n}. {body}")
80}
81
82/// The hover Markdown section for the `given` entry at `offset`: the shortest
83/// chain, one linked step per line. `None` off an entry or when the entry
84/// reaches no use (it is unused — `bynk.given.unused_capability` says so).
85pub fn hover_section(view: &PathView<'_>, offset: usize) -> Option<String> {
86    let graph = view.graph()?;
87    let (entry, _) = graph.entry_at(offset)?;
88    let w = graph.witness(entry)?;
89    let heading = if w.path.is_direct() {
90        format!("`{}` needs `{}` directly:", w.declaration, w.capability)
91    } else {
92        format!(
93            "`{}` needs `{}` through {} call(s):",
94            w.declaration,
95            w.capability,
96            w.path.steps.len() - 1
97        )
98    };
99    let lines: Vec<String> = w
100        .path
101        .steps
102        .iter()
103        .enumerate()
104        .map(|(i, s)| step_line(view, i + 1, s, &w.capability))
105        .collect();
106    Some(format!("{heading}\n\n{}", lines.join("\n")))
107}