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
use std::{
    char::ParseCharError,
    fmt::{Display, Formatter},
    num::{ParseFloatError, ParseIntError},
    str::ParseBoolError,
};
#[cfg(feature = "peginator")]
mod for_peginator;

use ariadne::ReportKind;

use crate::{FileID, FileSpan, ValkyrieError, ValkyrieErrorKind, ValkyrieReport};

#[derive(Clone, Debug)]
pub struct ParseError {
    info: String,
    span: FileSpan,
}

impl Display for ParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.info)
    }
}

impl ParseError {
    pub fn new(info: impl Into<String>) -> Self {
        Self { span: FileSpan::default(), info: info.into() }
    }
    pub fn with_file(mut self, file: FileID) -> Self {
        self.span.file = file;
        self
    }
    pub fn with_range(mut self, range: (usize, usize)) -> Self {
        self.span.head = range.0;
        self.span.tail = range.1;
        self
    }
    pub fn as_report(&self, kind: ReportKind) -> ValkyrieReport {
        let mut report = ValkyrieReport::build(kind, self.span.file, self.span.head);
        report.set_message(self.to_string());
        report.add_label(self.span.as_label(self.to_string()));
        report.finish()
    }
}

impl From<ParseError> for ValkyrieError {
    fn from(value: ParseError) -> Self {
        ValkyrieError { kind: ValkyrieErrorKind::Parsing(Box::new(value)), level: ReportKind::Error }
    }
}

macro_rules! wrap_parse_error {
    ($($type:ty),*) => {
        $(
            impl From<$type> for ValkyrieError {
                fn from(value: $type) -> Self {
                    ParseError::new(value.to_string()).into()
                }
            }
        )*
    };
}

wrap_parse_error!(ParseIntError, ParseFloatError, ParseBoolError, ParseCharError, url::ParseError);

#[cfg(feature = "peginator")]
wrap_parse_error!(peginator::ParseError);