Skip to main content

temple_dsl/common/
error.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4/// A byte range `start..end` in a source string.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
6pub struct Span {
7    /// First byte.
8    pub start: u32,
9    /// Just past the last byte.
10    pub end: u32,
11}
12
13impl Span {
14    /// A span from byte `start` up to, not including, byte `end`.
15    pub fn new(start: usize, end: usize) -> Self {
16        Self {
17            start: start as u32,
18            end: end as u32,
19        }
20    }
21
22    /// The span as a `usize` range, for slicing the source.
23    pub fn range(self) -> std::ops::Range<usize> {
24        self.start as usize..self.end as usize
25    }
26
27    /// From the start of `self` to the end of `last`.
28    pub(crate) fn to(self, last: Span) -> Span {
29        Span {
30            start: self.start,
31            end: last.end,
32        }
33    }
34
35    /// 1-based line and column of the start in `src`; columns count
36    /// characters.
37    pub fn line_col(self, src: &str) -> (usize, usize) {
38        let location = Lines::new(src).locate(self.start as usize);
39        (location.line, location.column)
40    }
41}
42
43/// Why a template could not be compiled.
44#[derive(Debug, Clone)]
45#[allow(missing_docs)] // variant fields name themselves
46pub enum CompileError {
47    /// The source doesn't parse, or names something that doesn't exist.
48    Syntax { message: String, span: Span },
49    /// The template nests deeper than `limit` levels.
50    TooDeep { limit: usize, span: Span },
51    /// The source is longer than `limit` bytes.
52    TooLarge { bytes: usize, limit: usize },
53}
54
55impl CompileError {
56    /// The source span this error points at. `TooLarge` has none.
57    pub fn span(&self) -> Option<Span> {
58        match self {
59            CompileError::Syntax { span, .. } | CompileError::TooDeep { span, .. } => Some(*span),
60            CompileError::TooLarge { .. } => None,
61        }
62    }
63
64    /// The error as an underlined snippet of `src`:
65    ///
66    /// ```text
67    /// error: unknown identifier `inputt`
68    ///  --> 2:13
69    ///   |
70    /// 2 |   "id": {{ inputt.id }}
71    ///   |          ^^^^^^
72    /// ```
73    pub fn report(&self, src: &str) -> String {
74        snippet(&Lines::new(src), self.span(), &self.headline())
75    }
76
77    /// Every error in `errors` as a snippet, separated by blank lines.
78    pub fn report_all(src: &str, errors: &[CompileError]) -> String {
79        let lines = Lines::new(src);
80        errors
81            .iter()
82            .map(|e| snippet(&lines, e.span(), &e.headline()))
83            .collect::<Vec<_>>()
84            .join("\n\n")
85    }
86
87    /// The message without its location.
88    fn headline(&self) -> String {
89        match self {
90            CompileError::Syntax { message, .. } => message.clone(),
91            CompileError::TooDeep { limit, .. } => {
92                format!("template nests too deeply (limit {limit} levels)")
93            }
94            CompileError::TooLarge { bytes, limit } => {
95                format!("template is too large: {bytes} bytes exceeds the limit of {limit}")
96            }
97        }
98    }
99}
100
101/// Why a template could not be rendered.
102#[derive(Debug, Clone)]
103#[allow(missing_docs)] // variant fields name themselves
104pub enum RenderError {
105    /// A path reached a field that isn't there; `key` is the missing field.
106    MissingPath {
107        path: String,
108        key: Option<String>,
109        span: Span,
110    },
111    /// A value has the wrong type for what was done with it.
112    TypeMismatch {
113        expected: &'static str,
114        got: String,
115        span: Span,
116    },
117    /// Division or remainder by zero.
118    DivideByZero { span: Span },
119    /// A number left the range it can represent.
120    ArithmeticOverflow { span: Span },
121    /// No `when` branch matched and there was no `else`.
122    WhenNoMatch { span: Span },
123    /// A method that doesn't exist on the value's type.
124    UnknownMethod {
125        method: String,
126        on_type: String,
127        span: Span,
128    },
129    /// A method or function called with the wrong number of arguments.
130    ArityMismatch {
131        method: String,
132        expected: usize,
133        got: usize,
134        span: Span,
135    },
136    /// An array index outside the array.
137    IndexOutOfBounds {
138        index: i64,
139        length: usize,
140        span: Span,
141    },
142    /// `[...]` on a value that isn't an array or object.
143    NotIndexable { got: String, span: Span },
144    /// A method that takes a lambda was given something else.
145    LambdaExpected { span: Span },
146    /// A value nests deeper than `limit` levels.
147    ValueTooDeep { limit: usize, span: Span },
148    /// An object literal produced the same key twice.
149    DuplicateKey { key: String, span: Span },
150    /// The rendered value could not be turned into the requested Rust type.
151    Deserialize(String),
152}
153
154impl RenderError {
155    /// The source span this error points at. `Deserialize` has none.
156    pub fn span(&self) -> Option<Span> {
157        match self {
158            RenderError::MissingPath { span, .. }
159            | RenderError::TypeMismatch { span, .. }
160            | RenderError::DivideByZero { span }
161            | RenderError::ArithmeticOverflow { span }
162            | RenderError::WhenNoMatch { span }
163            | RenderError::UnknownMethod { span, .. }
164            | RenderError::ArityMismatch { span, .. }
165            | RenderError::IndexOutOfBounds { span, .. }
166            | RenderError::NotIndexable { span, .. }
167            | RenderError::LambdaExpected { span }
168            | RenderError::ValueTooDeep { span, .. }
169            | RenderError::DuplicateKey { span, .. } => Some(*span),
170            RenderError::Deserialize(_) => None,
171        }
172    }
173
174    /// The error as an underlined snippet of `src`, in the same layout as
175    /// [`CompileError::report`].
176    pub fn report(&self, src: &str) -> String {
177        snippet(&Lines::new(src), self.span(), &self.to_string())
178    }
179
180    #[cold]
181    pub(crate) fn type_mismatch(
182        expected: &'static str,
183        got: impl Into<String>,
184        span: Span,
185    ) -> Self {
186        RenderError::TypeMismatch {
187            expected,
188            got: got.into(),
189            span,
190        }
191    }
192
193    #[cold]
194    pub(crate) fn missing_field(name: &str, span: Span) -> Self {
195        RenderError::MissingPath {
196            path: name.to_string(),
197            key: Some(name.to_string()),
198            span,
199        }
200    }
201
202    #[cold]
203    pub(crate) fn not_indexable(got: &str, span: Span) -> Self {
204        RenderError::NotIndexable {
205            got: got.to_string(),
206            span,
207        }
208    }
209
210    #[cold]
211    pub(crate) fn unknown_method(method: &str, on_type: &str, span: Span) -> Self {
212        RenderError::UnknownMethod {
213            method: method.to_string(),
214            on_type: on_type.to_string(),
215            span,
216        }
217    }
218}
219
220/// Why a stored template could not be loaded.
221#[derive(Debug, Clone)]
222#[allow(missing_docs)] // variant fields name themselves
223pub enum LoadError {
224    /// The bytes are damaged or aren't a template blob.
225    Corrupt(String),
226    /// The blob was written with a different blob format.
227    IncompatibleVersion { found: u32, expected: u32 },
228}
229
230impl fmt::Display for CompileError {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        match self.span() {
233            Some(span) => write!(f, "{} at {}..{}", self.headline(), span.start, span.end),
234            None => write!(f, "{}", self.headline()),
235        }
236    }
237}
238
239impl fmt::Display for RenderError {
240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241        match self {
242            RenderError::MissingPath { path, key, .. } => match key {
243                Some(k) => write!(f, "missing field `{k}` while resolving `{path}`"),
244                None => write!(f, "missing path `{path}`"),
245            },
246            RenderError::TypeMismatch { expected, got, .. } => {
247                write!(f, "type mismatch: expected {expected}, got {got}")
248            }
249            RenderError::DivideByZero { .. } => write!(f, "divide by zero"),
250            RenderError::ArithmeticOverflow { .. } => write!(f, "arithmetic overflow"),
251            RenderError::WhenNoMatch { .. } => {
252                write!(f, "no `when` branch matched and no `else` provided")
253            }
254            RenderError::UnknownMethod {
255                method, on_type, ..
256            } => write!(f, "no method `{method}` on {on_type}"),
257            RenderError::ArityMismatch {
258                method,
259                expected,
260                got,
261                ..
262            } => write!(f, "{}", arity_message(method, &arguments(*expected), *got)),
263            RenderError::IndexOutOfBounds { index, length, .. } => write!(
264                f,
265                "index {index} out of bounds for array of length {length}"
266            ),
267            RenderError::NotIndexable { got, .. } => write!(f, "cannot index into {got}"),
268            RenderError::LambdaExpected { .. } => write!(f, "expected a lambda"),
269            RenderError::ValueTooDeep { limit, .. } => {
270                write!(f, "value nests deeper than the limit of {limit} levels")
271            }
272            RenderError::DuplicateKey { key, .. } => write!(f, "duplicate object key `{key}`"),
273            RenderError::Deserialize(msg) => write!(f, "deserialize error: {msg}"),
274        }
275    }
276}
277
278impl fmt::Display for LoadError {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        match self {
281            LoadError::Corrupt(s) => write!(f, "corrupt blob: {s}"),
282            LoadError::IncompatibleVersion { found, expected } => write!(
283                f,
284                "incompatible blob version: found {found}, expected {expected}"
285            ),
286        }
287    }
288}
289
290/// Why evaluating a unit failed.
291#[derive(Debug, Clone)]
292#[allow(missing_docs)] // variant fields name themselves
293pub enum EvalError {
294    /// The same errors a template render can produce.
295    Render(RenderError),
296    /// The [`Budget`](crate::Budget) ran out while evaluating the expression at `span`.
297    BudgetExceeded { limit: u64, span: Span },
298    /// Evaluations nested deeper than `limit` (host functions calling host
299    /// functions).
300    TooDeep { limit: u32, span: Span },
301}
302
303impl EvalError {
304    /// The source span this error points at, if it has one.
305    pub fn span(&self) -> Option<Span> {
306        match self {
307            EvalError::Render(e) => e.span(),
308            EvalError::BudgetExceeded { span, .. } | EvalError::TooDeep { span, .. } => Some(*span),
309        }
310    }
311
312    /// The error as an underlined snippet of the source the unit came from.
313    pub fn report(&self, src: &str) -> String {
314        snippet(&Lines::new(src), self.span(), &self.to_string())
315    }
316
317    /// Whether this is [`EvalError::BudgetExceeded`].
318    pub fn is_budget_exceeded(&self) -> bool {
319        matches!(self, EvalError::BudgetExceeded { .. })
320    }
321}
322
323impl From<RenderError> for EvalError {
324    fn from(e: RenderError) -> Self {
325        EvalError::Render(e)
326    }
327}
328
329impl fmt::Display for EvalError {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        match self {
332            EvalError::Render(e) => e.fmt(f),
333            EvalError::BudgetExceeded { limit, .. } => {
334                write!(f, "evaluation budget of {limit} steps exceeded")
335            }
336            EvalError::TooDeep { limit, .. } => {
337                write!(f, "evaluation nests more than {limit} levels deep")
338            }
339        }
340    }
341}
342
343impl std::error::Error for EvalError {
344    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
345        match self {
346            EvalError::Render(e) => Some(e),
347            EvalError::BudgetExceeded { .. } | EvalError::TooDeep { .. } => None,
348        }
349    }
350}
351
352impl std::error::Error for CompileError {}
353impl std::error::Error for RenderError {}
354impl std::error::Error for LoadError {}
355
356pub(crate) fn arity_message(name: &str, takes: &str, got: usize) -> String {
357    format!("`{name}` takes {takes}, got {got}")
358}
359
360pub(crate) fn arguments(count: usize) -> String {
361    if count == 1 {
362        "1 argument".to_string()
363    } else {
364        format!("{count} arguments")
365    }
366}
367
368/// Line starts of a source, so placing many spans scans it once.
369pub(crate) struct Lines<'a> {
370    src: &'a str,
371    starts: Vec<usize>,
372}
373
374impl<'a> Lines<'a> {
375    pub(crate) fn new(src: &'a str) -> Self {
376        let mut starts = vec![0];
377        starts.extend(
378            src.bytes()
379                .enumerate()
380                .filter(|&(_, b)| b == b'\n')
381                .map(|(i, _)| i + 1),
382        );
383        Lines { src, starts }
384    }
385
386    pub(crate) fn locate(&self, at: usize) -> Location<'a> {
387        let at = floor_char_boundary(self.src, at);
388        let line_index = self.starts.partition_point(|&start| start <= at) - 1;
389        let start = self.starts[line_index];
390        let end = self
391            .starts
392            .get(line_index + 1)
393            .map_or(self.src.len(), |&next_start| next_start - 1);
394        let text = self.src[start..end]
395            .strip_suffix('\r')
396            .unwrap_or(&self.src[start..end]);
397        Location {
398            line: line_index + 1,
399            column: self.src[start..at].chars().count() + 1,
400            text,
401        }
402    }
403}
404
405/// 1-based line and column (in characters), and the line's text.
406pub(crate) struct Location<'a> {
407    pub line: usize,
408    pub column: usize,
409    pub text: &'a str,
410}
411
412pub(crate) fn snippet(lines: &Lines, span: Option<Span>, message: &str) -> String {
413    let Some(span) = span else {
414        return format!("error: {message}");
415    };
416    let at = lines.locate(span.start as usize);
417    let line_number = at.line.to_string();
418    let gutter = " ".repeat(line_number.len());
419    let indent = " ".repeat(at.column - 1);
420    let carets = "^".repeat(caret_width(lines.src, span));
421    format!(
422        "error: {message}\n{gutter} --> {}:{}\n{gutter} |\n{line_number} | {}\n{gutter} | {indent}{carets}",
423        at.line, at.column, at.text
424    )
425}
426
427fn caret_width(src: &str, span: Span) -> usize {
428    let start = floor_char_boundary(src, span.start as usize);
429    let end = floor_char_boundary(src, span.end as usize).max(start);
430    let first_line = src[start..end].split('\n').next().unwrap_or("");
431    first_line.chars().count().max(1)
432}
433
434fn floor_char_boundary(src: &str, mut i: usize) -> usize {
435    if i >= src.len() {
436        return src.len();
437    }
438    while i > 0 && !src.is_char_boundary(i) {
439        i -= 1;
440    }
441    i
442}