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