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
use crate::{LeoError, Span};
use std::{fmt, sync::Arc};
pub const INDENT: &str = " ";
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct FormattedError {
pub line_start: usize,
pub line_stop: usize,
pub col_start: usize,
pub col_stop: usize,
pub path: Arc<String>,
pub content: String,
pub message: String,
}
impl FormattedError {
pub fn new_from_span(message: String, span: &Span) -> Self {
Self {
line_start: span.line_start,
line_stop: span.line_stop,
col_start: span.col_start,
col_stop: span.col_stop,
path: span.path.clone(),
content: span.content.to_string(),
message,
}
}
}
impl LeoError for FormattedError {}
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 FormattedError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let underline = underline(self.col_start - 1, self.col_stop - 1);
write!(
f,
"{indent }--> {path}: {line_start}:{start}\n\
{indent } |\n",
indent = INDENT,
path = &*self.path,
line_start = self.line_start,
start = self.col_start,
)?;
for (line_no, line) in self.content.lines().enumerate() {
writeln!(
f,
"{line_no:width$} | {text}",
width = INDENT.len(),
line_no = self.line_start + line_no,
text = line,
)?;
}
write!(
f,
"{indent } | {underline}\n\
{indent } |\n\
{indent } = {message}",
indent = INDENT,
underline = underline,
message = self.message,
)
}
}
impl std::error::Error for FormattedError {
fn description(&self) -> &str {
&self.message
}
}
#[test]
fn test_error() {
let err = FormattedError {
path: std::sync::Arc::new("file.leo".to_string()),
line_start: 2,
line_stop: 2,
col_start: 8,
col_stop: 9,
content: "let a = x;".into(),
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")
);
}