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