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