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