]>
Commit | Line | Data |
---|---|---|
dc9dc135 XL |
1 | //! The current rustc diagnostics emitter. |
2 | //! | |
3 | //! An `Emitter` takes care of generating the output from a `DiagnosticBuilder` struct. | |
4 | //! | |
5 | //! There are various `Emitter` implementations that generate different output formats such as | |
6 | //! JSON and human readable output. | |
7 | //! | |
ba9703b0 | 8 | //! The output types are defined in `rustc_session::config::ErrorOutputType`. |
dc9dc135 | 9 | |
9fa01778 | 10 | use Destination::*; |
1a4d82fc | 11 | |
dfeec247 XL |
12 | use rustc_span::source_map::SourceMap; |
13 | use rustc_span::{MultiSpan, SourceFile, Span}; | |
223e47cc | 14 | |
60c5eb7d XL |
15 | use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString}; |
16 | use crate::styled_buffer::StyledBuffer; | |
94222f64 XL |
17 | use crate::{ |
18 | CodeSuggestion, Diagnostic, DiagnosticId, Level, SubDiagnostic, SubstitutionHighlight, | |
19 | SuggestionStyle, | |
20 | }; | |
29967ef6 XL |
21 | |
22 | use rustc_lint_defs::pluralize; | |
9cc50fc6 | 23 | |
b7449926 | 24 | use rustc_data_structures::fx::FxHashMap; |
0531ce1d | 25 | use rustc_data_structures::sync::Lrc; |
dfeec247 | 26 | use rustc_span::hygiene::{ExpnKind, MacroKind}; |
041b39d2 | 27 | use std::borrow::Cow; |
60c5eb7d | 28 | use std::cmp::{max, min, Reverse}; |
c34b1796 | 29 | use std::io; |
60c5eb7d | 30 | use std::io::prelude::*; |
74b04a01 | 31 | use std::iter; |
48663c56 | 32 | use std::path::Path; |
60c5eb7d XL |
33 | use termcolor::{Ansi, BufferWriter, ColorChoice, ColorSpec, StandardStream}; |
34 | use termcolor::{Buffer, Color, WriteColor}; | |
3dfed10e | 35 | use tracing::*; |
1a4d82fc | 36 | |
f035d41b XL |
37 | /// Default column width, used in tests and when terminal dimensions cannot be determined. |
38 | const DEFAULT_COLUMN_WIDTH: usize = 140; | |
39 | ||
48663c56 XL |
40 | /// Describes the way the content of the `rendered` field of the json output is generated |
41 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
42 | pub enum HumanReadableErrorType { | |
43 | Default(ColorConfig), | |
dc9dc135 | 44 | AnnotateSnippet(ColorConfig), |
48663c56 XL |
45 | Short(ColorConfig), |
46 | } | |
47 | ||
48 | impl HumanReadableErrorType { | |
49 | /// Returns a (`short`, `color`) tuple | |
50 | pub fn unzip(self) -> (bool, ColorConfig) { | |
51 | match self { | |
52 | HumanReadableErrorType::Default(cc) => (false, cc), | |
53 | HumanReadableErrorType::Short(cc) => (true, cc), | |
dc9dc135 | 54 | HumanReadableErrorType::AnnotateSnippet(cc) => (false, cc), |
48663c56 XL |
55 | } |
56 | } | |
57 | pub fn new_emitter( | |
58 | self, | |
59 | dst: Box<dyn Write + Send>, | |
60c5eb7d | 60 | source_map: Option<Lrc<SourceMap>>, |
48663c56 | 61 | teach: bool, |
e1599b0c | 62 | terminal_width: Option<usize>, |
74b04a01 | 63 | macro_backtrace: bool, |
48663c56 XL |
64 | ) -> EmitterWriter { |
65 | let (short, color_config) = self.unzip(); | |
e1599b0c | 66 | let color = color_config.suggests_using_colors(); |
74b04a01 | 67 | EmitterWriter::new(dst, source_map, short, teach, color, terminal_width, macro_backtrace) |
e1599b0c XL |
68 | } |
69 | } | |
70 | ||
71 | #[derive(Clone, Copy, Debug)] | |
72 | struct Margin { | |
73 | /// The available whitespace in the left that can be consumed when centering. | |
74 | pub whitespace_left: usize, | |
75 | /// The column of the beginning of left-most span. | |
76 | pub span_left: usize, | |
77 | /// The column of the end of right-most span. | |
78 | pub span_right: usize, | |
79 | /// The beginning of the line to be displayed. | |
80 | pub computed_left: usize, | |
81 | /// The end of the line to be displayed. | |
82 | pub computed_right: usize, | |
f035d41b XL |
83 | /// The current width of the terminal. Uses value of `DEFAULT_COLUMN_WIDTH` constant by default |
84 | /// and in tests. | |
e1599b0c XL |
85 | pub column_width: usize, |
86 | /// The end column of a span label, including the span. Doesn't account for labels not in the | |
87 | /// same line as the span. | |
88 | pub label_right: usize, | |
89 | } | |
90 | ||
91 | impl Margin { | |
92 | fn new( | |
93 | whitespace_left: usize, | |
94 | span_left: usize, | |
95 | span_right: usize, | |
96 | label_right: usize, | |
97 | column_width: usize, | |
98 | max_line_len: usize, | |
99 | ) -> Self { | |
100 | // The 6 is padding to give a bit of room for `...` when displaying: | |
101 | // ``` | |
102 | // error: message | |
103 | // --> file.rs:16:58 | |
104 | // | | |
105 | // 16 | ... fn foo(self) -> Self::Bar { | |
106 | // | ^^^^^^^^^ | |
107 | // ``` | |
108 | ||
109 | let mut m = Margin { | |
e74abb32 XL |
110 | whitespace_left: whitespace_left.saturating_sub(6), |
111 | span_left: span_left.saturating_sub(6), | |
e1599b0c XL |
112 | span_right: span_right + 6, |
113 | computed_left: 0, | |
114 | computed_right: 0, | |
115 | column_width, | |
116 | label_right: label_right + 6, | |
117 | }; | |
118 | m.compute(max_line_len); | |
119 | m | |
120 | } | |
121 | ||
122 | fn was_cut_left(&self) -> bool { | |
123 | self.computed_left > 0 | |
124 | } | |
125 | ||
126 | fn was_cut_right(&self, line_len: usize) -> bool { | |
60c5eb7d XL |
127 | let right = |
128 | if self.computed_right == self.span_right || self.computed_right == self.label_right { | |
dfeec247 XL |
129 | // Account for the "..." padding given above. Otherwise we end up with code lines that |
130 | // do fit but end in "..." as if they were trimmed. | |
60c5eb7d XL |
131 | self.computed_right - 6 |
132 | } else { | |
133 | self.computed_right | |
134 | }; | |
e74abb32 | 135 | right < line_len && self.computed_left + self.column_width < line_len |
e1599b0c XL |
136 | } |
137 | ||
138 | fn compute(&mut self, max_line_len: usize) { | |
139 | // When there's a lot of whitespace (>20), we want to trim it as it is useless. | |
140 | self.computed_left = if self.whitespace_left > 20 { | |
141 | self.whitespace_left - 16 // We want some padding. | |
142 | } else { | |
143 | 0 | |
144 | }; | |
145 | // We want to show as much as possible, max_line_len is the right-most boundary for the | |
146 | // relevant code. | |
147 | self.computed_right = max(max_line_len, self.computed_left); | |
148 | ||
149 | if self.computed_right - self.computed_left > self.column_width { | |
150 | // Trimming only whitespace isn't enough, let's get craftier. | |
151 | if self.label_right - self.whitespace_left <= self.column_width { | |
152 | // Attempt to fit the code window only trimming whitespace. | |
153 | self.computed_left = self.whitespace_left; | |
154 | self.computed_right = self.computed_left + self.column_width; | |
155 | } else if self.label_right - self.span_left <= self.column_width { | |
156 | // Attempt to fit the code window considering only the spans and labels. | |
157 | let padding_left = (self.column_width - (self.label_right - self.span_left)) / 2; | |
158 | self.computed_left = self.span_left.saturating_sub(padding_left); | |
159 | self.computed_right = self.computed_left + self.column_width; | |
160 | } else if self.span_right - self.span_left <= self.column_width { | |
161 | // Attempt to fit the code window considering the spans and labels plus padding. | |
162 | let padding_left = (self.column_width - (self.span_right - self.span_left)) / 5 * 2; | |
163 | self.computed_left = self.span_left.saturating_sub(padding_left); | |
164 | self.computed_right = self.computed_left + self.column_width; | |
60c5eb7d XL |
165 | } else { |
166 | // Mostly give up but still don't show the full line. | |
e1599b0c XL |
167 | self.computed_left = self.span_left; |
168 | self.computed_right = self.span_right; | |
169 | } | |
170 | } | |
171 | } | |
172 | ||
173 | fn left(&self, line_len: usize) -> usize { | |
174 | min(self.computed_left, line_len) | |
175 | } | |
176 | ||
177 | fn right(&self, line_len: usize) -> usize { | |
e74abb32 | 178 | if line_len.saturating_sub(self.computed_left) <= self.column_width { |
e1599b0c XL |
179 | line_len |
180 | } else { | |
e74abb32 | 181 | min(line_len, self.computed_right) |
e1599b0c | 182 | } |
48663c56 XL |
183 | } |
184 | } | |
185 | ||
0531ce1d XL |
186 | const ANONYMIZED_LINE_NUM: &str = "LL"; |
187 | ||
5bcae85e | 188 | /// Emitter trait for emitting errors. |
9cc50fc6 | 189 | pub trait Emitter { |
9cc50fc6 | 190 | /// Emit a structured diagnostic. |
e74abb32 | 191 | fn emit_diagnostic(&mut self, diag: &Diagnostic); |
48663c56 XL |
192 | |
193 | /// Emit a notification that an artifact has been output. | |
194 | /// This is currently only supported for the JSON format, | |
195 | /// other formats can, and will, simply ignore it. | |
dc9dc135 | 196 | fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {} |
0531ce1d | 197 | |
136023e0 | 198 | fn emit_future_breakage_report(&mut self, _diags: Vec<Diagnostic>) {} |
29967ef6 | 199 | |
cdc7bbd5 XL |
200 | /// Emit list of unused externs |
201 | fn emit_unused_externs(&mut self, _lint_level: &str, _unused_externs: &[&str]) {} | |
202 | ||
9fa01778 | 203 | /// Checks if should show explanations about "rustc --explain" |
0531ce1d XL |
204 | fn should_show_explain(&self) -> bool { |
205 | true | |
206 | } | |
a7813a04 | 207 | |
fc512014 XL |
208 | /// Checks if we can use colors in the current output stream. |
209 | fn supports_color(&self) -> bool { | |
210 | false | |
211 | } | |
212 | ||
60c5eb7d | 213 | fn source_map(&self) -> Option<&Lrc<SourceMap>>; |
e74abb32 | 214 | |
e1599b0c XL |
215 | /// Formats the substitutions of the primary_span |
216 | /// | |
217 | /// The are a lot of conditions to this method, but in short: | |
218 | /// | |
219 | /// * If the current `Diagnostic` has only one visible `CodeSuggestion`, | |
220 | /// we format the `help` suggestion depending on the content of the | |
221 | /// substitutions. In that case, we return the modified span only. | |
222 | /// | |
223 | /// * If the current `Diagnostic` has multiple suggestions, | |
224 | /// we return the original `primary_span` and the original suggestions. | |
225 | fn primary_span_formatted<'a>( | |
226 | &mut self, | |
e74abb32 | 227 | diag: &'a Diagnostic, |
e1599b0c | 228 | ) -> (MultiSpan, &'a [CodeSuggestion]) { |
e74abb32 XL |
229 | let mut primary_span = diag.span.clone(); |
230 | if let Some((sugg, rest)) = diag.suggestions.split_first() { | |
7cac9316 | 231 | if rest.is_empty() && |
e1599b0c | 232 | // ^ if there is only one suggestion |
7cac9316 | 233 | // don't display multi-suggestions as labels |
abe05a73 XL |
234 | sugg.substitutions.len() == 1 && |
235 | // don't display multipart suggestions as labels | |
236 | sugg.substitutions[0].parts.len() == 1 && | |
7cac9316 XL |
237 | // don't display long messages as labels |
238 | sugg.msg.split_whitespace().count() < 10 && | |
239 | // don't display multiline suggestions as labels | |
9fa01778 | 240 | !sugg.substitutions[0].parts[0].snippet.contains('\n') && |
e74abb32 XL |
241 | ![ |
242 | // when this style is set we want the suggestion to be a message, not inline | |
243 | SuggestionStyle::HideCodeAlways, | |
244 | // trivial suggestion for tooling's sake, never shown | |
245 | SuggestionStyle::CompletelyHidden, | |
246 | // subtle suggestion, never shown inline | |
247 | SuggestionStyle::ShowAlways, | |
248 | ].contains(&sugg.style) | |
9fa01778 | 249 | { |
ff7c6d11 | 250 | let substitution = &sugg.substitutions[0].parts[0].snippet.trim(); |
74b04a01 | 251 | let msg = if substitution.is_empty() || sugg.style.hide_inline() { |
e1599b0c XL |
252 | // This substitution is only removal OR we explicitly don't want to show the |
253 | // code inline (`hide_inline`). Therefore, we don't show the substitution. | |
041b39d2 XL |
254 | format!("help: {}", sugg.msg) |
255 | } else { | |
e1599b0c | 256 | // Show the default suggestion text with the substitution |
e74abb32 XL |
257 | format!( |
258 | "help: {}{}: `{}`", | |
259 | sugg.msg, | |
60c5eb7d XL |
260 | if self |
261 | .source_map() | |
262 | .map(|sm| is_case_difference( | |
263 | &**sm, | |
264 | substitution, | |
265 | sugg.substitutions[0].parts[0].span, | |
266 | )) | |
267 | .unwrap_or(false) | |
268 | { | |
e74abb32 XL |
269 | " (notice the capitalization)" |
270 | } else { | |
271 | "" | |
272 | }, | |
273 | substitution, | |
274 | ) | |
041b39d2 | 275 | }; |
abe05a73 | 276 | primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg); |
e1599b0c XL |
277 | |
278 | // We return only the modified primary_span | |
279 | (primary_span, &[]) | |
7cac9316 XL |
280 | } else { |
281 | // if there are multiple suggestions, print them all in full | |
282 | // to be consistent. We could try to figure out if we can | |
283 | // make one (or the first one) inline, but that would give | |
284 | // undue importance to a semi-random suggestion | |
e74abb32 | 285 | (primary_span, &diag.suggestions) |
7cac9316 | 286 | } |
e1599b0c | 287 | } else { |
e74abb32 | 288 | (primary_span, &diag.suggestions) |
e1599b0c XL |
289 | } |
290 | } | |
291 | ||
74b04a01 | 292 | fn fix_multispans_in_extern_macros_and_render_macro_backtrace( |
60c5eb7d XL |
293 | &self, |
294 | source_map: &Option<Lrc<SourceMap>>, | |
295 | span: &mut MultiSpan, | |
296 | children: &mut Vec<SubDiagnostic>, | |
297 | level: &Level, | |
298 | backtrace: bool, | |
299 | ) { | |
74b04a01 XL |
300 | // Check for spans in macros, before `fix_multispans_in_extern_macros` |
301 | // has a chance to replace them. | |
302 | let has_macro_spans = iter::once(&*span) | |
303 | .chain(children.iter().map(|child| &child.span)) | |
304 | .flat_map(|span| span.primary_spans()) | |
f9f354fc XL |
305 | .flat_map(|sp| sp.macro_backtrace()) |
306 | .find_map(|expn_data| { | |
307 | match expn_data.kind { | |
308 | ExpnKind::Root => None, | |
74b04a01 | 309 | |
f9f354fc XL |
310 | // Skip past non-macro entries, just in case there |
311 | // are some which do actually involve macros. | |
29967ef6 | 312 | ExpnKind::Inlined | ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None, |
74b04a01 | 313 | |
136023e0 | 314 | ExpnKind::Macro(macro_kind, name) => Some((macro_kind, name)), |
f9f354fc XL |
315 | } |
316 | }); | |
74b04a01 XL |
317 | |
318 | if !backtrace { | |
319 | self.fix_multispans_in_extern_macros(source_map, span, children); | |
7cac9316 XL |
320 | } |
321 | ||
74b04a01 XL |
322 | self.render_multispans_macro_backtrace(span, children, backtrace); |
323 | ||
324 | if !backtrace { | |
17df50a5 XL |
325 | if let Some((macro_kind, name)) = has_macro_spans { |
326 | let descr = macro_kind.descr(); | |
327 | ||
74b04a01 | 328 | let msg = format!( |
17df50a5 | 329 | "this {level} originates in the {descr} `{name}` \ |
74b04a01 | 330 | (in Nightly builds, run with -Z macro-backtrace for more info)", |
74b04a01 XL |
331 | ); |
332 | ||
333 | children.push(SubDiagnostic { | |
334 | level: Level::Note, | |
335 | message: vec![(msg, Style::NoStyle)], | |
336 | span: MultiSpan::new(), | |
337 | render_span: None, | |
338 | }); | |
339 | } | |
e1599b0c XL |
340 | } |
341 | } | |
342 | ||
74b04a01 | 343 | fn render_multispans_macro_backtrace( |
60c5eb7d | 344 | &self, |
60c5eb7d | 345 | span: &mut MultiSpan, |
74b04a01 XL |
346 | children: &mut Vec<SubDiagnostic>, |
347 | backtrace: bool, | |
348 | ) { | |
349 | for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) { | |
350 | self.render_multispan_macro_backtrace(span, backtrace); | |
351 | } | |
352 | } | |
e1599b0c | 353 | |
74b04a01 | 354 | fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) { |
e74abb32 | 355 | let mut new_labels: Vec<(Span, String)> = vec![]; |
e1599b0c | 356 | |
74b04a01 | 357 | for &sp in span.primary_spans() { |
e74abb32 XL |
358 | if sp.is_dummy() { |
359 | continue; | |
360 | } | |
74b04a01 XL |
361 | |
362 | // FIXME(eddyb) use `retain` on `macro_backtrace` to remove all the | |
363 | // entries we don't want to print, to make sure the indices being | |
364 | // printed are contiguous (or omitted if there's only one entry). | |
dfeec247 | 365 | let macro_backtrace: Vec<_> = sp.macro_backtrace().collect(); |
dfeec247 | 366 | for (i, trace) in macro_backtrace.iter().rev().enumerate() { |
dfeec247 | 367 | if trace.def_site.is_dummy() { |
e1599b0c XL |
368 | continue; |
369 | } | |
74b04a01 | 370 | |
136023e0 | 371 | if always_backtrace && !matches!(trace.kind, ExpnKind::Inlined) { |
60c5eb7d | 372 | new_labels.push(( |
dfeec247 | 373 | trace.def_site, |
60c5eb7d | 374 | format!( |
136023e0 | 375 | "in this expansion of `{}`{}", |
dfeec247 | 376 | trace.kind.descr(), |
3dfed10e | 377 | if macro_backtrace.len() > 1 { |
74b04a01 XL |
378 | // if macro_backtrace.len() == 1 it'll be |
379 | // pointed at by "in this macro invocation" | |
60c5eb7d XL |
380 | format!(" (#{})", i + 1) |
381 | } else { | |
382 | String::new() | |
74b04a01 | 383 | }, |
60c5eb7d XL |
384 | ), |
385 | )); | |
e1599b0c | 386 | } |
74b04a01 XL |
387 | |
388 | // Don't add a label on the call site if the diagnostic itself | |
389 | // already points to (a part of) that call site, as the label | |
390 | // is meant for showing the relevant invocation when the actual | |
391 | // diagnostic is pointing to some part of macro definition. | |
392 | // | |
393 | // This also handles the case where an external span got replaced | |
394 | // with the call site span by `fix_multispans_in_extern_macros`. | |
395 | // | |
396 | // NB: `-Zmacro-backtrace` overrides this, for uniformity, as the | |
397 | // "in this expansion of" label above is always added in that mode, | |
398 | // and it needs an "in this macro invocation" label to match that. | |
399 | let redundant_span = trace.call_site.contains(sp); | |
400 | ||
136023e0 XL |
401 | if !redundant_span || always_backtrace { |
402 | let msg: Cow<'static, _> = match trace.kind { | |
403 | ExpnKind::Macro(MacroKind::Attr, _) => { | |
404 | "this procedural macro expansion".into() | |
405 | } | |
406 | ExpnKind::Macro(MacroKind::Derive, _) => { | |
407 | "this derive macro expansion".into() | |
408 | } | |
409 | ExpnKind::Macro(MacroKind::Bang, _) => "this macro invocation".into(), | |
410 | ExpnKind::Inlined => "the inlined copy of this code".into(), | |
411 | ExpnKind::Root => "in the crate root".into(), | |
412 | ExpnKind::AstPass(kind) => kind.descr().into(), | |
413 | ExpnKind::Desugaring(kind) => { | |
414 | format!("this {} desugaring", kind.descr()).into() | |
415 | } | |
416 | }; | |
60c5eb7d XL |
417 | new_labels.push(( |
418 | trace.call_site, | |
419 | format!( | |
136023e0 XL |
420 | "in {}{}", |
421 | msg, | |
3dfed10e | 422 | if macro_backtrace.len() > 1 && always_backtrace { |
60c5eb7d XL |
423 | // only specify order when the macro |
424 | // backtrace is multiple levels deep | |
425 | format!(" (#{})", i + 1) | |
426 | } else { | |
427 | String::new() | |
74b04a01 | 428 | }, |
60c5eb7d XL |
429 | ), |
430 | )); | |
74b04a01 XL |
431 | } |
432 | if !always_backtrace { | |
433 | break; | |
e1599b0c XL |
434 | } |
435 | } | |
e74abb32 | 436 | } |
74b04a01 | 437 | |
e74abb32 XL |
438 | for (label_span, label_text) in new_labels { |
439 | span.push_span_label(label_span, label_text); | |
440 | } | |
74b04a01 XL |
441 | } |
442 | ||
443 | // This does a small "fix" for multispans by looking to see if it can find any that | |
ba9703b0 XL |
444 | // point directly at external macros. Since these are often difficult to read, |
445 | // this will change the span to point at the use site. | |
74b04a01 XL |
446 | fn fix_multispans_in_extern_macros( |
447 | &self, | |
448 | source_map: &Option<Lrc<SourceMap>>, | |
449 | span: &mut MultiSpan, | |
450 | children: &mut Vec<SubDiagnostic>, | |
451 | ) { | |
cdc7bbd5 XL |
452 | let source_map = if let Some(ref sm) = source_map { |
453 | sm | |
454 | } else { | |
455 | return; | |
456 | }; | |
ba9703b0 | 457 | debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children); |
cdc7bbd5 XL |
458 | self.fix_multispan_in_extern_macros(source_map, span); |
459 | for child in children.iter_mut() { | |
460 | self.fix_multispan_in_extern_macros(source_map, &mut child.span); | |
e74abb32 | 461 | } |
ba9703b0 | 462 | debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children); |
74b04a01 XL |
463 | } |
464 | ||
ba9703b0 XL |
465 | // This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros. |
466 | // Since these locations are often difficult to read, | |
467 | // we move these spans from the external macros to their corresponding use site. | |
cdc7bbd5 | 468 | fn fix_multispan_in_extern_macros(&self, source_map: &Lrc<SourceMap>, span: &mut MultiSpan) { |
ba9703b0 | 469 | // First, find all the spans in external macros and point instead at their use site. |
74b04a01 XL |
470 | let replacements: Vec<(Span, Span)> = span |
471 | .primary_spans() | |
472 | .iter() | |
473 | .copied() | |
474 | .chain(span.span_labels().iter().map(|sp_label| sp_label.span)) | |
475 | .filter_map(|sp| { | |
cdc7bbd5 | 476 | if !sp.is_dummy() && source_map.is_imported(sp) { |
74b04a01 XL |
477 | let maybe_callsite = sp.source_callsite(); |
478 | if sp != maybe_callsite { | |
479 | return Some((sp, maybe_callsite)); | |
480 | } | |
481 | } | |
482 | None | |
483 | }) | |
484 | .collect(); | |
485 | ||
ba9703b0 | 486 | // After we have them, make sure we replace these 'bad' def sites with their use sites. |
74b04a01 XL |
487 | for (from, to) in replacements { |
488 | span.replace(from, to); | |
e1599b0c | 489 | } |
e1599b0c XL |
490 | } |
491 | } | |
492 | ||
493 | impl Emitter for EmitterWriter { | |
60c5eb7d | 494 | fn source_map(&self) -> Option<&Lrc<SourceMap>> { |
e74abb32 XL |
495 | self.sm.as_ref() |
496 | } | |
497 | ||
498 | fn emit_diagnostic(&mut self, diag: &Diagnostic) { | |
499 | let mut children = diag.children.clone(); | |
500 | let (mut primary_span, suggestions) = self.primary_span_formatted(&diag); | |
ba9703b0 | 501 | debug!("emit_diagnostic: suggestions={:?}", suggestions); |
e1599b0c | 502 | |
74b04a01 | 503 | self.fix_multispans_in_extern_macros_and_render_macro_backtrace( |
60c5eb7d XL |
504 | &self.sm, |
505 | &mut primary_span, | |
506 | &mut children, | |
507 | &diag.level, | |
74b04a01 | 508 | self.macro_backtrace, |
60c5eb7d XL |
509 | ); |
510 | ||
511 | self.emit_messages_default( | |
512 | &diag.level, | |
513 | &diag.styled_message(), | |
514 | &diag.code, | |
515 | &primary_span, | |
516 | &children, | |
517 | &suggestions, | |
518 | ); | |
1a4d82fc | 519 | } |
0531ce1d XL |
520 | |
521 | fn should_show_explain(&self) -> bool { | |
522 | !self.short_message | |
523 | } | |
fc512014 XL |
524 | |
525 | fn supports_color(&self) -> bool { | |
526 | self.dst.supports_color() | |
527 | } | |
223e47cc LB |
528 | } |
529 | ||
60c5eb7d XL |
530 | /// An emitter that does nothing when emitting a diagnostic. |
531 | pub struct SilentEmitter; | |
532 | ||
533 | impl Emitter for SilentEmitter { | |
534 | fn source_map(&self) -> Option<&Lrc<SourceMap>> { | |
535 | None | |
536 | } | |
537 | fn emit_diagnostic(&mut self, _: &Diagnostic) {} | |
538 | } | |
539 | ||
dfeec247 XL |
540 | /// Maximum number of lines we will print for a multiline suggestion; arbitrary. |
541 | /// | |
542 | /// This should be replaced with a more involved mechanism to output multiline suggestions that | |
29967ef6 | 543 | /// more closely mimics the regular diagnostic output, where irrelevant code lines are elided. |
dfeec247 XL |
544 | pub const MAX_SUGGESTION_HIGHLIGHT_LINES: usize = 6; |
545 | /// Maximum number of suggestions to be shown | |
7cac9316 XL |
546 | /// |
547 | /// Arbitrary, but taken from trait import suggestion limit | |
548 | pub const MAX_SUGGESTIONS: usize = 4; | |
7453a54e | 549 | |
9cc50fc6 | 550 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
1a4d82fc JJ |
551 | pub enum ColorConfig { |
552 | Auto, | |
553 | Always, | |
9cc50fc6 | 554 | Never, |
223e47cc LB |
555 | } |
556 | ||
9cc50fc6 | 557 | impl ColorConfig { |
48663c56 XL |
558 | fn to_color_choice(self) -> ColorChoice { |
559 | match self { | |
a1dfa0c6 XL |
560 | ColorConfig::Always => { |
561 | if atty::is(atty::Stream::Stderr) { | |
562 | ColorChoice::Always | |
563 | } else { | |
564 | ColorChoice::AlwaysAnsi | |
565 | } | |
566 | } | |
0531ce1d | 567 | ColorConfig::Never => ColorChoice::Never, |
60c5eb7d | 568 | ColorConfig::Auto if atty::is(atty::Stream::Stderr) => ColorChoice::Auto, |
0531ce1d | 569 | ColorConfig::Auto => ColorChoice::Never, |
9cc50fc6 | 570 | } |
d9579d0f | 571 | } |
48663c56 XL |
572 | fn suggests_using_colors(self) -> bool { |
573 | match self { | |
60c5eb7d | 574 | ColorConfig::Always | ColorConfig::Auto => true, |
48663c56 XL |
575 | ColorConfig::Never => false, |
576 | } | |
577 | } | |
d9579d0f AL |
578 | } |
579 | ||
dc9dc135 | 580 | /// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short` |
9cc50fc6 SL |
581 | pub struct EmitterWriter { |
582 | dst: Destination, | |
60c5eb7d | 583 | sm: Option<Lrc<SourceMap>>, |
abe05a73 | 584 | short_message: bool, |
2c00a5a8 | 585 | teach: bool, |
0531ce1d | 586 | ui_testing: bool, |
e1599b0c XL |
587 | terminal_width: Option<usize>, |
588 | ||
74b04a01 | 589 | macro_backtrace: bool, |
a7813a04 | 590 | } |
223e47cc | 591 | |
dc9dc135 XL |
592 | #[derive(Debug)] |
593 | pub struct FileWithAnnotatedLines { | |
594 | pub file: Lrc<SourceFile>, | |
595 | pub lines: Vec<Line>, | |
476ff2be | 596 | multiline_depth: usize, |
223e47cc LB |
597 | } |
598 | ||
1a4d82fc | 599 | impl EmitterWriter { |
e1599b0c XL |
600 | pub fn stderr( |
601 | color_config: ColorConfig, | |
60c5eb7d | 602 | source_map: Option<Lrc<SourceMap>>, |
e1599b0c XL |
603 | short_message: bool, |
604 | teach: bool, | |
605 | terminal_width: Option<usize>, | |
74b04a01 | 606 | macro_backtrace: bool, |
e1599b0c | 607 | ) -> EmitterWriter { |
0531ce1d XL |
608 | let dst = Destination::from_stderr(color_config); |
609 | EmitterWriter { | |
610 | dst, | |
a1dfa0c6 | 611 | sm: source_map, |
0531ce1d XL |
612 | short_message, |
613 | teach, | |
614 | ui_testing: false, | |
e1599b0c | 615 | terminal_width, |
74b04a01 | 616 | macro_backtrace, |
1a4d82fc JJ |
617 | } |
618 | } | |
619 | ||
48663c56 XL |
620 | pub fn new( |
621 | dst: Box<dyn Write + Send>, | |
60c5eb7d | 622 | source_map: Option<Lrc<SourceMap>>, |
48663c56 XL |
623 | short_message: bool, |
624 | teach: bool, | |
625 | colored: bool, | |
e1599b0c | 626 | terminal_width: Option<usize>, |
74b04a01 | 627 | macro_backtrace: bool, |
48663c56 | 628 | ) -> EmitterWriter { |
c30ab7b3 | 629 | EmitterWriter { |
48663c56 | 630 | dst: Raw(dst, colored), |
a1dfa0c6 | 631 | sm: source_map, |
2c00a5a8 XL |
632 | short_message, |
633 | teach, | |
0531ce1d | 634 | ui_testing: false, |
e1599b0c | 635 | terminal_width, |
74b04a01 | 636 | macro_backtrace, |
0531ce1d XL |
637 | } |
638 | } | |
639 | ||
640 | pub fn ui_testing(mut self, ui_testing: bool) -> Self { | |
641 | self.ui_testing = ui_testing; | |
642 | self | |
643 | } | |
644 | ||
645 | fn maybe_anonymized(&self, line_num: usize) -> String { | |
60c5eb7d | 646 | if self.ui_testing { ANONYMIZED_LINE_NUM.to_string() } else { line_num.to_string() } |
a7813a04 XL |
647 | } |
648 | ||
e1599b0c XL |
649 | fn draw_line( |
650 | &self, | |
651 | buffer: &mut StyledBuffer, | |
652 | source_string: &str, | |
653 | line_index: usize, | |
654 | line_offset: usize, | |
655 | width_offset: usize, | |
656 | code_offset: usize, | |
657 | margin: Margin, | |
658 | ) { | |
5869c6ff XL |
659 | // Tabs are assumed to have been replaced by spaces in calling code. |
660 | debug_assert!(!source_string.contains('\t')); | |
e1599b0c XL |
661 | let line_len = source_string.len(); |
662 | // Create the source line we will highlight. | |
663 | let left = margin.left(line_len); | |
664 | let right = margin.right(line_len); | |
665 | // On long lines, we strip the source line, accounting for unicode. | |
666 | let mut taken = 0; | |
60c5eb7d XL |
667 | let code: String = source_string |
668 | .chars() | |
669 | .skip(left) | |
670 | .take_while(|ch| { | |
dfeec247 XL |
671 | // Make sure that the trimming on the right will fall within the terminal width. |
672 | // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. | |
673 | // For now, just accept that sometimes the code line will be longer than desired. | |
60c5eb7d XL |
674 | let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1); |
675 | if taken + next > right - left { | |
676 | return false; | |
677 | } | |
678 | taken += next; | |
679 | true | |
680 | }) | |
681 | .collect(); | |
e1599b0c XL |
682 | buffer.puts(line_offset, code_offset, &code, Style::Quotation); |
683 | if margin.was_cut_left() { | |
684 | // We have stripped some code/whitespace from the beginning, make it clear. | |
685 | buffer.puts(line_offset, code_offset, "...", Style::LineNumber); | |
686 | } | |
687 | if margin.was_cut_right(line_len) { | |
688 | // We have stripped some code after the right-most span end, make it clear we did so. | |
689 | buffer.puts(line_offset, code_offset + taken - 3, "...", Style::LineNumber); | |
690 | } | |
691 | buffer.puts(line_offset, 0, &self.maybe_anonymized(line_index), Style::LineNumber); | |
692 | ||
693 | draw_col_separator(buffer, line_offset, width_offset - 2); | |
694 | } | |
695 | ||
696 | fn render_source_line( | |
697 | &self, | |
698 | buffer: &mut StyledBuffer, | |
699 | file: Lrc<SourceFile>, | |
700 | line: &Line, | |
701 | width_offset: usize, | |
702 | code_offset: usize, | |
703 | margin: Margin, | |
704 | ) -> Vec<(usize, Style)> { | |
705 | // Draw: | |
706 | // | |
707 | // LL | ... code ... | |
708 | // | ^^-^ span label | |
709 | // | | | |
710 | // | secondary span label | |
711 | // | |
712 | // ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it | |
713 | // | | | | | |
714 | // | | | actual code found in your source code and the spans we use to mark it | |
715 | // | | when there's too much wasted space to the left, trim it | |
716 | // | vertical divider between the column number and the code | |
717 | // column number | |
718 | ||
2c00a5a8 XL |
719 | if line.line_index == 0 { |
720 | return Vec::new(); | |
721 | } | |
722 | ||
7cac9316 | 723 | let source_string = match file.get_line(line.line_index - 1) { |
5869c6ff | 724 | Some(s) => replace_tabs(&*s), |
7cac9316 XL |
725 | None => return Vec::new(), |
726 | }; | |
5bcae85e SL |
727 | |
728 | let line_offset = buffer.num_lines(); | |
c1a9b12d | 729 | |
e1599b0c XL |
730 | let left = margin.left(source_string.len()); // Left trim |
731 | // Account for unicode characters of width !=0 that were removed. | |
60c5eb7d XL |
732 | let left = source_string |
733 | .chars() | |
734 | .take(left) | |
e74abb32 XL |
735 | .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) |
736 | .sum(); | |
5bcae85e | 737 | |
e1599b0c XL |
738 | self.draw_line( |
739 | buffer, | |
740 | &source_string, | |
741 | line.line_index, | |
742 | line_offset, | |
743 | width_offset, | |
744 | code_offset, | |
745 | margin, | |
746 | ); | |
5bcae85e | 747 | |
cc61c64b XL |
748 | // Special case when there's only one annotation involved, it is the start of a multiline |
749 | // span and there's no text at the beginning of the code line. Instead of doing the whole | |
750 | // graph: | |
751 | // | |
752 | // 2 | fn foo() { | |
753 | // | _^ | |
754 | // 3 | | | |
755 | // 4 | | } | |
756 | // | |_^ test | |
757 | // | |
758 | // we simplify the output to: | |
759 | // | |
760 | // 2 | / fn foo() { | |
761 | // 3 | | | |
762 | // 4 | | } | |
763 | // | |_^ test | |
e74abb32 XL |
764 | if let [ann] = &line.annotations[..] { |
765 | if let AnnotationType::MultilineStart(depth) = ann.annotation_type { | |
766 | if source_string.chars().take(ann.start_col).all(|c| c.is_whitespace()) { | |
767 | let style = if ann.is_primary { | |
768 | Style::UnderlinePrimary | |
769 | } else { | |
770 | Style::UnderlineSecondary | |
771 | }; | |
772 | buffer.putc(line_offset, width_offset + depth - 1, '/', style); | |
773 | return vec![(depth, style)]; | |
cc61c64b XL |
774 | } |
775 | } | |
776 | } | |
777 | ||
5bcae85e SL |
778 | // We want to display like this: |
779 | // | |
780 | // vec.push(vec.pop().unwrap()); | |
476ff2be | 781 | // --- ^^^ - previous borrow ends here |
5bcae85e SL |
782 | // | | |
783 | // | error occurs here | |
784 | // previous borrow of `vec` occurs here | |
785 | // | |
786 | // But there are some weird edge cases to be aware of: | |
787 | // | |
788 | // vec.push(vec.pop().unwrap()); | |
789 | // -------- - previous borrow ends here | |
790 | // || | |
791 | // |this makes no sense | |
792 | // previous borrow of `vec` occurs here | |
793 | // | |
794 | // For this reason, we group the lines into "highlight lines" | |
cc61c64b | 795 | // and "annotations lines", where the highlight lines have the `^`. |
5bcae85e SL |
796 | |
797 | // Sort the annotations by (start, end col) | |
3b2f2976 XL |
798 | // The labels are reversed, sort and then reversed again. |
799 | // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where | |
800 | // the letter signifies the span. Here we are only sorting by the | |
801 | // span and hence, the order of the elements with the same span will | |
802 | // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get | |
803 | // (C1, C2, B1, B2, A1, A2). All the elements with the same span are | |
804 | // still ordered first to last, but all the elements with different | |
805 | // spans are ordered by their spans in last to first order. Last to | |
806 | // first order is important, because the jiggly lines and | are on | |
807 | // the left, so the rightmost span needs to be rendered first, | |
808 | // otherwise the lines would end up needing to go over a message. | |
809 | ||
5bcae85e | 810 | let mut annotations = line.annotations.clone(); |
8faf50e0 | 811 | annotations.sort_by_key(|a| Reverse(a.start_col)); |
5bcae85e | 812 | |
476ff2be SL |
813 | // First, figure out where each label will be positioned. |
814 | // | |
815 | // In the case where you have the following annotations: | |
816 | // | |
817 | // vec.push(vec.pop().unwrap()); | |
818 | // -------- - previous borrow ends here [C] | |
819 | // || | |
820 | // |this makes no sense [B] | |
821 | // previous borrow of `vec` occurs here [A] | |
822 | // | |
823 | // `annotations_position` will hold [(2, A), (1, B), (0, C)]. | |
824 | // | |
825 | // We try, when possible, to stick the rightmost annotation at the end | |
826 | // of the highlight line: | |
5bcae85e SL |
827 | // |
828 | // vec.push(vec.pop().unwrap()); | |
829 | // --- --- - previous borrow ends here | |
830 | // | |
831 | // But sometimes that's not possible because one of the other | |
832 | // annotations overlaps it. For example, from the test | |
833 | // `span_overlap_label`, we have the following annotations | |
834 | // (written on distinct lines for clarity): | |
835 | // | |
836 | // fn foo(x: u32) { | |
837 | // -------------- | |
838 | // - | |
839 | // | |
840 | // In this case, we can't stick the rightmost-most label on | |
841 | // the highlight line, or we would get: | |
842 | // | |
843 | // fn foo(x: u32) { | |
844 | // -------- x_span | |
845 | // | | |
846 | // fn_span | |
847 | // | |
848 | // which is totally weird. Instead we want: | |
849 | // | |
850 | // fn foo(x: u32) { | |
851 | // -------------- | |
852 | // | | | |
853 | // | x_span | |
854 | // fn_span | |
855 | // | |
856 | // which is...less weird, at least. In fact, in general, if | |
857 | // the rightmost span overlaps with any other span, we should | |
858 | // use the "hang below" version, so we can at least make it | |
32a655c1 SL |
859 | // clear where the span *starts*. There's an exception for this |
860 | // logic, when the labels do not have a message: | |
861 | // | |
862 | // fn foo(x: u32) { | |
863 | // -------------- | |
864 | // | | |
865 | // x_span | |
866 | // | |
867 | // instead of: | |
868 | // | |
869 | // fn foo(x: u32) { | |
870 | // -------------- | |
871 | // | | | |
872 | // | x_span | |
873 | // <EMPTY LINE> | |
874 | // | |
476ff2be SL |
875 | let mut annotations_position = vec![]; |
876 | let mut line_len = 0; | |
877 | let mut p = 0; | |
8bb4bdeb XL |
878 | for (i, annotation) in annotations.iter().enumerate() { |
879 | for (j, next) in annotations.iter().enumerate() { | |
880 | if overlaps(next, annotation, 0) // This label overlaps with another one and both | |
cc61c64b XL |
881 | && annotation.has_label() // take space (they have text and are not |
882 | && j > i // multiline lines). | |
60c5eb7d XL |
883 | && p == 0 |
884 | // We're currently on the first line, move the label one line down | |
32a655c1 | 885 | { |
48663c56 XL |
886 | // If we're overlapping with an un-labelled annotation with the same span |
887 | // we can just merge them in the output | |
888 | if next.start_col == annotation.start_col | |
60c5eb7d XL |
889 | && next.end_col == annotation.end_col |
890 | && !next.has_label() | |
48663c56 XL |
891 | { |
892 | continue; | |
893 | } | |
894 | ||
32a655c1 | 895 | // This annotation needs a new line in the output. |
476ff2be | 896 | p += 1; |
8bb4bdeb | 897 | break; |
a7813a04 | 898 | } |
c1a9b12d | 899 | } |
476ff2be | 900 | annotations_position.push((p, annotation)); |
8bb4bdeb | 901 | for (j, next) in annotations.iter().enumerate() { |
60c5eb7d | 902 | if j > i { |
e74abb32 | 903 | let l = next.label.as_ref().map_or(0, |label| label.len() + 2); |
cc61c64b | 904 | if (overlaps(next, annotation, l) // Do not allow two labels to be in the same |
8bb4bdeb XL |
905 | // line if they overlap including padding, to |
906 | // avoid situations like: | |
907 | // | |
908 | // fn foo(x: u32) { | |
909 | // -------^------ | |
910 | // | | | |
911 | // fn_spanx_span | |
912 | // | |
8bb4bdeb | 913 | && annotation.has_label() // Both labels must have some text, otherwise |
cc61c64b XL |
914 | && next.has_label()) // they are not overlapping. |
915 | // Do not add a new line if this annotation | |
916 | // or the next are vertical line placeholders. | |
917 | || (annotation.takes_space() // If either this or the next annotation is | |
918 | && next.has_label()) // multiline start/end, move it to a new line | |
29967ef6 | 919 | || (annotation.has_label() // so as not to overlap the horizontal lines. |
cc61c64b | 920 | && next.takes_space()) |
041b39d2 XL |
921 | || (annotation.takes_space() && next.takes_space()) |
922 | || (overlaps(next, annotation, l) | |
923 | && next.end_col <= annotation.end_col | |
924 | && next.has_label() | |
60c5eb7d XL |
925 | && p == 0) |
926 | // Avoid #42595. | |
8bb4bdeb | 927 | { |
cc61c64b | 928 | // This annotation needs a new line in the output. |
8bb4bdeb XL |
929 | p += 1; |
930 | break; | |
931 | } | |
476ff2be SL |
932 | } |
933 | } | |
e74abb32 | 934 | line_len = max(line_len, p); |
476ff2be | 935 | } |
cc61c64b | 936 | |
476ff2be SL |
937 | if line_len != 0 { |
938 | line_len += 1; | |
5bcae85e SL |
939 | } |
940 | ||
476ff2be SL |
941 | // If there are no annotations or the only annotations on this line are |
942 | // MultilineLine, then there's only code being shown, stop processing. | |
8faf50e0 | 943 | if line.annotations.iter().all(|a| a.is_line()) { |
cc61c64b | 944 | return vec![]; |
5bcae85e SL |
945 | } |
946 | ||
60c5eb7d | 947 | // Write the column separator. |
32a655c1 SL |
948 | // |
949 | // After this we will have: | |
950 | // | |
951 | // 2 | fn foo() { | |
952 | // | | |
953 | // | | |
954 | // | | |
955 | // 3 | | |
956 | // 4 | } | |
957 | // | | |
0731742a | 958 | for pos in 0..=line_len { |
476ff2be | 959 | draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2); |
476ff2be SL |
960 | } |
961 | ||
962 | // Write the horizontal lines for multiline annotations | |
963 | // (only the first and last lines need this). | |
964 | // | |
965 | // After this we will have: | |
966 | // | |
967 | // 2 | fn foo() { | |
968 | // | __________ | |
969 | // | | |
970 | // | | |
971 | // 3 | | |
972 | // 4 | } | |
973 | // | _ | |
974 | for &(pos, annotation) in &annotations_position { | |
975 | let style = if annotation.is_primary { | |
976 | Style::UnderlinePrimary | |
977 | } else { | |
978 | Style::UnderlineSecondary | |
979 | }; | |
980 | let pos = pos + 1; | |
981 | match annotation.annotation_type { | |
60c5eb7d | 982 | AnnotationType::MultilineStart(depth) | AnnotationType::MultilineEnd(depth) => { |
e1599b0c XL |
983 | draw_range( |
984 | buffer, | |
985 | '_', | |
986 | line_offset + pos, | |
987 | width_offset + depth, | |
6c58768f | 988 | (code_offset + annotation.start_col).saturating_sub(left), |
e1599b0c XL |
989 | style, |
990 | ); | |
476ff2be | 991 | } |
2c00a5a8 | 992 | _ if self.teach => { |
e1599b0c XL |
993 | buffer.set_style_range( |
994 | line_offset, | |
6c58768f XL |
995 | (code_offset + annotation.start_col).saturating_sub(left), |
996 | (code_offset + annotation.end_col).saturating_sub(left), | |
e1599b0c XL |
997 | style, |
998 | annotation.is_primary, | |
999 | ); | |
2c00a5a8 XL |
1000 | } |
1001 | _ => {} | |
476ff2be SL |
1002 | } |
1003 | } | |
1004 | ||
cc61c64b | 1005 | // Write the vertical lines for labels that are on a different line as the underline. |
476ff2be SL |
1006 | // |
1007 | // After this we will have: | |
1008 | // | |
1009 | // 2 | fn foo() { | |
1010 | // | __________ | |
1011 | // | | | | |
1012 | // | | | |
60c5eb7d | 1013 | // 3 | | |
476ff2be SL |
1014 | // 4 | | } |
1015 | // | |_ | |
1016 | for &(pos, annotation) in &annotations_position { | |
1017 | let style = if annotation.is_primary { | |
1018 | Style::UnderlinePrimary | |
1019 | } else { | |
1020 | Style::UnderlineSecondary | |
1021 | }; | |
1022 | let pos = pos + 1; | |
32a655c1 | 1023 | |
cc61c64b | 1024 | if pos > 1 && (annotation.has_label() || annotation.takes_space()) { |
0731742a | 1025 | for p in line_offset + 1..=line_offset + pos { |
60c5eb7d XL |
1026 | buffer.putc( |
1027 | p, | |
1028 | (code_offset + annotation.start_col).saturating_sub(left), | |
1029 | '|', | |
1030 | style, | |
1031 | ); | |
476ff2be SL |
1032 | } |
1033 | } | |
1034 | match annotation.annotation_type { | |
1035 | AnnotationType::MultilineStart(depth) => { | |
1036 | for p in line_offset + pos + 1..line_offset + line_len + 2 { | |
60c5eb7d | 1037 | buffer.putc(p, width_offset + depth - 1, '|', style); |
476ff2be SL |
1038 | } |
1039 | } | |
1040 | AnnotationType::MultilineEnd(depth) => { | |
0731742a | 1041 | for p in line_offset..=line_offset + pos { |
60c5eb7d | 1042 | buffer.putc(p, width_offset + depth - 1, '|', style); |
476ff2be SL |
1043 | } |
1044 | } | |
476ff2be SL |
1045 | _ => (), |
1046 | } | |
1047 | } | |
1048 | ||
1049 | // Write the labels on the annotations that actually have a label. | |
1050 | // | |
1051 | // After this we will have: | |
1052 | // | |
1053 | // 2 | fn foo() { | |
cc61c64b XL |
1054 | // | __________ |
1055 | // | | | |
1056 | // | something about `foo` | |
1057 | // 3 | | |
1058 | // 4 | } | |
1059 | // | _ test | |
476ff2be | 1060 | for &(pos, annotation) in &annotations_position { |
60c5eb7d XL |
1061 | let style = |
1062 | if annotation.is_primary { Style::LabelPrimary } else { Style::LabelSecondary }; | |
476ff2be | 1063 | let (pos, col) = if pos == 0 { |
e74abb32 | 1064 | (pos + 1, (annotation.end_col + 1).saturating_sub(left)) |
476ff2be | 1065 | } else { |
e74abb32 | 1066 | (pos + 2, annotation.start_col.saturating_sub(left)) |
476ff2be SL |
1067 | }; |
1068 | if let Some(ref label) = annotation.label { | |
e1599b0c | 1069 | buffer.puts(line_offset + pos, code_offset + col, &label, style); |
476ff2be SL |
1070 | } |
1071 | } | |
1072 | ||
1073 | // Sort from biggest span to smallest span so that smaller spans are | |
1074 | // represented in the output: | |
1075 | // | |
1076 | // x | fn foo() | |
1077 | // | ^^^---^^ | |
1078 | // | | | | |
1079 | // | | something about `foo` | |
1080 | // | something about `fn foo()` | |
e74abb32 XL |
1081 | annotations_position.sort_by_key(|(_, ann)| { |
1082 | // Decreasing order. When annotations share the same length, prefer `Primary`. | |
1083 | (Reverse(ann.len()), ann.is_primary) | |
476ff2be | 1084 | }); |
5bcae85e | 1085 | |
476ff2be SL |
1086 | // Write the underlines. |
1087 | // | |
1088 | // After this we will have: | |
1089 | // | |
1090 | // 2 | fn foo() { | |
cc61c64b XL |
1091 | // | ____-_____^ |
1092 | // | | | |
1093 | // | something about `foo` | |
1094 | // 3 | | |
1095 | // 4 | } | |
1096 | // | _^ test | |
476ff2be SL |
1097 | for &(_, annotation) in &annotations_position { |
1098 | let (underline, style) = if annotation.is_primary { | |
1099 | ('^', Style::UnderlinePrimary) | |
5bcae85e | 1100 | } else { |
476ff2be SL |
1101 | ('-', Style::UnderlineSecondary) |
1102 | }; | |
1103 | for p in annotation.start_col..annotation.end_col { | |
e1599b0c XL |
1104 | buffer.putc( |
1105 | line_offset + 1, | |
e74abb32 | 1106 | (code_offset + p).saturating_sub(left), |
e1599b0c XL |
1107 | underline, |
1108 | style, | |
1109 | ); | |
c1a9b12d SL |
1110 | } |
1111 | } | |
60c5eb7d XL |
1112 | annotations_position |
1113 | .iter() | |
1114 | .filter_map(|&(_, annotation)| match annotation.annotation_type { | |
cc61c64b XL |
1115 | AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => { |
1116 | let style = if annotation.is_primary { | |
1117 | Style::LabelPrimary | |
1118 | } else { | |
1119 | Style::LabelSecondary | |
1120 | }; | |
1121 | Some((p, style)) | |
abe05a73 | 1122 | } |
60c5eb7d XL |
1123 | _ => None, |
1124 | }) | |
1125 | .collect::<Vec<_>>() | |
5bcae85e SL |
1126 | } |
1127 | ||
1128 | fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize { | |
e74abb32 XL |
1129 | let sm = match self.sm { |
1130 | Some(ref sm) => sm, | |
1131 | None => return 0, | |
1132 | }; | |
1133 | ||
5bcae85e | 1134 | let mut max = 0; |
e74abb32 XL |
1135 | for primary_span in msp.primary_spans() { |
1136 | if !primary_span.is_dummy() { | |
1137 | let hi = sm.lookup_char_pos(primary_span.hi()); | |
1138 | max = (hi.line).max(max); | |
5bcae85e | 1139 | } |
e74abb32 XL |
1140 | } |
1141 | if !self.short_message { | |
1142 | for span_label in msp.span_labels() { | |
1143 | if !span_label.span.is_dummy() { | |
1144 | let hi = sm.lookup_char_pos(span_label.span.hi()); | |
1145 | max = (hi.line).max(max); | |
a7813a04 | 1146 | } |
7453a54e | 1147 | } |
c1a9b12d | 1148 | } |
e74abb32 | 1149 | |
5bcae85e | 1150 | max |
c1a9b12d SL |
1151 | } |
1152 | ||
8faf50e0 | 1153 | fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize { |
9e0c209e | 1154 | let primary = self.get_multispan_max_line_num(span); |
60c5eb7d XL |
1155 | children |
1156 | .iter() | |
e74abb32 XL |
1157 | .map(|sub| self.get_multispan_max_line_num(&sub.span)) |
1158 | .max() | |
1159 | .unwrap_or(0) | |
1160 | .max(primary) | |
c1a9b12d SL |
1161 | } |
1162 | ||
9fa01778 | 1163 | /// Adds a left margin to every line but the first, given a padding length and the label being |
32a655c1 | 1164 | /// displayed, keeping the provided highlighting. |
60c5eb7d XL |
1165 | fn msg_to_buffer( |
1166 | &self, | |
1167 | buffer: &mut StyledBuffer, | |
1168 | msg: &[(String, Style)], | |
1169 | padding: usize, | |
1170 | label: &str, | |
1171 | override_style: Option<Style>, | |
1172 | ) { | |
32a655c1 SL |
1173 | // The extra 5 ` ` is padding that's always needed to align to the `note: `: |
1174 | // | |
1175 | // error: message | |
1176 | // --> file.rs:13:20 | |
1177 | // | | |
1178 | // 13 | <CODE> | |
1179 | // | ^^^^ | |
1180 | // | | |
1181 | // = note: multiline | |
1182 | // message | |
1183 | // ++^^^----xx | |
1184 | // | | | | | |
1185 | // | | | magic `2` | |
1186 | // | | length of label | |
1187 | // | magic `3` | |
1188 | // `max_line_num_len` | |
8faf50e0 | 1189 | let padding = " ".repeat(padding + label.len() + 5); |
32a655c1 | 1190 | |
e74abb32 XL |
1191 | /// Returns `override` if it is present and `style` is `NoStyle` or `style` otherwise |
1192 | fn style_or_override(style: Style, override_: Option<Style>) -> Style { | |
1193 | match (style, override_) { | |
1194 | (Style::NoStyle, Some(override_)) => override_, | |
1195 | _ => style, | |
32a655c1 | 1196 | } |
32a655c1 SL |
1197 | } |
1198 | ||
1199 | let mut line_number = 0; | |
1200 | ||
1201 | // Provided the following diagnostic message: | |
1202 | // | |
1203 | // let msg = vec![ | |
1204 | // (" | |
1205 | // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle), | |
1206 | // ("looks", Style::Highlight), | |
1207 | // ("with\nvery ", Style::NoStyle), | |
1208 | // ("weird", Style::Highlight), | |
1209 | // (" formats\n", Style::NoStyle), | |
1210 | // ("see?", Style::Highlight), | |
1211 | // ]; | |
1212 | // | |
ff7c6d11 | 1213 | // the expected output on a note is (* surround the highlighted text) |
32a655c1 SL |
1214 | // |
1215 | // = note: highlighted multiline | |
1216 | // string to | |
1217 | // see how it *looks* with | |
1218 | // very *weird* formats | |
1219 | // see? | |
1220 | for &(ref text, ref style) in msg.iter() { | |
1221 | let lines = text.split('\n').collect::<Vec<_>>(); | |
1222 | if lines.len() > 1 { | |
1223 | for (i, line) in lines.iter().enumerate() { | |
1224 | if i != 0 { | |
1225 | line_number += 1; | |
1226 | buffer.append(line_number, &padding, Style::NoStyle); | |
1227 | } | |
1228 | buffer.append(line_number, line, style_or_override(*style, override_style)); | |
1229 | } | |
1230 | } else { | |
1231 | buffer.append(line_number, text, style_or_override(*style, override_style)); | |
1232 | } | |
1233 | } | |
1234 | } | |
1235 | ||
9fa01778 XL |
1236 | fn emit_message_default( |
1237 | &mut self, | |
1238 | msp: &MultiSpan, | |
1239 | msg: &[(String, Style)], | |
1240 | code: &Option<DiagnosticId>, | |
1241 | level: &Level, | |
1242 | max_line_num_len: usize, | |
1243 | is_secondary: bool, | |
1244 | ) -> io::Result<()> { | |
5bcae85e SL |
1245 | let mut buffer = StyledBuffer::new(); |
1246 | ||
60c5eb7d XL |
1247 | if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary && !self.short_message |
1248 | { | |
5bcae85e SL |
1249 | // This is a secondary message with no span info |
1250 | for _ in 0..max_line_num_len { | |
1251 | buffer.prepend(0, " ", Style::NoStyle); | |
1252 | } | |
1253 | draw_note_separator(&mut buffer, 0, max_line_num_len + 1); | |
e1599b0c | 1254 | if *level != Level::FailureNote { |
1b1a35ee XL |
1255 | buffer.append(0, level.to_str(), Style::MainHeaderMsg); |
1256 | buffer.append(0, ": ", Style::NoStyle); | |
0531ce1d | 1257 | } |
32a655c1 | 1258 | self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None); |
c30ab7b3 | 1259 | } else { |
e1599b0c | 1260 | // The failure note level itself does not provide any useful diagnostic information |
1b1a35ee XL |
1261 | if *level != Level::FailureNote { |
1262 | buffer.append(0, level.to_str(), Style::Level(*level)); | |
0531ce1d | 1263 | } |
abe05a73 XL |
1264 | // only render error codes, not lint codes |
1265 | if let Some(DiagnosticId::Error(ref code)) = *code { | |
dfeec247 XL |
1266 | buffer.append(0, "[", Style::Level(*level)); |
1267 | buffer.append(0, &code, Style::Level(*level)); | |
1268 | buffer.append(0, "]", Style::Level(*level)); | |
5bcae85e | 1269 | } |
cdc7bbd5 | 1270 | let header_style = if is_secondary { Style::HeaderMsg } else { Style::MainHeaderMsg }; |
1b1a35ee | 1271 | if *level != Level::FailureNote { |
8faf50e0 | 1272 | buffer.append(0, ": ", header_style); |
0531ce1d | 1273 | } |
32a655c1 | 1274 | for &(ref text, _) in msg.iter() { |
cdc7bbd5 | 1275 | buffer.append(0, &replace_tabs(text), header_style); |
32a655c1 | 1276 | } |
5bcae85e SL |
1277 | } |
1278 | ||
dc9dc135 | 1279 | let mut annotated_files = FileWithAnnotatedLines::collect_annotations(msp, &self.sm); |
a7813a04 | 1280 | |
5bcae85e | 1281 | // Make sure our primary file comes first |
a1dfa0c6 | 1282 | let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) = |
60c5eb7d XL |
1283 | (self.sm.as_ref(), msp.primary_span().as_ref()) |
1284 | { | |
8faf50e0 | 1285 | if !primary_span.is_dummy() { |
a1dfa0c6 | 1286 | (sm.lookup_char_pos(primary_span.lo()), sm) |
5bcae85e | 1287 | } else { |
abe05a73 | 1288 | emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?; |
5bcae85e | 1289 | return Ok(()); |
c30ab7b3 SL |
1290 | } |
1291 | } else { | |
1292 | // If we don't have span information, emit and exit | |
abe05a73 | 1293 | emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?; |
c30ab7b3 SL |
1294 | return Ok(()); |
1295 | }; | |
5bcae85e | 1296 | if let Ok(pos) = |
60c5eb7d XL |
1297 | annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) |
1298 | { | |
5bcae85e SL |
1299 | annotated_files.swap(0, pos); |
1300 | } | |
1301 | ||
1302 | // Print out the annotate source lines that correspond with the error | |
1303 | for annotated_file in annotated_files { | |
7cac9316 | 1304 | // we can't annotate anything if the source is unavailable. |
a1dfa0c6 | 1305 | if !sm.ensure_source_file_source_present(annotated_file.file.clone()) { |
7cac9316 XL |
1306 | continue; |
1307 | } | |
1308 | ||
5bcae85e SL |
1309 | // print out the span location and spacer before we print the annotated source |
1310 | // to do this, we need to know if this span will be primary | |
1311 | let is_primary = primary_lo.file.name == annotated_file.file.name; | |
1312 | if is_primary { | |
5bcae85e | 1313 | let loc = primary_lo.clone(); |
abe05a73 XL |
1314 | if !self.short_message { |
1315 | // remember where we are in the output buffer for easy reference | |
1316 | let buffer_msg_line_offset = buffer.num_lines(); | |
1317 | ||
1318 | buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber); | |
e1599b0c XL |
1319 | buffer.append( |
1320 | buffer_msg_line_offset, | |
1321 | &format!( | |
1322 | "{}:{}:{}", | |
94222f64 | 1323 | sm.filename_for_diagnostics(&loc.file.name), |
e1599b0c XL |
1324 | sm.doctest_offset_line(&loc.file.name, loc.line), |
1325 | loc.col.0 + 1, | |
1326 | ), | |
1327 | Style::LineAndColumn, | |
1328 | ); | |
abe05a73 XL |
1329 | for _ in 0..max_line_num_len { |
1330 | buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle); | |
1331 | } | |
1332 | } else { | |
e1599b0c XL |
1333 | buffer.prepend( |
1334 | 0, | |
1335 | &format!( | |
1336 | "{}:{}:{}: ", | |
94222f64 | 1337 | sm.filename_for_diagnostics(&loc.file.name), |
e1599b0c XL |
1338 | sm.doctest_offset_line(&loc.file.name, loc.line), |
1339 | loc.col.0 + 1, | |
1340 | ), | |
1341 | Style::LineAndColumn, | |
1342 | ); | |
5bcae85e | 1343 | } |
abe05a73 | 1344 | } else if !self.short_message { |
5bcae85e SL |
1345 | // remember where we are in the output buffer for easy reference |
1346 | let buffer_msg_line_offset = buffer.num_lines(); | |
1347 | ||
1348 | // Add spacing line | |
94222f64 XL |
1349 | draw_col_separator_no_space( |
1350 | &mut buffer, | |
1351 | buffer_msg_line_offset, | |
1352 | max_line_num_len + 1, | |
1353 | ); | |
5bcae85e SL |
1354 | |
1355 | // Then, the secondary file indicator | |
1356 | buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber); | |
2c00a5a8 XL |
1357 | let loc = if let Some(first_line) = annotated_file.lines.first() { |
1358 | let col = if let Some(first_annotation) = first_line.annotations.first() { | |
1359 | format!(":{}", first_annotation.start_col + 1) | |
1360 | } else { | |
b7449926 | 1361 | String::new() |
2c00a5a8 | 1362 | }; |
60c5eb7d XL |
1363 | format!( |
1364 | "{}:{}{}", | |
94222f64 | 1365 | sm.filename_for_diagnostics(&annotated_file.file.name), |
60c5eb7d XL |
1366 | sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index), |
1367 | col | |
1368 | ) | |
2c00a5a8 | 1369 | } else { |
94222f64 | 1370 | format!("{}", sm.filename_for_diagnostics(&annotated_file.file.name)) |
2c00a5a8 | 1371 | }; |
60c5eb7d | 1372 | buffer.append(buffer_msg_line_offset + 1, &loc, Style::LineAndColumn); |
5bcae85e SL |
1373 | for _ in 0..max_line_num_len { |
1374 | buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle); | |
c1a9b12d | 1375 | } |
a7813a04 | 1376 | } |
c1a9b12d | 1377 | |
abe05a73 XL |
1378 | if !self.short_message { |
1379 | // Put in the spacer between the location and annotated source | |
1380 | let buffer_msg_line_offset = buffer.num_lines(); | |
60c5eb7d XL |
1381 | draw_col_separator_no_space( |
1382 | &mut buffer, | |
1383 | buffer_msg_line_offset, | |
1384 | max_line_num_len + 1, | |
1385 | ); | |
5bcae85e | 1386 | |
abe05a73 | 1387 | // Contains the vertical lines' positions for active multiline annotations |
b7449926 | 1388 | let mut multilines = FxHashMap::default(); |
cc61c64b | 1389 | |
e1599b0c | 1390 | // Get the left-side margin to remove it |
ba9703b0 | 1391 | let mut whitespace_margin = usize::MAX; |
e1599b0c XL |
1392 | for line_idx in 0..annotated_file.lines.len() { |
1393 | let file = annotated_file.file.clone(); | |
1394 | let line = &annotated_file.lines[line_idx]; | |
1395 | if let Some(source_string) = file.get_line(line.line_index - 1) { | |
5869c6ff XL |
1396 | let leading_whitespace = source_string |
1397 | .chars() | |
1398 | .take_while(|c| c.is_whitespace()) | |
1399 | .map(|c| { | |
1400 | match c { | |
1401 | // Tabs are displayed as 4 spaces | |
1402 | '\t' => 4, | |
1403 | _ => 1, | |
1404 | } | |
1405 | }) | |
1406 | .sum(); | |
e1599b0c | 1407 | if source_string.chars().any(|c| !c.is_whitespace()) { |
60c5eb7d | 1408 | whitespace_margin = min(whitespace_margin, leading_whitespace); |
e1599b0c XL |
1409 | } |
1410 | } | |
1411 | } | |
ba9703b0 | 1412 | if whitespace_margin == usize::MAX { |
e1599b0c XL |
1413 | whitespace_margin = 0; |
1414 | } | |
1415 | ||
1416 | // Left-most column any visible span points at. | |
ba9703b0 | 1417 | let mut span_left_margin = usize::MAX; |
e1599b0c XL |
1418 | for line in &annotated_file.lines { |
1419 | for ann in &line.annotations { | |
1420 | span_left_margin = min(span_left_margin, ann.start_col); | |
1421 | span_left_margin = min(span_left_margin, ann.end_col); | |
1422 | } | |
1423 | } | |
ba9703b0 | 1424 | if span_left_margin == usize::MAX { |
e1599b0c XL |
1425 | span_left_margin = 0; |
1426 | } | |
1427 | ||
1428 | // Right-most column any visible span points at. | |
1429 | let mut span_right_margin = 0; | |
1430 | let mut label_right_margin = 0; | |
1431 | let mut max_line_len = 0; | |
1432 | for line in &annotated_file.lines { | |
60c5eb7d XL |
1433 | max_line_len = max( |
1434 | max_line_len, | |
1435 | annotated_file.file.get_line(line.line_index - 1).map_or(0, |s| s.len()), | |
1436 | ); | |
e1599b0c XL |
1437 | for ann in &line.annotations { |
1438 | span_right_margin = max(span_right_margin, ann.start_col); | |
1439 | span_right_margin = max(span_right_margin, ann.end_col); | |
1440 | // FIXME: account for labels not in the same line | |
e74abb32 | 1441 | let label_right = ann.label.as_ref().map_or(0, |l| l.len() + 1); |
e1599b0c XL |
1442 | label_right_margin = max(label_right_margin, ann.end_col + label_right); |
1443 | } | |
1444 | } | |
1445 | ||
1446 | let width_offset = 3 + max_line_num_len; | |
1447 | let code_offset = if annotated_file.multiline_depth == 0 { | |
1448 | width_offset | |
1449 | } else { | |
1450 | width_offset + annotated_file.multiline_depth + 1 | |
1451 | }; | |
1452 | ||
1453 | let column_width = if let Some(width) = self.terminal_width { | |
1454 | width.saturating_sub(code_offset) | |
1455 | } else if self.ui_testing { | |
f035d41b | 1456 | DEFAULT_COLUMN_WIDTH |
e1599b0c | 1457 | } else { |
74b04a01 | 1458 | termize::dimensions() |
e1599b0c | 1459 | .map(|(w, _)| w.saturating_sub(code_offset)) |
f035d41b | 1460 | .unwrap_or(DEFAULT_COLUMN_WIDTH) |
e1599b0c XL |
1461 | }; |
1462 | ||
1463 | let margin = Margin::new( | |
1464 | whitespace_margin, | |
1465 | span_left_margin, | |
1466 | span_right_margin, | |
1467 | label_right_margin, | |
1468 | column_width, | |
1469 | max_line_len, | |
1470 | ); | |
1471 | ||
abe05a73 XL |
1472 | // Next, output the annotate source for this file |
1473 | for line_idx in 0..annotated_file.lines.len() { | |
1474 | let previous_buffer_line = buffer.num_lines(); | |
cc61c64b | 1475 | |
e1599b0c XL |
1476 | let depths = self.render_source_line( |
1477 | &mut buffer, | |
1478 | annotated_file.file.clone(), | |
1479 | &annotated_file.lines[line_idx], | |
1480 | width_offset, | |
1481 | code_offset, | |
1482 | margin, | |
1483 | ); | |
cc61c64b | 1484 | |
b7449926 | 1485 | let mut to_add = FxHashMap::default(); |
5bcae85e | 1486 | |
abe05a73 | 1487 | for (depth, style) in depths { |
cdc7bbd5 | 1488 | if multilines.remove(&depth).is_none() { |
abe05a73 XL |
1489 | to_add.insert(depth, style); |
1490 | } | |
cc61c64b | 1491 | } |
cc61c64b | 1492 | |
abe05a73 XL |
1493 | // Set the multiline annotation vertical lines to the left of |
1494 | // the code in this line. | |
1495 | for (depth, style) in &multilines { | |
1496 | for line in previous_buffer_line..buffer.num_lines() { | |
60c5eb7d | 1497 | draw_multiline_line(&mut buffer, line, width_offset, *depth, *style); |
cc61c64b | 1498 | } |
abe05a73 XL |
1499 | } |
1500 | // check to see if we need to print out or elide lines that come between | |
1501 | // this annotated line and the next one. | |
1502 | if line_idx < (annotated_file.lines.len() - 1) { | |
60c5eb7d XL |
1503 | let line_idx_delta = annotated_file.lines[line_idx + 1].line_index |
1504 | - annotated_file.lines[line_idx].line_index; | |
abe05a73 XL |
1505 | if line_idx_delta > 2 { |
1506 | let last_buffer_line_num = buffer.num_lines(); | |
1507 | buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber); | |
1508 | ||
1509 | // Set the multiline annotation vertical lines on `...` bridging line. | |
1510 | for (depth, style) in &multilines { | |
60c5eb7d XL |
1511 | draw_multiline_line( |
1512 | &mut buffer, | |
1513 | last_buffer_line_num, | |
1514 | width_offset, | |
1515 | *depth, | |
1516 | *style, | |
1517 | ); | |
abe05a73 XL |
1518 | } |
1519 | } else if line_idx_delta == 2 { | |
60c5eb7d XL |
1520 | let unannotated_line = annotated_file |
1521 | .file | |
abe05a73 XL |
1522 | .get_line(annotated_file.lines[line_idx].line_index) |
1523 | .unwrap_or_else(|| Cow::from("")); | |
1524 | ||
1525 | let last_buffer_line_num = buffer.num_lines(); | |
1526 | ||
e1599b0c XL |
1527 | self.draw_line( |
1528 | &mut buffer, | |
5869c6ff | 1529 | &replace_tabs(&unannotated_line), |
e1599b0c XL |
1530 | annotated_file.lines[line_idx + 1].line_index - 1, |
1531 | last_buffer_line_num, | |
1532 | width_offset, | |
1533 | code_offset, | |
1534 | margin, | |
1535 | ); | |
abe05a73 XL |
1536 | |
1537 | for (depth, style) in &multilines { | |
e1599b0c XL |
1538 | draw_multiline_line( |
1539 | &mut buffer, | |
1540 | last_buffer_line_num, | |
1541 | width_offset, | |
1542 | *depth, | |
1543 | *style, | |
1544 | ); | |
abe05a73 | 1545 | } |
cc61c64b | 1546 | } |
c1a9b12d | 1547 | } |
cc61c64b | 1548 | |
abe05a73 XL |
1549 | multilines.extend(&to_add); |
1550 | } | |
7453a54e SL |
1551 | } |
1552 | } | |
5bcae85e | 1553 | |
5bcae85e | 1554 | // final step: take our styled buffer, render it, then output it |
abe05a73 | 1555 | emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?; |
5bcae85e SL |
1556 | |
1557 | Ok(()) | |
1558 | } | |
ff7c6d11 | 1559 | |
9fa01778 XL |
1560 | fn emit_suggestion_default( |
1561 | &mut self, | |
1562 | suggestion: &CodeSuggestion, | |
1563 | level: &Level, | |
1564 | max_line_num_len: usize, | |
1565 | ) -> io::Result<()> { | |
e74abb32 XL |
1566 | let sm = match self.sm { |
1567 | Some(ref sm) => sm, | |
60c5eb7d | 1568 | None => return Ok(()), |
e74abb32 | 1569 | }; |
5bcae85e | 1570 | |
60c5eb7d XL |
1571 | // Render the replacements for each suggestion |
1572 | let suggestions = suggestion.splice_lines(&**sm); | |
ba9703b0 | 1573 | debug!("emit_suggestion_default: suggestions={:?}", suggestions); |
60c5eb7d XL |
1574 | |
1575 | if suggestions.is_empty() { | |
1576 | // Suggestions coming from macros can have malformed spans. This is a heavy handed | |
1577 | // approach to avoid ICEs by ignoring the suggestion outright. | |
1578 | return Ok(()); | |
1579 | } | |
1580 | ||
e74abb32 XL |
1581 | let mut buffer = StyledBuffer::new(); |
1582 | ||
1583 | // Render the suggestion message | |
1b1a35ee XL |
1584 | buffer.append(0, level.to_str(), Style::Level(*level)); |
1585 | buffer.append(0, ": ", Style::HeaderMsg); | |
1586 | ||
e74abb32 XL |
1587 | self.msg_to_buffer( |
1588 | &mut buffer, | |
1589 | &[(suggestion.msg.to_owned(), Style::NoStyle)], | |
1590 | max_line_num_len, | |
1591 | "suggestion", | |
1592 | Some(Style::HeaderMsg), | |
1593 | ); | |
1594 | ||
e74abb32 | 1595 | let mut row_num = 2; |
94222f64 | 1596 | draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1); |
e74abb32 | 1597 | let mut notice_capitalization = false; |
94222f64 XL |
1598 | for (complete, parts, highlights, only_capitalization) in |
1599 | suggestions.iter().take(MAX_SUGGESTIONS) | |
1600 | { | |
e74abb32 XL |
1601 | notice_capitalization |= only_capitalization; |
1602 | // Only show underline if the suggestion spans a single line and doesn't cover the | |
1603 | // entirety of the code output. If you have multiple replacements in the same line | |
1604 | // of code, show the underline. | |
60c5eb7d | 1605 | let show_underline = !(parts.len() == 1 && parts[0].snippet.trim() == complete.trim()) |
e74abb32 XL |
1606 | && complete.lines().count() == 1; |
1607 | ||
94222f64 XL |
1608 | let has_deletion = parts.iter().any(|p| p.is_deletion()); |
1609 | let is_multiline = complete.lines().count() > 1; | |
1610 | ||
1611 | let show_diff = has_deletion && !is_multiline; | |
1612 | ||
1613 | if show_diff { | |
1614 | row_num += 1; | |
1615 | } | |
1616 | ||
1617 | let file_lines = sm | |
60c5eb7d XL |
1618 | .span_to_lines(parts[0].span) |
1619 | .expect("span_to_lines failed when emitting suggestion"); | |
e74abb32 | 1620 | |
94222f64 | 1621 | assert!(!file_lines.lines.is_empty() || parts[0].span.is_dummy()); |
e74abb32 XL |
1622 | |
1623 | let line_start = sm.lookup_char_pos(parts[0].span.lo()).line; | |
1624 | draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1); | |
e74abb32 | 1625 | let mut lines = complete.lines(); |
94222f64 XL |
1626 | for (line_pos, (line, highlight_parts)) in |
1627 | lines.by_ref().zip(highlights).take(MAX_SUGGESTION_HIGHLIGHT_LINES).enumerate() | |
74b04a01 | 1628 | { |
e74abb32 | 1629 | // Print the span column to avoid confusion |
60c5eb7d XL |
1630 | buffer.puts( |
1631 | row_num, | |
1632 | 0, | |
1633 | &self.maybe_anonymized(line_start + line_pos), | |
1634 | Style::LineNumber, | |
1635 | ); | |
94222f64 XL |
1636 | if show_diff { |
1637 | // Add the line number for both addition and removal to drive the point home. | |
1638 | // | |
1639 | // N - fn foo<A: T>(bar: A) { | |
1640 | // N + fn foo(bar: impl T) { | |
1641 | buffer.puts( | |
1642 | row_num - 1, | |
1643 | 0, | |
1644 | &self.maybe_anonymized(line_start + line_pos), | |
1645 | Style::LineNumber, | |
1646 | ); | |
1647 | buffer.puts(row_num - 1, max_line_num_len + 1, "- ", Style::Removal); | |
1648 | buffer.puts( | |
1649 | row_num - 1, | |
1650 | max_line_num_len + 3, | |
1651 | &replace_tabs( | |
1652 | &*file_lines | |
1653 | .file | |
1654 | .get_line(file_lines.lines[line_pos].line_index) | |
1655 | .unwrap(), | |
1656 | ), | |
1657 | Style::NoStyle, | |
1658 | ); | |
1659 | buffer.puts(row_num, max_line_num_len + 1, "+ ", Style::Addition); | |
1660 | } else if is_multiline { | |
1661 | match &highlight_parts[..] { | |
1662 | [SubstitutionHighlight { start: 0, end }] if *end == line.len() => { | |
1663 | buffer.puts(row_num, max_line_num_len + 1, "+ ", Style::Addition); | |
1664 | } | |
1665 | [] => { | |
1666 | draw_col_separator(&mut buffer, row_num, max_line_num_len + 1); | |
1667 | } | |
1668 | _ => { | |
1669 | buffer.puts(row_num, max_line_num_len + 1, "~ ", Style::Addition); | |
1670 | } | |
1671 | } | |
1672 | } else { | |
1673 | draw_col_separator(&mut buffer, row_num, max_line_num_len + 1); | |
1674 | } | |
1675 | ||
e74abb32 | 1676 | // print the suggestion |
5869c6ff | 1677 | buffer.append(row_num, &replace_tabs(line), Style::NoStyle); |
94222f64 XL |
1678 | |
1679 | // Colorize addition/replacements with green. | |
1680 | for &SubstitutionHighlight { start, end } in highlight_parts { | |
1681 | // Account for tabs when highlighting (#87972). | |
1682 | let tabs: usize = line | |
1683 | .chars() | |
1684 | .take(start) | |
1685 | .map(|ch| match ch { | |
1686 | '\t' => 3, | |
1687 | _ => 0, | |
1688 | }) | |
1689 | .sum(); | |
1690 | buffer.set_style_range( | |
1691 | row_num, | |
1692 | max_line_num_len + 3 + start + tabs, | |
1693 | max_line_num_len + 3 + end + tabs, | |
1694 | Style::Addition, | |
1695 | true, | |
1696 | ); | |
1697 | } | |
e74abb32 | 1698 | row_num += 1; |
0531ce1d | 1699 | } |
94b46f34 | 1700 | |
e74abb32 XL |
1701 | // This offset and the ones below need to be signed to account for replacement code |
1702 | // that is shorter than the original code. | |
dfeec247 | 1703 | let mut offsets: Vec<(usize, isize)> = Vec::new(); |
e74abb32 XL |
1704 | // Only show an underline in the suggestions if the suggestion is not the |
1705 | // entirety of the code being shown and the displayed code is not multiline. | |
1706 | if show_underline { | |
1707 | draw_col_separator(&mut buffer, row_num, max_line_num_len + 1); | |
1708 | for part in parts { | |
1709 | let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display; | |
1710 | let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display; | |
1711 | ||
1712 | // Do not underline the leading... | |
60c5eb7d | 1713 | let start = part.snippet.len().saturating_sub(part.snippet.trim_start().len()); |
e74abb32 XL |
1714 | // ...or trailing spaces. Account for substitutions containing unicode |
1715 | // characters. | |
60c5eb7d XL |
1716 | let sub_len: usize = part |
1717 | .snippet | |
1718 | .trim() | |
1719 | .chars() | |
e74abb32 XL |
1720 | .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) |
1721 | .sum(); | |
1722 | ||
dfeec247 XL |
1723 | let offset: isize = offsets |
1724 | .iter() | |
1725 | .filter_map( | |
1726 | |(start, v)| if span_start_pos <= *start { None } else { Some(v) }, | |
1727 | ) | |
1728 | .sum(); | |
e74abb32 XL |
1729 | let underline_start = (span_start_pos + start) as isize + offset; |
1730 | let underline_end = (span_start_pos + start + sub_len) as isize + offset; | |
dfeec247 | 1731 | assert!(underline_start >= 0 && underline_end >= 0); |
94222f64 | 1732 | let padding: usize = max_line_num_len + 3; |
e74abb32 | 1733 | for p in underline_start..underline_end { |
94222f64 XL |
1734 | if !show_diff { |
1735 | // If this is a replacement, underline with `^`, if this is an addition | |
1736 | // underline with `+`. | |
60c5eb7d XL |
1737 | buffer.putc( |
1738 | row_num, | |
94222f64 XL |
1739 | (padding as isize + p) as usize, |
1740 | if part.is_addition(&sm) { '+' } else { '~' }, | |
1741 | Style::Addition, | |
60c5eb7d | 1742 | ); |
94b46f34 | 1743 | } |
041b39d2 | 1744 | } |
94222f64 XL |
1745 | if show_diff { |
1746 | // Colorize removal with red in diff format. | |
1747 | buffer.set_style_range( | |
1748 | row_num - 2, | |
1749 | (padding as isize + span_start_pos as isize) as usize, | |
1750 | (padding as isize + span_end_pos as isize) as usize, | |
1751 | Style::Removal, | |
1752 | true, | |
1753 | ); | |
1754 | } | |
5bcae85e | 1755 | |
e74abb32 | 1756 | // length of the code after substitution |
60c5eb7d XL |
1757 | let full_sub_len = part |
1758 | .snippet | |
1759 | .chars() | |
e74abb32 XL |
1760 | .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) |
1761 | .sum::<usize>() as isize; | |
1762 | ||
1763 | // length of the code to be substituted | |
1764 | let snippet_len = span_end_pos as isize - span_start_pos as isize; | |
1765 | // For multiple substitutions, use the position *after* the previous | |
dfeec247 XL |
1766 | // substitutions have happened, only when further substitutions are |
1767 | // located strictly after. | |
1768 | offsets.push((span_end_pos, full_sub_len - snippet_len)); | |
7cac9316 | 1769 | } |
e74abb32 | 1770 | row_num += 1; |
7cac9316 | 1771 | } |
e74abb32 XL |
1772 | |
1773 | // if we elided some lines, add an ellipsis | |
1774 | if lines.next().is_some() { | |
1775 | buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber); | |
1776 | } else if !show_underline { | |
1777 | draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1); | |
1778 | row_num += 1; | |
7453a54e | 1779 | } |
c1a9b12d | 1780 | } |
e74abb32 XL |
1781 | if suggestions.len() > MAX_SUGGESTIONS { |
1782 | let others = suggestions.len() - MAX_SUGGESTIONS; | |
60c5eb7d | 1783 | let msg = format!("and {} other candidate{}", others, pluralize!(others)); |
e74abb32 XL |
1784 | buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle); |
1785 | } else if notice_capitalization { | |
1786 | let msg = "notice the capitalization difference"; | |
1787 | buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle); | |
1788 | } | |
1789 | emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?; | |
7453a54e | 1790 | Ok(()) |
c1a9b12d | 1791 | } |
ff7c6d11 | 1792 | |
e74abb32 XL |
1793 | fn emit_messages_default( |
1794 | &mut self, | |
1795 | level: &Level, | |
1796 | message: &[(String, Style)], | |
1797 | code: &Option<DiagnosticId>, | |
1798 | span: &MultiSpan, | |
1799 | children: &[SubDiagnostic], | |
1800 | suggestions: &[CodeSuggestion], | |
1801 | ) { | |
0531ce1d XL |
1802 | let max_line_num_len = if self.ui_testing { |
1803 | ANONYMIZED_LINE_NUM.len() | |
1804 | } else { | |
6a06907d XL |
1805 | let n = self.get_max_line_num(span, children); |
1806 | num_decimal_digits(n) | |
0531ce1d | 1807 | }; |
5bcae85e | 1808 | |
e74abb32 | 1809 | match self.emit_message_default(span, message, code, level, max_line_num_len, false) { |
5bcae85e | 1810 | Ok(()) => { |
60c5eb7d XL |
1811 | if !children.is_empty() |
1812 | || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden) | |
1813 | { | |
5bcae85e | 1814 | let mut buffer = StyledBuffer::new(); |
abe05a73 XL |
1815 | if !self.short_message { |
1816 | draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1); | |
1817 | } | |
cdc7bbd5 | 1818 | if let Err(e) = emit_to_destination( |
60c5eb7d XL |
1819 | &buffer.render(), |
1820 | level, | |
1821 | &mut self.dst, | |
1822 | self.short_message, | |
1823 | ) { | |
cdc7bbd5 | 1824 | panic!("failed to emit error: {}", e) |
5bcae85e SL |
1825 | } |
1826 | } | |
abe05a73 XL |
1827 | if !self.short_message { |
1828 | for child in children { | |
1829 | let span = child.render_span.as_ref().unwrap_or(&child.span); | |
ba9703b0 | 1830 | if let Err(err) = self.emit_message_default( |
9fa01778 XL |
1831 | &span, |
1832 | &child.styled_message(), | |
1833 | &None, | |
1834 | &child.level, | |
1835 | max_line_num_len, | |
1836 | true, | |
1837 | ) { | |
ba9703b0 | 1838 | panic!("failed to emit error: {}", err); |
abe05a73 XL |
1839 | } |
1840 | } | |
1841 | for sugg in suggestions { | |
9fa01778 XL |
1842 | if sugg.style == SuggestionStyle::CompletelyHidden { |
1843 | // do not display this suggestion, it is meant only for tools | |
1844 | } else if sugg.style == SuggestionStyle::HideCodeAlways { | |
ba9703b0 | 1845 | if let Err(e) = self.emit_message_default( |
9fa01778 XL |
1846 | &MultiSpan::new(), |
1847 | &[(sugg.msg.to_owned(), Style::HeaderMsg)], | |
1848 | &None, | |
1849 | &Level::Help, | |
1850 | max_line_num_len, | |
1851 | true, | |
1852 | ) { | |
ba9703b0 | 1853 | panic!("failed to emit error: {}", e); |
9fa01778 | 1854 | } |
ba9703b0 XL |
1855 | } else if let Err(e) = |
1856 | self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len) | |
1857 | { | |
1858 | panic!("failed to emit error: {}", e); | |
1859 | }; | |
5bcae85e SL |
1860 | } |
1861 | } | |
1862 | } | |
c30ab7b3 | 1863 | Err(e) => panic!("failed to emit error: {}", e), |
5bcae85e | 1864 | } |
0531ce1d XL |
1865 | |
1866 | let mut dst = self.dst.writable(); | |
dc9dc135 | 1867 | match writeln!(dst) { |
5bcae85e | 1868 | Err(e) => panic!("failed to emit error: {}", e), |
ba9703b0 XL |
1869 | _ => { |
1870 | if let Err(e) = dst.flush() { | |
1871 | panic!("failed to emit error: {}", e) | |
1872 | } | |
1873 | } | |
c1a9b12d | 1874 | } |
c1a9b12d | 1875 | } |
1a4d82fc | 1876 | } |
970d7e83 | 1877 | |
dc9dc135 XL |
1878 | impl FileWithAnnotatedLines { |
1879 | /// Preprocess all the annotations so that they are grouped by file and by line number | |
1880 | /// This helps us quickly iterate over the whole message (including secondary file spans) | |
1881 | pub fn collect_annotations( | |
1882 | msp: &MultiSpan, | |
60c5eb7d | 1883 | source_map: &Option<Lrc<SourceMap>>, |
dc9dc135 | 1884 | ) -> Vec<FileWithAnnotatedLines> { |
60c5eb7d XL |
1885 | fn add_annotation_to_file( |
1886 | file_vec: &mut Vec<FileWithAnnotatedLines>, | |
1887 | file: Lrc<SourceFile>, | |
1888 | line_index: usize, | |
1889 | ann: Annotation, | |
1890 | ) { | |
dc9dc135 XL |
1891 | for slot in file_vec.iter_mut() { |
1892 | // Look through each of our files for the one we're adding to | |
1893 | if slot.file.name == file.name { | |
1894 | // See if we already have a line for it | |
1895 | for line_slot in &mut slot.lines { | |
1896 | if line_slot.line_index == line_index { | |
1897 | line_slot.annotations.push(ann); | |
1898 | return; | |
1899 | } | |
1900 | } | |
1901 | // We don't have a line yet, create one | |
60c5eb7d | 1902 | slot.lines.push(Line { line_index, annotations: vec![ann] }); |
dc9dc135 XL |
1903 | slot.lines.sort(); |
1904 | return; | |
1905 | } | |
1906 | } | |
1907 | // This is the first time we're seeing the file | |
1908 | file_vec.push(FileWithAnnotatedLines { | |
1909 | file, | |
60c5eb7d | 1910 | lines: vec![Line { line_index, annotations: vec![ann] }], |
dc9dc135 XL |
1911 | multiline_depth: 0, |
1912 | }); | |
1913 | } | |
1914 | ||
1915 | let mut output = vec![]; | |
1916 | let mut multiline_annotations = vec![]; | |
1917 | ||
1918 | if let Some(ref sm) = source_map { | |
1919 | for span_label in msp.span_labels() { | |
1920 | if span_label.span.is_dummy() { | |
1921 | continue; | |
1922 | } | |
1923 | ||
1924 | let lo = sm.lookup_char_pos(span_label.span.lo()); | |
1925 | let mut hi = sm.lookup_char_pos(span_label.span.hi()); | |
1926 | ||
1927 | // Watch out for "empty spans". If we get a span like 6..6, we | |
1928 | // want to just display a `^` at 6, so convert that to | |
1929 | // 6..7. This is degenerate input, but it's best to degrade | |
1930 | // gracefully -- and the parser likes to supply a span like | |
1931 | // that for EOF, in particular. | |
1932 | ||
1933 | if lo.col_display == hi.col_display && lo.line == hi.line { | |
1934 | hi.col_display += 1; | |
1935 | } | |
1936 | ||
e74abb32 | 1937 | if lo.line != hi.line { |
dc9dc135 XL |
1938 | let ml = MultilineAnnotation { |
1939 | depth: 1, | |
1940 | line_start: lo.line, | |
1941 | line_end: hi.line, | |
1942 | start_col: lo.col_display, | |
1943 | end_col: hi.col_display, | |
1944 | is_primary: span_label.is_primary, | |
e74abb32 | 1945 | label: span_label.label, |
dc9dc135 XL |
1946 | overlaps_exactly: false, |
1947 | }; | |
e74abb32 | 1948 | multiline_annotations.push((lo.file, ml)); |
dc9dc135 | 1949 | } else { |
e74abb32 XL |
1950 | let ann = Annotation { |
1951 | start_col: lo.col_display, | |
1952 | end_col: hi.col_display, | |
1953 | is_primary: span_label.is_primary, | |
1954 | label: span_label.label, | |
1955 | annotation_type: AnnotationType::Singleline, | |
1956 | }; | |
dc9dc135 | 1957 | add_annotation_to_file(&mut output, lo.file, lo.line, ann); |
e74abb32 | 1958 | }; |
dc9dc135 XL |
1959 | } |
1960 | } | |
1961 | ||
1962 | // Find overlapping multiline annotations, put them at different depths | |
1963 | multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end)); | |
e74abb32 XL |
1964 | for (_, ann) in multiline_annotations.clone() { |
1965 | for (_, a) in multiline_annotations.iter_mut() { | |
dc9dc135 XL |
1966 | // Move all other multiline annotations overlapping with this one |
1967 | // one level to the right. | |
60c5eb7d XL |
1968 | if !(ann.same_span(a)) |
1969 | && num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true) | |
dc9dc135 XL |
1970 | { |
1971 | a.increase_depth(); | |
1972 | } else if ann.same_span(a) && &ann != a { | |
1973 | a.overlaps_exactly = true; | |
1974 | } else { | |
1975 | break; | |
1976 | } | |
1977 | } | |
1978 | } | |
1979 | ||
60c5eb7d | 1980 | let mut max_depth = 0; // max overlapping multiline spans |
dc9dc135 | 1981 | for (file, ann) in multiline_annotations { |
e74abb32 | 1982 | max_depth = max(max_depth, ann.depth); |
dc9dc135 XL |
1983 | let mut end_ann = ann.as_end(); |
1984 | if !ann.overlaps_exactly { | |
1985 | // avoid output like | |
1986 | // | |
1987 | // | foo( | |
1988 | // | _____^ | |
1989 | // | |_____| | |
1990 | // | || bar, | |
1991 | // | || ); | |
1992 | // | || ^ | |
1993 | // | ||______| | |
1994 | // | |______foo | |
1995 | // | baz | |
1996 | // | |
1997 | // and instead get | |
1998 | // | |
1999 | // | foo( | |
2000 | // | _____^ | |
2001 | // | | bar, | |
2002 | // | | ); | |
2003 | // | | ^ | |
2004 | // | | | | |
2005 | // | |______foo | |
2006 | // | baz | |
2007 | add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start()); | |
2008 | // 4 is the minimum vertical length of a multiline span when presented: two lines | |
2009 | // of code and two lines of underline. This is not true for the special case where | |
2010 | // the beginning doesn't have an underline, but the current logic seems to be | |
2011 | // working correctly. | |
2012 | let middle = min(ann.line_start + 4, ann.line_end); | |
2013 | for line in ann.line_start + 1..middle { | |
2014 | // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`). | |
2015 | add_annotation_to_file(&mut output, file.clone(), line, ann.as_line()); | |
2016 | } | |
e74abb32 XL |
2017 | let line_end = ann.line_end - 1; |
2018 | if middle < line_end { | |
2019 | add_annotation_to_file(&mut output, file.clone(), line_end, ann.as_line()); | |
dc9dc135 XL |
2020 | } |
2021 | } else { | |
2022 | end_ann.annotation_type = AnnotationType::Singleline; | |
2023 | } | |
2024 | add_annotation_to_file(&mut output, file, ann.line_end, end_ann); | |
2025 | } | |
2026 | for file_vec in output.iter_mut() { | |
2027 | file_vec.multiline_depth = max_depth; | |
2028 | } | |
2029 | output | |
2030 | } | |
2031 | } | |
2032 | ||
6a06907d XL |
2033 | // instead of taking the String length or dividing by 10 while > 0, we multiply a limit by 10 until |
2034 | // we're higher. If the loop isn't exited by the `return`, the last multiplication will wrap, which | |
2035 | // is OK, because while we cannot fit a higher power of 10 in a usize, the loop will end anyway. | |
2036 | // This is also why we need the max number of decimal digits within a `usize`. | |
2037 | fn num_decimal_digits(num: usize) -> usize { | |
2038 | #[cfg(target_pointer_width = "64")] | |
2039 | const MAX_DIGITS: usize = 20; | |
2040 | ||
2041 | #[cfg(target_pointer_width = "32")] | |
2042 | const MAX_DIGITS: usize = 10; | |
2043 | ||
2044 | #[cfg(target_pointer_width = "16")] | |
2045 | const MAX_DIGITS: usize = 5; | |
2046 | ||
2047 | let mut lim = 10; | |
2048 | for num_digits in 1..MAX_DIGITS { | |
2049 | if num < lim { | |
2050 | return num_digits; | |
2051 | } | |
2052 | lim = lim.wrapping_mul(10); | |
2053 | } | |
2054 | MAX_DIGITS | |
2055 | } | |
2056 | ||
5869c6ff XL |
2057 | fn replace_tabs(str: &str) -> String { |
2058 | str.replace('\t', " ") | |
2059 | } | |
2060 | ||
5bcae85e SL |
2061 | fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) { |
2062 | buffer.puts(line, col, "| ", Style::LineNumber); | |
7453a54e SL |
2063 | } |
2064 | ||
5bcae85e | 2065 | fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) { |
476ff2be SL |
2066 | draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber); |
2067 | } | |
2068 | ||
60c5eb7d XL |
2069 | fn draw_col_separator_no_space_with_style( |
2070 | buffer: &mut StyledBuffer, | |
2071 | line: usize, | |
2072 | col: usize, | |
2073 | style: Style, | |
2074 | ) { | |
476ff2be SL |
2075 | buffer.putc(line, col, '|', style); |
2076 | } | |
2077 | ||
60c5eb7d XL |
2078 | fn draw_range( |
2079 | buffer: &mut StyledBuffer, | |
2080 | symbol: char, | |
2081 | line: usize, | |
2082 | col_from: usize, | |
2083 | col_to: usize, | |
2084 | style: Style, | |
2085 | ) { | |
476ff2be SL |
2086 | for col in col_from..col_to { |
2087 | buffer.putc(line, col, symbol, style); | |
2088 | } | |
5bcae85e SL |
2089 | } |
2090 | ||
2091 | fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) { | |
2092 | buffer.puts(line, col, "= ", Style::LineNumber); | |
2093 | } | |
2094 | ||
60c5eb7d XL |
2095 | fn draw_multiline_line( |
2096 | buffer: &mut StyledBuffer, | |
2097 | line: usize, | |
2098 | offset: usize, | |
2099 | depth: usize, | |
2100 | style: Style, | |
2101 | ) { | |
cc61c64b XL |
2102 | buffer.putc(line, offset + depth - 1, '|', style); |
2103 | } | |
2104 | ||
60c5eb7d XL |
2105 | fn num_overlap( |
2106 | a_start: usize, | |
2107 | a_end: usize, | |
2108 | b_start: usize, | |
2109 | b_end: usize, | |
2110 | inclusive: bool, | |
2111 | ) -> bool { | |
2112 | let extra = if inclusive { 1 } else { 0 }; | |
2113 | (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start) | |
476ff2be | 2114 | } |
8bb4bdeb XL |
2115 | fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool { |
2116 | num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false) | |
5bcae85e SL |
2117 | } |
2118 | ||
60c5eb7d XL |
2119 | fn emit_to_destination( |
2120 | rendered_buffer: &[Vec<StyledString>], | |
2121 | lvl: &Level, | |
2122 | dst: &mut Destination, | |
2123 | short_message: bool, | |
2124 | ) -> io::Result<()> { | |
9fa01778 | 2125 | use crate::lock; |
9e0c209e | 2126 | |
0531ce1d XL |
2127 | let mut dst = dst.writable(); |
2128 | ||
9e0c209e SL |
2129 | // In order to prevent error message interleaving, where multiple error lines get intermixed |
2130 | // when multiple compiler processes error simultaneously, we emit errors with additional | |
2131 | // steps. | |
2132 | // | |
2133 | // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When | |
2134 | // the .flush() is called we take the buffer created from the buffered writes and write it at | |
2135 | // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling | |
2136 | // scheme, this buffered approach works and maintains the styling. | |
2137 | // | |
2138 | // On Windows, styling happens through calls to a terminal API. This prevents us from using the | |
2139 | // same buffering approach. Instead, we use a global Windows mutex, which we acquire long | |
2140 | // enough to output the full error message, then we release. | |
2141 | let _buffer_lock = lock::acquire_global_lock("rustc_errors"); | |
0531ce1d | 2142 | for (pos, line) in rendered_buffer.iter().enumerate() { |
5bcae85e | 2143 | for part in line { |
ba9703b0 | 2144 | dst.apply_style(*lvl, part.style)?; |
5bcae85e | 2145 | write!(dst, "{}", part.text)?; |
0531ce1d | 2146 | dst.reset()?; |
a7813a04 | 2147 | } |
0531ce1d | 2148 | if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) { |
dc9dc135 | 2149 | writeln!(dst)?; |
abe05a73 | 2150 | } |
9cc50fc6 | 2151 | } |
9e0c209e | 2152 | dst.flush()?; |
9cc50fc6 SL |
2153 | Ok(()) |
2154 | } | |
2155 | ||
5bcae85e | 2156 | pub enum Destination { |
0531ce1d XL |
2157 | Terminal(StandardStream), |
2158 | Buffered(BufferWriter), | |
48663c56 XL |
2159 | // The bool denotes whether we should be emitting ansi color codes or not |
2160 | Raw(Box<(dyn Write + Send)>, bool), | |
9cc50fc6 SL |
2161 | } |
2162 | ||
0531ce1d XL |
2163 | pub enum WritableDst<'a> { |
2164 | Terminal(&'a mut StandardStream), | |
2165 | Buffered(&'a mut BufferWriter, Buffer), | |
48663c56 XL |
2166 | Raw(&'a mut (dyn Write + Send)), |
2167 | ColoredRaw(Ansi<&'a mut (dyn Write + Send)>), | |
9e0c209e SL |
2168 | } |
2169 | ||
9cc50fc6 | 2170 | impl Destination { |
0531ce1d XL |
2171 | fn from_stderr(color: ColorConfig) -> Destination { |
2172 | let choice = color.to_color_choice(); | |
2173 | // On Windows we'll be performing global synchronization on the entire | |
2174 | // system for emitting rustc errors, so there's no need to buffer | |
2175 | // anything. | |
2176 | // | |
2177 | // On non-Windows we rely on the atomicity of `write` to ensure errors | |
2178 | // don't get all jumbled up. | |
2179 | if cfg!(windows) { | |
2180 | Terminal(StandardStream::stderr(choice)) | |
2181 | } else { | |
2182 | Buffered(BufferWriter::stderr(choice)) | |
9e0c209e SL |
2183 | } |
2184 | } | |
2185 | ||
416331ca | 2186 | fn writable(&mut self) -> WritableDst<'_> { |
0531ce1d XL |
2187 | match *self { |
2188 | Destination::Terminal(ref mut t) => WritableDst::Terminal(t), | |
2189 | Destination::Buffered(ref mut t) => { | |
2190 | let buf = t.buffer(); | |
2191 | WritableDst::Buffered(t, buf) | |
2192 | } | |
48663c56 XL |
2193 | Destination::Raw(ref mut t, false) => WritableDst::Raw(t), |
2194 | Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)), | |
9cc50fc6 SL |
2195 | } |
2196 | } | |
fc512014 XL |
2197 | |
2198 | fn supports_color(&self) -> bool { | |
2199 | match *self { | |
2200 | Self::Terminal(ref stream) => stream.supports_color(), | |
2201 | Self::Buffered(ref buffer) => buffer.buffer().supports_color(), | |
2202 | Self::Raw(_, supports_color) => supports_color, | |
2203 | } | |
2204 | } | |
0531ce1d | 2205 | } |
9cc50fc6 | 2206 | |
0531ce1d | 2207 | impl<'a> WritableDst<'a> { |
c30ab7b3 | 2208 | fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> { |
0531ce1d | 2209 | let mut spec = ColorSpec::new(); |
a7813a04 | 2210 | match style { |
94222f64 XL |
2211 | Style::Addition => { |
2212 | spec.set_fg(Some(Color::Green)).set_intense(true); | |
2213 | } | |
2214 | Style::Removal => { | |
2215 | spec.set_fg(Some(Color::Red)).set_intense(true); | |
2216 | } | |
041b39d2 | 2217 | Style::LineAndColumn => {} |
a7813a04 | 2218 | Style::LineNumber => { |
0531ce1d XL |
2219 | spec.set_bold(true); |
2220 | spec.set_intense(true); | |
9e0c209e | 2221 | if cfg!(windows) { |
0531ce1d | 2222 | spec.set_fg(Some(Color::Cyan)); |
9e0c209e | 2223 | } else { |
0531ce1d | 2224 | spec.set_fg(Some(Color::Blue)); |
9e0c209e | 2225 | } |
a7813a04 | 2226 | } |
5bcae85e | 2227 | Style::Quotation => {} |
dc9dc135 | 2228 | Style::MainHeaderMsg => { |
0531ce1d | 2229 | spec.set_bold(true); |
9e0c209e | 2230 | if cfg!(windows) { |
60c5eb7d | 2231 | spec.set_intense(true).set_fg(Some(Color::White)); |
9e0c209e | 2232 | } |
a7813a04 XL |
2233 | } |
2234 | Style::UnderlinePrimary | Style::LabelPrimary => { | |
0531ce1d XL |
2235 | spec = lvl.color(); |
2236 | spec.set_bold(true); | |
a7813a04 | 2237 | } |
60c5eb7d XL |
2238 | Style::UnderlineSecondary | Style::LabelSecondary => { |
2239 | spec.set_bold(true).set_intense(true); | |
9e0c209e | 2240 | if cfg!(windows) { |
0531ce1d | 2241 | spec.set_fg(Some(Color::Cyan)); |
9e0c209e | 2242 | } else { |
0531ce1d | 2243 | spec.set_fg(Some(Color::Blue)); |
9e0c209e | 2244 | } |
a7813a04 | 2245 | } |
60c5eb7d | 2246 | Style::HeaderMsg | Style::NoStyle => {} |
0531ce1d XL |
2247 | Style::Level(lvl) => { |
2248 | spec = lvl.color(); | |
2249 | spec.set_bold(true); | |
2250 | } | |
2251 | Style::Highlight => { | |
2252 | spec.set_bold(true); | |
a7813a04 XL |
2253 | } |
2254 | } | |
0531ce1d | 2255 | self.set_color(&spec) |
a7813a04 XL |
2256 | } |
2257 | ||
0531ce1d | 2258 | fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> { |
a7813a04 | 2259 | match *self { |
0531ce1d XL |
2260 | WritableDst::Terminal(ref mut t) => t.set_color(color), |
2261 | WritableDst::Buffered(_, ref mut t) => t.set_color(color), | |
48663c56 | 2262 | WritableDst::ColoredRaw(ref mut t) => t.set_color(color), |
60c5eb7d | 2263 | WritableDst::Raw(_) => Ok(()), |
a7813a04 | 2264 | } |
a7813a04 XL |
2265 | } |
2266 | ||
0531ce1d | 2267 | fn reset(&mut self) -> io::Result<()> { |
a7813a04 | 2268 | match *self { |
0531ce1d XL |
2269 | WritableDst::Terminal(ref mut t) => t.reset(), |
2270 | WritableDst::Buffered(_, ref mut t) => t.reset(), | |
48663c56 | 2271 | WritableDst::ColoredRaw(ref mut t) => t.reset(), |
0531ce1d | 2272 | WritableDst::Raw(_) => Ok(()), |
a7813a04 | 2273 | } |
a7813a04 | 2274 | } |
9cc50fc6 SL |
2275 | } |
2276 | ||
0531ce1d | 2277 | impl<'a> Write for WritableDst<'a> { |
c34b1796 AL |
2278 | fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { |
2279 | match *self { | |
0531ce1d XL |
2280 | WritableDst::Terminal(ref mut t) => t.write(bytes), |
2281 | WritableDst::Buffered(_, ref mut buf) => buf.write(bytes), | |
2282 | WritableDst::Raw(ref mut w) => w.write(bytes), | |
48663c56 | 2283 | WritableDst::ColoredRaw(ref mut t) => t.write(bytes), |
c34b1796 AL |
2284 | } |
2285 | } | |
0531ce1d | 2286 | |
c34b1796 | 2287 | fn flush(&mut self) -> io::Result<()> { |
1a4d82fc | 2288 | match *self { |
0531ce1d XL |
2289 | WritableDst::Terminal(ref mut t) => t.flush(), |
2290 | WritableDst::Buffered(_, ref mut buf) => buf.flush(), | |
2291 | WritableDst::Raw(ref mut w) => w.flush(), | |
48663c56 | 2292 | WritableDst::ColoredRaw(ref mut w) => w.flush(), |
0531ce1d XL |
2293 | } |
2294 | } | |
2295 | } | |
2296 | ||
2297 | impl<'a> Drop for WritableDst<'a> { | |
2298 | fn drop(&mut self) { | |
ba9703b0 XL |
2299 | if let WritableDst::Buffered(ref mut dst, ref mut buf) = self { |
2300 | drop(dst.print(buf)); | |
1a4d82fc JJ |
2301 | } |
2302 | } | |
9e0c209e | 2303 | } |
e74abb32 XL |
2304 | |
2305 | /// Whether the original and suggested code are visually similar enough to warrant extra wording. | |
60c5eb7d | 2306 | pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool { |
e74abb32 | 2307 | // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode. |
60c5eb7d XL |
2308 | let found = match sm.span_to_snippet(sp) { |
2309 | Ok(snippet) => snippet, | |
2310 | Err(e) => { | |
2311 | warn!("Invalid span {:?}. Err={:?}", sp, e); | |
2312 | return false; | |
2313 | } | |
2314 | }; | |
e74abb32 XL |
2315 | let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z']; |
2316 | // All the chars that differ in capitalization are confusable (above): | |
cdc7bbd5 | 2317 | let confusable = iter::zip(found.chars(), suggested.chars()) |
60c5eb7d XL |
2318 | .filter(|(f, s)| f != s) |
2319 | .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s))); | |
e74abb32 XL |
2320 | confusable && found.to_lowercase() == suggested.to_lowercase() |
2321 | // FIXME: We sometimes suggest the same thing we already have, which is a | |
2322 | // bug, but be defensive against that here. | |
2323 | && found != suggested | |
2324 | } |