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)]
23 #![feature(conservative_impl_trait)]
25 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
26 #![cfg_attr(stage0, feature(rustc_private))]
27 #![cfg_attr(stage0, feature(staged_api))]
31 extern crate serialize as rustc_serialize;
32 extern crate syntax_pos;
34 pub use emitter::ColorConfig;
38 use emitter::{Emitter, EmitterWriter};
40 use std::cell::{RefCell, Cell};
41 use std::{error, fmt};
45 pub mod diagnostic_builder;
49 pub mod styled_buffer;
52 use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION};
54 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
56 /// A FullSpan renders with both with an initial line for the
57 /// message, prefixed by file:linenum, followed by a summary of
58 /// the source code covered by the span.
61 /// A suggestion renders with both with an initial line for the
62 /// message, prefixed by file:linenum, followed by a summary
63 /// of hypothetical source code, where each `String` is spliced
64 /// into the lines in place of the code covered by each span.
65 Suggestion(CodeSuggestion),
68 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
69 pub struct CodeSuggestion {
70 /// Each substitute can have multiple variants due to multiple
71 /// applicable suggestions
73 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
74 /// `foo` and `bar` on their own:
78 /// (0..3, vec!["a", "x"]),
79 /// (4..7, vec!["b", "y"]),
83 /// or by replacing the entire span:
86 /// vec![(0..7, vec!["a.b", "x.y"])]
88 pub substitution_parts: Vec<Substitution>,
92 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
93 /// See the docs on `CodeSuggestion::substitutions`
94 pub struct Substitution {
96 pub substitutions: Vec<String>,
99 pub trait CodeMapper {
100 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
101 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
102 fn span_to_string(&self, sp: Span) -> String;
103 fn span_to_filename(&self, sp: Span) -> FileName;
104 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
107 impl CodeSuggestion {
108 /// Returns the number of substitutions
109 fn substitutions(&self) -> usize {
110 self.substitution_parts[0].substitutions.len()
113 /// Returns the number of substitutions
114 pub fn substitution_spans<'a>(&'a self) -> impl Iterator<Item = Span> + 'a {
115 self.substitution_parts.iter().map(|sub| sub.span)
118 /// Returns the assembled code suggestions.
119 pub fn splice_lines(&self, cm: &CodeMapper) -> Vec<String> {
120 use syntax_pos::{CharPos, Loc, Pos};
122 fn push_trailing(buf: &mut String,
123 line_opt: Option<&str>,
125 hi_opt: Option<&Loc>) {
126 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
127 if let Some(line) = line_opt {
128 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
129 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
130 buf.push_str(match hi_opt {
131 Some(hi) => &line[lo..hi],
135 if let None = hi_opt {
141 if self.substitution_parts.is_empty() {
142 return vec![String::new()];
145 let mut primary_spans: Vec<_> = self.substitution_parts
147 .map(|sub| (sub.span, &sub.substitutions))
150 // Assumption: all spans are in the same file, and all spans
151 // are disjoint. Sort in ascending order.
152 primary_spans.sort_by_key(|sp| sp.0.lo);
154 // Find the bounding span.
155 let lo = primary_spans.iter().map(|sp| sp.0.lo).min().unwrap();
156 let hi = primary_spans.iter().map(|sp| sp.0.hi).min().unwrap();
157 let bounding_span = Span {
162 let lines = cm.span_to_lines(bounding_span).unwrap();
163 assert!(!lines.lines.is_empty());
165 // To build up the result, we do this for each span:
166 // - push the line segment trailing the previous span
167 // (at the beginning a "phantom" span pointing at the start of the line)
168 // - push lines between the previous and current span (if any)
169 // - if the previous and current span are not on the same line
170 // push the line segment leading up to the current span
171 // - splice in the span substitution
173 // Finally push the trailing line segment of the last span
174 let fm = &lines.file;
175 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo);
176 prev_hi.col = CharPos::from_usize(0);
178 let mut prev_line = fm.get_line(lines.lines[0].line_index);
179 let mut bufs = vec![String::new(); self.substitutions()];
181 for (sp, substitutes) in primary_spans {
182 let cur_lo = cm.lookup_char_pos(sp.lo);
183 for (buf, substitute) in bufs.iter_mut().zip(substitutes) {
184 if prev_hi.line == cur_lo.line {
185 push_trailing(buf, prev_line, &prev_hi, Some(&cur_lo));
187 push_trailing(buf, prev_line, &prev_hi, None);
188 // push lines between the previous and current span (if any)
189 for idx in prev_hi.line..(cur_lo.line - 1) {
190 if let Some(line) = fm.get_line(idx) {
195 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
196 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
199 buf.push_str(substitute);
201 prev_hi = cm.lookup_char_pos(sp.hi);
202 prev_line = fm.get_line(prev_hi.line - 1);
204 for buf in &mut bufs {
205 // if the replacement already ends with a newline, don't print the next line
206 if !buf.ends_with('\n') {
207 push_trailing(buf, prev_line, &prev_hi, None);
209 // remove trailing newline
216 /// Used as a return value to signify a fatal error occurred. (It is also
217 /// used as the argument to panic at the moment, but that will eventually
219 #[derive(Copy, Clone, Debug)]
221 pub struct FatalError;
223 impl fmt::Display for FatalError {
224 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
225 write!(f, "parser fatal error")
229 impl error::Error for FatalError {
230 fn description(&self) -> &str {
231 "The parser has encountered a fatal error"
235 /// Signifies that the compiler died with an explicit call to `.bug`
236 /// or `.span_bug` rather than a failed assertion, etc.
237 #[derive(Copy, Clone, Debug)]
238 pub struct ExplicitBug;
240 impl fmt::Display for ExplicitBug {
241 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
242 write!(f, "parser internal bug")
246 impl error::Error for ExplicitBug {
247 fn description(&self) -> &str {
248 "The parser has encountered an internal bug"
252 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, StringPart};
253 pub use diagnostic_builder::DiagnosticBuilder;
255 /// A handler deals with errors; certain errors
256 /// (fatal, bug, unimpl) may cause immediate exit,
257 /// others log errors for later reporting.
259 err_count: Cell<usize>,
260 emitter: RefCell<Box<Emitter>>,
261 pub can_emit_warnings: bool,
262 treat_err_as_bug: bool,
263 continue_after_error: Cell<bool>,
264 delayed_span_bug: RefCell<Option<(MultiSpan, String)>>,
268 pub fn with_tty_emitter(color_config: ColorConfig,
269 can_emit_warnings: bool,
270 treat_err_as_bug: bool,
271 cm: Option<Rc<CodeMapper>>)
273 let emitter = Box::new(EmitterWriter::stderr(color_config, cm));
274 Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter)
277 pub fn with_emitter(can_emit_warnings: bool,
278 treat_err_as_bug: bool,
282 err_count: Cell::new(0),
283 emitter: RefCell::new(e),
284 can_emit_warnings: can_emit_warnings,
285 treat_err_as_bug: treat_err_as_bug,
286 continue_after_error: Cell::new(true),
287 delayed_span_bug: RefCell::new(None),
291 pub fn set_continue_after_error(&self, continue_after_error: bool) {
292 self.continue_after_error.set(continue_after_error);
295 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
296 DiagnosticBuilder::new(self, Level::Cancelled, "")
299 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
302 -> DiagnosticBuilder<'a> {
303 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
305 if !self.can_emit_warnings {
310 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
314 -> DiagnosticBuilder<'a> {
315 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
317 result.code(code.to_owned());
318 if !self.can_emit_warnings {
323 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
324 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
325 if !self.can_emit_warnings {
330 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
333 -> DiagnosticBuilder<'a> {
334 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
338 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
342 -> DiagnosticBuilder<'a> {
343 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
345 result.code(code.to_owned());
348 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
349 DiagnosticBuilder::new(self, Level::Error, msg)
351 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
354 -> DiagnosticBuilder<'a> {
355 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
359 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
363 -> DiagnosticBuilder<'a> {
364 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
366 result.code(code.to_owned());
369 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
370 DiagnosticBuilder::new(self, Level::Fatal, msg)
373 pub fn cancel(&self, err: &mut DiagnosticBuilder) {
377 fn panic_if_treat_err_as_bug(&self) {
378 if self.treat_err_as_bug {
379 panic!("encountered error with `-Z treat_err_as_bug");
383 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
384 self.emit(&sp.into(), msg, Fatal);
385 self.panic_if_treat_err_as_bug();
388 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
393 self.emit_with_code(&sp.into(), msg, code, Fatal);
394 self.panic_if_treat_err_as_bug();
397 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
398 self.emit(&sp.into(), msg, Error);
399 self.panic_if_treat_err_as_bug();
401 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
404 -> DiagnosticBuilder<'a> {
405 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
409 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
410 self.emit_with_code(&sp.into(), msg, code, Error);
411 self.panic_if_treat_err_as_bug();
413 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
414 self.emit(&sp.into(), msg, Warning);
416 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
417 self.emit_with_code(&sp.into(), msg, code, Warning);
419 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
420 self.emit(&sp.into(), msg, Bug);
423 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
424 if self.treat_err_as_bug {
425 self.span_bug(sp, msg);
427 let mut delayed = self.delayed_span_bug.borrow_mut();
428 *delayed = Some((sp.into(), msg.to_string()));
430 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
431 self.emit(&sp.into(), msg, Bug);
433 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
434 self.emit(&sp.into(), msg, Note);
436 pub fn span_note_diag<'a>(&'a self,
439 -> DiagnosticBuilder<'a> {
440 let mut db = DiagnosticBuilder::new(self, Note, msg);
444 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
445 self.span_bug(sp, &format!("unimplemented {}", msg));
447 pub fn fatal(&self, msg: &str) -> FatalError {
448 if self.treat_err_as_bug {
451 let mut db = DiagnosticBuilder::new(self, Fatal, msg);
455 pub fn err(&self, msg: &str) {
456 if self.treat_err_as_bug {
459 let mut db = DiagnosticBuilder::new(self, Error, msg);
462 pub fn warn(&self, msg: &str) {
463 let mut db = DiagnosticBuilder::new(self, Warning, msg);
466 pub fn note_without_error(&self, msg: &str) {
467 let mut db = DiagnosticBuilder::new(self, Note, msg);
470 pub fn bug(&self, msg: &str) -> ! {
471 let mut db = DiagnosticBuilder::new(self, Bug, msg);
475 pub fn unimpl(&self, msg: &str) -> ! {
476 self.bug(&format!("unimplemented {}", msg));
479 pub fn bump_err_count(&self) {
480 self.err_count.set(self.err_count.get() + 1);
483 pub fn err_count(&self) -> usize {
487 pub fn has_errors(&self) -> bool {
488 self.err_count.get() > 0
490 pub fn abort_if_errors(&self) {
492 match self.err_count.get() {
494 let delayed_bug = self.delayed_span_bug.borrow();
496 Some((ref span, ref errmsg)) => {
497 self.span_bug(span.clone(), errmsg);
504 1 => s = "aborting due to previous error".to_string(),
506 s = format!("aborting due to {} previous errors", self.err_count.get());
510 panic!(self.fatal(&s));
512 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
513 if lvl == Warning && !self.can_emit_warnings {
516 let mut db = DiagnosticBuilder::new(self, lvl, msg);
517 db.set_span(msp.clone());
519 if !self.continue_after_error.get() {
520 self.abort_if_errors();
523 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
524 if lvl == Warning && !self.can_emit_warnings {
527 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
528 db.set_span(msp.clone());
530 if !self.continue_after_error.get() {
531 self.abort_if_errors();
537 #[derive(Copy, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
541 // An error which while not immediately fatal, should stop the compiler
542 // progressing beyond the current phase.
551 impl fmt::Display for Level {
552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
558 pub fn color(self) -> term::color::Color {
560 Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
563 term::color::BRIGHT_YELLOW
568 Note => term::color::BRIGHT_GREEN,
569 Help => term::color::BRIGHT_CYAN,
570 Cancelled => unreachable!(),
574 pub fn to_str(self) -> &'static str {
576 Bug => "error: internal compiler error",
577 Fatal | PhaseFatal | Error => "error",
578 Warning => "warning",
581 Cancelled => panic!("Shouldn't call on cancelled error"),
586 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
587 where M: FnOnce() -> String
591 None => diag.bug(&msg()),