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