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