]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
rustc: Remove #![unstable] annotation
[rust.git] / src / librustc_errors / lib.rs
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.
4 //
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.
10
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/")]
17 #![deny(warnings)]
18
19 #![feature(custom_attribute)]
20 #![allow(unused_attributes)]
21 #![feature(range_contains)]
22 #![feature(libc)]
23
24 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
25 #![cfg_attr(stage0, feature(rustc_private))]
26 #![cfg_attr(stage0, feature(staged_api))]
27
28 extern crate term;
29 extern crate libc;
30 extern crate serialize as rustc_serialize;
31 extern crate syntax_pos;
32
33 pub use emitter::ColorConfig;
34
35 use self::Level::*;
36
37 use emitter::{Emitter, EmitterWriter};
38
39 use std::cell::{RefCell, Cell};
40 use std::{error, fmt};
41 use std::rc::Rc;
42
43 pub mod diagnostic;
44 pub mod diagnostic_builder;
45 pub mod emitter;
46 pub mod snippet;
47 pub mod registry;
48 pub mod styled_buffer;
49 mod lock;
50
51 use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION};
52
53 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
54 pub enum RenderSpan {
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.
58     FullSpan(MultiSpan),
59
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),
65 }
66
67 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
68 pub struct CodeSuggestion {
69     pub msp: MultiSpan,
70     pub substitutes: Vec<String>,
71     pub msg: String,
72 }
73
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>;
80 }
81
82 impl CodeSuggestion {
83     /// Returns the assembled code suggestion.
84     pub fn splice_lines(&self, cm: &CodeMapper) -> String {
85         use syntax_pos::{CharPos, Loc, Pos};
86
87         fn push_trailing(buf: &mut String,
88                          line_opt: Option<&str>,
89                          lo: &Loc,
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],
97                         None => &line[lo..],
98                     });
99                 }
100                 if let None = hi_opt {
101                     buf.push('\n');
102                 }
103             }
104         }
105
106         let mut primary_spans = self.msp.primary_spans().to_owned();
107
108         assert_eq!(primary_spans.len(), self.substitutes.len());
109         if primary_spans.is_empty() {
110             return format!("");
111         }
112
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);
116
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 {
121             lo: lo,
122             hi: hi,
123             ctxt: NO_EXPANSION,
124         };
125         let lines = cm.span_to_lines(bounding_span).unwrap();
126         assert!(!lines.lines.is_empty());
127
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
135         //
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);
140
141         let mut prev_line = fm.get_line(lines.lines[0].line_index);
142         let mut buf = String::new();
143
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));
148             } else {
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) {
153                         buf.push_str(line);
154                         buf.push('\n');
155                     }
156                 }
157                 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
158                     buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
159                 }
160             }
161             buf.push_str(substitute);
162             prev_hi = cm.lookup_char_pos(sp.hi);
163             prev_line = fm.get_line(prev_hi.line - 1);
164         }
165         push_trailing(&mut buf, prev_line, &prev_hi, None);
166         // remove trailing newline
167         buf.pop();
168         buf
169     }
170 }
171
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
174 /// not be true.)
175 #[derive(Copy, Clone, Debug)]
176 #[must_use]
177 pub struct FatalError;
178
179 impl fmt::Display for FatalError {
180     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
181         write!(f, "parser fatal error")
182     }
183 }
184
185 impl error::Error for FatalError {
186     fn description(&self) -> &str {
187         "The parser has encountered a fatal error"
188     }
189 }
190
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;
195
196 impl fmt::Display for ExplicitBug {
197     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
198         write!(f, "parser internal bug")
199     }
200 }
201
202 impl error::Error for ExplicitBug {
203     fn description(&self) -> &str {
204         "The parser has encountered an internal bug"
205     }
206 }
207
208 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, StringPart};
209 pub use diagnostic_builder::DiagnosticBuilder;
210
211 /// A handler deals with errors; certain errors
212 /// (fatal, bug, unimpl) may cause immediate exit,
213 /// others log errors for later reporting.
214 pub struct Handler {
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)>>,
221 }
222
223 impl Handler {
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>>)
228                             -> Handler {
229         let emitter = Box::new(EmitterWriter::stderr(color_config, cm));
230         Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter)
231     }
232
233     pub fn with_emitter(can_emit_warnings: bool,
234                         treat_err_as_bug: bool,
235                         e: Box<Emitter>)
236                         -> Handler {
237         Handler {
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),
244         }
245     }
246
247     pub fn set_continue_after_error(&self, continue_after_error: bool) {
248         self.continue_after_error.set(continue_after_error);
249     }
250
251     pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
252         DiagnosticBuilder::new(self, Level::Cancelled, "")
253     }
254
255     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
256                                                     sp: S,
257                                                     msg: &str)
258                                                     -> DiagnosticBuilder<'a> {
259         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
260         result.set_span(sp);
261         if !self.can_emit_warnings {
262             result.cancel();
263         }
264         result
265     }
266     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
267                                                               sp: S,
268                                                               msg: &str,
269                                                               code: &str)
270                                                               -> DiagnosticBuilder<'a> {
271         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
272         result.set_span(sp);
273         result.code(code.to_owned());
274         if !self.can_emit_warnings {
275             result.cancel();
276         }
277         result
278     }
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 {
282             result.cancel();
283         }
284         result
285     }
286     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
287                                                    sp: S,
288                                                    msg: &str)
289                                                    -> DiagnosticBuilder<'a> {
290         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
291         result.set_span(sp);
292         result
293     }
294     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
295                                                              sp: S,
296                                                              msg: &str,
297                                                              code: &str)
298                                                              -> DiagnosticBuilder<'a> {
299         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
300         result.set_span(sp);
301         result.code(code.to_owned());
302         result
303     }
304     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
305         DiagnosticBuilder::new(self, Level::Error, msg)
306     }
307     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
308                                                      sp: S,
309                                                      msg: &str)
310                                                      -> DiagnosticBuilder<'a> {
311         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
312         result.set_span(sp);
313         result
314     }
315     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
316                                                                sp: S,
317                                                                msg: &str,
318                                                                code: &str)
319                                                                -> DiagnosticBuilder<'a> {
320         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
321         result.set_span(sp);
322         result.code(code.to_owned());
323         result
324     }
325     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
326         DiagnosticBuilder::new(self, Level::Fatal, msg)
327     }
328
329     pub fn cancel(&self, err: &mut DiagnosticBuilder) {
330         err.cancel();
331     }
332
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");
336         }
337     }
338
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();
342         return FatalError;
343     }
344     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
345                                                     sp: S,
346                                                     msg: &str,
347                                                     code: &str)
348                                                     -> FatalError {
349         self.emit_with_code(&sp.into(), msg, code, Fatal);
350         self.panic_if_treat_err_as_bug();
351         return FatalError;
352     }
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();
356     }
357     pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
358                                                 sp: S,
359                                                 msg: &str)
360                                                 -> DiagnosticBuilder<'a> {
361         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
362         result.set_span(sp);
363         result
364     }
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();
368     }
369     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
370         self.emit(&sp.into(), msg, Warning);
371     }
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);
374     }
375     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
376         self.emit(&sp.into(), msg, Bug);
377         panic!(ExplicitBug);
378     }
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);
382         }
383         let mut delayed = self.delayed_span_bug.borrow_mut();
384         *delayed = Some((sp.into(), msg.to_string()));
385     }
386     pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
387         self.emit(&sp.into(), msg, Bug);
388     }
389     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
390         self.emit(&sp.into(), msg, Note);
391     }
392     pub fn span_note_diag<'a>(&'a self,
393                               sp: Span,
394                               msg: &str)
395                               -> DiagnosticBuilder<'a> {
396         let mut db = DiagnosticBuilder::new(self, Note, msg);
397         db.set_span(sp);
398         db
399     }
400     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
401         self.span_bug(sp, &format!("unimplemented {}", msg));
402     }
403     pub fn fatal(&self, msg: &str) -> FatalError {
404         if self.treat_err_as_bug {
405             self.bug(msg);
406         }
407         let mut db = DiagnosticBuilder::new(self, Fatal, msg);
408         db.emit();
409         FatalError
410     }
411     pub fn err(&self, msg: &str) {
412         if self.treat_err_as_bug {
413             self.bug(msg);
414         }
415         let mut db = DiagnosticBuilder::new(self, Error, msg);
416         db.emit();
417     }
418     pub fn warn(&self, msg: &str) {
419         let mut db = DiagnosticBuilder::new(self, Warning, msg);
420         db.emit();
421     }
422     pub fn note_without_error(&self, msg: &str) {
423         let mut db = DiagnosticBuilder::new(self, Note, msg);
424         db.emit();
425     }
426     pub fn bug(&self, msg: &str) -> ! {
427         let mut db = DiagnosticBuilder::new(self, Bug, msg);
428         db.emit();
429         panic!(ExplicitBug);
430     }
431     pub fn unimpl(&self, msg: &str) -> ! {
432         self.bug(&format!("unimplemented {}", msg));
433     }
434
435     pub fn bump_err_count(&self) {
436         self.err_count.set(self.err_count.get() + 1);
437     }
438
439     pub fn err_count(&self) -> usize {
440         self.err_count.get()
441     }
442
443     pub fn has_errors(&self) -> bool {
444         self.err_count.get() > 0
445     }
446     pub fn abort_if_errors(&self) {
447         let s;
448         match self.err_count.get() {
449             0 => {
450                 let delayed_bug = self.delayed_span_bug.borrow();
451                 match *delayed_bug {
452                     Some((ref span, ref errmsg)) => {
453                         self.span_bug(span.clone(), errmsg);
454                     }
455                     _ => {}
456                 }
457
458                 return;
459             }
460             1 => s = "aborting due to previous error".to_string(),
461             _ => {
462                 s = format!("aborting due to {} previous errors", self.err_count.get());
463             }
464         }
465
466         panic!(self.fatal(&s));
467     }
468     pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
469         if lvl == Warning && !self.can_emit_warnings {
470             return;
471         }
472         let mut db = DiagnosticBuilder::new(self, lvl, msg);
473         db.set_span(msp.clone());
474         db.emit();
475         if !self.continue_after_error.get() {
476             self.abort_if_errors();
477         }
478     }
479     pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
480         if lvl == Warning && !self.can_emit_warnings {
481             return;
482         }
483         let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
484         db.set_span(msp.clone());
485         db.emit();
486         if !self.continue_after_error.get() {
487             self.abort_if_errors();
488         }
489     }
490 }
491
492
493 #[derive(Copy, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
494 pub enum Level {
495     Bug,
496     Fatal,
497     // An error which while not immediately fatal, should stop the compiler
498     // progressing beyond the current phase.
499     PhaseFatal,
500     Error,
501     Warning,
502     Note,
503     Help,
504     Cancelled,
505 }
506
507 impl fmt::Display for Level {
508     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
509         self.to_str().fmt(f)
510     }
511 }
512
513 impl Level {
514     pub fn color(self) -> term::color::Color {
515         match self {
516             Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
517             Warning => {
518                 if cfg!(windows) {
519                     term::color::BRIGHT_YELLOW
520                 } else {
521                     term::color::YELLOW
522                 }
523             }
524             Note => term::color::BRIGHT_GREEN,
525             Help => term::color::BRIGHT_CYAN,
526             Cancelled => unreachable!(),
527         }
528     }
529
530     pub fn to_str(self) -> &'static str {
531         match self {
532             Bug => "error: internal compiler error",
533             Fatal | PhaseFatal | Error => "error",
534             Warning => "warning",
535             Note => "note",
536             Help => "help",
537             Cancelled => panic!("Shouldn't call on cancelled error"),
538         }
539     }
540 }
541
542 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
543     where M: FnOnce() -> String
544 {
545     match opt {
546         Some(t) => t,
547         None => diag.bug(&msg()),
548     }
549 }