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
use crate::Span;
use std::{fmt, path::Path};
pub const INDENT: &str = " ";
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Error {
pub path: Option<String>,
pub line: usize,
pub start: usize,
pub end: usize,
pub text: String,
pub message: String,
}
impl Error {
pub fn new_from_span(message: String, span: Span) -> Self {
Self {
path: None,
line: span.line,
start: span.start,
end: span.end,
text: span.text,
message,
}
}
pub fn new_from_span_with_path(message: String, span: Span, path: &Path) -> Self {
Self {
path: Some(format!("{:?}", path)),
line: span.line,
start: span.start,
end: span.end,
text: span.text,
message,
}
}
pub fn set_path(&mut self, path: &Path) {
self.path = Some(format!("{:?}", path));
}
pub fn format(&self) -> String {
let path = self.path.as_ref().map(|path| format!("{}:", path)).unwrap_or_default();
let underline = underline(self.start, self.end);
format!(
"{indent }--> {path} {line}:{start}\n\
{indent } |\n\
{line:width$} | {text}\n\
{indent } | {underline}\n\
{indent } |\n\
{indent } = {message}",
indent = INDENT,
width = INDENT.len(),
path = path,
line = self.line,
start = self.start,
text = self.text,
underline = underline,
message = self.message,
)
}
}
fn underline(mut start: usize, mut end: usize) -> String {
if start > end {
std::mem::swap(&mut start, &mut end)
}
let mut underline = String::new();
for _ in 0..start {
underline.push(' ');
end -= 1;
}
for _ in 0..end {
underline.push('^');
}
underline
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.format())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.message
}
}
#[test]
fn test_error() {
let err = Error {
path: Some("file.leo".to_string()),
line: 2,
start: 8,
end: 9,
text: "let a = x;".to_string(),
message: "undefined value `x`".to_string(),
};
assert_eq!(
err.to_string(),
vec![
" --> file.leo: 2:8",
" |",
" 2 | let a = x;",
" | ^",
" |",
" = undefined value `x`",
]
.join("\n")
);
}