]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Make Handler more thread-safe
[rust.git] / src / librustc_errors / lib.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13       html_root_url = "https://doc.rust-lang.org/nightly/")]
14
15 #![feature(custom_attribute)]
16 #![allow(unused_attributes)]
17 #![feature(range_contains)]
18 #![cfg_attr(unix, feature(libc))]
19 #![feature(optin_builtin_traits)]
20
21 extern crate atty;
22 extern crate termcolor;
23 #[cfg(unix)]
24 extern crate libc;
25 extern crate rustc_data_structures;
26 extern crate serialize as rustc_serialize;
27 extern crate syntax_pos;
28 extern crate unicode_width;
29
30 pub use emitter::ColorConfig;
31
32 use self::Level::*;
33
34 use emitter::{Emitter, EmitterWriter};
35
36 use rustc_data_structures::sync::{self, Lrc, Lock, LockCell};
37 use rustc_data_structures::fx::FxHashSet;
38 use rustc_data_structures::stable_hasher::StableHasher;
39
40 use std::borrow::Cow;
41 use std::cell::Cell;
42 use std::{error, fmt};
43 use std::sync::atomic::AtomicUsize;
44 use std::sync::atomic::Ordering::SeqCst;
45 use std::panic;
46
47 use termcolor::{ColorSpec, Color};
48
49 mod diagnostic;
50 mod diagnostic_builder;
51 pub mod emitter;
52 mod snippet;
53 pub mod registry;
54 mod styled_buffer;
55 mod lock;
56
57 use syntax_pos::{BytePos, Loc, FileLinesResult, FileMap, FileName, MultiSpan, Span, NO_EXPANSION};
58
59 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
60 pub struct CodeSuggestion {
61     /// Each substitute can have multiple variants due to multiple
62     /// applicable suggestions
63     ///
64     /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
65     /// `foo` and `bar` on their own:
66     ///
67     /// ```
68     /// vec![
69     ///     Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
70     ///     Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
71     /// ]
72     /// ```
73     ///
74     /// or by replacing the entire span:
75     ///
76     /// ```
77     /// vec![
78     ///     Substitution { parts: vec![(0..7, "a.b")] },
79     ///     Substitution { parts: vec![(0..7, "x.y")] },
80     /// ]
81     /// ```
82     pub substitutions: Vec<Substitution>,
83     pub msg: String,
84     pub show_code_when_inline: bool,
85     /// Whether or not the suggestion is approximate
86     ///
87     /// Sometimes we may show suggestions with placeholders,
88     /// which are useful for users but not useful for
89     /// tools like rustfix
90     pub approximate: bool,
91 }
92
93 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
94 /// See the docs on `CodeSuggestion::substitutions`
95 pub struct Substitution {
96     pub parts: Vec<SubstitutionPart>,
97 }
98
99 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
100 pub struct SubstitutionPart {
101     pub span: Span,
102     pub snippet: String,
103 }
104
105 pub type CodeMapperDyn = CodeMapper + sync::Send + sync::Sync;
106
107 pub trait CodeMapper {
108     fn lookup_char_pos(&self, pos: BytePos) -> Loc;
109     fn span_to_lines(&self, sp: Span) -> FileLinesResult;
110     fn span_to_string(&self, sp: Span) -> String;
111     fn span_to_filename(&self, sp: Span) -> FileName;
112     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
113     fn call_span_if_macro(&self, sp: Span) -> Span;
114     fn ensure_filemap_source_present(&self, file_map: Lrc<FileMap>) -> bool;
115     fn doctest_offset_line(&self, line: usize) -> usize;
116 }
117
118 impl CodeSuggestion {
119     /// Returns the assembled code suggestions and whether they should be shown with an underline.
120     pub fn splice_lines(&self, cm: &CodeMapperDyn)
121                         -> Vec<(String, Vec<SubstitutionPart>)> {
122         use syntax_pos::{CharPos, Loc, Pos};
123
124         fn push_trailing(buf: &mut String,
125                          line_opt: Option<&Cow<str>>,
126                          lo: &Loc,
127                          hi_opt: Option<&Loc>) {
128             let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
129             if let Some(line) = line_opt {
130                 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
131                     let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
132                     buf.push_str(match hi_opt {
133                         Some(hi) => &line[lo..hi],
134                         None => &line[lo..],
135                     });
136                 }
137                 if let None = hi_opt {
138                     buf.push('\n');
139                 }
140             }
141         }
142
143         assert!(!self.substitutions.is_empty());
144
145         self.substitutions.iter().cloned().map(|mut substitution| {
146             // Assumption: all spans are in the same file, and all spans
147             // are disjoint. Sort in ascending order.
148             substitution.parts.sort_by_key(|part| part.span.lo());
149
150             // Find the bounding span.
151             let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
152             let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
153             let bounding_span = Span::new(lo, hi, NO_EXPANSION);
154             let lines = cm.span_to_lines(bounding_span).unwrap();
155             assert!(!lines.lines.is_empty());
156
157             // To build up the result, we do this for each span:
158             // - push the line segment trailing the previous span
159             //   (at the beginning a "phantom" span pointing at the start of the line)
160             // - push lines between the previous and current span (if any)
161             // - if the previous and current span are not on the same line
162             //   push the line segment leading up to the current span
163             // - splice in the span substitution
164             //
165             // Finally push the trailing line segment of the last span
166             let fm = &lines.file;
167             let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
168             prev_hi.col = CharPos::from_usize(0);
169
170             let mut prev_line = fm.get_line(lines.lines[0].line_index);
171             let mut buf = String::new();
172
173             for part in &substitution.parts {
174                 let cur_lo = cm.lookup_char_pos(part.span.lo());
175                 if prev_hi.line == cur_lo.line {
176                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
177                 } else {
178                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
179                     // push lines between the previous and current span (if any)
180                     for idx in prev_hi.line..(cur_lo.line - 1) {
181                         if let Some(line) = fm.get_line(idx) {
182                             buf.push_str(line.as_ref());
183                             buf.push('\n');
184                         }
185                     }
186                     if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
187                         buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
188                     }
189                 }
190                 buf.push_str(&part.snippet);
191                 prev_hi = cm.lookup_char_pos(part.span.hi());
192                 prev_line = fm.get_line(prev_hi.line - 1);
193             }
194             // if the replacement already ends with a newline, don't print the next line
195             if !buf.ends_with('\n') {
196                 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
197             }
198             // remove trailing newlines
199             while buf.ends_with('\n') {
200                 buf.pop();
201             }
202             (buf, substitution.parts)
203         }).collect()
204     }
205 }
206
207 /// Used as a return value to signify a fatal error occurred. (It is also
208 /// used as the argument to panic at the moment, but that will eventually
209 /// not be true.)
210 #[derive(Copy, Clone, Debug)]
211 #[must_use]
212 pub struct FatalError;
213
214 pub struct FatalErrorMarker;
215
216 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
217 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
218 impl !Send for FatalError {}
219
220 impl FatalError {
221     pub fn raise(self) -> ! {
222         panic::resume_unwind(Box::new(FatalErrorMarker))
223     }
224 }
225
226 impl fmt::Display for FatalError {
227     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
228         write!(f, "parser fatal error")
229     }
230 }
231
232 impl error::Error for FatalError {
233     fn description(&self) -> &str {
234         "The parser has encountered a fatal error"
235     }
236 }
237
238 /// Signifies that the compiler died with an explicit call to `.bug`
239 /// or `.span_bug` rather than a failed assertion, etc.
240 #[derive(Copy, Clone, Debug)]
241 pub struct ExplicitBug;
242
243 impl fmt::Display for ExplicitBug {
244     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
245         write!(f, "parser internal bug")
246     }
247 }
248
249 impl error::Error for ExplicitBug {
250     fn description(&self) -> &str {
251         "The parser has encountered an internal bug"
252     }
253 }
254
255 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
256 pub use diagnostic_builder::DiagnosticBuilder;
257
258 /// A handler deals with errors; certain errors
259 /// (fatal, bug, unimpl) may cause immediate exit,
260 /// others log errors for later reporting.
261 pub struct Handler {
262     pub flags: HandlerFlags,
263
264     err_count: AtomicUsize,
265     emitter: Lock<Box<Emitter + sync::Send>>,
266     continue_after_error: LockCell<bool>,
267     delayed_span_bug: Lock<Option<Diagnostic>>,
268
269     // This set contains the `DiagnosticId` of all emitted diagnostics to avoid
270     // emitting the same diagnostic with extended help (`--teach`) twice, which
271     // would be uneccessary repetition.
272     taught_diagnostics: Lock<FxHashSet<DiagnosticId>>,
273
274     /// Used to suggest rustc --explain <error code>
275     emitted_diagnostic_codes: Lock<FxHashSet<DiagnosticId>>,
276
277     // This set contains a hash of every diagnostic that has been emitted by
278     // this handler. These hashes is used to avoid emitting the same error
279     // twice.
280     emitted_diagnostics: Lock<FxHashSet<u128>>,
281 }
282
283 fn default_track_diagnostic(_: &Diagnostic) {}
284
285 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
286                 Cell::new(default_track_diagnostic));
287
288 #[derive(Default)]
289 pub struct HandlerFlags {
290     pub can_emit_warnings: bool,
291     pub treat_err_as_bug: bool,
292     pub external_macro_backtrace: bool,
293 }
294
295 impl Handler {
296     pub fn with_tty_emitter(color_config: ColorConfig,
297                             can_emit_warnings: bool,
298                             treat_err_as_bug: bool,
299                             cm: Option<Lrc<CodeMapperDyn>>)
300                             -> Handler {
301         Handler::with_tty_emitter_and_flags(
302             color_config,
303             cm,
304             HandlerFlags {
305                 can_emit_warnings,
306                 treat_err_as_bug,
307                 .. Default::default()
308             })
309     }
310
311     pub fn with_tty_emitter_and_flags(color_config: ColorConfig,
312                                       cm: Option<Lrc<CodeMapperDyn>>,
313                                       flags: HandlerFlags)
314                                       -> Handler {
315         let emitter = Box::new(EmitterWriter::stderr(color_config, cm, false, false));
316         Handler::with_emitter_and_flags(emitter, flags)
317     }
318
319     pub fn with_emitter(can_emit_warnings: bool,
320                         treat_err_as_bug: bool,
321                         e: Box<Emitter + sync::Send>)
322                         -> Handler {
323         Handler::with_emitter_and_flags(
324             e,
325             HandlerFlags {
326                 can_emit_warnings,
327                 treat_err_as_bug,
328                 .. Default::default()
329             })
330     }
331
332     pub fn with_emitter_and_flags(e: Box<Emitter + sync::Send>, flags: HandlerFlags) -> Handler {
333         Handler {
334             flags,
335             err_count: AtomicUsize::new(0),
336             emitter: Lock::new(e),
337             continue_after_error: LockCell::new(true),
338             delayed_span_bug: Lock::new(None),
339             taught_diagnostics: Lock::new(FxHashSet()),
340             emitted_diagnostic_codes: Lock::new(FxHashSet()),
341             emitted_diagnostics: Lock::new(FxHashSet()),
342         }
343     }
344
345     pub fn set_continue_after_error(&self, continue_after_error: bool) {
346         self.continue_after_error.set(continue_after_error);
347     }
348
349     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
350     ///
351     /// NOTE: DO NOT call this function from rustc. It is only meant to be called from external
352     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
353     /// the overall count of emitted error diagnostics.
354     pub fn reset_err_count(&self) {
355         *self.emitted_diagnostics.borrow_mut() = FxHashSet();
356         self.err_count.store(0, SeqCst);
357     }
358
359     pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
360         DiagnosticBuilder::new(self, Level::Cancelled, "")
361     }
362
363     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
364                                                     sp: S,
365                                                     msg: &str)
366                                                     -> DiagnosticBuilder<'a> {
367         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
368         result.set_span(sp);
369         if !self.flags.can_emit_warnings {
370             result.cancel();
371         }
372         result
373     }
374     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
375                                                               sp: S,
376                                                               msg: &str,
377                                                               code: DiagnosticId)
378                                                               -> DiagnosticBuilder<'a> {
379         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
380         result.set_span(sp);
381         result.code(code);
382         if !self.flags.can_emit_warnings {
383             result.cancel();
384         }
385         result
386     }
387     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
388         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
389         if !self.flags.can_emit_warnings {
390             result.cancel();
391         }
392         result
393     }
394     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
395                                                    sp: S,
396                                                    msg: &str)
397                                                    -> DiagnosticBuilder<'a> {
398         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
399         result.set_span(sp);
400         result
401     }
402     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
403                                                              sp: S,
404                                                              msg: &str,
405                                                              code: DiagnosticId)
406                                                              -> DiagnosticBuilder<'a> {
407         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
408         result.set_span(sp);
409         result.code(code);
410         result
411     }
412     // FIXME: This method should be removed (every error should have an associated error code).
413     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
414         DiagnosticBuilder::new(self, Level::Error, msg)
415     }
416     pub fn struct_err_with_code<'a>(
417         &'a self,
418         msg: &str,
419         code: DiagnosticId,
420     ) -> DiagnosticBuilder<'a> {
421         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
422         result.code(code);
423         result
424     }
425     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
426                                                      sp: S,
427                                                      msg: &str)
428                                                      -> DiagnosticBuilder<'a> {
429         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
430         result.set_span(sp);
431         result
432     }
433     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
434                                                                sp: S,
435                                                                msg: &str,
436                                                                code: DiagnosticId)
437                                                                -> DiagnosticBuilder<'a> {
438         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
439         result.set_span(sp);
440         result.code(code);
441         result
442     }
443     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
444         DiagnosticBuilder::new(self, Level::Fatal, msg)
445     }
446
447     pub fn cancel(&self, err: &mut DiagnosticBuilder) {
448         err.cancel();
449     }
450
451     fn panic_if_treat_err_as_bug(&self) {
452         if self.flags.treat_err_as_bug {
453             panic!("encountered error with `-Z treat_err_as_bug");
454         }
455     }
456
457     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
458         self.emit(&sp.into(), msg, Fatal);
459         FatalError
460     }
461     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
462                                                     sp: S,
463                                                     msg: &str,
464                                                     code: DiagnosticId)
465                                                     -> FatalError {
466         self.emit_with_code(&sp.into(), msg, code, Fatal);
467         FatalError
468     }
469     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
470         self.emit(&sp.into(), msg, Error);
471     }
472     pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
473                                                 sp: S,
474                                                 msg: &str)
475                                                 -> DiagnosticBuilder<'a> {
476         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
477         result.set_span(sp);
478         result
479     }
480     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
481         self.emit_with_code(&sp.into(), msg, code, Error);
482     }
483     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
484         self.emit(&sp.into(), msg, Warning);
485     }
486     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
487         self.emit_with_code(&sp.into(), msg, code, Warning);
488     }
489     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
490         self.emit(&sp.into(), msg, Bug);
491         panic!(ExplicitBug);
492     }
493     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
494         if self.flags.treat_err_as_bug {
495             self.span_bug(sp, msg);
496         }
497         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
498         diagnostic.set_span(sp.into());
499         *self.delayed_span_bug.borrow_mut() = Some(diagnostic);
500     }
501     pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
502         self.emit(&sp.into(), msg, Bug);
503     }
504     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
505         self.emit(&sp.into(), msg, Note);
506     }
507     pub fn span_note_diag<'a>(&'a self,
508                               sp: Span,
509                               msg: &str)
510                               -> DiagnosticBuilder<'a> {
511         let mut db = DiagnosticBuilder::new(self, Note, msg);
512         db.set_span(sp);
513         db
514     }
515     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
516         self.span_bug(sp, &format!("unimplemented {}", msg));
517     }
518     pub fn failure(&self, msg: &str) {
519         DiagnosticBuilder::new(self, FailureNote, msg).emit()
520     }
521     pub fn fatal(&self, msg: &str) -> FatalError {
522         if self.flags.treat_err_as_bug {
523             self.bug(msg);
524         }
525         DiagnosticBuilder::new(self, Fatal, msg).emit();
526         FatalError
527     }
528     pub fn err(&self, msg: &str) {
529         if self.flags.treat_err_as_bug {
530             self.bug(msg);
531         }
532         let mut db = DiagnosticBuilder::new(self, Error, msg);
533         db.emit();
534     }
535     pub fn warn(&self, msg: &str) {
536         let mut db = DiagnosticBuilder::new(self, Warning, msg);
537         db.emit();
538     }
539     pub fn note_without_error(&self, msg: &str) {
540         let mut db = DiagnosticBuilder::new(self, Note, msg);
541         db.emit();
542     }
543     pub fn bug(&self, msg: &str) -> ! {
544         let mut db = DiagnosticBuilder::new(self, Bug, msg);
545         db.emit();
546         panic!(ExplicitBug);
547     }
548     pub fn unimpl(&self, msg: &str) -> ! {
549         self.bug(&format!("unimplemented {}", msg));
550     }
551
552     fn bump_err_count(&self) {
553         self.panic_if_treat_err_as_bug();
554         self.err_count.fetch_add(1, SeqCst);
555     }
556
557     pub fn err_count(&self) -> usize {
558         self.err_count.load(SeqCst)
559     }
560
561     pub fn has_errors(&self) -> bool {
562         self.err_count() > 0
563     }
564
565     pub fn print_error_count(&self) {
566         let s = match self.err_count() {
567             0 => return,
568             1 => "aborting due to previous error".to_string(),
569             _ => format!("aborting due to {} previous errors", self.err_count())
570         };
571
572         let _ = self.fatal(&s);
573
574         let can_show_explain = self.emitter.borrow().should_show_explain();
575         let are_there_diagnostics = !self.emitted_diagnostic_codes.borrow().is_empty();
576         if can_show_explain && are_there_diagnostics {
577             let mut error_codes =
578                 self.emitted_diagnostic_codes.borrow()
579                                              .clone()
580                                              .into_iter()
581                                              .filter_map(|x| match x {
582                                                  DiagnosticId::Error(ref s) => Some(s.clone()),
583                                                  _ => None,
584                                              })
585                                              .collect::<Vec<_>>();
586             if !error_codes.is_empty() {
587                 error_codes.sort();
588                 if error_codes.len() > 1 {
589                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
590                     self.failure(&format!("Some errors occurred: {}{}",
591                                           error_codes[..limit].join(", "),
592                                           if error_codes.len() > 9 { "..." } else { "." }));
593                     self.failure(&format!("For more information about an error, try \
594                                            `rustc --explain {}`.",
595                                           &error_codes[0]));
596                 } else {
597                     self.failure(&format!("For more information about this error, try \
598                                            `rustc --explain {}`.",
599                                           &error_codes[0]));
600                 }
601             }
602         }
603     }
604
605     pub fn abort_if_errors(&self) {
606         if self.err_count() == 0 {
607             if let Some(bug) = self.delayed_span_bug.borrow_mut().take() {
608                 DiagnosticBuilder::new_diagnostic(self, bug).emit();
609             }
610             return;
611         }
612         FatalError.raise();
613     }
614     pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
615         if lvl == Warning && !self.flags.can_emit_warnings {
616             return;
617         }
618         let mut db = DiagnosticBuilder::new(self, lvl, msg);
619         db.set_span(msp.clone());
620         db.emit();
621         if !self.continue_after_error.get() {
622             self.abort_if_errors();
623         }
624     }
625     pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
626         if lvl == Warning && !self.flags.can_emit_warnings {
627             return;
628         }
629         let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code), msg);
630         db.set_span(msp.clone());
631         db.emit();
632         if !self.continue_after_error.get() {
633             self.abort_if_errors();
634         }
635     }
636
637     /// `true` if we haven't taught a diagnostic with this code already.
638     /// The caller must then teach the user about such a diagnostic.
639     ///
640     /// Used to suppress emitting the same error multiple times with extended explanation when
641     /// calling `-Zteach`.
642     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
643         self.taught_diagnostics.borrow_mut().insert(code.clone())
644     }
645
646     pub fn force_print_db(&self, mut db: DiagnosticBuilder) {
647         self.emitter.borrow_mut().emit(&db);
648         db.cancel();
649     }
650
651     fn emit_db(&self, db: &DiagnosticBuilder) {
652         let diagnostic = &**db;
653
654         TRACK_DIAGNOSTICS.with(|track_diagnostics| {
655             track_diagnostics.get()(diagnostic);
656         });
657
658         if let Some(ref code) = diagnostic.code {
659             self.emitted_diagnostic_codes.borrow_mut().insert(code.clone());
660         }
661
662         let diagnostic_hash = {
663             use std::hash::Hash;
664             let mut hasher = StableHasher::new();
665             diagnostic.hash(&mut hasher);
666             hasher.finish()
667         };
668
669         // Only emit the diagnostic if we haven't already emitted an equivalent
670         // one:
671         if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) {
672             self.emitter.borrow_mut().emit(db);
673             if db.is_error() {
674                 self.bump_err_count();
675             }
676         }
677     }
678 }
679
680
681 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
682 pub enum Level {
683     Bug,
684     Fatal,
685     // An error which while not immediately fatal, should stop the compiler
686     // progressing beyond the current phase.
687     PhaseFatal,
688     Error,
689     Warning,
690     Note,
691     Help,
692     Cancelled,
693     FailureNote,
694 }
695
696 impl fmt::Display for Level {
697     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
698         self.to_str().fmt(f)
699     }
700 }
701
702 impl Level {
703     fn color(self) -> ColorSpec {
704         let mut spec = ColorSpec::new();
705         match self {
706             Bug | Fatal | PhaseFatal | Error => {
707                 spec.set_fg(Some(Color::Red))
708                     .set_intense(true);
709             }
710             Warning => {
711                 spec.set_fg(Some(Color::Yellow))
712                     .set_intense(cfg!(windows));
713             }
714             Note => {
715                 spec.set_fg(Some(Color::Green))
716                     .set_intense(true);
717             }
718             Help => {
719                 spec.set_fg(Some(Color::Cyan))
720                     .set_intense(true);
721             }
722             FailureNote => {}
723             Cancelled => unreachable!(),
724         }
725         spec
726     }
727
728     pub fn to_str(self) -> &'static str {
729         match self {
730             Bug => "error: internal compiler error",
731             Fatal | PhaseFatal | Error => "error",
732             Warning => "warning",
733             Note => "note",
734             Help => "help",
735             FailureNote => "",
736             Cancelled => panic!("Shouldn't call on cancelled error"),
737         }
738     }
739
740     pub fn is_failure_note(&self) -> bool {
741         match *self {
742             FailureNote => true,
743             _ => false,
744         }
745     }
746 }