bynk_ide/
capability_path.rs1use 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
16pub struct PathView<'a> {
18 pub graphs: &'a FileCapabilityPaths,
19 pub snapshots: &'a HashMap<PathBuf, String>,
21 pub project_root: &'a Path,
22 pub rel: &'a Path,
24}
25
26impl PathView<'_> {
27 pub fn graph(&self) -> Option<&CapabilityGraph> {
29 self.graphs.get(self.rel)
30 }
31
32 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 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
70fn 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
82pub 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}