1use crate::intern::Interner;
32use crate::sourcemap::{OwnershipRole, SourceMap};
33use crate::style::Style;
34use crate::token::Span;
35use serde::Deserialize;
36
37#[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#[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#[derive(Debug, Deserialize)]
76pub struct RustcCode {
77 pub code: String,
79}
80
81#[derive(Debug, Deserialize)]
86pub struct RustcSpan {
87 pub file_name: String,
89 pub line_start: u32,
91 pub line_end: u32,
93 pub column_start: u32,
95 pub column_end: u32,
97 pub is_primary: bool,
99 pub label: Option<String>,
101 #[serde(default)]
103 pub text: Vec<RustcSpanText>,
104}
105
106#[derive(Debug, Deserialize)]
108pub struct RustcSpanText {
109 pub text: String,
111 pub highlight_start: u32,
113 pub highlight_end: u32,
115}
116
117#[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
129pub fn parse_rustc_json(stderr: &str) -> Vec<RustcDiagnostic> {
135 let mut diagnostics = Vec::new();
136
137 for line in stderr.lines() {
138 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) => {} Err(_) => {} }
152 }
153
154 diagnostics
155}
156
157pub fn get_error_code(diag: &RustcDiagnostic) -> Option<&str> {
161 diag.code.as_ref().map(|c| c.code.as_str())
162}
163
164pub fn get_primary_span(diag: &RustcDiagnostic) -> Option<&RustcSpan> {
169 diag.spans.iter().find(|s| s.is_primary)
170}
171
172fn 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
181pub struct DiagnosticBridge<'a> {
191 source_map: &'a SourceMap,
193 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 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 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 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 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 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 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 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 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
391pub 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
406pub 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#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct RemappedError {
428 pub message: String,
430 pub file: Option<String>,
433 pub line: u32,
435 pub column: u32,
437 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
456pub 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
487fn 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;