]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/lib.rs
Rollup merge of #41918 - brson:lic, r=alexcrichton
[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 #![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/")]
18 #![deny(warnings)]
19
20 #![feature(custom_attribute)]
21 #![allow(unused_attributes)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
24 #![feature(range_contains)]
25 #![feature(libc)]
26 #![feature(conservative_impl_trait)]
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     /// Each substitute can have multiple variants due to multiple
70     /// applicable suggestions
71     ///
72     /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
73     /// `foo` and `bar` on their own:
74     ///
75     /// ```
76     /// vec![
77     ///     (0..3, vec!["a", "x"]),
78     ///     (4..7, vec!["b", "y"]),
79     /// ]
80     /// ```
81     ///
82     /// or by replacing the entire span:
83     ///
84     /// ```
85     /// vec![(0..7, vec!["a.b", "x.y"])]
86     /// ```
87     pub substitution_parts: Vec<Substitution>,
88     pub msg: String,
89 }
90
91 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
92 /// See the docs on `CodeSuggestion::substitutions`
93 pub struct Substitution {
94     pub span: Span,
95     pub substitutions: Vec<String>,
96 }
97
98 pub trait CodeMapper {
99     fn lookup_char_pos(&self, pos: BytePos) -> Loc;
100     fn span_to_lines(&self, sp: Span) -> FileLinesResult;
101     fn span_to_string(&self, sp: Span) -> String;
102     fn span_to_filename(&self, sp: Span) -> FileName;
103     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
104 }
105
106 impl CodeSuggestion {
107     /// Returns the number of substitutions
108     fn substitutions(&self) -> usize {
109         self.substitution_parts[0].substitutions.len()
110     }
111
112     /// Returns the number of substitutions
113     pub fn substitution_spans<'a>(&'a self) -> impl Iterator<Item = Span> + 'a {
114         self.substitution_parts.iter().map(|sub| sub.span)
115     }
116
117     /// Returns the assembled code suggestions.
118     pub fn splice_lines(&self, cm: &CodeMapper) -> Vec<String> {
119         use syntax_pos::{CharPos, Loc, Pos};
120
121         fn push_trailing(buf: &mut String,
122                          line_opt: Option<&str>,
123                          lo: &Loc,
124                          hi_opt: Option<&Loc>) {
125             let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
126             if let Some(line) = line_opt {
127                 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
128                     let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
129                     buf.push_str(match hi_opt {
130                         Some(hi) => &line[lo..hi],
131                         None => &line[lo..],
132                     });
133                 }
134                 if let None = hi_opt {
135                     buf.push('\n');
136                 }
137             }
138         }
139
140         if self.substitution_parts.is_empty() {
141             return vec![String::new()];
142         }
143
144         let mut primary_spans: Vec<_> = self.substitution_parts
145             .iter()
146             .map(|sub| (sub.span, &sub.substitutions))
147             .collect();
148
149         // Assumption: all spans are in the same file, and all spans
150         // are disjoint. Sort in ascending order.
151         primary_spans.sort_by_key(|sp| sp.0.lo);
152
153         // Find the bounding span.
154         let lo = primary_spans.iter().map(|sp| sp.0.lo).min().unwrap();
155         let hi = primary_spans.iter().map(|sp| sp.0.hi).min().unwrap();
156         let bounding_span = Span {
157             lo: lo,
158             hi: hi,
159             ctxt: NO_EXPANSION,
160         };
161         let lines = cm.span_to_lines(bounding_span).unwrap();
162         assert!(!lines.lines.is_empty());
163
164         // To build up the result, we do this for each span:
165         // - push the line segment trailing the previous span
166         //   (at the beginning a "phantom" span pointing at the start of the line)
167         // - push lines between the previous and current span (if any)
168         // - if the previous and current span are not on the same line
169         //   push the line segment leading up to the current span
170         // - splice in the span substitution
171         //
172         // Finally push the trailing line segment of the last span
173         let fm = &lines.file;
174         let mut prev_hi = cm.lookup_char_pos(bounding_span.lo);
175         prev_hi.col = CharPos::from_usize(0);
176
177         let mut prev_line = fm.get_line(lines.lines[0].line_index);
178         let mut bufs = vec![String::new(); self.substitutions()];
179
180         for (sp, substitutes) in primary_spans {
181             let cur_lo = cm.lookup_char_pos(sp.lo);
182             for (buf, substitute) in bufs.iter_mut().zip(substitutes) {
183                 if prev_hi.line == cur_lo.line {
184                     push_trailing(buf, prev_line, &prev_hi, Some(&cur_lo));
185                 } else {
186                     push_trailing(buf, prev_line, &prev_hi, None);
187                     // push lines between the previous and current span (if any)
188                     for idx in prev_hi.line..(cur_lo.line - 1) {
189                         if let Some(line) = fm.get_line(idx) {
190                             buf.push_str(line);
191                             buf.push('\n');
192                         }
193                     }
194                     if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
195                         buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
196                     }
197                 }
198                 buf.push_str(substitute);
199             }
200             prev_hi = cm.lookup_char_pos(sp.hi);
201             prev_line = fm.get_line(prev_hi.line - 1);
202         }
203         for buf in &mut bufs {
204             // if the replacement already ends with a newline, don't print the next line
205             if !buf.ends_with('\n') {
206                 push_trailing(buf, prev_line, &prev_hi, None);
207             }
208             // remove trailing newline
209             buf.pop();
210         }
211         bufs
212     }
213 }
214
215 /// Used as a return value to signify a fatal error occurred. (It is also
216 /// used as the argument to panic at the moment, but that will eventually
217 /// not be true.)
218 #[derive(Copy, Clone, Debug)]
219 #[must_use]
220 pub struct FatalError;
221
222 impl fmt::Display for FatalError {
223     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
224         write!(f, "parser fatal error")
225     }
226 }
227
228 impl error::Error for FatalError {
229     fn description(&self) -> &str {
230         "The parser has encountered a fatal error"
231     }
232 }
233
234 /// Signifies that the compiler died with an explicit call to `.bug`
235 /// or `.span_bug` rather than a failed assertion, etc.
236 #[derive(Copy, Clone, Debug)]
237 pub struct ExplicitBug;
238
239 impl fmt::Display for ExplicitBug {
240     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
241         write!(f, "parser internal bug")
242     }
243 }
244
245 impl error::Error for ExplicitBug {
246     fn description(&self) -> &str {
247         "The parser has encountered an internal bug"
248     }
249 }
250
251 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, StringPart};
252 pub use diagnostic_builder::DiagnosticBuilder;
253
254 /// A handler deals with errors; certain errors
255 /// (fatal, bug, unimpl) may cause immediate exit,
256 /// others log errors for later reporting.
257 pub struct Handler {
258     err_count: Cell<usize>,
259     emitter: RefCell<Box<Emitter>>,
260     pub can_emit_warnings: bool,
261     treat_err_as_bug: bool,
262     continue_after_error: Cell<bool>,
263     delayed_span_bug: RefCell<Option<(MultiSpan, String)>>,
264 }
265
266 impl Handler {
267     pub fn with_tty_emitter(color_config: ColorConfig,
268                             can_emit_warnings: bool,
269                             treat_err_as_bug: bool,
270                             cm: Option<Rc<CodeMapper>>)
271                             -> Handler {
272         let emitter = Box::new(EmitterWriter::stderr(color_config, cm));
273         Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter)
274     }
275
276     pub fn with_emitter(can_emit_warnings: bool,
277                         treat_err_as_bug: bool,
278                         e: Box<Emitter>)
279                         -> Handler {
280         Handler {
281             err_count: Cell::new(0),
282             emitter: RefCell::new(e),
283             can_emit_warnings: can_emit_warnings,
284             treat_err_as_bug: treat_err_as_bug,
285             continue_after_error: Cell::new(true),
286             delayed_span_bug: RefCell::new(None),
287         }
288     }
289
290     pub fn set_continue_after_error(&self, continue_after_error: bool) {
291         self.continue_after_error.set(continue_after_error);
292     }
293
294     pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
295         DiagnosticBuilder::new(self, Level::Cancelled, "")
296     }
297
298     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
299                                                     sp: S,
300                                                     msg: &str)
301                                                     -> DiagnosticBuilder<'a> {
302         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
303         result.set_span(sp);
304         if !self.can_emit_warnings {
305             result.cancel();
306         }
307         result
308     }
309     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
310                                                               sp: S,
311                                                               msg: &str,
312                                                               code: &str)
313                                                               -> DiagnosticBuilder<'a> {
314         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
315         result.set_span(sp);
316         result.code(code.to_owned());
317         if !self.can_emit_warnings {
318             result.cancel();
319         }
320         result
321     }
322     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
323         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
324         if !self.can_emit_warnings {
325             result.cancel();
326         }
327         result
328     }
329     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
330                                                    sp: S,
331                                                    msg: &str)
332                                                    -> DiagnosticBuilder<'a> {
333         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
334         result.set_span(sp);
335         result
336     }
337     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
338                                                              sp: S,
339                                                              msg: &str,
340                                                              code: &str)
341                                                              -> DiagnosticBuilder<'a> {
342         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
343         result.set_span(sp);
344         result.code(code.to_owned());
345         result
346     }
347     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
348         DiagnosticBuilder::new(self, Level::Error, msg)
349     }
350     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
351                                                      sp: S,
352                                                      msg: &str)
353                                                      -> DiagnosticBuilder<'a> {
354         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
355         result.set_span(sp);
356         result
357     }
358     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
359                                                                sp: S,
360                                                                msg: &str,
361                                                                code: &str)
362                                                                -> DiagnosticBuilder<'a> {
363         let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
364         result.set_span(sp);
365         result.code(code.to_owned());
366         result
367     }
368     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
369         DiagnosticBuilder::new(self, Level::Fatal, msg)
370     }
371
372     pub fn cancel(&self, err: &mut DiagnosticBuilder) {
373         err.cancel();
374     }
375
376     fn panic_if_treat_err_as_bug(&self) {
377         if self.treat_err_as_bug {
378             panic!("encountered error with `-Z treat_err_as_bug");
379         }
380     }
381
382     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
383         self.emit(&sp.into(), msg, Fatal);
384         self.panic_if_treat_err_as_bug();
385         return FatalError;
386     }
387     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
388                                                     sp: S,
389                                                     msg: &str,
390                                                     code: &str)
391                                                     -> FatalError {
392         self.emit_with_code(&sp.into(), msg, code, Fatal);
393         self.panic_if_treat_err_as_bug();
394         return FatalError;
395     }
396     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
397         self.emit(&sp.into(), msg, Error);
398         self.panic_if_treat_err_as_bug();
399     }
400     pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
401                                                 sp: S,
402                                                 msg: &str)
403                                                 -> DiagnosticBuilder<'a> {
404         let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
405         result.set_span(sp);
406         result
407     }
408     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
409         self.emit_with_code(&sp.into(), msg, code, Error);
410         self.panic_if_treat_err_as_bug();
411     }
412     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
413         self.emit(&sp.into(), msg, Warning);
414     }
415     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
416         self.emit_with_code(&sp.into(), msg, code, Warning);
417     }
418     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
419         self.emit(&sp.into(), msg, Bug);
420         panic!(ExplicitBug);
421     }
422     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
423         if self.treat_err_as_bug {
424             self.span_bug(sp, msg);
425         }
426         let mut delayed = self.delayed_span_bug.borrow_mut();
427         *delayed = Some((sp.into(), msg.to_string()));
428     }
429     pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
430         self.emit(&sp.into(), msg, Bug);
431     }
432     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
433         self.emit(&sp.into(), msg, Note);
434     }
435     pub fn span_note_diag<'a>(&'a self,
436                               sp: Span,
437                               msg: &str)
438                               -> DiagnosticBuilder<'a> {
439         let mut db = DiagnosticBuilder::new(self, Note, msg);
440         db.set_span(sp);
441         db
442     }
443     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
444         self.span_bug(sp, &format!("unimplemented {}", msg));
445     }
446     pub fn fatal(&self, msg: &str) -> FatalError {
447         if self.treat_err_as_bug {
448             self.bug(msg);
449         }
450         let mut db = DiagnosticBuilder::new(self, Fatal, msg);
451         db.emit();
452         FatalError
453     }
454     pub fn err(&self, msg: &str) {
455         if self.treat_err_as_bug {
456             self.bug(msg);
457         }
458         let mut db = DiagnosticBuilder::new(self, Error, msg);
459         db.emit();
460     }
461     pub fn warn(&self, msg: &str) {
462         let mut db = DiagnosticBuilder::new(self, Warning, msg);
463         db.emit();
464     }
465     pub fn note_without_error(&self, msg: &str) {
466         let mut db = DiagnosticBuilder::new(self, Note, msg);
467         db.emit();
468     }
469     pub fn bug(&self, msg: &str) -> ! {
470         let mut db = DiagnosticBuilder::new(self, Bug, msg);
471         db.emit();
472         panic!(ExplicitBug);
473     }
474     pub fn unimpl(&self, msg: &str) -> ! {
475         self.bug(&format!("unimplemented {}", msg));
476     }
477
478     pub fn bump_err_count(&self) {
479         self.err_count.set(self.err_count.get() + 1);
480     }
481
482     pub fn err_count(&self) -> usize {
483         self.err_count.get()
484     }
485
486     pub fn has_errors(&self) -> bool {
487         self.err_count.get() > 0
488     }
489     pub fn abort_if_errors(&self) {
490         let s;
491         match self.err_count.get() {
492             0 => {
493                 let delayed_bug = self.delayed_span_bug.borrow();
494                 match *delayed_bug {
495                     Some((ref span, ref errmsg)) => {
496                         self.span_bug(span.clone(), errmsg);
497                     }
498                     _ => {}
499                 }
500
501                 return;
502             }
503             1 => s = "aborting due to previous error".to_string(),
504             _ => {
505                 s = format!("aborting due to {} previous errors", self.err_count.get());
506             }
507         }
508
509         panic!(self.fatal(&s));
510     }
511     pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
512         if lvl == Warning && !self.can_emit_warnings {
513             return;
514         }
515         let mut db = DiagnosticBuilder::new(self, lvl, msg);
516         db.set_span(msp.clone());
517         db.emit();
518         if !self.continue_after_error.get() {
519             self.abort_if_errors();
520         }
521     }
522     pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) {
523         if lvl == Warning && !self.can_emit_warnings {
524             return;
525         }
526         let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg);
527         db.set_span(msp.clone());
528         db.emit();
529         if !self.continue_after_error.get() {
530             self.abort_if_errors();
531         }
532     }
533 }
534
535
536 #[derive(Copy, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
537 pub enum Level {
538     Bug,
539     Fatal,
540     // An error which while not immediately fatal, should stop the compiler
541     // progressing beyond the current phase.
542     PhaseFatal,
543     Error,
544     Warning,
545     Note,
546     Help,
547     Cancelled,
548 }
549
550 impl fmt::Display for Level {
551     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
552         self.to_str().fmt(f)
553     }
554 }
555
556 impl Level {
557     pub fn color(self) -> term::color::Color {
558         match self {
559             Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED,
560             Warning => {
561                 if cfg!(windows) {
562                     term::color::BRIGHT_YELLOW
563                 } else {
564                     term::color::YELLOW
565                 }
566             }
567             Note => term::color::BRIGHT_GREEN,
568             Help => term::color::BRIGHT_CYAN,
569             Cancelled => unreachable!(),
570         }
571     }
572
573     pub fn to_str(self) -> &'static str {
574         match self {
575             Bug => "error: internal compiler error",
576             Fatal | PhaseFatal | Error => "error",
577             Warning => "warning",
578             Note => "note",
579             Help => "help",
580             Cancelled => panic!("Shouldn't call on cancelled error"),
581         }
582     }
583 }
584
585 pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T
586     where M: FnOnce() -> String
587 {
588     match opt {
589         Some(t) => t,
590         None => diag.bug(&msg()),
591     }
592 }