]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
17765ef9deefa25df550aebe9041fe0c312e400e
[rust.git] / src / librustc_errors / lib.rs
1 //! Diagnostics creation and emission for `rustc`.
2 //!
3 //! This module contains the code for creating and emitting diagnostics.
4
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
6
7 #![feature(crate_visibility_modifier)]
8 #![cfg_attr(unix, feature(libc))]
9 #![feature(nll)]
10 #![feature(optin_builtin_traits)]
11
12 pub use emitter::ColorConfig;
13
14 use Level::*;
15
16 use emitter::{Emitter, EmitterWriter, is_case_difference};
17 use registry::Registry;
18 use rustc_data_structures::sync::{self, Lrc, Lock};
19 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
20 use rustc_data_structures::stable_hasher::StableHasher;
21 use syntax_pos::source_map::SourceMap;
22 use syntax_pos::{Loc, Span, MultiSpan};
23
24 use std::borrow::Cow;
25 use std::cell::Cell;
26 use std::{error, fmt};
27 use std::panic;
28 use std::path::Path;
29
30 use termcolor::{ColorSpec, Color};
31
32 mod diagnostic;
33 mod diagnostic_builder;
34 pub mod emitter;
35 pub mod annotate_snippet_emitter_writer;
36 mod snippet;
37 pub mod registry;
38 mod styled_buffer;
39 mod lock;
40 pub mod json;
41
42 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
43
44 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
45 // (See also the comment on `DiagnosticBuilderInner`.)
46 #[cfg(target_arch = "x86_64")]
47 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
48
49 /// Indicates the confidence in the correctness of a suggestion.
50 ///
51 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
52 /// to determine whether it should be automatically applied or if the user should be consulted
53 /// before applying the suggestion.
54 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
55 pub enum Applicability {
56     /// The suggestion is definitely what the user intended. This suggestion should be
57     /// automatically applied.
58     MachineApplicable,
59
60     /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
61     /// result in valid Rust code if it is applied.
62     MaybeIncorrect,
63
64     /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
65     /// cannot be applied automatically because it will not result in valid Rust code. The user
66     /// will need to fill in the placeholders.
67     HasPlaceholders,
68
69     /// The applicability of the suggestion is unknown.
70     Unspecified,
71 }
72
73 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
74 pub enum SuggestionStyle {
75     /// Hide the suggested code when displaying this suggestion inline.
76     HideCodeInline,
77     /// Always hide the suggested code but display the message.
78     HideCodeAlways,
79     /// Do not display this suggestion in the cli output, it is only meant for tools.
80     CompletelyHidden,
81     /// Always show the suggested code.
82     /// This will *not* show the code if the suggestion is inline *and* the suggested code is
83     /// empty.
84     ShowCode,
85     /// Always show the suggested code independently.
86     ShowAlways,
87 }
88
89 impl SuggestionStyle {
90     fn hide_inline(&self) -> bool {
91         match *self {
92             SuggestionStyle::ShowCode => false,
93             _ => true,
94         }
95     }
96 }
97
98 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
99 pub struct CodeSuggestion {
100     /// Each substitute can have multiple variants due to multiple
101     /// applicable suggestions
102     ///
103     /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
104     /// `foo` and `bar` on their own:
105     ///
106     /// ```
107     /// vec![
108     ///     Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
109     ///     Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
110     /// ]
111     /// ```
112     ///
113     /// or by replacing the entire span:
114     ///
115     /// ```
116     /// vec![
117     ///     Substitution { parts: vec![(0..7, "a.b")] },
118     ///     Substitution { parts: vec![(0..7, "x.y")] },
119     /// ]
120     /// ```
121     pub substitutions: Vec<Substitution>,
122     pub msg: String,
123     /// Visual representation of this suggestion.
124     pub style: SuggestionStyle,
125     /// Whether or not the suggestion is approximate
126     ///
127     /// Sometimes we may show suggestions with placeholders,
128     /// which are useful for users but not useful for
129     /// tools like rustfix
130     pub applicability: Applicability,
131 }
132
133 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
134 /// See the docs on `CodeSuggestion::substitutions`
135 pub struct Substitution {
136     pub parts: Vec<SubstitutionPart>,
137 }
138
139 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
140 pub struct SubstitutionPart {
141     pub span: Span,
142     pub snippet: String,
143 }
144
145 impl CodeSuggestion {
146     /// Returns the assembled code suggestions, whether they should be shown with an underline
147     /// and whether the substitution only differs in capitalization.
148     pub fn splice_lines(
149         &self,
150         cm: &SourceMap,
151     ) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
152         use syntax_pos::{CharPos, Pos};
153
154         fn push_trailing(buf: &mut String,
155                          line_opt: Option<&Cow<'_, str>>,
156                          lo: &Loc,
157                          hi_opt: Option<&Loc>) {
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.iter().cloned().map(|mut substitution| {
177             // Assumption: all spans are in the same file, and all spans
178             // are disjoint. Sort in ascending order.
179             substitution.parts.sort_by_key(|part| part.span.lo());
180
181             // Find the bounding span.
182             let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
183             let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
184             let bounding_span = Span::with_root_ctxt(lo, hi);
185             let lines = cm.span_to_lines(bounding_span).unwrap();
186             assert!(!lines.lines.is_empty());
187
188             // To build up the result, we do this for each span:
189             // - push the line segment trailing the previous span
190             //   (at the beginning a "phantom" span pointing at the start of the line)
191             // - push lines between the previous and current span (if any)
192             // - if the previous and current span are not on the same line
193             //   push the line segment leading up to the current span
194             // - splice in the span substitution
195             //
196             // Finally push the trailing line segment of the last span
197             let fm = &lines.file;
198             let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
199             prev_hi.col = CharPos::from_usize(0);
200
201             let mut prev_line = fm.get_line(lines.lines[0].line_index);
202             let mut buf = String::new();
203
204             for part in &substitution.parts {
205                 let cur_lo = cm.lookup_char_pos(part.span.lo());
206                 if prev_hi.line == cur_lo.line {
207                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
208                 } else {
209                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
210                     // push lines between the previous and current span (if any)
211                     for idx in prev_hi.line..(cur_lo.line - 1) {
212                         if let Some(line) = fm.get_line(idx) {
213                             buf.push_str(line.as_ref());
214                             buf.push('\n');
215                         }
216                     }
217                     if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
218                         let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
219                         buf.push_str(&cur_line[..end]);
220                     }
221                 }
222                 buf.push_str(&part.snippet);
223                 prev_hi = cm.lookup_char_pos(part.span.hi());
224                 prev_line = fm.get_line(prev_hi.line - 1);
225             }
226             let only_capitalization = is_case_difference(cm, &buf, bounding_span);
227             // if the replacement already ends with a newline, don't print the next line
228             if !buf.ends_with('\n') {
229                 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
230             }
231             // remove trailing newlines
232             while buf.ends_with('\n') {
233                 buf.pop();
234             }
235             (buf, substitution.parts, only_capitalization)
236         }).collect()
237     }
238 }
239
240 pub use syntax_pos::fatal_error::{FatalError, FatalErrorMarker};
241
242 /// Signifies that the compiler died with an explicit call to `.bug`
243 /// or `.span_bug` rather than a failed assertion, etc.
244 #[derive(Copy, Clone, Debug)]
245 pub struct ExplicitBug;
246
247 impl fmt::Display for ExplicitBug {
248     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249         write!(f, "parser internal bug")
250     }
251 }
252
253 impl error::Error for ExplicitBug {
254     fn description(&self) -> &str {
255         "The parser has encountered an internal bug"
256     }
257 }
258
259 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
260 pub use diagnostic_builder::DiagnosticBuilder;
261
262 /// A handler deals with errors and other compiler output.
263 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
264 /// others log errors for later reporting.
265 pub struct Handler {
266     flags: HandlerFlags,
267     inner: Lock<HandlerInner>,
268 }
269
270 /// This inner struct exists to keep it all behind a single lock;
271 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
272 /// as well as inconsistent state observation.
273 struct HandlerInner {
274     flags: HandlerFlags,
275     /// The number of errors that have been emitted, including duplicates.
276     ///
277     /// This is not necessarily the count that's reported to the user once
278     /// compilation ends.
279     err_count: usize,
280     deduplicated_err_count: usize,
281     emitter: Box<dyn Emitter + sync::Send>,
282     continue_after_error: bool,
283     delayed_span_bugs: Vec<Diagnostic>,
284
285     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
286     /// emitting the same diagnostic with extended help (`--teach`) twice, which
287     /// would be uneccessary repetition.
288     taught_diagnostics: FxHashSet<DiagnosticId>,
289
290     /// Used to suggest rustc --explain <error code>
291     emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
292
293     /// This set contains a hash of every diagnostic that has been emitted by
294     /// this handler. These hashes is used to avoid emitting the same error
295     /// twice.
296     emitted_diagnostics: FxHashSet<u128>,
297
298     /// Stashed diagnostics emitted in one stage of the compiler that may be
299     /// stolen by other stages (e.g. to improve them and add more information).
300     /// The stashed diagnostics count towards the total error count.
301     /// When `.abort_if_errors()` is called, these are also emitted.
302     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
303 }
304
305 /// A key denoting where from a diagnostic was stashed.
306 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
307 pub enum StashKey {
308     ItemNoType,
309 }
310
311 fn default_track_diagnostic(_: &Diagnostic) {}
312
313 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
314                 Cell::new(default_track_diagnostic));
315
316 #[derive(Copy, Clone, Default)]
317 pub struct HandlerFlags {
318     /// If false, warning-level lints are suppressed.
319     /// (rustc: see `--allow warnings` and `--cap-lints`)
320     pub can_emit_warnings: bool,
321     /// If true, error-level diagnostics are upgraded to bug-level.
322     /// (rustc: see `-Z treat-err-as-bug`)
323     pub treat_err_as_bug: Option<usize>,
324     /// If true, immediately emit diagnostics that would otherwise be buffered.
325     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
326     pub dont_buffer_diagnostics: bool,
327     /// If true, immediately print bugs registered with `delay_span_bug`.
328     /// (rustc: see `-Z report-delayed-bugs`)
329     pub report_delayed_bugs: bool,
330     /// show macro backtraces even for non-local macros.
331     /// (rustc: see `-Z external-macro-backtrace`)
332     pub external_macro_backtrace: bool,
333 }
334
335 impl Drop for HandlerInner {
336     fn drop(&mut self) {
337         self.emit_stashed_diagnostics();
338
339         if !self.has_errors() {
340             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
341             let has_bugs = !bugs.is_empty();
342             for bug in bugs {
343                 self.emit_diagnostic(&bug);
344             }
345             if has_bugs {
346                 panic!("no errors encountered even though `delay_span_bug` issued");
347             }
348         }
349     }
350 }
351
352 impl Handler {
353     pub fn with_tty_emitter(
354         color_config: ColorConfig,
355         can_emit_warnings: bool,
356         treat_err_as_bug: Option<usize>,
357         cm: Option<Lrc<SourceMap>>,
358     ) -> Self {
359         Self::with_tty_emitter_and_flags(
360             color_config,
361             cm,
362             HandlerFlags {
363                 can_emit_warnings,
364                 treat_err_as_bug,
365                 .. Default::default()
366             },
367         )
368     }
369
370     pub fn with_tty_emitter_and_flags(
371         color_config: ColorConfig,
372         cm: Option<Lrc<SourceMap>>,
373         flags: HandlerFlags,
374     ) -> Self {
375         let emitter = Box::new(EmitterWriter::stderr(
376             color_config,
377             cm,
378             false,
379             false,
380             None,
381             flags.external_macro_backtrace,
382         ));
383         Self::with_emitter_and_flags(emitter, flags)
384     }
385
386     pub fn with_emitter(
387         can_emit_warnings: bool,
388         treat_err_as_bug: Option<usize>,
389         emitter: Box<dyn Emitter + sync::Send>,
390     ) -> Self {
391         Handler::with_emitter_and_flags(
392             emitter,
393             HandlerFlags {
394                 can_emit_warnings,
395                 treat_err_as_bug,
396                 .. Default::default()
397             },
398         )
399     }
400
401     pub fn with_emitter_and_flags(
402         emitter: Box<dyn Emitter + sync::Send>,
403         flags: HandlerFlags
404     ) -> Self {
405         Self {
406             flags,
407             inner: Lock::new(HandlerInner {
408                 flags,
409                 err_count: 0,
410                 deduplicated_err_count: 0,
411                 emitter,
412                 continue_after_error: true,
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     pub fn set_continue_after_error(&self, continue_after_error: bool) {
423         self.inner.borrow_mut().continue_after_error = continue_after_error;
424     }
425
426     // This is here to not allow mutation of flags;
427     // as of this writing it's only used in tests in librustc.
428     pub fn can_emit_warnings(&self) -> bool {
429         self.flags.can_emit_warnings
430     }
431
432     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
433     ///
434     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
435     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
436     /// the overall count of emitted error diagnostics.
437     pub fn reset_err_count(&self) {
438         let mut inner = self.inner.borrow_mut();
439         inner.err_count = 0;
440         inner.deduplicated_err_count = 0;
441
442         // actually free the underlying memory (which `clear` would not do)
443         inner.delayed_span_bugs = Default::default();
444         inner.taught_diagnostics = Default::default();
445         inner.emitted_diagnostic_codes = Default::default();
446         inner.emitted_diagnostics = Default::default();
447         inner.stashed_diagnostics = Default::default();
448     }
449
450     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
451     /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
452     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
453         let mut inner = self.inner.borrow_mut();
454         if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
455             // We are removing a previously stashed diagnostic which should not happen.
456             old_diag.level = Bug;
457             old_diag.note(&format!(
458                 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
459                 file!(), line!(), span, 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     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
578         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
579         FatalError
580     }
581
582     pub fn span_fatal_with_code(
583         &self,
584         span: impl Into<MultiSpan>,
585         msg: &str,
586         code: DiagnosticId,
587     ) -> FatalError {
588         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
589         FatalError
590     }
591
592     pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
593         self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
594     }
595
596     pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
597         self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
598     }
599
600     pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
601         self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
602     }
603
604     pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
605         self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
606     }
607
608     pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
609         self.inner.borrow_mut().span_bug(span, msg)
610     }
611
612     pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
613         self.inner.borrow_mut().delay_span_bug(span, msg)
614     }
615
616     pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
617         self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
618     }
619
620     pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
621         self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
622     }
623
624     pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
625         let mut db = DiagnosticBuilder::new(self, Note, msg);
626         db.set_span(span);
627         db
628     }
629
630     pub fn failure(&self, msg: &str) {
631         self.inner.borrow_mut().failure(msg);
632     }
633
634     pub fn fatal(&self, msg: &str) -> FatalError {
635         self.inner.borrow_mut().fatal(msg)
636     }
637
638     pub fn err(&self, msg: &str) {
639         self.inner.borrow_mut().err(msg);
640     }
641
642     pub fn warn(&self, msg: &str) {
643         let mut db = DiagnosticBuilder::new(self, Warning, msg);
644         db.emit();
645     }
646
647     pub fn note_without_error(&self, msg: &str) {
648         DiagnosticBuilder::new(self, Note, msg).emit();
649     }
650
651     pub fn bug(&self, msg: &str) -> ! {
652         self.inner.borrow_mut().bug(msg)
653     }
654
655     pub fn err_count(&self) -> usize {
656         self.inner.borrow().err_count()
657     }
658
659     pub fn has_errors(&self) -> bool {
660         self.inner.borrow().has_errors()
661     }
662     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
663         self.inner.borrow().has_errors_or_delayed_span_bugs()
664     }
665
666     pub fn print_error_count(&self, registry: &Registry) {
667         self.inner.borrow_mut().print_error_count(registry)
668     }
669
670     pub fn abort_if_errors(&self) {
671         self.inner.borrow_mut().abort_if_errors()
672     }
673
674     pub fn abort_if_errors_and_should_abort(&self) {
675         self.inner.borrow_mut().abort_if_errors_and_should_abort()
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         inner.abort_if_errors_and_should_abort();
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.with(|track_diagnostics| {
735             track_diagnostics.get()(diagnostic);
736         });
737
738         if let Some(ref code) = diagnostic.code {
739             self.emitted_diagnostic_codes.insert(code.clone());
740         }
741
742         let diagnostic_hash = {
743             use std::hash::Hash;
744             let mut hasher = StableHasher::new();
745             diagnostic.hash(&mut hasher);
746             hasher.finish()
747         };
748
749         // Only emit the diagnostic if we haven't already emitted an equivalent
750         // one:
751         if self.emitted_diagnostics.insert(diagnostic_hash) {
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!("Some errors have detailed explanations: {}{}",
802                                           error_codes[..limit].join(", "),
803                                           if error_codes.len() > 9 { "..." } else { "." }));
804                     self.failure(&format!("For more information about an error, try \
805                                            `rustc --explain {}`.",
806                                           &error_codes[0]));
807                 } else {
808                     self.failure(&format!("For more information about this error, try \
809                                            `rustc --explain {}`.",
810                                           &error_codes[0]));
811                 }
812             }
813         }
814     }
815
816     fn err_count(&self) -> usize {
817         self.err_count + self.stashed_diagnostics.len()
818     }
819
820     fn has_errors(&self) -> bool {
821         self.err_count() > 0
822     }
823     fn has_errors_or_delayed_span_bugs(&self) -> bool {
824         self.has_errors() || !self.delayed_span_bugs.is_empty()
825     }
826
827     fn abort_if_errors_and_should_abort(&mut self) {
828         self.emit_stashed_diagnostics();
829
830         if self.has_errors() && !self.continue_after_error {
831             FatalError.raise();
832         }
833     }
834
835     fn abort_if_errors(&mut self) {
836         self.emit_stashed_diagnostics();
837
838         if self.has_errors() {
839             FatalError.raise();
840         }
841     }
842
843     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
844         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
845         panic!(ExplicitBug);
846     }
847
848     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
849         self.emit_diagnostic(diag.set_span(sp));
850         self.abort_if_errors_and_should_abort();
851     }
852
853     fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
854         if self.treat_err_as_bug() {
855             // FIXME: don't abort here if report_delayed_bugs is off
856             self.span_bug(sp, msg);
857         }
858         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
859         diagnostic.set_span(sp.into());
860         self.delay_as_bug(diagnostic)
861     }
862
863     fn failure(&mut self, msg: &str) {
864         self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
865     }
866
867     fn fatal(&mut self, msg: &str) -> FatalError {
868         self.emit_error(Fatal, msg);
869         FatalError
870     }
871
872     fn err(&mut self, msg: &str) {
873         self.emit_error(Error, msg);
874     }
875
876     /// Emit an error; level should be `Error` or `Fatal`.
877     fn emit_error(&mut self, level: Level, msg: &str,) {
878         if self.treat_err_as_bug() {
879             self.bug(msg);
880         }
881         self.emit_diagnostic(&Diagnostic::new(level, msg));
882     }
883
884     fn bug(&mut self, msg: &str) -> ! {
885         self.emit_diagnostic(&Diagnostic::new(Bug, msg));
886         panic!(ExplicitBug);
887     }
888
889     fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
890         if self.flags.report_delayed_bugs {
891             self.emit_diagnostic(&diagnostic);
892         }
893         self.delayed_span_bugs.push(diagnostic);
894     }
895
896     fn bump_err_count(&mut self) {
897         self.err_count += 1;
898         self.panic_if_treat_err_as_bug();
899     }
900
901     fn panic_if_treat_err_as_bug(&self) {
902         if self.treat_err_as_bug() {
903             let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
904                 (0, _) => return,
905                 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
906                 (1, _) => return,
907                 (count, as_bug) => {
908                     format!(
909                         "aborting after {} errors due to `-Z treat-err-as-bug={}`",
910                         count,
911                         as_bug,
912                     )
913                 }
914             };
915             panic!(s);
916         }
917     }
918 }
919
920 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
921 pub enum Level {
922     Bug,
923     Fatal,
924     Error,
925     Warning,
926     Note,
927     Help,
928     Cancelled,
929     FailureNote,
930 }
931
932 impl fmt::Display for Level {
933     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
934         self.to_str().fmt(f)
935     }
936 }
937
938 impl Level {
939     fn color(self) -> ColorSpec {
940         let mut spec = ColorSpec::new();
941         match self {
942             Bug | Fatal | Error => {
943                 spec.set_fg(Some(Color::Red))
944                     .set_intense(true);
945             }
946             Warning => {
947                 spec.set_fg(Some(Color::Yellow))
948                     .set_intense(cfg!(windows));
949             }
950             Note => {
951                 spec.set_fg(Some(Color::Green))
952                     .set_intense(true);
953             }
954             Help => {
955                 spec.set_fg(Some(Color::Cyan))
956                     .set_intense(true);
957             }
958             FailureNote => {}
959             Cancelled => unreachable!(),
960         }
961         spec
962     }
963
964     pub fn to_str(self) -> &'static str {
965         match self {
966             Bug => "error: internal compiler error",
967             Fatal | Error => "error",
968             Warning => "warning",
969             Note => "note",
970             Help => "help",
971             FailureNote => "failure-note",
972             Cancelled => panic!("Shouldn't call on cancelled error"),
973         }
974     }
975
976     pub fn is_failure_note(&self) -> bool {
977         match *self {
978             FailureNote => true,
979             _ => false,
980         }
981     }
982 }
983
984 #[macro_export]
985 macro_rules! pluralize {
986     ($x:expr) => {
987         if $x != 1 { "s" } else { "" }
988     };
989 }