Skip to main content

logicaffeine_compile/
diagnostic.rs

1//! Diagnostic bridge for translating Rust errors to LOGOS.
2//!
3//! Translates Rust borrow checker errors into friendly LOGOS error messages
4//! using Socratic phrasing. Parses rustc JSON output and maps errors back
5//! to LOGOS source locations using the [`SourceMap`].
6//!
7//! # Supported Error Codes
8//!
9//! | Rust Error | LOGOS Translation |
10//! |------------|-------------------|
11//! | E0382 | "Cannot use 'x' after giving it away" |
12//! | E0505 | "Cannot borrow 'x' while it's borrowed elsewhere" |
13//! | E0597 | "Reference 'x' cannot escape zone" |
14//!
15//! # Translation Flow
16//!
17//! ```text
18//! rustc --error-format=json
19//!           │
20//!           ▼
21//! ┌─────────────────────┐
22//! │ parse_rustc_json()  │ Parse JSON diagnostics
23//! └──────────┬──────────┘
24//!            ▼
25//! ┌─────────────────────┐
26//! │ translate_diagnostics│ Map to LOGOS source
27//! └──────────┬──────────┘
28//!            ▼
29//!    LogosError with friendly message
30
31use crate::intern::Interner;
32use crate::sourcemap::{OwnershipRole, SourceMap};
33use crate::style::Style;
34use crate::token::Span;
35use serde::Deserialize;
36
37/// A translated error message for LOGOS users.
38#[derive(Debug, Clone)]
39pub struct LogosError {
40    pub title: String,
41    pub explanation: String,
42    pub logos_span: Option<Span>,
43    pub suggestion: Option<String>,
44}
45
46impl std::fmt::Display for LogosError {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        writeln!(f, "{}: {}", Style::bold_red("ownership error"), self.title)?;
49        writeln!(f)?;
50        writeln!(f, "{}", self.explanation)?;
51        if let Some(suggestion) = &self.suggestion {
52            writeln!(f)?;
53            writeln!(f, "{}: {}", Style::cyan("suggestion"), suggestion)?;
54        }
55        Ok(())
56    }
57}
58
59// =============================================================================
60// Rustc JSON Diagnostic Types
61// =============================================================================
62
63/// Rustc JSON diagnostic message (subset of fields we need).
64#[derive(Debug, Deserialize)]
65pub struct RustcDiagnostic {
66    pub message: String,
67    pub code: Option<RustcCode>,
68    pub level: String,
69    pub spans: Vec<RustcSpan>,
70    #[serde(default)]
71    pub children: Vec<RustcDiagnostic>,
72}
73
74/// Error code from rustc (e.g., "E0382").
75#[derive(Debug, Deserialize)]
76pub struct RustcCode {
77    /// The error code string (e.g., "E0382" for use-after-move).
78    pub code: String,
79}
80
81/// Source location information from a rustc diagnostic.
82///
83/// Describes where in the generated Rust source an error occurred,
84/// which is then mapped back to LOGOS source using the [`SourceMap`].
85#[derive(Debug, Deserialize)]
86pub struct RustcSpan {
87    /// Path to the file containing the error.
88    pub file_name: String,
89    /// Starting line number (1-based).
90    pub line_start: u32,
91    /// Ending line number (1-based).
92    pub line_end: u32,
93    /// Starting column number (1-based).
94    pub column_start: u32,
95    /// Ending column number (1-based).
96    pub column_end: u32,
97    /// Whether this is the primary error location.
98    pub is_primary: bool,
99    /// Optional diagnostic label for this span.
100    pub label: Option<String>,
101    /// Source text lines with highlighting information.
102    #[serde(default)]
103    pub text: Vec<RustcSpanText>,
104}
105
106/// Source text with highlight range from a rustc diagnostic.
107#[derive(Debug, Deserialize)]
108pub struct RustcSpanText {
109    /// The actual source text line.
110    pub text: String,
111    /// Column where highlighting starts (1-based).
112    pub highlight_start: u32,
113    /// Column where highlighting ends (1-based).
114    pub highlight_end: u32,
115}
116
117/// Parsed rustc output: either a diagnostic or artifact info.
118#[derive(Debug, Deserialize)]
119#[serde(tag = "reason")]
120#[serde(rename_all = "kebab-case")]
121pub enum RustcMessage {
122    CompilerMessage {
123        message: RustcDiagnostic,
124    },
125    #[serde(other)]
126    Other,
127}
128
129// =============================================================================
130// JSON Parsing
131// =============================================================================
132
133/// Parse rustc stderr output from `cargo build --message-format=json`.
134pub fn parse_rustc_json(stderr: &str) -> Vec<RustcDiagnostic> {
135    let mut diagnostics = Vec::new();
136
137    for line in stderr.lines() {
138        // Skip empty lines and non-JSON output
139        if !line.starts_with('{') {
140            continue;
141        }
142
143        match serde_json::from_str::<RustcMessage>(line) {
144            Ok(RustcMessage::CompilerMessage { message }) => {
145                if message.level == "error" {
146                    diagnostics.push(message);
147                }
148            }
149            Ok(RustcMessage::Other) => {} // Ignore artifacts, build-finished, etc.
150            Err(_) => {}                  // Ignore malformed lines
151        }
152    }
153
154    diagnostics
155}
156
157/// Extracts the error code (e.g., "E0382") from a diagnostic.
158///
159/// Returns `None` if the diagnostic has no associated error code.
160pub fn get_error_code(diag: &RustcDiagnostic) -> Option<&str> {
161    diag.code.as_ref().map(|c| c.code.as_str())
162}
163
164/// Extracts the primary source span from a diagnostic.
165///
166/// Diagnostics may have multiple spans; this returns the one marked
167/// as primary (the main error location).
168pub fn get_primary_span(diag: &RustcDiagnostic) -> Option<&RustcSpan> {
169    diag.spans.iter().find(|s| s.is_primary)
170}
171
172/// Extract variable name from rustc error message.
173/// Example: "use of moved value: `data`" -> "data"
174fn extract_var_from_message(message: &str, prefix: &str, suffix: &str) -> Option<String> {
175    let start = message.find(prefix)?;
176    let after_prefix = &message[start + prefix.len()..];
177    let end = after_prefix.find(suffix)?;
178    Some(after_prefix[..end].to_string())
179}
180
181// =============================================================================
182// Diagnostic Bridge
183// =============================================================================
184
185/// Translates rustc diagnostics into user-friendly LOGOS error messages.
186///
187/// Uses the source map to map Rust source locations back to LOGOS source,
188/// and applies Socratic phrasing to explain ownership errors in terms of
189/// LOGOS semantics (Give, Show, Zone).
190pub struct DiagnosticBridge<'a> {
191    /// Source map for translating Rust locations to LOGOS locations.
192    source_map: &'a SourceMap,
193    /// Interner for resolving symbol names.
194    interner: &'a Interner,
195}
196
197impl<'a> DiagnosticBridge<'a> {
198    pub fn new(source_map: &'a SourceMap, interner: &'a Interner) -> Self {
199        Self {
200            source_map,
201            interner,
202        }
203    }
204
205    /// Translate a rustc diagnostic into a LOGOS error.
206    pub fn translate(&self, diag: &RustcDiagnostic) -> Option<LogosError> {
207        let code = get_error_code(diag)?;
208        let span = get_primary_span(diag);
209
210        match code {
211            "E0382" => self.translate_use_after_move(diag, span),
212            "E0505" => self.translate_move_while_borrowed(diag, span),
213            "E0597" => self.translate_lifetime_error(diag, span),
214            _ => self.translate_generic(diag, span),
215        }
216    }
217
218    /// E0382: "use of moved value: `x`"
219    /// LOGOS: "You already gave X away - you can't use it anymore"
220    fn translate_use_after_move(
221        &self,
222        diag: &RustcDiagnostic,
223        span: Option<&RustcSpan>,
224    ) -> Option<LogosError> {
225        let var_name = extract_var_from_message(&diag.message, "value: `", "`")
226            .or_else(|| extract_var_from_message(&diag.message, "value `", "`"))?;
227
228        let logos_span = span.and_then(|s| self.source_map.find_nearest_span(s.line_start));
229
230        // Look up variable origin if available
231        let (logos_name, role) = if let Some(origin) = self.source_map.get_var_origin(&var_name) {
232            (
233                self.interner.resolve(origin.logos_name).to_string(),
234                Some(origin.role),
235            )
236        } else {
237            (var_name.clone(), None)
238        };
239
240        let explanation = match role {
241            Some(OwnershipRole::GiveObject) => format!(
242                "You gave '{}' away with a Give statement, so you can't use it anymore.\n\
243                In LOGOS, 'Give X to Y' transfers ownership - X moves to Y and leaves your hands.\n\
244                This is like handing someone a physical object: once given, you no longer have it.",
245                logos_name
246            ),
247            Some(OwnershipRole::LetBinding) | None => format!(
248                "The value '{}' was moved somewhere else and can't be used again.\n\
249                Check if you used 'Give' or passed it to a function that took ownership.",
250                logos_name
251            ),
252            _ => format!(
253                "The value '{}' has been moved and is no longer available.",
254                logos_name
255            ),
256        };
257
258        let suggestion = Some(format!(
259            "If you need to use '{}' after giving it away, either:\n\
260             1. Use 'Show {} to Y' instead (this borrows, keeping ownership)\n\
261             2. Use 'a copy of {}' before the Give",
262            logos_name, logos_name, logos_name
263        ));
264
265        Some(LogosError {
266            title: format!("Cannot use '{}' after giving it away", logos_name),
267            explanation,
268            logos_span,
269            suggestion,
270        })
271    }
272
273    /// E0505: "cannot move out of `x` because it is borrowed"
274    /// LOGOS: "You're trying to give X away while someone is still looking at it"
275    fn translate_move_while_borrowed(
276        &self,
277        diag: &RustcDiagnostic,
278        span: Option<&RustcSpan>,
279    ) -> Option<LogosError> {
280        let var_name = extract_var_from_message(&diag.message, "out of `", "`")
281            .or_else(|| extract_var_from_message(&diag.message, "move out of `", "`"))?;
282
283        let logos_span = span.and_then(|s| self.source_map.find_nearest_span(s.line_start));
284
285        let logos_name = if let Some(origin) = self.source_map.get_var_origin(&var_name) {
286            self.interner.resolve(origin.logos_name).to_string()
287        } else {
288            var_name.clone()
289        };
290
291        let explanation = format!(
292            "You showed '{}' to someone (creating a temporary view),\n\
293            but then tried to give it away before they finished looking.\n\
294            In LOGOS, 'Show' creates a promise that the data won't change or disappear\n\
295            while being viewed. You can't break that promise by giving it away.",
296            logos_name
297        );
298
299        let suggestion = Some(format!(
300            "Make sure all 'Show' usages of '{}' complete before any 'Give'.\n\
301            Alternatively, give away a copy: 'Give a copy of {} to Y'",
302            logos_name, logos_name
303        ));
304
305        Some(LogosError {
306            title: format!("Cannot give '{}' while it's being shown", logos_name),
307            explanation,
308            logos_span,
309            suggestion,
310        })
311    }
312
313    /// E0597: "borrowed value does not live long enough"
314    /// LOGOS: "You can't take a reference outside its zone" (the zone containment rule)
315    fn translate_lifetime_error(
316        &self,
317        diag: &RustcDiagnostic,
318        span: Option<&RustcSpan>,
319    ) -> Option<LogosError> {
320        let logos_span = span.and_then(|s| self.source_map.find_nearest_span(s.line_start));
321
322        // Check if this is zone-related by looking at the message and children
323        let is_zone_related = diag.message.contains("borrowed")
324            || diag.children.iter().any(|c| c.message.contains("dropped"));
325
326        let explanation = if is_zone_related {
327            "A value created inside a Zone cannot be referenced from outside.\n\
328            Zones are memory arenas - when the Zone ends, everything inside it is released.\n\
329            This is the 'Hotel California' rule: data can check in (be created),\n\
330            but references can't check out (escape the Zone)."
331                .to_string()
332        } else {
333            "A borrowed reference is being used after the original value has gone away.\n\
334            References are temporary views - they can't outlive what they're viewing."
335                .to_string()
336        };
337
338        let suggestion = Some(
339            "If you need the data after the Zone ends, either:\n\
340             1. Move the data out with 'Give' before the Zone closes\n\
341             2. Copy the data: 'Let result be a copy of zone_data'\n\
342             3. Restructure so the computation completes inside the Zone"
343                .to_string(),
344        );
345
346        Some(LogosError {
347            title: "Reference cannot outlive its data".to_string(),
348            explanation,
349            logos_span,
350            suggestion,
351        })
352    }
353
354    /// Fallback for other errors - provide the raw message with context.
355    fn translate_generic(
356        &self,
357        diag: &RustcDiagnostic,
358        span: Option<&RustcSpan>,
359    ) -> Option<LogosError> {
360        let logos_span = span.and_then(|s| self.source_map.find_nearest_span(s.line_start));
361
362        // Try to extract any variable name
363        let var_hint = if let Some(start) = diag.message.find('`') {
364            if let Some(end) = diag.message[start + 1..].find('`') {
365                Some(&diag.message[start + 1..start + 1 + end])
366            } else {
367                None
368            }
369        } else {
370            None
371        };
372
373        let explanation = if let Some(var) = var_hint {
374            format!(
375                "The Rust compiler reported an error involving '{}':\n{}",
376                var, diag.message
377            )
378        } else {
379            format!("The Rust compiler reported an error:\n{}", diag.message)
380        };
381
382        Some(LogosError {
383            title: "Compilation error".to_string(),
384            explanation,
385            logos_span,
386            suggestion: None,
387        })
388    }
389}
390
391/// Translates rustc diagnostics to LOGOS errors.
392///
393/// Returns the first successfully translated error — the CLI's
394/// one-error-at-a-time contract. IDE surfaces want
395/// [`translate_diagnostics_all`].
396pub fn translate_diagnostics(
397    diagnostics: &[RustcDiagnostic],
398    source_map: &SourceMap,
399    interner: &Interner,
400) -> Option<LogosError> {
401    translate_diagnostics_all(diagnostics, source_map, interner)
402        .into_iter()
403        .next()
404}
405
406/// Translates EVERY rustc diagnostic that has a LOGOS reading.
407///
408/// Diagnostics the bridge cannot translate (rustc internals with no LOGOS
409/// counterpart) are skipped, not fabricated.
410pub fn translate_diagnostics_all(
411    diagnostics: &[RustcDiagnostic],
412    source_map: &SourceMap,
413    interner: &Interner,
414) -> Vec<LogosError> {
415    let bridge = DiagnosticBridge::new(source_map, interner);
416    diagnostics
417        .iter()
418        .filter_map(|diag| bridge.translate(diag))
419        .collect()
420}
421
422/// A rustc error remapped to the LOGOS source location it originated from — the
423/// GENERIC path for any diagnostic (the [`DiagnosticBridge`] only gives the
424/// ownership errors a bespoke English reading; every other rustc error still
425/// deserves to point at the LOGOS line the user wrote, not the generated Rust).
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct RemappedError {
428    /// rustc's message, verbatim.
429    pub message: String,
430    /// The originating LOGOS file (a `.lg`/`.md` in a multi-file project), if the
431    /// location could be attributed to one.
432    pub file: Option<String>,
433    /// 1-based LOGOS line the generated Rust line maps back to.
434    pub line: u32,
435    /// 1-based column within that LOGOS line.
436    pub column: u32,
437    /// The LOGOS source line's text, for the caret excerpt.
438    pub source_line: String,
439}
440
441impl std::fmt::Display for RemappedError {
442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
443        writeln!(f, "{}: {}", Style::bold_red("error"), self.message)?;
444        let location = match &self.file {
445            Some(file) => format!("{file}:{}:{}", self.line, self.column),
446            None => format!("{}:{}", self.line, self.column),
447        };
448        writeln!(f, "  --> {location}")?;
449        let gutter = format!("{} | ", self.line);
450        writeln!(f, "{gutter}{}", self.source_line)?;
451        let caret_pad = " ".repeat(gutter.len() + self.column.saturating_sub(1) as usize);
452        writeln!(f, "{caret_pad}{}", Style::bold_red("^"))
453    }
454}
455
456/// Remap every rustc error diagnostic to its originating LOGOS line via the
457/// `SourceMap`. Diagnostics whose Rust line can't be mapped are dropped (better
458/// silent than pointing at generated Rust). Uses each diagnostic's PRIMARY span.
459pub fn remap_rustc_diagnostics(
460    diagnostics: &[RustcDiagnostic],
461    source_map: &SourceMap,
462    file_of: &dyn Fn(usize) -> Option<String>,
463) -> Vec<RemappedError> {
464    let source = source_map.logos_source();
465    diagnostics
466        .iter()
467        .filter_map(|diag| {
468            let primary = diag
469                .spans
470                .iter()
471                .find(|s| s.is_primary)
472                .or_else(|| diag.spans.first())?;
473            let span = source_map.find_nearest_span(primary.line_start)?;
474            let offset = span.start as usize;
475            let (line, column, source_line) = byte_offset_to_line_col(source, offset);
476            Some(RemappedError {
477                message: diag.message.clone(),
478                file: file_of(offset),
479                line,
480                column,
481                source_line,
482            })
483        })
484        .collect()
485}
486
487/// Translate a byte offset in the LOGOS source into (1-based line, 1-based
488/// column, the whole source line's text). Panic-proof for any offset — the
489/// column is counted char-by-char (never a slice at a possibly-mid-char offset),
490/// and `line_start` is always a char boundary (`0` or just after a `\n`).
491fn byte_offset_to_line_col(source: &str, offset: usize) -> (u32, u32, String) {
492    let clamped = offset.min(source.len());
493    let mut line = 1u32;
494    let mut column = 1u32;
495    let mut line_start = 0usize;
496    for (i, ch) in source.char_indices() {
497        if i >= clamped {
498            break;
499        }
500        if ch == '\n' {
501            line += 1;
502            column = 1;
503            line_start = i + 1;
504        } else {
505            column += 1;
506        }
507    }
508    let source_line = source[line_start..]
509        .lines()
510        .next()
511        .unwrap_or("")
512        .to_string();
513    (line, column, source_line)
514}
515
516#[cfg(test)]
517#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/diagnostic/tests.rs"]
518mod tests;