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