]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
move error handling from libsyntax/diagnostics.rs to libsyntax/errors/*
[rust.git] / src / librustc / session / mod.rs
1 // Copyright 2012-2013 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 use lint;
12 use middle::cstore::CrateStore;
13 use middle::dependency_format;
14 use session::search_paths::PathKind;
15 use util::nodemap::{NodeMap, FnvHashMap};
16
17 use syntax::ast::{NodeId, NodeIdAssigner, Name};
18 use syntax::codemap::Span;
19 use syntax::errors;
20 use syntax::errors::emitter::{Emitter, BasicEmitter};
21 use syntax::diagnostics;
22 use syntax::feature_gate;
23 use syntax::parse;
24 use syntax::parse::ParseSess;
25 use syntax::{ast, codemap};
26 use syntax::feature_gate::AttributeType;
27
28 use rustc_back::target::Target;
29
30 use std::path::{Path, PathBuf};
31 use std::cell::{Cell, RefCell};
32 use std::collections::HashSet;
33 use std::env;
34 use std::rc::Rc;
35
36 pub mod config;
37 pub mod filesearch;
38 pub mod search_paths;
39
40 // Represents the data associated with a compilation
41 // session for a single crate.
42 pub struct Session {
43     pub target: config::Config,
44     pub host: Target,
45     pub opts: config::Options,
46     pub cstore: Rc<for<'a> CrateStore<'a>>,
47     pub parse_sess: ParseSess,
48     // For a library crate, this is always none
49     pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
50     pub entry_type: Cell<Option<config::EntryFnType>>,
51     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
52     pub default_sysroot: Option<PathBuf>,
53     // The name of the root source file of the crate, in the local file system.
54     // The path is always expected to be absolute. `None` means that there is no
55     // source file.
56     pub local_crate_source_file: Option<PathBuf>,
57     pub working_dir: PathBuf,
58     pub lint_store: RefCell<lint::LintStore>,
59     pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
60     pub plugin_llvm_passes: RefCell<Vec<String>>,
61     pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
62     pub crate_types: RefCell<Vec<config::CrateType>>,
63     pub dependency_formats: RefCell<dependency_format::Dependencies>,
64     pub crate_metadata: RefCell<Vec<String>>,
65     pub features: RefCell<feature_gate::Features>,
66
67     pub delayed_span_bug: RefCell<Option<(codemap::Span, String)>>,
68
69     /// The maximum recursion limit for potentially infinitely recursive
70     /// operations such as auto-dereference and monomorphization.
71     pub recursion_limit: Cell<usize>,
72
73     pub can_print_warnings: bool,
74
75     /// The metadata::creader module may inject an allocator dependency if it
76     /// didn't already find one, and this tracks what was injected.
77     pub injected_allocator: Cell<Option<ast::CrateNum>>,
78
79     /// Names of all bang-style macros and syntax extensions
80     /// available in this crate
81     pub available_macros: RefCell<HashSet<Name>>,
82
83     next_node_id: Cell<ast::NodeId>,
84 }
85
86 impl Session {
87     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
88         if self.opts.treat_err_as_bug {
89             self.span_bug(sp, msg);
90         }
91         panic!(self.diagnostic().span_fatal(sp, msg))
92     }
93     pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
94         if self.opts.treat_err_as_bug {
95             self.span_bug(sp, msg);
96         }
97         panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
98     }
99     pub fn fatal(&self, msg: &str) -> ! {
100         if self.opts.treat_err_as_bug {
101             self.bug(msg);
102         }
103         panic!(self.diagnostic().fatal(msg))
104     }
105     pub fn span_err_or_warn(&self, is_warning: bool, sp: Span, msg: &str) {
106         if is_warning {
107             self.span_warn(sp, msg);
108         } else {
109             self.span_err(sp, msg);
110         }
111     }
112     pub fn span_err(&self, sp: Span, msg: &str) {
113         if self.opts.treat_err_as_bug {
114             self.span_bug(sp, msg);
115         }
116         match split_msg_into_multilines(msg) {
117             Some(msg) => self.diagnostic().span_err(sp, &msg[..]),
118             None => self.diagnostic().span_err(sp, msg)
119         }
120     }
121     pub fn note_rfc_1214(&self, span: Span) {
122         self.span_note(
123             span,
124             &format!("this warning results from recent bug fixes and clarifications; \
125                       it will become a HARD ERROR in the next release. \
126                       See RFC 1214 for details."));
127     }
128     pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
129         if self.opts.treat_err_as_bug {
130             self.span_bug(sp, msg);
131         }
132         match split_msg_into_multilines(msg) {
133             Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[..], code),
134             None => self.diagnostic().span_err_with_code(sp, msg, code)
135         }
136     }
137     pub fn err(&self, msg: &str) {
138         if self.opts.treat_err_as_bug {
139             self.bug(msg);
140         }
141         self.diagnostic().err(msg)
142     }
143     pub fn err_count(&self) -> usize {
144         self.diagnostic().err_count()
145     }
146     pub fn has_errors(&self) -> bool {
147         self.diagnostic().has_errors()
148     }
149     pub fn abort_if_errors(&self) {
150         self.diagnostic().abort_if_errors();
151
152         let delayed_bug = self.delayed_span_bug.borrow();
153         match *delayed_bug {
154             Some((span, ref errmsg)) => {
155                 self.diagnostic().span_bug(span, errmsg);
156             },
157             _ => {}
158         }
159     }
160     pub fn abort_if_new_errors<F>(&self, mut f: F)
161         where F: FnMut()
162     {
163         let count = self.err_count();
164         f();
165         if self.err_count() > count {
166             self.abort_if_errors();
167         }
168     }
169     pub fn span_warn(&self, sp: Span, msg: &str) {
170         if self.can_print_warnings {
171             self.diagnostic().span_warn(sp, msg)
172         }
173     }
174     pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
175         if self.can_print_warnings {
176             self.diagnostic().span_warn_with_code(sp, msg, code)
177         }
178     }
179     pub fn warn(&self, msg: &str) {
180         if self.can_print_warnings {
181             self.diagnostic().warn(msg)
182         }
183     }
184     pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
185         match opt_sp {
186             Some(sp) => self.span_warn(sp, msg),
187             None => self.warn(msg),
188         }
189     }
190     pub fn span_note(&self, sp: Span, msg: &str) {
191         self.diagnostic().span_note(sp, msg)
192     }
193     pub fn span_end_note(&self, sp: Span, msg: &str) {
194         self.diagnostic().span_end_note(sp, msg)
195     }
196
197     /// Prints out a message with a suggested edit of the code.
198     ///
199     /// See `errors::RenderSpan::Suggestion` for more information.
200     pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
201         self.diagnostic().span_suggestion(sp, msg, suggestion)
202     }
203     pub fn span_help(&self, sp: Span, msg: &str) {
204         self.diagnostic().span_help(sp, msg)
205     }
206     pub fn fileline_note(&self, sp: Span, msg: &str) {
207         self.diagnostic().fileline_note(sp, msg)
208     }
209     pub fn fileline_help(&self, sp: Span, msg: &str) {
210         self.diagnostic().fileline_help(sp, msg)
211     }
212     pub fn note(&self, msg: &str) {
213         self.diagnostic().note(msg)
214     }
215     pub fn help(&self, msg: &str) {
216         self.diagnostic().help(msg)
217     }
218     pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
219         match opt_sp {
220             Some(sp) => self.span_bug(sp, msg),
221             None => self.bug(msg),
222         }
223     }
224     /// Delay a span_bug() call until abort_if_errors()
225     pub fn delay_span_bug(&self, sp: Span, msg: &str) {
226         let mut delayed = self.delayed_span_bug.borrow_mut();
227         *delayed = Some((sp, msg.to_string()));
228     }
229     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
230         self.diagnostic().span_bug(sp, msg)
231     }
232     pub fn bug(&self, msg: &str) -> ! {
233         self.diagnostic().bug(msg)
234     }
235     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
236         self.diagnostic().span_unimpl(sp, msg)
237     }
238     pub fn unimpl(&self, msg: &str) -> ! {
239         self.diagnostic().unimpl(msg)
240     }
241     pub fn add_lint(&self,
242                     lint: &'static lint::Lint,
243                     id: ast::NodeId,
244                     sp: Span,
245                     msg: String) {
246         let lint_id = lint::LintId::of(lint);
247         let mut lints = self.lints.borrow_mut();
248         match lints.get_mut(&id) {
249             Some(arr) => { arr.push((lint_id, sp, msg)); return; }
250             None => {}
251         }
252         lints.insert(id, vec!((lint_id, sp, msg)));
253     }
254     pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
255         let id = self.next_node_id.get();
256
257         match id.checked_add(count) {
258             Some(next) => self.next_node_id.set(next),
259             None => self.bug("Input too large, ran out of node ids!")
260         }
261
262         id
263     }
264     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
265         &self.parse_sess.span_diagnostic
266     }
267     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
268         self.parse_sess.codemap()
269     }
270     // This exists to help with refactoring to eliminate impossible
271     // cases later on
272     pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
273         self.span_bug(sp,
274                       &format!("impossible case reached: {}", msg));
275     }
276     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
277     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
278     pub fn count_llvm_insns(&self) -> bool {
279         self.opts.debugging_opts.count_llvm_insns
280     }
281     pub fn count_type_sizes(&self) -> bool {
282         self.opts.debugging_opts.count_type_sizes
283     }
284     pub fn time_llvm_passes(&self) -> bool {
285         self.opts.debugging_opts.time_llvm_passes
286     }
287     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
288     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
289     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
290     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
291     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
292     pub fn print_llvm_passes(&self) -> bool {
293         self.opts.debugging_opts.print_llvm_passes
294     }
295     pub fn lto(&self) -> bool {
296         self.opts.cg.lto
297     }
298     pub fn no_landing_pads(&self) -> bool {
299         self.opts.debugging_opts.no_landing_pads
300     }
301     pub fn unstable_options(&self) -> bool {
302         self.opts.debugging_opts.unstable_options
303     }
304     pub fn print_enum_sizes(&self) -> bool {
305         self.opts.debugging_opts.print_enum_sizes
306     }
307     pub fn nonzeroing_move_hints(&self) -> bool {
308         self.opts.debugging_opts.enable_nonzeroing_move_hints
309     }
310     pub fn sysroot<'a>(&'a self) -> &'a Path {
311         match self.opts.maybe_sysroot {
312             Some (ref sysroot) => sysroot,
313             None => self.default_sysroot.as_ref()
314                         .expect("missing sysroot and default_sysroot in Session")
315         }
316     }
317     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
318         filesearch::FileSearch::new(self.sysroot(),
319                                     &self.opts.target_triple,
320                                     &self.opts.search_paths,
321                                     kind)
322     }
323     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
324         filesearch::FileSearch::new(
325             self.sysroot(),
326             config::host_triple(),
327             &self.opts.search_paths,
328             kind)
329     }
330 }
331
332 impl NodeIdAssigner for Session {
333     fn next_node_id(&self) -> NodeId {
334         self.reserve_node_ids(1)
335     }
336
337     fn peek_node_id(&self) -> NodeId {
338         self.next_node_id.get().checked_add(1).unwrap()
339     }
340 }
341
342 fn split_msg_into_multilines(msg: &str) -> Option<String> {
343     // Conditions for enabling multi-line errors:
344     if !msg.contains("mismatched types") &&
345         !msg.contains("type mismatch resolving") &&
346         !msg.contains("if and else have incompatible types") &&
347         !msg.contains("if may be missing an else clause") &&
348         !msg.contains("match arms have incompatible types") &&
349         !msg.contains("structure constructor specifies a structure of type") &&
350         !msg.contains("has an incompatible type for trait") {
351             return None
352     }
353     let first = msg.match_indices("expected").filter(|s| {
354         s.0 > 0 && (msg.char_at_reverse(s.0) == ' ' ||
355                     msg.char_at_reverse(s.0) == '(')
356     }).map(|(a, b)| (a - 1, a + b.len()));
357     let second = msg.match_indices("found").filter(|s| {
358         msg.char_at_reverse(s.0) == ' '
359     }).map(|(a, b)| (a - 1, a + b.len()));
360
361     let mut new_msg = String::new();
362     let mut head = 0;
363
364     // Insert `\n` before expected and found.
365     for (pos1, pos2) in first.zip(second) {
366         new_msg = new_msg +
367         // A `(` may be preceded by a space and it should be trimmed
368                   msg[head..pos1.0].trim_right() + // prefix
369                   "\n" +                           // insert before first
370                   &msg[pos1.0..pos1.1] +           // insert what first matched
371                   &msg[pos1.1..pos2.0] +           // between matches
372                   "\n   " +                        // insert before second
373         //           123
374         // `expected` is 3 char longer than `found`. To align the types,
375         // `found` gets 3 spaces prepended.
376                   &msg[pos2.0..pos2.1];            // insert what second matched
377
378         head = pos2.1;
379     }
380
381     let mut tail = &msg[head..];
382     let third = tail.find("(values differ")
383                    .or(tail.find("(lifetime"))
384                    .or(tail.find("(cyclic type of infinite size"));
385     // Insert `\n` before any remaining messages which match.
386     if let Some(pos) = third {
387         // The end of the message may just be wrapped in `()` without
388         // `expected`/`found`.  Push this also to a new line and add the
389         // final tail after.
390         new_msg = new_msg +
391         // `(` is usually preceded by a space and should be trimmed.
392                   tail[..pos].trim_right() + // prefix
393                   "\n" +                     // insert before paren
394                   &tail[pos..];              // append the tail
395
396         tail = "";
397     }
398
399     new_msg.push_str(tail);
400     return Some(new_msg);
401 }
402
403 pub fn build_session(sopts: config::Options,
404                      local_crate_source_file: Option<PathBuf>,
405                      registry: diagnostics::registry::Registry,
406                      cstore: Rc<for<'a> CrateStore<'a>>)
407                      -> Session {
408     // FIXME: This is not general enough to make the warning lint completely override
409     // normal diagnostic warnings, since the warning lint can also be denied and changed
410     // later via the source code.
411     let can_print_warnings = sopts.lint_opts
412         .iter()
413         .filter(|&&(ref key, _)| *key == "warnings")
414         .map(|&(_, ref level)| *level != lint::Allow)
415         .last()
416         .unwrap_or(true);
417
418     let codemap = Rc::new(codemap::CodeMap::new());
419     let diagnostic_handler =
420         errors::Handler::new(sopts.color, Some(registry), can_print_warnings, codemap.clone());
421
422     build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap, cstore)
423 }
424
425 pub fn build_session_(sopts: config::Options,
426                       local_crate_source_file: Option<PathBuf>,
427                       span_diagnostic: errors::Handler,
428                       codemap: Rc<codemap::CodeMap>,
429                       cstore: Rc<for<'a> CrateStore<'a>>)
430                       -> Session {
431     let host = match Target::search(config::host_triple()) {
432         Ok(t) => t,
433         Err(e) => {
434             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
435     }
436     };
437     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
438     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
439     let default_sysroot = match sopts.maybe_sysroot {
440         Some(_) => None,
441         None => Some(filesearch::get_or_default_sysroot())
442     };
443
444     // Make the path absolute, if necessary
445     let local_crate_source_file = local_crate_source_file.map(|path|
446         if path.is_absolute() {
447             path.clone()
448         } else {
449             env::current_dir().unwrap().join(&path)
450         }
451     );
452
453     let can_print_warnings = sopts.lint_opts
454         .iter()
455         .filter(|&&(ref key, _)| *key == "warnings")
456         .map(|&(_, ref level)| *level != lint::Allow)
457         .last()
458         .unwrap_or(true);
459
460     let sess = Session {
461         target: target_cfg,
462         host: host,
463         opts: sopts,
464         cstore: cstore,
465         parse_sess: p_s,
466         // For a library crate, this is always none
467         entry_fn: RefCell::new(None),
468         entry_type: Cell::new(None),
469         plugin_registrar_fn: Cell::new(None),
470         default_sysroot: default_sysroot,
471         local_crate_source_file: local_crate_source_file,
472         working_dir: env::current_dir().unwrap(),
473         lint_store: RefCell::new(lint::LintStore::new()),
474         lints: RefCell::new(NodeMap()),
475         plugin_llvm_passes: RefCell::new(Vec::new()),
476         plugin_attributes: RefCell::new(Vec::new()),
477         crate_types: RefCell::new(Vec::new()),
478         dependency_formats: RefCell::new(FnvHashMap()),
479         crate_metadata: RefCell::new(Vec::new()),
480         delayed_span_bug: RefCell::new(None),
481         features: RefCell::new(feature_gate::Features::new()),
482         recursion_limit: Cell::new(64),
483         can_print_warnings: can_print_warnings,
484         next_node_id: Cell::new(1),
485         injected_allocator: Cell::new(None),
486         available_macros: RefCell::new(HashSet::new()),
487     };
488
489     sess
490 }
491
492 // Seems out of place, but it uses session, so I'm putting it here
493 pub fn expect<T, M>(sess: &Session, opt: Option<T>, msg: M) -> T where
494     M: FnOnce() -> String,
495 {
496     errors::expect(sess.diagnostic(), opt, msg)
497 }
498
499 pub fn early_error(color: errors::ColorConfig, msg: &str) -> ! {
500     let mut emitter = BasicEmitter::stderr(color);
501     emitter.emit(None, msg, None, errors::Level::Fatal);
502     panic!(errors::FatalError);
503 }
504
505 pub fn early_warn(color: errors::ColorConfig, msg: &str) {
506     let mut emitter = BasicEmitter::stderr(color);
507     emitter.emit(None, msg, None, errors::Level::Warning);
508 }