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 syntax_pos
;
31 pub use emitter
::ColorConfig
;
35 use emitter
::{Emitter, EmitterWriter}
;
37 use std
::cell
::{RefCell, Cell}
;
38 use std
::{error, fmt}
;
42 pub mod diagnostic_builder
;
46 pub mod styled_buffer
;
49 use syntax_pos
::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION}
;
50 use syntax_pos
::MacroBacktrace
;
52 #[derive(Clone, Debug, PartialEq)]
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)]
67 pub struct CodeSuggestion
{
69 pub substitutes
: Vec
<String
>,
72 pub trait CodeMapper
{
73 fn lookup_char_pos(&self, pos
: BytePos
) -> Loc
;
74 fn span_to_lines(&self, sp
: Span
) -> FileLinesResult
;
75 fn span_to_string(&self, sp
: Span
) -> String
;
76 fn span_to_filename(&self, sp
: Span
) -> FileName
;
77 fn macro_backtrace(&self, span
: Span
) -> Vec
<MacroBacktrace
>;
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
{
93 buf
.push_str(match hi_opt
{
94 Some(hi
) => &line
[lo
..hi
],
98 if let None
= hi_opt
{
104 let mut primary_spans
= self.msp
.primary_spans().to_owned();
106 assert_eq
!(primary_spans
.len(), self.substitutes
.len());
107 if primary_spans
.is_empty() {
111 // Assumption: all spans are in the same file, and all spans
112 // are disjoint. Sort in ascending order.
113 primary_spans
.sort_by_key(|sp
| sp
.lo
);
115 // Find the bounding span.
116 let lo
= primary_spans
.iter().map(|sp
| sp
.lo
).min().unwrap();
117 let hi
= primary_spans
.iter().map(|sp
| sp
.hi
).min().unwrap();
118 let bounding_span
= Span
{
121 expn_id
: NO_EXPANSION
,
123 let lines
= cm
.span_to_lines(bounding_span
).unwrap();
124 assert
!(!lines
.lines
.is_empty());
126 // To build up the result, we do this for each span:
127 // - push the line segment trailing the previous span
128 // (at the beginning a "phantom" span pointing at the start of the line)
129 // - push lines between the previous and current span (if any)
130 // - if the previous and current span are not on the same line
131 // push the line segment leading up to the current span
132 // - splice in the span substitution
134 // Finally push the trailing line segment of the last span
135 let fm
= &lines
.file
;
136 let mut prev_hi
= cm
.lookup_char_pos(bounding_span
.lo
);
137 prev_hi
.col
= CharPos
::from_usize(0);
139 let mut prev_line
= fm
.get_line(lines
.lines
[0].line_index
);
140 let mut buf
= String
::new();
142 for (sp
, substitute
) in primary_spans
.iter().zip(self.substitutes
.iter()) {
143 let cur_lo
= cm
.lookup_char_pos(sp
.lo
);
144 if prev_hi
.line
== cur_lo
.line
{
145 push_trailing(&mut buf
, prev_line
, &prev_hi
, Some(&cur_lo
));
147 push_trailing(&mut buf
, prev_line
, &prev_hi
, None
);
148 // push lines between the previous and current span (if any)
149 for idx
in prev_hi
.line
..(cur_lo
.line
- 1) {
150 if let Some(line
) = fm
.get_line(idx
) {
155 if let Some(cur_line
) = fm
.get_line(cur_lo
.line
- 1) {
156 buf
.push_str(&cur_line
[..cur_lo
.col
.to_usize()]);
159 buf
.push_str(substitute
);
160 prev_hi
= cm
.lookup_char_pos(sp
.hi
);
161 prev_line
= fm
.get_line(prev_hi
.line
- 1);
163 push_trailing(&mut buf
, prev_line
, &prev_hi
, None
);
164 // remove trailing newline
170 /// Used as a return value to signify a fatal error occurred. (It is also
171 /// used as the argument to panic at the moment, but that will eventually
173 #[derive(Copy, Clone, Debug)]
175 pub struct FatalError
;
177 impl fmt
::Display
for FatalError
{
178 fn fmt(&self, f
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
179 write
!(f
, "parser fatal error")
183 impl error
::Error
for FatalError
{
184 fn description(&self) -> &str {
185 "The parser has encountered a fatal error"
189 /// Signifies that the compiler died with an explicit call to `.bug`
190 /// or `.span_bug` rather than a failed assertion, etc.
191 #[derive(Copy, Clone, Debug)]
192 pub struct ExplicitBug
;
194 impl fmt
::Display
for ExplicitBug
{
195 fn fmt(&self, f
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
196 write
!(f
, "parser internal bug")
200 impl error
::Error
for ExplicitBug
{
201 fn description(&self) -> &str {
202 "The parser has encountered an internal bug"
206 pub use diagnostic
::{Diagnostic, SubDiagnostic}
;
207 pub use diagnostic_builder
::DiagnosticBuilder
;
209 /// A handler deals with errors; certain errors
210 /// (fatal, bug, unimpl) may cause immediate exit,
211 /// others log errors for later reporting.
213 err_count
: Cell
<usize>,
214 emitter
: RefCell
<Box
<Emitter
>>,
215 pub can_emit_warnings
: bool
,
216 treat_err_as_bug
: bool
,
217 continue_after_error
: Cell
<bool
>,
218 delayed_span_bug
: RefCell
<Option
<(MultiSpan
, String
)>>,
222 pub fn with_tty_emitter(color_config
: ColorConfig
,
223 can_emit_warnings
: bool
,
224 treat_err_as_bug
: bool
,
225 cm
: Option
<Rc
<CodeMapper
>>)
227 let emitter
= Box
::new(EmitterWriter
::stderr(color_config
, cm
));
228 Handler
::with_emitter(can_emit_warnings
, treat_err_as_bug
, emitter
)
231 pub fn with_emitter(can_emit_warnings
: bool
,
232 treat_err_as_bug
: bool
,
236 err_count
: Cell
::new(0),
237 emitter
: RefCell
::new(e
),
238 can_emit_warnings
: can_emit_warnings
,
239 treat_err_as_bug
: treat_err_as_bug
,
240 continue_after_error
: Cell
::new(true),
241 delayed_span_bug
: RefCell
::new(None
),
245 pub fn set_continue_after_error(&self, continue_after_error
: bool
) {
246 self.continue_after_error
.set(continue_after_error
);
249 pub fn struct_dummy
<'a
>(&'a
self) -> DiagnosticBuilder
<'a
> {
250 DiagnosticBuilder
::new(self, Level
::Cancelled
, "")
253 pub fn struct_span_warn
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
256 -> DiagnosticBuilder
<'a
> {
257 let mut result
= DiagnosticBuilder
::new(self, Level
::Warning
, msg
);
259 if !self.can_emit_warnings
{
264 pub fn struct_span_warn_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
268 -> DiagnosticBuilder
<'a
> {
269 let mut result
= DiagnosticBuilder
::new(self, Level
::Warning
, msg
);
271 result
.code(code
.to_owned());
272 if !self.can_emit_warnings
{
277 pub fn struct_warn
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
278 let mut result
= DiagnosticBuilder
::new(self, Level
::Warning
, msg
);
279 if !self.can_emit_warnings
{
284 pub fn struct_span_err
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
287 -> DiagnosticBuilder
<'a
> {
288 let mut result
= DiagnosticBuilder
::new(self, Level
::Error
, msg
);
292 pub fn struct_span_err_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
296 -> DiagnosticBuilder
<'a
> {
297 let mut result
= DiagnosticBuilder
::new(self, Level
::Error
, msg
);
299 result
.code(code
.to_owned());
302 pub fn struct_err
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
303 DiagnosticBuilder
::new(self, Level
::Error
, msg
)
305 pub fn struct_span_fatal
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
308 -> DiagnosticBuilder
<'a
> {
309 let mut result
= DiagnosticBuilder
::new(self, Level
::Fatal
, msg
);
313 pub fn struct_span_fatal_with_code
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
317 -> DiagnosticBuilder
<'a
> {
318 let mut result
= DiagnosticBuilder
::new(self, Level
::Fatal
, msg
);
320 result
.code(code
.to_owned());
323 pub fn struct_fatal
<'a
>(&'a
self, msg
: &str) -> DiagnosticBuilder
<'a
> {
324 DiagnosticBuilder
::new(self, Level
::Fatal
, msg
)
327 pub fn cancel(&self, err
: &mut DiagnosticBuilder
) {
331 fn panic_if_treat_err_as_bug(&self) {
332 if self.treat_err_as_bug
{
333 panic
!("encountered error with `-Z treat_err_as_bug");
337 pub fn span_fatal
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> FatalError
{
338 self.emit(&sp
.into(), msg
, Fatal
);
339 self.panic_if_treat_err_as_bug();
342 pub fn span_fatal_with_code
<S
: Into
<MultiSpan
>>(&self,
347 self.emit_with_code(&sp
.into(), msg
, code
, Fatal
);
348 self.panic_if_treat_err_as_bug();
351 pub fn span_err
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
352 self.emit(&sp
.into(), msg
, Error
);
353 self.panic_if_treat_err_as_bug();
355 pub fn mut_span_err
<'a
, S
: Into
<MultiSpan
>>(&'a
self,
358 -> DiagnosticBuilder
<'a
> {
359 let mut result
= DiagnosticBuilder
::new(self, Level
::Error
, msg
);
363 pub fn span_err_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: &str) {
364 self.emit_with_code(&sp
.into(), msg
, code
, Error
);
365 self.panic_if_treat_err_as_bug();
367 pub fn span_warn
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
368 self.emit(&sp
.into(), msg
, Warning
);
370 pub fn span_warn_with_code
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str, code
: &str) {
371 self.emit_with_code(&sp
.into(), msg
, code
, Warning
);
373 pub fn span_bug
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> ! {
374 self.emit(&sp
.into(), msg
, Bug
);
377 pub fn delay_span_bug
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
378 let mut delayed
= self.delayed_span_bug
.borrow_mut();
379 *delayed
= Some((sp
.into(), msg
.to_string()));
381 pub fn span_bug_no_panic
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
382 self.emit(&sp
.into(), msg
, Bug
);
384 pub fn span_note_without_error
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) {
385 self.emit(&sp
.into(), msg
, Note
);
387 pub fn span_unimpl
<S
: Into
<MultiSpan
>>(&self, sp
: S
, msg
: &str) -> ! {
388 self.span_bug(sp
, &format
!("unimplemented {}", msg
));
390 pub fn fatal(&self, msg
: &str) -> FatalError
{
391 if self.treat_err_as_bug
{
394 let mut db
= DiagnosticBuilder
::new(self, Fatal
, msg
);
398 pub fn err(&self, msg
: &str) {
399 if self.treat_err_as_bug
{
402 let mut db
= DiagnosticBuilder
::new(self, Error
, msg
);
405 pub fn warn(&self, msg
: &str) {
406 let mut db
= DiagnosticBuilder
::new(self, Warning
, msg
);
409 pub fn note_without_error(&self, msg
: &str) {
410 let mut db
= DiagnosticBuilder
::new(self, Note
, msg
);
413 pub fn bug(&self, msg
: &str) -> ! {
414 let mut db
= DiagnosticBuilder
::new(self, Bug
, msg
);
418 pub fn unimpl(&self, msg
: &str) -> ! {
419 self.bug(&format
!("unimplemented {}", msg
));
422 pub fn bump_err_count(&self) {
423 self.err_count
.set(self.err_count
.get() + 1);
426 pub fn err_count(&self) -> usize {
430 pub fn has_errors(&self) -> bool
{
431 self.err_count
.get() > 0
433 pub fn abort_if_errors(&self) {
435 match self.err_count
.get() {
437 let delayed_bug
= self.delayed_span_bug
.borrow();
439 Some((ref span
, ref errmsg
)) => {
440 self.span_bug(span
.clone(), errmsg
);
447 1 => s
= "aborting due to previous error".to_string(),
449 s
= format
!("aborting due to {} previous errors", self.err_count
.get());
453 panic
!(self.fatal(&s
));
455 pub fn emit(&self, msp
: &MultiSpan
, msg
: &str, lvl
: Level
) {
456 if lvl
== Warning
&& !self.can_emit_warnings
{
459 let mut db
= DiagnosticBuilder
::new(self, lvl
, msg
);
460 db
.set_span(msp
.clone());
462 if !self.continue_after_error
.get() {
463 self.abort_if_errors();
466 pub fn emit_with_code(&self, msp
: &MultiSpan
, msg
: &str, code
: &str, lvl
: Level
) {
467 if lvl
== Warning
&& !self.can_emit_warnings
{
470 let mut db
= DiagnosticBuilder
::new_with_code(self, lvl
, Some(code
.to_owned()), msg
);
471 db
.set_span(msp
.clone());
473 if !self.continue_after_error
.get() {
474 self.abort_if_errors();
480 #[derive(Copy, PartialEq, Clone, Debug)]
484 // An error which while not immediately fatal, should stop the compiler
485 // progressing beyond the current phase.
494 impl fmt
::Display
for Level
{
495 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
501 pub fn color(self) -> term
::color
::Color
{
503 Bug
| Fatal
| PhaseFatal
| Error
=> term
::color
::BRIGHT_RED
,
506 term
::color
::BRIGHT_YELLOW
511 Note
=> term
::color
::BRIGHT_GREEN
,
512 Help
=> term
::color
::BRIGHT_CYAN
,
513 Cancelled
=> unreachable
!(),
517 pub fn to_str(self) -> &'
static str {
519 Bug
=> "error: internal compiler error",
520 Fatal
| PhaseFatal
| Error
=> "error",
521 Warning
=> "warning",
524 Cancelled
=> panic
!("Shouldn't call on cancelled error"),
529 pub fn expect
<T
, M
>(diag
: &Handler
, opt
: Option
<T
>, msg
: M
) -> T
530 where M
: FnOnce() -> String
534 None
=> diag
.bug(&msg()),