-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdiagnostic.rs
324 lines (268 loc) · 9.49 KB
/
diagnostic.rs
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use std::fmt::Display;
use crate::parser::Parser;
use crate::{diagnostics::DiagnosticType, parser::span::Span, parser::span2::Span as Span2};
use crate::{
hir::HirId,
parser::SourceFile,
ty::{FuncType, Type},
};
use colored::*;
use nom::error::{VerboseError, VerboseErrorKind};
#[derive(Clone, Debug)]
pub struct Diagnostic {
pub span: Span,
kind: DiagnosticKind,
}
impl Diagnostic {
pub fn new(span: Span, kind: DiagnosticKind) -> Self {
Self { span, kind }
}
pub fn new_empty() -> Self {
Self {
span: Span::new_placeholder(),
kind: DiagnosticKind::NoError,
}
}
pub fn new_file_not_found(span: Span, path: String) -> Self {
Self::new(span, DiagnosticKind::FileNotFound(path))
}
pub fn new_unexpected_token(span: Span) -> Self {
Self::new(span, DiagnosticKind::UnexpectedToken)
}
pub fn new_syntax_error(span: Span, msg: String) -> Self {
Self::new(span, DiagnosticKind::SyntaxError(msg))
}
pub fn new_unknown_identifier(span: Span) -> Self {
Self::new(span, DiagnosticKind::UnknownIdentifier)
}
pub fn new_unused_function(span: Span) -> Self {
Self::new(span, DiagnosticKind::UnusedFunction)
}
pub fn new_module_not_found(span: Span, path: String) -> Self {
Self::new(span, DiagnosticKind::ModuleNotFound(path))
}
pub fn new_unresolved_type(span: Span, t: Type) -> Self {
Self::new(span, DiagnosticKind::UnresolvedType(t))
}
pub fn new_out_of_bounds(span: Span, got: u64, expected: u64) -> Self {
Self::new(span, DiagnosticKind::OutOfBounds(got, expected))
}
pub fn new_unresolved_trait_call(
span: Span,
call_hir_id: HirId,
given_sig: FuncType,
existing_impls: Vec<FuncType>,
) -> Self {
Self::new(
span,
DiagnosticKind::UnresolvedTraitCall {
call_hir_id,
given_sig,
existing_impls,
},
)
}
pub fn new_codegen_error(span: Span, hir_id: HirId, msg: &str) -> Self {
Self::new(span, DiagnosticKind::CodegenError(hir_id, msg.to_string()))
}
pub fn new_duplicated_operator(span: Span) -> Self {
Self::new(span, DiagnosticKind::DuplicatedOperator)
}
pub fn new_no_main() -> Self {
Self::new(Span::new_placeholder(), DiagnosticKind::NoMain)
}
pub fn new_is_not_a_property_of(span: Span, t: Type) -> Self {
Self::new(span, DiagnosticKind::IsNotAPropertyOf(t))
}
pub fn new_type_conflict(span: Span, t1: Type, t2: Type, in1: Type, in2: Type) -> Self {
Self::new(span, DiagnosticKind::TypeConflict(t1, t2, in1, in2))
}
pub fn print(&self, file: &SourceFile, diag_type: &DiagnosticType) {
let input: Vec<char> = file.content.chars().collect();
let line = input[..self.span.start].split(|c| *c == '\n').count();
let lines: Vec<_> = input.split(|c| *c == '\n').collect();
let count: usize = lines.clone()[..line - 1].iter().map(|v| v.len()).sum();
let count = count + line;
let line_start = if count > self.span.start {
0
} else {
self.span.start - count
};
let line_ind = format!(
" -> {}({}:{})",
file.file_path.to_str().unwrap(),
line,
line_start
);
let mut arrow = String::new();
let mut i = 0;
while line_start > 0 && i <= line_start {
arrow.push(' ');
i += 1;
}
arrow.push('^');
// FIXME: some span don't have txt
if self.span.end - self.span.start > 0 {
let mut i = 0;
while i < self.span.end - self.span.start - 1 {
arrow.push('~');
i += 1;
}
}
let diag_type_str = match diag_type {
DiagnosticType::Error => "Error".red(),
DiagnosticType::Warning => "Warning".yellow(),
};
let color = |x: String| match diag_type {
DiagnosticType::Error => x.red(),
DiagnosticType::Warning => x.yellow(),
};
let color_bright = |x: String| match diag_type {
DiagnosticType::Error => x.bright_red(),
DiagnosticType::Warning => x.bright_yellow(),
};
let diag_type_str = format!(
"{}{}{} {}{}",
"[".bright_black(),
diag_type_str,
"]".bright_black(),
color(self.kind.to_string()).bold(),
":".bright_black(),
);
let line_span_start = line_start;
let mut line_span_stop = line_start + (self.span.end - self.span.start);
let line_colored = lines[line - 1].iter().cloned().collect::<String>();
if line_span_stop > line_colored.len() {
line_span_stop = line_colored.len() - 1;
}
let first_part = &line_colored[..line_span_start];
let colored_part = color(line_colored[line_span_start..=line_span_stop].to_string());
let last_part = if line_span_stop + 1 >= line_colored.len() {
String::new()
} else {
line_colored[line_span_stop + 1..].to_owned()
};
let line_colored = format!("{}{}{}", first_part, colored_part, last_part,);
println!(
"{}\n{}\n{:>4} {}\n{:>4} {} {}\n{:>4} {} {}",
diag_type_str,
line_ind.bright_black(),
"",
"|".bright_black(),
color_bright(line.to_string()),
"|".bright_black(),
line_colored,
"",
"|".bright_black(),
color_bright(arrow),
);
}
pub fn get_kind(&self) -> DiagnosticKind {
self.kind.clone()
}
}
#[derive(Clone, Debug)]
pub enum DiagnosticKind {
FileNotFound(String),
UnexpectedToken,
SyntaxError(String),
UnknownIdentifier,
ModuleNotFound(String),
NotAFunction,
UnusedParameter,
UnresolvedTraitCall {
call_hir_id: HirId,
given_sig: FuncType,
existing_impls: Vec<FuncType>,
},
UnusedFunction,
DuplicatedOperator,
TypeConflict(Type, Type, Type, Type),
UnresolvedType(Type),
CodegenError(HirId, String),
IsNotAPropertyOf(Type),
OutOfBounds(u64, u64),
NoMain,
NoError, //TODO: remove that
}
impl Display for DiagnosticKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::UnexpectedToken => "UnexpectedToken".to_string(),
Self::SyntaxError(msg) => format!("SyntaxError: {}", msg),
Self::UnknownIdentifier => "UnknownIdentifier".to_string(),
Self::ModuleNotFound(path) => format!("Module not found: {}", path),
Self::DuplicatedOperator => "DuplicatedOperator".to_string(),
Self::TypeConflict(t1, t2, _in1, _in2) => {
format!(
"Type conflict:\n{:<8}Expected {:?}\n{:<8}But got {:?}",
"", t2, "", t1
)
}
Self::UnresolvedType(t) => {
format!(
"Unresolved type: Type {:?} should be known at this point",
t
)
}
Self::UnresolvedTraitCall {
call_hir_id: _,
given_sig,
existing_impls,
} => {
format!(
"Unresolved trait call {:?}\n{}",
given_sig,
existing_impls
.iter()
.map(|sig| format!(" Found impl: {:?}", sig))
.collect::<Vec<_>>()
.join("\n")
)
}
Self::FileNotFound(path) => format!("FileNotFound {}", path),
Self::CodegenError(hir_id, msg) => format!("CodegenError: {} {:?}", msg, hir_id),
Self::OutOfBounds(got, expected) => format!(
"Out of bounds error: got indice {} but array len is {}",
got, expected
),
DiagnosticKind::NotAFunction => "NotAFunction".to_string(),
DiagnosticKind::UnusedParameter => "UnusedParameter".to_string(),
DiagnosticKind::UnusedFunction => "UnusedFunction".to_string(),
DiagnosticKind::NoMain => "NoMain".to_string(),
DiagnosticKind::NoError => "NoError".to_string(),
DiagnosticKind::IsNotAPropertyOf(t) => {
format!("Not a property of {:?}", t)
}
};
write!(f, "{}", s)
}
}
impl<'a> From<Parser<'a>> for Diagnostic {
fn from(err: Parser<'a>) -> Self {
let span2 = Span2::from(err);
let span = Span::from(span2);
let msg = "Syntax error".to_string();
Diagnostic::new_syntax_error(span, msg)
}
}
impl<'a> From<VerboseError<Parser<'a>>> for Diagnostic {
fn from(err: VerboseError<Parser<'a>>) -> Self {
let (input, _kind) = err.errors.iter().next().unwrap().clone();
let span2 = Span2::from(input);
let span = Span::from(span2);
let msg = err.to_string();
Diagnostic::new_syntax_error(span, msg)
}
}
impl<I> From<(I, VerboseErrorKind)> for Diagnostic
where
Span2: From<I>,
{
fn from((input, _kind): (I, VerboseErrorKind)) -> Self {
let span2 = Span2::from(input);
let span = Span::from(span2);
let msg = "Syntax error".to_string();
Diagnostic::new_syntax_error(span, msg)
}
}