Skip to main content

tabnas/
error.rs

1// Copyright (c) 2013-2026 Richard Rodger, MIT License
2
3use serde::ser::{Serialize, SerializeStruct, Serializer};
4use std::any::Any;
5use std::collections::{BTreeMap, HashMap};
6use std::fmt;
7use std::fmt::Write;
8use std::panic::{catch_unwind, AssertUnwindSafe};
9
10use crate::options::{ColorOptions, ErrorSuffix, ErrorSuffixContext, Options};
11use crate::token::Token;
12use crate::value::Value;
13
14#[derive(Debug, Clone, PartialEq)]
15pub struct ErrorToken {
16    pub name: String,
17    pub src: String,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct RecoveredAt {
22    pub skipped: usize,
23    pub sync: Option<crate::token::Tin>,
24    pub bad: bool,
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct TabnasError {
29    pub code: String,
30    pub detail: String,
31    pub pos: usize,
32    pub row: usize,
33    pub col: usize,
34    pub src: String,
35    pub hint: String,
36    pub tag: String,
37    pub full_source: String,
38    pub len: usize,
39    pub rule: String,
40    pub rule_stack: Vec<String>,
41    pub token: ErrorToken,
42    pub expected: Vec<String>,
43    pub plugins: Vec<String>,
44    /// Recovery metadata is intentionally not part of the stable serialized
45    /// diagnostic schema, matching the canonical implementations.
46    pub recovered: Option<RecoveredAt>,
47    details: HashMap<String, Value>,
48    rendered_detail: String,
49    rendered_hint: String,
50    instance_tag: String,
51    rule_state: String,
52    why: String,
53    suffix: ErrorSuffix,
54    link: String,
55    color: ColorOptions,
56    /// The row and column `full_source` starts at: 1 and 1 for the whole
57    /// source, and in a parse from a reader where the window begins, which
58    /// may cut its first line ([`TabnasError::set_excerpt`]).
59    source_row: usize,
60    source_col: usize,
61}
62
63impl TabnasError {
64    pub fn new(
65        code: impl Into<String>,
66        src: impl Into<String>,
67        full_source: impl Into<String>,
68        pos: usize,
69        row: usize,
70        col: usize,
71    ) -> Self {
72        let code_str = code.into();
73        let src_str = src.into();
74        let len = src_str.chars().count();
75        let full_src = full_source.into();
76        let detail = format_error_message(&code_str, &src_str);
77        let hint = format_error_hint(&code_str, &src_str);
78
79        TabnasError {
80            code: code_str,
81            detail: detail.clone(),
82            pos,
83            row,
84            col,
85            src: src_str.clone(),
86            hint: hint.clone(),
87            tag: "tabnas".to_string(),
88            full_source: full_src,
89            len,
90            rule: String::new(),
91            rule_stack: Vec::new(),
92            token: ErrorToken {
93                name: "#BD".to_string(),
94                src: src_str,
95            },
96            expected: Vec::new(),
97            plugins: Vec::new(),
98            recovered: None,
99            details: HashMap::new(),
100            rendered_detail: detail,
101            rendered_hint: hint,
102            instance_tag: "-".into(),
103            rule_state: String::new(),
104            why: String::new(),
105            suffix: ErrorSuffix::Standard,
106            link: String::new(),
107            color: ColorOptions::default(),
108            source_row: 1,
109            source_col: 1,
110        }
111    }
112
113    /// Give the error the text it shows its line from, and the row and
114    /// column that text starts at: the whole source, from row 1 and column
115    /// 1, or in a parse from a reader the window, from where the window
116    /// begins, its first line cut there.
117    pub(crate) fn set_excerpt(&mut self, text: String, first_row: usize, first_col: usize) {
118        self.full_source = text;
119        self.source_row = first_row.max(1);
120        self.source_col = first_col.max(1);
121    }
122
123    pub(crate) fn apply_options(&mut self, options: &Options) {
124        let render = ErrorRender {
125            code: &self.code,
126            src: &self.src,
127            pos: self.pos,
128            row: self.row,
129            col: self.col,
130            rule: &self.rule,
131            details: &self.details,
132        };
133        let next_detail = format_from_catalog(&options.error, &render);
134        if self.detail == self.rendered_detail {
135            self.detail = next_detail.clone();
136        }
137        self.rendered_detail = next_detail;
138
139        let next_hint = format_hint_from_catalog(&options.hint, &render);
140        if self.hint == self.rendered_hint {
141            self.hint = next_hint.clone();
142        }
143        self.rendered_hint = next_hint;
144
145        self.tag.clone_from(&options.errmsg.name);
146        self.instance_tag.clone_from(&options.tag);
147        self.suffix.clone_from(&options.errmsg.suffix);
148        self.link.clone_from(&options.errmsg.link);
149        self.color.clone_from(&options.color);
150    }
151
152    pub(crate) fn from_panic(
153        payload: Box<dyn Any + Send>,
154        api: &str,
155        full_source: &str,
156        pos: usize,
157        row: usize,
158        col: usize,
159        options: &Options,
160    ) -> Self {
161        let mut error = if let Some(error) = payload.downcast_ref::<Self>() {
162            error.clone()
163        } else if let Some(error) = payload.downcast_ref::<Box<Self>>() {
164            (**error).clone()
165        } else {
166            let detail = payload
167                .downcast_ref::<&str>()
168                .map(|message| (*message).to_string())
169                .or_else(|| payload.downcast_ref::<String>().cloned())
170                .unwrap_or_else(|| "unknown panic".into());
171            Self::new(
172                "internal",
173                format!("{api}: {detail}"),
174                full_source,
175                pos,
176                row,
177                col,
178            )
179        };
180        if error.full_source.is_empty() {
181            error.full_source = full_source.into();
182        }
183        if error.row == 0 {
184            error.row = row;
185        }
186        if error.col == 0 {
187            error.col = col;
188        }
189        error.apply_options(options);
190        error
191    }
192
193    pub fn attach_context(
194        &mut self,
195        rule: &str,
196        rule_state: &str,
197        rule_stack: Vec<String>,
198        token: Option<&Token>,
199        mut expected: Vec<String>,
200    ) {
201        self.rule = rule.to_string();
202        self.rule_state = rule_state.to_string();
203        self.rule_stack = rule_stack;
204        expected.sort();
205        expected.dedup();
206        self.expected = expected;
207        if let Some(token) = token {
208            self.pos = token.site.pos;
209            self.row = token.site.ri;
210            self.col = token.site.ci;
211            self.len = token.src.chars().count();
212            self.token = ErrorToken {
213                name: token.name.to_string(),
214                src: token.src.to_string(),
215            };
216            self.details.clone_from(token.use_data());
217            self.why = if token.why.is_empty() {
218                token.err.to_string()
219            } else {
220                token.why.to_string()
221            };
222        }
223    }
224
225    fn source_line(&self) -> String {
226        // A row before the excerpt's first is not in it: no line.
227        let Some(index) = self.row.max(1).checked_sub(self.source_row) else {
228            return String::new();
229        };
230        self.full_source
231            .lines()
232            .nth(index)
233            .unwrap_or("")
234            .to_string()
235    }
236}
237
238impl Serialize for TabnasError {
239    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
240    where
241        S: Serializer,
242    {
243        let mut state = serializer.serialize_struct("TabnasError", 15)?;
244        state.serialize_field("status", "failure")?;
245        state.serialize_field("code", &self.code)?;
246        state.serialize_field("message", &self.detail)?;
247        state.serialize_field("hint", &self.hint)?;
248        state.serialize_field("row", &self.row)?;
249        state.serialize_field("col", &self.col)?;
250        state.serialize_field("pos", &self.pos)?;
251        state.serialize_field("len", &self.len)?;
252        state.serialize_field("rule", &self.rule)?;
253        state.serialize_field("ruleStack", &self.rule_stack)?;
254        state.serialize_field(
255            "token",
256            &serde_json::json!({"name": self.token.name, "src": self.token.src}),
257        )?;
258        state.serialize_field("expected", &self.expected)?;
259        state.serialize_field("src", &self.source_line())?;
260        state.serialize_field("plugins", &self.plugins)?;
261        state.serialize_field("version", crate::VERSION)?;
262        state.end()
263    }
264}
265
266impl fmt::Display for TabnasError {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        let (hi, lo, line, reset) = self.color.codes();
269        write!(
270            f,
271            "{hi}[{}/{}]:{reset} {}\n  {line}-->{reset} <no-file>:{}:{}",
272            self.tag, self.code, self.detail, self.row, self.col
273        )?;
274
275        if !self.full_source.is_empty() {
276            let site = source_site(
277                &self.full_source,
278                (self.source_row, self.source_col),
279                &self.src,
280                &self.detail,
281                self.row,
282                self.col,
283                &self.color,
284            );
285            if !site.is_empty() {
286                write!(f, "\n{site}")?;
287            }
288        }
289
290        if !self.hint.is_empty() {
291            for (index, hint_line) in self.hint.trim().lines().enumerate() {
292                if index == 0 {
293                    write!(f, "\n\n  {hint_line}")?;
294                } else {
295                    write!(f, "\n  {hint_line}")?;
296                }
297            }
298        }
299
300        match &self.suffix {
301            ErrorSuffix::Disabled => {}
302            ErrorSuffix::Text(text) => write!(f, "\n{text}")?,
303            ErrorSuffix::Callback(render) => {
304                let context = ErrorSuffixContext {
305                    code: self.code.clone(),
306                    source: self.src.clone(),
307                    message: self.detail.clone(),
308                    hint: self.hint.clone(),
309                    pos: self.pos,
310                    row: self.row,
311                    col: self.col,
312                    name: self.tag.clone(),
313                    tag: self.instance_tag.clone(),
314                    rule: self.rule.clone(),
315                    rule_state: self.rule_state.clone(),
316                    token: self.token.name.clone(),
317                    why: self.why.clone(),
318                    plugins: self.plugins.clone(),
319                    color: self.color.clone(),
320                };
321                let suffix = catch_unwind(AssertUnwindSafe(|| render(&context)))
322                    .unwrap_or_else(|_| "--internal: errmsg.suffix callback panicked--".into());
323                write!(f, "\n{suffix}")?;
324            }
325            ErrorSuffix::Standard => {
326                if !self.link.is_empty() {
327                    write!(f, "\n\n  {lo}{}{reset}", self.link)?;
328                }
329                write!(
330                    f,
331                    "\n\n  {lo}--internal: tag={}; rule={}~{}; token={}",
332                    self.instance_tag, self.rule, self.rule_state, self.token.name
333                )?;
334                if !self.why.is_empty() {
335                    write!(f, "~{}", self.why)?;
336                }
337                write!(f, "; plugins={}--{reset}", self.plugins.join(","))?;
338            }
339        }
340
341        Ok(())
342    }
343}
344
345impl std::error::Error for TabnasError {}
346
347pub(crate) fn default_error_messages() -> HashMap<String, String> {
348    [
349        ("unknown", "unknown error: {code}"),
350        ("unexpected", "unexpected character(s): {src}"),
351        ("invalid_unicode", "invalid unicode escape: {src}"),
352        ("invalid_ascii", "invalid ascii escape: {src}"),
353        ("unprintable", "unprintable character: {src}"),
354        ("unterminated_string", "unterminated string: {src}"),
355        ("unterminated_comment", "unterminated comment: {src}"),
356        ("unknown_rule", "unknown rule: {rulename}"),
357        ("end_of_source", "unexpected end of source"),
358        ("cancel", "parse cancelled"),
359        ("internal", "internal error: {src}"),
360        ("unreadable", "the source could not be read: {src}"),
361    ]
362    .into_iter()
363    .map(|(code, template)| (code.into(), template.into()))
364    .collect()
365}
366
367pub(crate) fn default_error_hints() -> HashMap<String, String> {
368    [
369        (
370            "unknown",
371            "Unknown error code: {code}\nDetails:\n{details}",
372        ),
373        (
374            "unexpected",
375            "The character(s) {src} do not match any rule alternative active at\nthis position.",
376        ),
377        (
378            "invalid_unicode",
379            "The escape sequence {src} does not encode a valid unicode code point.",
380        ),
381        (
382            "invalid_ascii",
383            "The escape sequence {src} does not encode a valid ASCII character.",
384        ),
385        (
386            "unprintable",
387            "The character {src} (code point below 32) is not allowed inside a\nstring literal.",
388        ),
389        ("unterminated_string", "This string has no end quote."),
390        ("unterminated_comment", "This comment is never closed."),
391        ("unknown_rule", "No rule named {rulename} is defined."),
392        ("end_of_source", "Unexpected end of source."),
393        (
394            "cancel",
395            "The parse was cancelled by the caller's parse.budget.onCheck callback\n(or exceeded its configured budget) before completing.",
396        ),
397        (
398            "internal",
399            "The parser failed unexpectedly; this is a bug in tabnas\nor a plugin, not in your input.",
400        ),
401        (
402            "unreadable",
403            "The reader the source came from failed, or gave bytes that\nare not UTF-8, so the parse ends where the source does.",
404        ),
405    ]
406    .into_iter()
407    .map(|(code, template)| (code.into(), template.into()))
408    .collect()
409}
410
411pub fn format_error_message(code: &str, src: &str) -> String {
412    format_from_catalog(
413        &default_error_messages(),
414        &ErrorRender {
415            code,
416            src,
417            pos: 0,
418            row: 1,
419            col: 1,
420            rule: if code == "unknown_rule" { src } else { "" },
421            details: &HashMap::new(),
422        },
423    )
424}
425
426pub fn format_error_hint(code: &str, src: &str) -> String {
427    format_hint_from_catalog(
428        &default_error_hints(),
429        &ErrorRender {
430            code,
431            src,
432            pos: 0,
433            row: 1,
434            col: 1,
435            rule: if code == "unknown_rule" { src } else { "" },
436            details: &HashMap::new(),
437        },
438    )
439}
440
441struct ErrorRender<'a> {
442    code: &'a str,
443    src: &'a str,
444    pos: usize,
445    row: usize,
446    col: usize,
447    rule: &'a str,
448    details: &'a HashMap<String, Value>,
449}
450
451fn format_from_catalog(catalog: &HashMap<String, String>, render: &ErrorRender<'_>) -> String {
452    let defaults = default_error_messages();
453    let template = catalog
454        .get(render.code)
455        .filter(|template| !template.is_empty())
456        .or_else(|| {
457            catalog
458                .get("unknown")
459                .filter(|template| !template.is_empty())
460        })
461        .or_else(|| defaults.get("unknown"))
462        .map(String::as_str)
463        .unwrap_or("unknown error: {code}");
464    interpolate(template, &interpolation_vars(render))
465}
466
467fn format_hint_from_catalog(catalog: &HashMap<String, String>, render: &ErrorRender<'_>) -> String {
468    let defaults = default_error_hints();
469    let Some(template) = catalog
470        .get(render.code)
471        .filter(|template| !template.is_empty())
472        .or_else(|| {
473            catalog
474                .get("unknown")
475                .filter(|template| !template.is_empty())
476        })
477        .or_else(|| defaults.get("unknown"))
478    else {
479        return String::new();
480    };
481    interpolate(template, &interpolation_vars(render))
482        .trim()
483        .to_string()
484}
485
486fn interpolation_vars(render: &ErrorRender<'_>) -> HashMap<String, String> {
487    let mut vars = HashMap::new();
488    vars.insert("code".into(), render.code.into());
489    vars.insert("src".into(), render.src.into());
490    vars.insert("pos".into(), render.pos.to_string());
491    vars.insert("row".into(), render.row.to_string());
492    vars.insert("col".into(), render.col.to_string());
493    let unknown_rule_name = render
494        .details
495        .get("rulename")
496        .map(injection_value)
497        .unwrap_or_else(|| {
498            if render.code == "unknown_rule" && render.rule.is_empty() {
499                render.src.into()
500            } else {
501                render.rule.into()
502            }
503        });
504    vars.insert("rulename".into(), unknown_rule_name);
505    for (key, value) in render.details {
506        vars.insert(key.clone(), injection_value(value));
507    }
508    vars.insert("details".into(), format_details(render.details));
509    vars
510}
511
512fn injection_value(value: &Value) -> String {
513    match value {
514        Value::Undefined => String::new(),
515        Value::Null => "null".into(),
516        Value::Bool(value) => value.to_string(),
517        Value::Number(value) => value.to_string(),
518        Value::String(value) => value.clone(),
519        other => serde_json::to_string(other).unwrap_or_else(|_| other.to_string()),
520    }
521}
522
523fn format_details(details: &HashMap<String, Value>) -> String {
524    let ordered: BTreeMap<_, _> = details.iter().collect();
525    let json = serde_json::to_string(&ordered).unwrap_or_else(|_| "{}".into());
526    json.replace('"', "")
527}
528
529fn interpolate(template: &str, vars: &HashMap<String, String>) -> String {
530    let mut out = String::with_capacity(template.len());
531    let mut chars = template.chars().peekable();
532    while let Some(c) = chars.next() {
533        if c == '{' {
534            let mut key = String::new();
535            while let Some(&k) = chars.peek() {
536                chars.next();
537                if k == '}' {
538                    break;
539                }
540                key.push(k);
541            }
542            if let Some(val) = vars.get(key.as_str()) {
543                out.push_str(val);
544            } else {
545                out.push('{');
546                out.push_str(&key);
547                out.push('}');
548            }
549        } else {
550            out.push(c);
551        }
552    }
553    out
554}
555
556fn source_site(
557    source: &str,
558    (first_row, first_col): (usize, usize),
559    span: &str,
560    message: &str,
561    row: usize,
562    col: usize,
563    color: &ColorOptions,
564) -> String {
565    let row = row.max(1);
566    let col = col.max(1);
567    let lines: Vec<_> = source.split('\n').collect();
568    if lines.is_empty() {
569        return String::new();
570    }
571    // `source` begins at `first_row` and `first_col`: the whole source at
572    // 1 and 1, or the window of a parse from a reader, whose first line
573    // the window cuts. A row before it is not shown.
574    let Some(offset) = row.checked_sub(first_row) else {
575        return String::new();
576    };
577    let line_index = offset.min(lines.len() - 1);
578    let line_start = if line_index == 0 { first_col } else { 1 };
579    let pad = (row + 2).to_string().len() + 2;
580    let (_, _, line_color, reset) = color.codes();
581    let mut output = Vec::new();
582    let render_line = |number: usize, text: &str| {
583        format!("{line_color}{number:>width$} | {reset}{text}", width = pad)
584    };
585
586    if line_index >= 2 {
587        output.push(render_line(row - 2, lines[line_index - 2]));
588    }
589    if line_index >= 1 {
590        output.push(render_line(row - 1, lines[line_index - 1]));
591    }
592    output.push(render_line(row, lines[line_index]));
593
594    let caret_count = span.chars().count().max(1);
595    let mut caret = String::new();
596    write!(
597        caret,
598        "{}   {}{line_color}{} {message}{reset}",
599        " ".repeat(pad),
600        " ".repeat(col.saturating_sub(line_start)),
601        "^".repeat(caret_count),
602    )
603    .expect("writing to a String cannot fail");
604    output.push(caret);
605
606    if line_index + 1 < lines.len() {
607        output.push(render_line(row + 1, lines[line_index + 1]));
608    }
609    if line_index + 2 < lines.len() {
610        output.push(render_line(row + 2, lines[line_index + 2]));
611    }
612    output.join("\n")
613}