]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Rollup merge of #42071 - nrc:parse-mods, r=nikomatsakis
[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     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
349         DiagnosticBuilder::new(self, Level::Error, msg)
350     }
351     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
352                                                      sp: S,
353                                                      msg: &str)
354                                                      -> DiagnosticBuilder<'a> {
355         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
356         result.set_span(sp);
357         result
358     }
359     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
360                                                                sp: S,
361                                                                msg: &str,
362                                                                code: &str)
363                                                                -> DiagnosticBuilder<'a> {
364         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
365         result.set_span(sp);
366         result.code(code.to_owned());
367         result
368     }
369     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
370         DiagnosticBuilder::new(self, Level::Fatal, msg)
371     }
372
373     pub fn cancel(&self, err: &mut DiagnosticBuilder) {
374         err.cancel();
375     }
376
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");
380         }
381     }
382
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();
386         FatalError
387     }
388     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
389                                                     sp: S,
390                                                     msg: &str,
391                                                     code: &str)
392                                                     -> FatalError {
393         self.emit_with_code(&sp.into(), msg, code, Fatal);
394         self.panic_if_treat_err_as_bug();
395         FatalError
396     }
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();
400     }
401     pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
402                                                 sp: S,
403                                                 msg: &str)
404                                                 -> DiagnosticBuilder<'a> {
405         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
406         result.set_span(sp);
407         result
408     }
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();
412     }
413     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
414         self.emit(&sp.into(), msg, Warning);
415     }
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);
418     }
419     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
420         self.emit(&sp.into(), msg, Bug);
421         panic!(ExplicitBug);
422     }
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);
426         }
427         let mut delayed = self.delayed_span_bug.borrow_mut();
428         *delayed = Some((sp.into(), msg.to_string()));
429     }
430     pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
431         self.emit(&sp.into(), msg, Bug);
432     }
433     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
434         self.emit(&sp.into(), msg, Note);
435     }
436     pub fn span_note_diag<'a>(&'a self,
437                               sp: Span,
438                               msg: &str)
439                               -> DiagnosticBuilder<'a> {
440         let mut db = DiagnosticBuilder::new(self, Note, msg);
441         db.set_span(sp);
442         db
443     }
444     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
445         self.span_bug(sp, &format!("unimplemented {}", msg));
446     }
447     pub fn fatal(&self, msg: &str) -> FatalError {
448         if self.treat_err_as_bug {
449             self.bug(msg);
450         }
451         let mut db = DiagnosticBuilder::new(self, Fatal, msg);
452         db.emit();
453         FatalError
454     }
455     pub fn err(&self, msg: &str) {
456         if self.treat_err_as_bug {
457             self.bug(msg);
458         }
459         let mut db = DiagnosticBuilder::new(self, Error, msg);
460         db.emit();
461     }
462     pub fn warn(&self, msg: &str) {
463         let mut db = DiagnosticBuilder::new(self, Warning, msg);
464         db.emit();
465     }
466     pub fn note_without_error(&self, msg: &str) {
467         let mut db = DiagnosticBuilder::new(self, Note, msg);
468         db.emit();
469     }
470     pub fn bug(&self, msg: &str) -> ! {
471         let mut db = DiagnosticBuilder::new(self, Bug, msg);
472         db.emit();
473         panic!(ExplicitBug);
474     }
475     pub fn unimpl(&self, msg: &str) -> ! {
476         self.bug(&format!("unimplemented {}", msg));
477     }
478
479     pub fn bump_err_count(&self) {
480         self.err_count.set(self.err_count.get() + 1);
481     }
482
483     pub fn err_count(&self) -> usize {
484         self.err_count.get()
485     }
486
487     pub fn has_errors(&self) -> bool {
488         self.err_count.get() > 0
489     }
490     pub fn abort_if_errors(&self) {
491         let s;
492         match self.err_count.get() {
493             0 => {
494                 let delayed_bug = self.delayed_span_bug.borrow();
495                 match *delayed_bug {
496                     Some((ref span, ref errmsg)) => {
497                         self.span_bug(span.clone(), errmsg);
498                     }
499                     _ => {}
500                 }
501
502                 return;
503             }
504             1 => s = "aborting due to previous error".to_string(),
505             _ => {
506                 s = format!("aborting due to {} previous errors", self.err_count.get());
507             }
508         }
509
510         panic!(self.fatal(&s));
511     }
512     pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
513         if lvl == Warning && !self.can_emit_warnings {
514             return;
515         }
516         let mut db = DiagnosticBuilder::new(self, lvl, msg);
517         db.set_span(msp.clone());
518         db.emit();
519         if !self.continue_after_error.get() {
520             self.abort_if_errors();
521         }
522     }
523     pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
524         if lvl == Warning && !self.can_emit_warnings {
525             return;
526         }
527         let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
528         db.set_span(msp.clone());
529         db.emit();
530         if !self.continue_after_error.get() {
531             self.abort_if_errors();
532         }
533     }
534 }
535
536
537 #[derive(Copy, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
538 pub enum Level {
539     Bug,
540     Fatal,
541     // An error which while not immediately fatal, should stop the compiler
542     // progressing beyond the current phase.
543     PhaseFatal,
544     Error,
545     Warning,
546     Note,
547     Help,
548     Cancelled,
549 }
550
551 impl fmt::Display for Level {
552     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
553         self.to_str().fmt(f)
554     }
555 }
556
557 impl Level {
558     pub fn color(self) -> term::color::Color {
559         match self {
560             Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
561             Warning => {
562                 if cfg!(windows) {
563                     term::color::BRIGHT_YELLOW
564                 } else {
565                     term::color::YELLOW
566                 }
567             }
568             Note => term::color::BRIGHT_GREEN,
569             Help => term::color::BRIGHT_CYAN,
570             Cancelled => unreachable!(),
571         }
572     }
573
574     pub fn to_str(self) -> &'static str {
575         match self {
576             Bug => "error: internal compiler error",
577             Fatal | PhaseFatal | Error => "error",
578             Warning => "warning",
579             Note => "note",
580             Help => "help",
581             Cancelled => panic!("Shouldn't call on cancelled error"),
582         }
583     }
584 }
585
586 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
587     where M: FnOnce() -> String
588 {
589     match opt {
590         Some(t) => t,
591         None => diag.bug(&msg()),
592     }
593 }