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 #![crate_name = "rustc_errors"]
12 #![crate_type = "dylib"]
13 #![crate_type = "rlib"]
14 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
15 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
16 html_root_url = "https://doc.rust-lang.org/nightly/")]
19 #![feature(custom_attribute)]
20 #![allow(unused_attributes)]
21 #![feature(range_contains)]
24 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
25 #![cfg_attr(stage0, feature(rustc_private))]
26 #![cfg_attr(stage0, feature(staged_api))]
30 extern crate serialize as rustc_serialize;
31 extern crate syntax_pos;
33 pub use emitter::ColorConfig;
37 use emitter::{Emitter, EmitterWriter};
39 use std::cell::{RefCell, Cell};
40 use std::{error, fmt};
44 pub mod diagnostic_builder;
48 pub mod styled_buffer;
51 use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION};
53 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
55 /// A FullSpan renders with both with an initial line for the
56 /// message, prefixed by file:linenum, followed by a summary of
57 /// the source code covered by the span.
60 /// A suggestion renders with both with an initial line for the
61 /// message, prefixed by file:linenum, followed by a summary
62 /// of hypothetical source code, where each `String` is spliced
63 /// into the lines in place of the code covered by each span.
64 Suggestion(CodeSuggestion),
67 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
68 pub struct CodeSuggestion {
70 pub substitutes: Vec<String>,
74 pub trait CodeMapper {
75 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
76 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
77 fn span_to_string(&self, sp: Span) -> String;
78 fn span_to_filename(&self, sp: Span) -> FileName;
79 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
83 /// Returns the assembled code suggestion.
84 pub fn splice_lines(&self, cm: &CodeMapper) -> String {
85 use syntax_pos::{CharPos, Loc, Pos};
87 fn push_trailing(buf: &mut String,
88 line_opt: Option<&str>,
90 hi_opt: Option<&Loc>) {
91 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
92 if let Some(line) = line_opt {
93 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
94 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
95 buf.push_str(match hi_opt {
96 Some(hi) => &line[lo..hi],
100 if let None = hi_opt {
106 let mut primary_spans = self.msp.primary_spans().to_owned();
108 assert_eq!(primary_spans.len(), self.substitutes.len());
109 if primary_spans.is_empty() {
113 // Assumption: all spans are in the same file, and all spans
114 // are disjoint. Sort in ascending order.
115 primary_spans.sort_by_key(|sp| sp.lo);
117 // Find the bounding span.
118 let lo = primary_spans.iter().map(|sp| sp.lo).min().unwrap();
119 let hi = primary_spans.iter().map(|sp| sp.hi).min().unwrap();
120 let bounding_span = Span {
125 let lines = cm.span_to_lines(bounding_span).unwrap();
126 assert!(!lines.lines.is_empty());
128 // To build up the result, we do this for each span:
129 // - push the line segment trailing the previous span
130 // (at the beginning a "phantom" span pointing at the start of the line)
131 // - push lines between the previous and current span (if any)
132 // - if the previous and current span are not on the same line
133 // push the line segment leading up to the current span
134 // - splice in the span substitution
136 // Finally push the trailing line segment of the last span
137 let fm = &lines.file;
138 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo);
139 prev_hi.col = CharPos::from_usize(0);
141 let mut prev_line = fm.get_line(lines.lines[0].line_index);
142 let mut buf = String::new();
144 for (sp, substitute) in primary_spans.iter().zip(self.substitutes.iter()) {
145 let cur_lo = cm.lookup_char_pos(sp.lo);
146 if prev_hi.line == cur_lo.line {
147 push_trailing(&mut buf, prev_line, &prev_hi, Some(&cur_lo));
149 push_trailing(&mut buf, prev_line, &prev_hi, None);
150 // push lines between the previous and current span (if any)
151 for idx in prev_hi.line..(cur_lo.line - 1) {
152 if let Some(line) = fm.get_line(idx) {
157 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
158 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
161 buf.push_str(substitute);
162 prev_hi = cm.lookup_char_pos(sp.hi);
163 prev_line = fm.get_line(prev_hi.line - 1);
165 push_trailing(&mut buf, prev_line, &prev_hi, None);
166 // remove trailing newline
172 /// Used as a return value to signify a fatal error occurred. (It is also
173 /// used as the argument to panic at the moment, but that will eventually
175 #[derive(Copy, Clone, Debug)]
177 pub struct FatalError;
179 impl fmt::Display for FatalError {
180 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
181 write!(f, "parser fatal error")
185 impl error::Error for FatalError {
186 fn description(&self) -> &str {
187 "The parser has encountered a fatal error"
191 /// Signifies that the compiler died with an explicit call to `.bug`
192 /// or `.span_bug` rather than a failed assertion, etc.
193 #[derive(Copy, Clone, Debug)]
194 pub struct ExplicitBug;
196 impl fmt::Display for ExplicitBug {
197 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
198 write!(f, "parser internal bug")
202 impl error::Error for ExplicitBug {
203 fn description(&self) -> &str {
204 "The parser has encountered an internal bug"
208 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, StringPart};
209 pub use diagnostic_builder::DiagnosticBuilder;
211 /// A handler deals with errors; certain errors
212 /// (fatal, bug, unimpl) may cause immediate exit,
213 /// others log errors for later reporting.
215 err_count: Cell<usize>,
216 emitter: RefCell<Box<Emitter>>,
217 pub can_emit_warnings: bool,
218 treat_err_as_bug: bool,
219 continue_after_error: Cell<bool>,
220 delayed_span_bug: RefCell<Option<(MultiSpan, String)>>,
224 pub fn with_tty_emitter(color_config: ColorConfig,
225 can_emit_warnings: bool,
226 treat_err_as_bug: bool,
227 cm: Option<Rc<CodeMapper>>)
229 let emitter = Box::new(EmitterWriter::stderr(color_config, cm));
230 Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter)
233 pub fn with_emitter(can_emit_warnings: bool,
234 treat_err_as_bug: bool,
238 err_count: Cell::new(0),
239 emitter: RefCell::new(e),
240 can_emit_warnings: can_emit_warnings,
241 treat_err_as_bug: treat_err_as_bug,
242 continue_after_error: Cell::new(true),
243 delayed_span_bug: RefCell::new(None),
247 pub fn set_continue_after_error(&self, continue_after_error: bool) {
248 self.continue_after_error.set(continue_after_error);
251 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
252 DiagnosticBuilder::new(self, Level::Cancelled, "")
255 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
258 -> DiagnosticBuilder<'a> {
259 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
261 if !self.can_emit_warnings {
266 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
270 -> DiagnosticBuilder<'a> {
271 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
273 result.code(code.to_owned());
274 if !self.can_emit_warnings {
279 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
280 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
281 if !self.can_emit_warnings {
286 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
289 -> DiagnosticBuilder<'a> {
290 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
294 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
298 -> DiagnosticBuilder<'a> {
299 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
301 result.code(code.to_owned());
304 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
305 DiagnosticBuilder::new(self, Level::Error, msg)
307 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
310 -> DiagnosticBuilder<'a> {
311 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
315 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
319 -> DiagnosticBuilder<'a> {
320 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
322 result.code(code.to_owned());
325 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
326 DiagnosticBuilder::new(self, Level::Fatal, msg)
329 pub fn cancel(&self, err: &mut DiagnosticBuilder) {
333 fn panic_if_treat_err_as_bug(&self) {
334 if self.treat_err_as_bug {
335 panic!("encountered error with `-Z treat_err_as_bug");
339 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
340 self.emit(&sp.into(), msg, Fatal);
341 self.panic_if_treat_err_as_bug();
344 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
349 self.emit_with_code(&sp.into(), msg, code, Fatal);
350 self.panic_if_treat_err_as_bug();
353 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
354 self.emit(&sp.into(), msg, Error);
355 self.panic_if_treat_err_as_bug();
357 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
360 -> DiagnosticBuilder<'a> {
361 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
365 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
366 self.emit_with_code(&sp.into(), msg, code, Error);
367 self.panic_if_treat_err_as_bug();
369 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
370 self.emit(&sp.into(), msg, Warning);
372 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
373 self.emit_with_code(&sp.into(), msg, code, Warning);
375 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
376 self.emit(&sp.into(), msg, Bug);
379 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
380 if self.treat_err_as_bug {
381 self.span_bug(sp, msg);
383 let mut delayed = self.delayed_span_bug.borrow_mut();
384 *delayed = Some((sp.into(), msg.to_string()));
386 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
387 self.emit(&sp.into(), msg, Bug);
389 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
390 self.emit(&sp.into(), msg, Note);
392 pub fn span_note_diag<'a>(&'a self,
395 -> DiagnosticBuilder<'a> {
396 let mut db = DiagnosticBuilder::new(self, Note, msg);
400 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
401 self.span_bug(sp, &format!("unimplemented {}", msg));
403 pub fn fatal(&self, msg: &str) -> FatalError {
404 if self.treat_err_as_bug {
407 let mut db = DiagnosticBuilder::new(self, Fatal, msg);
411 pub fn err(&self, msg: &str) {
412 if self.treat_err_as_bug {
415 let mut db = DiagnosticBuilder::new(self, Error, msg);
418 pub fn warn(&self, msg: &str) {
419 let mut db = DiagnosticBuilder::new(self, Warning, msg);
422 pub fn note_without_error(&self, msg: &str) {
423 let mut db = DiagnosticBuilder::new(self, Note, msg);
426 pub fn bug(&self, msg: &str) -> ! {
427 let mut db = DiagnosticBuilder::new(self, Bug, msg);
431 pub fn unimpl(&self, msg: &str) -> ! {
432 self.bug(&format!("unimplemented {}", msg));
435 pub fn bump_err_count(&self) {
436 self.err_count.set(self.err_count.get() + 1);
439 pub fn err_count(&self) -> usize {
443 pub fn has_errors(&self) -> bool {
444 self.err_count.get() > 0
446 pub fn abort_if_errors(&self) {
448 match self.err_count.get() {
450 let delayed_bug = self.delayed_span_bug.borrow();
452 Some((ref span, ref errmsg)) => {
453 self.span_bug(span.clone(), errmsg);
460 1 => s = "aborting due to previous error".to_string(),
462 s = format!("aborting due to {} previous errors", self.err_count.get());
466 panic!(self.fatal(&s));
468 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
469 if lvl == Warning && !self.can_emit_warnings {
472 let mut db = DiagnosticBuilder::new(self, lvl, msg);
473 db.set_span(msp.clone());
475 if !self.continue_after_error.get() {
476 self.abort_if_errors();
479 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
480 if lvl == Warning && !self.can_emit_warnings {
483 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
484 db.set_span(msp.clone());
486 if !self.continue_after_error.get() {
487 self.abort_if_errors();
493 #[derive(Copy, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
497 // An error which while not immediately fatal, should stop the compiler
498 // progressing beyond the current phase.
507 impl fmt::Display for Level {
508 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514 pub fn color(self) -> term::color::Color {
516 Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
519 term::color::BRIGHT_YELLOW
524 Note => term::color::BRIGHT_GREEN,
525 Help => term::color::BRIGHT_CYAN,
526 Cancelled => unreachable!(),
530 pub fn to_str(self) -> &'static str {
532 Bug => "error: internal compiler error",
533 Fatal | PhaseFatal | Error => "error",
534 Warning => "warning",
537 Cancelled => panic!("Shouldn't call on cancelled error"),
542 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
543 where M: FnOnce() -> String
547 None => diag.bug(&msg()),