Skip to main content

rustia/
diagnostic.rs

1//! Bounded plain-text presentation for script failures.
2
3use crate::Error;
4use std::fmt::{self, Write};
5
6pub use crate::diagnostic_data::{
7    Diagnostic, DiagnosticFrame, DiagnosticLimits, DiagnosticReason, DiagnosticSpan, SourceSnapshot,
8};
9
10/// An error formatted with source context and a call trace when available.
11///
12/// Create one with [`Error::report`] and print it with `eprintln!("{report}")`.
13/// Formatting is bounded by the configured [`DiagnosticLimits`] and never
14/// runs script code.
15pub struct ErrorReport<'a> {
16    error: &'a Error,
17}
18
19impl Error {
20    /// Returns the source location, call trace, and other details captured
21    /// when this error occurred.
22    ///
23    /// These details remain usable after the VM is dropped or reset. Use
24    /// [`report`](Self::report) to format them for a person.
25    pub fn diagnostic(&self) -> Option<&Diagnostic> {
26        self.diagnostic.as_deref().or_else(|| {
27            self.as_vm_error()
28                .and_then(|error| error.diagnostic.as_deref())
29        })
30    }
31
32    /// Formats this error for a console or log, with source context when available.
33    ///
34    /// ```
35    /// # use rustia::Rustia;
36    /// let mut vm = Rustia::builder().build()?;
37    /// if let Err(error) = vm.load("return missing.health")
38    ///     .source_name("combat.luau")
39    ///     .exec()
40    /// {
41    ///     eprintln!("{}", error.report());
42    /// }
43    /// # Ok::<(), rustia::Error>(())
44    /// ```
45    ///
46    /// Printing the error itself gives a shorter message. Use
47    /// [`kind`](Self::kind) to decide how your application should respond.
48    pub fn report(&self) -> ErrorReport<'_> {
49        ErrorReport { error: self }
50    }
51}
52
53impl fmt::Display for ErrorReport<'_> {
54    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55        let mut output = BoundedWriter {
56            formatter,
57            remaining: self
58                .error
59                .diagnostic()
60                .map_or(16 * 1024, |diagnostic| diagnostic.report_bytes),
61            truncated: false,
62        };
63        let reason = self
64            .error
65            .diagnostic()
66            .and_then(|diagnostic| diagnostic.reason.as_ref());
67        if let Some(reason) = reason {
68            match reason {
69                DiagnosticReason::Index {
70                    object_type,
71                    key: Some(key),
72                } => writeln!(
73                    output,
74                    "error: cannot access `{key}`: the indexed value is {object_type}"
75                )?,
76                DiagnosticReason::Index {
77                    object_type,
78                    key: None,
79                } => writeln!(
80                    output,
81                    "error: cannot index a {object_type} value with this key"
82                )?,
83                DiagnosticReason::Call { value_type } => {
84                    writeln!(output, "error: this {value_type} value is not callable")?
85                }
86                DiagnosticReason::Arithmetic {
87                    operation,
88                    left_type,
89                    right_type,
90                } => writeln!(
91                    output,
92                    "error: cannot perform {operation} on {left_type} and {right_type}"
93                )?,
94            }
95        } else if let Some(error) = self.error.as_vm_error().filter(|_| {
96            self.error
97                .diagnostic()
98                .is_some_and(|diagnostic| diagnostic.source.is_some())
99        }) {
100            writeln!(output, "error: {}", error.message())?;
101        } else {
102            writeln!(output, "error: {}", self.error.kind())?;
103        }
104        for context in self.error.contexts().rev() {
105            writeln!(output, "note: {context}")?;
106        }
107        if let Some(diagnostic) = self.error.diagnostic() {
108            if let Some((line, expected)) = diagnostic.unclosed_block {
109                writeln!(
110                    output,
111                    "help: the block opened on line {line} still needs `{expected}`"
112                )?;
113            }
114            if let Some(path) = &diagnostic.data_path {
115                writeln!(output, "field: {path}")?;
116            }
117            if diagnostic.generated_source {
118                writeln!(output, "note: the failure is in generated wrapper code")?;
119            }
120            if let (Some(source), Some(line)) = (&diagnostic.source, diagnostic.line) {
121                let column = diagnostic.snapshot.as_ref().and_then(|snapshot| {
122                    let span = diagnostic.span?;
123                    let prefix = std::str::from_utf8(snapshot.bytes().get(..span.start)?).ok()?;
124                    let actual_line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
125                    (actual_line == line as usize)
126                        .then(|| prefix.rsplit('\n').next().unwrap_or("").chars().count() + 1)
127                });
128                if let Some(column) = column {
129                    writeln!(output, "  --> {source}:{line}:{column}")?;
130                } else {
131                    writeln!(output, "  --> {source}:{line}")?;
132                }
133            } else if let Some(source) = &diagnostic.source {
134                writeln!(output, "  --> {source}")?;
135            }
136            if let (Some(snapshot), Some(line)) = (&diagnostic.snapshot, diagnostic.line) {
137                // Source is byte-oriented. Invalid UTF-8 is not guessed into
138                // character columns; retain a location-only report instead.
139                if let Ok(source) = std::str::from_utf8(snapshot.bytes()) {
140                    let line_index = line.saturating_sub(1) as usize;
141                    let start = if line_index == 0 {
142                        Some(0)
143                    } else {
144                        source
145                            .bytes()
146                            .enumerate()
147                            .filter(|(_, byte)| *byte == b'\n')
148                            .map(|(index, _)| index + 1)
149                            .nth(line_index - 1)
150                    };
151                    if let Some(start) = start {
152                        let text = source[start..]
153                            .split('\n')
154                            .next()
155                            .unwrap_or("")
156                            .trim_end_matches('\r');
157                        writeln!(output, "\n {line} | {text}")?;
158                        if let Some(span) = diagnostic.span {
159                            let end = start.saturating_add(text.len());
160                            if span.start >= start
161                                && span.start <= end
162                                && span.end >= span.start
163                                && source.is_char_boundary(span.start)
164                            {
165                                let prefix = &source[start..span.start];
166                                let marked_end = span.end.min(end);
167                                if source.is_char_boundary(marked_end) {
168                                    let width =
169                                        source[span.start..marked_end].chars().count().max(1);
170                                    // Keep alignment honest for characters whose terminal
171                                    // width is not known to this ASCII renderer.
172                                    if text.is_ascii() && !text.chars().any(char::is_control) {
173                                        write!(
174                                            output,
175                                            " {} | ",
176                                            " ".repeat(line.to_string().len())
177                                        )?;
178                                        for _ in 0..prefix.len().min(16 * 1024) {
179                                            output.write_char(' ')?;
180                                        }
181                                        for _ in 0..width.min(16 * 1024) {
182                                            output.write_char('^')?;
183                                        }
184                                        writeln!(output)?;
185                                    }
186                                }
187                            }
188                        }
189                    }
190                }
191            }
192            if reason.is_some() {
193                if let Some(error) = self.error.as_vm_error() {
194                    writeln!(output, "original: {}", error.message())?;
195                }
196            }
197            if !diagnostic.frames.is_empty() {
198                writeln!(output, "\ncalled from:")?;
199                let mut index = 0;
200                while let Some(frame) = diagnostic.frames.get(index) {
201                    let repeated = diagnostic.frames[index..]
202                        .iter()
203                        .take_while(|other| *other == frame)
204                        .count();
205                    writeln!(
206                        output,
207                        "  {}    {}:{}",
208                        frame.function.as_deref().unwrap_or("<script>"),
209                        frame.source,
210                        frame.line
211                    )?;
212                    if repeated > 1 {
213                        writeln!(output, "  ... {} repeated calls ...", repeated - 1)?;
214                    }
215                    index += repeated;
216                }
217            }
218            if diagnostic.frames_truncated {
219                writeln!(output, "  ... additional frames omitted ...")?;
220            }
221        }
222        if let Some(error) = self.error.as_vm_error() {
223            match error.kind {
224                crate::VmErrorKind::FuelExhausted { .. } => writeln!(output, "note: this is where the instruction budget ran out, not necessarily where most work happened")?,
225                crate::VmErrorKind::OutOfMemory => writeln!(output, "note: this is where execution stopped, not necessarily the main source of memory use")?,
226                crate::VmErrorKind::RecursionLimit { .. } => writeln!(output, "help: check recursion stopping conditions and whether the input can contain cycles")?,
227                _ => {}
228            }
229        }
230        // Host causes may contain useful I/O or schema context. Traverse a
231        // bounded chain (including pathological cycles), never guest values.
232        let mut cause = match self.error.kind() {
233            crate::ErrorKind::Vm(error) => std::error::Error::source(error.as_ref()),
234            crate::ErrorKind::External(error) => error.source(),
235            _ => None,
236        };
237        for _ in 0..8 {
238            let Some(current) = cause else { break };
239            writeln!(output, "caused by: {current}")?;
240            cause = current.source();
241        }
242        if cause.is_some() {
243            writeln!(output, "... additional causes omitted ...")?;
244        }
245        if output.truncated && output.remaining >= "\n... report truncated ...".len() {
246            output.formatter.write_str("\n... report truncated ...")?;
247        }
248        Ok(())
249    }
250}
251
252// Stream directly into the formatter: never build an unbounded intermediate
253// string from a guest error message. Reserve space for the truncation marker.
254struct BoundedWriter<'a, 'b> {
255    formatter: &'a mut fmt::Formatter<'b>,
256    remaining: usize,
257    truncated: bool,
258}
259
260impl Write for BoundedWriter<'_, '_> {
261    fn write_str(&mut self, text: &str) -> fmt::Result {
262        if self.truncated {
263            return Ok(());
264        }
265        for character in text.chars() {
266            let mut encoded = [0; 4];
267            let text = if character.is_control() && character != '\n' {
268                // All control characters except structural newlines are
269                // escaped, including tabs, carriage returns and ANSI ESC.
270                let escaped = character.escape_default();
271                for character in escaped {
272                    let text = character.encode_utf8(&mut encoded);
273                    if self.remaining < text.len() + 32 {
274                        self.truncated = true;
275                        return Ok(());
276                    }
277                    self.formatter.write_str(text)?;
278                    self.remaining -= text.len();
279                }
280                continue;
281            } else {
282                character.encode_utf8(&mut encoded)
283            };
284            if self.remaining < text.len() + 32 {
285                self.truncated = true;
286                return Ok(());
287            }
288            self.formatter.write_str(text)?;
289            self.remaining -= text.len();
290        }
291        Ok(())
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use crate::{Error, Rustia};
298
299    #[test]
300    fn report_does_not_change_original_error() {
301        let error = Error::embed("bad\u{1b}[2Jvalue\r\t".to_owned());
302        let original = error.to_string();
303        let report = error.report().to_string();
304        assert!(report.contains("bad\\u{1b}[2Jvalue\\r\\t"));
305        assert_eq!(error.to_string(), original);
306    }
307
308    #[test]
309    fn report_output_is_bounded_on_utf8_boundary() {
310        let error = Error::embed("🦀".repeat(20_000));
311        let report = error.report().to_string();
312        assert!(report.len() <= 16 * 1024);
313        assert!(report.ends_with("... report truncated ..."));
314    }
315
316    #[test]
317    fn diagnostic_outlives_vm_and_reset() {
318        let mut vm = Rustia::new(crate::Profile::LuauCompat);
319        let error = vm.load("local function inner() error('broken') end\nlocal function outer() inner() end\nouter()")
320            .source_name("trace.luau").exec().unwrap_err();
321        let report = error.report().to_string();
322        assert!(report.contains("trace.luau"));
323        assert!(report.contains("called from:"), "{report}");
324        assert!(report.contains("local function inner()"), "{report}");
325        vm.reset_decision().unwrap();
326        drop(vm);
327        assert_eq!(error.report().to_string(), report);
328    }
329
330    #[test]
331    fn explicitly_suppressed_location_has_no_host_trace() {
332        let mut vm = Rustia::new(crate::Profile::LuauCompat);
333        let error = vm
334            .load("error('private', 0)")
335            .source_name("hidden.luau")
336            .exec()
337            .unwrap_err();
338        assert!(error.diagnostic().is_none());
339        assert!(!error.report().to_string().contains("hidden.luau"));
340    }
341
342    #[test]
343    fn source_budget_is_retained_by_errors_and_released_on_drop() {
344        let mut vm = Rustia::new(crate::Profile::LuauCompat);
345        let error = vm
346            .load("error('broken')")
347            .source_name("budget.luau")
348            .exec()
349            .unwrap_err();
350        assert!(vm.diagnostic_source_bytes() > 0);
351        vm.reset_decision().unwrap();
352        assert!(vm.diagnostic_source_bytes() > 0);
353        drop(error);
354        assert_eq!(vm.diagnostic_source_bytes(), 0);
355    }
356
357    #[test]
358    fn syntax_failure_has_named_source_and_snippet() {
359        let error = Rustia::compile_module("syntax.luau", "local = 1")
360            .err()
361            .expect("invalid syntax");
362        let report = error.report().to_string();
363        assert!(report.contains("syntax.luau:1"), "{report}");
364        assert!(report.contains("local = 1"), "{report}");
365    }
366
367    #[test]
368    fn zero_source_budget_keeps_location_and_execution_behavior() {
369        let mut vm = crate::RustiaBuilder::standard()
370            .diagnostic_limits(
371                super::DiagnosticLimits::default()
372                    .with_retained_source_bytes(0)
373                    .with_report_bytes(0),
374            )
375            .build()
376            .unwrap();
377        let error = vm
378            .load("error('broken')")
379            .source_name("limited.luau")
380            .exec()
381            .unwrap_err();
382        assert!(error.diagnostic().unwrap().snapshot.is_none());
383        assert_eq!(error.source_location().unwrap().source, "limited.luau");
384        assert_eq!(error.report().to_string(), "");
385        assert_eq!(vm.diagnostic_source_bytes(), 0);
386    }
387
388    #[test]
389    fn serde_paths_use_lua_array_positions_and_preserve_messages() {
390        #[derive(serde::Deserialize)]
391        struct Enemy {
392            #[serde(rename = "health")]
393            _health: u32,
394        }
395        #[derive(serde::Deserialize)]
396        struct Scenario {
397            #[serde(rename = "enemies")]
398            _enemies: Vec<Enemy>,
399        }
400        let mut vm = Rustia::new(crate::Profile::LuauCompat);
401        let error = vm
402            .load("return {enemies = {{health=1}, {health=2}, {health='bad'}}}")
403            .eval_serde::<Scenario>()
404            .err()
405            .expect("invalid health");
406        assert_eq!(
407            error.diagnostic().unwrap().data_path.as_deref(),
408            Some("enemies[3].health")
409        );
410        assert!(error
411            .report()
412            .to_string()
413            .contains("field: enemies[3].health"));
414    }
415
416    #[test]
417    fn host_context_preserves_resource_classification() {
418        let error = Error::from(crate::VmError::new(crate::VmErrorKind::OutOfMemory))
419            .with_context("installing scripts");
420        assert!(matches!(
421            error.as_vm_error().unwrap().kind,
422            crate::VmErrorKind::OutOfMemory
423        ));
424    }
425
426    #[test]
427    fn console_prefix_maps_runtime_spans_and_retained_source() {
428        let mut vm = Rustia::new(crate::Profile::LuauCompat);
429        let error = vm
430            .load("return missing.health")
431            .source_name("console")
432            .source_map(crate::SourceMap::generated_prefix(7))
433            .exec()
434            .unwrap_err();
435        let report = error.report().to_string();
436        assert!(report.contains("1 | missing.health"), "{report}");
437        assert!(!report.contains("1 | return"), "{report}");
438        assert_eq!(
439            error.source_span(),
440            Some(crate::SourceSpan { start: 0, end: 14 })
441        );
442    }
443
444    #[test]
445    fn generated_wrapper_failure_is_not_attributed_to_user_input() {
446        let mut vm = Rustia::new(crate::Profile::LuauCompat);
447        let error = vm
448            .load("not_valid local x = 1")
449            .source_map(crate::SourceMap::generated_prefix(10))
450            .exec()
451            .unwrap_err();
452        assert!(error.diagnostic().unwrap().generated_source);
453        assert!(error
454            .report()
455            .to_string()
456            .contains("generated wrapper code"));
457    }
458
459    #[test]
460    fn missing_end_points_to_the_innermost_unclosed_block() {
461        let error = Rustia::compile_module(
462            "blocks.luau",
463            "local function outer()\n  if true then\n    local x = 1",
464        )
465        .err()
466        .unwrap();
467        assert_eq!(error.diagnostic().unwrap().unclosed_block, Some((2, "end")));
468        assert!(error
469            .report()
470            .to_string()
471            .contains("block opened on line 2 still needs `end`"));
472    }
473
474    #[test]
475    fn reused_names_keep_the_exact_executed_source() {
476        let mut vm = Rustia::default();
477        vm.load("function old() return missing.old_field end")
478            .source_name("shared.luau")
479            .exec()
480            .unwrap();
481        let error = vm
482            .load("-- replacement version\nold()")
483            .source_name("shared.luau")
484            .exec()
485            .unwrap_err();
486        let report = error.report().to_string();
487        assert!(
488            report.contains("1 | function old() return missing.old_field end"),
489            "{report}"
490        );
491        assert!(!report.contains("replacement version"), "{report}");
492    }
493
494    #[test]
495    fn unicode_source_uses_honest_line_fallback() {
496        let mut vm = Rustia::default();
497        let error = vm
498            .load("local label = '🦀'; return missing.health")
499            .source_name("unicode.luau")
500            .exec()
501            .unwrap_err();
502        let report = error.report().to_string();
503        assert!(report.contains("🦀"), "{report}");
504        assert!(!report.contains('^'), "{report}");
505    }
506
507    #[test]
508    fn deep_calls_are_bounded_and_explicitly_truncated() {
509        let mut vm = crate::RustiaBuilder::standard()
510            .diagnostic_limits(super::DiagnosticLimits::default().with_frames(3))
511            .build()
512            .unwrap();
513        let error = vm
514            .load(
515                "local function f(n) if n == 0 then error('stop') end return 1 + f(n-1) end\nf(20)",
516            )
517            .source_name("recursion.luau")
518            .exec()
519            .unwrap_err();
520        let diagnostic = error.diagnostic().unwrap();
521        assert!(diagnostic.frames.len() <= 3);
522        assert!(diagnostic.frames_truncated);
523        assert!(error
524            .report()
525            .to_string()
526            .contains("additional frames omitted"));
527    }
528
529    #[test]
530    fn host_errors_keep_typed_causes_and_guest_call_sites() {
531        use std::error::Error as _;
532        let mut vm = Rustia::default();
533        let callback = vm
534            .create_function(|| -> crate::Result<()> {
535                Err(Error::external(std::io::Error::new(
536                    std::io::ErrorKind::NotFound,
537                    "asset missing",
538                )))
539            })
540            .unwrap();
541        vm.globals()
542            .unwrap()
543            .set_live(&mut vm, "asset", &callback.as_value())
544            .unwrap();
545        let error = vm
546            .load("asset()")
547            .source_name("assets.luau")
548            .exec()
549            .unwrap_err();
550        let mut cause = error.source();
551        let mut found = false;
552        while let Some(current) = cause {
553            found |= current.downcast_ref::<std::io::Error>().is_some();
554            cause = current.source();
555        }
556        assert!(found);
557        assert!(error.report().to_string().contains("assets.luau:1"));
558    }
559
560    #[test]
561    fn failed_install_reports_only_the_guaranteed_rollback() {
562        let mut vm = Rustia::default();
563        let error = vm
564            .load("_G.changed = 1; error('failed')")
565            .source_name("install.luau")
566            .install()
567            .unwrap_err();
568        let report = error.report().to_string();
569        assert!(report.contains("guest state was restored"));
570        assert!(report.contains("external host effects are not rolled back"));
571        assert!(vm.eval::<bool>("return changed == nil").unwrap());
572    }
573
574    #[test]
575    fn host_panic_reports_script_trigger_without_changing_raw_location_policy() {
576        let mut vm = Rustia::default();
577        let callback = vm
578            .create_function(|| -> () { panic!("test host failure") })
579            .unwrap();
580        vm.globals()
581            .unwrap()
582            .set_live(&mut vm, "broken_host", &callback.as_value())
583            .unwrap();
584        let error = vm
585            .load("broken_host()")
586            .source_name("host-trigger.luau")
587            .exec()
588            .unwrap_err();
589        assert!(error.as_vm_error().unwrap().location_suppressed);
590        assert!(error.as_vm_error().unwrap().location.is_none());
591        assert!(error.report().to_string().contains("host-trigger.luau:1"));
592        assert!(matches!(
593            error.as_vm_error().unwrap().kind,
594            crate::VmErrorKind::HostPanicked { .. }
595        ));
596    }
597
598    #[test]
599    fn diagnostic_limits_do_not_change_guest_messages_clock_or_live_memory() {
600        fn run(limits: crate::DiagnosticLimits) -> ((bool, String, f64), usize) {
601            let mut vm = crate::RustiaBuilder::standard()
602                .diagnostic_limits(limits)
603                .build()
604                .unwrap();
605            let result = vm.load("local ok, message = pcall(function() return missing.health end)\nreturn {ok, message, os.clock()}")
606                .source_name("protected.luau").eval_serde().unwrap();
607            (result, vm.memory_stats().live_bytes())
608        }
609        assert_eq!(
610            run(crate::DiagnosticLimits::default()),
611            run(crate::DiagnosticLimits {
612                retained_source_bytes: 0,
613                source_bytes: 0,
614                frames: 0,
615                report_bytes: 0,
616            })
617        );
618    }
619}