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