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