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