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