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
pub use self::source::YggdrasilErrorSource;
use crate::{span::TextSpan, YggdrasilRule};
use alloc::{
    borrow::ToOwned,
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};
use core::{
    fmt,
    fmt::{Display, Formatter},
    ops::Range,
};

mod source;

/// Parse-related error type.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct YggdrasilError<R> {
    /// Variant of the error
    pub variant: YggdrasilErrorKind<R>,
    /// Location within the input string
    pub location: Range<usize>,
    /// The file path where the error occurred
    pub source: YggdrasilErrorSource,
}

/// Different kinds of parsing errors.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum YggdrasilErrorKind<R> {
    /// Generated parsing error with expected and unexpected `Rule`s
    InvalidRule {
        /// Positive attempts
        positives: Vec<R>,
        /// Negative attempts
        negatives: Vec<R>,
    },
    /// Unable to convert given node to ast
    InvalidNode {
        expect: R,
    },
    InvalidTag(InvalidTag),
    /// Custom error with a message
    CustomError {
        /// Short explanation
        message: String,
    },
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct InvalidTag {
    pub found: Vec<String>,
    pub expect: Vec<String>,
}

impl InvalidTag {
    pub fn new<T>(expect: T) -> Self
    where
        T: Into<String>,
    {
        Self { found: vec![], expect: vec![expect.into()] }
    }
    pub fn push_found<T>(&mut self, found: T)
    where
        T: Into<String>,
    {
        self.found.push(found.into())
    }
    pub fn with_span<R>(self, span: TextSpan<'_>) -> YggdrasilError<R> {
        let end = span.end_pos();
        YggdrasilError {
            variant: YggdrasilErrorKind::InvalidTag(self),
            location: span.start()..end.offset(),
            source: YggdrasilErrorSource::Missing,
        }
    }
}

impl<R: YggdrasilRule> YggdrasilError<R> {
    /// Creates `Error` from `ErrorVariant` and `Span`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use yggdrasil_rt::error::{YggdrasilError, ErrorKind};
    /// # use yggdrasil_rt::{Position, TextSpan};
    /// # #[allow(non_camel_case_types)]
    /// # #[allow(dead_code)]
    /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    /// # enum Rule {
    /// #     open_paren,
    /// #     closed_paren
    /// # }
    /// # let input = "";
    /// # let start = Position::from_start(input);
    /// # let end = start.clone();
    /// # let span = start.span(&end);
    /// let error = YggdrasilError::new_from_span(
    ///     ErrorKind::ParsingError {
    ///         positives: vec![Rule::open_paren],
    ///         negatives: vec![Rule::closed_paren],
    ///     },
    ///     span,
    /// );
    ///
    /// println!("{}", error);
    /// ```
    pub fn new_from_span(variant: YggdrasilErrorKind<R>, span: TextSpan<'_>) -> YggdrasilError<R> {
        let end = span.end_pos();
        // let end_line_col = end.line_column();
        // end position is after a \n, so we want to point to the visual lf symbol
        // if end_line_col.1 == 1 {
        //     let mut visual_end = end;
        //     visual_end.skip_back(1);
        // };
        Self { variant, location: span.start()..end.offset(), source: Default::default() }
    }

    /// unable to create node
    pub fn invalid_node(expect: R, span: TextSpan) -> YggdrasilError<R> {
        Self::new_from_span(YggdrasilErrorKind::InvalidNode { expect }, span)
    }
    /// missing rule
    pub fn missing_rule(expect: R, span: TextSpan) -> YggdrasilError<R> {
        Self::new_from_span(YggdrasilErrorKind::InvalidNode { expect }, span)
    }

    /// missing rule
    pub fn custom_error<S: Display>(message: S, span: TextSpan) -> YggdrasilError<R> {
        Self::new_from_span(YggdrasilErrorKind::CustomError { message: message.to_string() }, span)
    }

    /// Returns `Error` variant with `path` which is shown when formatted with `Display`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use yggdrasil_rt::{YggdrasilError};
    /// # use yggdrasil_rt::Position;
    /// # #[allow(non_camel_case_types)]
    /// # #[allow(dead_code)]
    /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    /// # enum Rule {
    /// #     open_paren,
    /// #     closed_paren
    /// # }
    /// # let input = "";
    /// # let pos = Position::from_start(input);
    /// YggdrasilError::new_from_offset(
    ///     ErrorKind::ParsingError {
    ///         positives: vec![Rule::open_paren],
    ///         negatives: vec![Rule::closed_paren],
    ///     },
    ///     pos,
    /// )
    /// .with_path("file.rs");
    /// ```
    pub fn with_path(mut self, path: &str) -> YggdrasilError<R> {
        self.source = YggdrasilErrorSource::Local(path.to_string());
        self
    }

    /// Returns the path set using [`YggdrasilError::with_path()`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use yggdrasil_rt::error::{YggdrasilError, ErrorKind};
    /// # use yggdrasil_rt::Position;
    /// # #[allow(non_camel_case_types)]
    /// # #[allow(dead_code)]
    /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    /// # enum Rule {
    /// #     open_paren,
    /// #     closed_paren
    /// # }
    /// # let input = "";
    /// # let pos = Position::from_start(input);
    /// # let error = YggdrasilError::new_from_offset(
    /// #     ErrorKind::ParsingError {
    /// #         positives: vec![Rule::open_paren],
    /// #         negatives: vec![Rule::closed_paren]
    /// #     },
    /// #     pos);
    /// let error = error.with_path("file.rs");
    /// assert_eq!(Some("file.rs"), error.path());
    /// ```
    pub fn get_local_path(&self) -> Option<&str> {
        match &self.source {
            YggdrasilErrorSource::Local(v) => Some(v.as_str()),
            _ => None,
        }
    }

    /// Renames all `Rule`s if this is a [`ParsingError`]. It does nothing when called on a
    /// [`CustomError`].
    ///
    /// Useful in order to rename verbose rules or have detailed per-`Rule` formatting.
    ///
    /// [`ParsingError`]: enum.ErrorVariant.html#variant.ParsingError
    /// [`CustomError`]: enum.ErrorVariant.html#variant.CustomError
    ///
    /// # Examples
    ///
    /// ```
    /// # use yggdrasil_rt::error::{YggdrasilError, ErrorKind};
    /// # use yggdrasil_rt::Position;
    /// # #[allow(non_camel_case_types)]
    /// # #[allow(dead_code)]
    /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    /// # enum Rule {
    /// #     open_paren,
    /// #     closed_paren
    /// # }
    /// # let input = "";
    /// # let pos = Position::from_start(input);
    /// YggdrasilError::new_from_offset(
    ///     ErrorKind::ParsingError {
    ///         positives: vec![Rule::open_paren],
    ///         negatives: vec![Rule::closed_paren],
    ///     },
    ///     pos,
    /// )
    /// .renamed_rules(|rule| match *rule {
    ///     Rule::open_paren => "(".to_owned(),
    ///     Rule::closed_paren => "closed paren".to_owned(),
    /// });
    /// ```
    pub fn renamed_rules<F>(mut self, f: F) -> YggdrasilError<R>
    where
        F: FnMut(&R) -> String,
    {
        let variant = match self.variant {
            YggdrasilErrorKind::InvalidRule { positives, negatives } => {
                let message = YggdrasilError::parsing_error_message(&positives, &negatives, f);
                YggdrasilErrorKind::CustomError { message }
            }
            variant => variant,
        };

        self.variant = variant;

        self
    }

    fn parsing_error_message<F>(positives: &[R], negatives: &[R], mut f: F) -> String
    where
        F: FnMut(&R) -> String,
    {
        match (negatives.is_empty(), positives.is_empty()) {
            (false, false) => {
                format!(
                    "unexpected {}; expected {}",
                    YggdrasilError::enumerate(negatives, &mut f),
                    YggdrasilError::enumerate(positives, &mut f)
                )
            }
            (false, true) => format!("unexpected {}", YggdrasilError::enumerate(negatives, &mut f)),
            (true, false) => format!("expected {}", YggdrasilError::enumerate(positives, &mut f)),
            (true, true) => "unknown parsing error".to_owned(),
        }
    }

    fn enumerate<F>(rules: &[R], f: &mut F) -> String
    where
        F: FnMut(&R) -> String,
    {
        match rules.len() {
            1 => f(&rules[0]),
            2 => format!("{} or {}", f(&rules[0]), f(&rules[1])),
            l => {
                let non_separated = f(&rules[l - 1]);
                let separated = rules.iter().take(l - 1).map(f).collect::<Vec<_>>().join(", ");
                format!("{}, or {}", separated, non_separated)
            }
        }
    }
}

impl<R: YggdrasilRule> Display for YggdrasilError<R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.variant, f)
    }
}

impl<R: YggdrasilRule> Display for YggdrasilErrorKind<R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            YggdrasilErrorKind::InvalidRule { positives, negatives } => {
                write!(f, "invalid rule, except: {:?}, found: {:?}", positives, negatives)
            }
            YggdrasilErrorKind::InvalidNode { expect } => {
                write!(f, "invalid node, except: {:?}", expect)
            }
            YggdrasilErrorKind::InvalidTag(error) => Display::fmt(error, f),
            YggdrasilErrorKind::CustomError { message } => {
                write!(f, "{}", message)
            }
        }
    }
}

impl Display for InvalidTag {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "invalid tag, except {:?}", self.expect)?;
        match self.found.as_slice() {
            [] => Ok(()),
            s => write!(f, ", found {:?}", s),
        }
    }
}

#[allow(unused)]
fn visualize_whitespace(input: &str) -> String {
    input.to_owned().replace('\r', "␍").replace('\n', "␊")
}