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