forked from kcl-lang/kcl
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
608 lines (564 loc) · 20.6 KB
/
lib.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Diagnostics creation and emission for `KCLVM`.
//! This module contains the code for creating and emitting diagnostics.
//!
//! We can use `Handler` to create and emit diagnostics.
pub mod diagnostic;
mod error;
use annotate_snippets::{
display_list::DisplayList,
display_list::FormatOptions,
snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},
};
use anyhow::Result;
use compiler_base_error::errors::ComponentFormatError;
use compiler_base_error::StyledBuffer;
use compiler_base_error::{
components::{CodeSnippet, Label},
Component, Diagnostic as DiagnosticTrait, DiagnosticStyle,
};
use compiler_base_session::{Session, SessionDiagnostic};
use compiler_base_span::{span::new_byte_pos, Span};
use diagnostic::Range;
use indexmap::IndexSet;
use kclvm_runtime::PanicInfo;
use std::{any::Any, sync::Arc};
use thiserror::Error;
pub use diagnostic::{Diagnostic, DiagnosticId, Level, Message, Position, Style};
pub use error::*;
/// A handler deals with errors and other compiler output.
/// Certain errors (error, bug) may cause immediate exit,
/// others log errors for later reporting.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Handler {
pub diagnostics: IndexSet<Diagnostic>,
}
impl Handler {
/// New a handler using a emitter
pub fn new() -> Self {
Self {
diagnostics: Default::default(),
}
}
/// Panic program and report a bug
#[inline]
pub fn bug(&self, msg: &str) -> ! {
compiler_base_macros::bug!("{}", msg)
}
#[inline]
pub fn has_errors(&self) -> bool {
self.diagnostics
.iter()
.any(|diag| diag.level == Level::Error)
}
/// Emit all diagnostics and return whether has errors.
pub fn emit(&mut self) -> Result<bool> {
let sess = Session::default();
for diag in &self.diagnostics {
sess.add_err(diag.clone())?;
}
sess.emit_stashed_diagnostics()?;
Ok(self.has_errors())
}
/// Emit diagnostic to string.
pub fn emit_to_string(&mut self) -> Result<String> {
let sess = Session::default();
for diag in &self.diagnostics {
sess.add_err(diag.clone())?;
}
let errors = sess.emit_all_diags_into_string()?;
let mut error_strings = vec![];
for error in errors {
error_strings.push(error?);
}
Ok(error_strings.join("\n"))
}
/// Emit all diagnostics and abort if has any errors.
pub fn abort_if_any_errors(&mut self) {
match self.emit() {
Ok(has_error) => {
if has_error {
std::process::exit(1);
}
}
Err(err) => self.bug(&format!("{err}")),
}
}
/// Construct a parse error and put it into the handler diagnostic buffer
pub fn add_syntex_error(&mut self, msg: &str, range: Range) -> &mut Self {
let message = format!("Invalid syntax: {msg}");
let diag = Diagnostic::new_with_code(
Level::Error,
&message,
None,
range,
Some(DiagnosticId::Error(E1001.kind)),
None,
);
self.add_diagnostic(diag);
self
}
/// Construct a type error and put it into the handler diagnostic buffer
pub fn add_type_error(&mut self, msg: &str, range: Range) -> &mut Self {
let diag = Diagnostic::new_with_code(
Level::Error,
msg,
None,
range,
Some(DiagnosticId::Error(E2G22.kind)),
None,
);
self.add_diagnostic(diag);
self
}
/// Construct a type error and put it into the handler diagnostic buffer
pub fn add_compile_error(&mut self, msg: &str, range: Range) -> &mut Self {
self.add_compile_error_with_suggestions(msg, range, None)
}
pub fn add_compile_error_with_suggestions(
&mut self,
msg: &str,
range: Range,
suggestions: Option<Vec<String>>,
) -> &mut Self {
let diag = Diagnostic::new_with_code(
Level::Error,
msg,
None,
range,
Some(DiagnosticId::Error(E2L23.kind)),
suggestions,
);
self.add_diagnostic(diag);
self
}
/// Put a runtime panic info the handler diagnostic buffer.
pub fn add_panic_info(&mut self, panic_info: &PanicInfo) -> &mut Self {
self.add_diagnostic(panic_info.clone().into());
self
}
/// Add an error into the handler
/// ```
/// use kclvm_error::*;
/// let mut handler = Handler::default();
/// handler.add_error(ErrorKind::InvalidSyntax, &[
/// Message {
/// range: (Position::dummy_pos(), Position::dummy_pos()),
/// style: Style::LineAndColumn,
/// message: "Invalid syntax: expected '+', got '-'".to_string(),
/// note: None,
/// suggested_replacement: None,
/// }
/// ]);
/// ```
pub fn add_error(&mut self, err: ErrorKind, msgs: &[Message]) -> &mut Self {
let diag = Diagnostic {
level: Level::Error,
messages: msgs.to_owned(),
code: Some(DiagnosticId::Error(err)),
};
self.add_diagnostic(diag);
self
}
pub fn add_suggestions(&mut self, msgs: Vec<String>) -> &mut Self {
msgs.iter().for_each(|s| {
self.add_diagnostic(Diagnostic {
level: Level::Suggestions,
messages: vec![Message {
range: Range::default(),
style: Style::Line,
message: s.to_string(),
note: None,
suggested_replacement: None,
}],
code: Some(DiagnosticId::Suggestions),
});
});
self
}
/// Add an warning into the handler
/// ```
/// use kclvm_error::*;
/// let mut handler = Handler::default();
/// handler.add_warning(WarningKind::UnusedImportWarning, &[
/// Message {
/// range: (Position::dummy_pos(), Position::dummy_pos()),
/// style: Style::LineAndColumn,
/// message: "Module 'a' imported but unused.".to_string(),
/// note: None,
/// suggested_replacement: None,
/// }],
/// );
/// ```
pub fn add_warning(&mut self, warning: WarningKind, msgs: &[Message]) -> &mut Self {
let diag = Diagnostic {
level: Level::Warning,
messages: msgs.to_owned(),
code: Some(DiagnosticId::Warning(warning)),
};
self.add_diagnostic(diag);
self
}
/// Classify diagnostics into errors and warnings.
pub fn classification(&self) -> (IndexSet<Diagnostic>, IndexSet<Diagnostic>) {
let (mut errs, mut warnings) = (IndexSet::new(), IndexSet::new());
for diag in &self.diagnostics {
if diag.level == Level::Error || diag.level == Level::Suggestions {
errs.insert(diag.clone());
} else if diag.level == Level::Warning {
warnings.insert(diag.clone());
} else {
continue;
}
}
(errs, warnings)
}
/// Store a diagnostics into the handler.
///
/// # Example
///
/// ```
/// use kclvm_error::*;
/// let mut handler = Handler::default();
/// handler.add_diagnostic(Diagnostic::new_with_code(Level::Error, "error message", None, (Position::dummy_pos(), Position::dummy_pos()), Some(DiagnosticId::Error(E1001.kind)), None));
/// ```
#[inline]
pub fn add_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut Self {
self.diagnostics.insert(diagnostic);
self
}
}
impl From<PanicInfo> for Diagnostic {
fn from(panic_info: PanicInfo) -> Self {
let panic_msg = if panic_info.kcl_arg_msg.is_empty() {
&panic_info.message
} else {
&panic_info.kcl_arg_msg
};
let mut diag = if panic_info.backtrace.is_empty() {
let pos = Position {
filename: panic_info.kcl_file.clone(),
line: panic_info.kcl_line as u64,
column: None,
};
Diagnostic::new_with_code(
Level::Error,
panic_msg,
None,
(pos.clone(), pos),
None,
None,
)
} else {
let mut backtrace_msg = "backtrace:\n".to_string();
let mut backtrace = panic_info.backtrace.clone();
backtrace.reverse();
for (index, frame) in backtrace.iter().enumerate() {
backtrace_msg.push_str(&format!(
"\t{index}: {}\n\t\tat {}:{}",
frame.func, frame.file, frame.line
));
if frame.col != 0 {
backtrace_msg.push_str(&format!(":{}", frame.col))
}
backtrace_msg.push('\n')
}
let pos = Position {
filename: panic_info.kcl_file.clone(),
line: panic_info.kcl_line as u64,
column: None,
};
Diagnostic::new_with_code(
Level::Error,
panic_msg,
Some(&backtrace_msg),
(pos.clone(), pos),
None,
None,
)
};
if panic_info.kcl_config_meta_file.is_empty() {
return diag;
}
let pos = Position {
filename: panic_info.kcl_config_meta_file.clone(),
line: panic_info.kcl_config_meta_line as u64,
column: Some(panic_info.kcl_config_meta_col as u64),
};
let mut config_meta_diag = Diagnostic::new_with_code(
Level::Error,
&panic_info.kcl_config_meta_arg_msg,
None,
(pos.clone(), pos),
None,
None,
);
config_meta_diag.messages.append(&mut diag.messages);
config_meta_diag
}
}
#[derive(Error, Debug, Clone)]
pub enum ParseErrorMessage {
#[error("invalid token '!', consider using 'not '")]
InvalidTokenNot,
#[error("'else if' here is invalid in KCL, consider using the 'elif' keyword")]
InvalidTokenElseIf,
#[error("unterminated string")]
UnterminatedString,
#[error("unexpected character after line continuation character")]
CharAfterLineContinuationToken,
#[error("the semicolon ';' here is unnecessary, please remove it")]
RedundantSemicolon,
#[error("expected expression, got {0}")]
ExpectExpr(String),
#[error("invalid string interpolation expression: '{0}'")]
InvalidStringInterpolationExpr(String),
#[error("invalid joined string spec without #")]
InvalidJoinedStringSpec,
#[error("invalid joined string")]
InvalidJoinedStringExpr,
}
#[derive(Debug, Clone)]
pub enum ParseError {
UnexpectedToken {
expected: Vec<String>,
got: String,
span: Span,
},
Message {
message: ParseErrorMessage,
span: Span,
suggestions: Option<Vec<String>>,
},
String {
message: String,
span: Span,
},
}
/// A single string error.
pub struct StringError(pub String);
impl ParseError {
/// New a unexpected token parse error with span and token information.
pub fn unexpected_token(expected: &[&str], got: &str, span: Span) -> Self {
ParseError::UnexpectedToken {
expected: expected
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>(),
got: got.to_string(),
span,
}
}
/// New a message parse error with span.
pub fn message(
message: ParseErrorMessage,
span: Span,
suggestions: Option<Vec<String>>,
) -> Self {
ParseError::Message {
message,
span,
suggestions,
}
}
}
impl ParseError {
/// Convert a parse error into an error diagnostic.
pub fn into_diag(self, sess: &Session) -> Result<Diagnostic> {
let span = match self {
ParseError::UnexpectedToken { span, .. } => span,
ParseError::Message { span, .. } => span,
ParseError::String { span, .. } => span,
};
let start_pos = sess.sm.lookup_char_pos(span.lo()).into();
let end_pos = sess.sm.lookup_char_pos(span.hi()).into();
let suggestions = match &self {
ParseError::Message { suggestions, .. } => suggestions.clone(),
_ => None,
};
Ok(Diagnostic::new_with_code(
Level::Error,
&self.to_string(),
None,
(start_pos, end_pos),
Some(DiagnosticId::Error(ErrorKind::InvalidSyntax)),
suggestions,
))
}
}
impl ToString for ParseError {
fn to_string(&self) -> String {
match self {
ParseError::UnexpectedToken { expected, got, .. } => {
format!("expected one of {expected:?} got {got}")
}
ParseError::Message { message, .. } => message.to_string(),
ParseError::String { message, .. } => message.to_string(),
}
}
}
impl SessionDiagnostic for ParseError {
fn into_diagnostic(self, sess: &Session) -> Result<DiagnosticTrait<DiagnosticStyle>> {
let mut diag = DiagnosticTrait::<DiagnosticStyle>::new();
diag.append_component(Box::new(Label::Error(E1001.code.to_string())));
diag.append_component(Box::new(": invalid syntax\n".to_string()));
match self {
ParseError::UnexpectedToken { span, .. } => {
let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm));
diag.append_component(Box::new(code_snippet));
diag.append_component(Box::new(format!(" {}\n", self.to_string())));
Ok(diag)
}
ParseError::Message { message, span, .. } => {
let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm));
diag.append_component(Box::new(code_snippet));
diag.append_component(Box::new(format!(" {message}\n")));
Ok(diag)
}
ParseError::String { message, span } => {
let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm));
diag.append_component(Box::new(code_snippet));
diag.append_component(Box::new(format!(" {message}\n")));
Ok(diag)
}
}
}
}
#[derive(Default)]
pub struct SuggestionsLabel;
impl Component<DiagnosticStyle> for SuggestionsLabel {
fn format(&self, sb: &mut StyledBuffer<DiagnosticStyle>, _: &mut Vec<ComponentFormatError>) {
sb.appendl("suggestion: ", Some(DiagnosticStyle::NeedAttention));
}
}
impl SessionDiagnostic for Diagnostic {
fn into_diagnostic(self, _: &Session) -> Result<DiagnosticTrait<DiagnosticStyle>> {
let mut diag = DiagnosticTrait::<DiagnosticStyle>::new();
match self.code {
Some(id) => match id {
DiagnosticId::Error(error) => {
diag.append_component(Box::new(Label::Error(error.code())));
diag.append_component(Box::new(format!(": {}\n", error.name())));
}
DiagnosticId::Warning(warning) => {
diag.append_component(Box::new(Label::Warning(warning.code())));
diag.append_component(Box::new(format!(": {}\n", warning.name())));
}
DiagnosticId::Suggestions => {
diag.append_component(Box::new(SuggestionsLabel));
}
},
None => match self.level {
Level::Error => {
diag.append_component(Box::new(format!("{}\n", ErrorKind::EvaluationError)));
}
Level::Warning => {
diag.append_component(Box::new(format!("{}\n", WarningKind::CompilerWarning)));
}
Level::Note => {
diag.append_component(Box::new(Label::Note));
}
Level::Suggestions => {
diag.append_component(Box::new(SuggestionsLabel));
}
},
}
for msg in &self.messages {
match Session::new_with_file_and_code(&msg.range.0.filename, None) {
Ok(sess) => {
let source = sess.sm.lookup_source_file(new_byte_pos(0));
let line = source.get_line(
(if msg.range.0.line >= 1 {
msg.range.0.line - 1
} else {
0
}) as usize,
);
match line.as_ref() {
Some(content) => {
let length = content.chars().count();
let snippet = Snippet {
title: None,
footer: vec![],
slices: vec![Slice {
source: content,
line_start: msg.range.0.line as usize,
origin: Some(&msg.range.0.filename),
annotations: vec![SourceAnnotation {
range: match msg.range.0.column {
Some(column) if length >= 1 => {
let column = column as usize;
// If the position exceeds the length of the content,
// put the annotation at the end of the line.
if column >= length {
(length - 1, length)
} else {
(column, column + 1)
}
}
_ => (0, 0),
},
label: &msg.message,
annotation_type: AnnotationType::Error,
}],
fold: true,
}],
opt: FormatOptions {
color: true,
anonymized_line_numbers: false,
margin: None,
},
};
let dl = DisplayList::from(snippet);
diag.append_component(Box::new(format!("{dl}\n")));
}
None => {
diag.append_component(Box::new(format!(
"{}: {}\n",
msg.range.0.info(),
msg.message
)));
}
};
}
Err(_) => diag.append_component(Box::new(format!(
"{}: {}\n",
msg.range.0.info(),
msg.message
))),
};
if let Some(note) = &msg.note {
diag.append_component(Box::new(Label::Note));
diag.append_component(Box::new(format!(": {note}\n")));
}
// Append a new line.
diag.append_component(Box::new(String::from("\n")));
}
Ok(diag)
}
}
impl SessionDiagnostic for StringError {
fn into_diagnostic(self, _: &Session) -> Result<DiagnosticTrait<DiagnosticStyle>> {
let mut diag = DiagnosticTrait::<DiagnosticStyle>::new();
diag.append_component(Box::new(Label::Error(E3M38.code.to_string())));
diag.append_component(Box::new(format!(": {}\n", self.0)));
Ok(diag)
}
}
/// Convert an error to string.
///
/// ```
/// use kclvm_error::err_to_str;
///
/// assert_eq!(err_to_str(Box::new("error_string".to_string())), "error_string");
/// ```
pub fn err_to_str(err: Box<dyn Any + Send>) -> String {
if let Some(s) = err.downcast_ref::<&str>() {
s.to_string()
} else if let Some(s) = err.downcast_ref::<&String>() {
(*s).clone()
} else if let Some(s) = err.downcast_ref::<String>() {
(*s).clone()
} else {
"".to_string()
}
}