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
//! Error types and error display logic.

use crate::token;
use crate::token::trace;
use crate::vm;
use texcraft_stdext::algorithms::spellcheck::{self, WordDiff};

pub mod display;
#[cfg(feature = "serde")]
mod serde;

/// Texlang error type
///
/// Note that serializing and deserializing this type results in type erasure.
/// Also the serialization format is private.
/// This is not by design: the minimal amount of work was done to make the type
///     serializable, and future work to make this better is welcome!
#[derive(Debug)]
pub enum Error {
    Tex(Box<dyn TexError + 'static>),
    Propagated(PropagatedError),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        display::format_error(f, self)
    }
}

#[cfg(feature = "serde")]
impl ::serde::Serialize for Error {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ::serde::Serializer,
    {
        let serializable_error: serde::Error = self.into();
        serializable_error.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> ::serde::Deserialize<'de> for Error {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        let serializable_error = serde::Error::deserialize(deserializer)?;
        Ok(serializable_error.into())
    }
}

impl Error {
    pub fn new_propagated<S>(
        vm: &vm::VM<S>,
        context: PropagationContext,
        token: token::Token,
        error: Box<Error>,
    ) -> Box<Error> {
        Box::new(Error::Propagated(PropagatedError {
            context,
            token,
            trace: vm.trace(token),
            error,
        }))
    }

    pub fn stack_view(&self) -> (Vec<&PropagatedError>, &dyn TexError) {
        let mut stack: Vec<&PropagatedError> = vec![];
        let mut last = self;
        loop {
            match last {
                Error::Tex(error) => {
                    return (stack, error.as_ref());
                }
                Error::Propagated(propagated) => {
                    stack.push(propagated);
                    last = &propagated.error;
                }
            }
        }
    }
}

impl<T: TexError + 'static> From<T> for Box<Error> {
    fn from(err: T) -> Self {
        Box::new(Error::Tex(Box::new(err)))
    }
}

#[derive(Debug)]
pub struct PropagatedError {
    pub context: PropagationContext,
    pub token: token::Token,
    pub trace: trace::SourceCodeTrace,
    pub error: Box<Error>,
}

#[derive(Debug)]
pub enum Kind<'a> {
    Token(&'a trace::SourceCodeTrace),
    EndOfInput(&'a trace::SourceCodeTrace),
    FailedPrecondition,
}

pub trait TexError: std::fmt::Debug {
    fn kind(&self) -> Kind;

    fn title(&self) -> String;

    fn notes(&self) -> Vec<display::Note> {
        vec![]
    }

    fn source_annotation(&self) -> String {
        TexError::default_source_annotation(self)
    }

    fn default_source_annotation(&self) -> String {
        match TexError::kind(self) {
            Kind::Token(s) => {
                let t = s.token.unwrap();
                match (t.char(), t.cat_code()) {
                    (Some(c), Some(code)) => {
                        format!["character token with value {c} and category code {code}",]
                    }
                    _ => "control sequence".to_string(),
                }
            }
            Kind::EndOfInput(_) => "input ended here".into(),
            Kind::FailedPrecondition => "error occurred while running this command".into(),
        }
    }

    // TODO: have a method that returns the exact error messages as Knuth's TeX
    // The method will return a vector of static strings
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
pub enum PropagationContext {
    Expansion,
    Execution,
    VariableIndex,
    VariableAssignment,
}

impl PropagationContext {
    fn action(&self) -> &'static str {
        match self {
            PropagationContext::Expansion => "expanding this command",
            PropagationContext::Execution => "executing this command",
            PropagationContext::VariableIndex => "determining the index of this variable",
            PropagationContext::VariableAssignment => {
                "determining the value to assign to this variable"
            }
        }
    }
}

#[derive(Debug)]
pub struct SimpleTokenError {
    pub token: token::Token,
    pub trace: trace::SourceCodeTrace,
    pub title: String,
}

impl SimpleTokenError {
    /// Create a new simple token error.
    #[allow(clippy::new_ret_no_self)]
    pub fn new<S, T: AsRef<str>>(
        vm: &vm::VM<S>,
        token: token::Token,
        title: T,
    ) -> SimpleTokenError {
        let trace = vm.trace(token);
        SimpleTokenError {
            token,
            trace,
            title: title.as_ref().into(),
        }
    }
}

impl TexError for SimpleTokenError {
    fn kind(&self) -> Kind {
        Kind::Token(&self.trace)
    }

    fn title(&self) -> String {
        self.title.clone()
    }
}

#[derive(Debug)]
pub struct SimpleEndOfInputError {
    pub trace: trace::SourceCodeTrace,
    pub title: String,
    pub text_notes: Vec<String>,
}

impl SimpleEndOfInputError {
    /// Create a new simple end of input error.
    pub fn new<S, T: AsRef<str>>(vm: &vm::VM<S>, title: T) -> Self {
        Self {
            trace: vm.trace_end_of_input(),
            title: title.as_ref().into(),
            text_notes: vec![],
        }
    }

    pub fn with_note<T: Into<String>>(mut self, note: T) -> Self {
        self.text_notes.push(note.into());
        self
    }
}

impl TexError for SimpleEndOfInputError {
    fn kind(&self) -> Kind {
        Kind::EndOfInput(&self.trace)
    }

    fn title(&self) -> String {
        self.title.clone()
    }

    fn notes(&self) -> Vec<display::Note> {
        let mut notes = vec![];
        for text_note in &self.text_notes {
            notes.push(text_note.into())
        }
        notes
    }
}

#[derive(Debug)]
pub struct SimpleFailedPreconditionError {
    pub title: String,
    pub text_notes: Vec<String>,
}

impl SimpleFailedPreconditionError {
    /// Create a new simple failed precondition error.
    pub fn new<T: AsRef<str>>(title: T) -> Self {
        Self {
            title: title.as_ref().into(),
            text_notes: vec![],
        }
    }

    pub fn with_note<T: Into<String>>(mut self, note: T) -> Self {
        self.text_notes.push(note.into());
        self
    }
}

impl TexError for SimpleFailedPreconditionError {
    fn kind(&self) -> Kind {
        Kind::FailedPrecondition
    }

    fn title(&self) -> String {
        self.title.clone()
    }

    fn notes(&self) -> Vec<display::Note> {
        let mut notes = vec![];
        for text_note in &self.text_notes {
            notes.push(text_note.into())
        }
        notes
    }
}

#[derive(Debug)]
pub struct UndefinedCommandError {
    pub trace: trace::SourceCodeTrace,
    pub close_names: Vec<WordDiff>,
}

impl UndefinedCommandError {
    pub fn new<S>(vm: &vm::VM<S>, token: token::Token) -> UndefinedCommandError {
        let name = match &token.value() {
            token::Value::CommandRef(command_ref) => command_ref.to_string(vm.cs_name_interner()),
            _ => panic!("undefined command error does not work for non-command-ref tokens"),
        };
        let mut all_names = Vec::<String>::new();
        for (cs_name, _) in vm.get_commands_as_map_slow().into_iter() {
            all_names.push(cs_name);
        }
        let close_names = spellcheck::find_close_words(all_names, &name);

        UndefinedCommandError {
            trace: vm.trace(token),
            close_names,
        }
    }
}

impl TexError for UndefinedCommandError {
    fn kind(&self) -> Kind {
        Kind::Token(&self.trace)
    }

    fn title(&self) -> String {
        format!["undefined control sequence {}", &self.trace.value]
    }

    fn notes(&self) -> Vec<display::Note> {
        let mut notes: Vec<display::Note> = Default::default();
        use colored::Colorize;
        if let Some(close_name) = self.close_names.first() {
            notes.push(format!["did you mean \\{}?\n", close_name.right().bold(),].into());
        }
        notes
    }
}