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