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