]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Auto merge of #69393 - Dylan-DPC:rollup-rxbd1zg, r=Dylan-DPC
[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 #![feature(nll)]
8
9 pub use emitter::ColorConfig;
10
11 use log::debug;
12 use Level::*;
13
14 use emitter::{is_case_difference, Emitter, EmitterWriter};
15 use registry::Registry;
16 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
17 use rustc_data_structures::stable_hasher::StableHasher;
18 use rustc_data_structures::sync::{self, Lock, Lrc};
19 use rustc_data_structures::AtomicRef;
20 use rustc_span::source_map::SourceMap;
21 use rustc_span::{Loc, MultiSpan, Span};
22
23 use std::borrow::Cow;
24 use std::panic;
25 use std::path::Path;
26 use std::{error, fmt};
27
28 use termcolor::{Color, ColorSpec};
29
30 pub mod annotate_snippet_emitter_writer;
31 mod diagnostic;
32 mod diagnostic_builder;
33 pub mod emitter;
34 pub mod json;
35 mod lock;
36 pub mod registry;
37 mod snippet;
38 mod styled_buffer;
39 pub use snippet::Style;
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(&self, sm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
148         use rustc_span::{CharPos, Pos};
149
150         fn push_trailing(
151             buf: &mut String,
152             line_opt: Option<&Cow<'_, str>>,
153             lo: &Loc,
154             hi_opt: Option<&Loc>,
155         ) {
156             let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
157             if let Some(line) = line_opt {
158                 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
159                     let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
160                     match hi_opt {
161                         Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
162                         Some(_) => (),
163                         None => buf.push_str(&line[lo..]),
164                     }
165                 }
166                 if let None = hi_opt {
167                     buf.push('\n');
168                 }
169             }
170         }
171
172         assert!(!self.substitutions.is_empty());
173
174         self.substitutions
175             .iter()
176             .filter(|subst| {
177                 // Suggestions coming from macros can have malformed spans. This is a heavy
178                 // handed approach to avoid ICEs by ignoring the suggestion outright.
179                 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
180                 if invalid {
181                     debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
182                 }
183                 !invalid
184             })
185             .cloned()
186             .filter_map(|mut substitution| {
187                 // Assumption: all spans are in the same file, and all spans
188                 // are disjoint. Sort in ascending order.
189                 substitution.parts.sort_by_key(|part| part.span.lo());
190
191                 // Find the bounding span.
192                 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
193                 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
194                 let bounding_span = Span::with_root_ctxt(lo, hi);
195                 // The different spans might belong to different contexts, if so ignore suggestion.
196                 let lines = sm.span_to_lines(bounding_span).ok()?;
197                 assert!(!lines.lines.is_empty());
198
199                 // To build up the result, we do this for each span:
200                 // - push the line segment trailing the previous span
201                 //   (at the beginning a "phantom" span pointing at the start of the line)
202                 // - push lines between the previous and current span (if any)
203                 // - if the previous and current span are not on the same line
204                 //   push the line segment leading up to the current span
205                 // - splice in the span substitution
206                 //
207                 // Finally push the trailing line segment of the last span
208                 let sf = &lines.file;
209                 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
210                 prev_hi.col = CharPos::from_usize(0);
211
212                 let mut prev_line = sf.get_line(lines.lines[0].line_index);
213                 let mut buf = String::new();
214
215                 for part in &substitution.parts {
216                     let cur_lo = sm.lookup_char_pos(part.span.lo());
217                     if prev_hi.line == cur_lo.line {
218                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
219                     } else {
220                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
221                         // push lines between the previous and current span (if any)
222                         for idx in prev_hi.line..(cur_lo.line - 1) {
223                             if let Some(line) = sf.get_line(idx) {
224                                 buf.push_str(line.as_ref());
225                                 buf.push('\n');
226                             }
227                         }
228                         if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
229                             let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
230                             buf.push_str(&cur_line[..end]);
231                         }
232                     }
233                     buf.push_str(&part.snippet);
234                     prev_hi = sm.lookup_char_pos(part.span.hi());
235                     prev_line = sf.get_line(prev_hi.line - 1);
236                 }
237                 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
238                 // if the replacement already ends with a newline, don't print the next line
239                 if !buf.ends_with('\n') {
240                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
241                 }
242                 // remove trailing newlines
243                 while buf.ends_with('\n') {
244                     buf.pop();
245                 }
246                 Some((buf, substitution.parts, only_capitalization))
247             })
248             .collect()
249     }
250 }
251
252 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
253
254 /// Signifies that the compiler died with an explicit call to `.bug`
255 /// or `.span_bug` rather than a failed assertion, etc.
256 #[derive(Copy, Clone, Debug)]
257 pub struct ExplicitBug;
258
259 impl fmt::Display for ExplicitBug {
260     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261         write!(f, "parser internal bug")
262     }
263 }
264
265 impl error::Error for ExplicitBug {}
266
267 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
268 pub use diagnostic_builder::DiagnosticBuilder;
269
270 /// A handler deals with errors and other compiler output.
271 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
272 /// others log errors for later reporting.
273 pub struct Handler {
274     flags: HandlerFlags,
275     inner: Lock<HandlerInner>,
276 }
277
278 /// This inner struct exists to keep it all behind a single lock;
279 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
280 /// as well as inconsistent state observation.
281 struct HandlerInner {
282     flags: HandlerFlags,
283     /// The number of errors that have been emitted, including duplicates.
284     ///
285     /// This is not necessarily the count that's reported to the user once
286     /// compilation ends.
287     err_count: usize,
288     deduplicated_err_count: usize,
289     emitter: Box<dyn Emitter + sync::Send>,
290     delayed_span_bugs: Vec<Diagnostic>,
291
292     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
293     /// emitting the same diagnostic with extended help (`--teach`) twice, which
294     /// would be uneccessary repetition.
295     taught_diagnostics: FxHashSet<DiagnosticId>,
296
297     /// Used to suggest rustc --explain <error code>
298     emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
299
300     /// This set contains a hash of every diagnostic that has been emitted by
301     /// this handler. These hashes is used to avoid emitting the same error
302     /// twice.
303     emitted_diagnostics: FxHashSet<u128>,
304
305     /// Stashed diagnostics emitted in one stage of the compiler that may be
306     /// stolen by other stages (e.g. to improve them and add more information).
307     /// The stashed diagnostics count towards the total error count.
308     /// When `.abort_if_errors()` is called, these are also emitted.
309     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
310 }
311
312 /// A key denoting where from a diagnostic was stashed.
313 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
314 pub enum StashKey {
315     ItemNoType,
316 }
317
318 fn default_track_diagnostic(_: &Diagnostic) {}
319
320 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
321     AtomicRef::new(&(default_track_diagnostic as fn(&_)));
322
323 #[derive(Copy, Clone, Default)]
324 pub struct HandlerFlags {
325     /// If false, warning-level lints are suppressed.
326     /// (rustc: see `--allow warnings` and `--cap-lints`)
327     pub can_emit_warnings: bool,
328     /// If true, error-level diagnostics are upgraded to bug-level.
329     /// (rustc: see `-Z treat-err-as-bug`)
330     pub treat_err_as_bug: Option<usize>,
331     /// If true, immediately emit diagnostics that would otherwise be buffered.
332     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
333     pub dont_buffer_diagnostics: bool,
334     /// If true, immediately print bugs registered with `delay_span_bug`.
335     /// (rustc: see `-Z report-delayed-bugs`)
336     pub report_delayed_bugs: bool,
337     /// Show macro backtraces.
338     /// (rustc: see `-Z macro-backtrace`)
339     pub macro_backtrace: bool,
340     /// If true, identical diagnostics are reported only once.
341     pub deduplicate_diagnostics: bool,
342 }
343
344 impl Drop for HandlerInner {
345     fn drop(&mut self) {
346         self.emit_stashed_diagnostics();
347
348         if !self.has_errors() {
349             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
350             let has_bugs = !bugs.is_empty();
351             for bug in bugs {
352                 self.emit_diagnostic(&bug);
353             }
354             if has_bugs {
355                 panic!("no errors encountered even though `delay_span_bug` issued");
356             }
357         }
358     }
359 }
360
361 impl Handler {
362     pub fn with_tty_emitter(
363         color_config: ColorConfig,
364         can_emit_warnings: bool,
365         treat_err_as_bug: Option<usize>,
366         sm: Option<Lrc<SourceMap>>,
367     ) -> Self {
368         Self::with_tty_emitter_and_flags(
369             color_config,
370             sm,
371             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
372         )
373     }
374
375     pub fn with_tty_emitter_and_flags(
376         color_config: ColorConfig,
377         sm: Option<Lrc<SourceMap>>,
378         flags: HandlerFlags,
379     ) -> Self {
380         let emitter = Box::new(EmitterWriter::stderr(
381             color_config,
382             sm,
383             false,
384             false,
385             None,
386             flags.macro_backtrace,
387         ));
388         Self::with_emitter_and_flags(emitter, flags)
389     }
390
391     pub fn with_emitter(
392         can_emit_warnings: bool,
393         treat_err_as_bug: Option<usize>,
394         emitter: Box<dyn Emitter + sync::Send>,
395     ) -> Self {
396         Handler::with_emitter_and_flags(
397             emitter,
398             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
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                 delayed_span_bugs: Vec::new(),
414                 taught_diagnostics: Default::default(),
415                 emitted_diagnostic_codes: Default::default(),
416                 emitted_diagnostics: Default::default(),
417                 stashed_diagnostics: Default::default(),
418             }),
419         }
420     }
421
422     // This is here to not allow mutation of flags;
423     // as of this writing it's only used in tests in librustc.
424     pub fn can_emit_warnings(&self) -> bool {
425         self.flags.can_emit_warnings
426     }
427
428     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
429     ///
430     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
431     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
432     /// the overall count of emitted error diagnostics.
433     pub fn reset_err_count(&self) {
434         let mut inner = self.inner.borrow_mut();
435         inner.err_count = 0;
436         inner.deduplicated_err_count = 0;
437
438         // actually free the underlying memory (which `clear` would not do)
439         inner.delayed_span_bugs = Default::default();
440         inner.taught_diagnostics = Default::default();
441         inner.emitted_diagnostic_codes = Default::default();
442         inner.emitted_diagnostics = Default::default();
443         inner.stashed_diagnostics = Default::default();
444     }
445
446     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
447     /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
448     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
449         let mut inner = self.inner.borrow_mut();
450         if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
451             // We are removing a previously stashed diagnostic which should not happen.
452             old_diag.level = Bug;
453             old_diag.note(&format!(
454                 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
455                 file!(),
456                 line!(),
457                 span,
458                 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     /// Construct a builder at the `Help` level with the `msg`.
577     pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
578         DiagnosticBuilder::new(self, Level::Help, msg)
579     }
580
581     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
582         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
583         FatalError
584     }
585
586     pub fn span_fatal_with_code(
587         &self,
588         span: impl Into<MultiSpan>,
589         msg: &str,
590         code: DiagnosticId,
591     ) -> FatalError {
592         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
593         FatalError
594     }
595
596     pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
597         self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
598     }
599
600     pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
601         self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
602     }
603
604     pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
605         self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
606     }
607
608     pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
609         self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
610     }
611
612     pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
613         self.inner.borrow_mut().span_bug(span, msg)
614     }
615
616     pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
617         self.inner.borrow_mut().delay_span_bug(span, msg)
618     }
619
620     pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
621         self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
622     }
623
624     pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
625         self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
626     }
627
628     pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
629         let mut db = DiagnosticBuilder::new(self, Note, msg);
630         db.set_span(span);
631         db
632     }
633
634     pub fn failure(&self, msg: &str) {
635         self.inner.borrow_mut().failure(msg);
636     }
637
638     pub fn fatal(&self, msg: &str) -> FatalError {
639         self.inner.borrow_mut().fatal(msg)
640     }
641
642     pub fn err(&self, msg: &str) {
643         self.inner.borrow_mut().err(msg);
644     }
645
646     pub fn warn(&self, msg: &str) {
647         let mut db = DiagnosticBuilder::new(self, Warning, msg);
648         db.emit();
649     }
650
651     pub fn note_without_error(&self, msg: &str) {
652         DiagnosticBuilder::new(self, Note, msg).emit();
653     }
654
655     pub fn bug(&self, msg: &str) -> ! {
656         self.inner.borrow_mut().bug(msg)
657     }
658
659     pub fn err_count(&self) -> usize {
660         self.inner.borrow().err_count()
661     }
662
663     pub fn has_errors(&self) -> bool {
664         self.inner.borrow().has_errors()
665     }
666     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
667         self.inner.borrow().has_errors_or_delayed_span_bugs()
668     }
669
670     pub fn print_error_count(&self, registry: &Registry) {
671         self.inner.borrow_mut().print_error_count(registry)
672     }
673
674     pub fn abort_if_errors(&self) {
675         self.inner.borrow_mut().abort_if_errors()
676     }
677
678     /// `true` if we haven't taught a diagnostic with this code already.
679     /// The caller must then teach the user about such a diagnostic.
680     ///
681     /// Used to suppress emitting the same error multiple times with extended explanation when
682     /// calling `-Zteach`.
683     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
684         self.inner.borrow_mut().must_teach(code)
685     }
686
687     pub fn force_print_diagnostic(&self, db: Diagnostic) {
688         self.inner.borrow_mut().force_print_diagnostic(db)
689     }
690
691     pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
692         self.inner.borrow_mut().emit_diagnostic(diagnostic)
693     }
694
695     fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
696         let mut inner = self.inner.borrow_mut();
697         inner.emit_diagnostic(diag.set_span(sp));
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)(diagnostic);
734
735         if let Some(ref code) = diagnostic.code {
736             self.emitted_diagnostic_codes.insert(code.clone());
737         }
738
739         let already_emitted = |this: &mut Self| {
740             use std::hash::Hash;
741             let mut hasher = StableHasher::new();
742             diagnostic.hash(&mut hasher);
743             let diagnostic_hash = hasher.finish();
744             !this.emitted_diagnostics.insert(diagnostic_hash)
745         };
746
747         // Only emit the diagnostic if we've been asked to deduplicate and
748         // haven't already emitted an equivalent diagnostic.
749         if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
750             self.emitter.emit_diagnostic(diagnostic);
751             if diagnostic.is_error() {
752                 self.deduplicated_err_count += 1;
753             }
754         }
755         if diagnostic.is_error() {
756             self.bump_err_count();
757         }
758     }
759
760     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
761         self.emitter.emit_artifact_notification(path, artifact_type);
762     }
763
764     fn treat_err_as_bug(&self) -> bool {
765         self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
766     }
767
768     fn print_error_count(&mut self, registry: &Registry) {
769         self.emit_stashed_diagnostics();
770
771         let s = match self.deduplicated_err_count {
772             0 => return,
773             1 => "aborting due to previous error".to_string(),
774             count => format!("aborting due to {} previous errors", count),
775         };
776         if self.treat_err_as_bug() {
777             return;
778         }
779
780         let _ = self.fatal(&s);
781
782         let can_show_explain = self.emitter.should_show_explain();
783         let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
784         if can_show_explain && are_there_diagnostics {
785             let mut error_codes = self
786                 .emitted_diagnostic_codes
787                 .iter()
788                 .filter_map(|x| match &x {
789                     DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
790                         Some(s.clone())
791                     }
792                     _ => None,
793                 })
794                 .collect::<Vec<_>>();
795             if !error_codes.is_empty() {
796                 error_codes.sort();
797                 if error_codes.len() > 1 {
798                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
799                     self.failure(&format!(
800                         "Some errors have detailed explanations: {}{}",
801                         error_codes[..limit].join(", "),
802                         if error_codes.len() > 9 { "..." } else { "." }
803                     ));
804                     self.failure(&format!(
805                         "For more information about an error, try \
806                                            `rustc --explain {}`.",
807                         &error_codes[0]
808                     ));
809                 } else {
810                     self.failure(&format!(
811                         "For more information about this error, try \
812                                            `rustc --explain {}`.",
813                         &error_codes[0]
814                     ));
815                 }
816             }
817         }
818     }
819
820     fn err_count(&self) -> usize {
821         self.err_count + self.stashed_diagnostics.len()
822     }
823
824     fn has_errors(&self) -> bool {
825         self.err_count() > 0
826     }
827     fn has_errors_or_delayed_span_bugs(&self) -> bool {
828         self.has_errors() || !self.delayed_span_bugs.is_empty()
829     }
830
831     fn abort_if_errors(&mut self) {
832         self.emit_stashed_diagnostics();
833
834         if self.has_errors() {
835             FatalError.raise();
836         }
837     }
838
839     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
840         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
841         panic!(ExplicitBug);
842     }
843
844     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
845         self.emit_diagnostic(diag.set_span(sp));
846     }
847
848     fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
849         if self.treat_err_as_bug() {
850             // FIXME: don't abort here if report_delayed_bugs is off
851             self.span_bug(sp, msg);
852         }
853         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
854         diagnostic.set_span(sp.into());
855         self.delay_as_bug(diagnostic)
856     }
857
858     fn failure(&mut self, msg: &str) {
859         self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
860     }
861
862     fn fatal(&mut self, msg: &str) -> FatalError {
863         self.emit_error(Fatal, msg);
864         FatalError
865     }
866
867     fn err(&mut self, msg: &str) {
868         self.emit_error(Error, msg);
869     }
870
871     /// Emit an error; level should be `Error` or `Fatal`.
872     fn emit_error(&mut self, level: Level, msg: &str) {
873         if self.treat_err_as_bug() {
874             self.bug(msg);
875         }
876         self.emit_diagnostic(&Diagnostic::new(level, msg));
877     }
878
879     fn bug(&mut self, msg: &str) -> ! {
880         self.emit_diagnostic(&Diagnostic::new(Bug, msg));
881         panic!(ExplicitBug);
882     }
883
884     fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
885         if self.flags.report_delayed_bugs {
886             self.emit_diagnostic(&diagnostic);
887         }
888         self.delayed_span_bugs.push(diagnostic);
889     }
890
891     fn bump_err_count(&mut self) {
892         self.err_count += 1;
893         self.panic_if_treat_err_as_bug();
894     }
895
896     fn panic_if_treat_err_as_bug(&self) {
897         if self.treat_err_as_bug() {
898             let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
899                 (0, _) => return,
900                 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
901                 (1, _) => return,
902                 (count, as_bug) => format!(
903                     "aborting after {} errors due to `-Z treat-err-as-bug={}`",
904                     count, as_bug,
905                 ),
906             };
907             panic!(s);
908         }
909     }
910 }
911
912 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
913 pub enum Level {
914     Bug,
915     Fatal,
916     Error,
917     Warning,
918     Note,
919     Help,
920     Cancelled,
921     FailureNote,
922 }
923
924 impl fmt::Display for Level {
925     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
926         self.to_str().fmt(f)
927     }
928 }
929
930 impl Level {
931     fn color(self) -> ColorSpec {
932         let mut spec = ColorSpec::new();
933         match self {
934             Bug | Fatal | Error => {
935                 spec.set_fg(Some(Color::Red)).set_intense(true);
936             }
937             Warning => {
938                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
939             }
940             Note => {
941                 spec.set_fg(Some(Color::Green)).set_intense(true);
942             }
943             Help => {
944                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
945             }
946             FailureNote => {}
947             Cancelled => unreachable!(),
948         }
949         spec
950     }
951
952     pub fn to_str(self) -> &'static str {
953         match self {
954             Bug => "error: internal compiler error",
955             Fatal | Error => "error",
956             Warning => "warning",
957             Note => "note",
958             Help => "help",
959             FailureNote => "failure-note",
960             Cancelled => panic!("Shouldn't call on cancelled error"),
961         }
962     }
963
964     pub fn is_failure_note(&self) -> bool {
965         match *self {
966             FailureNote => true,
967             _ => false,
968         }
969     }
970 }
971
972 #[macro_export]
973 macro_rules! pluralize {
974     ($x:expr) => {
975         if $x != 1 { "s" } else { "" }
976     };
977 }
978
979 // Useful type to use with `Result<>` indicate that an error has already
980 // been reported to the user, so no need to continue checking.
981 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
982 pub struct ErrorReported;
983
984 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);