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