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
use crate::eval;
use crate::parser::Rule;
use pest::{error::LineColLocation, Span};
use serde::{de, ser};
use std::fmt::{self, Display};
use std::io;
use std::str::Utf8Error;
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Message {
msg: String,
location: Option<Location>,
},
Eof,
Utf8(Utf8Error),
Io(io::Error),
InvalidEscape(char),
InvalidUnicodeCodePoint(String),
InvalidIdentifier(String),
Eval(eval::Error),
}
impl Error {
pub(crate) fn new<T>(msg: T) -> Error
where
T: Display,
{
Error::Message {
msg: msg.to_string(),
location: None,
}
}
pub fn location(&self) -> Option<&Location> {
match self {
Error::Message { location, .. } => location.as_ref(),
_ => None,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Eof => write!(f, "unexpected end of input"),
Error::Io(err) => Display::fmt(err, f),
Error::Utf8(err) => Display::fmt(err, f),
Error::Message { msg, location } => match location {
Some(loc) => {
write!(f, "{msg} in line {}, col {}", loc.line, loc.col)
}
None => write!(f, "{msg}"),
},
Error::InvalidEscape(c) => write!(f, "invalid escape sequence '\\{c}'"),
Error::InvalidUnicodeCodePoint(u) => {
write!(f, "invalid unicode code point '\\u{u}'")
}
Error::InvalidIdentifier(ident) => write!(f, "invalid identifier `{ident}`"),
Error::Eval(err) => write!(f, "eval error: {err}"),
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
impl From<Utf8Error> for Error {
fn from(err: Utf8Error) -> Self {
Error::Utf8(err)
}
}
impl From<pest::error::Error<Rule>> for Error {
fn from(err: pest::error::Error<Rule>) -> Self {
let (line, col) = match err.line_col {
LineColLocation::Pos((l, c)) | LineColLocation::Span((l, c), (_, _)) => (l, c),
};
Error::Message {
msg: err.to_string(),
location: Some(Location { line, col }),
}
}
}
impl From<eval::Error> for Error {
fn from(err: eval::Error) -> Self {
Error::Eval(err)
}
}
impl std::error::Error for Error {}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::new(msg)
}
}
impl de::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::new(msg)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Location {
pub line: usize,
pub col: usize,
}
impl From<Span<'_>> for Location {
fn from(span: Span<'_>) -> Self {
let (line, col) = span.start_pos().line_col();
Location { line, col }
}
}