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