]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[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
12 use lint;
13 use metadata::cstore::CStore;
14 use metadata::filesearch;
15 use session::search_paths::PathKind;
16 use util::nodemap::NodeMap;
17
18 use regex::Regex;
19
20 use syntax::ast::NodeId;
21 use syntax::codemap::Span;
22 use syntax::diagnostic::{self, Emitter};
23 use syntax::diagnostics;
24 use syntax::feature_gate;
25 use syntax::parse;
26 use syntax::parse::token;
27 use syntax::parse::ParseSess;
28 use syntax::{ast, codemap};
29
30 use rustc_back::target::Target;
31
32 use std::os;
33 use std::cell::{Cell, RefCell};
34
35 pub mod config;
36 pub mod search_paths;
37
38 // Represents the data associated with a compilation
39 // session for a single crate.
40 pub struct Session {
41     pub target: config::Config,
42     pub host: Target,
43     pub opts: config::Options,
44     pub cstore: CStore,
45     pub parse_sess: ParseSess,
46     // For a library crate, this is always none
47     pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
48     pub entry_type: Cell<Option<config::EntryFnType>>,
49     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
50     pub default_sysroot: Option<Path>,
51     // The name of the root source file of the crate, in the local file system. The path is always
52     // expected to be absolute. `None` means that there is no source file.
53     pub local_crate_source_file: Option<Path>,
54     pub working_dir: Path,
55     pub lint_store: RefCell<lint::LintStore>,
56     pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
57     pub crate_types: RefCell<Vec<config::CrateType>>,
58     pub crate_metadata: RefCell<Vec<String>>,
59     pub features: RefCell<feature_gate::Features>,
60
61     /// The maximum recursion limit for potentially infinitely recursive
62     /// operations such as auto-dereference and monomorphization.
63     pub recursion_limit: Cell<uint>,
64
65     pub can_print_warnings: bool
66 }
67
68 impl Session {
69     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
70         self.diagnostic().span_fatal(sp, msg)
71     }
72     pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
73         self.diagnostic().span_fatal_with_code(sp, msg, code)
74     }
75     pub fn fatal(&self, msg: &str) -> ! {
76         self.diagnostic().handler().fatal(msg)
77     }
78     pub fn span_err(&self, sp: Span, msg: &str) {
79         match split_msg_into_multilines(msg) {
80             Some(msg) => self.diagnostic().span_err(sp, &msg[]),
81             None => self.diagnostic().span_err(sp, msg)
82         }
83     }
84     pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
85         match split_msg_into_multilines(msg) {
86             Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[], code),
87             None => self.diagnostic().span_err_with_code(sp, msg, code)
88         }
89     }
90     pub fn err(&self, msg: &str) {
91         self.diagnostic().handler().err(msg)
92     }
93     pub fn err_count(&self) -> uint {
94         self.diagnostic().handler().err_count()
95     }
96     pub fn has_errors(&self) -> bool {
97         self.diagnostic().handler().has_errors()
98     }
99     pub fn abort_if_errors(&self) {
100         self.diagnostic().handler().abort_if_errors()
101     }
102     pub fn span_warn(&self, sp: Span, msg: &str) {
103         if self.can_print_warnings {
104             self.diagnostic().span_warn(sp, msg)
105         }
106     }
107     pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
108         if self.can_print_warnings {
109             self.diagnostic().span_warn_with_code(sp, msg, code)
110         }
111     }
112     pub fn warn(&self, msg: &str) {
113         if self.can_print_warnings {
114             self.diagnostic().handler().warn(msg)
115         }
116     }
117     pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
118         match opt_sp {
119             Some(sp) => self.span_warn(sp, msg),
120             None => self.warn(msg),
121         }
122     }
123     pub fn span_note(&self, sp: Span, msg: &str) {
124         self.diagnostic().span_note(sp, msg)
125     }
126     pub fn span_end_note(&self, sp: Span, msg: &str) {
127         self.diagnostic().span_end_note(sp, msg)
128     }
129     pub fn span_help(&self, sp: Span, msg: &str) {
130         self.diagnostic().span_help(sp, msg)
131     }
132     pub fn fileline_note(&self, sp: Span, msg: &str) {
133         self.diagnostic().fileline_note(sp, msg)
134     }
135     pub fn fileline_help(&self, sp: Span, msg: &str) {
136         self.diagnostic().fileline_help(sp, msg)
137     }
138     pub fn note(&self, msg: &str) {
139         self.diagnostic().handler().note(msg)
140     }
141     pub fn help(&self, msg: &str) {
142         self.diagnostic().handler().note(msg)
143     }
144     pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
145         match opt_sp {
146             Some(sp) => self.span_bug(sp, msg),
147             None => self.bug(msg),
148         }
149     }
150     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
151         self.diagnostic().span_bug(sp, msg)
152     }
153     pub fn bug(&self, msg: &str) -> ! {
154         self.diagnostic().handler().bug(msg)
155     }
156     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
157         self.diagnostic().span_unimpl(sp, msg)
158     }
159     pub fn unimpl(&self, msg: &str) -> ! {
160         self.diagnostic().handler().unimpl(msg)
161     }
162     pub fn add_lint(&self,
163                     lint: &'static lint::Lint,
164                     id: ast::NodeId,
165                     sp: Span,
166                     msg: String) {
167         let lint_id = lint::LintId::of(lint);
168         let mut lints = self.lints.borrow_mut();
169         match lints.get_mut(&id) {
170             Some(arr) => { arr.push((lint_id, sp, msg)); return; }
171             None => {}
172         }
173         lints.insert(id, vec!((lint_id, sp, msg)));
174     }
175     pub fn next_node_id(&self) -> ast::NodeId {
176         self.parse_sess.next_node_id()
177     }
178     pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
179         self.parse_sess.reserve_node_ids(count)
180     }
181     pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler {
182         &self.parse_sess.span_diagnostic
183     }
184     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
185         &self.parse_sess.span_diagnostic.cm
186     }
187     // This exists to help with refactoring to eliminate impossible
188     // cases later on
189     pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
190         self.span_bug(sp,
191                       &format!("impossible case reached: {}", msg)[]);
192     }
193     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
194     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
195     pub fn count_llvm_insns(&self) -> bool {
196         self.opts.debugging_opts.count_llvm_insns
197     }
198     pub fn count_type_sizes(&self) -> bool {
199         self.opts.debugging_opts.count_type_sizes
200     }
201     pub fn time_llvm_passes(&self) -> bool {
202         self.opts.debugging_opts.time_llvm_passes
203     }
204     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
205     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
206     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
207     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
208     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
209     pub fn print_llvm_passes(&self) -> bool {
210         self.opts.debugging_opts.print_llvm_passes
211     }
212     pub fn lto(&self) -> bool {
213         self.opts.cg.lto
214     }
215     pub fn no_landing_pads(&self) -> bool {
216         self.opts.debugging_opts.no_landing_pads
217     }
218     pub fn unstable_options(&self) -> bool {
219         self.opts.debugging_opts.unstable_options
220     }
221     pub fn print_enum_sizes(&self) -> bool {
222         self.opts.debugging_opts.print_enum_sizes
223     }
224     pub fn sysroot<'a>(&'a self) -> &'a Path {
225         match self.opts.maybe_sysroot {
226             Some (ref sysroot) => sysroot,
227             None => self.default_sysroot.as_ref()
228                         .expect("missing sysroot and default_sysroot in Session")
229         }
230     }
231     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
232         filesearch::FileSearch::new(self.sysroot(),
233                                     &self.opts.target_triple[],
234                                     &self.opts.search_paths,
235                                     kind)
236     }
237     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
238         filesearch::FileSearch::new(
239             self.sysroot(),
240             config::host_triple(),
241             &self.opts.search_paths,
242             kind)
243     }
244 }
245
246 fn split_msg_into_multilines(msg: &str) -> Option<String> {
247     // Conditions for enabling multi-line errors:
248     if !msg.contains("mismatched types") &&
249         !msg.contains("type mismatch resolving") &&
250         !msg.contains("if and else have incompatible types") &&
251         !msg.contains("if may be missing an else clause") &&
252         !msg.contains("match arms have incompatible types") &&
253         !msg.contains("structure constructor specifies a structure of type") {
254             return None
255     }
256
257     let first  = Regex::new(r"[( ]expected").unwrap();
258     let second = Regex::new(r" found").unwrap();
259     let third  = Regex::new(
260         r"\((values differ|lifetime|cyclic type of infinite size)").unwrap();
261
262     let mut new_msg = String::new();
263     let mut head = 0u;
264
265     // Insert `\n` before expected and found.
266     for (pos1, pos2) in first.find_iter(msg).zip(
267         second.find_iter(msg)) {
268         new_msg = new_msg +
269             // A `(` may be preceded by a space and it should be trimmed
270             msg[head..pos1.0].trim_right() + // prefix
271             "\n" +                           // insert before first
272             &msg[pos1.0..pos1.1] +           // insert what first matched
273             &msg[pos1.1..pos2.0] +           // between matches
274             "\n   " +                        // insert before second
275             //           123
276             // `expected` is 3 char longer than `found`. To align the types, `found` gets
277             // 3 spaces prepended.
278             &msg[pos2.0..pos2.1];            // insert what second matched
279
280         head = pos2.1;
281     }
282
283     let mut tail = &msg[head..];
284     // Insert `\n` before any remaining messages which match.
285     for pos in third.find_iter(tail).take(1) {
286         // The end of the message may just be wrapped in `()` without `expected`/`found`.
287         // Push this also to a new line and add the final tail after.
288         new_msg = new_msg +
289             // `(` is usually preceded by a space and should be trimmed.
290             tail[..pos.0].trim_right() + // prefix
291             "\n" +                       // insert before paren
292             &tail[pos.0..];              // append the tail
293
294         tail = "";
295     }
296
297     new_msg.push_str(tail);
298
299     return Some(new_msg)
300 }
301
302 pub fn build_session(sopts: config::Options,
303                      local_crate_source_file: Option<Path>,
304                      registry: diagnostics::registry::Registry)
305                      -> Session {
306     let codemap = codemap::CodeMap::new();
307     let diagnostic_handler =
308         diagnostic::default_handler(sopts.color, Some(registry));
309     let span_diagnostic_handler =
310         diagnostic::mk_span_handler(diagnostic_handler, codemap);
311
312     build_session_(sopts, local_crate_source_file, span_diagnostic_handler)
313 }
314
315 pub fn build_session_(sopts: config::Options,
316                       local_crate_source_file: Option<Path>,
317                       span_diagnostic: diagnostic::SpanHandler)
318                       -> Session {
319     let host = match Target::search(config::host_triple()) {
320         Ok(t) => t,
321         Err(e) => {
322             span_diagnostic.handler()
323                 .fatal((format!("Error loading host specification: {}", e)).as_slice());
324     }
325     };
326     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
327     let p_s = parse::new_parse_sess_special_handler(span_diagnostic);
328     let default_sysroot = match sopts.maybe_sysroot {
329         Some(_) => None,
330         None => Some(filesearch::get_or_default_sysroot())
331     };
332
333     // Make the path absolute, if necessary
334     let local_crate_source_file = local_crate_source_file.map(|path|
335         if path.is_absolute() {
336             path.clone()
337         } else {
338             os::getcwd().unwrap().join(&path)
339         }
340     );
341
342     let can_print_warnings = sopts.lint_opts
343         .iter()
344         .filter(|&&(ref key, _)| *key == "warnings")
345         .map(|&(_, ref level)| *level != lint::Allow)
346         .last()
347         .unwrap_or(true);
348
349     let sess = Session {
350         target: target_cfg,
351         host: host,
352         opts: sopts,
353         cstore: CStore::new(token::get_ident_interner()),
354         parse_sess: p_s,
355         // For a library crate, this is always none
356         entry_fn: RefCell::new(None),
357         entry_type: Cell::new(None),
358         plugin_registrar_fn: Cell::new(None),
359         default_sysroot: default_sysroot,
360         local_crate_source_file: local_crate_source_file,
361         working_dir: os::getcwd().unwrap(),
362         lint_store: RefCell::new(lint::LintStore::new()),
363         lints: RefCell::new(NodeMap()),
364         crate_types: RefCell::new(Vec::new()),
365         crate_metadata: RefCell::new(Vec::new()),
366         features: RefCell::new(feature_gate::Features::new()),
367         recursion_limit: Cell::new(64),
368         can_print_warnings: can_print_warnings
369     };
370
371     sess.lint_store.borrow_mut().register_builtin(Some(&sess));
372     sess
373 }
374
375 // Seems out of place, but it uses session, so I'm putting it here
376 pub fn expect<T, M>(sess: &Session, opt: Option<T>, msg: M) -> T where
377     M: FnOnce() -> String,
378 {
379     diagnostic::expect(sess.diagnostic(), opt, msg)
380 }
381
382 pub fn early_error(msg: &str) -> ! {
383     let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
384     emitter.emit(None, msg, None, diagnostic::Fatal);
385     panic!(diagnostic::FatalError);
386 }
387
388 pub fn early_warn(msg: &str) {
389     let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
390     emitter.emit(None, msg, None, diagnostic::Warning);
391 }