]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_errors/src/lib.rs
New upstream version 1.58.1+dfsg1
[rustc.git] / compiler / rustc_errors / src / lib.rs
CommitLineData
dc9dc135
XL
1//! Diagnostics creation and emission for `rustc`.
2//!
3//! This module contains the code for creating and emitting diagnostics.
4
1b1a35ee 5#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
dc9dc135 6#![feature(crate_visibility_modifier)]
1b1a35ee 7#![feature(backtrace)]
94222f64 8#![feature(if_let_guard)]
3c0e092e 9#![cfg_attr(bootstrap, feature(format_args_capture))]
cdc7bbd5 10#![feature(iter_zip)]
3c0e092e 11#![feature(let_else)]
0bf4aa26 12#![feature(nll)]
3dfed10e
XL
13
14#[macro_use]
15extern crate rustc_macros;
3157f602 16
c295e0f8
XL
17#[macro_use]
18extern crate tracing;
19
3157f602 20pub use emitter::ColorConfig;
9cc50fc6 21
9fa01778 22use Level::*;
9cc50fc6 23
60c5eb7d 24use emitter::{is_case_difference, Emitter, EmitterWriter};
48663c56 25use registry::Registry;
e74abb32 26use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
abe05a73 27use rustc_data_structures::stable_hasher::StableHasher;
60c5eb7d 28use rustc_data_structures::sync::{self, Lock, Lrc};
dfeec247 29use rustc_data_structures::AtomicRef;
29967ef6 30pub use rustc_lint_defs::{pluralize, Applicability};
6a06907d
XL
31use rustc_serialize::json::Json;
32use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
dfeec247
XL
33use rustc_span::source_map::SourceMap;
34use rustc_span::{Loc, MultiSpan, Span};
abe05a73 35
041b39d2 36use std::borrow::Cow;
6a06907d
XL
37use std::hash::{Hash, Hasher};
38use std::num::NonZeroUsize;
2c00a5a8 39use std::panic;
48663c56 40use std::path::Path;
60c5eb7d 41use std::{error, fmt};
9cc50fc6 42
60c5eb7d 43use termcolor::{Color, ColorSpec};
0531ce1d 44
60c5eb7d 45pub mod annotate_snippet_emitter_writer;
3b2f2976
XL
46mod diagnostic;
47mod diagnostic_builder;
9cc50fc6 48pub mod emitter;
60c5eb7d
XL
49pub mod json;
50mod lock;
3157f602 51pub mod registry;
60c5eb7d 52mod snippet;
041b39d2 53mod styled_buffer;
60c5eb7d
XL
54pub use snippet::Style;
55
56pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
3157f602 57
60c5eb7d
XL
58// `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
59// (See also the comment on `DiagnosticBuilderInner`.)
6a06907d 60#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
60c5eb7d 61rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
9cc50fc6 62
3dfed10e 63#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
9fa01778
XL
64pub enum SuggestionStyle {
65 /// Hide the suggested code when displaying this suggestion inline.
66 HideCodeInline,
67 /// Always hide the suggested code but display the message.
68 HideCodeAlways,
69 /// Do not display this suggestion in the cli output, it is only meant for tools.
70 CompletelyHidden,
71 /// Always show the suggested code.
72 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
73 /// empty.
74 ShowCode,
e74abb32
XL
75 /// Always show the suggested code independently.
76 ShowAlways,
9fa01778
XL
77}
78
79impl SuggestionStyle {
80 fn hide_inline(&self) -> bool {
29967ef6 81 !matches!(*self, SuggestionStyle::ShowCode)
9fa01778 82 }
83c7162d
XL
83}
84
6a06907d
XL
85#[derive(Clone, Debug, PartialEq, Default)]
86pub struct ToolMetadata(pub Option<Json>);
87
88impl ToolMetadata {
89 fn new(json: Json) -> Self {
90 ToolMetadata(Some(json))
91 }
92
93 fn is_set(&self) -> bool {
94 self.0.is_some()
95 }
96}
97
98impl Hash for ToolMetadata {
99 fn hash<H: Hasher>(&self, _state: &mut H) {}
100}
101
102// Doesn't really need to round-trip
103impl<D: Decoder> Decodable<D> for ToolMetadata {
104 fn decode(_d: &mut D) -> Result<Self, D::Error> {
105 Ok(ToolMetadata(None))
106 }
107}
108
109impl<S: Encoder> Encodable<S> for ToolMetadata {
110 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
111 match &self.0 {
112 None => e.emit_unit(),
113 Some(json) => json.encode(e),
114 }
115 }
116}
117
3dfed10e 118#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
7453a54e 119pub struct CodeSuggestion {
7cac9316
XL
120 /// Each substitute can have multiple variants due to multiple
121 /// applicable suggestions
122 ///
123 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
124 /// `foo` and `bar` on their own:
125 ///
126 /// ```
127 /// vec![
abe05a73
XL
128 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
129 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
7cac9316
XL
130 /// ]
131 /// ```
132 ///
133 /// or by replacing the entire span:
134 ///
135 /// ```
abe05a73
XL
136 /// vec![
137 /// Substitution { parts: vec![(0..7, "a.b")] },
138 /// Substitution { parts: vec![(0..7, "x.y")] },
139 /// ]
7cac9316 140 /// ```
abe05a73 141 pub substitutions: Vec<Substitution>,
7cac9316 142 pub msg: String,
9fa01778
XL
143 /// Visual representation of this suggestion.
144 pub style: SuggestionStyle,
2c00a5a8
XL
145 /// Whether or not the suggestion is approximate
146 ///
147 /// Sometimes we may show suggestions with placeholders,
148 /// which are useful for users but not useful for
149 /// tools like rustfix
83c7162d 150 pub applicability: Applicability,
6a06907d
XL
151 /// Tool-specific metadata
152 pub tool_metadata: ToolMetadata,
7cac9316
XL
153}
154
3dfed10e 155#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
7cac9316
XL
156/// See the docs on `CodeSuggestion::substitutions`
157pub struct Substitution {
abe05a73
XL
158 pub parts: Vec<SubstitutionPart>,
159}
160
3dfed10e 161#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
abe05a73 162pub struct SubstitutionPart {
7cac9316 163 pub span: Span,
abe05a73 164 pub snippet: String,
3157f602
XL
165}
166
94222f64
XL
167/// Used to translate between `Span`s and byte positions within a single output line in highlighted
168/// code of structured suggestions.
169#[derive(Debug, Clone, Copy)]
170pub struct SubstitutionHighlight {
171 start: usize,
172 end: usize,
173}
174
175impl SubstitutionPart {
176 pub fn is_addition(&self, sm: &SourceMap) -> bool {
177 !self.snippet.is_empty()
178 && sm
179 .span_to_snippet(self.span)
180 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
181 }
182
183 pub fn is_deletion(&self) -> bool {
184 self.snippet.trim().is_empty()
185 }
186
187 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
188 !self.snippet.is_empty()
189 && sm
190 .span_to_snippet(self.span)
191 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
192 }
193}
194
7453a54e 195impl CodeSuggestion {
e74abb32
XL
196 /// Returns the assembled code suggestions, whether they should be shown with an underline
197 /// and whether the substitution only differs in capitalization.
94222f64
XL
198 pub fn splice_lines(
199 &self,
200 sm: &SourceMap,
201 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
202 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
203 // corresponds to the output snippet's lines, while the second level corresponds to the
204 // substrings within that line that should be highlighted.
205
dfeec247 206 use rustc_span::{CharPos, Pos};
7453a54e 207
94222f64
XL
208 /// Append to a buffer the remainder of the line of existing source code, and return the
209 /// count of lines that have been added for accurate highlighting.
60c5eb7d
XL
210 fn push_trailing(
211 buf: &mut String,
212 line_opt: Option<&Cow<'_, str>>,
213 lo: &Loc,
214 hi_opt: Option<&Loc>,
94222f64
XL
215 ) -> usize {
216 let mut line_count = 0;
c30ab7b3 217 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
7453a54e 218 if let Some(line) = line_opt {
8bb4bdeb
XL
219 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
220 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
9fa01778 221 match hi_opt {
94222f64
XL
222 Some(hi) if hi > lo => {
223 line_count = line[lo..hi].matches('\n').count();
224 buf.push_str(&line[lo..hi])
225 }
9fa01778 226 Some(_) => (),
94222f64
XL
227 None => {
228 line_count = line[lo..].matches('\n').count();
229 buf.push_str(&line[lo..])
230 }
9fa01778 231 }
7453a54e 232 }
74b04a01 233 if hi_opt.is_none() {
7453a54e
SL
234 buf.push('\n');
235 }
236 }
94222f64 237 line_count
9cc50fc6 238 }
7453a54e 239
abe05a73
XL
240 assert!(!self.substitutions.is_empty());
241
60c5eb7d
XL
242 self.substitutions
243 .iter()
244 .filter(|subst| {
245 // Suggestions coming from macros can have malformed spans. This is a heavy
246 // handed approach to avoid ICEs by ignoring the suggestion outright.
74b04a01 247 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
60c5eb7d
XL
248 if invalid {
249 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
250 }
251 !invalid
252 })
253 .cloned()
dfeec247 254 .filter_map(|mut substitution| {
60c5eb7d
XL
255 // Assumption: all spans are in the same file, and all spans
256 // are disjoint. Sort in ascending order.
257 substitution.parts.sort_by_key(|part| part.span.lo());
258
259 // Find the bounding span.
dfeec247
XL
260 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
261 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
60c5eb7d 262 let bounding_span = Span::with_root_ctxt(lo, hi);
dfeec247 263 // The different spans might belong to different contexts, if so ignore suggestion.
74b04a01 264 let lines = sm.span_to_lines(bounding_span).ok()?;
ba9703b0
XL
265 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
266
267 // We can't splice anything if the source is unavailable.
268 if !sm.ensure_source_file_source_present(lines.file.clone()) {
269 return None;
270 }
60c5eb7d 271
94222f64 272 let mut highlights = vec![];
60c5eb7d
XL
273 // To build up the result, we do this for each span:
274 // - push the line segment trailing the previous span
275 // (at the beginning a "phantom" span pointing at the start of the line)
276 // - push lines between the previous and current span (if any)
277 // - if the previous and current span are not on the same line
278 // push the line segment leading up to the current span
279 // - splice in the span substitution
280 //
281 // Finally push the trailing line segment of the last span
74b04a01
XL
282 let sf = &lines.file;
283 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
60c5eb7d 284 prev_hi.col = CharPos::from_usize(0);
ba9703b0
XL
285 let mut prev_line =
286 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
60c5eb7d
XL
287 let mut buf = String::new();
288
94222f64
XL
289 let mut line_highlight = vec![];
290 // We need to keep track of the difference between the existing code and the added
291 // or deleted code in order to point at the correct column *after* substitution.
292 let mut acc = 0;
60c5eb7d 293 for part in &substitution.parts {
74b04a01 294 let cur_lo = sm.lookup_char_pos(part.span.lo());
60c5eb7d 295 if prev_hi.line == cur_lo.line {
94222f64
XL
296 let mut count =
297 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
298 while count > 0 {
299 highlights.push(std::mem::take(&mut line_highlight));
300 acc = 0;
301 count -= 1;
302 }
60c5eb7d 303 } else {
94222f64
XL
304 acc = 0;
305 highlights.push(std::mem::take(&mut line_highlight));
306 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
307 while count > 0 {
308 highlights.push(std::mem::take(&mut line_highlight));
309 count -= 1;
310 }
60c5eb7d
XL
311 // push lines between the previous and current span (if any)
312 for idx in prev_hi.line..(cur_lo.line - 1) {
74b04a01 313 if let Some(line) = sf.get_line(idx) {
60c5eb7d
XL
314 buf.push_str(line.as_ref());
315 buf.push('\n');
94222f64 316 highlights.push(std::mem::take(&mut line_highlight));
60c5eb7d
XL
317 }
318 }
74b04a01 319 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
ba9703b0
XL
320 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
321 Some((i, _)) => i,
322 None => cur_line.len(),
323 };
60c5eb7d 324 buf.push_str(&cur_line[..end]);
7cac9316
XL
325 }
326 }
94222f64
XL
327 // Add a whole line highlight per line in the snippet.
328 let len: isize = part
329 .snippet
330 .split('\n')
331 .next()
332 .unwrap_or(&part.snippet)
333 .chars()
334 .map(|c| match c {
335 '\t' => 4,
336 _ => 1,
337 })
338 .sum();
339 line_highlight.push(SubstitutionHighlight {
340 start: (cur_lo.col.0 as isize + acc) as usize,
341 end: (cur_lo.col.0 as isize + acc + len) as usize,
342 });
60c5eb7d 343 buf.push_str(&part.snippet);
94222f64 344 let cur_hi = sm.lookup_char_pos(part.span.hi());
c295e0f8 345 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
94222f64
XL
346 // Account for the difference between the width of the current code and the
347 // snippet being suggested, so that the *later* suggestions are correctly
348 // aligned on the screen.
349 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
350 }
351 prev_hi = cur_hi;
74b04a01 352 prev_line = sf.get_line(prev_hi.line - 1);
94222f64
XL
353 for line in part.snippet.split('\n').skip(1) {
354 acc = 0;
355 highlights.push(std::mem::take(&mut line_highlight));
356 let end: usize = line
357 .chars()
358 .map(|c| match c {
359 '\t' => 4,
360 _ => 1,
361 })
362 .sum();
363 line_highlight.push(SubstitutionHighlight { start: 0, end });
364 }
7453a54e 365 }
94222f64 366 highlights.push(std::mem::take(&mut line_highlight));
74b04a01 367 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
60c5eb7d
XL
368 // if the replacement already ends with a newline, don't print the next line
369 if !buf.ends_with('\n') {
370 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
371 }
372 // remove trailing newlines
373 while buf.ends_with('\n') {
374 buf.pop();
375 }
94222f64 376 Some((buf, substitution.parts, highlights, only_capitalization))
60c5eb7d
XL
377 })
378 .collect()
9cc50fc6
SL
379 }
380}
381
dfeec247 382pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
9cc50fc6
SL
383
384/// Signifies that the compiler died with an explicit call to `.bug`
385/// or `.span_bug` rather than a failed assertion, etc.
386#[derive(Copy, Clone, Debug)]
387pub struct ExplicitBug;
388
389impl fmt::Display for ExplicitBug {
9fa01778 390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9cc50fc6
SL
391 write!(f, "parser internal bug")
392 }
393}
394
dfeec247 395impl error::Error for ExplicitBug {}
9cc50fc6 396
60c5eb7d 397pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
c30ab7b3 398pub use diagnostic_builder::DiagnosticBuilder;
17df50a5 399use std::backtrace::Backtrace;
9cc50fc6 400
48663c56
XL
401/// A handler deals with errors and other compiler output.
402/// Certain errors (fatal, bug, unimpl) may cause immediate exit,
9cc50fc6
SL
403/// others log errors for later reporting.
404pub struct Handler {
e1599b0c
XL
405 flags: HandlerFlags,
406 inner: Lock<HandlerInner>,
407}
ff7c6d11 408
e74abb32
XL
409/// This inner struct exists to keep it all behind a single lock;
410/// this is done to prevent possible deadlocks in a multi-threaded compiler,
411/// as well as inconsistent state observation.
e1599b0c
XL
412struct HandlerInner {
413 flags: HandlerFlags,
3c0e092e
XL
414 /// The number of lint errors that have been emitted.
415 lint_err_count: usize,
dc9dc135
XL
416 /// The number of errors that have been emitted, including duplicates.
417 ///
418 /// This is not necessarily the count that's reported to the user once
419 /// compilation ends.
e1599b0c 420 err_count: usize,
1b1a35ee 421 warn_count: usize,
e1599b0c
XL
422 deduplicated_err_count: usize,
423 emitter: Box<dyn Emitter + sync::Send>,
e1599b0c 424 delayed_span_bugs: Vec<Diagnostic>,
17df50a5 425 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
abe05a73 426
48663c56
XL
427 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
428 /// emitting the same diagnostic with extended help (`--teach`) twice, which
cdc7bbd5 429 /// would be unnecessary repetition.
e1599b0c 430 taught_diagnostics: FxHashSet<DiagnosticId>,
83c7162d
XL
431
432 /// Used to suggest rustc --explain <error code>
e1599b0c 433 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
2c00a5a8 434
48663c56
XL
435 /// This set contains a hash of every diagnostic that has been emitted by
436 /// this handler. These hashes is used to avoid emitting the same error
437 /// twice.
e1599b0c 438 emitted_diagnostics: FxHashSet<u128>,
e74abb32
XL
439
440 /// Stashed diagnostics emitted in one stage of the compiler that may be
441 /// stolen by other stages (e.g. to improve them and add more information).
442 /// The stashed diagnostics count towards the total error count.
443 /// When `.abort_if_errors()` is called, these are also emitted.
444 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
ba9703b0
XL
445
446 /// The warning count, used for a recap upon finishing
447 deduplicated_warn_count: usize,
29967ef6
XL
448
449 future_breakage_diagnostics: Vec<Diagnostic>,
94222f64
XL
450
451 /// If set to `true`, no warning or error will be emitted.
452 quiet: bool,
e74abb32
XL
453}
454
455/// A key denoting where from a diagnostic was stashed.
456#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
457pub enum StashKey {
458 ItemNoType,
9cc50fc6
SL
459}
460
83c7162d
XL
461fn default_track_diagnostic(_: &Diagnostic) {}
462
dfeec247
XL
463pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
464 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
83c7162d 465
e1599b0c 466#[derive(Copy, Clone, Default)]
ff7c6d11 467pub struct HandlerFlags {
0bf4aa26
XL
468 /// If false, warning-level lints are suppressed.
469 /// (rustc: see `--allow warnings` and `--cap-lints`)
ff7c6d11 470 pub can_emit_warnings: bool,
0bf4aa26
XL
471 /// If true, error-level diagnostics are upgraded to bug-level.
472 /// (rustc: see `-Z treat-err-as-bug`)
6a06907d 473 pub treat_err_as_bug: Option<NonZeroUsize>,
0bf4aa26
XL
474 /// If true, immediately emit diagnostics that would otherwise be buffered.
475 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
476 pub dont_buffer_diagnostics: bool,
477 /// If true, immediately print bugs registered with `delay_span_bug`.
478 /// (rustc: see `-Z report-delayed-bugs`)
8faf50e0 479 pub report_delayed_bugs: bool,
74b04a01
XL
480 /// Show macro backtraces.
481 /// (rustc: see `-Z macro-backtrace`)
482 pub macro_backtrace: bool,
dfeec247
XL
483 /// If true, identical diagnostics are reported only once.
484 pub deduplicate_diagnostics: bool,
ff7c6d11
XL
485}
486
e1599b0c 487impl Drop for HandlerInner {
8faf50e0 488 fn drop(&mut self) {
e74abb32
XL
489 self.emit_stashed_diagnostics();
490
491 if !self.has_errors() {
e1599b0c 492 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
1b1a35ee
XL
493 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
494 }
495
496 if !self.has_any_message() {
497 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
498 self.flush_delayed(
17df50a5 499 bugs.into_iter().map(DelayedDiagnostic::decorate).collect(),
1b1a35ee
XL
500 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
501 );
8faf50e0
XL
502 }
503 }
504}
505
9cc50fc6 506impl Handler {
e74abb32
XL
507 pub fn with_tty_emitter(
508 color_config: ColorConfig,
509 can_emit_warnings: bool,
6a06907d 510 treat_err_as_bug: Option<NonZeroUsize>,
74b04a01 511 sm: Option<Lrc<SourceMap>>,
e74abb32
XL
512 ) -> Self {
513 Self::with_tty_emitter_and_flags(
ff7c6d11 514 color_config,
74b04a01 515 sm,
60c5eb7d 516 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
e74abb32 517 )
ff7c6d11
XL
518 }
519
e74abb32
XL
520 pub fn with_tty_emitter_and_flags(
521 color_config: ColorConfig,
74b04a01 522 sm: Option<Lrc<SourceMap>>,
e74abb32
XL
523 flags: HandlerFlags,
524 ) -> Self {
e1599b0c 525 let emitter = Box::new(EmitterWriter::stderr(
e74abb32 526 color_config,
74b04a01 527 sm,
e74abb32
XL
528 false,
529 false,
530 None,
74b04a01 531 flags.macro_backtrace,
e74abb32
XL
532 ));
533 Self::with_emitter_and_flags(emitter, flags)
534 }
535
536 pub fn with_emitter(
537 can_emit_warnings: bool,
6a06907d 538 treat_err_as_bug: Option<NonZeroUsize>,
e74abb32
XL
539 emitter: Box<dyn Emitter + sync::Send>,
540 ) -> Self {
ff7c6d11 541 Handler::with_emitter_and_flags(
e74abb32 542 emitter,
60c5eb7d 543 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
e74abb32 544 )
ff7c6d11
XL
545 }
546
e74abb32
XL
547 pub fn with_emitter_and_flags(
548 emitter: Box<dyn Emitter + sync::Send>,
60c5eb7d 549 flags: HandlerFlags,
e74abb32
XL
550 ) -> Self {
551 Self {
ff7c6d11 552 flags,
e1599b0c
XL
553 inner: Lock::new(HandlerInner {
554 flags,
3c0e092e 555 lint_err_count: 0,
e1599b0c 556 err_count: 0,
1b1a35ee 557 warn_count: 0,
e1599b0c 558 deduplicated_err_count: 0,
ba9703b0 559 deduplicated_warn_count: 0,
e74abb32 560 emitter,
e1599b0c 561 delayed_span_bugs: Vec::new(),
1b1a35ee 562 delayed_good_path_bugs: Vec::new(),
e1599b0c
XL
563 taught_diagnostics: Default::default(),
564 emitted_diagnostic_codes: Default::default(),
565 emitted_diagnostics: Default::default(),
e74abb32 566 stashed_diagnostics: Default::default(),
29967ef6 567 future_breakage_diagnostics: Vec::new(),
94222f64 568 quiet: false,
e1599b0c 569 }),
9cc50fc6
SL
570 }
571 }
572
94222f64
XL
573 pub fn with_disabled_diagnostic<T, F: FnOnce() -> T>(&self, f: F) -> T {
574 let prev = self.inner.borrow_mut().quiet;
575 self.inner.borrow_mut().quiet = true;
576 let ret = f();
577 self.inner.borrow_mut().quiet = prev;
578 ret
579 }
580
e1599b0c 581 // This is here to not allow mutation of flags;
ba9703b0 582 // as of this writing it's only used in tests in librustc_middle.
e1599b0c
XL
583 pub fn can_emit_warnings(&self) -> bool {
584 self.flags.can_emit_warnings
7453a54e
SL
585 }
586
2c00a5a8
XL
587 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
588 ///
9fa01778 589 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
2c00a5a8
XL
590 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
591 /// the overall count of emitted error diagnostics.
ea8adc8c 592 pub fn reset_err_count(&self) {
e1599b0c 593 let mut inner = self.inner.borrow_mut();
e1599b0c 594 inner.err_count = 0;
1b1a35ee 595 inner.warn_count = 0;
e74abb32 596 inner.deduplicated_err_count = 0;
ba9703b0 597 inner.deduplicated_warn_count = 0;
e74abb32
XL
598
599 // actually free the underlying memory (which `clear` would not do)
600 inner.delayed_span_bugs = Default::default();
1b1a35ee 601 inner.delayed_good_path_bugs = Default::default();
e74abb32
XL
602 inner.taught_diagnostics = Default::default();
603 inner.emitted_diagnostic_codes = Default::default();
604 inner.emitted_diagnostics = Default::default();
605 inner.stashed_diagnostics = Default::default();
606 }
607
608 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
e74abb32
XL
609 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
610 let mut inner = self.inner.borrow_mut();
dfeec247
XL
611 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
612 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
613 // See the PR for a discussion.
614 inner.stashed_diagnostics.insert((span, key), diag);
e74abb32
XL
615 }
616
617 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
618 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
619 self.inner
620 .borrow_mut()
621 .stashed_diagnostics
622 .remove(&(span, key))
623 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
ea8adc8c
XL
624 }
625
e74abb32
XL
626 /// Emit all stashed diagnostics.
627 pub fn emit_stashed_diagnostics(&self) {
628 self.inner.borrow_mut().emit_stashed_diagnostics();
629 }
630
631 /// Construct a dummy builder with `Level::Cancelled`.
632 ///
633 /// Using this will neither report anything to the user (e.g. a warning),
634 /// nor will compilation cancel as a result.
416331ca 635 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
a7813a04 636 DiagnosticBuilder::new(self, Level::Cancelled, "")
9cc50fc6
SL
637 }
638
e74abb32 639 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
136023e0
XL
640 ///
641 /// The builder will be canceled if warnings cannot be emitted.
e74abb32
XL
642 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
643 let mut result = self.struct_warn(msg);
644 result.set_span(span);
9cc50fc6
SL
645 result
646 }
e74abb32 647
136023e0
XL
648 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
649 ///
650 /// This will "force" the warning meaning it will not be canceled even
651 /// if warnings cannot be emitted.
652 pub fn struct_span_force_warn(
653 &self,
654 span: impl Into<MultiSpan>,
655 msg: &str,
656 ) -> DiagnosticBuilder<'_> {
657 let mut result = self.struct_force_warn(msg);
658 result.set_span(span);
659 result
660 }
661
29967ef6
XL
662 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
663 pub fn struct_span_allow(
664 &self,
665 span: impl Into<MultiSpan>,
666 msg: &str,
667 ) -> DiagnosticBuilder<'_> {
668 let mut result = self.struct_allow(msg);
669 result.set_span(span);
670 result
671 }
672
e74abb32
XL
673 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
674 /// Also include a code.
675 pub fn struct_span_warn_with_code(
676 &self,
677 span: impl Into<MultiSpan>,
678 msg: &str,
679 code: DiagnosticId,
680 ) -> DiagnosticBuilder<'_> {
681 let mut result = self.struct_span_warn(span, msg);
abe05a73 682 result.code(code);
9cc50fc6
SL
683 result
684 }
e74abb32
XL
685
686 /// Construct a builder at the `Warning` level with the `msg`.
136023e0
XL
687 ///
688 /// The builder will be canceled if warnings cannot be emitted.
416331ca 689 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
a7813a04 690 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
ff7c6d11 691 if !self.flags.can_emit_warnings {
9cc50fc6
SL
692 result.cancel();
693 }
694 result
695 }
e74abb32 696
136023e0
XL
697 /// Construct a builder at the `Warning` level with the `msg`.
698 ///
699 /// This will "force" a warning meaning it will not be canceled even
700 /// if warnings cannot be emitted.
701 pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
702 DiagnosticBuilder::new(self, Level::Warning, msg)
703 }
704
29967ef6
XL
705 /// Construct a builder at the `Allow` level with the `msg`.
706 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
707 DiagnosticBuilder::new(self, Level::Allow, msg)
708 }
709
e74abb32
XL
710 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
711 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
712 let mut result = self.struct_err(msg);
713 result.set_span(span);
9cc50fc6
SL
714 result
715 }
e74abb32
XL
716
717 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
718 pub fn struct_span_err_with_code(
719 &self,
720 span: impl Into<MultiSpan>,
721 msg: &str,
722 code: DiagnosticId,
723 ) -> DiagnosticBuilder<'_> {
724 let mut result = self.struct_span_err(span, msg);
abe05a73 725 result.code(code);
9cc50fc6
SL
726 result
727 }
e74abb32
XL
728
729 /// Construct a builder at the `Error` level with the `msg`.
7cac9316 730 // FIXME: This method should be removed (every error should have an associated error code).
416331ca 731 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
3c0e092e
XL
732 DiagnosticBuilder::new(self, Level::Error { lint: false }, msg)
733 }
734
735 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
736 #[doc(hidden)]
737 pub fn struct_err_lint(&self, msg: &str) -> DiagnosticBuilder<'_> {
738 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
9cc50fc6 739 }
e74abb32
XL
740
741 /// Construct a builder at the `Error` level with the `msg` and the `code`.
742 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
743 let mut result = self.struct_err(msg);
abe05a73 744 result.code(code);
7cac9316
XL
745 result
746 }
e74abb32
XL
747
748 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
749 pub fn struct_span_fatal(
750 &self,
751 span: impl Into<MultiSpan>,
752 msg: &str,
753 ) -> DiagnosticBuilder<'_> {
754 let mut result = self.struct_fatal(msg);
755 result.set_span(span);
9cc50fc6
SL
756 result
757 }
e74abb32
XL
758
759 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
760 pub fn struct_span_fatal_with_code(
761 &self,
762 span: impl Into<MultiSpan>,
763 msg: &str,
764 code: DiagnosticId,
765 ) -> DiagnosticBuilder<'_> {
766 let mut result = self.struct_span_fatal(span, msg);
abe05a73 767 result.code(code);
9cc50fc6
SL
768 result
769 }
e74abb32
XL
770
771 /// Construct a builder at the `Error` level with the `msg`.
416331ca 772 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
a7813a04 773 DiagnosticBuilder::new(self, Level::Fatal, msg)
9cc50fc6
SL
774 }
775
60c5eb7d
XL
776 /// Construct a builder at the `Help` level with the `msg`.
777 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
778 DiagnosticBuilder::new(self, Level::Help, msg)
779 }
780
f035d41b
XL
781 /// Construct a builder at the `Note` level with the `msg`.
782 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
783 DiagnosticBuilder::new(self, Level::Note, msg)
784 }
785
17df50a5 786 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
e74abb32 787 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
17df50a5 788 FatalError.raise()
9cc50fc6 789 }
e74abb32
XL
790
791 pub fn span_fatal_with_code(
792 &self,
793 span: impl Into<MultiSpan>,
794 msg: &str,
795 code: DiagnosticId,
17df50a5 796 ) -> ! {
e74abb32 797 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
17df50a5 798 FatalError.raise()
9cc50fc6 799 }
e74abb32
XL
800
801 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
3c0e092e 802 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span);
9e0c209e 803 }
e74abb32
XL
804
805 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
3c0e092e
XL
806 self.emit_diag_at_span(
807 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
808 span,
809 );
9cc50fc6 810 }
e74abb32
XL
811
812 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
813 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
9cc50fc6 814 }
e74abb32
XL
815
816 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
817 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
9cc50fc6 818 }
e74abb32
XL
819
820 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
821 self.inner.borrow_mut().span_bug(span, msg)
9cc50fc6 822 }
e74abb32 823
f035d41b 824 #[track_caller]
e74abb32
XL
825 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
826 self.inner.borrow_mut().delay_span_bug(span, msg)
9cc50fc6 827 }
e74abb32 828
1b1a35ee
XL
829 pub fn delay_good_path_bug(&self, msg: &str) {
830 self.inner.borrow_mut().delay_good_path_bug(msg)
831 }
832
e74abb32
XL
833 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
834 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
9cc50fc6 835 }
e74abb32
XL
836
837 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
838 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
9cc50fc6 839 }
e74abb32
XL
840
841 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
7cac9316 842 let mut db = DiagnosticBuilder::new(self, Note, msg);
e74abb32 843 db.set_span(span);
7cac9316
XL
844 db
845 }
e74abb32 846
17df50a5 847 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
9cc50fc6 848 pub fn fatal(&self, msg: &str) -> FatalError {
e1599b0c 849 self.inner.borrow_mut().fatal(msg)
9cc50fc6 850 }
e74abb32 851
9cc50fc6 852 pub fn err(&self, msg: &str) {
e1599b0c 853 self.inner.borrow_mut().err(msg);
9cc50fc6 854 }
e74abb32 855
9cc50fc6 856 pub fn warn(&self, msg: &str) {
c30ab7b3 857 let mut db = DiagnosticBuilder::new(self, Warning, msg);
5bcae85e 858 db.emit();
9cc50fc6 859 }
e74abb32 860
9cc50fc6 861 pub fn note_without_error(&self, msg: &str) {
e74abb32 862 DiagnosticBuilder::new(self, Note, msg).emit();
9cc50fc6 863 }
e74abb32 864
9cc50fc6 865 pub fn bug(&self, msg: &str) -> ! {
e1599b0c 866 self.inner.borrow_mut().bug(msg)
9cc50fc6
SL
867 }
868
17df50a5 869 #[inline]
9cc50fc6 870 pub fn err_count(&self) -> usize {
e74abb32 871 self.inner.borrow().err_count()
9cc50fc6
SL
872 }
873
874 pub fn has_errors(&self) -> bool {
e74abb32
XL
875 self.inner.borrow().has_errors()
876 }
3c0e092e
XL
877 pub fn has_errors_or_lint_errors(&self) -> bool {
878 self.inner.borrow().has_errors_or_lint_errors()
879 }
e74abb32
XL
880 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
881 self.inner.borrow().has_errors_or_delayed_span_bugs()
9cc50fc6 882 }
0531ce1d 883
48663c56 884 pub fn print_error_count(&self, registry: &Registry) {
e1599b0c
XL
885 self.inner.borrow_mut().print_error_count(registry)
886 }
887
29967ef6
XL
888 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
889 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
890 }
891
e1599b0c 892 pub fn abort_if_errors(&self) {
e74abb32 893 self.inner.borrow_mut().abort_if_errors()
e1599b0c
XL
894 }
895
e74abb32
XL
896 /// `true` if we haven't taught a diagnostic with this code already.
897 /// The caller must then teach the user about such a diagnostic.
898 ///
899 /// Used to suppress emitting the same error multiple times with extended explanation when
900 /// calling `-Zteach`.
e1599b0c
XL
901 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
902 self.inner.borrow_mut().must_teach(code)
903 }
904
905 pub fn force_print_diagnostic(&self, db: Diagnostic) {
906 self.inner.borrow_mut().force_print_diagnostic(db)
907 }
908
909 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
910 self.inner.borrow_mut().emit_diagnostic(diagnostic)
911 }
912
e74abb32
XL
913 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
914 let mut inner = self.inner.borrow_mut();
915 inner.emit_diagnostic(diag.set_span(sp));
e74abb32
XL
916 }
917
e1599b0c
XL
918 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
919 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
920 }
921
136023e0 922 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
29967ef6
XL
923 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
924 }
925
cdc7bbd5
XL
926 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
927 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
928 }
929
e1599b0c
XL
930 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
931 self.inner.borrow_mut().delay_as_bug(diagnostic)
932 }
933}
934
935impl HandlerInner {
e1599b0c
XL
936 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
937 self.taught_diagnostics.insert(code.clone())
938 }
939
940 fn force_print_diagnostic(&mut self, db: Diagnostic) {
941 self.emitter.emit_diagnostic(&db);
942 }
943
e74abb32
XL
944 /// Emit all stashed diagnostics.
945 fn emit_stashed_diagnostics(&mut self) {
946 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
947 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
948 }
949
e1599b0c 950 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
94222f64 951 if diagnostic.cancelled() || self.quiet {
e1599b0c
XL
952 return;
953 }
954
29967ef6
XL
955 if diagnostic.has_future_breakage() {
956 self.future_breakage_diagnostics.push(diagnostic.clone());
957 }
958
136023e0
XL
959 if diagnostic.level == Warning
960 && !self.flags.can_emit_warnings
961 && !diagnostic.is_force_warn()
962 {
29967ef6
XL
963 if diagnostic.has_future_breakage() {
964 (*TRACK_DIAGNOSTICS)(diagnostic);
965 }
e1599b0c
XL
966 return;
967 }
968
dfeec247 969 (*TRACK_DIAGNOSTICS)(diagnostic);
e1599b0c 970
29967ef6
XL
971 if diagnostic.level == Allow {
972 return;
973 }
974
e1599b0c
XL
975 if let Some(ref code) = diagnostic.code {
976 self.emitted_diagnostic_codes.insert(code.clone());
977 }
978
dfeec247 979 let already_emitted = |this: &mut Self| {
e1599b0c
XL
980 let mut hasher = StableHasher::new();
981 diagnostic.hash(&mut hasher);
dfeec247
XL
982 let diagnostic_hash = hasher.finish();
983 !this.emitted_diagnostics.insert(diagnostic_hash)
e1599b0c
XL
984 };
985
dfeec247
XL
986 // Only emit the diagnostic if we've been asked to deduplicate and
987 // haven't already emitted an equivalent diagnostic.
988 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
e1599b0c
XL
989 self.emitter.emit_diagnostic(diagnostic);
990 if diagnostic.is_error() {
991 self.deduplicated_err_count += 1;
ba9703b0
XL
992 } else if diagnostic.level == Warning {
993 self.deduplicated_warn_count += 1;
e1599b0c
XL
994 }
995 }
996 if diagnostic.is_error() {
3c0e092e
XL
997 if matches!(diagnostic.level, Level::Error { lint: true }) {
998 self.bump_lint_err_count();
999 } else {
1000 self.bump_err_count();
1001 }
1b1a35ee
XL
1002 } else {
1003 self.bump_warn_count();
e1599b0c
XL
1004 }
1005 }
1006
1007 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1008 self.emitter.emit_artifact_notification(path, artifact_type);
cdc7bbd5
XL
1009 }
1010
1011 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
1012 self.emitter.emit_unused_externs(lint_level, unused_externs);
e1599b0c
XL
1013 }
1014
1015 fn treat_err_as_bug(&self) -> bool {
6a06907d 1016 self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c.get())
e1599b0c
XL
1017 }
1018
1019 fn print_error_count(&mut self, registry: &Registry) {
e74abb32
XL
1020 self.emit_stashed_diagnostics();
1021
ba9703b0
XL
1022 let warnings = match self.deduplicated_warn_count {
1023 0 => String::new(),
1024 1 => "1 warning emitted".to_string(),
1025 count => format!("{} warnings emitted", count),
1026 };
1027 let errors = match self.deduplicated_err_count {
1028 0 => String::new(),
0531ce1d 1029 1 => "aborting due to previous error".to_string(),
60c5eb7d 1030 count => format!("aborting due to {} previous errors", count),
0531ce1d 1031 };
532ac7d7
XL
1032 if self.treat_err_as_bug() {
1033 return;
1034 }
0531ce1d 1035
ba9703b0
XL
1036 match (errors.len(), warnings.len()) {
1037 (0, 0) => return,
136023e0 1038 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
ba9703b0
XL
1039 (_, 0) => {
1040 let _ = self.fatal(&errors);
1041 }
1042 (_, _) => {
1043 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1044 }
1045 }
0531ce1d 1046
e1599b0c
XL
1047 let can_show_explain = self.emitter.should_show_explain();
1048 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
0531ce1d 1049 if can_show_explain && are_there_diagnostics {
48663c56
XL
1050 let mut error_codes = self
1051 .emitted_diagnostic_codes
48663c56 1052 .iter()
c295e0f8 1053 .filter_map(|x| match &x {
94222f64 1054 DiagnosticId::Error(s)
c295e0f8 1055 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
94222f64
XL
1056 {
1057 Some(s.clone())
48663c56
XL
1058 }
1059 _ => None,
1060 })
1061 .collect::<Vec<_>>();
0531ce1d
XL
1062 if !error_codes.is_empty() {
1063 error_codes.sort();
1064 if error_codes.len() > 1 {
1065 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
60c5eb7d
XL
1066 self.failure(&format!(
1067 "Some errors have detailed explanations: {}{}",
1068 error_codes[..limit].join(", "),
1069 if error_codes.len() > 9 { "..." } else { "." }
1070 ));
1071 self.failure(&format!(
1072 "For more information about an error, try \
ba9703b0 1073 `rustc --explain {}`.",
60c5eb7d
XL
1074 &error_codes[0]
1075 ));
0531ce1d 1076 } else {
60c5eb7d
XL
1077 self.failure(&format!(
1078 "For more information about this error, try \
ba9703b0 1079 `rustc --explain {}`.",
60c5eb7d
XL
1080 &error_codes[0]
1081 ));
9cc50fc6 1082 }
041b39d2 1083 }
9cc50fc6 1084 }
0531ce1d 1085 }
9cc50fc6 1086
17df50a5 1087 #[inline]
e74abb32
XL
1088 fn err_count(&self) -> usize {
1089 self.err_count + self.stashed_diagnostics.len()
1090 }
1091
1092 fn has_errors(&self) -> bool {
1093 self.err_count() > 0
1094 }
3c0e092e
XL
1095 fn has_errors_or_lint_errors(&self) -> bool {
1096 self.has_errors() || self.lint_err_count > 0
1097 }
e74abb32
XL
1098 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1099 self.has_errors() || !self.delayed_span_bugs.is_empty()
1100 }
1b1a35ee 1101 fn has_any_message(&self) -> bool {
3c0e092e 1102 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1b1a35ee 1103 }
e74abb32 1104
e74abb32
XL
1105 fn abort_if_errors(&mut self) {
1106 self.emit_stashed_diagnostics();
1107
1108 if self.has_errors() {
e1599b0c 1109 FatalError.raise();
c30ab7b3 1110 }
9cc50fc6 1111 }
3b2f2976 1112
e74abb32
XL
1113 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1114 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
5869c6ff 1115 panic::panic_any(ExplicitBug);
83c7162d
XL
1116 }
1117
e74abb32
XL
1118 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1119 self.emit_diagnostic(diag.set_span(sp));
e74abb32
XL
1120 }
1121
f035d41b 1122 #[track_caller]
e74abb32 1123 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
f9f354fc
XL
1124 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1125 // incrementing `err_count` by one, so we need to +1 the comparing.
1126 // FIXME: Would be nice to increment err_count in a more coherent way.
6a06907d 1127 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
e1599b0c
XL
1128 // FIXME: don't abort here if report_delayed_bugs is off
1129 self.span_bug(sp, msg);
1130 }
1131 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
1132 diagnostic.set_span(sp.into());
f035d41b 1133 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
e1599b0c 1134 self.delay_as_bug(diagnostic)
2c00a5a8
XL
1135 }
1136
1b1a35ee 1137 fn delay_good_path_bug(&mut self, msg: &str) {
17df50a5 1138 let diagnostic = Diagnostic::new(Level::Bug, msg);
1b1a35ee
XL
1139 if self.flags.report_delayed_bugs {
1140 self.emit_diagnostic(&diagnostic);
1141 }
17df50a5
XL
1142 let backtrace = std::backtrace::Backtrace::force_capture();
1143 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1b1a35ee
XL
1144 }
1145
e1599b0c
XL
1146 fn failure(&mut self, msg: &str) {
1147 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1148 }
abe05a73 1149
e1599b0c 1150 fn fatal(&mut self, msg: &str) -> FatalError {
e74abb32 1151 self.emit_error(Fatal, msg);
e1599b0c
XL
1152 FatalError
1153 }
abe05a73 1154
e1599b0c 1155 fn err(&mut self, msg: &str) {
3c0e092e 1156 self.emit_error(Error { lint: false }, msg);
e74abb32
XL
1157 }
1158
1159 /// Emit an error; level should be `Error` or `Fatal`.
60c5eb7d 1160 fn emit_error(&mut self, level: Level, msg: &str) {
e1599b0c
XL
1161 if self.treat_err_as_bug() {
1162 self.bug(msg);
2c00a5a8 1163 }
e74abb32 1164 self.emit_diagnostic(&Diagnostic::new(level, msg));
e1599b0c 1165 }
2c00a5a8 1166
e1599b0c
XL
1167 fn bug(&mut self, msg: &str) -> ! {
1168 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
5869c6ff 1169 panic::panic_any(ExplicitBug);
e1599b0c 1170 }
abe05a73 1171
e1599b0c 1172 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
94222f64
XL
1173 if self.quiet {
1174 return;
1175 }
e1599b0c
XL
1176 if self.flags.report_delayed_bugs {
1177 self.emit_diagnostic(&diagnostic);
dc9dc135 1178 }
e1599b0c 1179 self.delayed_span_bugs.push(diagnostic);
3b2f2976 1180 }
9cc50fc6 1181
1b1a35ee
XL
1182 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1183 let has_bugs = !bugs.is_empty();
1184 for bug in bugs {
1185 self.emit_diagnostic(&bug);
1186 }
1187 if has_bugs {
1188 panic!("{}", explanation);
1189 }
1190 }
1191
3c0e092e
XL
1192 fn bump_lint_err_count(&mut self) {
1193 self.lint_err_count += 1;
1194 self.panic_if_treat_err_as_bug();
1195 }
1196
e1599b0c
XL
1197 fn bump_err_count(&mut self) {
1198 self.err_count += 1;
1199 self.panic_if_treat_err_as_bug();
1200 }
1201
1b1a35ee
XL
1202 fn bump_warn_count(&mut self) {
1203 self.warn_count += 1;
1204 }
1205
e1599b0c
XL
1206 fn panic_if_treat_err_as_bug(&self) {
1207 if self.treat_err_as_bug() {
6a06907d 1208 match (self.err_count(), self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0)) {
1b1a35ee
XL
1209 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1210 (0, _) | (1, _) => {}
1211 (count, as_bug) => panic!(
60c5eb7d
XL
1212 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1213 count, as_bug,
1214 ),
1b1a35ee 1215 }
e1599b0c 1216 }
48663c56
XL
1217 }
1218}
9cc50fc6 1219
17df50a5
XL
1220struct DelayedDiagnostic {
1221 inner: Diagnostic,
1222 note: Backtrace,
1223}
1224
1225impl DelayedDiagnostic {
1226 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1227 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1228 }
1229
1230 fn decorate(mut self) -> Diagnostic {
1231 self.inner.note(&format!("delayed at {}", self.note));
1232 self.inner
1233 }
1234}
1235
3dfed10e 1236#[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
9cc50fc6
SL
1237pub enum Level {
1238 Bug,
1239 Fatal,
3c0e092e
XL
1240 Error {
1241 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1242 lint: bool,
1243 },
9cc50fc6
SL
1244 Warning,
1245 Note,
1246 Help,
1247 Cancelled,
0531ce1d 1248 FailureNote,
29967ef6 1249 Allow,
9cc50fc6
SL
1250}
1251
1252impl fmt::Display for Level {
9fa01778 1253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9cc50fc6
SL
1254 self.to_str().fmt(f)
1255 }
1256}
1257
1258impl Level {
0531ce1d
XL
1259 fn color(self) -> ColorSpec {
1260 let mut spec = ColorSpec::new();
9cc50fc6 1261 match self {
3c0e092e 1262 Bug | Fatal | Error { .. } => {
60c5eb7d 1263 spec.set_fg(Some(Color::Red)).set_intense(true);
0531ce1d 1264 }
9e0c209e 1265 Warning => {
60c5eb7d 1266 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
c30ab7b3 1267 }
0531ce1d 1268 Note => {
60c5eb7d 1269 spec.set_fg(Some(Color::Green)).set_intense(true);
0531ce1d
XL
1270 }
1271 Help => {
60c5eb7d 1272 spec.set_fg(Some(Color::Cyan)).set_intense(true);
0531ce1d
XL
1273 }
1274 FailureNote => {}
29967ef6 1275 Allow | Cancelled => unreachable!(),
9cc50fc6 1276 }
0531ce1d 1277 spec
9cc50fc6
SL
1278 }
1279
3157f602 1280 pub fn to_str(self) -> &'static str {
9cc50fc6
SL
1281 match self {
1282 Bug => "error: internal compiler error",
3c0e092e 1283 Fatal | Error { .. } => "error",
9cc50fc6
SL
1284 Warning => "warning",
1285 Note => "note",
1286 Help => "help",
e1599b0c 1287 FailureNote => "failure-note",
9cc50fc6 1288 Cancelled => panic!("Shouldn't call on cancelled error"),
29967ef6 1289 Allow => panic!("Shouldn't call on allowed error"),
9cc50fc6
SL
1290 }
1291 }
0531ce1d
XL
1292
1293 pub fn is_failure_note(&self) -> bool {
29967ef6 1294 matches!(*self, FailureNote)
0531ce1d 1295 }
9cc50fc6 1296}
e1599b0c 1297
29967ef6
XL
1298pub fn add_elided_lifetime_in_path_suggestion(
1299 source_map: &SourceMap,
1300 db: &mut DiagnosticBuilder<'_>,
1301 n: usize,
1302 path_span: Span,
1303 incl_angl_brckt: bool,
1304 insertion_span: Span,
1305 anon_lts: String,
1306) {
1307 let (replace_span, suggestion) = if incl_angl_brckt {
1308 (insertion_span, anon_lts)
1309 } else {
1310 // When possible, prefer a suggestion that replaces the whole
1311 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1312 // at a point (which makes for an ugly/confusing label)
1313 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1314 // But our spans can get out of whack due to macros; if the place we think
1315 // we want to insert `'_` isn't even within the path expression's span, we
1316 // should bail out of making any suggestion rather than panicking on a
1317 // subtract-with-overflow or string-slice-out-out-bounds (!)
1318 // FIXME: can we do better?
1319 if insertion_span.lo().0 < path_span.lo().0 {
1320 return;
1321 }
1322 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1323 if insertion_index > snippet.len() {
1324 return;
1325 }
1326 let (before, after) = snippet.split_at(insertion_index);
1327 (path_span, format!("{}{}{}", before, anon_lts, after))
1328 } else {
1329 (insertion_span, anon_lts)
1330 }
e1599b0c 1331 };
29967ef6
XL
1332 db.span_suggestion(
1333 replace_span,
1334 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1335 suggestion,
1336 Applicability::MachineApplicable,
1337 );
e1599b0c 1338}
60c5eb7d
XL
1339
1340// Useful type to use with `Result<>` indicate that an error has already
1341// been reported to the user, so no need to continue checking.
3dfed10e 1342#[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
60c5eb7d
XL
1343pub struct ErrorReported;
1344
1345rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);