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