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