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