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