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