]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Rollup merge of #68889 - Zoxc:hir-krate, r=eddyb
[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             .filter_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()?;
195                 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
196                 let bounding_span = Span::with_root_ctxt(lo, hi);
197                 // The different spans might belong to different contexts, if so ignore suggestion.
198                 let lines = cm.span_to_lines(bounding_span).ok()?;
199                 assert!(!lines.lines.is_empty());
200
201                 // To build up the result, we do this for each span:
202                 // - push the line segment trailing the previous span
203                 //   (at the beginning a "phantom" span pointing at the start of the line)
204                 // - push lines between the previous and current span (if any)
205                 // - if the previous and current span are not on the same line
206                 //   push the line segment leading up to the current span
207                 // - splice in the span substitution
208                 //
209                 // Finally push the trailing line segment of the last span
210                 let fm = &lines.file;
211                 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
212                 prev_hi.col = CharPos::from_usize(0);
213
214                 let mut prev_line = fm.get_line(lines.lines[0].line_index);
215                 let mut buf = String::new();
216
217                 for part in &substitution.parts {
218                     let cur_lo = cm.lookup_char_pos(part.span.lo());
219                     if prev_hi.line == cur_lo.line {
220                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
221                     } else {
222                         push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
223                         // push lines between the previous and current span (if any)
224                         for idx in prev_hi.line..(cur_lo.line - 1) {
225                             if let Some(line) = fm.get_line(idx) {
226                                 buf.push_str(line.as_ref());
227                                 buf.push('\n');
228                             }
229                         }
230                         if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
231                             let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
232                             buf.push_str(&cur_line[..end]);
233                         }
234                     }
235                     buf.push_str(&part.snippet);
236                     prev_hi = cm.lookup_char_pos(part.span.hi());
237                     prev_line = fm.get_line(prev_hi.line - 1);
238                 }
239                 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
240                 // if the replacement already ends with a newline, don't print the next line
241                 if !buf.ends_with('\n') {
242                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
243                 }
244                 // remove trailing newlines
245                 while buf.ends_with('\n') {
246                     buf.pop();
247                 }
248                 Some((buf, substitution.parts, only_capitalization))
249             })
250             .collect()
251     }
252 }
253
254 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
255
256 /// Signifies that the compiler died with an explicit call to `.bug`
257 /// or `.span_bug` rather than a failed assertion, etc.
258 #[derive(Copy, Clone, Debug)]
259 pub struct ExplicitBug;
260
261 impl fmt::Display for ExplicitBug {
262     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263         write!(f, "parser internal bug")
264     }
265 }
266
267 impl error::Error for ExplicitBug {}
268
269 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
270 pub use diagnostic_builder::DiagnosticBuilder;
271
272 /// A handler deals with errors and other compiler output.
273 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
274 /// others log errors for later reporting.
275 pub struct Handler {
276     flags: HandlerFlags,
277     inner: Lock<HandlerInner>,
278 }
279
280 /// This inner struct exists to keep it all behind a single lock;
281 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
282 /// as well as inconsistent state observation.
283 struct HandlerInner {
284     flags: HandlerFlags,
285     /// The number of errors that have been emitted, including duplicates.
286     ///
287     /// This is not necessarily the count that's reported to the user once
288     /// compilation ends.
289     err_count: usize,
290     deduplicated_err_count: usize,
291     emitter: Box<dyn Emitter + sync::Send>,
292     delayed_span_bugs: Vec<Diagnostic>,
293
294     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
295     /// emitting the same diagnostic with extended help (`--teach`) twice, which
296     /// would be uneccessary repetition.
297     taught_diagnostics: FxHashSet<DiagnosticId>,
298
299     /// Used to suggest rustc --explain <error code>
300     emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
301
302     /// This set contains a hash of every diagnostic that has been emitted by
303     /// this handler. These hashes is used to avoid emitting the same error
304     /// twice.
305     emitted_diagnostics: FxHashSet<u128>,
306
307     /// Stashed diagnostics emitted in one stage of the compiler that may be
308     /// stolen by other stages (e.g. to improve them and add more information).
309     /// The stashed diagnostics count towards the total error count.
310     /// When `.abort_if_errors()` is called, these are also emitted.
311     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
312 }
313
314 /// A key denoting where from a diagnostic was stashed.
315 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
316 pub enum StashKey {
317     ItemNoType,
318 }
319
320 fn default_track_diagnostic(_: &Diagnostic) {}
321
322 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
323     AtomicRef::new(&(default_track_diagnostic as fn(&_)));
324
325 #[derive(Copy, Clone, Default)]
326 pub struct HandlerFlags {
327     /// If false, warning-level lints are suppressed.
328     /// (rustc: see `--allow warnings` and `--cap-lints`)
329     pub can_emit_warnings: bool,
330     /// If true, error-level diagnostics are upgraded to bug-level.
331     /// (rustc: see `-Z treat-err-as-bug`)
332     pub treat_err_as_bug: Option<usize>,
333     /// If true, immediately emit diagnostics that would otherwise be buffered.
334     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
335     pub dont_buffer_diagnostics: bool,
336     /// If true, immediately print bugs registered with `delay_span_bug`.
337     /// (rustc: see `-Z report-delayed-bugs`)
338     pub report_delayed_bugs: bool,
339     /// Show macro backtraces.
340     /// (rustc: see `-Z macro-backtrace`)
341     pub macro_backtrace: bool,
342     /// If true, identical diagnostics are reported only once.
343     pub deduplicate_diagnostics: bool,
344 }
345
346 impl Drop for HandlerInner {
347     fn drop(&mut self) {
348         self.emit_stashed_diagnostics();
349
350         if !self.has_errors() {
351             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
352             let has_bugs = !bugs.is_empty();
353             for bug in bugs {
354                 self.emit_diagnostic(&bug);
355             }
356             if has_bugs {
357                 panic!("no errors encountered even though `delay_span_bug` issued");
358             }
359         }
360     }
361 }
362
363 impl Handler {
364     pub fn with_tty_emitter(
365         color_config: ColorConfig,
366         can_emit_warnings: bool,
367         treat_err_as_bug: Option<usize>,
368         cm: Option<Lrc<SourceMap>>,
369     ) -> Self {
370         Self::with_tty_emitter_and_flags(
371             color_config,
372             cm,
373             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
374         )
375     }
376
377     pub fn with_tty_emitter_and_flags(
378         color_config: ColorConfig,
379         cm: Option<Lrc<SourceMap>>,
380         flags: HandlerFlags,
381     ) -> Self {
382         let emitter = Box::new(EmitterWriter::stderr(
383             color_config,
384             cm,
385             false,
386             false,
387             None,
388             flags.macro_backtrace,
389         ));
390         Self::with_emitter_and_flags(emitter, flags)
391     }
392
393     pub fn with_emitter(
394         can_emit_warnings: bool,
395         treat_err_as_bug: Option<usize>,
396         emitter: Box<dyn Emitter + sync::Send>,
397     ) -> Self {
398         Handler::with_emitter_and_flags(
399             emitter,
400             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
401         )
402     }
403
404     pub fn with_emitter_and_flags(
405         emitter: Box<dyn Emitter + sync::Send>,
406         flags: HandlerFlags,
407     ) -> Self {
408         Self {
409             flags,
410             inner: Lock::new(HandlerInner {
411                 flags,
412                 err_count: 0,
413                 deduplicated_err_count: 0,
414                 emitter,
415                 delayed_span_bugs: Vec::new(),
416                 taught_diagnostics: Default::default(),
417                 emitted_diagnostic_codes: Default::default(),
418                 emitted_diagnostics: Default::default(),
419                 stashed_diagnostics: Default::default(),
420             }),
421         }
422     }
423
424     // This is here to not allow mutation of flags;
425     // as of this writing it's only used in tests in librustc.
426     pub fn can_emit_warnings(&self) -> bool {
427         self.flags.can_emit_warnings
428     }
429
430     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
431     ///
432     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
433     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
434     /// the overall count of emitted error diagnostics.
435     pub fn reset_err_count(&self) {
436         let mut inner = self.inner.borrow_mut();
437         inner.err_count = 0;
438         inner.deduplicated_err_count = 0;
439
440         // actually free the underlying memory (which `clear` would not do)
441         inner.delayed_span_bugs = Default::default();
442         inner.taught_diagnostics = Default::default();
443         inner.emitted_diagnostic_codes = Default::default();
444         inner.emitted_diagnostics = Default::default();
445         inner.stashed_diagnostics = Default::default();
446     }
447
448     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
449     /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
450     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
451         let mut inner = self.inner.borrow_mut();
452         if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
453             // We are removing a previously stashed diagnostic which should not happen.
454             old_diag.level = Bug;
455             old_diag.note(&format!(
456                 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
457                 file!(),
458                 line!(),
459                 span,
460                 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     /// `true` if we haven't taught a diagnostic with this code already.
681     /// The caller must then teach the user about such a diagnostic.
682     ///
683     /// Used to suppress emitting the same error multiple times with extended explanation when
684     /// calling `-Zteach`.
685     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
686         self.inner.borrow_mut().must_teach(code)
687     }
688
689     pub fn force_print_diagnostic(&self, db: Diagnostic) {
690         self.inner.borrow_mut().force_print_diagnostic(db)
691     }
692
693     pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
694         self.inner.borrow_mut().emit_diagnostic(diagnostic)
695     }
696
697     fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
698         let mut inner = self.inner.borrow_mut();
699         inner.emit_diagnostic(diag.set_span(sp));
700     }
701
702     pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
703         self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
704     }
705
706     pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
707         self.inner.borrow_mut().delay_as_bug(diagnostic)
708     }
709 }
710
711 impl HandlerInner {
712     fn must_teach(&mut self, code: &DiagnosticId) -> bool {
713         self.taught_diagnostics.insert(code.clone())
714     }
715
716     fn force_print_diagnostic(&mut self, db: Diagnostic) {
717         self.emitter.emit_diagnostic(&db);
718     }
719
720     /// Emit all stashed diagnostics.
721     fn emit_stashed_diagnostics(&mut self) {
722         let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
723         diags.iter().for_each(|diag| self.emit_diagnostic(diag));
724     }
725
726     fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
727         if diagnostic.cancelled() {
728             return;
729         }
730
731         if diagnostic.level == Warning && !self.flags.can_emit_warnings {
732             return;
733         }
734
735         (*TRACK_DIAGNOSTICS)(diagnostic);
736
737         if let Some(ref code) = diagnostic.code {
738             self.emitted_diagnostic_codes.insert(code.clone());
739         }
740
741         let already_emitted = |this: &mut Self| {
742             use std::hash::Hash;
743             let mut hasher = StableHasher::new();
744             diagnostic.hash(&mut hasher);
745             let diagnostic_hash = hasher.finish();
746             !this.emitted_diagnostics.insert(diagnostic_hash)
747         };
748
749         // Only emit the diagnostic if we've been asked to deduplicate and
750         // haven't already emitted an equivalent diagnostic.
751         if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
752             self.emitter.emit_diagnostic(diagnostic);
753             if diagnostic.is_error() {
754                 self.deduplicated_err_count += 1;
755             }
756         }
757         if diagnostic.is_error() {
758             self.bump_err_count();
759         }
760     }
761
762     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
763         self.emitter.emit_artifact_notification(path, artifact_type);
764     }
765
766     fn treat_err_as_bug(&self) -> bool {
767         self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
768     }
769
770     fn print_error_count(&mut self, registry: &Registry) {
771         self.emit_stashed_diagnostics();
772
773         let s = match self.deduplicated_err_count {
774             0 => return,
775             1 => "aborting due to previous error".to_string(),
776             count => format!("aborting due to {} previous errors", count),
777         };
778         if self.treat_err_as_bug() {
779             return;
780         }
781
782         let _ = self.fatal(&s);
783
784         let can_show_explain = self.emitter.should_show_explain();
785         let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
786         if can_show_explain && are_there_diagnostics {
787             let mut error_codes = self
788                 .emitted_diagnostic_codes
789                 .iter()
790                 .filter_map(|x| match &x {
791                     DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
792                         Some(s.clone())
793                     }
794                     _ => None,
795                 })
796                 .collect::<Vec<_>>();
797             if !error_codes.is_empty() {
798                 error_codes.sort();
799                 if error_codes.len() > 1 {
800                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
801                     self.failure(&format!(
802                         "Some errors have detailed explanations: {}{}",
803                         error_codes[..limit].join(", "),
804                         if error_codes.len() > 9 { "..." } else { "." }
805                     ));
806                     self.failure(&format!(
807                         "For more information about an error, try \
808                                            `rustc --explain {}`.",
809                         &error_codes[0]
810                     ));
811                 } else {
812                     self.failure(&format!(
813                         "For more information about this error, try \
814                                            `rustc --explain {}`.",
815                         &error_codes[0]
816                     ));
817                 }
818             }
819         }
820     }
821
822     fn err_count(&self) -> usize {
823         self.err_count + self.stashed_diagnostics.len()
824     }
825
826     fn has_errors(&self) -> bool {
827         self.err_count() > 0
828     }
829     fn has_errors_or_delayed_span_bugs(&self) -> bool {
830         self.has_errors() || !self.delayed_span_bugs.is_empty()
831     }
832
833     fn abort_if_errors(&mut self) {
834         self.emit_stashed_diagnostics();
835
836         if self.has_errors() {
837             FatalError.raise();
838         }
839     }
840
841     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
842         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
843         panic!(ExplicitBug);
844     }
845
846     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
847         self.emit_diagnostic(diag.set_span(sp));
848     }
849
850     fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
851         if self.treat_err_as_bug() {
852             // FIXME: don't abort here if report_delayed_bugs is off
853             self.span_bug(sp, msg);
854         }
855         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
856         diagnostic.set_span(sp.into());
857         self.delay_as_bug(diagnostic)
858     }
859
860     fn failure(&mut self, msg: &str) {
861         self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
862     }
863
864     fn fatal(&mut self, msg: &str) -> FatalError {
865         self.emit_error(Fatal, msg);
866         FatalError
867     }
868
869     fn err(&mut self, msg: &str) {
870         self.emit_error(Error, msg);
871     }
872
873     /// Emit an error; level should be `Error` or `Fatal`.
874     fn emit_error(&mut self, level: Level, msg: &str) {
875         if self.treat_err_as_bug() {
876             self.bug(msg);
877         }
878         self.emit_diagnostic(&Diagnostic::new(level, msg));
879     }
880
881     fn bug(&mut self, msg: &str) -> ! {
882         self.emit_diagnostic(&Diagnostic::new(Bug, msg));
883         panic!(ExplicitBug);
884     }
885
886     fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
887         if self.flags.report_delayed_bugs {
888             self.emit_diagnostic(&diagnostic);
889         }
890         self.delayed_span_bugs.push(diagnostic);
891     }
892
893     fn bump_err_count(&mut self) {
894         self.err_count += 1;
895         self.panic_if_treat_err_as_bug();
896     }
897
898     fn panic_if_treat_err_as_bug(&self) {
899         if self.treat_err_as_bug() {
900             let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
901                 (0, _) => return,
902                 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
903                 (1, _) => return,
904                 (count, as_bug) => format!(
905                     "aborting after {} errors due to `-Z treat-err-as-bug={}`",
906                     count, as_bug,
907                 ),
908             };
909             panic!(s);
910         }
911     }
912 }
913
914 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
915 pub enum Level {
916     Bug,
917     Fatal,
918     Error,
919     Warning,
920     Note,
921     Help,
922     Cancelled,
923     FailureNote,
924 }
925
926 impl fmt::Display for Level {
927     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
928         self.to_str().fmt(f)
929     }
930 }
931
932 impl Level {
933     fn color(self) -> ColorSpec {
934         let mut spec = ColorSpec::new();
935         match self {
936             Bug | Fatal | Error => {
937                 spec.set_fg(Some(Color::Red)).set_intense(true);
938             }
939             Warning => {
940                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
941             }
942             Note => {
943                 spec.set_fg(Some(Color::Green)).set_intense(true);
944             }
945             Help => {
946                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
947             }
948             FailureNote => {}
949             Cancelled => unreachable!(),
950         }
951         spec
952     }
953
954     pub fn to_str(self) -> &'static str {
955         match self {
956             Bug => "error: internal compiler error",
957             Fatal | Error => "error",
958             Warning => "warning",
959             Note => "note",
960             Help => "help",
961             FailureNote => "failure-note",
962             Cancelled => panic!("Shouldn't call on cancelled error"),
963         }
964     }
965
966     pub fn is_failure_note(&self) -> bool {
967         match *self {
968             FailureNote => true,
969             _ => false,
970         }
971     }
972 }
973
974 #[macro_export]
975 macro_rules! pluralize {
976     ($x:expr) => {
977         if $x != 1 { "s" } else { "" }
978     };
979 }
980
981 // Useful type to use with `Result<>` indicate that an error has already
982 // been reported to the user, so no need to continue checking.
983 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
984 pub struct ErrorReported;
985
986 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);