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 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
/*
Copyright (c) 2023 Michał Wilczek, Michał Margos
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the “Software”), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::{collections::BTreeMap, fmt::Display, path::Path};
use crossterm::style::{Color, Stylize};
use crate::script::token::{Position, Span};
#[derive(Debug, Clone, Copy)]
pub enum DiagnosticKind {
Error,
Note,
Help,
}
#[must_use]
pub fn get_color(kind: DiagnosticKind) -> Color {
match kind {
DiagnosticKind::Error => Color::Red,
DiagnosticKind::Note => Color::Blue,
DiagnosticKind::Help => Color::Yellow,
// UnderscoreType::Warning => Color::Yellow,
// UnderscoreType::Info => Color::Cyan,
}
}
#[derive(Debug, Clone, Copy)]
pub enum AnnotationKind {
Note,
Help,
}
#[derive(Debug)]
struct AnnotationSet {
span: Span,
annotations: Vec<AnnotationPrivate>,
}
#[derive(Debug)]
struct AnnotationPrivate {
message: String,
kind: AnnotationKind,
}
pub struct Annotation {
pub kind: AnnotationKind,
pub message: String,
pub at: Span,
}
#[derive(Debug, Clone)]
pub struct Change {
pub span: Span,
/// Instead of a simple string, we use a vector of lines to make the
/// rendering process more reliable.
pub new_content: Vec<String>,
}
#[derive(Debug)]
pub struct Fix {
pub changes: Vec<Change>,
pub message: String,
}
pub struct Diagnostic<'r> {
kind: DiagnosticKind,
annotations: Vec<AnnotationSet>,
notes: Vec<(AnnotationKind, String)>,
message: String,
annotated_notes: BTreeMap<Position, Diagnostic<'r>>,
fixes: Vec<Fix>,
file: &'r Path,
script: &'r str,
}
pub struct DiagnosticData {
pub message: String,
pub spans: Vec<Span>,
pub annotations: Vec<Annotation>,
pub notes: Vec<(AnnotationKind, String)>,
pub fixes: Vec<Fix>,
}
impl DiagnosticData {
#[must_use]
pub fn new<S: ToString + ?Sized>(message: &S) -> Self {
Self {
message: message.to_string(),
spans: Vec::new(),
annotations: Vec::new(),
notes: Vec::new(),
fixes: Vec::new(),
}
}
#[must_use]
pub fn add_note(mut self, kind: AnnotationKind, message: String) -> Self {
self.notes.push((kind, message));
self
}
#[must_use]
pub fn add_span(mut self, sp: Span) -> Self {
self.spans.push(sp);
self
}
#[must_use]
pub fn add_annotation<S: ToString + ?Sized>(
mut self,
at: Span,
kind: AnnotationKind,
message: &S,
) -> Self {
self.annotations.push(Annotation {
kind,
message: message.to_string(),
at,
});
self
}
#[must_use]
pub fn add_annotation_opt_msg<S: ToString + ?Sized>(
mut self,
at: Span,
kind: AnnotationKind,
message: Option<&S>,
) -> Self {
if let Some(message) = message {
self.annotations.push(Annotation {
kind,
message: message.to_string(),
at,
});
}
self
}
#[must_use]
pub fn add_annotation_opt_span<S: ToString + ?Sized>(
mut self,
at: Option<Span>,
kind: AnnotationKind,
message: &S,
) -> Self {
if let Some(at) = at {
self.annotations.push(Annotation {
kind,
message: message.to_string(),
at,
});
}
self
}
#[must_use]
pub fn add_fix(mut self, fix: Fix) -> Self {
self.fixes.push(fix);
self
}
}
impl<'r> Diagnostic<'r> {
fn find_spans(
spans: Vec<Span>,
kind: DiagnosticKind,
message: &str,
file: &'r Path,
script: &'r str,
) -> (Vec<AnnotationSet>, BTreeMap<Position, Diagnostic<'r>>) {
let mut annotation_sets: Vec<AnnotationSet> = Vec::new();
let mut annotated_notes = BTreeMap::new();
for at in spans {
let mut index = 0;
let mut insert_at: u8 = 2;
for (i, set) in annotation_sets.iter_mut().enumerate() {
if set.span.overlaps(at) {
set.span = set.span.join(at);
insert_at = 0;
break;
}
if !at.is_single_line()
&& set.span.is_single_line()
&& at.end.line == set.span.start.line
{
// Banish the span
annotated_notes.insert(
at.start,
Diagnostic::new(
kind,
DiagnosticData {
message: String::from(message),
spans: vec![at],
annotations: Vec::new(),
notes: Vec::new(),
fixes: Vec::new(),
},
file,
script,
),
);
insert_at = 0;
break;
}
if at.start > set.span.start {
index = i;
} else {
insert_at = 1;
break;
}
}
match insert_at {
0 => (),
1 => annotation_sets.insert(
index,
AnnotationSet {
span: at,
annotations: Vec::new(),
},
),
2 => annotation_sets.push(AnnotationSet {
span: at,
annotations: Vec::new(),
}),
_ => unreachable!(),
}
}
(annotation_sets, annotated_notes)
}
#[must_use]
pub fn new(
kind: DiagnosticKind,
data: DiagnosticData,
file: &'r Path,
script: &'r str,
) -> Self {
let (mut annotation_sets, mut annotated_notes) =
Diagnostic::find_spans(data.spans, kind, &data.message, file, script);
for ann in data.annotations {
let mut index = 0;
let mut insert_at: u8 = 2;
for (i, annotation) in annotation_sets.iter_mut().enumerate() {
if annotation.span == ann.at {
// If there's a common span, attach both messages to one span.
annotation.annotations.push(AnnotationPrivate {
message: ann.message.clone(),
kind: ann.kind,
});
insert_at = 0;
break;
} else if annotation.span.overlaps(ann.at) {
// If there is an overlap, banish the note to annotated_notes.
annotated_notes.insert(
ann.at.start,
Diagnostic::new(
match ann.kind {
AnnotationKind::Help => DiagnosticKind::Help,
AnnotationKind::Note => DiagnosticKind::Note,
},
DiagnosticData {
message: ann.message.clone(),
spans: vec![ann.at],
annotations: Vec::new(),
notes: Vec::new(),
fixes: Vec::new(),
},
file,
script,
),
);
insert_at = 0;
break;
}
if ann.at.start > annotation.span.start {
index = i;
} else {
insert_at = 1;
break;
}
}
// If the function has not broken before, the annotation should be inserted at the given index.
match insert_at {
0 => (),
1 => annotation_sets.insert(
index,
AnnotationSet {
span: ann.at,
annotations: vec![AnnotationPrivate {
message: ann.message.clone(),
kind: ann.kind,
}],
},
),
2 => annotation_sets.push(AnnotationSet {
span: ann.at,
annotations: vec![AnnotationPrivate {
message: ann.message.clone(),
kind: ann.kind,
}],
}),
_ => unreachable!(),
}
}
// Sort by span start position in reverse (first span is the last in the vector)
let fixes = data
.fixes
.into_iter()
.map(|mut v| {
v.changes.sort_unstable_by_key(|c| c.span.start);
v.changes.reverse();
v
})
.collect();
Diagnostic {
kind,
annotations: annotation_sets,
notes: Vec::new(),
message: data.message,
annotated_notes,
fixes,
file,
script,
}
}
}
impl<'r> Display for Diagnostic<'r> {
#[allow(clippy::too_many_lines)]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Display the main message
writeln!(
f,
"{}{} {}",
match self.kind {
DiagnosticKind::Error => "error".red().bold(),
DiagnosticKind::Note => "note".blue().bold(),
DiagnosticKind::Help => "help".yellow().bold(),
},
":".white().bold(),
self.message.clone().white().bold()
)?;
let vertical = "|".blue().bold();
// Only execute the rest if there are any annotations.
let note_indent = if let Some(last) = self.annotations.last() {
let first = self.annotations.first().unwrap();
// Calculate the necessary indent (how much space to leave for line numbers).
let indent = last.span.end.line.to_string().len();
// Write the file path
writeln!(
f,
"{:indent$}{} {}:{}:{}",
"",
"-->".blue().bold(),
self.file.display(),
first.span.start.line,
first.span.start.column
)?;
let mut lines = self.script.lines().skip(first.span.start.line - 1);
// First " | "
writeln!(f, "{:indent$} {vertical}", "")?;
let mut annotations = self.annotations.iter().peekable();
// Do for each annotation
while let Some(ann) = annotations.next() {
if ann.span.is_single_line() {
// If single line, only render the line of code
writeln!(
f,
"{:indent$} {vertical} {}",
ann.span.start.line.to_string().blue().bold(),
lines.next().unwrap()
)?;
// And simple squiggles
write!(
f,
"{:<indent$} {vertical} {:squiggle_offset$}{}",
"",
"",
"^".repeat(ann.span.end.column - ann.span.start.column)
.with(get_color(self.kind))
.bold(),
squiggle_offset = ann.span.start.column - 1
)?;
} else {
// Otherwise
if ann.span.start.column == 1 {
// If range starts at column 1, start with '/'
writeln!(
f,
"{:<indent$} {vertical} {} {}",
ann.span.start.line.to_string().blue().bold(),
"/".with(get_color(self.kind)).bold(),
lines.next().unwrap()
)?;
} else {
// Otherwise with an indicator of where the span starts
writeln!(
f,
"{:indent$} {vertical} {}",
ann.span.start.line.to_string().blue().bold(),
lines.next().unwrap()
)?;
writeln!(
f,
"{:indent$} {vertical} {}",
"",
(String::from(" ") + &"_".repeat(ann.span.start.column - 2) + "^")
.with(get_color(self.kind))
.bold()
)?;
}
// Then add '|' for each line in span.
for i in ann.span.start.line..ann.span.end.line {
writeln!(
f,
"{:<indent$} {vertical} {} {}",
(i + 1).to_string().blue().bold(),
"|".with(get_color(self.kind)).bold(),
lines.next().unwrap()
)?;
}
// And end with ending indicator.
write!(
f,
"{:indent$} {vertical} {}",
"",
(String::from("|") + &"_".repeat(ann.span.end.column - 1) + "^")
.with(get_color(self.kind))
.bold()
)?;
}
let mut messages: Vec<(usize, Vec<&AnnotationPrivate>)> = vec![(
ann.span.end.column,
ann.annotations
.iter()
.filter(|x| !x.message.is_empty())
.collect(),
)];
// While we can, we put squiggles in the same line.
let mut previous = ann;
let mut next_ann = annotations.peek().copied();
while let Some(next) = next_ann {
if next.span.start.line == previous.span.end.line {
annotations.next();
write!(
f,
"{:squiggle_offset$}{}",
"",
"^".repeat(next.span.end.column - next.span.start.column)
.with(get_color(self.kind))
.bold(),
squiggle_offset = next.span.start.column - previous.span.end.column
)?;
messages.push((
next.span.end.column,
next.annotations
.iter()
.filter(|x| !x.message.is_empty())
.collect(),
));
previous = next;
next_ann = annotations.peek().copied();
} else {
break;
}
}
let l = messages.len();
let mut messages: Vec<(usize, Vec<&AnnotationPrivate>)> = messages
.into_iter()
.enumerate()
.filter(|(i, (_, x))| !x.is_empty() || *i == l - 1)
.map(|x| x.1)
.collect();
// We first dispatch the last message, since it can follow the squiggles immediately.
if let Some(v) = messages.last().unwrap().1.first() {
write!(
f,
"{}",
format!(
" {}: {}",
match v.kind {
AnnotationKind::Note => "note",
AnnotationKind::Help => "help",
},
v.message
)
.with(get_color(self.kind))
.bold()
)?;
}
if !messages.last_mut().unwrap().1.is_empty() {
messages.last_mut().unwrap().1.remove(0);
}
writeln!(f)?;
let mut offsets: Vec<usize> = messages.iter().map(|x| x.0).collect();
offsets.pop();
// And then for each annotation
for (offset, msg) in messages.into_iter().rev() {
// For each message.
for ann in msg {
write!(f, "{:indent$} {vertical} ", "")?;
let mut last = 1;
// We write the `|` for other messages.
for off in &offsets {
write!(
f,
"{:ind$}{}",
"",
"|".with(get_color(self.kind)).bold(),
ind = *off - last - 1
)?;
last = *off;
}
// And then write the message itself.
writeln!(
f,
"{:ind$} {}",
"",
format!(
" {}: {}",
match ann.kind {
AnnotationKind::Note => "note",
AnnotationKind::Help => "help",
},
ann.message
)
.with(get_color(self.kind))
.bold(),
ind = offset - last - 1
)?;
}
offsets.pop();
}
// Advance the source display
if let Some(next) = next_ann {
match next.span.start.line - previous.span.end.line {
1 => (),
2 => writeln!(
f,
"{:<indent$} {vertical} {}",
(previous.span.start.line - 1).to_string().blue().bold(),
lines.next().unwrap()
)?,
diff => {
for _ in 0..(diff - 1) {
lines.next();
}
writeln!(f, "{:indent$}{}", "", "...".blue().bold())?;
}
}
}
}
indent
} else {
0
};
// Display notes.
for note in &self.notes {
writeln!(
f,
"{:note_indent$} = {}",
"",
format!(
"{}: {}",
match ¬e.0 {
AnnotationKind::Note => "note",
AnnotationKind::Help => "help",
},
note.1
)
.bold()
)?;
}
// Display annotated notes
if !self.annotated_notes.is_empty() {
writeln!(f, "{:note_indent$} {vertical}", "")?;
}
for diagnostic in self.annotated_notes.values() {
write!(f, "{diagnostic}")?;
}
for fix in &self.fixes {
writeln!(
f,
"{} {}",
"Fix:".green().bold(),
fix.message.clone().bold(),
)?;
if let Some(last) = fix.changes.last() {
// Calculate the necessary indent (how much space to leave for line numbers).
let indent = last.span.end.line.to_string().len();
let first = fix.changes.first().unwrap();
// Write the file path
writeln!(
f,
"{:indent$}{} {}:{}:{}",
"",
"-->".blue().bold(),
self.file.display(),
first.span.start.line,
first.span.start.column
)?;
let mut lines = self.script.lines().skip(first.span.start.line - 1);
// First " | "
writeln!(f, "{:note_indent$} {vertical}", "")?;
// A fix is a message with vector of changes ordered in descending span start.
// So we will create a stack for those spans.
// In each iteration we will consider the top entry.
// If the entry's span is single-line, we simply print it
// Otherwise, we divide the span and push the two parts to the top of the stack,
// so that it is considered in the next iteration.
let mut changes = fix.changes.clone();
let mut current_line = lines.next().map(|s| s.chars().enumerate());
let mut signs = Vec::new();
// Until there is a top of the stack.
while let Some(change) = changes.pop() {
if !change.span.is_single_line() {
// If not single line, divide in two.
changes.push(Change {
span: Span {
start: Position {
line: change.span.start.line + 1,
column: 1,
},
end: change.span.end,
},
new_content: change.new_content,
});
changes.push(Change {
span: Span {
start: change.span.start,
end: Position {
line: change.span.start.line,
column: usize::MAX,
},
},
new_content: Vec::new(),
});
} else if let Some(chars) = current_line.as_mut() {
// Render the line and fill in `signs`.
write!(
f,
"{:<indent$} {vertical} ",
change.span.start.line.to_string().blue().bold()
)?;
// Render the line pre-change
if change.span.start.column > 1 {
for (i, c) in chars.by_ref() {
write!(f, "{c}")?;
signs.push(' ');
if i + 2 >= change.span.start.column {
// next character is too far, break
break;
}
}
}
// Render the deleted span as red.
if !change.span.is_empty() {
for (i, c) in chars.by_ref() {
write!(f, "{}", c.red())?;
signs.push('-');
if i + 2 >= change.span.end.column {
break;
}
}
}
let mut first = true;
// Render the added code.
for ln in &change.new_content {
// If it's not the first line of the added content, print a newline and signs
if !first {
writeln!(f)?;
write!(f, "{:indent$} {vertical} ", "")?;
for sign in &signs {
match sign {
'+' => write!(f, "{}", "+".green())?,
'-' => write!(f, "{}", "-".red())?,
_ => write!(f, " ")?,
}
}
writeln!(f)?;
write!(f, "{:indent$} {vertical} ", "")?;
}
// Print the line
write!(f, "{}", ln.as_str().green())?;
// And add signs
signs.resize(signs.len() + ln.chars().count(), '+');
first = false;
}
// Render the rest of the line and fill in `signs`.
for (_, c) in chars {
write!(f, "{c}")?;
signs.push(' ');
}
}
// Advance the source display
if let Some(next) = changes.last() {
if next.span.start.line != change.span.end.line {
// Render signs
writeln!(f)?; // Finish the line.
write!(f, "{:note_indent$} {vertical} ", "")?;
for sign in &signs {
match sign {
'+' => write!(f, "{}", "+".green())?,
'-' => write!(f, "{}", "-".red())?,
_ => write!(f, " ")?,
}
}
writeln!(f)?;
signs.clear();
match next.span.start.line - change.span.end.line {
1 => (),
2 => writeln!(
f,
"{:<note_indent$} {vertical} {}",
(change.span.start.line + 1).to_string().blue().bold(),
lines.next().unwrap()
)?,
diff => {
for _ in 0..(diff - 1) {
lines.next();
}
writeln!(f, "{:indent$}{}", "", "...".blue().bold())?;
}
}
current_line = lines.next().map(|s| s.chars().enumerate());
}
}
}
}
}
Ok(())
}
}