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
//! Error type returned by the parser upon failure.
//!
//! This error type is used to provide context to an error which occurs during the parsing stage.
use std::{error::Error, fmt::Display};
use thiserror::Error;

use crate::event::Grouping;
use super::SpanStack;

/// Anything that could possibly go wrong while parsing.
///
/// This error type is used to provide context to an error which occurs during the parsing stage.
///
/// The [`Parser`](crate::Parser) implements the [`Iterator`] trait, which returns a stream of `Result<Event, ParserError>`.
#[derive(Debug)]
pub struct ParserError {
    inner: Box<Inner>,
}

#[derive(Debug)]
struct Inner {
    error: ErrorKind,
    context: Box<str>,
}

impl ParserError {
    pub(super) fn new(error: ErrorKind, place: *const u8, span_stack: &mut SpanStack) -> Self {
        const CONTEXT_SIZE: usize = 12;
        const CONTEXT_PREFIX: &str = "context: ";
        const EXPANSION_PREFIX: &str = "which was expanded from: ";

        let index = span_stack.reach_original_call_site(place);
        let mut context = String::from(CONTEXT_PREFIX);

        let first_string = span_stack
            .expansions
            .last()
            .map(|exp| exp.full_expansion)
            .unwrap_or(span_stack.input);

        let (mut lower_bound, mut upper_bound) = (
            floor_char_boundary(first_string, index.saturating_sub(CONTEXT_SIZE)),
            floor_char_boundary(first_string, index + CONTEXT_SIZE),
        );

        span_stack
            .expansions
            .iter()
            .rev()
            .enumerate()
            .for_each(|(index, expansion)| {
                let context_str = &expansion.full_expansion[lower_bound..upper_bound];
                context.push_str(context_str);
                context.push('\n');
                context.push_str(EXPANSION_PREFIX);

                let next_string = (span_stack.expansions.len() - 1)
                    .checked_sub(index + 1)
                    .map(|index| span_stack.expansions[index].full_expansion)
                    .unwrap_or(span_stack.input);

                lower_bound = floor_char_boundary(
                    next_string,
                    expansion
                        .call_site_in_origin
                        .start
                        .saturating_sub(CONTEXT_SIZE),
                );
                upper_bound = floor_char_boundary(
                    next_string,
                    expansion.call_site_in_origin.end + CONTEXT_SIZE,
                );
            });
        context.push_str(&span_stack.input[lower_bound..upper_bound]);
        context.shrink_to_fit();

        Self {
            inner: Box::new(Inner {
                error,
                context: context.into_boxed_str(),
            }),
        }
    }
}

impl Error for ParserError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.inner.error)
    }
}

impl Display for ParserError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("parsing error: ")?;
        self.inner.error.fmt(f)?;
        f.write_str("\n")?;
        f.write_str(&self.inner.context)?;
        Ok(())
    }
}

pub(crate) type InnerResult<T> = std::result::Result<T, ErrorKind>;

#[derive(Debug, Error)]
pub(crate) enum ErrorKind {
    // TODO: this error is very misleading. Rework it.
    #[error("unbalanced group found, expected {:?}", .0)]
    UnbalancedGroup(Option<Grouping>),
    #[error("unkown mathematical environment found")]
    Environment,
    #[error(
        "unexpected math `$` (math shift) character - this character cannot be used inside math mode"
    )]
    MathShift,
    #[error(
        "unexpected hash sign `#` character - this character can only be used in macro definitions"
    )]
    HashSign,
    #[error("unexpected end of input")]
    EndOfInput,
    #[error("expected a dimension or glue argument")]
    DimensionArgument,
    #[error("expected a dimensional unit")]
    DimensionUnit,
    #[error("expected mathematical units (mu) in dimension specification")]
    MathUnit,
    #[error("expected a delimiter token")]
    Delimiter,
    #[error("expected a control sequence")]
    ControlSequence,
    #[error("expected a number")]
    Number,
    #[error("expected a character representing a number after '`'. found a non ascii character")]
    CharacterNumber,
    #[error("expected an argument")]
    Argument,
    #[error("expected an argument delimited by `{{}}`")]
    GroupArgument,
    #[error("trying to add a subscript twice to the same element")]
    DoubleSubscript,
    #[error("trying to add a superscript twice to the same element")]
    DoubleSuperscript,
    #[error("unknown primitive command found")]
    UnknownPrimitive,
    #[error("control sequence found as argument to a command that does not support them")]
    ControlSequenceAsArgument,
    #[error("subscript and/or superscript found as argument to a command")]
    ScriptAsArgument,
    #[error("empty control sequence")]
    EmptyControlSequence,
    #[error("unkown color. colors must either be predefined or in the form `#RRGGBB`")]
    UnknownColor,
    #[error("expected a number in the range 0..=255 for it to be translated into a character")]
    InvalidCharNumber,
    #[error("cannot use the `\\relax` command in this context")]
    Relax,
    #[error("macro definition of parameters contains '{{' or '}}'")]
    BracesInParamText,
    #[error("macro definition of parameters contains a (`%`) comment")]
    CommentInParamText,
    #[error("macro definition found parameter #{0} but expected #{1}")]
    IncorrectMacroParams(u8, u8),
    #[error(
        "macro definition found parameter #{0} but expected a parameter in the range [#1, #{1}]"
    )]
    IncorrectReplacementParams(u8, u8),
    #[error("macro definition contains too many parameters, the maximum is 9")]
    TooManyParams,
    #[error("macro definition contains a standalone '#'")]
    StandaloneHashSign,
    // TODO: should specify what the macro expects the prefix string to be.
    #[error("macro use does not match its definition, expected it to begin with a prefix string as specified in the definition")]
    IncorrectMacroPrefix,
    #[error("macro already defined")]
    MacroAlreadyDefined,
    #[error("macro not defined")]
    MacroNotDefined,
}

fn floor_char_boundary(str: &str, index: usize) -> usize {
    if index >= str.len() {
        str.len()
    } else {
        let lower_bound = index.saturating_sub(3);
        let new_index = str.as_bytes()[lower_bound..=index].iter().rposition(|b| {
            // This is bit magic equivalent to: b < 128 || b >= 192
            (*b as i8) >= -0x40
        });

        // SAFETY: we know that the character boundary will be within four bytes
        unsafe { lower_bound + new_index.unwrap_unchecked() }
    }
}