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