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 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
18 #![cfg_attr(not(stage0), deny(warnings))]
20 #![feature(custom_attribute)]
21 #![allow(unused_attributes)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
24 #![feature(range_contains)]
28 extern crate serialize;
34 extern crate std_unicode;
35 extern crate serialize as rustc_serialize; // used by deriving
36 extern crate syntax_pos;
38 pub use emitter::ColorConfig;
42 use emitter::{Emitter, EmitterWriter};
44 use std::cell::{RefCell, Cell};
45 use std::{error, fmt};
49 pub mod diagnostic_builder;
53 pub mod styled_buffer;
56 use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION};
57 use syntax_pos::MacroBacktrace;
59 #[derive(Clone, Debug, PartialEq)]
61 /// A FullSpan renders with both with an initial line for the
62 /// message, prefixed by file:linenum, followed by a summary of
63 /// the source code covered by the span.
66 /// A suggestion renders with both with an initial line for the
67 /// message, prefixed by file:linenum, followed by a summary
68 /// of hypothetical source code, where each `String` is spliced
69 /// into the lines in place of the code covered by each span.
70 Suggestion(CodeSuggestion),
73 #[derive(Clone, Debug, PartialEq)]
74 pub struct CodeSuggestion {
76 pub substitutes: Vec<String>,
79 pub trait CodeMapper {
80 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
81 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
82 fn span_to_string(&self, sp: Span) -> String;
83 fn span_to_filename(&self, sp: Span) -> FileName;
84 fn macro_backtrace(&self, span: Span) -> Vec<MacroBacktrace>;
85 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
89 /// Returns the assembled code suggestion.
90 pub fn splice_lines(&self, cm: &CodeMapper) -> String {
91 use syntax_pos::{CharPos, Loc, Pos};
93 fn push_trailing(buf: &mut String,
94 line_opt: Option<&str>,
96 hi_opt: Option<&Loc>) {
97 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
98 if let Some(line) = line_opt {
100 buf.push_str(match hi_opt {
101 Some(hi) => &line[lo..hi],
105 if let None = hi_opt {
111 let mut primary_spans = self.msp.primary_spans().to_owned();
113 assert_eq!(primary_spans.len(), self.substitutes.len());
114 if primary_spans.is_empty() {
118 // Assumption: all spans are in the same file, and all spans
119 // are disjoint. Sort in ascending order.
120 primary_spans.sort_by_key(|sp| sp.lo);
122 // Find the bounding span.
123 let lo = primary_spans.iter().map(|sp| sp.lo).min().unwrap();
124 let hi = primary_spans.iter().map(|sp| sp.hi).min().unwrap();
125 let bounding_span = Span {
128 expn_id: NO_EXPANSION,
130 let lines = cm.span_to_lines(bounding_span).unwrap();
131 assert!(!lines.lines.is_empty());
133 // To build up the result, we do this for each span:
134 // - push the line segment trailing the previous span
135 // (at the beginning a "phantom" span pointing at the start of the line)
136 // - push lines between the previous and current span (if any)
137 // - if the previous and current span are not on the same line
138 // push the line segment leading up to the current span
139 // - splice in the span substitution
141 // Finally push the trailing line segment of the last span
142 let fm = &lines.file;
143 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo);
144 prev_hi.col = CharPos::from_usize(0);
146 let mut prev_line = fm.get_line(lines.lines[0].line_index);
147 let mut buf = String::new();
149 for (sp, substitute) in primary_spans.iter().zip(self.substitutes.iter()) {
150 let cur_lo = cm.lookup_char_pos(sp.lo);
151 if prev_hi.line == cur_lo.line {
152 push_trailing(&mut buf, prev_line, &prev_hi, Some(&cur_lo));
154 push_trailing(&mut buf, prev_line, &prev_hi, None);
155 // push lines between the previous and current span (if any)
156 for idx in prev_hi.line..(cur_lo.line - 1) {
157 if let Some(line) = fm.get_line(idx) {
162 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
163 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
166 buf.push_str(substitute);
167 prev_hi = cm.lookup_char_pos(sp.hi);
168 prev_line = fm.get_line(prev_hi.line - 1);
170 push_trailing(&mut buf, prev_line, &prev_hi, None);
171 // remove trailing newline
177 /// Used as a return value to signify a fatal error occurred. (It is also
178 /// used as the argument to panic at the moment, but that will eventually
180 #[derive(Copy, Clone, Debug)]
182 pub struct FatalError;
184 impl fmt::Display for FatalError {
185 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
186 write!(f, "parser fatal error")
190 impl error::Error for FatalError {
191 fn description(&self) -> &str {
192 "The parser has encountered a fatal error"
196 /// Signifies that the compiler died with an explicit call to `.bug`
197 /// or `.span_bug` rather than a failed assertion, etc.
198 #[derive(Copy, Clone, Debug)]
199 pub struct ExplicitBug;
201 impl fmt::Display for ExplicitBug {
202 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
203 write!(f, "parser internal bug")
207 impl error::Error for ExplicitBug {
208 fn description(&self) -> &str {
209 "The parser has encountered an internal bug"
213 pub use diagnostic::{Diagnostic, SubDiagnostic};
214 pub use diagnostic_builder::DiagnosticBuilder;
216 /// A handler deals with errors; certain errors
217 /// (fatal, bug, unimpl) may cause immediate exit,
218 /// others log errors for later reporting.
220 err_count: Cell<usize>,
221 emitter: RefCell<Box<Emitter>>,
222 pub can_emit_warnings: bool,
223 treat_err_as_bug: bool,
224 continue_after_error: Cell<bool>,
225 delayed_span_bug: RefCell<Option<(MultiSpan, String)>>,
229 pub fn with_tty_emitter(color_config: ColorConfig,
230 can_emit_warnings: bool,
231 treat_err_as_bug: bool,
232 cm: Option<Rc<CodeMapper>>)
234 let emitter = Box::new(EmitterWriter::stderr(color_config, cm));
235 Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter)
238 pub fn with_emitter(can_emit_warnings: bool,
239 treat_err_as_bug: bool,
243 err_count: Cell::new(0),
244 emitter: RefCell::new(e),
245 can_emit_warnings: can_emit_warnings,
246 treat_err_as_bug: treat_err_as_bug,
247 continue_after_error: Cell::new(true),
248 delayed_span_bug: RefCell::new(None),
252 pub fn set_continue_after_error(&self, continue_after_error: bool) {
253 self.continue_after_error.set(continue_after_error);
256 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
257 DiagnosticBuilder::new(self, Level::Cancelled, "")
260 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
263 -> DiagnosticBuilder<'a> {
264 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
266 if !self.can_emit_warnings {
271 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
275 -> DiagnosticBuilder<'a> {
276 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
278 result.code(code.to_owned());
279 if !self.can_emit_warnings {
284 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
285 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
286 if !self.can_emit_warnings {
291 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
294 -> DiagnosticBuilder<'a> {
295 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
299 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
303 -> DiagnosticBuilder<'a> {
304 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
306 result.code(code.to_owned());
309 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
310 DiagnosticBuilder::new(self, Level::Error, msg)
312 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
315 -> DiagnosticBuilder<'a> {
316 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
320 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
324 -> DiagnosticBuilder<'a> {
325 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
327 result.code(code.to_owned());
330 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
331 DiagnosticBuilder::new(self, Level::Fatal, msg)
334 pub fn cancel(&self, err: &mut DiagnosticBuilder) {
338 fn panic_if_treat_err_as_bug(&self) {
339 if self.treat_err_as_bug {
340 panic!("encountered error with `-Z treat_err_as_bug");
344 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
345 self.emit(&sp.into(), msg, Fatal);
346 self.panic_if_treat_err_as_bug();
349 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
354 self.emit_with_code(&sp.into(), msg, code, Fatal);
355 self.panic_if_treat_err_as_bug();
358 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
359 self.emit(&sp.into(), msg, Error);
360 self.panic_if_treat_err_as_bug();
362 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
365 -> DiagnosticBuilder<'a> {
366 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
370 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
371 self.emit_with_code(&sp.into(), msg, code, Error);
372 self.panic_if_treat_err_as_bug();
374 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
375 self.emit(&sp.into(), msg, Warning);
377 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
378 self.emit_with_code(&sp.into(), msg, code, Warning);
380 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
381 self.emit(&sp.into(), msg, Bug);
384 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
385 let mut delayed = self.delayed_span_bug.borrow_mut();
386 *delayed = Some((sp.into(), msg.to_string()));
388 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
389 self.emit(&sp.into(), msg, Bug);
391 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
392 self.emit(&sp.into(), msg, Note);
394 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
395 self.span_bug(sp, &format!("unimplemented {}", msg));
397 pub fn fatal(&self, msg: &str) -> FatalError {
398 if self.treat_err_as_bug {
401 let mut db = DiagnosticBuilder::new(self, Fatal, msg);
405 pub fn err(&self, msg: &str) {
406 if self.treat_err_as_bug {
409 let mut db = DiagnosticBuilder::new(self, Error, msg);
412 pub fn warn(&self, msg: &str) {
413 let mut db = DiagnosticBuilder::new(self, Warning, msg);
416 pub fn note_without_error(&self, msg: &str) {
417 let mut db = DiagnosticBuilder::new(self, Note, msg);
420 pub fn bug(&self, msg: &str) -> ! {
421 let mut db = DiagnosticBuilder::new(self, Bug, msg);
425 pub fn unimpl(&self, msg: &str) -> ! {
426 self.bug(&format!("unimplemented {}", msg));
429 pub fn bump_err_count(&self) {
430 self.err_count.set(self.err_count.get() + 1);
433 pub fn err_count(&self) -> usize {
437 pub fn has_errors(&self) -> bool {
438 self.err_count.get() > 0
440 pub fn abort_if_errors(&self) {
442 match self.err_count.get() {
444 let delayed_bug = self.delayed_span_bug.borrow();
446 Some((ref span, ref errmsg)) => {
447 self.span_bug(span.clone(), errmsg);
454 1 => s = "aborting due to previous error".to_string(),
456 s = format!("aborting due to {} previous errors", self.err_count.get());
460 panic!(self.fatal(&s));
462 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
463 if lvl == Warning && !self.can_emit_warnings {
466 let mut db = DiagnosticBuilder::new(self, lvl, msg);
467 db.set_span(msp.clone());
469 if !self.continue_after_error.get() {
470 self.abort_if_errors();
473 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
474 if lvl == Warning && !self.can_emit_warnings {
477 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
478 db.set_span(msp.clone());
480 if !self.continue_after_error.get() {
481 self.abort_if_errors();
487 #[derive(Copy, PartialEq, Clone, Debug)]
491 // An error which while not immediately fatal, should stop the compiler
492 // progressing beyond the current phase.
501 impl fmt::Display for Level {
502 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
508 pub fn color(self) -> term::color::Color {
510 Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
513 term::color::BRIGHT_YELLOW
518 Note => term::color::BRIGHT_GREEN,
519 Help => term::color::BRIGHT_CYAN,
520 Cancelled => unreachable!(),
524 pub fn to_str(self) -> &'static str {
526 Bug => "error: internal compiler error",
527 Fatal | PhaseFatal | Error => "error",
528 Warning => "warning",
531 Cancelled => panic!("Shouldn't call on cancelled error"),
536 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
537 where M: FnOnce() -> String
541 None => diag.bug(&msg()),