]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Rollup merge of #68026 - llogiq:ch-ch-ch-ch-changes, r=varkor
[rust.git] / src / librustc_errors / lib.rs
1 //! Diagnostics creation and emission for `rustc`.
2 //!
3 //! This module contains the code for creating and emitting diagnostics.
4
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
6 #![feature(crate_visibility_modifier)]
7 #![cfg_attr(unix, feature(libc))]
8 #![feature(nll)]
9 #![feature(optin_builtin_traits)]
10
11 pub use emitter::ColorConfig;
12
13 use Level::*;
14
15 use emitter::{is_case_difference, Emitter, EmitterWriter};
16 use registry::Registry;
17 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
18 use rustc_data_structures::stable_hasher::StableHasher;
19 use rustc_data_structures::sync::{self, Lock, Lrc};
20 use rustc_data_structures::AtomicRef;
21 use rustc_span::source_map::SourceMap;
22 use rustc_span::{Loc, MultiSpan, Span};
23
24 use std::borrow::Cow;
25 use std::panic;
26 use std::path::Path;
27 use std::{error, fmt};
28
29 use termcolor::{Color, ColorSpec};
30
31 pub mod annotate_snippet_emitter_writer;
32 mod diagnostic;
33 mod diagnostic_builder;
34 pub mod emitter;
35 pub mod json;
36 mod lock;
37 pub mod registry;
38 mod snippet;
39 mod styled_buffer;
40 pub use snippet::Style;
41
42 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
43
44 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
45 // (See also the comment on `DiagnosticBuilderInner`.)
46 #[cfg(target_arch = "x86_64")]
47 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
48
49 /// Indicates the confidence in the correctness of a suggestion.
50 ///
51 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
52 /// to determine whether it should be automatically applied or if the user should be consulted
53 /// before applying the suggestion.
54 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
55 pub enum Applicability {
56     /// The suggestion is definitely what the user intended. This suggestion should be
57     /// automatically applied.
58     MachineApplicable,
59
60     /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
61     /// result in valid Rust code if it is applied.
62     MaybeIncorrect,
63
64     /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
65     /// cannot be applied automatically because it will not result in valid Rust code. The user
66     /// will need to fill in the placeholders.
67     HasPlaceholders,
68
69     /// The applicability of the suggestion is unknown.
70     Unspecified,
71 }
72
73 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
74 pub enum SuggestionStyle {
75     /// Hide the suggested code when displaying this suggestion inline.
76     HideCodeInline,
77     /// Always hide the suggested code but display the message.
78     HideCodeAlways,
79     /// Do not display this suggestion in the cli output, it is only meant for tools.
80     CompletelyHidden,
81     /// Always show the suggested code.
82     /// This will *not* show the code if the suggestion is inline *and* the suggested code is
83     /// empty.
84     ShowCode,
85     /// Always show the suggested code independently.
86     ShowAlways,
87 }
88
89 impl SuggestionStyle {
90     fn hide_inline(&self) -> bool {
91         match *self {
92             SuggestionStyle::ShowCode => false,
93             _ => true,
94         }
95     }
96 }
97
98 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
99 pub struct CodeSuggestion {
100     /// Each substitute can have multiple variants due to multiple
101     /// applicable suggestions
102     ///
103     /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
104     /// `foo` and `bar` on their own:
105     ///
106     /// ```
107     /// vec![
108     ///     Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
109     ///     Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
110     /// ]
111     /// ```
112     ///
113     /// or by replacing the entire span:
114     ///
115     /// ```
116     /// vec![
117     ///     Substitution { parts: vec![(0..7, "a.b")] },
118     ///     Substitution { parts: vec![(0..7, "x.y")] },
119     /// ]
120     /// ```
121     pub substitutions: Vec<Substitution>,
122     pub msg: String,
123     /// Visual representation of this suggestion.
124     pub style: SuggestionStyle,
125     /// Whether or not the suggestion is approximate
126     ///
127     /// Sometimes we may show suggestions with placeholders,
128     /// which are useful for users but not useful for
129     /// tools like rustfix
130     pub applicability: Applicability,
131 }
132
133 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
134 /// See the docs on `CodeSuggestion::substitutions`
135 pub struct Substitution {
136     pub parts: Vec<SubstitutionPart>,
137 }
138
139 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
140 pub struct SubstitutionPart {
141     pub span: Span,
142     pub snippet: String,
143 }
144
145 impl CodeSuggestion {
146     /// Returns the assembled code suggestions, whether they should be shown with an underline
147     /// and whether the substitution only differs in capitalization.
148     pub fn splice_lines(&self, cm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
149         use rustc_span::{CharPos, Pos};
150
151         fn push_trailing(
152             buf: &mut String,
153             line_opt: Option<&Cow<'_, str>>,
154             lo: &Loc,
155             hi_opt: Option<&Loc>,
156         ) {
157             let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
158             if let Some(line) = line_opt {
159                 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
160                     let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
161                     match hi_opt {
162                         Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
163                         Some(_) => (),
164                         None => buf.push_str(&line[lo..]),
165                     }
166                 }
167                 if let None = hi_opt {
168                     buf.push('\n');
169                 }
170             }
171         }
172
173         assert!(!self.substitutions.is_empty());
174
175         self.substitutions
176             .iter()
177             .cloned()
178             .map(|mut substitution| {
179                 // Assumption: all spans are in the same file, and all spans
180                 // are disjoint. Sort in ascending order.
181                 substitution.parts.sort_by_key(|part| part.span.lo());
182
183                 // Find the bounding span.
184                 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
185                 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
186                 let bounding_span = Span::with_root_ctxt(lo, hi);
187                 let lines = cm.span_to_lines(bounding_span).unwrap();
188                 assert!(!lines.lines.is_empty());
189
190                 // To build up the result, we do this for each span:
191                 // - push the line segment trailing the previous span
192                 //   (at the beginning a "phantom" span pointing at the start of the line)
193                 // - push lines between the previous and current span (if any)
194                 // - if the previous and current span are not on the same line
195                 //   push the line segment leading up to the current span
196                 // - splice in the span substitution
197                 //
198                 // Finally push the trailing line segment of the last span
199                 let fm = &lines.file;
200                 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
201                 prev_hi.col = CharPos::from_usize(0);
202
203                 let mut prev_line = fm.get_line(lines.lines[0].line_index);
204                 let mut buf = String::new();
205
206                 for part in &substitution.parts {
207                     let cur_lo = cm.lookup_char_pos(part.span.lo());
208                     if prev_hi.line == cur_lo.line {
209                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
210                     } else {
211                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
212                         // push lines between the previous and current span (if any)
213                         for idx in prev_hi.line..(cur_lo.line - 1) {
214                             if let Some(line) = fm.get_line(idx) {
215                                 buf.push_str(line.as_ref());
216                                 buf.push('\n');
217                             }
218                         }
219                         if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
220                             let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
221                             buf.push_str(&cur_line[..end]);
222                         }
223                     }
224                     buf.push_str(&part.snippet);
225                     prev_hi = cm.lookup_char_pos(part.span.hi());
226                     prev_line = fm.get_line(prev_hi.line - 1);
227                 }
228                 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
229                 // if the replacement already ends with a newline, don't print the next line
230                 if !buf.ends_with('\n') {
231                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
232                 }
233                 // remove trailing newlines
234                 while buf.ends_with('\n') {
235                     buf.pop();
236                 }
237                 (buf, substitution.parts, only_capitalization)
238             })
239             .collect()
240     }
241 }
242
243 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
244
245 /// Signifies that the compiler died with an explicit call to `.bug`
246 /// or `.span_bug` rather than a failed assertion, etc.
247 #[derive(Copy, Clone, Debug)]
248 pub struct ExplicitBug;
249
250 impl fmt::Display for ExplicitBug {
251     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252         write!(f, "parser internal bug")
253     }
254 }
255
256 impl error::Error for ExplicitBug {}
257
258 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
259 pub use diagnostic_builder::DiagnosticBuilder;
260
261 /// A handler deals with errors and other compiler output.
262 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
263 /// others log errors for later reporting.
264 pub struct Handler {
265     flags: HandlerFlags,
266     inner: Lock<HandlerInner>,
267 }
268
269 /// This inner struct exists to keep it all behind a single lock;
270 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
271 /// as well as inconsistent state observation.
272 struct HandlerInner {
273     flags: HandlerFlags,
274     /// The number of errors that have been emitted, including duplicates.
275     ///
276     /// This is not necessarily the count that's reported to the user once
277     /// compilation ends.
278     err_count: usize,
279     deduplicated_err_count: usize,
280     emitter: Box<dyn Emitter + sync::Send>,
281     delayed_span_bugs: Vec<Diagnostic>,
282
283     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
284     /// emitting the same diagnostic with extended help (`--teach`) twice, which
285     /// would be uneccessary repetition.
286     taught_diagnostics: FxHashSet<DiagnosticId>,
287
288     /// Used to suggest rustc --explain <error code>
289     emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
290
291     /// This set contains a hash of every diagnostic that has been emitted by
292     /// this handler. These hashes is used to avoid emitting the same error
293     /// twice.
294     emitted_diagnostics: FxHashSet<u128>,
295
296     /// Stashed diagnostics emitted in one stage of the compiler that may be
297     /// stolen by other stages (e.g. to improve them and add more information).
298     /// The stashed diagnostics count towards the total error count.
299     /// When `.abort_if_errors()` is called, these are also emitted.
300     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
301 }
302
303 /// A key denoting where from a diagnostic was stashed.
304 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
305 pub enum StashKey {
306     ItemNoType,
307 }
308
309 fn default_track_diagnostic(_: &Diagnostic) {}
310
311 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
312     AtomicRef::new(&(default_track_diagnostic as fn(&_)));
313
314 #[derive(Copy, Clone, Default)]
315 pub struct HandlerFlags {
316     /// If false, warning-level lints are suppressed.
317     /// (rustc: see `--allow warnings` and `--cap-lints`)
318     pub can_emit_warnings: bool,
319     /// If true, error-level diagnostics are upgraded to bug-level.
320     /// (rustc: see `-Z treat-err-as-bug`)
321     pub treat_err_as_bug: Option<usize>,
322     /// If true, immediately emit diagnostics that would otherwise be buffered.
323     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
324     pub dont_buffer_diagnostics: bool,
325     /// If true, immediately print bugs registered with `delay_span_bug`.
326     /// (rustc: see `-Z report-delayed-bugs`)
327     pub report_delayed_bugs: bool,
328     /// show macro backtraces even for non-local macros.
329     /// (rustc: see `-Z external-macro-backtrace`)
330     pub external_macro_backtrace: bool,
331     /// If true, identical diagnostics are reported only once.
332     pub deduplicate_diagnostics: bool,
333 }
334
335 impl Drop for HandlerInner {
336     fn drop(&mut self) {
337         self.emit_stashed_diagnostics();
338
339         if !self.has_errors() {
340             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
341             let has_bugs = !bugs.is_empty();
342             for bug in bugs {
343                 self.emit_diagnostic(&bug);
344             }
345             if has_bugs {
346                 panic!("no errors encountered even though `delay_span_bug` issued");
347             }
348         }
349     }
350 }
351
352 impl Handler {
353     pub fn with_tty_emitter(
354         color_config: ColorConfig,
355         can_emit_warnings: bool,
356         treat_err_as_bug: Option<usize>,
357         cm: Option<Lrc<SourceMap>>,
358     ) -> Self {
359         Self::with_tty_emitter_and_flags(
360             color_config,
361             cm,
362             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
363         )
364     }
365
366     pub fn with_tty_emitter_and_flags(
367         color_config: ColorConfig,
368         cm: Option<Lrc<SourceMap>>,
369         flags: HandlerFlags,
370     ) -> Self {
371         let emitter = Box::new(EmitterWriter::stderr(
372             color_config,
373             cm,
374             false,
375             false,
376             None,
377             flags.external_macro_backtrace,
378         ));
379         Self::with_emitter_and_flags(emitter, flags)
380     }
381
382     pub fn with_emitter(
383         can_emit_warnings: bool,
384         treat_err_as_bug: Option<usize>,
385         emitter: Box<dyn Emitter + sync::Send>,
386     ) -> Self {
387         Handler::with_emitter_and_flags(
388             emitter,
389             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
390         )
391     }
392
393     pub fn with_emitter_and_flags(
394         emitter: Box<dyn Emitter + sync::Send>,
395         flags: HandlerFlags,
396     ) -> Self {
397         Self {
398             flags,
399             inner: Lock::new(HandlerInner {
400                 flags,
401                 err_count: 0,
402                 deduplicated_err_count: 0,
403                 emitter,
404                 delayed_span_bugs: Vec::new(),
405                 taught_diagnostics: Default::default(),
406                 emitted_diagnostic_codes: Default::default(),
407                 emitted_diagnostics: Default::default(),
408                 stashed_diagnostics: Default::default(),
409             }),
410         }
411     }
412
413     // This is here to not allow mutation of flags;
414     // as of this writing it's only used in tests in librustc.
415     pub fn can_emit_warnings(&self) -> bool {
416         self.flags.can_emit_warnings
417     }
418
419     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
420     ///
421     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
422     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
423     /// the overall count of emitted error diagnostics.
424     pub fn reset_err_count(&self) {
425         let mut inner = self.inner.borrow_mut();
426         inner.err_count = 0;
427         inner.deduplicated_err_count = 0;
428
429         // actually free the underlying memory (which `clear` would not do)
430         inner.delayed_span_bugs = Default::default();
431         inner.taught_diagnostics = Default::default();
432         inner.emitted_diagnostic_codes = Default::default();
433         inner.emitted_diagnostics = Default::default();
434         inner.stashed_diagnostics = Default::default();
435     }
436
437     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
438     /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
439     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
440         let mut inner = self.inner.borrow_mut();
441         if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
442             // We are removing a previously stashed diagnostic which should not happen.
443             old_diag.level = Bug;
444             old_diag.note(&format!(
445                 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
446                 file!(),
447                 line!(),
448                 span,
449                 key
450             ));
451             inner.emit_diag_at_span(old_diag, span);
452             panic!(ExplicitBug);
453         }
454     }
455
456     /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
457     pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
458         self.inner
459             .borrow_mut()
460             .stashed_diagnostics
461             .remove(&(span, key))
462             .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
463     }
464
465     /// Emit all stashed diagnostics.
466     pub fn emit_stashed_diagnostics(&self) {
467         self.inner.borrow_mut().emit_stashed_diagnostics();
468     }
469
470     /// Construct a dummy builder with `Level::Cancelled`.
471     ///
472     /// Using this will neither report anything to the user (e.g. a warning),
473     /// nor will compilation cancel as a result.
474     pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
475         DiagnosticBuilder::new(self, Level::Cancelled, "")
476     }
477
478     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
479     pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
480         let mut result = self.struct_warn(msg);
481         result.set_span(span);
482         result
483     }
484
485     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
486     /// Also include a code.
487     pub fn struct_span_warn_with_code(
488         &self,
489         span: impl Into<MultiSpan>,
490         msg: &str,
491         code: DiagnosticId,
492     ) -> DiagnosticBuilder<'_> {
493         let mut result = self.struct_span_warn(span, msg);
494         result.code(code);
495         result
496     }
497
498     /// Construct a builder at the `Warning` level with the `msg`.
499     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
500         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
501         if !self.flags.can_emit_warnings {
502             result.cancel();
503         }
504         result
505     }
506
507     /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
508     pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
509         let mut result = self.struct_err(msg);
510         result.set_span(span);
511         result
512     }
513
514     /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
515     pub fn struct_span_err_with_code(
516         &self,
517         span: impl Into<MultiSpan>,
518         msg: &str,
519         code: DiagnosticId,
520     ) -> DiagnosticBuilder<'_> {
521         let mut result = self.struct_span_err(span, msg);
522         result.code(code);
523         result
524     }
525
526     /// Construct a builder at the `Error` level with the `msg`.
527     // FIXME: This method should be removed (every error should have an associated error code).
528     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
529         DiagnosticBuilder::new(self, Level::Error, msg)
530     }
531
532     /// Construct a builder at the `Error` level with the `msg` and the `code`.
533     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
534         let mut result = self.struct_err(msg);
535         result.code(code);
536         result
537     }
538
539     /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
540     pub fn struct_span_fatal(
541         &self,
542         span: impl Into<MultiSpan>,
543         msg: &str,
544     ) -> DiagnosticBuilder<'_> {
545         let mut result = self.struct_fatal(msg);
546         result.set_span(span);
547         result
548     }
549
550     /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
551     pub fn struct_span_fatal_with_code(
552         &self,
553         span: impl Into<MultiSpan>,
554         msg: &str,
555         code: DiagnosticId,
556     ) -> DiagnosticBuilder<'_> {
557         let mut result = self.struct_span_fatal(span, msg);
558         result.code(code);
559         result
560     }
561
562     /// Construct a builder at the `Error` level with the `msg`.
563     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
564         DiagnosticBuilder::new(self, Level::Fatal, msg)
565     }
566
567     /// Construct a builder at the `Help` level with the `msg`.
568     pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
569         DiagnosticBuilder::new(self, Level::Help, msg)
570     }
571
572     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
573         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
574         FatalError
575     }
576
577     pub fn span_fatal_with_code(
578         &self,
579         span: impl Into<MultiSpan>,
580         msg: &str,
581         code: DiagnosticId,
582     ) -> FatalError {
583         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
584         FatalError
585     }
586
587     pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
588         self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
589     }
590
591     pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
592         self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
593     }
594
595     pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
596         self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
597     }
598
599     pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
600         self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
601     }
602
603     pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
604         self.inner.borrow_mut().span_bug(span, msg)
605     }
606
607     pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
608         self.inner.borrow_mut().delay_span_bug(span, msg)
609     }
610
611     pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
612         self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
613     }
614
615     pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
616         self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
617     }
618
619     pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
620         let mut db = DiagnosticBuilder::new(self, Note, msg);
621         db.set_span(span);
622         db
623     }
624
625     pub fn failure(&self, msg: &str) {
626         self.inner.borrow_mut().failure(msg);
627     }
628
629     pub fn fatal(&self, msg: &str) -> FatalError {
630         self.inner.borrow_mut().fatal(msg)
631     }
632
633     pub fn err(&self, msg: &str) {
634         self.inner.borrow_mut().err(msg);
635     }
636
637     pub fn warn(&self, msg: &str) {
638         let mut db = DiagnosticBuilder::new(self, Warning, msg);
639         db.emit();
640     }
641
642     pub fn note_without_error(&self, msg: &str) {
643         DiagnosticBuilder::new(self, Note, msg).emit();
644     }
645
646     pub fn bug(&self, msg: &str) -> ! {
647         self.inner.borrow_mut().bug(msg)
648     }
649
650     pub fn err_count(&self) -> usize {
651         self.inner.borrow().err_count()
652     }
653
654     pub fn has_errors(&self) -> bool {
655         self.inner.borrow().has_errors()
656     }
657     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
658         self.inner.borrow().has_errors_or_delayed_span_bugs()
659     }
660
661     pub fn print_error_count(&self, registry: &Registry) {
662         self.inner.borrow_mut().print_error_count(registry)
663     }
664
665     pub fn abort_if_errors(&self) {
666         self.inner.borrow_mut().abort_if_errors()
667     }
668
669     /// `true` if we haven't taught a diagnostic with this code already.
670     /// The caller must then teach the user about such a diagnostic.
671     ///
672     /// Used to suppress emitting the same error multiple times with extended explanation when
673     /// calling `-Zteach`.
674     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
675         self.inner.borrow_mut().must_teach(code)
676     }
677
678     pub fn force_print_diagnostic(&self, db: Diagnostic) {
679         self.inner.borrow_mut().force_print_diagnostic(db)
680     }
681
682     pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
683         self.inner.borrow_mut().emit_diagnostic(diagnostic)
684     }
685
686     fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
687         let mut inner = self.inner.borrow_mut();
688         inner.emit_diagnostic(diag.set_span(sp));
689     }
690
691     pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
692         self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
693     }
694
695     pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
696         self.inner.borrow_mut().delay_as_bug(diagnostic)
697     }
698 }
699
700 impl HandlerInner {
701     fn must_teach(&mut self, code: &DiagnosticId) -> bool {
702         self.taught_diagnostics.insert(code.clone())
703     }
704
705     fn force_print_diagnostic(&mut self, db: Diagnostic) {
706         self.emitter.emit_diagnostic(&db);
707     }
708
709     /// Emit all stashed diagnostics.
710     fn emit_stashed_diagnostics(&mut self) {
711         let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
712         diags.iter().for_each(|diag| self.emit_diagnostic(diag));
713     }
714
715     fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
716         if diagnostic.cancelled() {
717             return;
718         }
719
720         if diagnostic.level == Warning && !self.flags.can_emit_warnings {
721             return;
722         }
723
724         (*TRACK_DIAGNOSTICS)(diagnostic);
725
726         if let Some(ref code) = diagnostic.code {
727             self.emitted_diagnostic_codes.insert(code.clone());
728         }
729
730         let already_emitted = |this: &mut Self| {
731             use std::hash::Hash;
732             let mut hasher = StableHasher::new();
733             diagnostic.hash(&mut hasher);
734             let diagnostic_hash = hasher.finish();
735             !this.emitted_diagnostics.insert(diagnostic_hash)
736         };
737
738         // Only emit the diagnostic if we've been asked to deduplicate and
739         // haven't already emitted an equivalent diagnostic.
740         if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
741             self.emitter.emit_diagnostic(diagnostic);
742             if diagnostic.is_error() {
743                 self.deduplicated_err_count += 1;
744             }
745         }
746         if diagnostic.is_error() {
747             self.bump_err_count();
748         }
749     }
750
751     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
752         self.emitter.emit_artifact_notification(path, artifact_type);
753     }
754
755     fn treat_err_as_bug(&self) -> bool {
756         self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
757     }
758
759     fn print_error_count(&mut self, registry: &Registry) {
760         self.emit_stashed_diagnostics();
761
762         let s = match self.deduplicated_err_count {
763             0 => return,
764             1 => "aborting due to previous error".to_string(),
765             count => format!("aborting due to {} previous errors", count),
766         };
767         if self.treat_err_as_bug() {
768             return;
769         }
770
771         let _ = self.fatal(&s);
772
773         let can_show_explain = self.emitter.should_show_explain();
774         let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
775         if can_show_explain && are_there_diagnostics {
776             let mut error_codes = self
777                 .emitted_diagnostic_codes
778                 .iter()
779                 .filter_map(|x| match &x {
780                     DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
781                         Some(s.clone())
782                     }
783                     _ => None,
784                 })
785                 .collect::<Vec<_>>();
786             if !error_codes.is_empty() {
787                 error_codes.sort();
788                 if error_codes.len() > 1 {
789                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
790                     self.failure(&format!(
791                         "Some errors have detailed explanations: {}{}",
792                         error_codes[..limit].join(", "),
793                         if error_codes.len() > 9 { "..." } else { "." }
794                     ));
795                     self.failure(&format!(
796                         "For more information about an error, try \
797                                            `rustc --explain {}`.",
798                         &error_codes[0]
799                     ));
800                 } else {
801                     self.failure(&format!(
802                         "For more information about this error, try \
803                                            `rustc --explain {}`.",
804                         &error_codes[0]
805                     ));
806                 }
807             }
808         }
809     }
810
811     fn err_count(&self) -> usize {
812         self.err_count + self.stashed_diagnostics.len()
813     }
814
815     fn has_errors(&self) -> bool {
816         self.err_count() > 0
817     }
818     fn has_errors_or_delayed_span_bugs(&self) -> bool {
819         self.has_errors() || !self.delayed_span_bugs.is_empty()
820     }
821
822     fn abort_if_errors(&mut self) {
823         self.emit_stashed_diagnostics();
824
825         if self.has_errors() {
826             FatalError.raise();
827         }
828     }
829
830     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
831         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
832         panic!(ExplicitBug);
833     }
834
835     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
836         self.emit_diagnostic(diag.set_span(sp));
837     }
838
839     fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
840         if self.treat_err_as_bug() {
841             // FIXME: don't abort here if report_delayed_bugs is off
842             self.span_bug(sp, msg);
843         }
844         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
845         diagnostic.set_span(sp.into());
846         self.delay_as_bug(diagnostic)
847     }
848
849     fn failure(&mut self, msg: &str) {
850         self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
851     }
852
853     fn fatal(&mut self, msg: &str) -> FatalError {
854         self.emit_error(Fatal, msg);
855         FatalError
856     }
857
858     fn err(&mut self, msg: &str) {
859         self.emit_error(Error, msg);
860     }
861
862     /// Emit an error; level should be `Error` or `Fatal`.
863     fn emit_error(&mut self, level: Level, msg: &str) {
864         if self.treat_err_as_bug() {
865             self.bug(msg);
866         }
867         self.emit_diagnostic(&Diagnostic::new(level, msg));
868     }
869
870     fn bug(&mut self, msg: &str) -> ! {
871         self.emit_diagnostic(&Diagnostic::new(Bug, msg));
872         panic!(ExplicitBug);
873     }
874
875     fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
876         if self.flags.report_delayed_bugs {
877             self.emit_diagnostic(&diagnostic);
878         }
879         self.delayed_span_bugs.push(diagnostic);
880     }
881
882     fn bump_err_count(&mut self) {
883         self.err_count += 1;
884         self.panic_if_treat_err_as_bug();
885     }
886
887     fn panic_if_treat_err_as_bug(&self) {
888         if self.treat_err_as_bug() {
889             let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
890                 (0, _) => return,
891                 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
892                 (1, _) => return,
893                 (count, as_bug) => format!(
894                     "aborting after {} errors due to `-Z treat-err-as-bug={}`",
895                     count, as_bug,
896                 ),
897             };
898             panic!(s);
899         }
900     }
901 }
902
903 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
904 pub enum Level {
905     Bug,
906     Fatal,
907     Error,
908     Warning,
909     Note,
910     Help,
911     Cancelled,
912     FailureNote,
913 }
914
915 impl fmt::Display for Level {
916     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
917         self.to_str().fmt(f)
918     }
919 }
920
921 impl Level {
922     fn color(self) -> ColorSpec {
923         let mut spec = ColorSpec::new();
924         match self {
925             Bug | Fatal | Error => {
926                 spec.set_fg(Some(Color::Red)).set_intense(true);
927             }
928             Warning => {
929                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
930             }
931             Note => {
932                 spec.set_fg(Some(Color::Green)).set_intense(true);
933             }
934             Help => {
935                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
936             }
937             FailureNote => {}
938             Cancelled => unreachable!(),
939         }
940         spec
941     }
942
943     pub fn to_str(self) -> &'static str {
944         match self {
945             Bug => "error: internal compiler error",
946             Fatal | Error => "error",
947             Warning => "warning",
948             Note => "note",
949             Help => "help",
950             FailureNote => "failure-note",
951             Cancelled => panic!("Shouldn't call on cancelled error"),
952         }
953     }
954
955     pub fn is_failure_note(&self) -> bool {
956         match *self {
957             FailureNote => true,
958             _ => false,
959         }
960     }
961 }
962
963 #[macro_export]
964 macro_rules! pluralize {
965     ($x:expr) => {
966         if $x != 1 { "s" } else { "" }
967     };
968 }
969
970 // Useful type to use with `Result<>` indicate that an error has already
971 // been reported to the user, so no need to continue checking.
972 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
973 pub struct ErrorReported;
974
975 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);