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