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