]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
rustdoc: Hide `self: Box<Self>` in list of deref methods
[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 #![feature(conservative_impl_trait)]
24
25 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
26 #![cfg_attr(stage0, feature(rustc_private))]
27 #![cfg_attr(stage0, feature(staged_api))]
28
29 extern crate term;
30 extern crate libc;
31 extern crate serialize as rustc_serialize;
32 extern crate syntax_pos;
33
34 pub use emitter::ColorConfig;
35
36 use self::Level::*;
37
38 use emitter::{Emitter, EmitterWriter};
39
40 use std::cell::{RefCell, Cell};
41 use std::{error, fmt};
42 use std::rc::Rc;
43
44 pub mod diagnostic;
45 pub mod diagnostic_builder;
46 pub mod emitter;
47 pub mod snippet;
48 pub mod registry;
49 pub mod styled_buffer;
50 mod lock;
51
52 use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION};
53
54 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
55 pub enum RenderSpan {
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.
59     FullSpan(MultiSpan),
60
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),
66 }
67
68 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
69 pub struct CodeSuggestion {
70     /// Each substitute can have multiple variants due to multiple
71     /// applicable suggestions
72     ///
73     /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
74     /// `foo` and `bar` on their own:
75     ///
76     /// ```
77     /// vec![
78     ///     (0..3, vec!["a", "x"]),
79     ///     (4..7, vec!["b", "y"]),
80     /// ]
81     /// ```
82     ///
83     /// or by replacing the entire span:
84     ///
85     /// ```
86     /// vec![(0..7, vec!["a.b", "x.y"])]
87     /// ```
88     pub substitution_parts: Vec<Substitution>,
89     pub msg: String,
90 }
91
92 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
93 /// See the docs on `CodeSuggestion::substitutions`
94 pub struct Substitution {
95     pub span: Span,
96     pub substitutions: Vec<String>,
97 }
98
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>;
105 }
106
107 impl CodeSuggestion {
108     /// Returns the number of substitutions
109     fn substitutions(&self) -> usize {
110         self.substitution_parts[0].substitutions.len()
111     }
112
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)
116     }
117
118     /// Returns the assembled code suggestions.
119     pub fn splice_lines(&self, cm: &CodeMapper) -> Vec<String> {
120         use syntax_pos::{CharPos, Loc, Pos};
121
122         fn push_trailing(buf: &mut String,
123                          line_opt: Option<&str>,
124                          lo: &Loc,
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],
132                         None => &line[lo..],
133                     });
134                 }
135                 if let None = hi_opt {
136                     buf.push('\n');
137                 }
138             }
139         }
140
141         if self.substitution_parts.is_empty() {
142             return vec![String::new()];
143         }
144
145         let mut primary_spans: Vec<_> = self.substitution_parts
146             .iter()
147             .map(|sub| (sub.span, &sub.substitutions))
148             .collect();
149
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);
153
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 {
158             lo: lo,
159             hi: hi,
160             ctxt: NO_EXPANSION,
161         };
162         let lines = cm.span_to_lines(bounding_span).unwrap();
163         assert!(!lines.lines.is_empty());
164
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
172         //
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);
177
178         let mut prev_line = fm.get_line(lines.lines[0].line_index);
179         let mut bufs = vec![String::new(); self.substitutions()];
180
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));
186                 } else {
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) {
191                             buf.push_str(line);
192                             buf.push('\n');
193                         }
194                     }
195                     if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
196                         buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
197                     }
198                 }
199                 buf.push_str(substitute);
200             }
201             prev_hi = cm.lookup_char_pos(sp.hi);
202             prev_line = fm.get_line(prev_hi.line - 1);
203         }
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);
208             }
209             // remove trailing newline
210             buf.pop();
211         }
212         bufs
213     }
214 }
215
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
218 /// not be true.)
219 #[derive(Copy, Clone, Debug)]
220 #[must_use]
221 pub struct FatalError;
222
223 impl fmt::Display for FatalError {
224     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
225         write!(f, "parser fatal error")
226     }
227 }
228
229 impl error::Error for FatalError {
230     fn description(&self) -> &str {
231         "The parser has encountered a fatal error"
232     }
233 }
234
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;
239
240 impl fmt::Display for ExplicitBug {
241     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
242         write!(f, "parser internal bug")
243     }
244 }
245
246 impl error::Error for ExplicitBug {
247     fn description(&self) -> &str {
248         "The parser has encountered an internal bug"
249     }
250 }
251
252 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, StringPart};
253 pub use diagnostic_builder::DiagnosticBuilder;
254
255 /// A handler deals with errors; certain errors
256 /// (fatal, bug, unimpl) may cause immediate exit,
257 /// others log errors for later reporting.
258 pub struct Handler {
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)>>,
265 }
266
267 impl Handler {
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>>)
272                             -> Handler {
273         let emitter = Box::new(EmitterWriter::stderr(color_config, cm));
274         Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter)
275     }
276
277     pub fn with_emitter(can_emit_warnings: bool,
278                         treat_err_as_bug: bool,
279                         e: Box<Emitter>)
280                         -> Handler {
281         Handler {
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),
288         }
289     }
290
291     pub fn set_continue_after_error(&self, continue_after_error: bool) {
292         self.continue_after_error.set(continue_after_error);
293     }
294
295     pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
296         DiagnosticBuilder::new(self, Level::Cancelled, "")
297     }
298
299     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
300                                                     sp: S,
301                                                     msg: &str)
302                                                     -> DiagnosticBuilder<'a> {
303         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
304         result.set_span(sp);
305         if !self.can_emit_warnings {
306             result.cancel();
307         }
308         result
309     }
310     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
311                                                               sp: S,
312                                                               msg: &str,
313                                                               code: &str)
314                                                               -> DiagnosticBuilder<'a> {
315         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
316         result.set_span(sp);
317         result.code(code.to_owned());
318         if !self.can_emit_warnings {
319             result.cancel();
320         }
321         result
322     }
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 {
326             result.cancel();
327         }
328         result
329     }
330     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
331                                                    sp: S,
332                                                    msg: &str)
333                                                    -> DiagnosticBuilder<'a> {
334         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
335         result.set_span(sp);
336         result
337     }
338     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
339                                                              sp: S,
340                                                              msg: &str,
341                                                              code: &str)
342                                                              -> DiagnosticBuilder<'a> {
343         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
344         result.set_span(sp);
345         result.code(code.to_owned());
346         result
347     }
348     // FIXME: This method should be removed (every error should have an associated error code).
349     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
350         DiagnosticBuilder::new(self, Level::Error, msg)
351     }
352     pub fn struct_err_with_code<'a>(&'a self, msg: &str, code: &str) -> DiagnosticBuilder<'a> {
353         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
354         result.code(code.to_owned());
355         result
356     }
357     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
358                                                      sp: S,
359                                                      msg: &str)
360                                                      -> DiagnosticBuilder<'a> {
361         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
362         result.set_span(sp);
363         result
364     }
365     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
366                                                                sp: S,
367                                                                msg: &str,
368                                                                code: &str)
369                                                                -> DiagnosticBuilder<'a> {
370         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
371         result.set_span(sp);
372         result.code(code.to_owned());
373         result
374     }
375     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
376         DiagnosticBuilder::new(self, Level::Fatal, msg)
377     }
378
379     pub fn cancel(&self, err: &mut DiagnosticBuilder) {
380         err.cancel();
381     }
382
383     fn panic_if_treat_err_as_bug(&self) {
384         if self.treat_err_as_bug {
385             panic!("encountered error with `-Z treat_err_as_bug");
386         }
387     }
388
389     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
390         self.emit(&sp.into(), msg, Fatal);
391         self.panic_if_treat_err_as_bug();
392         FatalError
393     }
394     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
395                                                     sp: S,
396                                                     msg: &str,
397                                                     code: &str)
398                                                     -> FatalError {
399         self.emit_with_code(&sp.into(), msg, code, Fatal);
400         self.panic_if_treat_err_as_bug();
401         FatalError
402     }
403     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
404         self.emit(&sp.into(), msg, Error);
405         self.panic_if_treat_err_as_bug();
406     }
407     pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
408                                                 sp: S,
409                                                 msg: &str)
410                                                 -> DiagnosticBuilder<'a> {
411         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
412         result.set_span(sp);
413         result
414     }
415     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
416         self.emit_with_code(&sp.into(), msg, code, Error);
417         self.panic_if_treat_err_as_bug();
418     }
419     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
420         self.emit(&sp.into(), msg, Warning);
421     }
422     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
423         self.emit_with_code(&sp.into(), msg, code, Warning);
424     }
425     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
426         self.emit(&sp.into(), msg, Bug);
427         panic!(ExplicitBug);
428     }
429     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
430         if self.treat_err_as_bug {
431             self.span_bug(sp, msg);
432         }
433         let mut delayed = self.delayed_span_bug.borrow_mut();
434         *delayed = Some((sp.into(), msg.to_string()));
435     }
436     pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
437         self.emit(&sp.into(), msg, Bug);
438     }
439     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
440         self.emit(&sp.into(), msg, Note);
441     }
442     pub fn span_note_diag<'a>(&'a self,
443                               sp: Span,
444                               msg: &str)
445                               -> DiagnosticBuilder<'a> {
446         let mut db = DiagnosticBuilder::new(self, Note, msg);
447         db.set_span(sp);
448         db
449     }
450     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
451         self.span_bug(sp, &format!("unimplemented {}", msg));
452     }
453     pub fn fatal(&self, msg: &str) -> FatalError {
454         if self.treat_err_as_bug {
455             self.bug(msg);
456         }
457         let mut db = DiagnosticBuilder::new(self, Fatal, msg);
458         db.emit();
459         FatalError
460     }
461     pub fn err(&self, msg: &str) {
462         if self.treat_err_as_bug {
463             self.bug(msg);
464         }
465         let mut db = DiagnosticBuilder::new(self, Error, msg);
466         db.emit();
467     }
468     pub fn warn(&self, msg: &str) {
469         let mut db = DiagnosticBuilder::new(self, Warning, msg);
470         db.emit();
471     }
472     pub fn note_without_error(&self, msg: &str) {
473         let mut db = DiagnosticBuilder::new(self, Note, msg);
474         db.emit();
475     }
476     pub fn bug(&self, msg: &str) -> ! {
477         let mut db = DiagnosticBuilder::new(self, Bug, msg);
478         db.emit();
479         panic!(ExplicitBug);
480     }
481     pub fn unimpl(&self, msg: &str) -> ! {
482         self.bug(&format!("unimplemented {}", msg));
483     }
484
485     pub fn bump_err_count(&self) {
486         self.err_count.set(self.err_count.get() + 1);
487     }
488
489     pub fn err_count(&self) -> usize {
490         self.err_count.get()
491     }
492
493     pub fn has_errors(&self) -> bool {
494         self.err_count.get() > 0
495     }
496     pub fn abort_if_errors(&self) {
497         let s;
498         match self.err_count.get() {
499             0 => {
500                 let delayed_bug = self.delayed_span_bug.borrow();
501                 match *delayed_bug {
502                     Some((ref span, ref errmsg)) => {
503                         self.span_bug(span.clone(), errmsg);
504                     }
505                     _ => {}
506                 }
507
508                 return;
509             }
510             _ => s = "aborting due to previous error(s)".to_string(),
511         }
512
513         panic!(self.fatal(&s));
514     }
515     pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
516         if lvl == Warning && !self.can_emit_warnings {
517             return;
518         }
519         let mut db = DiagnosticBuilder::new(self, lvl, msg);
520         db.set_span(msp.clone());
521         db.emit();
522         if !self.continue_after_error.get() {
523             self.abort_if_errors();
524         }
525     }
526     pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
527         if lvl == Warning && !self.can_emit_warnings {
528             return;
529         }
530         let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
531         db.set_span(msp.clone());
532         db.emit();
533         if !self.continue_after_error.get() {
534             self.abort_if_errors();
535         }
536     }
537 }
538
539
540 #[derive(Copy, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
541 pub enum Level {
542     Bug,
543     Fatal,
544     // An error which while not immediately fatal, should stop the compiler
545     // progressing beyond the current phase.
546     PhaseFatal,
547     Error,
548     Warning,
549     Note,
550     Help,
551     Cancelled,
552 }
553
554 impl fmt::Display for Level {
555     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
556         self.to_str().fmt(f)
557     }
558 }
559
560 impl Level {
561     pub fn color(self) -> term::color::Color {
562         match self {
563             Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
564             Warning => {
565                 if cfg!(windows) {
566                     term::color::BRIGHT_YELLOW
567                 } else {
568                     term::color::YELLOW
569                 }
570             }
571             Note => term::color::BRIGHT_GREEN,
572             Help => term::color::BRIGHT_CYAN,
573             Cancelled => unreachable!(),
574         }
575     }
576
577     pub fn to_str(self) -> &'static str {
578         match self {
579             Bug => "error: internal compiler error",
580             Fatal | PhaseFatal | Error => "error",
581             Warning => "warning",
582             Note => "note",
583             Help => "help",
584             Cancelled => panic!("Shouldn't call on cancelled error"),
585         }
586     }
587 }
588
589 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
590     where M: FnOnce() -> String
591 {
592     match opt {
593         Some(t) => t,
594         None => diag.bug(&msg()),
595     }
596 }