]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
827e9b831f32d711978c1b0c960fc90aabc4ab49
[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 log::debug;
14 use Level::*;
15
16 use emitter::{is_case_difference, Emitter, EmitterWriter};
17 use registry::Registry;
18 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
19 use rustc_data_structures::stable_hasher::StableHasher;
20 use rustc_data_structures::sync::{self, Lock, Lrc};
21 use rustc_data_structures::AtomicRef;
22 use rustc_span::source_map::SourceMap;
23 use rustc_span::{Loc, MultiSpan, Span};
24
25 use std::borrow::Cow;
26 use std::panic;
27 use std::path::Path;
28 use std::{error, fmt};
29
30 use termcolor::{Color, ColorSpec};
31
32 pub mod annotate_snippet_emitter_writer;
33 mod diagnostic;
34 mod diagnostic_builder;
35 pub mod emitter;
36 pub mod json;
37 mod lock;
38 pub mod registry;
39 mod snippet;
40 mod styled_buffer;
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(&self, cm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
150         use rustc_span::{CharPos, Pos};
151
152         fn push_trailing(
153             buf: &mut String,
154             line_opt: Option<&Cow<'_, str>>,
155             lo: &Loc,
156             hi_opt: Option<&Loc>,
157         ) {
158             let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
159             if let Some(line) = line_opt {
160                 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
161                     let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
162                     match hi_opt {
163                         Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
164                         Some(_) => (),
165                         None => buf.push_str(&line[lo..]),
166                     }
167                 }
168                 if let None = hi_opt {
169                     buf.push('\n');
170                 }
171             }
172         }
173
174         assert!(!self.substitutions.is_empty());
175
176         self.substitutions
177             .iter()
178             .filter(|subst| {
179                 // Suggestions coming from macros can have malformed spans. This is a heavy
180                 // handed approach to avoid ICEs by ignoring the suggestion outright.
181                 let invalid = subst.parts.iter().any(|item| cm.is_valid_span(item.span).is_err());
182                 if invalid {
183                     debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
184                 }
185                 !invalid
186             })
187             .cloned()
188             .map(|mut substitution| {
189                 // Assumption: all spans are in the same file, and all spans
190                 // are disjoint. Sort in ascending order.
191                 substitution.parts.sort_by_key(|part| part.span.lo());
192
193                 // Find the bounding span.
194                 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
195                 let hi = substitution.parts.iter().map(|part| part.span.hi()).max().unwrap();
196                 let bounding_span = Span::with_root_ctxt(lo, hi);
197                 let lines = cm.span_to_lines(bounding_span).unwrap();
198                 assert!(!lines.lines.is_empty());
199
200                 // To build up the result, we do this for each span:
201                 // - push the line segment trailing the previous span
202                 //   (at the beginning a "phantom" span pointing at the start of the line)
203                 // - push lines between the previous and current span (if any)
204                 // - if the previous and current span are not on the same line
205                 //   push the line segment leading up to the current span
206                 // - splice in the span substitution
207                 //
208                 // Finally push the trailing line segment of the last span
209                 let fm = &lines.file;
210                 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
211                 prev_hi.col = CharPos::from_usize(0);
212
213                 let mut prev_line = fm.get_line(lines.lines[0].line_index);
214                 let mut buf = String::new();
215
216                 for part in &substitution.parts {
217                     let cur_lo = cm.lookup_char_pos(part.span.lo());
218                     if prev_hi.line == cur_lo.line {
219                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
220                     } else {
221                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
222                         // push lines between the previous and current span (if any)
223                         for idx in prev_hi.line..(cur_lo.line - 1) {
224                             if let Some(line) = fm.get_line(idx) {
225                                 buf.push_str(line.as_ref());
226                                 buf.push('\n');
227                             }
228                         }
229                         if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
230                             let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
231                             buf.push_str(&cur_line[..end]);
232                         }
233                     }
234                     buf.push_str(&part.snippet);
235                     prev_hi = cm.lookup_char_pos(part.span.hi());
236                     prev_line = fm.get_line(prev_hi.line - 1);
237                 }
238                 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
239                 // if the replacement already ends with a newline, don't print the next line
240                 if !buf.ends_with('\n') {
241                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
242                 }
243                 // remove trailing newlines
244                 while buf.ends_with('\n') {
245                     buf.pop();
246                 }
247                 (buf, substitution.parts, only_capitalization)
248             })
249             .collect()
250     }
251 }
252
253 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
254
255 /// Signifies that the compiler died with an explicit call to `.bug`
256 /// or `.span_bug` rather than a failed assertion, etc.
257 #[derive(Copy, Clone, Debug)]
258 pub struct ExplicitBug;
259
260 impl fmt::Display for ExplicitBug {
261     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262         write!(f, "parser internal bug")
263     }
264 }
265
266 impl error::Error for ExplicitBug {}
267
268 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
269 pub use diagnostic_builder::DiagnosticBuilder;
270
271 /// A handler deals with errors and other compiler output.
272 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
273 /// others log errors for later reporting.
274 pub struct Handler {
275     flags: HandlerFlags,
276     inner: Lock<HandlerInner>,
277 }
278
279 /// This inner struct exists to keep it all behind a single lock;
280 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
281 /// as well as inconsistent state observation.
282 struct HandlerInner {
283     flags: HandlerFlags,
284     /// The number of errors that have been emitted, including duplicates.
285     ///
286     /// This is not necessarily the count that's reported to the user once
287     /// compilation ends.
288     err_count: usize,
289     deduplicated_err_count: usize,
290     emitter: Box<dyn Emitter + sync::Send>,
291     delayed_span_bugs: Vec<Diagnostic>,
292
293     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
294     /// emitting the same diagnostic with extended help (`--teach`) twice, which
295     /// would be uneccessary repetition.
296     taught_diagnostics: FxHashSet<DiagnosticId>,
297
298     /// Used to suggest rustc --explain <error code>
299     emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
300
301     /// This set contains a hash of every diagnostic that has been emitted by
302     /// this handler. These hashes is used to avoid emitting the same error
303     /// twice.
304     emitted_diagnostics: FxHashSet<u128>,
305
306     /// Stashed diagnostics emitted in one stage of the compiler that may be
307     /// stolen by other stages (e.g. to improve them and add more information).
308     /// The stashed diagnostics count towards the total error count.
309     /// When `.abort_if_errors()` is called, these are also emitted.
310     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
311 }
312
313 /// A key denoting where from a diagnostic was stashed.
314 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
315 pub enum StashKey {
316     ItemNoType,
317 }
318
319 fn default_track_diagnostic(_: &Diagnostic) {}
320
321 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
322     AtomicRef::new(&(default_track_diagnostic as fn(&_)));
323
324 #[derive(Copy, Clone, Default)]
325 pub struct HandlerFlags {
326     /// If false, warning-level lints are suppressed.
327     /// (rustc: see `--allow warnings` and `--cap-lints`)
328     pub can_emit_warnings: bool,
329     /// If true, error-level diagnostics are upgraded to bug-level.
330     /// (rustc: see `-Z treat-err-as-bug`)
331     pub treat_err_as_bug: Option<usize>,
332     /// If true, immediately emit diagnostics that would otherwise be buffered.
333     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
334     pub dont_buffer_diagnostics: bool,
335     /// If true, immediately print bugs registered with `delay_span_bug`.
336     /// (rustc: see `-Z report-delayed-bugs`)
337     pub report_delayed_bugs: bool,
338     /// show macro backtraces even for non-local macros.
339     /// (rustc: see `-Z external-macro-backtrace`)
340     pub external_macro_backtrace: bool,
341     /// If true, identical diagnostics are reported only once.
342     pub deduplicate_diagnostics: bool,
343 }
344
345 impl Drop for HandlerInner {
346     fn drop(&mut self) {
347         self.emit_stashed_diagnostics();
348
349         if !self.has_errors() {
350             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
351             let has_bugs = !bugs.is_empty();
352             for bug in bugs {
353                 self.emit_diagnostic(&bug);
354             }
355             if has_bugs {
356                 panic!("no errors encountered even though `delay_span_bug` issued");
357             }
358         }
359     }
360 }
361
362 impl Handler {
363     pub fn with_tty_emitter(
364         color_config: ColorConfig,
365         can_emit_warnings: bool,
366         treat_err_as_bug: Option<usize>,
367         cm: Option<Lrc<SourceMap>>,
368     ) -> Self {
369         Self::with_tty_emitter_and_flags(
370             color_config,
371             cm,
372             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
373         )
374     }
375
376     pub fn with_tty_emitter_and_flags(
377         color_config: ColorConfig,
378         cm: Option<Lrc<SourceMap>>,
379         flags: HandlerFlags,
380     ) -> Self {
381         let emitter = Box::new(EmitterWriter::stderr(
382             color_config,
383             cm,
384             false,
385             false,
386             None,
387             flags.external_macro_backtrace,
388         ));
389         Self::with_emitter_and_flags(emitter, flags)
390     }
391
392     pub fn with_emitter(
393         can_emit_warnings: bool,
394         treat_err_as_bug: Option<usize>,
395         emitter: Box<dyn Emitter + sync::Send>,
396     ) -> Self {
397         Handler::with_emitter_and_flags(
398             emitter,
399             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
400         )
401     }
402
403     pub fn with_emitter_and_flags(
404         emitter: Box<dyn Emitter + sync::Send>,
405         flags: HandlerFlags,
406     ) -> Self {
407         Self {
408             flags,
409             inner: Lock::new(HandlerInner {
410                 flags,
411                 err_count: 0,
412                 deduplicated_err_count: 0,
413                 emitter,
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     // This is here to not allow mutation of flags;
424     // as of this writing it's only used in tests in librustc.
425     pub fn can_emit_warnings(&self) -> bool {
426         self.flags.can_emit_warnings
427     }
428
429     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
430     ///
431     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
432     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
433     /// the overall count of emitted error diagnostics.
434     pub fn reset_err_count(&self) {
435         let mut inner = self.inner.borrow_mut();
436         inner.err_count = 0;
437         inner.deduplicated_err_count = 0;
438
439         // actually free the underlying memory (which `clear` would not do)
440         inner.delayed_span_bugs = Default::default();
441         inner.taught_diagnostics = Default::default();
442         inner.emitted_diagnostic_codes = Default::default();
443         inner.emitted_diagnostics = Default::default();
444         inner.stashed_diagnostics = Default::default();
445     }
446
447     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
448     /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
449     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
450         let mut inner = self.inner.borrow_mut();
451         if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
452             // We are removing a previously stashed diagnostic which should not happen.
453             old_diag.level = Bug;
454             old_diag.note(&format!(
455                 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
456                 file!(),
457                 line!(),
458                 span,
459                 key
460             ));
461             inner.emit_diag_at_span(old_diag, span);
462             panic!(ExplicitBug);
463         }
464     }
465
466     /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
467     pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
468         self.inner
469             .borrow_mut()
470             .stashed_diagnostics
471             .remove(&(span, key))
472             .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
473     }
474
475     /// Emit all stashed diagnostics.
476     pub fn emit_stashed_diagnostics(&self) {
477         self.inner.borrow_mut().emit_stashed_diagnostics();
478     }
479
480     /// Construct a dummy builder with `Level::Cancelled`.
481     ///
482     /// Using this will neither report anything to the user (e.g. a warning),
483     /// nor will compilation cancel as a result.
484     pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
485         DiagnosticBuilder::new(self, Level::Cancelled, "")
486     }
487
488     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
489     pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
490         let mut result = self.struct_warn(msg);
491         result.set_span(span);
492         result
493     }
494
495     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
496     /// Also include a code.
497     pub fn struct_span_warn_with_code(
498         &self,
499         span: impl Into<MultiSpan>,
500         msg: &str,
501         code: DiagnosticId,
502     ) -> DiagnosticBuilder<'_> {
503         let mut result = self.struct_span_warn(span, msg);
504         result.code(code);
505         result
506     }
507
508     /// Construct a builder at the `Warning` level with the `msg`.
509     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
510         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
511         if !self.flags.can_emit_warnings {
512             result.cancel();
513         }
514         result
515     }
516
517     /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
518     pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
519         let mut result = self.struct_err(msg);
520         result.set_span(span);
521         result
522     }
523
524     /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
525     pub fn struct_span_err_with_code(
526         &self,
527         span: impl Into<MultiSpan>,
528         msg: &str,
529         code: DiagnosticId,
530     ) -> DiagnosticBuilder<'_> {
531         let mut result = self.struct_span_err(span, msg);
532         result.code(code);
533         result
534     }
535
536     /// Construct a builder at the `Error` level with the `msg`.
537     // FIXME: This method should be removed (every error should have an associated error code).
538     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
539         DiagnosticBuilder::new(self, Level::Error, msg)
540     }
541
542     /// Construct a builder at the `Error` level with the `msg` and the `code`.
543     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
544         let mut result = self.struct_err(msg);
545         result.code(code);
546         result
547     }
548
549     /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
550     pub fn struct_span_fatal(
551         &self,
552         span: impl Into<MultiSpan>,
553         msg: &str,
554     ) -> DiagnosticBuilder<'_> {
555         let mut result = self.struct_fatal(msg);
556         result.set_span(span);
557         result
558     }
559
560     /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
561     pub fn struct_span_fatal_with_code(
562         &self,
563         span: impl Into<MultiSpan>,
564         msg: &str,
565         code: DiagnosticId,
566     ) -> DiagnosticBuilder<'_> {
567         let mut result = self.struct_span_fatal(span, msg);
568         result.code(code);
569         result
570     }
571
572     /// Construct a builder at the `Error` level with the `msg`.
573     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
574         DiagnosticBuilder::new(self, Level::Fatal, msg)
575     }
576
577     /// Construct a builder at the `Help` level with the `msg`.
578     pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
579         DiagnosticBuilder::new(self, Level::Help, msg)
580     }
581
582     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
583         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
584         FatalError
585     }
586
587     pub fn span_fatal_with_code(
588         &self,
589         span: impl Into<MultiSpan>,
590         msg: &str,
591         code: DiagnosticId,
592     ) -> FatalError {
593         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
594         FatalError
595     }
596
597     pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
598         self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
599     }
600
601     pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
602         self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
603     }
604
605     pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
606         self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
607     }
608
609     pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
610         self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
611     }
612
613     pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
614         self.inner.borrow_mut().span_bug(span, msg)
615     }
616
617     pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
618         self.inner.borrow_mut().delay_span_bug(span, msg)
619     }
620
621     pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
622         self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
623     }
624
625     pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
626         self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
627     }
628
629     pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
630         let mut db = DiagnosticBuilder::new(self, Note, msg);
631         db.set_span(span);
632         db
633     }
634
635     pub fn failure(&self, msg: &str) {
636         self.inner.borrow_mut().failure(msg);
637     }
638
639     pub fn fatal(&self, msg: &str) -> FatalError {
640         self.inner.borrow_mut().fatal(msg)
641     }
642
643     pub fn err(&self, msg: &str) {
644         self.inner.borrow_mut().err(msg);
645     }
646
647     pub fn warn(&self, msg: &str) {
648         let mut db = DiagnosticBuilder::new(self, Warning, msg);
649         db.emit();
650     }
651
652     pub fn note_without_error(&self, msg: &str) {
653         DiagnosticBuilder::new(self, Note, msg).emit();
654     }
655
656     pub fn bug(&self, msg: &str) -> ! {
657         self.inner.borrow_mut().bug(msg)
658     }
659
660     pub fn err_count(&self) -> usize {
661         self.inner.borrow().err_count()
662     }
663
664     pub fn has_errors(&self) -> bool {
665         self.inner.borrow().has_errors()
666     }
667     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
668         self.inner.borrow().has_errors_or_delayed_span_bugs()
669     }
670
671     pub fn print_error_count(&self, registry: &Registry) {
672         self.inner.borrow_mut().print_error_count(registry)
673     }
674
675     pub fn abort_if_errors(&self) {
676         self.inner.borrow_mut().abort_if_errors()
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     }
700
701     pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
702         self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
703     }
704
705     pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
706         self.inner.borrow_mut().delay_as_bug(diagnostic)
707     }
708 }
709
710 impl HandlerInner {
711     fn must_teach(&mut self, code: &DiagnosticId) -> bool {
712         self.taught_diagnostics.insert(code.clone())
713     }
714
715     fn force_print_diagnostic(&mut self, db: Diagnostic) {
716         self.emitter.emit_diagnostic(&db);
717     }
718
719     /// Emit all stashed diagnostics.
720     fn emit_stashed_diagnostics(&mut self) {
721         let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
722         diags.iter().for_each(|diag| self.emit_diagnostic(diag));
723     }
724
725     fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
726         if diagnostic.cancelled() {
727             return;
728         }
729
730         if diagnostic.level == Warning && !self.flags.can_emit_warnings {
731             return;
732         }
733
734         (*TRACK_DIAGNOSTICS)(diagnostic);
735
736         if let Some(ref code) = diagnostic.code {
737             self.emitted_diagnostic_codes.insert(code.clone());
738         }
739
740         let already_emitted = |this: &mut Self| {
741             use std::hash::Hash;
742             let mut hasher = StableHasher::new();
743             diagnostic.hash(&mut hasher);
744             let diagnostic_hash = hasher.finish();
745             !this.emitted_diagnostics.insert(diagnostic_hash)
746         };
747
748         // Only emit the diagnostic if we've been asked to deduplicate and
749         // haven't already emitted an equivalent diagnostic.
750         if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
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!(
801                         "Some errors have detailed explanations: {}{}",
802                         error_codes[..limit].join(", "),
803                         if error_codes.len() > 9 { "..." } else { "." }
804                     ));
805                     self.failure(&format!(
806                         "For more information about an error, try \
807                                            `rustc --explain {}`.",
808                         &error_codes[0]
809                     ));
810                 } else {
811                     self.failure(&format!(
812                         "For more information about this error, try \
813                                            `rustc --explain {}`.",
814                         &error_codes[0]
815                     ));
816                 }
817             }
818         }
819     }
820
821     fn err_count(&self) -> usize {
822         self.err_count + self.stashed_diagnostics.len()
823     }
824
825     fn has_errors(&self) -> bool {
826         self.err_count() > 0
827     }
828     fn has_errors_or_delayed_span_bugs(&self) -> bool {
829         self.has_errors() || !self.delayed_span_bugs.is_empty()
830     }
831
832     fn abort_if_errors(&mut self) {
833         self.emit_stashed_diagnostics();
834
835         if self.has_errors() {
836             FatalError.raise();
837         }
838     }
839
840     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
841         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
842         panic!(ExplicitBug);
843     }
844
845     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
846         self.emit_diagnostic(diag.set_span(sp));
847     }
848
849     fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
850         if self.treat_err_as_bug() {
851             // FIXME: don't abort here if report_delayed_bugs is off
852             self.span_bug(sp, msg);
853         }
854         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
855         diagnostic.set_span(sp.into());
856         self.delay_as_bug(diagnostic)
857     }
858
859     fn failure(&mut self, msg: &str) {
860         self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
861     }
862
863     fn fatal(&mut self, msg: &str) -> FatalError {
864         self.emit_error(Fatal, msg);
865         FatalError
866     }
867
868     fn err(&mut self, msg: &str) {
869         self.emit_error(Error, msg);
870     }
871
872     /// Emit an error; level should be `Error` or `Fatal`.
873     fn emit_error(&mut self, level: Level, msg: &str) {
874         if self.treat_err_as_bug() {
875             self.bug(msg);
876         }
877         self.emit_diagnostic(&Diagnostic::new(level, msg));
878     }
879
880     fn bug(&mut self, msg: &str) -> ! {
881         self.emit_diagnostic(&Diagnostic::new(Bug, msg));
882         panic!(ExplicitBug);
883     }
884
885     fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
886         if self.flags.report_delayed_bugs {
887             self.emit_diagnostic(&diagnostic);
888         }
889         self.delayed_span_bugs.push(diagnostic);
890     }
891
892     fn bump_err_count(&mut self) {
893         self.err_count += 1;
894         self.panic_if_treat_err_as_bug();
895     }
896
897     fn panic_if_treat_err_as_bug(&self) {
898         if self.treat_err_as_bug() {
899             let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
900                 (0, _) => return,
901                 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
902                 (1, _) => return,
903                 (count, as_bug) => format!(
904                     "aborting after {} errors due to `-Z treat-err-as-bug={}`",
905                     count, as_bug,
906                 ),
907             };
908             panic!(s);
909         }
910     }
911 }
912
913 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
914 pub enum Level {
915     Bug,
916     Fatal,
917     Error,
918     Warning,
919     Note,
920     Help,
921     Cancelled,
922     FailureNote,
923 }
924
925 impl fmt::Display for Level {
926     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
927         self.to_str().fmt(f)
928     }
929 }
930
931 impl Level {
932     fn color(self) -> ColorSpec {
933         let mut spec = ColorSpec::new();
934         match self {
935             Bug | Fatal | Error => {
936                 spec.set_fg(Some(Color::Red)).set_intense(true);
937             }
938             Warning => {
939                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
940             }
941             Note => {
942                 spec.set_fg(Some(Color::Green)).set_intense(true);
943             }
944             Help => {
945                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
946             }
947             FailureNote => {}
948             Cancelled => unreachable!(),
949         }
950         spec
951     }
952
953     pub fn to_str(self) -> &'static str {
954         match self {
955             Bug => "error: internal compiler error",
956             Fatal | Error => "error",
957             Warning => "warning",
958             Note => "note",
959             Help => "help",
960             FailureNote => "failure-note",
961             Cancelled => panic!("Shouldn't call on cancelled error"),
962         }
963     }
964
965     pub fn is_failure_note(&self) -> bool {
966         match *self {
967             FailureNote => true,
968             _ => false,
969         }
970     }
971 }
972
973 #[macro_export]
974 macro_rules! pluralize {
975     ($x:expr) => {
976         if $x != 1 { "s" } else { "" }
977     };
978 }
979
980 // Useful type to use with `Result<>` indicate that an error has already
981 // been reported to the user, so no need to continue checking.
982 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
983 pub struct ErrorReported;
984
985 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);