Skip to main content

arb/
err.rs

1//! `SpecError` — a lex/parse/build error that optionally carries the source
2//! span (char offsets) where it occurred, so the LSP can anchor a diagnostic to
3//! the real location. It converts freely to/from `String` (via the `From` impls
4//! below), so every existing caller that used `Result<_, String>` keeps working:
5//! `?` widens a `String` error into a spanless `SpecError`, and a `SpecError`
6//! narrows back to its message for anything that still wants a `String`.
7
8use std::fmt;
9
10/// An error with an optional `(start, end)` char-offset span in the source.
11#[derive(Debug, Clone)]
12pub struct SpecError {
13    pub msg: String,
14    pub span: Option<(usize, usize)>,
15}
16
17impl SpecError {
18    /// Attach a span if none is set yet (keeps a more precise inner span).
19    pub fn or_span(mut self, start: usize, len: usize) -> Self {
20        if self.span.is_none() {
21            self.span = Some((start, start + len));
22        }
23        self
24    }
25}
26
27impl fmt::Display for SpecError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        f.write_str(&self.msg)
30    }
31}
32
33impl From<String> for SpecError {
34    fn from(msg: String) -> Self {
35        SpecError { msg, span: None }
36    }
37}
38
39impl From<&str> for SpecError {
40    fn from(msg: &str) -> Self {
41        SpecError {
42            msg: msg.to_string(),
43            span: None,
44        }
45    }
46}
47
48impl From<&String> for SpecError {
49    fn from(msg: &String) -> Self {
50        SpecError {
51            msg: msg.clone(),
52            span: None,
53        }
54    }
55}
56
57impl From<SpecError> for String {
58    fn from(e: SpecError) -> String {
59        e.msg
60    }
61}