]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Auto merge of #60039 - rasendubi:assert-trailing-junk, r=alexcrichton
[rust.git] / src / librustc_errors / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
2
3 #![feature(custom_attribute)]
4 #![allow(unused_attributes)]
5 #![cfg_attr(unix, feature(libc))]
6 #![feature(nll)]
7 #![feature(optin_builtin_traits)]
8 #![deny(rust_2018_idioms)]
9 #![deny(internal)]
10
11 #[allow(unused_extern_crates)]
12 extern crate serialize as rustc_serialize; // used by deriving
13
14 pub use emitter::ColorConfig;
15
16 use Level::*;
17
18 use emitter::{Emitter, EmitterWriter};
19 use registry::Registry;
20
21 use rustc_data_structures::sync::{self, Lrc, Lock, AtomicUsize, AtomicBool, SeqCst};
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::stable_hasher::StableHasher;
24
25 use std::borrow::Cow;
26 use std::cell::Cell;
27 use std::{error, fmt};
28 use std::panic;
29
30 use termcolor::{ColorSpec, Color};
31
32 mod diagnostic;
33 mod diagnostic_builder;
34 pub mod emitter;
35 mod snippet;
36 pub mod registry;
37 mod styled_buffer;
38 mod lock;
39
40 use syntax_pos::{BytePos,
41                  Loc,
42                  FileLinesResult,
43                  SourceFile,
44                  FileName,
45                  MultiSpan,
46                  Span,
47                  NO_EXPANSION};
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 }
86
87 impl SuggestionStyle {
88     fn hide_inline(&self) -> bool {
89         match *self {
90             SuggestionStyle::ShowCode => false,
91             _ => true,
92         }
93     }
94 }
95
96 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
97 pub struct CodeSuggestion {
98     /// Each substitute can have multiple variants due to multiple
99     /// applicable suggestions
100     ///
101     /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
102     /// `foo` and `bar` on their own:
103     ///
104     /// ```
105     /// vec![
106     ///     Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
107     ///     Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
108     /// ]
109     /// ```
110     ///
111     /// or by replacing the entire span:
112     ///
113     /// ```
114     /// vec![
115     ///     Substitution { parts: vec![(0..7, "a.b")] },
116     ///     Substitution { parts: vec![(0..7, "x.y")] },
117     /// ]
118     /// ```
119     pub substitutions: Vec<Substitution>,
120     pub msg: String,
121     /// Visual representation of this suggestion.
122     pub style: SuggestionStyle,
123     /// Whether or not the suggestion is approximate
124     ///
125     /// Sometimes we may show suggestions with placeholders,
126     /// which are useful for users but not useful for
127     /// tools like rustfix
128     pub applicability: Applicability,
129 }
130
131 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
132 /// See the docs on `CodeSuggestion::substitutions`
133 pub struct Substitution {
134     pub parts: Vec<SubstitutionPart>,
135 }
136
137 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
138 pub struct SubstitutionPart {
139     pub span: Span,
140     pub snippet: String,
141 }
142
143 pub type SourceMapperDyn = dyn SourceMapper + sync::Send + sync::Sync;
144
145 pub trait SourceMapper {
146     fn lookup_char_pos(&self, pos: BytePos) -> Loc;
147     fn span_to_lines(&self, sp: Span) -> FileLinesResult;
148     fn span_to_string(&self, sp: Span) -> String;
149     fn span_to_filename(&self, sp: Span) -> FileName;
150     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
151     fn call_span_if_macro(&self, sp: Span) -> Span;
152     fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
153     fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
154 }
155
156 impl CodeSuggestion {
157     /// Returns the assembled code suggestions and whether they should be shown with an underline.
158     pub fn splice_lines(&self, cm: &SourceMapperDyn)
159                         -> Vec<(String, Vec<SubstitutionPart>)> {
160         use syntax_pos::{CharPos, Pos};
161
162         fn push_trailing(buf: &mut String,
163                          line_opt: Option<&Cow<'_, str>>,
164                          lo: &Loc,
165                          hi_opt: Option<&Loc>) {
166             let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
167             if let Some(line) = line_opt {
168                 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
169                     let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
170                     match hi_opt {
171                         Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
172                         Some(_) => (),
173                         None => buf.push_str(&line[lo..]),
174                     }
175                 }
176                 if let None = hi_opt {
177                     buf.push('\n');
178                 }
179             }
180         }
181
182         assert!(!self.substitutions.is_empty());
183
184         self.substitutions.iter().cloned().map(|mut substitution| {
185             // Assumption: all spans are in the same file, and all spans
186             // are disjoint. Sort in ascending order.
187             substitution.parts.sort_by_key(|part| part.span.lo());
188
189             // Find the bounding span.
190             let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
191             let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
192             let bounding_span = Span::new(lo, hi, NO_EXPANSION);
193             let lines = cm.span_to_lines(bounding_span).unwrap();
194             assert!(!lines.lines.is_empty());
195
196             // To build up the result, we do this for each span:
197             // - push the line segment trailing the previous span
198             //   (at the beginning a "phantom" span pointing at the start of the line)
199             // - push lines between the previous and current span (if any)
200             // - if the previous and current span are not on the same line
201             //   push the line segment leading up to the current span
202             // - splice in the span substitution
203             //
204             // Finally push the trailing line segment of the last span
205             let fm = &lines.file;
206             let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
207             prev_hi.col = CharPos::from_usize(0);
208
209             let mut prev_line = fm.get_line(lines.lines[0].line_index);
210             let mut buf = String::new();
211
212             for part in &substitution.parts {
213                 let cur_lo = cm.lookup_char_pos(part.span.lo());
214                 if prev_hi.line == cur_lo.line {
215                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
216                 } else {
217                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
218                     // push lines between the previous and current span (if any)
219                     for idx in prev_hi.line..(cur_lo.line - 1) {
220                         if let Some(line) = fm.get_line(idx) {
221                             buf.push_str(line.as_ref());
222                             buf.push('\n');
223                         }
224                     }
225                     if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
226                         buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
227                     }
228                 }
229                 buf.push_str(&part.snippet);
230                 prev_hi = cm.lookup_char_pos(part.span.hi());
231                 prev_line = fm.get_line(prev_hi.line - 1);
232             }
233             // if the replacement already ends with a newline, don't print the next line
234             if !buf.ends_with('\n') {
235                 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
236             }
237             // remove trailing newlines
238             while buf.ends_with('\n') {
239                 buf.pop();
240             }
241             (buf, substitution.parts)
242         }).collect()
243     }
244 }
245
246 /// Used as a return value to signify a fatal error occurred. (It is also
247 /// used as the argument to panic at the moment, but that will eventually
248 /// not be true.)
249 #[derive(Copy, Clone, Debug)]
250 #[must_use]
251 pub struct FatalError;
252
253 pub struct FatalErrorMarker;
254
255 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
256 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
257 impl !Send for FatalError {}
258
259 impl FatalError {
260     pub fn raise(self) -> ! {
261         panic::resume_unwind(Box::new(FatalErrorMarker))
262     }
263 }
264
265 impl fmt::Display for FatalError {
266     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267         write!(f, "parser fatal error")
268     }
269 }
270
271 impl error::Error for FatalError {
272     fn description(&self) -> &str {
273         "The parser has encountered a fatal error"
274     }
275 }
276
277 /// Signifies that the compiler died with an explicit call to `.bug`
278 /// or `.span_bug` rather than a failed assertion, etc.
279 #[derive(Copy, Clone, Debug)]
280 pub struct ExplicitBug;
281
282 impl fmt::Display for ExplicitBug {
283     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284         write!(f, "parser internal bug")
285     }
286 }
287
288 impl error::Error for ExplicitBug {
289     fn description(&self) -> &str {
290         "The parser has encountered an internal bug"
291     }
292 }
293
294 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
295 pub use diagnostic_builder::DiagnosticBuilder;
296
297 /// A handler deals with errors; certain errors
298 /// (fatal, bug, unimpl) may cause immediate exit,
299 /// others log errors for later reporting.
300 pub struct Handler {
301     pub flags: HandlerFlags,
302
303     err_count: AtomicUsize,
304     emitter: Lock<Box<dyn Emitter + sync::Send>>,
305     continue_after_error: AtomicBool,
306     delayed_span_bugs: Lock<Vec<Diagnostic>>,
307
308     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
309     /// emitting the same diagnostic with extended help (`--teach`) twice, which
310     /// would be uneccessary repetition.
311     taught_diagnostics: Lock<FxHashSet<DiagnosticId>>,
312
313     /// Used to suggest rustc --explain <error code>
314     emitted_diagnostic_codes: Lock<FxHashSet<DiagnosticId>>,
315
316     /// This set contains a hash of every diagnostic that has been emitted by
317     /// this handler. These hashes is used to avoid emitting the same error
318     /// twice.
319     emitted_diagnostics: Lock<FxHashSet<u128>>,
320 }
321
322 fn default_track_diagnostic(_: &Diagnostic) {}
323
324 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
325                 Cell::new(default_track_diagnostic));
326
327 #[derive(Default)]
328 pub struct HandlerFlags {
329     /// If false, warning-level lints are suppressed.
330     /// (rustc: see `--allow warnings` and `--cap-lints`)
331     pub can_emit_warnings: bool,
332     /// If true, error-level diagnostics are upgraded to bug-level.
333     /// (rustc: see `-Z treat-err-as-bug`)
334     pub treat_err_as_bug: Option<usize>,
335     /// If true, immediately emit diagnostics that would otherwise be buffered.
336     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
337     pub dont_buffer_diagnostics: bool,
338     /// If true, immediately print bugs registered with `delay_span_bug`.
339     /// (rustc: see `-Z report-delayed-bugs`)
340     pub report_delayed_bugs: bool,
341     /// show macro backtraces even for non-local macros.
342     /// (rustc: see `-Z external-macro-backtrace`)
343     pub external_macro_backtrace: bool,
344 }
345
346 impl Drop for Handler {
347     fn drop(&mut self) {
348         if self.err_count() == 0 {
349             let mut bugs = self.delayed_span_bugs.borrow_mut();
350             let has_bugs = !bugs.is_empty();
351             for bug in bugs.drain(..) {
352                 DiagnosticBuilder::new_diagnostic(self, bug).emit();
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(color_config: ColorConfig,
363                             can_emit_warnings: bool,
364                             treat_err_as_bug: Option<usize>,
365                             cm: Option<Lrc<SourceMapperDyn>>)
366                             -> Handler {
367         Handler::with_tty_emitter_and_flags(
368             color_config,
369             cm,
370             HandlerFlags {
371                 can_emit_warnings,
372                 treat_err_as_bug,
373                 .. Default::default()
374             })
375     }
376
377     pub fn with_tty_emitter_and_flags(color_config: ColorConfig,
378                                       cm: Option<Lrc<SourceMapperDyn>>,
379                                       flags: HandlerFlags)
380                                       -> Handler {
381         let emitter = Box::new(EmitterWriter::stderr(color_config, cm, false, false));
382         Handler::with_emitter_and_flags(emitter, flags)
383     }
384
385     pub fn with_emitter(can_emit_warnings: bool,
386                         treat_err_as_bug: Option<usize>,
387                         e: Box<dyn Emitter + sync::Send>)
388                         -> Handler {
389         Handler::with_emitter_and_flags(
390             e,
391             HandlerFlags {
392                 can_emit_warnings,
393                 treat_err_as_bug,
394                 .. Default::default()
395             })
396     }
397
398     pub fn with_emitter_and_flags(e: Box<dyn Emitter + sync::Send>, flags: HandlerFlags) -> Handler
399     {
400         Handler {
401             flags,
402             err_count: AtomicUsize::new(0),
403             emitter: Lock::new(e),
404             continue_after_error: AtomicBool::new(true),
405             delayed_span_bugs: Lock::new(Vec::new()),
406             taught_diagnostics: Default::default(),
407             emitted_diagnostic_codes: Default::default(),
408             emitted_diagnostics: Default::default(),
409         }
410     }
411
412     pub fn set_continue_after_error(&self, continue_after_error: bool) {
413         self.continue_after_error.store(continue_after_error, SeqCst);
414     }
415
416     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
417     ///
418     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
419     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
420     /// the overall count of emitted error diagnostics.
421     pub fn reset_err_count(&self) {
422         // actually frees the underlying memory (which `clear` would not do)
423         *self.emitted_diagnostics.borrow_mut() = Default::default();
424         self.err_count.store(0, SeqCst);
425     }
426
427     pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
428         DiagnosticBuilder::new(self, Level::Cancelled, "")
429     }
430
431     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
432                                                     sp: S,
433                                                     msg: &str)
434                                                     -> DiagnosticBuilder<'a> {
435         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
436         result.set_span(sp);
437         if !self.flags.can_emit_warnings {
438             result.cancel();
439         }
440         result
441     }
442     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
443                                                               sp: S,
444                                                               msg: &str,
445                                                               code: DiagnosticId)
446                                                               -> DiagnosticBuilder<'a> {
447         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
448         result.set_span(sp);
449         result.code(code);
450         if !self.flags.can_emit_warnings {
451             result.cancel();
452         }
453         result
454     }
455     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
456         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
457         if !self.flags.can_emit_warnings {
458             result.cancel();
459         }
460         result
461     }
462     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
463                                                    sp: S,
464                                                    msg: &str)
465                                                    -> DiagnosticBuilder<'a> {
466         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
467         result.set_span(sp);
468         result
469     }
470     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
471                                                              sp: S,
472                                                              msg: &str,
473                                                              code: DiagnosticId)
474                                                              -> DiagnosticBuilder<'a> {
475         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
476         result.set_span(sp);
477         result.code(code);
478         result
479     }
480     // FIXME: This method should be removed (every error should have an associated error code).
481     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
482         DiagnosticBuilder::new(self, Level::Error, msg)
483     }
484     pub fn struct_err_with_code<'a>(
485         &'a self,
486         msg: &str,
487         code: DiagnosticId,
488     ) -> DiagnosticBuilder<'a> {
489         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
490         result.code(code);
491         result
492     }
493     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
494                                                      sp: S,
495                                                      msg: &str)
496                                                      -> DiagnosticBuilder<'a> {
497         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
498         result.set_span(sp);
499         result
500     }
501     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
502                                                                sp: S,
503                                                                msg: &str,
504                                                                code: DiagnosticId)
505                                                                -> DiagnosticBuilder<'a> {
506         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
507         result.set_span(sp);
508         result.code(code);
509         result
510     }
511     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
512         DiagnosticBuilder::new(self, Level::Fatal, msg)
513     }
514
515     pub fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
516         err.cancel();
517     }
518
519     fn panic_if_treat_err_as_bug(&self) {
520         if self.treat_err_as_bug() {
521             let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
522                 (0, _) => return,
523                 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
524                 (1, _) => return,
525                 (count, as_bug) => {
526                     format!(
527                         "aborting after {} errors due to `-Z treat-err-as-bug={}`",
528                         count,
529                         as_bug,
530                     )
531                 }
532             };
533             panic!(s);
534         }
535     }
536
537     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
538         self.emit(&sp.into(), msg, Fatal);
539         FatalError
540     }
541     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
542                                                     sp: S,
543                                                     msg: &str,
544                                                     code: DiagnosticId)
545                                                     -> FatalError {
546         self.emit_with_code(&sp.into(), msg, code, Fatal);
547         FatalError
548     }
549     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
550         self.emit(&sp.into(), msg, Error);
551     }
552     pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
553                                                 sp: S,
554                                                 msg: &str)
555                                                 -> DiagnosticBuilder<'a> {
556         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
557         result.set_span(sp);
558         result
559     }
560     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
561         self.emit_with_code(&sp.into(), msg, code, Error);
562     }
563     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
564         self.emit(&sp.into(), msg, Warning);
565     }
566     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
567         self.emit_with_code(&sp.into(), msg, code, Warning);
568     }
569     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
570         self.emit(&sp.into(), msg, Bug);
571         panic!(ExplicitBug);
572     }
573     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
574         if self.treat_err_as_bug() {
575             // FIXME: don't abort here if report_delayed_bugs is off
576             self.span_bug(sp, msg);
577         }
578         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
579         diagnostic.set_span(sp.into());
580         self.delay_as_bug(diagnostic);
581     }
582     fn delay_as_bug(&self, diagnostic: Diagnostic) {
583         if self.flags.report_delayed_bugs {
584             DiagnosticBuilder::new_diagnostic(self, diagnostic.clone()).emit();
585         }
586         self.delayed_span_bugs.borrow_mut().push(diagnostic);
587     }
588     pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
589         self.emit(&sp.into(), msg, Bug);
590     }
591     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
592         self.emit(&sp.into(), msg, Note);
593     }
594     pub fn span_note_diag<'a>(&'a self,
595                               sp: Span,
596                               msg: &str)
597                               -> DiagnosticBuilder<'a> {
598         let mut db = DiagnosticBuilder::new(self, Note, msg);
599         db.set_span(sp);
600         db
601     }
602     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
603         self.span_bug(sp, &format!("unimplemented {}", msg));
604     }
605     pub fn failure(&self, msg: &str) {
606         DiagnosticBuilder::new(self, FailureNote, msg).emit()
607     }
608     pub fn fatal(&self, msg: &str) -> FatalError {
609         if self.treat_err_as_bug() {
610             self.bug(msg);
611         }
612         DiagnosticBuilder::new(self, Fatal, msg).emit();
613         FatalError
614     }
615     pub fn err(&self, msg: &str) {
616         if self.treat_err_as_bug() {
617             self.bug(msg);
618         }
619         let mut db = DiagnosticBuilder::new(self, Error, msg);
620         db.emit();
621     }
622     pub fn warn(&self, msg: &str) {
623         let mut db = DiagnosticBuilder::new(self, Warning, msg);
624         db.emit();
625     }
626     fn treat_err_as_bug(&self) -> bool {
627         self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
628     }
629     pub fn note_without_error(&self, msg: &str) {
630         let mut db = DiagnosticBuilder::new(self, Note, msg);
631         db.emit();
632     }
633     pub fn bug(&self, msg: &str) -> ! {
634         let mut db = DiagnosticBuilder::new(self, Bug, msg);
635         db.emit();
636         panic!(ExplicitBug);
637     }
638     pub fn unimpl(&self, msg: &str) -> ! {
639         self.bug(&format!("unimplemented {}", msg));
640     }
641
642     fn bump_err_count(&self) {
643         self.err_count.fetch_add(1, SeqCst);
644         self.panic_if_treat_err_as_bug();
645     }
646
647     pub fn err_count(&self) -> usize {
648         self.err_count.load(SeqCst)
649     }
650
651     pub fn has_errors(&self) -> bool {
652         self.err_count() > 0
653     }
654
655     pub fn print_error_count(&self, registry: &Registry) {
656         let s = match self.err_count() {
657             0 => return,
658             1 => "aborting due to previous error".to_string(),
659             _ => format!("aborting due to {} previous errors", self.err_count())
660         };
661         if self.treat_err_as_bug() {
662             return;
663         }
664
665         let _ = self.fatal(&s);
666
667         let can_show_explain = self.emitter.borrow().should_show_explain();
668         let are_there_diagnostics = !self.emitted_diagnostic_codes.borrow().is_empty();
669         if can_show_explain && are_there_diagnostics {
670             let mut error_codes = self
671                 .emitted_diagnostic_codes
672                 .borrow()
673                 .iter()
674                 .filter_map(|x| match &x {
675                     DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
676                         Some(s.clone())
677                     }
678                     _ => None,
679                 })
680                 .collect::<Vec<_>>();
681             if !error_codes.is_empty() {
682                 error_codes.sort();
683                 if error_codes.len() > 1 {
684                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
685                     self.failure(&format!("Some errors have detailed explanations: {}{}",
686                                           error_codes[..limit].join(", "),
687                                           if error_codes.len() > 9 { "..." } else { "." }));
688                     self.failure(&format!("For more information about an error, try \
689                                            `rustc --explain {}`.",
690                                           &error_codes[0]));
691                 } else {
692                     self.failure(&format!("For more information about this error, try \
693                                            `rustc --explain {}`.",
694                                           &error_codes[0]));
695                 }
696             }
697         }
698     }
699
700     pub fn abort_if_errors(&self) {
701         if self.err_count() == 0 {
702             return;
703         }
704         FatalError.raise();
705     }
706     pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
707         if lvl == Warning && !self.flags.can_emit_warnings {
708             return;
709         }
710         let mut db = DiagnosticBuilder::new(self, lvl, msg);
711         db.set_span(msp.clone());
712         db.emit();
713         if !self.continue_after_error.load(SeqCst) {
714             self.abort_if_errors();
715         }
716     }
717     pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
718         if lvl == Warning && !self.flags.can_emit_warnings {
719             return;
720         }
721         let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code), msg);
722         db.set_span(msp.clone());
723         db.emit();
724         if !self.continue_after_error.load(SeqCst) {
725             self.abort_if_errors();
726         }
727     }
728
729     /// `true` if we haven't taught a diagnostic with this code already.
730     /// The caller must then teach the user about such a diagnostic.
731     ///
732     /// Used to suppress emitting the same error multiple times with extended explanation when
733     /// calling `-Zteach`.
734     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
735         self.taught_diagnostics.borrow_mut().insert(code.clone())
736     }
737
738     pub fn force_print_db(&self, mut db: DiagnosticBuilder<'_>) {
739         self.emitter.borrow_mut().emit(&db);
740         db.cancel();
741     }
742
743     fn emit_db(&self, db: &DiagnosticBuilder<'_>) {
744         let diagnostic = &**db;
745
746         TRACK_DIAGNOSTICS.with(|track_diagnostics| {
747             track_diagnostics.get()(diagnostic);
748         });
749
750         if let Some(ref code) = diagnostic.code {
751             self.emitted_diagnostic_codes.borrow_mut().insert(code.clone());
752         }
753
754         let diagnostic_hash = {
755             use std::hash::Hash;
756             let mut hasher = StableHasher::new();
757             diagnostic.hash(&mut hasher);
758             hasher.finish()
759         };
760
761         // Only emit the diagnostic if we haven't already emitted an equivalent
762         // one:
763         if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) {
764             self.emitter.borrow_mut().emit(db);
765             if db.is_error() {
766                 self.bump_err_count();
767             }
768         }
769     }
770 }
771
772
773 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
774 pub enum Level {
775     Bug,
776     Fatal,
777     // An error which while not immediately fatal, should stop the compiler
778     // progressing beyond the current phase.
779     PhaseFatal,
780     Error,
781     Warning,
782     Note,
783     Help,
784     Cancelled,
785     FailureNote,
786 }
787
788 impl fmt::Display for Level {
789     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
790         self.to_str().fmt(f)
791     }
792 }
793
794 impl Level {
795     fn color(self) -> ColorSpec {
796         let mut spec = ColorSpec::new();
797         match self {
798             Bug | Fatal | PhaseFatal | Error => {
799                 spec.set_fg(Some(Color::Red))
800                     .set_intense(true);
801             }
802             Warning => {
803                 spec.set_fg(Some(Color::Yellow))
804                     .set_intense(cfg!(windows));
805             }
806             Note => {
807                 spec.set_fg(Some(Color::Green))
808                     .set_intense(true);
809             }
810             Help => {
811                 spec.set_fg(Some(Color::Cyan))
812                     .set_intense(true);
813             }
814             FailureNote => {}
815             Cancelled => unreachable!(),
816         }
817         spec
818     }
819
820     pub fn to_str(self) -> &'static str {
821         match self {
822             Bug => "error: internal compiler error",
823             Fatal | PhaseFatal | Error => "error",
824             Warning => "warning",
825             Note => "note",
826             Help => "help",
827             FailureNote => "",
828             Cancelled => panic!("Shouldn't call on cancelled error"),
829         }
830     }
831
832     pub fn is_failure_note(&self) -> bool {
833         match *self {
834             FailureNote => true,
835             _ => false,
836         }
837     }
838 }