Skip to content

Commit 3f727ae

Browse files
committed
Add new diagnostic writer using annotate-snippet library
This adds a new diagnostic writer `AnnotateRsEmitterWriter` that uses the [`annotate-snippet`][as] library to print out the human readable diagnostics. The goal is to eventually switch over to using the library instead of maintaining our own diagnostics output. This commit does *not* add all the required features to the new diagnostics writer. It is only meant as a starting point so that other people can contribute as well. [as]: https://github.com/rust-lang/annotate-snippets-rs
1 parent acda261 commit 3f727ae

File tree

6 files changed

+219
-2
lines changed

6 files changed

+219
-2
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -2789,6 +2789,7 @@ dependencies = [
27892789
name = "rustc_errors"
27902790
version = "0.0.0"
27912791
dependencies = [
2792+
"annotate-snippets 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
27922793
"atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
27932794
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
27942795
"rustc_cratesio_shim 0.0.0",

src/librustc_errors/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,4 @@ rustc_cratesio_shim = { path = "../librustc_cratesio_shim" }
1818
unicode-width = "0.1.4"
1919
atty = "0.2"
2020
termcolor = "1.0"
21+
annotate-snippets = "0.5.0"
+210
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
/// Emit diagnostics using the `annotate-snippets` library
2+
///
3+
/// This is the equivalent of `./emitter.rs` but making use of the
4+
/// [`annotate-snippets`][annotate_snippets] library instead of building the output ourselves.
5+
///
6+
/// [annotate_snippets]: https://docs.rs/crate/annotate-snippets/
7+
8+
use syntax_pos::{SourceFile, MultiSpan, Loc};
9+
use crate::{
10+
Level, CodeSuggestion, DiagnosticBuilder, Emitter,
11+
SourceMapperDyn, SubDiagnostic, DiagnosticId
12+
};
13+
use crate::emitter::FileWithAnnotatedLines;
14+
use rustc_data_structures::sync::Lrc;
15+
use crate::snippet::Line;
16+
use annotate_snippets::snippet::*;
17+
use annotate_snippets::display_list::DisplayList;
18+
use annotate_snippets::formatter::DisplayListFormatter;
19+
20+
21+
/// Generates diagnostics using annotate-rs
22+
pub struct AnnotateRsEmitterWriter {
23+
source_map: Option<Lrc<SourceMapperDyn>>,
24+
/// If true, hides the longer explanation text
25+
short_message: bool,
26+
/// If true, will normalize line numbers with LL to prevent noise in UI test diffs.
27+
ui_testing: bool,
28+
}
29+
30+
impl Emitter for AnnotateRsEmitterWriter {
31+
/// The entry point for the diagnostics generation
32+
fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
33+
let primary_span = db.span.clone();
34+
let children = db.children.clone();
35+
// FIXME(#59346): Collect suggestions (see emitter.rs)
36+
let suggestions: &[_] = &[];
37+
38+
// FIXME(#59346): Add `fix_multispans_in_std_macros` function from emitter.rs
39+
40+
self.emit_messages_default(&db.level,
41+
db.message(),
42+
&db.code,
43+
&primary_span,
44+
&children,
45+
&suggestions);
46+
}
47+
48+
fn should_show_explain(&self) -> bool {
49+
!self.short_message
50+
}
51+
}
52+
53+
/// Collects all the data needed to generate the data structures needed for the
54+
/// `annotate-snippets` library.
55+
struct DiagnosticConverter<'a> {
56+
source_map: Option<Lrc<SourceMapperDyn>>,
57+
level: Level,
58+
message: String,
59+
code: Option<DiagnosticId>,
60+
msp: MultiSpan,
61+
#[allow(dead_code)]
62+
children: &'a [SubDiagnostic],
63+
#[allow(dead_code)]
64+
suggestions: &'a [CodeSuggestion]
65+
}
66+
67+
impl<'a> DiagnosticConverter<'a> {
68+
/// Turns rustc Diagnostic information into a `annotate_snippets::snippet::Snippet`.
69+
fn to_annotation_snippet(&self) -> Option<Snippet> {
70+
if let Some(source_map) = &self.source_map {
71+
// Make sure our primary file comes first
72+
let primary_lo = if let Some(ref primary_span) =
73+
self.msp.primary_span().as_ref() {
74+
source_map.lookup_char_pos(primary_span.lo())
75+
} else {
76+
// FIXME(#59346): Not sure when this is the case and what
77+
// should be done if it happens
78+
return None
79+
};
80+
let annotated_files = FileWithAnnotatedLines::collect_annotations(
81+
&self.msp,
82+
&self.source_map
83+
);
84+
let slices = self.slices_for_files(annotated_files, primary_lo);
85+
86+
Some(Snippet {
87+
title: Some(Annotation {
88+
label: Some(self.message.to_string()),
89+
id: self.code.clone().map(|c| {
90+
match c {
91+
DiagnosticId::Error(val) | DiagnosticId::Lint(val) => val
92+
}
93+
}),
94+
annotation_type: Self::annotation_type_for_level(self.level),
95+
}),
96+
footer: vec![],
97+
slices: slices,
98+
})
99+
} else {
100+
// FIXME(#59346): Is it ok to return None if there's no source_map?
101+
None
102+
}
103+
}
104+
105+
fn slices_for_files(
106+
&self,
107+
annotated_files: Vec<FileWithAnnotatedLines>,
108+
primary_lo: Loc
109+
) -> Vec<Slice> {
110+
// FIXME(#59346): Provide a test case where `annotated_files` is > 1
111+
annotated_files.iter().flat_map(|annotated_file| {
112+
annotated_file.lines.iter().map(|line| {
113+
let line_source = Self::source_string(annotated_file.file.clone(), &line);
114+
Slice {
115+
source: line_source,
116+
line_start: line.line_index,
117+
origin: Some(primary_lo.file.name.to_string()),
118+
// FIXME(#59346): Not really sure when `fold` should be true or false
119+
fold: false,
120+
annotations: line.annotations.iter().map(|a| {
121+
self.annotation_to_source_annotation(a.clone())
122+
}).collect(),
123+
}
124+
}).collect::<Vec<Slice>>()
125+
}).collect::<Vec<Slice>>()
126+
}
127+
128+
/// Turns a `crate::snippet::Annotation` into a `SourceAnnotation`
129+
fn annotation_to_source_annotation(
130+
&self,
131+
annotation: crate::snippet::Annotation
132+
) -> SourceAnnotation {
133+
SourceAnnotation {
134+
range: (annotation.start_col, annotation.end_col),
135+
label: annotation.label.unwrap_or("".to_string()),
136+
annotation_type: Self::annotation_type_for_level(self.level)
137+
}
138+
}
139+
140+
/// Provides the source string for the given `line` of `file`
141+
fn source_string(file: Lrc<SourceFile>,
142+
line: &Line) -> String {
143+
let source_string = match file.get_line(line.line_index - 1) {
144+
Some(s) => s.clone(),
145+
None => return String::new(),
146+
};
147+
source_string.to_string()
148+
}
149+
150+
/// Maps `Diagnostic::Level` to `snippet::AnnotationType`
151+
fn annotation_type_for_level(level: Level) -> AnnotationType {
152+
match level {
153+
Level::Bug | Level::Fatal | Level::PhaseFatal | Level::Error => AnnotationType::Error,
154+
Level::Warning => AnnotationType::Warning,
155+
Level::Note => AnnotationType::Note,
156+
Level::Help => AnnotationType::Help,
157+
// FIXME(#59346): Not sure how to map these two levels
158+
Level::Cancelled | Level::FailureNote => AnnotationType::Error
159+
}
160+
}
161+
}
162+
163+
impl AnnotateRsEmitterWriter {
164+
pub fn new(
165+
source_map: Option<Lrc<SourceMapperDyn>>,
166+
short_message: bool
167+
) -> Self {
168+
Self {
169+
source_map,
170+
short_message,
171+
ui_testing: false,
172+
}
173+
}
174+
175+
/// Allows to modify `Self` to enable or disable the `ui_testing` flag.
176+
///
177+
/// If this is set to true, line numbers will be normalized as `LL` in the output.
178+
// FIXME(#59346): This method is used via the public interface, but setting the `ui_testing`
179+
// flag currently does not anonymize line numbers. We would have to add the `maybe_anonymized`
180+
// method from `emitter.rs` and implement rust-lang/annotate-snippets-rs#2 in order to
181+
// anonymize line numbers.
182+
pub fn ui_testing(mut self, ui_testing: bool) -> Self {
183+
self.ui_testing = ui_testing;
184+
self
185+
}
186+
187+
fn emit_messages_default(&mut self,
188+
level: &Level,
189+
message: String,
190+
code: &Option<DiagnosticId>,
191+
msp: &MultiSpan,
192+
children: &[SubDiagnostic],
193+
suggestions: &[CodeSuggestion]
194+
) {
195+
let converter = DiagnosticConverter {
196+
source_map: self.source_map.clone(),
197+
level: level.clone(),
198+
message: message.clone(),
199+
code: code.clone(),
200+
msp: msp.clone(),
201+
children,
202+
suggestions
203+
};
204+
if let Some(snippet) = converter.to_annotation_snippet() {
205+
let dl = DisplayList::from(snippet);
206+
let dlf = DisplayListFormatter::new(true);
207+
print!("{}", dlf.format(&dl));
208+
};
209+
}
210+
}

src/librustc_errors/emitter.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ use termcolor::{WriteColor, Color, Buffer};
2424
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2525
pub enum HumanReadableErrorType {
2626
Default(ColorConfig),
27+
AnnotateRs(ColorConfig),
2728
Short(ColorConfig),
2829
}
2930

@@ -33,6 +34,7 @@ impl HumanReadableErrorType {
3334
match self {
3435
HumanReadableErrorType::Default(cc) => (false, cc),
3536
HumanReadableErrorType::Short(cc) => (true, cc),
37+
HumanReadableErrorType::AnnotateRs(cc) => (false, cc),
3638
}
3739
}
3840
pub fn new_emitter(
@@ -173,8 +175,8 @@ pub struct EmitterWriter {
173175

174176
#[derive(Debug)]
175177
pub struct FileWithAnnotatedLines {
176-
file: Lrc<SourceFile>,
177-
lines: Vec<Line>,
178+
pub file: Lrc<SourceFile>,
179+
pub lines: Vec<Line>,
178180
multiline_depth: usize,
179181
}
180182

src/librustc_errors/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ use termcolor::{ColorSpec, Color};
3333
mod diagnostic;
3434
mod diagnostic_builder;
3535
pub mod emitter;
36+
pub mod annotate_rs_emitter;
3637
mod snippet;
3738
pub mod registry;
3839
mod styled_buffer;

src/tools/tidy/src/deps.rs

+2
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ const WHITELIST_CRATES: &[CrateVersion<'_>] = &[
6262
const WHITELIST: &[Crate<'_>] = &[
6363
Crate("adler32"),
6464
Crate("aho-corasick"),
65+
Crate("annotate-snippets"),
66+
Crate("ansi_term"),
6567
Crate("arrayvec"),
6668
Crate("atty"),
6769
Crate("autocfg"),

0 commit comments

Comments
 (0)