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