Skip to main content

logicaffeine_lsp/
flycheck.rs

1//! The rustc flycheck: on save, compile the document through the AOT
2//! backend's mapped codegen and run `cargo check` over it, translating every
3//! finding back to English with real user-source spans — the borrow checker,
4//! speaking LOGOS.
5//!
6//! Never on the interactive path: saves trigger it, a per-document
7//! generation guard drops stale results (a newer save always wins), edits
8//! clear findings outright (their positions would lie), and a machine
9//! without cargo degrades to interactive-only diagnostics.
10
11use 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
22/// The diagnostic source label — distinct from interactive `logicaffeine`
23/// diagnostics so editors and users can tell the two engines apart.
24pub const FLYCHECK_SOURCE: &str = "logicaffeine (rustc)";
25
26/// One translated rustc finding.
27pub struct FlycheckFinding {
28    pub message: String,
29    pub suggestion: Option<String>,
30    /// User-source span from the mapped codegen; `None` = whole file.
31    pub span: Option<Span>,
32}
33
34/// The check engine seam. The real runner shells out to cargo; tests inject
35/// mocks so the server's merge/staleness/dedup behavior is provable without
36/// a toolchain.
37pub trait FlycheckRunner: Send + Sync {
38    /// `None` = the toolchain is unavailable (degrade silently);
39    /// `Some(findings)` = the check ran.
40    fn check(&self, source: &str, workspace_key: &str) -> Option<Vec<FlycheckFinding>>;
41}
42
43/// Per-document flycheck state: save generations and the last published
44/// findings (already converted to diagnostics against the checked text).
45pub 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    /// A save happened: invalidate any in-flight run and return the new
61    /// generation this one must still hold when it finishes.
62    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    /// Edits invalidate findings outright — their positions would lie. Returns
78    /// whether stored findings were actually dropped, so the caller can retract
79    /// them from the editor NOW (republish the interactive-only set) instead of
80    /// leaving them pinned to pre-edit positions until the analysis debounce.
81    pub fn clear(&self, uri: &Url) -> bool {
82        let had_findings = self.results.remove(uri).is_some();
83        // Bump so an in-flight save result from before the edit is dropped.
84        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    /// The last completed run's diagnostics, for merging into any publish.
96    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    /// Run the checker (blocking — call inside `spawn_blocking`).
104    pub fn run(&self, source: &str, workspace_key: &str) -> Option<Vec<FlycheckFinding>> {
105        self.runner.check(source, workspace_key)
106    }
107
108    /// Store a completed run's findings if its generation still holds.
109    /// Returns the stored diagnostics, or `None` when the run went stale.
110    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
127/// Convert findings to LSP diagnostics against the text that was checked,
128/// dropping any that overlap an interactive ERROR — rustc's value is what
129/// the local checkers MISS, not an echo of what they already said.
130fn 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
172// ---------------------------------------------------------------------------
173// The real runner
174// ---------------------------------------------------------------------------
175
176/// Shells out to `cargo check` through
177/// [`logicaffeine_compile::compile::rustc_check`], one persistent cache
178/// directory per workspace (warm incremental runs), single-flight per
179/// workspace so two saves never race one cargo target dir.
180pub 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            // The interactive pipeline already reports parse problems.
240            Err(logicaffeine_compile::compile::CompileError::Parse(_)) => Some(Vec::new()),
241            // Generated code that fails rustc WITHOUT a LOGOS translation is
242            // a compiler bug worth surfacing, not hiding.
243            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;