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/")]
20 #![feature(custom_attribute)]
21 #![allow(unused_attributes)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
24 #![feature(range_contains)]
29 extern crate serialize as rustc_serialize;
30 extern crate syntax_pos;
32 pub use emitter::ColorConfig;
36 use emitter::{Emitter, EmitterWriter};
38 use std::cell::{RefCell, Cell};
39 use std::{error, fmt};
43 pub mod diagnostic_builder;
47 pub mod styled_buffer;
50 use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION};
52 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
54 /// A FullSpan renders with both with an initial line for the
55 /// message, prefixed by file:linenum, followed by a summary of
56 /// the source code covered by the span.
59 /// A suggestion renders with both with an initial line for the
60 /// message, prefixed by file:linenum, followed by a summary
61 /// of hypothetical source code, where each `String` is spliced
62 /// into the lines in place of the code covered by each span.
63 Suggestion(CodeSuggestion),
66 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
67 pub struct CodeSuggestion {
69 pub substitutes: Vec<String>,
73 pub trait CodeMapper {
74 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
75 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
76 fn span_to_string(&self, sp: Span) -> String;
77 fn span_to_filename(&self, sp: Span) -> FileName;
78 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
82 /// Returns the assembled code suggestion.
83 pub fn splice_lines(&self, cm: &CodeMapper) -> String {
84 use syntax_pos::{CharPos, Loc, Pos};
86 fn push_trailing(buf: &mut String,
87 line_opt: Option<&str>,
89 hi_opt: Option<&Loc>) {
90 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
91 if let Some(line) = line_opt {
92 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
93 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
94 buf.push_str(match hi_opt {
95 Some(hi) => &line[lo..hi],
99 if let None = hi_opt {
105 let mut primary_spans = self.msp.primary_spans().to_owned();
107 assert_eq!(primary_spans.len(), self.substitutes.len());
108 if primary_spans.is_empty() {
112 // Assumption: all spans are in the same file, and all spans
113 // are disjoint. Sort in ascending order.
114 primary_spans.sort_by_key(|sp| sp.lo);
116 // Find the bounding span.
117 let lo = primary_spans.iter().map(|sp| sp.lo).min().unwrap();
118 let hi = primary_spans.iter().map(|sp| sp.hi).min().unwrap();
119 let bounding_span = Span {
124 let lines = cm.span_to_lines(bounding_span).unwrap();
125 assert!(!lines.lines.is_empty());
127 // To build up the result, we do this for each span:
128 // - push the line segment trailing the previous span
129 // (at the beginning a "phantom" span pointing at the start of the line)
130 // - push lines between the previous and current span (if any)
131 // - if the previous and current span are not on the same line
132 // push the line segment leading up to the current span
133 // - splice in the span substitution
135 // Finally push the trailing line segment of the last span
136 let fm = &lines.file;
137 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo);
138 prev_hi.col = CharPos::from_usize(0);
140 let mut prev_line = fm.get_line(lines.lines[0].line_index);
141 let mut buf = String::new();
143 for (sp, substitute) in primary_spans.iter().zip(self.substitutes.iter()) {
144 let cur_lo = cm.lookup_char_pos(sp.lo);
145 if prev_hi.line == cur_lo.line {
146 push_trailing(&mut buf, prev_line, &prev_hi, Some(&cur_lo));
148 push_trailing(&mut buf, prev_line, &prev_hi, None);
149 // push lines between the previous and current span (if any)
150 for idx in prev_hi.line..(cur_lo.line - 1) {
151 if let Some(line) = fm.get_line(idx) {
156 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
157 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
160 buf.push_str(substitute);
161 prev_hi = cm.lookup_char_pos(sp.hi);
162 prev_line = fm.get_line(prev_hi.line - 1);
164 push_trailing(&mut buf, prev_line, &prev_hi, None);
165 // remove trailing newline
171 /// Used as a return value to signify a fatal error occurred. (It is also
172 /// used as the argument to panic at the moment, but that will eventually
174 #[derive(Copy, Clone, Debug)]
176 pub struct FatalError;
178 impl fmt::Display for FatalError {
179 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
180 write!(f, "parser fatal error")
184 impl error::Error for FatalError {
185 fn description(&self) -> &str {
186 "The parser has encountered a fatal error"
190 /// Signifies that the compiler died with an explicit call to `.bug`
191 /// or `.span_bug` rather than a failed assertion, etc.
192 #[derive(Copy, Clone, Debug)]
193 pub struct ExplicitBug;
195 impl fmt::Display for ExplicitBug {
196 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
197 write!(f, "parser internal bug")
201 impl error::Error for ExplicitBug {
202 fn description(&self) -> &str {
203 "The parser has encountered an internal bug"
207 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, StringPart};
208 pub use diagnostic_builder::DiagnosticBuilder;
210 /// A handler deals with errors; certain errors
211 /// (fatal, bug, unimpl) may cause immediate exit,
212 /// others log errors for later reporting.
214 err_count: Cell<usize>,
215 emitter: RefCell<Box<Emitter>>,
216 pub can_emit_warnings: bool,
217 treat_err_as_bug: bool,
218 continue_after_error: Cell<bool>,
219 delayed_span_bug: RefCell<Option<(MultiSpan, String)>>,
223 pub fn with_tty_emitter(color_config: ColorConfig,
224 can_emit_warnings: bool,
225 treat_err_as_bug: bool,
226 cm: Option<Rc<CodeMapper>>)
228 let emitter = Box::new(EmitterWriter::stderr(color_config, cm));
229 Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter)
232 pub fn with_emitter(can_emit_warnings: bool,
233 treat_err_as_bug: bool,
237 err_count: Cell::new(0),
238 emitter: RefCell::new(e),
239 can_emit_warnings: can_emit_warnings,
240 treat_err_as_bug: treat_err_as_bug,
241 continue_after_error: Cell::new(true),
242 delayed_span_bug: RefCell::new(None),
246 pub fn set_continue_after_error(&self, continue_after_error: bool) {
247 self.continue_after_error.set(continue_after_error);
250 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
251 DiagnosticBuilder::new(self, Level::Cancelled, "")
254 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
257 -> DiagnosticBuilder<'a> {
258 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
260 if !self.can_emit_warnings {
265 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
269 -> DiagnosticBuilder<'a> {
270 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
272 result.code(code.to_owned());
273 if !self.can_emit_warnings {
278 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
279 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
280 if !self.can_emit_warnings {
285 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
288 -> DiagnosticBuilder<'a> {
289 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
293 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
297 -> DiagnosticBuilder<'a> {
298 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
300 result.code(code.to_owned());
303 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
304 DiagnosticBuilder::new(self, Level::Error, msg)
306 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
309 -> DiagnosticBuilder<'a> {
310 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
314 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
318 -> DiagnosticBuilder<'a> {
319 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
321 result.code(code.to_owned());
324 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
325 DiagnosticBuilder::new(self, Level::Fatal, msg)
328 pub fn cancel(&self, err: &mut DiagnosticBuilder) {
332 fn panic_if_treat_err_as_bug(&self) {
333 if self.treat_err_as_bug {
334 panic!("encountered error with `-Z treat_err_as_bug");
338 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
339 self.emit(&sp.into(), msg, Fatal);
340 self.panic_if_treat_err_as_bug();
343 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
348 self.emit_with_code(&sp.into(), msg, code, Fatal);
349 self.panic_if_treat_err_as_bug();
352 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
353 self.emit(&sp.into(), msg, Error);
354 self.panic_if_treat_err_as_bug();
356 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
359 -> DiagnosticBuilder<'a> {
360 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
364 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
365 self.emit_with_code(&sp.into(), msg, code, Error);
366 self.panic_if_treat_err_as_bug();
368 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
369 self.emit(&sp.into(), msg, Warning);
371 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
372 self.emit_with_code(&sp.into(), msg, code, Warning);
374 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
375 self.emit(&sp.into(), msg, Bug);
378 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
379 if self.treat_err_as_bug {
380 self.span_bug(sp, msg);
382 let mut delayed = self.delayed_span_bug.borrow_mut();
383 *delayed = Some((sp.into(), msg.to_string()));
385 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
386 self.emit(&sp.into(), msg, Bug);
388 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
389 self.emit(&sp.into(), msg, Note);
391 pub fn span_note_diag<'a>(&'a self,
394 -> DiagnosticBuilder<'a> {
395 let mut db = DiagnosticBuilder::new(self, Note, msg);
399 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
400 self.span_bug(sp, &format!("unimplemented {}", msg));
402 pub fn fatal(&self, msg: &str) -> FatalError {
403 if self.treat_err_as_bug {
406 let mut db = DiagnosticBuilder::new(self, Fatal, msg);
410 pub fn err(&self, msg: &str) {
411 if self.treat_err_as_bug {
414 let mut db = DiagnosticBuilder::new(self, Error, msg);
417 pub fn warn(&self, msg: &str) {
418 let mut db = DiagnosticBuilder::new(self, Warning, msg);
421 pub fn note_without_error(&self, msg: &str) {
422 let mut db = DiagnosticBuilder::new(self, Note, msg);
425 pub fn bug(&self, msg: &str) -> ! {
426 let mut db = DiagnosticBuilder::new(self, Bug, msg);
430 pub fn unimpl(&self, msg: &str) -> ! {
431 self.bug(&format!("unimplemented {}", msg));
434 pub fn bump_err_count(&self) {
435 self.err_count.set(self.err_count.get() + 1);
438 pub fn err_count(&self) -> usize {
442 pub fn has_errors(&self) -> bool {
443 self.err_count.get() > 0
445 pub fn abort_if_errors(&self) {
447 match self.err_count.get() {
449 let delayed_bug = self.delayed_span_bug.borrow();
451 Some((ref span, ref errmsg)) => {
452 self.span_bug(span.clone(), errmsg);
459 1 => s = "aborting due to previous error".to_string(),
461 s = format!("aborting due to {} previous errors", self.err_count.get());
465 panic!(self.fatal(&s));
467 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
468 if lvl == Warning && !self.can_emit_warnings {
471 let mut db = DiagnosticBuilder::new(self, lvl, msg);
472 db.set_span(msp.clone());
474 if !self.continue_after_error.get() {
475 self.abort_if_errors();
478 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
479 if lvl == Warning && !self.can_emit_warnings {
482 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
483 db.set_span(msp.clone());
485 if !self.continue_after_error.get() {
486 self.abort_if_errors();
492 #[derive(Copy, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
496 // An error which while not immediately fatal, should stop the compiler
497 // progressing beyond the current phase.
506 impl fmt::Display for Level {
507 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
513 pub fn color(self) -> term::color::Color {
515 Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
518 term::color::BRIGHT_YELLOW
523 Note => term::color::BRIGHT_GREEN,
524 Help => term::color::BRIGHT_CYAN,
525 Cancelled => unreachable!(),
529 pub fn to_str(self) -> &'static str {
531 Bug => "error: internal compiler error",
532 Fatal | PhaseFatal | Error => "error",
533 Warning => "warning",
536 Cancelled => panic!("Shouldn't call on cancelled error"),
541 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
542 where M: FnOnce() -> String
546 None => diag.bug(&msg()),