tabnas-parser 0.12.9

A dynamic JSON parser that isn't strict and can be customized.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
// Copyright (c) 2013-2026 Richard Rodger, MIT License

use serde::ser::{Serialize, SerializeStruct, Serializer};
use std::any::Any;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::fmt::Write;
use std::panic::{catch_unwind, AssertUnwindSafe};

use crate::options::{ColorOptions, ErrorSuffix, ErrorSuffixContext, Options};
use crate::token::Token;
use crate::value::Value;

#[derive(Debug, Clone, PartialEq)]
pub struct ErrorToken {
    pub name: String,
    pub src: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecoveredAt {
    pub skipped: usize,
    pub sync: Option<crate::token::Tin>,
    pub bad: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TabnasError {
    pub code: String,
    pub detail: String,
    pub pos: usize,
    pub row: usize,
    pub col: usize,
    pub src: String,
    pub hint: String,
    pub tag: String,
    pub full_source: String,
    pub len: usize,
    pub rule: String,
    pub rule_stack: Vec<String>,
    pub token: ErrorToken,
    pub expected: Vec<String>,
    pub plugins: Vec<String>,
    /// Recovery metadata is intentionally not part of the stable serialized
    /// diagnostic schema, matching the canonical implementations.
    pub recovered: Option<RecoveredAt>,
    details: HashMap<String, Value>,
    rendered_detail: String,
    rendered_hint: String,
    instance_tag: String,
    rule_state: String,
    why: String,
    suffix: ErrorSuffix,
    link: String,
    color: ColorOptions,
}

impl TabnasError {
    pub fn new(
        code: impl Into<String>,
        src: impl Into<String>,
        full_source: impl Into<String>,
        pos: usize,
        row: usize,
        col: usize,
    ) -> Self {
        let code_str = code.into();
        let src_str = src.into();
        let len = src_str.chars().count();
        let full_src = full_source.into();
        let detail = format_error_message(&code_str, &src_str);
        let hint = format_error_hint(&code_str, &src_str);

        TabnasError {
            code: code_str,
            detail: detail.clone(),
            pos,
            row,
            col,
            src: src_str.clone(),
            hint: hint.clone(),
            tag: "tabnas".to_string(),
            full_source: full_src,
            len,
            rule: String::new(),
            rule_stack: Vec::new(),
            token: ErrorToken {
                name: "#BD".to_string(),
                src: src_str,
            },
            expected: Vec::new(),
            plugins: Vec::new(),
            recovered: None,
            details: HashMap::new(),
            rendered_detail: detail,
            rendered_hint: hint,
            instance_tag: "-".into(),
            rule_state: String::new(),
            why: String::new(),
            suffix: ErrorSuffix::Standard,
            link: String::new(),
            color: ColorOptions::default(),
        }
    }

    pub(crate) fn apply_options(&mut self, options: &Options) {
        let render = ErrorRender {
            code: &self.code,
            src: &self.src,
            pos: self.pos,
            row: self.row,
            col: self.col,
            rule: &self.rule,
            details: &self.details,
        };
        let next_detail = format_from_catalog(&options.error, &render);
        if self.detail == self.rendered_detail {
            self.detail = next_detail.clone();
        }
        self.rendered_detail = next_detail;

        let next_hint = format_hint_from_catalog(&options.hint, &render);
        if self.hint == self.rendered_hint {
            self.hint = next_hint.clone();
        }
        self.rendered_hint = next_hint;

        self.tag.clone_from(&options.errmsg.name);
        self.instance_tag.clone_from(&options.tag);
        self.suffix.clone_from(&options.errmsg.suffix);
        self.link.clone_from(&options.errmsg.link);
        self.color.clone_from(&options.color);
    }

    pub(crate) fn from_panic(
        payload: Box<dyn Any + Send>,
        api: &str,
        full_source: &str,
        pos: usize,
        row: usize,
        col: usize,
        options: &Options,
    ) -> Self {
        let mut error = if let Some(error) = payload.downcast_ref::<Self>() {
            error.clone()
        } else if let Some(error) = payload.downcast_ref::<Box<Self>>() {
            (**error).clone()
        } else {
            let detail = payload
                .downcast_ref::<&str>()
                .map(|message| (*message).to_string())
                .or_else(|| payload.downcast_ref::<String>().cloned())
                .unwrap_or_else(|| "unknown panic".into());
            Self::new(
                "internal",
                format!("{api}: {detail}"),
                full_source,
                pos,
                row,
                col,
            )
        };
        if error.full_source.is_empty() {
            error.full_source = full_source.into();
        }
        if error.row == 0 {
            error.row = row;
        }
        if error.col == 0 {
            error.col = col;
        }
        error.apply_options(options);
        error
    }

    pub fn attach_context(
        &mut self,
        rule: &str,
        rule_state: &str,
        rule_stack: Vec<String>,
        token: Option<&Token>,
        mut expected: Vec<String>,
    ) {
        self.rule = rule.to_string();
        self.rule_state = rule_state.to_string();
        self.rule_stack = rule_stack;
        expected.sort();
        expected.dedup();
        self.expected = expected;
        if let Some(token) = token {
            self.pos = token.site.pos;
            self.row = token.site.ri;
            self.col = token.site.ci;
            self.len = token.src.chars().count();
            self.token = ErrorToken {
                name: token.name.to_string(),
                src: token.src.to_string(),
            };
            self.details.clone_from(token.use_data());
            self.why = if token.why.is_empty() {
                token.err.to_string()
            } else {
                token.why.to_string()
            };
        }
    }

    fn source_line(&self) -> String {
        self.full_source
            .lines()
            .nth(self.row.saturating_sub(1))
            .unwrap_or("")
            .to_string()
    }
}

impl Serialize for TabnasError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("TabnasError", 15)?;
        state.serialize_field("status", "failure")?;
        state.serialize_field("code", &self.code)?;
        state.serialize_field("message", &self.detail)?;
        state.serialize_field("hint", &self.hint)?;
        state.serialize_field("row", &self.row)?;
        state.serialize_field("col", &self.col)?;
        state.serialize_field("pos", &self.pos)?;
        state.serialize_field("len", &self.len)?;
        state.serialize_field("rule", &self.rule)?;
        state.serialize_field("ruleStack", &self.rule_stack)?;
        state.serialize_field(
            "token",
            &serde_json::json!({"name": self.token.name, "src": self.token.src}),
        )?;
        state.serialize_field("expected", &self.expected)?;
        state.serialize_field("src", &self.source_line())?;
        state.serialize_field("plugins", &self.plugins)?;
        state.serialize_field("version", crate::VERSION)?;
        state.end()
    }
}

impl fmt::Display for TabnasError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (hi, lo, line, reset) = self.color.codes();
        write!(
            f,
            "{hi}[{}/{}]:{reset} {}\n  {line}-->{reset} <no-file>:{}:{}",
            self.tag, self.code, self.detail, self.row, self.col
        )?;

        if !self.full_source.is_empty() {
            let site = source_site(
                &self.full_source,
                &self.src,
                &self.detail,
                self.row,
                self.col,
                &self.color,
            );
            if !site.is_empty() {
                write!(f, "\n{site}")?;
            }
        }

        if !self.hint.is_empty() {
            for (index, hint_line) in self.hint.trim().lines().enumerate() {
                if index == 0 {
                    write!(f, "\n\n  {hint_line}")?;
                } else {
                    write!(f, "\n  {hint_line}")?;
                }
            }
        }

        match &self.suffix {
            ErrorSuffix::Disabled => {}
            ErrorSuffix::Text(text) => write!(f, "\n{text}")?,
            ErrorSuffix::Callback(render) => {
                let context = ErrorSuffixContext {
                    code: self.code.clone(),
                    source: self.src.clone(),
                    message: self.detail.clone(),
                    hint: self.hint.clone(),
                    pos: self.pos,
                    row: self.row,
                    col: self.col,
                    name: self.tag.clone(),
                    tag: self.instance_tag.clone(),
                    rule: self.rule.clone(),
                    rule_state: self.rule_state.clone(),
                    token: self.token.name.clone(),
                    why: self.why.clone(),
                    plugins: self.plugins.clone(),
                    color: self.color.clone(),
                };
                let suffix = catch_unwind(AssertUnwindSafe(|| render(&context)))
                    .unwrap_or_else(|_| "--internal: errmsg.suffix callback panicked--".into());
                write!(f, "\n{suffix}")?;
            }
            ErrorSuffix::Standard => {
                if !self.link.is_empty() {
                    write!(f, "\n\n  {lo}{}{reset}", self.link)?;
                }
                write!(
                    f,
                    "\n\n  {lo}--internal: tag={}; rule={}~{}; token={}",
                    self.instance_tag, self.rule, self.rule_state, self.token.name
                )?;
                if !self.why.is_empty() {
                    write!(f, "~{}", self.why)?;
                }
                write!(f, "; plugins={}--{reset}", self.plugins.join(","))?;
            }
        }

        Ok(())
    }
}

impl std::error::Error for TabnasError {}

pub(crate) fn default_error_messages() -> HashMap<String, String> {
    [
        ("unknown", "unknown error: {code}"),
        ("unexpected", "unexpected character(s): {src}"),
        ("invalid_unicode", "invalid unicode escape: {src}"),
        ("invalid_ascii", "invalid ascii escape: {src}"),
        ("unprintable", "unprintable character: {src}"),
        ("unterminated_string", "unterminated string: {src}"),
        ("unterminated_comment", "unterminated comment: {src}"),
        ("unknown_rule", "unknown rule: {rulename}"),
        ("end_of_source", "unexpected end of source"),
        ("cancel", "parse cancelled"),
        ("internal", "internal error: {src}"),
    ]
    .into_iter()
    .map(|(code, template)| (code.into(), template.into()))
    .collect()
}

pub(crate) fn default_error_hints() -> HashMap<String, String> {
    [
        (
            "unknown",
            "Unknown error code: {code}\nDetails:\n{details}",
        ),
        (
            "unexpected",
            "The character(s) {src} do not match any rule alternative active at\nthis position.",
        ),
        (
            "invalid_unicode",
            "The escape sequence {src} does not encode a valid unicode code point.",
        ),
        (
            "invalid_ascii",
            "The escape sequence {src} does not encode a valid ASCII character.",
        ),
        (
            "unprintable",
            "The character {src} (code point below 32) is not allowed inside a\nstring literal.",
        ),
        ("unterminated_string", "This string has no end quote."),
        ("unterminated_comment", "This comment is never closed."),
        ("unknown_rule", "No rule named {rulename} is defined."),
        ("end_of_source", "Unexpected end of source."),
        (
            "cancel",
            "The parse was cancelled by the caller's parse.budget.onCheck callback\n(or exceeded its configured budget) before completing.",
        ),
        (
            "internal",
            "The parser failed unexpectedly; this is a bug in tabnas\nor a plugin, not in your input.",
        ),
    ]
    .into_iter()
    .map(|(code, template)| (code.into(), template.into()))
    .collect()
}

pub fn format_error_message(code: &str, src: &str) -> String {
    format_from_catalog(
        &default_error_messages(),
        &ErrorRender {
            code,
            src,
            pos: 0,
            row: 1,
            col: 1,
            rule: if code == "unknown_rule" { src } else { "" },
            details: &HashMap::new(),
        },
    )
}

pub fn format_error_hint(code: &str, src: &str) -> String {
    format_hint_from_catalog(
        &default_error_hints(),
        &ErrorRender {
            code,
            src,
            pos: 0,
            row: 1,
            col: 1,
            rule: if code == "unknown_rule" { src } else { "" },
            details: &HashMap::new(),
        },
    )
}

struct ErrorRender<'a> {
    code: &'a str,
    src: &'a str,
    pos: usize,
    row: usize,
    col: usize,
    rule: &'a str,
    details: &'a HashMap<String, Value>,
}

fn format_from_catalog(catalog: &HashMap<String, String>, render: &ErrorRender<'_>) -> String {
    let defaults = default_error_messages();
    let template = catalog
        .get(render.code)
        .filter(|template| !template.is_empty())
        .or_else(|| {
            catalog
                .get("unknown")
                .filter(|template| !template.is_empty())
        })
        .or_else(|| defaults.get("unknown"))
        .map(String::as_str)
        .unwrap_or("unknown error: {code}");
    interpolate(template, &interpolation_vars(render))
}

fn format_hint_from_catalog(catalog: &HashMap<String, String>, render: &ErrorRender<'_>) -> String {
    let defaults = default_error_hints();
    let Some(template) = catalog
        .get(render.code)
        .filter(|template| !template.is_empty())
        .or_else(|| {
            catalog
                .get("unknown")
                .filter(|template| !template.is_empty())
        })
        .or_else(|| defaults.get("unknown"))
    else {
        return String::new();
    };
    interpolate(template, &interpolation_vars(render))
        .trim()
        .to_string()
}

fn interpolation_vars(render: &ErrorRender<'_>) -> HashMap<String, String> {
    let mut vars = HashMap::new();
    vars.insert("code".into(), render.code.into());
    vars.insert("src".into(), render.src.into());
    vars.insert("pos".into(), render.pos.to_string());
    vars.insert("row".into(), render.row.to_string());
    vars.insert("col".into(), render.col.to_string());
    let unknown_rule_name = render
        .details
        .get("rulename")
        .map(injection_value)
        .unwrap_or_else(|| {
            if render.code == "unknown_rule" && render.rule.is_empty() {
                render.src.into()
            } else {
                render.rule.into()
            }
        });
    vars.insert("rulename".into(), unknown_rule_name);
    for (key, value) in render.details {
        vars.insert(key.clone(), injection_value(value));
    }
    vars.insert("details".into(), format_details(render.details));
    vars
}

fn injection_value(value: &Value) -> String {
    match value {
        Value::Undefined => String::new(),
        Value::Null => "null".into(),
        Value::Bool(value) => value.to_string(),
        Value::Number(value) => value.to_string(),
        Value::String(value) => value.clone(),
        other => serde_json::to_string(other).unwrap_or_else(|_| other.to_string()),
    }
}

fn format_details(details: &HashMap<String, Value>) -> String {
    let ordered: BTreeMap<_, _> = details.iter().collect();
    let json = serde_json::to_string(&ordered).unwrap_or_else(|_| "{}".into());
    json.replace('"', "")
}

fn interpolate(template: &str, vars: &HashMap<String, String>) -> String {
    let mut out = String::with_capacity(template.len());
    let mut chars = template.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '{' {
            let mut key = String::new();
            while let Some(&k) = chars.peek() {
                chars.next();
                if k == '}' {
                    break;
                }
                key.push(k);
            }
            if let Some(val) = vars.get(key.as_str()) {
                out.push_str(val);
            } else {
                out.push('{');
                out.push_str(&key);
                out.push('}');
            }
        } else {
            out.push(c);
        }
    }
    out
}

fn source_site(
    source: &str,
    span: &str,
    message: &str,
    row: usize,
    col: usize,
    color: &ColorOptions,
) -> String {
    let row = row.max(1);
    let col = col.max(1);
    let lines: Vec<_> = source.split('\n').collect();
    if lines.is_empty() {
        return String::new();
    }
    let line_index = row.saturating_sub(1).min(lines.len() - 1);
    let pad = (row + 2).to_string().len() + 2;
    let (_, _, line_color, reset) = color.codes();
    let mut output = Vec::new();
    let render_line = |number: usize, text: &str| {
        format!("{line_color}{number:>width$} | {reset}{text}", width = pad)
    };

    if line_index >= 2 {
        output.push(render_line(row - 2, lines[line_index - 2]));
    }
    if line_index >= 1 {
        output.push(render_line(row - 1, lines[line_index - 1]));
    }
    output.push(render_line(row, lines[line_index]));

    let caret_count = span.chars().count().max(1);
    let mut caret = String::new();
    write!(
        caret,
        "{}   {}{line_color}{} {message}{reset}",
        " ".repeat(pad),
        " ".repeat(col - 1),
        "^".repeat(caret_count),
    )
    .expect("writing to a String cannot fail");
    output.push(caret);

    if line_index + 1 < lines.len() {
        output.push(render_line(row + 1, lines[line_index + 1]));
    }
    if line_index + 2 < lines.len() {
        output.push(render_line(row + 2, lines[line_index + 2]));
    }
    output.join("\n")
}