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