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.
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.
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/")]
15 #![feature(custom_attribute)]
16 #![allow(unused_attributes)]
17 #![feature(range_contains)]
18 #![cfg_attr(unix, feature(libc))]
19 #![feature(optin_builtin_traits)]
22 extern crate termcolor;
25 extern crate rustc_data_structures;
26 extern crate serialize as rustc_serialize;
27 extern crate syntax_pos;
28 extern crate unicode_width;
30 pub use emitter::ColorConfig;
34 use emitter::{Emitter, EmitterWriter};
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;
42 use std::{error, fmt};
43 use std::sync::atomic::AtomicUsize;
44 use std::sync::atomic::Ordering::SeqCst;
47 use termcolor::{ColorSpec, Color};
50 mod diagnostic_builder;
57 use syntax_pos::{BytePos, Loc, FileLinesResult, FileMap, FileName, MultiSpan, Span, NO_EXPANSION};
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
64 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
65 /// `foo` and `bar` on their own:
69 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
70 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
74 /// or by replacing the entire span:
78 /// Substitution { parts: vec![(0..7, "a.b")] },
79 /// Substitution { parts: vec![(0..7, "x.y")] },
82 pub substitutions: Vec<Substitution>,
84 pub show_code_when_inline: bool,
85 /// Whether or not the suggestion is approximate
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,
93 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
94 /// See the docs on `CodeSuggestion::substitutions`
95 pub struct Substitution {
96 pub parts: Vec<SubstitutionPart>,
99 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
100 pub struct SubstitutionPart {
105 pub type CodeMapperDyn = CodeMapper + sync::Send + sync::Sync;
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;
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};
124 fn push_trailing(buf: &mut String,
125 line_opt: Option<&Cow<str>>,
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],
137 if let None = hi_opt {
143 assert!(!self.substitutions.is_empty());
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());
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());
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
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);
170 let mut prev_line = fm.get_line(lines.lines[0].line_index);
171 let mut buf = String::new();
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));
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());
186 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
187 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
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);
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);
198 // remove trailing newlines
199 while buf.ends_with('\n') {
202 (buf, substitution.parts)
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
210 #[derive(Copy, Clone, Debug)]
212 pub struct FatalError;
214 pub struct FatalErrorMarker;
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 {}
221 pub fn raise(self) -> ! {
222 panic::resume_unwind(Box::new(FatalErrorMarker))
226 impl fmt::Display for FatalError {
227 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
228 write!(f, "parser fatal error")
232 impl error::Error for FatalError {
233 fn description(&self) -> &str {
234 "The parser has encountered a fatal error"
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;
243 impl fmt::Display for ExplicitBug {
244 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
245 write!(f, "parser internal bug")
249 impl error::Error for ExplicitBug {
250 fn description(&self) -> &str {
251 "The parser has encountered an internal bug"
255 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
256 pub use diagnostic_builder::DiagnosticBuilder;
258 /// A handler deals with errors; certain errors
259 /// (fatal, bug, unimpl) may cause immediate exit,
260 /// others log errors for later reporting.
262 pub flags: HandlerFlags,
264 err_count: AtomicUsize,
265 emitter: Lock<Box<Emitter + sync::Send>>,
266 continue_after_error: LockCell<bool>,
267 delayed_span_bug: Lock<Option<Diagnostic>>,
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>>,
274 /// Used to suggest rustc --explain <error code>
275 emitted_diagnostic_codes: Lock<FxHashSet<DiagnosticId>>,
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
280 emitted_diagnostics: Lock<FxHashSet<u128>>,
283 fn default_track_diagnostic(_: &Diagnostic) {}
285 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
286 Cell::new(default_track_diagnostic));
289 pub struct HandlerFlags {
290 pub can_emit_warnings: bool,
291 pub treat_err_as_bug: bool,
292 pub external_macro_backtrace: bool,
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>>)
301 Handler::with_tty_emitter_and_flags(
307 .. Default::default()
311 pub fn with_tty_emitter_and_flags(color_config: ColorConfig,
312 cm: Option<Lrc<CodeMapperDyn>>,
315 let emitter = Box::new(EmitterWriter::stderr(color_config, cm, false, false));
316 Handler::with_emitter_and_flags(emitter, flags)
319 pub fn with_emitter(can_emit_warnings: bool,
320 treat_err_as_bug: bool,
321 e: Box<Emitter + sync::Send>)
323 Handler::with_emitter_and_flags(
328 .. Default::default()
332 pub fn with_emitter_and_flags(e: Box<Emitter + sync::Send>, flags: HandlerFlags) -> Handler {
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()),
345 pub fn set_continue_after_error(&self, continue_after_error: bool) {
346 self.continue_after_error.set(continue_after_error);
349 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
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);
359 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
360 DiagnosticBuilder::new(self, Level::Cancelled, "")
363 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
366 -> DiagnosticBuilder<'a> {
367 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
369 if !self.flags.can_emit_warnings {
374 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
378 -> DiagnosticBuilder<'a> {
379 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
382 if !self.flags.can_emit_warnings {
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 {
394 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
397 -> DiagnosticBuilder<'a> {
398 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
402 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
406 -> DiagnosticBuilder<'a> {
407 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
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)
416 pub fn struct_err_with_code<'a>(
420 ) -> DiagnosticBuilder<'a> {
421 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
425 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
428 -> DiagnosticBuilder<'a> {
429 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
433 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
437 -> DiagnosticBuilder<'a> {
438 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
443 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
444 DiagnosticBuilder::new(self, Level::Fatal, msg)
447 pub fn cancel(&self, err: &mut DiagnosticBuilder) {
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");
457 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
458 self.emit(&sp.into(), msg, Fatal);
461 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
466 self.emit_with_code(&sp.into(), msg, code, Fatal);
469 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
470 self.emit(&sp.into(), msg, Error);
472 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
475 -> DiagnosticBuilder<'a> {
476 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
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);
483 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
484 self.emit(&sp.into(), msg, Warning);
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);
489 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
490 self.emit(&sp.into(), msg, Bug);
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);
497 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
498 diagnostic.set_span(sp.into());
499 *self.delayed_span_bug.borrow_mut() = Some(diagnostic);
501 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
502 self.emit(&sp.into(), msg, Bug);
504 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
505 self.emit(&sp.into(), msg, Note);
507 pub fn span_note_diag<'a>(&'a self,
510 -> DiagnosticBuilder<'a> {
511 let mut db = DiagnosticBuilder::new(self, Note, msg);
515 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
516 self.span_bug(sp, &format!("unimplemented {}", msg));
518 pub fn failure(&self, msg: &str) {
519 DiagnosticBuilder::new(self, FailureNote, msg).emit()
521 pub fn fatal(&self, msg: &str) -> FatalError {
522 if self.flags.treat_err_as_bug {
525 DiagnosticBuilder::new(self, Fatal, msg).emit();
528 pub fn err(&self, msg: &str) {
529 if self.flags.treat_err_as_bug {
532 let mut db = DiagnosticBuilder::new(self, Error, msg);
535 pub fn warn(&self, msg: &str) {
536 let mut db = DiagnosticBuilder::new(self, Warning, msg);
539 pub fn note_without_error(&self, msg: &str) {
540 let mut db = DiagnosticBuilder::new(self, Note, msg);
543 pub fn bug(&self, msg: &str) -> ! {
544 let mut db = DiagnosticBuilder::new(self, Bug, msg);
548 pub fn unimpl(&self, msg: &str) -> ! {
549 self.bug(&format!("unimplemented {}", msg));
552 fn bump_err_count(&self) {
553 self.panic_if_treat_err_as_bug();
554 self.err_count.fetch_add(1, SeqCst);
557 pub fn err_count(&self) -> usize {
558 self.err_count.load(SeqCst)
561 pub fn has_errors(&self) -> bool {
565 pub fn print_error_count(&self) {
566 let s = match self.err_count() {
568 1 => "aborting due to previous error".to_string(),
569 _ => format!("aborting due to {} previous errors", self.err_count())
572 let _ = self.fatal(&s);
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()
581 .filter_map(|x| match x {
582 DiagnosticId::Error(ref s) => Some(s.clone()),
585 .collect::<Vec<_>>();
586 if !error_codes.is_empty() {
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 {}`.",
597 self.failure(&format!("For more information about this error, try \
598 `rustc --explain {}`.",
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();
614 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
615 if lvl == Warning && !self.flags.can_emit_warnings {
618 let mut db = DiagnosticBuilder::new(self, lvl, msg);
619 db.set_span(msp.clone());
621 if !self.continue_after_error.get() {
622 self.abort_if_errors();
625 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
626 if lvl == Warning && !self.flags.can_emit_warnings {
629 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code), msg);
630 db.set_span(msp.clone());
632 if !self.continue_after_error.get() {
633 self.abort_if_errors();
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.
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())
646 pub fn force_print_db(&self, mut db: DiagnosticBuilder) {
647 self.emitter.borrow_mut().emit(&db);
651 fn emit_db(&self, db: &DiagnosticBuilder) {
652 let diagnostic = &**db;
654 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
655 track_diagnostics.get()(diagnostic);
658 if let Some(ref code) = diagnostic.code {
659 self.emitted_diagnostic_codes.borrow_mut().insert(code.clone());
662 let diagnostic_hash = {
664 let mut hasher = StableHasher::new();
665 diagnostic.hash(&mut hasher);
669 // Only emit the diagnostic if we haven't already emitted an equivalent
671 if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) {
672 self.emitter.borrow_mut().emit(db);
674 self.bump_err_count();
681 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
685 // An error which while not immediately fatal, should stop the compiler
686 // progressing beyond the current phase.
696 impl fmt::Display for Level {
697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
703 fn color(self) -> ColorSpec {
704 let mut spec = ColorSpec::new();
706 Bug | Fatal | PhaseFatal | Error => {
707 spec.set_fg(Some(Color::Red))
711 spec.set_fg(Some(Color::Yellow))
712 .set_intense(cfg!(windows));
715 spec.set_fg(Some(Color::Green))
719 spec.set_fg(Some(Color::Cyan))
723 Cancelled => unreachable!(),
728 pub fn to_str(self) -> &'static str {
730 Bug => "error: internal compiler error",
731 Fatal | PhaseFatal | Error => "error",
732 Warning => "warning",
736 Cancelled => panic!("Shouldn't call on cancelled error"),
740 pub fn is_failure_note(&self) -> bool {