Skip to main content

oxblade/
error.rs

1//! Source-aware diagnostics shared by compilation and rendering.
2
3use crate::span::Span;
4use std::fmt;
5
6/// The operation that failed.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum ErrorKind {
10    /// An invalid Blade token.
11    Lex,
12    /// Invalid template structure.
13    Parse,
14    /// An invalid expression, statement, or pattern.
15    Syntax,
16    /// A source could not be loaded.
17    Load,
18    /// Compilation failed.
19    Compile,
20    /// A static check failed.
21    Check,
22    /// Rendering or expression evaluation failed.
23    Render,
24    /// A configured resource limit was exceeded.
25    Limit,
26    /// Rendering deliberately stopped through a debug directive.
27    DebugAbort,
28}
29
30/// One step in the chain leading from a view to a nested render.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct Frame {
33    /// Description of the view, component or slot.
34    pub name: String,
35    /// Call site in the caller, when available.
36    pub span: Option<Span>,
37}
38
39/// An engine diagnostic.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct Error {
42    /// Category of the failure.
43    pub kind: ErrorKind,
44    /// Diagnostic text.
45    pub message: String,
46    /// Source range, when known.
47    pub span: Option<Span>,
48    /// Optional explanation or suggested correction.
49    pub help: Option<String>,
50    /// Render call chain, most recent frame last.
51    pub chain: Vec<Frame>,
52}
53
54impl Error {
55    /// Creates a diagnostic with an optional source range.
56    pub fn new(kind: ErrorKind, message: impl Into<String>, span: impl Into<Option<Span>>) -> Self {
57        Self {
58            kind,
59            message: message.into(),
60            span: span.into(),
61            help: None,
62            chain: Vec::new(),
63        }
64    }
65
66    /// Attaches help text to this diagnostic.
67    pub fn with_help(mut self, help: impl Into<String>) -> Self {
68        self.help = Some(help.into());
69        self
70    }
71
72    /// Adds the call site for a view, component or slot.
73    pub fn with_frame(mut self, frame: Frame) -> Self {
74        self.chain.push(frame);
75        self
76    }
77}
78
79impl fmt::Display for Error {
80    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
81        formatter.write_str(&self.message)
82    }
83}
84
85impl std::error::Error for Error {}
86
87/// The result of an engine operation.
88pub type Result<T> = std::result::Result<T, Error>;