logicaffeine_lsp/
flycheck.rs1use std::hash::{Hash, Hasher};
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{Mutex, OnceLock};
14
15use dashmap::DashMap;
16use lsp_types::{Diagnostic, DiagnosticSeverity, Range, Url};
17
18use logicaffeine_language::token::Span;
19
20use crate::line_index::LineIndex;
21
22pub const FLYCHECK_SOURCE: &str = "logicaffeine (rustc)";
25
26pub struct FlycheckFinding {
28 pub message: String,
29 pub suggestion: Option<String>,
30 pub span: Option<Span>,
32}
33
34pub trait FlycheckRunner: Send + Sync {
38 fn check(&self, source: &str, workspace_key: &str) -> Option<Vec<FlycheckFinding>>;
41}
42
43pub struct Flycheck {
46 runner: Box<dyn FlycheckRunner>,
47 generations: DashMap<Url, AtomicU64>,
48 results: DashMap<Url, Vec<Diagnostic>>,
49}
50
51impl Flycheck {
52 pub fn new(runner: Box<dyn FlycheckRunner>) -> Self {
53 Flycheck {
54 runner,
55 generations: DashMap::new(),
56 results: DashMap::new(),
57 }
58 }
59
60 pub fn begin_save(&self, uri: &Url) -> u64 {
63 self.generations
64 .entry(uri.clone())
65 .or_insert_with(|| AtomicU64::new(0))
66 .fetch_add(1, Ordering::SeqCst)
67 + 1
68 }
69
70 pub fn is_current(&self, uri: &Url, generation: u64) -> bool {
71 self.generations
72 .get(uri)
73 .map(|g| g.load(Ordering::SeqCst) == generation)
74 .unwrap_or(false)
75 }
76
77 pub fn clear(&self, uri: &Url) -> bool {
82 let had_findings = self.results.remove(uri).is_some();
83 if let Some(generation) = self.generations.get(uri) {
85 generation.fetch_add(1, Ordering::SeqCst);
86 }
87 had_findings
88 }
89
90 pub fn forget(&self, uri: &Url) {
91 self.results.remove(uri);
92 self.generations.remove(uri);
93 }
94
95 pub fn diagnostics_for(&self, uri: &Url) -> Vec<Diagnostic> {
97 self.results
98 .get(uri)
99 .map(|entry| entry.clone())
100 .unwrap_or_default()
101 }
102
103 pub fn run(&self, source: &str, workspace_key: &str) -> Option<Vec<FlycheckFinding>> {
105 self.runner.check(source, workspace_key)
106 }
107
108 pub fn complete(
111 &self,
112 uri: &Url,
113 generation: u64,
114 findings: Vec<FlycheckFinding>,
115 checked_text: &str,
116 interactive: &[Diagnostic],
117 ) -> Option<Vec<Diagnostic>> {
118 if !self.is_current(uri, generation) {
119 return None;
120 }
121 let diagnostics = to_diagnostics(findings, checked_text, interactive);
122 self.results.insert(uri.clone(), diagnostics.clone());
123 Some(diagnostics)
124 }
125}
126
127fn to_diagnostics(
131 findings: Vec<FlycheckFinding>,
132 checked_text: &str,
133 interactive: &[Diagnostic],
134) -> Vec<Diagnostic> {
135 let line_index = LineIndex::new(checked_text);
136 findings
137 .into_iter()
138 .map(|finding| {
139 let range = match finding.span {
140 Some(span) => Range {
141 start: line_index.position(span.start),
142 end: line_index.position(span.end),
143 },
144 None => Range::default(),
145 };
146 let mut message = finding.message;
147 if let Some(suggestion) = finding.suggestion {
148 message.push_str("\n\n");
149 message.push_str(&suggestion);
150 }
151 Diagnostic {
152 range,
153 severity: Some(DiagnosticSeverity::ERROR),
154 source: Some(FLYCHECK_SOURCE.to_string()),
155 message,
156 ..Default::default()
157 }
158 })
159 .filter(|diagnostic| {
160 !interactive.iter().any(|existing| {
161 existing.severity == Some(DiagnosticSeverity::ERROR)
162 && ranges_intersect(&existing.range, &diagnostic.range)
163 })
164 })
165 .collect()
166}
167
168fn ranges_intersect(a: &Range, b: &Range) -> bool {
169 !(a.end < b.start || b.end < a.start)
170}
171
172pub struct CargoFlycheck {
181 locks: DashMap<String, std::sync::Arc<Mutex<()>>>,
182}
183
184impl CargoFlycheck {
185 pub fn new() -> Self {
186 CargoFlycheck {
187 locks: DashMap::new(),
188 }
189 }
190}
191
192impl Default for CargoFlycheck {
193 fn default() -> Self {
194 Self::new()
195 }
196}
197
198fn cargo_available() -> bool {
199 static AVAILABLE: OnceLock<bool> = OnceLock::new();
200 *AVAILABLE.get_or_init(|| {
201 std::process::Command::new("cargo")
202 .arg("--version")
203 .output()
204 .map(|o| o.status.success())
205 .unwrap_or(false)
206 })
207}
208
209fn cache_dir_for(workspace_key: &str) -> std::path::PathBuf {
210 let mut hasher = std::collections::hash_map::DefaultHasher::new();
211 workspace_key.hash(&mut hasher);
212 std::env::temp_dir().join(format!("logicaffeine-flycheck-{:016x}", hasher.finish()))
213}
214
215impl FlycheckRunner for CargoFlycheck {
216 fn check(&self, source: &str, workspace_key: &str) -> Option<Vec<FlycheckFinding>> {
217 if !cargo_available() {
218 return None;
219 }
220 let lock = self
221 .locks
222 .entry(workspace_key.to_string())
223 .or_insert_with(|| std::sync::Arc::new(Mutex::new(())))
224 .clone();
225 let _guard = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
226
227 let dir = cache_dir_for(workspace_key);
228 match logicaffeine_compile::compile::rustc_check(source, &dir) {
229 Ok(errors) => Some(
230 errors
231 .into_iter()
232 .map(|e| FlycheckFinding {
233 message: format!("{}\n\n{}", e.title, e.explanation),
234 suggestion: e.suggestion,
235 span: e.logos_span,
236 })
237 .collect(),
238 ),
239 Err(logicaffeine_compile::compile::CompileError::Parse(_)) => Some(Vec::new()),
241 Err(logicaffeine_compile::compile::CompileError::Build(stderr)) => {
244 let first_error = stderr
245 .lines()
246 .find(|l| l.contains("error"))
247 .unwrap_or("cargo check failed")
248 .to_string();
249 Some(vec![FlycheckFinding {
250 message: format!(
251 "The generated Rust failed to compile — likely a LOGOS compiler bug, \
252 not an error in your program.\n\n{first_error}"
253 ),
254 suggestion: None,
255 span: None,
256 }])
257 }
258 Err(other) => {
259 log::warn!("flycheck could not run: {other:?}");
260 None
261 }
262 }
263 }
264}
265
266#[cfg(test)]
267#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/flycheck/tests.rs"]
268mod tests;