1use std::collections::BTreeMap;
7
8use serde::Serialize;
9
10use crate::core::property_graph::{CodeGraph, EdgeKind};
11
12use super::evidence::{EdgeEvidence, EvidenceGrade};
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
16pub struct GradeCounts {
17 pub verified: usize,
18 pub resolved: usize,
19 pub heuristic: usize,
20 pub unannotated: usize,
22}
23
24impl GradeCounts {
25 pub fn total(&self) -> usize {
26 self.verified + self.resolved + self.heuristic + self.unannotated
27 }
28
29 pub fn verified_percent(&self) -> usize {
31 (self.verified * 100).checked_div(self.total()).unwrap_or(0)
32 }
33}
34
35pub fn coverage_by_language(graph: &CodeGraph) -> BTreeMap<&'static str, GradeCounts> {
38 let mut out: BTreeMap<&'static str, GradeCounts> = BTreeMap::new();
39 for (source, _, metadata) in graph
40 .file_edges_of_kind(&EdgeKind::Calls)
41 .unwrap_or_default()
42 {
43 let Some(lang) = crate::core::language_capabilities::language_for_path(&source) else {
44 continue;
45 };
46 let counts = out.entry(lang.id_str()).or_default();
47 match EdgeEvidence::from_metadata(metadata.as_deref()).map(|e| e.grade) {
48 Some(EvidenceGrade::VerifiedSemantic) => counts.verified += 1,
49 Some(EvidenceGrade::ResolvedStructural) => counts.resolved += 1,
50 Some(EvidenceGrade::HeuristicStructural) => counts.heuristic += 1,
51 None => counts.unannotated += 1,
52 }
53 }
54 out
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
59pub struct ServerStatus {
60 pub binary: String,
62 pub runnable: bool,
65 #[serde(skip_serializing_if = "Option::is_none")]
67 pub install_hint: Option<&'static str>,
68}
69
70pub fn server_status(language: &str, project_root: &str) -> Option<ServerStatus> {
75 let default = crate::lsp::config::default_servers()
76 .remove(language)?
77 .command;
78 let resolved = resolved_binary_cached(language, project_root);
79 let hint_lang = if language == "javascript" {
81 "typescript"
82 } else {
83 language
84 };
85 Some(ServerStatus {
86 install_hint: resolved
87 .is_none()
88 .then(|| crate::lsp::config::install_hint_for_language(hint_lang)),
89 runnable: resolved.is_some(),
90 binary: resolved.unwrap_or(default),
91 })
92}
93
94fn resolved_binary_cached(language: &str, project_root: &str) -> Option<String> {
98 use std::collections::HashMap;
99 use std::sync::{LazyLock, Mutex, PoisonError};
100 use std::time::{Duration, Instant};
101 type Key = (String, String);
102 static CACHE: LazyLock<Mutex<HashMap<Key, (Option<String>, Instant)>>> =
103 LazyLock::new(|| Mutex::new(HashMap::new()));
104 const TTL: Duration = Duration::from_mins(1);
105
106 let key = (language.to_string(), project_root.to_string());
107 if let Some((binary, at)) = CACHE
108 .lock()
109 .unwrap_or_else(PoisonError::into_inner)
110 .get(&key)
111 && at.elapsed() < TTL
112 {
113 return binary.clone();
114 }
115 let binary = crate::lsp::router::standalone_server(language, project_root)
117 .ok()
118 .map(|s| s.binary_name());
119 let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner);
120 cache.retain(|_, (_, at)| at.elapsed() < TTL);
121 cache.insert(key, (binary.clone(), Instant::now()));
122 binary
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
130pub struct NegotiatedBackend {
131 pub identity: String,
133 pub features: Vec<String>,
135 pub missing: Vec<String>,
137}
138
139fn used_features(
141 caps: &crate::lsp::capabilities::SemanticCapabilities,
142) -> [(&'static str, bool); 4] {
143 [
144 ("definition", caps.definition),
145 ("references", caps.references),
146 ("implementations", caps.implementations),
147 ("type hierarchy", caps.type_hierarchy),
148 ]
149}
150
151fn negotiated_path() -> Option<std::path::PathBuf> {
152 crate::core::data_dir::lean_ctx_data_dir()
153 .ok()
154 .map(|d| d.join("semantic-backends.json"))
155}
156
157fn read_negotiated() -> BTreeMap<String, NegotiatedBackend> {
158 negotiated_path()
159 .and_then(|p| std::fs::read_to_string(p).ok())
160 .and_then(|t| serde_json::from_str(&t).ok())
161 .unwrap_or_default()
162}
163
164pub fn record_negotiated(language: &str, info: &crate::lsp::capabilities::SemanticBackendInfo) {
168 let (offered, absent): (Vec<_>, Vec<_>) = used_features(&info.capabilities)
169 .into_iter()
170 .partition(|(_, on)| *on);
171 let entry = NegotiatedBackend {
172 identity: info.identity(),
173 features: offered.into_iter().map(|(n, _)| n.to_string()).collect(),
174 missing: absent.into_iter().map(|(n, _)| n.to_string()).collect(),
175 };
176 if read_negotiated().get(language) == Some(&entry) {
177 return;
178 }
179 let Some(path) = negotiated_path() else {
180 return;
181 };
182 if let Some(dir) = path.parent() {
183 let _ = std::fs::create_dir_all(dir);
184 }
185 let Ok(lock) = std::fs::OpenOptions::new()
189 .create(true)
190 .truncate(false)
191 .write(true)
192 .open(path.with_extension("json.lock"))
193 else {
194 return;
195 };
196 if crate::core::file_lock::acquire_exclusive_timeout(&lock, std::time::Duration::from_secs(2))
197 .is_err()
198 {
199 return;
200 }
201 let mut all = read_negotiated();
202 if all.get(language) != Some(&entry) {
203 all.insert(language.to_string(), entry);
204 if let Ok(json) = serde_json::to_vec_pretty(&all) {
205 let _ = crate::core::atomic_fs::try_atomic_write(&path, &json, None);
206 }
207 }
208 let _ = fs2::FileExt::unlock(&lock);
209}
210
211pub fn negotiated(language: &str) -> Option<NegotiatedBackend> {
213 read_negotiated().remove(language)
214}
215
216pub fn coverage_lines(
220 coverage: &BTreeMap<&'static str, GradeCounts>,
221 project_root: &str,
222) -> Vec<String> {
223 let negotiated = read_negotiated();
224 coverage
225 .iter()
226 .map(|(lang, c)| {
227 let server = match server_status(lang, project_root) {
228 Some(s) if s.runnable => format!("{} ✓", s.binary),
229 Some(s) => format!(
230 "{} not installed ({})",
231 s.binary,
232 s.install_hint.unwrap_or("see docs")
233 ),
234 None => "no standalone server (JetBrains IDE only)".to_string(),
235 };
236 let features = negotiated
237 .get(*lang)
238 .map(|n| {
239 let mut s = format!(" · offers {}", n.features.join(", "));
240 if !n.missing.is_empty() {
241 s.push_str(&format!("; no {}", n.missing.join(", no ")));
242 }
243 s
244 })
245 .unwrap_or_default();
246 format!(
247 " {lang:<11} {}/{} verified ({}%) · {server}{features}",
248 c.verified,
249 c.total(),
250 c.verified_percent()
251 )
252 })
253 .collect()
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259 use crate::core::property_graph::Node;
260 use crate::core::semantic::EvidenceOrigin;
261
262 #[test]
263 #[allow(clippy::many_single_char_names)] fn calls_are_counted_per_caller_language_and_grade() {
265 let g = CodeGraph::open_in_memory().unwrap();
266 let id = |p: &str| g.upsert_node(&Node::file(p)).unwrap();
267 let (a, b, t, u) = (
268 id("src/a.rs"),
269 id("src/b.rs"),
270 id("web/t.ts"),
271 id("web/u.ts"),
272 );
273 let ev = |grade| EdgeEvidence::new(grade, EvidenceOrigin::Enrichment, None, 1);
274 g.upsert_edge_with_evidence(a, b, &EdgeKind::Calls, &ev(EvidenceGrade::VerifiedSemantic))
275 .unwrap();
276 g.upsert_edge_with_evidence(
277 b,
278 a,
279 &EdgeKind::Calls,
280 &ev(EvidenceGrade::HeuristicStructural),
281 )
282 .unwrap();
283 g.upsert_edge_with_evidence(
284 t,
285 u,
286 &EdgeKind::Calls,
287 &ev(EvidenceGrade::ResolvedStructural),
288 )
289 .unwrap();
290
291 let cov = coverage_by_language(&g);
292 let rust = cov["rust"];
293 assert_eq!((rust.verified, rust.heuristic, rust.total()), (1, 1, 2));
294 assert_eq!(rust.verified_percent(), 50);
295 assert_eq!(cov["typescript"].resolved, 1);
296 assert_eq!(
297 GradeCounts::default().verified_percent(),
298 0,
299 "no division by zero"
300 );
301 }
302
303 #[test]
306 fn negotiated_features_are_recorded_and_shown() {
307 use crate::lsp::capabilities::{
308 SemanticBackendInfo, SemanticBackendKind, SemanticCapabilities,
309 };
310 let _isolated = crate::core::data_dir::isolated_data_dir();
311 let info = SemanticBackendInfo {
312 kind: SemanticBackendKind::Lsp,
313 server_name: Some("rust-analyzer".into()),
314 server_version: Some("1.97.1".into()),
315 capabilities: SemanticCapabilities {
316 definition: true,
317 references: true,
318 implementations: true,
319 ..SemanticCapabilities::default()
320 },
321 utf8_positions: true,
322 };
323 record_negotiated("rust", &info);
324 let n = negotiated("rust").expect("recorded");
325 assert_eq!(n.identity, "lsp:rust-analyzer@1.97.1");
326 assert_eq!(n.missing, ["type hierarchy"]);
327 assert_eq!(negotiated("go"), None);
328
329 let coverage = BTreeMap::from([("rust", GradeCounts::default())]);
330 let line = &coverage_lines(&coverage, "/nonexistent/project")[0];
331 assert!(
332 line.ends_with("· offers definition, references, implementations; no type hierarchy"),
333 "{line}"
334 );
335
336 let langs = ["go", "python", "typescript", "java", "c", "lua"];
338 std::thread::scope(|s| {
339 for lang in langs {
340 let info = info.clone();
341 s.spawn(move || record_negotiated(lang, &info));
342 }
343 });
344 for lang in langs.iter().chain(&["rust"]) {
345 assert!(negotiated(lang).is_some(), "{lang} entry lost");
346 }
347 }
348}