]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Rollup merge of #67798 - matklad:spin-thouse-docs, r=Amanieu
[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     continue_after_error: bool,
282     delayed_span_bugs: Vec<Diagnostic>,
283
284     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
285     /// emitting the same diagnostic with extended help (`--teach`) twice, which
286     /// would be uneccessary repetition.
287     taught_diagnostics: FxHashSet<DiagnosticId>,
288
289     /// Used to suggest rustc --explain <error code>
290     emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
291
292     /// This set contains a hash of every diagnostic that has been emitted by
293     /// this handler. These hashes is used to avoid emitting the same error
294     /// twice.
295     emitted_diagnostics: FxHashSet<u128>,
296
297     /// Stashed diagnostics emitted in one stage of the compiler that may be
298     /// stolen by other stages (e.g. to improve them and add more information).
299     /// The stashed diagnostics count towards the total error count.
300     /// When `.abort_if_errors()` is called, these are also emitted.
301     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
302 }
303
304 /// A key denoting where from a diagnostic was stashed.
305 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
306 pub enum StashKey {
307     ItemNoType,
308 }
309
310 fn default_track_diagnostic(_: &Diagnostic) {}
311
312 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
313     AtomicRef::new(&(default_track_diagnostic as fn(&_)));
314
315 #[derive(Copy, Clone, Default)]
316 pub struct HandlerFlags {
317     /// If false, warning-level lints are suppressed.
318     /// (rustc: see `--allow warnings` and `--cap-lints`)
319     pub can_emit_warnings: bool,
320     /// If true, error-level diagnostics are upgraded to bug-level.
321     /// (rustc: see `-Z treat-err-as-bug`)
322     pub treat_err_as_bug: Option<usize>,
323     /// If true, immediately emit diagnostics that would otherwise be buffered.
324     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
325     pub dont_buffer_diagnostics: bool,
326     /// If true, immediately print bugs registered with `delay_span_bug`.
327     /// (rustc: see `-Z report-delayed-bugs`)
328     pub report_delayed_bugs: bool,
329     /// show macro backtraces even for non-local macros.
330     /// (rustc: see `-Z external-macro-backtrace`)
331     pub external_macro_backtrace: bool,
332     /// If true, identical diagnostics are reported only once.
333     pub deduplicate_diagnostics: bool,
334 }
335
336 impl Drop for HandlerInner {
337     fn drop(&mut self) {
338         self.emit_stashed_diagnostics();
339
340         if !self.has_errors() {
341             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
342             let has_bugs = !bugs.is_empty();
343             for bug in bugs {
344                 self.emit_diagnostic(&bug);
345             }
346             if has_bugs {
347                 panic!("no errors encountered even though `delay_span_bug` issued");
348             }
349         }
350     }
351 }
352
353 impl Handler {
354     pub fn with_tty_emitter(
355         color_config: ColorConfig,
356         can_emit_warnings: bool,
357         treat_err_as_bug: Option<usize>,
358         cm: Option<Lrc<SourceMap>>,
359     ) -> Self {
360         Self::with_tty_emitter_and_flags(
361             color_config,
362             cm,
363             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
364         )
365     }
366
367     pub fn with_tty_emitter_and_flags(
368         color_config: ColorConfig,
369         cm: Option<Lrc<SourceMap>>,
370         flags: HandlerFlags,
371     ) -> Self {
372         let emitter = Box::new(EmitterWriter::stderr(
373             color_config,
374             cm,
375             false,
376             false,
377             None,
378             flags.external_macro_backtrace,
379         ));
380         Self::with_emitter_and_flags(emitter, flags)
381     }
382
383     pub fn with_emitter(
384         can_emit_warnings: bool,
385         treat_err_as_bug: Option<usize>,
386         emitter: Box<dyn Emitter + sync::Send>,
387     ) -> Self {
388         Handler::with_emitter_and_flags(
389             emitter,
390             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
391         )
392     }
393
394     pub fn with_emitter_and_flags(
395         emitter: Box<dyn Emitter + sync::Send>,
396         flags: HandlerFlags,
397     ) -> Self {
398         Self {
399             flags,
400             inner: Lock::new(HandlerInner {
401                 flags,
402                 err_count: 0,
403                 deduplicated_err_count: 0,
404                 emitter,
405                 continue_after_error: true,
406                 delayed_span_bugs: Vec::new(),
407                 taught_diagnostics: Default::default(),
408                 emitted_diagnostic_codes: Default::default(),
409                 emitted_diagnostics: Default::default(),
410                 stashed_diagnostics: Default::default(),
411             }),
412         }
413     }
414
415     pub fn set_continue_after_error(&self, continue_after_error: bool) {
416         self.inner.borrow_mut().continue_after_error = continue_after_error;
417     }
418
419     // This is here to not allow mutation of flags;
420     // as of this writing it's only used in tests in librustc.
421     pub fn can_emit_warnings(&self) -> bool {
422         self.flags.can_emit_warnings
423     }
424
425     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
426     ///
427     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
428     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
429     /// the overall count of emitted error diagnostics.
430     pub fn reset_err_count(&self) {
431         let mut inner = self.inner.borrow_mut();
432         inner.err_count = 0;
433         inner.deduplicated_err_count = 0;
434
435         // actually free the underlying memory (which `clear` would not do)
436         inner.delayed_span_bugs = Default::default();
437         inner.taught_diagnostics = Default::default();
438         inner.emitted_diagnostic_codes = Default::default();
439         inner.emitted_diagnostics = Default::default();
440         inner.stashed_diagnostics = Default::default();
441     }
442
443     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
444     /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
445     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
446         let mut inner = self.inner.borrow_mut();
447         if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
448             // We are removing a previously stashed diagnostic which should not happen.
449             old_diag.level = Bug;
450             old_diag.note(&format!(
451                 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
452                 file!(),
453                 line!(),
454                 span,
455                 key
456             ));
457             inner.emit_diag_at_span(old_diag, span);
458             panic!(ExplicitBug);
459         }
460     }
461
462     /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
463     pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
464         self.inner
465             .borrow_mut()
466             .stashed_diagnostics
467             .remove(&(span, key))
468             .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
469     }
470
471     /// Emit all stashed diagnostics.
472     pub fn emit_stashed_diagnostics(&self) {
473         self.inner.borrow_mut().emit_stashed_diagnostics();
474     }
475
476     /// Construct a dummy builder with `Level::Cancelled`.
477     ///
478     /// Using this will neither report anything to the user (e.g. a warning),
479     /// nor will compilation cancel as a result.
480     pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
481         DiagnosticBuilder::new(self, Level::Cancelled, "")
482     }
483
484     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
485     pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
486         let mut result = self.struct_warn(msg);
487         result.set_span(span);
488         result
489     }
490
491     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
492     /// Also include a code.
493     pub fn struct_span_warn_with_code(
494         &self,
495         span: impl Into<MultiSpan>,
496         msg: &str,
497         code: DiagnosticId,
498     ) -> DiagnosticBuilder<'_> {
499         let mut result = self.struct_span_warn(span, msg);
500         result.code(code);
501         result
502     }
503
504     /// Construct a builder at the `Warning` level with the `msg`.
505     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
506         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
507         if !self.flags.can_emit_warnings {
508             result.cancel();
509         }
510         result
511     }
512
513     /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
514     pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
515         let mut result = self.struct_err(msg);
516         result.set_span(span);
517         result
518     }
519
520     /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
521     pub fn struct_span_err_with_code(
522         &self,
523         span: impl Into<MultiSpan>,
524         msg: &str,
525         code: DiagnosticId,
526     ) -> DiagnosticBuilder<'_> {
527         let mut result = self.struct_span_err(span, msg);
528         result.code(code);
529         result
530     }
531
532     /// Construct a builder at the `Error` level with the `msg`.
533     // FIXME: This method should be removed (every error should have an associated error code).
534     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
535         DiagnosticBuilder::new(self, Level::Error, msg)
536     }
537
538     /// Construct a builder at the `Error` level with the `msg` and the `code`.
539     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
540         let mut result = self.struct_err(msg);
541         result.code(code);
542         result
543     }
544
545     /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
546     pub fn struct_span_fatal(
547         &self,
548         span: impl Into<MultiSpan>,
549         msg: &str,
550     ) -> DiagnosticBuilder<'_> {
551         let mut result = self.struct_fatal(msg);
552         result.set_span(span);
553         result
554     }
555
556     /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
557     pub fn struct_span_fatal_with_code(
558         &self,
559         span: impl Into<MultiSpan>,
560         msg: &str,
561         code: DiagnosticId,
562     ) -> DiagnosticBuilder<'_> {
563         let mut result = self.struct_span_fatal(span, msg);
564         result.code(code);
565         result
566     }
567
568     /// Construct a builder at the `Error` level with the `msg`.
569     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
570         DiagnosticBuilder::new(self, Level::Fatal, msg)
571     }
572
573     /// Construct a builder at the `Help` level with the `msg`.
574     pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
575         DiagnosticBuilder::new(self, Level::Help, msg)
576     }
577
578     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
579         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
580         FatalError
581     }
582
583     pub fn span_fatal_with_code(
584         &self,
585         span: impl Into<MultiSpan>,
586         msg: &str,
587         code: DiagnosticId,
588     ) -> FatalError {
589         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
590         FatalError
591     }
592
593     pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
594         self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
595     }
596
597     pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
598         self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
599     }
600
601     pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
602         self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
603     }
604
605     pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
606         self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
607     }
608
609     pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
610         self.inner.borrow_mut().span_bug(span, msg)
611     }
612
613     pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
614         self.inner.borrow_mut().delay_span_bug(span, msg)
615     }
616
617     pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
618         self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
619     }
620
621     pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
622         self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
623     }
624
625     pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
626         let mut db = DiagnosticBuilder::new(self, Note, msg);
627         db.set_span(span);
628         db
629     }
630
631     pub fn failure(&self, msg: &str) {
632         self.inner.borrow_mut().failure(msg);
633     }
634
635     pub fn fatal(&self, msg: &str) -> FatalError {
636         self.inner.borrow_mut().fatal(msg)
637     }
638
639     pub fn err(&self, msg: &str) {
640         self.inner.borrow_mut().err(msg);
641     }
642
643     pub fn warn(&self, msg: &str) {
644         let mut db = DiagnosticBuilder::new(self, Warning, msg);
645         db.emit();
646     }
647
648     pub fn note_without_error(&self, msg: &str) {
649         DiagnosticBuilder::new(self, Note, msg).emit();
650     }
651
652     pub fn bug(&self, msg: &str) -> ! {
653         self.inner.borrow_mut().bug(msg)
654     }
655
656     pub fn err_count(&self) -> usize {
657         self.inner.borrow().err_count()
658     }
659
660     pub fn has_errors(&self) -> bool {
661         self.inner.borrow().has_errors()
662     }
663     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
664         self.inner.borrow().has_errors_or_delayed_span_bugs()
665     }
666
667     pub fn print_error_count(&self, registry: &Registry) {
668         self.inner.borrow_mut().print_error_count(registry)
669     }
670
671     pub fn abort_if_errors(&self) {
672         self.inner.borrow_mut().abort_if_errors()
673     }
674
675     pub fn abort_if_errors_and_should_abort(&self) {
676         self.inner.borrow_mut().abort_if_errors_and_should_abort()
677     }
678
679     /// `true` if we haven't taught a diagnostic with this code already.
680     /// The caller must then teach the user about such a diagnostic.
681     ///
682     /// Used to suppress emitting the same error multiple times with extended explanation when
683     /// calling `-Zteach`.
684     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
685         self.inner.borrow_mut().must_teach(code)
686     }
687
688     pub fn force_print_diagnostic(&self, db: Diagnostic) {
689         self.inner.borrow_mut().force_print_diagnostic(db)
690     }
691
692     pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
693         self.inner.borrow_mut().emit_diagnostic(diagnostic)
694     }
695
696     fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
697         let mut inner = self.inner.borrow_mut();
698         inner.emit_diagnostic(diag.set_span(sp));
699         inner.abort_if_errors_and_should_abort();
700     }
701
702     pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
703         self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
704     }
705
706     pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
707         self.inner.borrow_mut().delay_as_bug(diagnostic)
708     }
709 }
710
711 impl HandlerInner {
712     fn must_teach(&mut self, code: &DiagnosticId) -> bool {
713         self.taught_diagnostics.insert(code.clone())
714     }
715
716     fn force_print_diagnostic(&mut self, db: Diagnostic) {
717         self.emitter.emit_diagnostic(&db);
718     }
719
720     /// Emit all stashed diagnostics.
721     fn emit_stashed_diagnostics(&mut self) {
722         let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
723         diags.iter().for_each(|diag| self.emit_diagnostic(diag));
724     }
725
726     fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
727         if diagnostic.cancelled() {
728             return;
729         }
730
731         if diagnostic.level == Warning && !self.flags.can_emit_warnings {
732             return;
733         }
734
735         (*TRACK_DIAGNOSTICS)(diagnostic);
736
737         if let Some(ref code) = diagnostic.code {
738             self.emitted_diagnostic_codes.insert(code.clone());
739         }
740
741         let already_emitted = |this: &mut Self| {
742             use std::hash::Hash;
743             let mut hasher = StableHasher::new();
744             diagnostic.hash(&mut hasher);
745             let diagnostic_hash = hasher.finish();
746             !this.emitted_diagnostics.insert(diagnostic_hash)
747         };
748
749         // Only emit the diagnostic if we've been asked to deduplicate and
750         // haven't already emitted an equivalent diagnostic.
751         if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
752             self.emitter.emit_diagnostic(diagnostic);
753             if diagnostic.is_error() {
754                 self.deduplicated_err_count += 1;
755             }
756         }
757         if diagnostic.is_error() {
758             self.bump_err_count();
759         }
760     }
761
762     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
763         self.emitter.emit_artifact_notification(path, artifact_type);
764     }
765
766     fn treat_err_as_bug(&self) -> bool {
767         self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
768     }
769
770     fn print_error_count(&mut self, registry: &Registry) {
771         self.emit_stashed_diagnostics();
772
773         let s = match self.deduplicated_err_count {
774             0 => return,
775             1 => "aborting due to previous error".to_string(),
776             count => format!("aborting due to {} previous errors", count),
777         };
778         if self.treat_err_as_bug() {
779             return;
780         }
781
782         let _ = self.fatal(&s);
783
784         let can_show_explain = self.emitter.should_show_explain();
785         let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
786         if can_show_explain && are_there_diagnostics {
787             let mut error_codes = self
788                 .emitted_diagnostic_codes
789                 .iter()
790                 .filter_map(|x| match &x {
791                     DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
792                         Some(s.clone())
793                     }
794                     _ => None,
795                 })
796                 .collect::<Vec<_>>();
797             if !error_codes.is_empty() {
798                 error_codes.sort();
799                 if error_codes.len() > 1 {
800                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
801                     self.failure(&format!(
802                         "Some errors have detailed explanations: {}{}",
803                         error_codes[..limit].join(", "),
804                         if error_codes.len() > 9 { "..." } else { "." }
805                     ));
806                     self.failure(&format!(
807                         "For more information about an error, try \
808                                            `rustc --explain {}`.",
809                         &error_codes[0]
810                     ));
811                 } else {
812                     self.failure(&format!(
813                         "For more information about this error, try \
814                                            `rustc --explain {}`.",
815                         &error_codes[0]
816                     ));
817                 }
818             }
819         }
820     }
821
822     fn err_count(&self) -> usize {
823         self.err_count + self.stashed_diagnostics.len()
824     }
825
826     fn has_errors(&self) -> bool {
827         self.err_count() > 0
828     }
829     fn has_errors_or_delayed_span_bugs(&self) -> bool {
830         self.has_errors() || !self.delayed_span_bugs.is_empty()
831     }
832
833     fn abort_if_errors_and_should_abort(&mut self) {
834         self.emit_stashed_diagnostics();
835
836         if self.has_errors() && !self.continue_after_error {
837             FatalError.raise();
838         }
839     }
840
841     fn abort_if_errors(&mut self) {
842         self.emit_stashed_diagnostics();
843
844         if self.has_errors() {
845             FatalError.raise();
846         }
847     }
848
849     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
850         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
851         panic!(ExplicitBug);
852     }
853
854     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
855         self.emit_diagnostic(diag.set_span(sp));
856         self.abort_if_errors_and_should_abort();
857     }
858
859     fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
860         if self.treat_err_as_bug() {
861             // FIXME: don't abort here if report_delayed_bugs is off
862             self.span_bug(sp, msg);
863         }
864         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
865         diagnostic.set_span(sp.into());
866         self.delay_as_bug(diagnostic)
867     }
868
869     fn failure(&mut self, msg: &str) {
870         self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
871     }
872
873     fn fatal(&mut self, msg: &str) -> FatalError {
874         self.emit_error(Fatal, msg);
875         FatalError
876     }
877
878     fn err(&mut self, msg: &str) {
879         self.emit_error(Error, msg);
880     }
881
882     /// Emit an error; level should be `Error` or `Fatal`.
883     fn emit_error(&mut self, level: Level, msg: &str) {
884         if self.treat_err_as_bug() {
885             self.bug(msg);
886         }
887         self.emit_diagnostic(&Diagnostic::new(level, msg));
888     }
889
890     fn bug(&mut self, msg: &str) -> ! {
891         self.emit_diagnostic(&Diagnostic::new(Bug, msg));
892         panic!(ExplicitBug);
893     }
894
895     fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
896         if self.flags.report_delayed_bugs {
897             self.emit_diagnostic(&diagnostic);
898         }
899         self.delayed_span_bugs.push(diagnostic);
900     }
901
902     fn bump_err_count(&mut self) {
903         self.err_count += 1;
904         self.panic_if_treat_err_as_bug();
905     }
906
907     fn panic_if_treat_err_as_bug(&self) {
908         if self.treat_err_as_bug() {
909             let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
910                 (0, _) => return,
911                 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
912                 (1, _) => return,
913                 (count, as_bug) => format!(
914                     "aborting after {} errors due to `-Z treat-err-as-bug={}`",
915                     count, as_bug,
916                 ),
917             };
918             panic!(s);
919         }
920     }
921 }
922
923 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
924 pub enum Level {
925     Bug,
926     Fatal,
927     Error,
928     Warning,
929     Note,
930     Help,
931     Cancelled,
932     FailureNote,
933 }
934
935 impl fmt::Display for Level {
936     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
937         self.to_str().fmt(f)
938     }
939 }
940
941 impl Level {
942     fn color(self) -> ColorSpec {
943         let mut spec = ColorSpec::new();
944         match self {
945             Bug | Fatal | Error => {
946                 spec.set_fg(Some(Color::Red)).set_intense(true);
947             }
948             Warning => {
949                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
950             }
951             Note => {
952                 spec.set_fg(Some(Color::Green)).set_intense(true);
953             }
954             Help => {
955                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
956             }
957             FailureNote => {}
958             Cancelled => unreachable!(),
959         }
960         spec
961     }
962
963     pub fn to_str(self) -> &'static str {
964         match self {
965             Bug => "error: internal compiler error",
966             Fatal | Error => "error",
967             Warning => "warning",
968             Note => "note",
969             Help => "help",
970             FailureNote => "failure-note",
971             Cancelled => panic!("Shouldn't call on cancelled error"),
972         }
973     }
974
975     pub fn is_failure_note(&self) -> bool {
976         match *self {
977             FailureNote => true,
978             _ => false,
979         }
980     }
981 }
982
983 #[macro_export]
984 macro_rules! pluralize {
985     ($x:expr) => {
986         if $x != 1 { "s" } else { "" }
987     };
988 }
989
990 // Useful type to use with `Result<>` indicate that an error has already
991 // been reported to the user, so no need to continue checking.
992 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
993 pub struct ErrorReported;
994
995 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);