Skip to main content

bynk_lsp/
capability_path.rs

1//! #2469: "why does this need `Logger`?" — the editor face of the checker's
2//! capability paths ([`bynk_check::capability_paths`]).
3//!
4//! Hovering a `given` entry shows the **shortest** chain from the declaration to
5//! the capability's use, each step a link to source. The "Show capability path"
6//! code action lists **every** chain: it carries a client-side command
7//! ([`SHOW_COMMAND`]) that opens the editor's references peek over the steps'
8//! sites. Both read the checker's recorded graph; nothing here re-derives a
9//! path from the source text, and the full set is computed on demand by
10//! [`bynk_check::capability_paths::CapabilityGraph::all_paths`] rather than stored per entry.
11//!
12//! Because the command is executed by the *client*, the action is offered only
13//! to a client that says it implements it —
14//! `experimental.capabilityPathCommand: true` in its `ClientCapabilities` — the
15//! same gate as the "Explain …" action ([`crate::explain_request`]).
16
17use bynk_syntax::span::Span;
18use tower_lsp::lsp_types::Url;
19use tower_lsp::lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Command};
20
21use crate::position::offset_to_position;
22
23/// The client-side command the code action invokes. The VS Code extension
24/// registers it (`src/capabilityPath.ts` in bynk-lang/vscode-bynk).
25pub const SHOW_COMMAND: &str = "bynk.showCapabilityPath";
26
27/// The `ClientCapabilities.experimental` key a client sets to `true` to say it
28/// implements [`SHOW_COMMAND`].
29pub const CLIENT_CAPABILITY: &str = "capabilityPathCommand";
30
31/// Whether the client advertised `experimental.capabilityPathCommand: true`.
32pub fn client_supports_command(experimental: Option<&serde_json::Value>) -> bool {
33    experimental
34        .and_then(|v| v.get(CLIENT_CAPABILITY))
35        .and_then(serde_json::Value::as_bool)
36        .unwrap_or(false)
37}
38
39pub use bynk_ide::capability_path::{PathView, hover_section};
40
41/// A location the client peeks at: a step's site.
42#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
43pub struct StepLocation {
44    pub uri: Url,
45    pub range: tower_lsp::lsp_types::Range,
46}
47
48/// The full set of chains for the entry at `offset`, flattened to the sites the
49/// peek lists (path by path, shortest first, a shared site once), with the
50/// capability, the entry's position, the number of chains, and whether the
51/// checker's cap cut the list short. [`AllPaths::by_path`] keeps each chain's
52/// own sites, a shared site repeated, so a client can mark where one path ends
53/// and the next begins (#2534).
54pub struct AllPaths {
55    pub capability: String,
56    pub entry: tower_lsp::lsp_types::Position,
57    pub paths: usize,
58    pub truncated: bool,
59    pub locations: Vec<StepLocation>,
60    /// Each chain's sites in order, shortest chain first (one per chain
61    /// counted by `paths`; a step whose file is unknown is left out).
62    pub by_path: Vec<Vec<StepLocation>>,
63}
64
65pub fn all_paths(view: &PathView<'_>, offset: usize) -> Option<AllPaths> {
66    let graph = view.graph()?;
67    let (entry, _) = graph.entry_at(offset)?;
68    let (capability, paths, truncated) = graph.all_paths(entry)?;
69    if paths.is_empty() {
70        return None;
71    }
72    let text = view.snapshots.get(view.rel)?;
73    let mut locations: Vec<StepLocation> = Vec::new();
74    let mut by_path: Vec<Vec<StepLocation>> = Vec::with_capacity(paths.len());
75    for path in &paths {
76        let mut own = Vec::with_capacity(path.steps.len());
77        for step in &path.steps {
78            let Some(loc) = location(view, step.site()) else {
79                continue;
80            };
81            if !locations.contains(&loc) {
82                locations.push(loc.clone());
83            }
84            own.push(loc);
85        }
86        // A chain none of whose sites resolve is dropped, so `by_path` and
87        // `paths` count the same chains.
88        if !own.is_empty() {
89            by_path.push(own);
90        }
91    }
92    if by_path.is_empty() {
93        return None;
94    }
95    Some(AllPaths {
96        capability,
97        entry: offset_to_position(text, entry.start),
98        paths: by_path.len(),
99        truncated,
100        locations,
101        by_path,
102    })
103}
104
105fn location(view: &PathView<'_>, span: Span) -> Option<StepLocation> {
106    let (path, text) = view.text_of(span)?;
107    let uri = Url::from_file_path(view.project_root.join(path)).ok()?;
108    let positions = crate::position::PositionMap::new(text);
109    Some(StepLocation {
110        uri,
111        range: positions.range(span),
112    })
113}
114
115/// The "Show capability path" action for the `given` entry at `offset`, or none
116/// off an entry. Its command carries `[uri, position, locations]` for the
117/// client to hand to the editor's references peek, then (#2534) `by_path`, each
118/// chain's sites with shared ones repeated, for a client that groups the peek
119/// by path; a client that reads three arguments is unaffected.
120pub fn show_action(view: &PathView<'_>, uri: &Url, offset: usize) -> Option<CodeActionOrCommand> {
121    let all = all_paths(view, offset)?;
122    let title = if all.paths == 1 {
123        format!("Show capability path for `{}`", all.capability)
124    } else {
125        format!(
126            "Show capability paths for `{}` ({}{})",
127            all.capability,
128            all.paths,
129            if all.truncated { "+" } else { "" }
130        )
131    };
132    Some(CodeActionOrCommand::CodeAction(CodeAction {
133        title: title.clone(),
134        kind: Some(CodeActionKind::QUICKFIX),
135        command: Some(Command {
136            title,
137            command: SHOW_COMMAND.to_string(),
138            arguments: Some(vec![
139                serde_json::json!(uri),
140                serde_json::json!(all.entry),
141                serde_json::json!(all.locations),
142                serde_json::json!(all.by_path),
143            ]),
144        }),
145        is_preferred: Some(false),
146        ..Default::default()
147    }))
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn the_command_needs_an_explicit_client_opt_in() {
156        assert!(!client_supports_command(None));
157        assert!(!client_supports_command(Some(&serde_json::json!({}))));
158        assert!(!client_supports_command(Some(
159            &serde_json::json!({ "capabilityPathCommand": "yes" })
160        )));
161        assert!(client_supports_command(Some(
162            &serde_json::json!({ "capabilityPathCommand": true })
163        )));
164    }
165}