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
use std::convert::From;
use std::fmt;
use std::fmt::Display;
use std::io;
use crate::ast::Position;
use crate::build::opcode::convert;
#[derive(Debug)]
pub struct Error {
message: String,
pos: Option<Position>,
call_stack: Vec<Position>,
}
impl Error {
pub fn new(msg: String, pos: Position) -> Self {
Self {
message: msg,
pos: Some(pos),
call_stack: Vec::new(),
}
}
pub fn with_pos(mut self, pos: Position) -> Self {
self.pos = Some(pos);
self
}
pub fn push_call_stack(&mut self, pos: Position) {
self.call_stack.push(pos);
}
}
macro_rules! decorate_error {
($pos:expr => $result:expr) => {
match $result {
Ok(v) => Ok(v),
Err(e) => Err(e.with_pos($pos.clone())),
}
};
}
macro_rules! decorate_call {
($pos:expr => $result:expr) => {
match $result {
Ok(v) => Ok(v),
Err(mut e) => {
e.push_call_stack($pos.clone());
Err(e)
}
}
};
}
impl From<regex::Error> for Error {
fn from(e: regex::Error) -> Self {
Error {
message: format!("{}", e),
pos: None,
call_stack: Vec::new(),
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
let msg = match e.kind() {
io::ErrorKind::NotFound | io::ErrorKind::Other => {
format!("OSError: Path not found: {}", e)
}
_ => format!("{}", e),
};
Error {
message: msg,
pos: None,
call_stack: Vec::new(),
}
}
}
impl From<convert::Error> for Error {
fn from(e: convert::Error) -> Self {
Error {
message: e.message(),
pos: None,
call_stack: Vec::new(),
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(ref pos) = self.pos {
write!(f, "{} at {}", self.message, pos)?;
} else {
write!(f, "{}", self.message)?;
}
if !self.call_stack.is_empty() {
for p in self.call_stack.iter() {
write!(f, "\nVIA: {}", p)?;
}
}
Ok(())
}
}
impl std::error::Error for Error {}