]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[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 metadata::cstore::CStore;
13 use metadata::filesearch;
14 use lint;
15 use util::nodemap::NodeMap;
16
17 use syntax::ast::NodeId;
18 use syntax::codemap::Span;
19 use syntax::diagnostic::{mod, Emitter};
20 use syntax::diagnostics;
21 use syntax::feature_gate;
22 use syntax::parse;
23 use syntax::parse::token;
24 use syntax::parse::ParseSess;
25 use syntax::{ast, codemap};
26
27 use std::os;
28 use std::cell::{Cell, RefCell};
29
30 pub mod config;
31
32 // Represents the data associated with a compilation
33 // session for a single crate.
34 pub struct Session {
35     pub target: config::Config,
36     pub opts: config::Options,
37     pub cstore: CStore,
38     pub parse_sess: ParseSess,
39     // For a library crate, this is always none
40     pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
41     pub entry_type: Cell<Option<config::EntryFnType>>,
42     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
43     pub default_sysroot: Option<Path>,
44     // The name of the root source file of the crate, in the local file system. The path is always
45     // expected to be absolute. `None` means that there is no source file.
46     pub local_crate_source_file: Option<Path>,
47     pub working_dir: Path,
48     pub lint_store: RefCell<lint::LintStore>,
49     pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
50     pub crate_types: RefCell<Vec<config::CrateType>>,
51     pub crate_metadata: RefCell<Vec<String>>,
52     pub features: RefCell<feature_gate::Features>,
53
54     /// The maximum recursion limit for potentially infinitely recursive
55     /// operations such as auto-dereference and monomorphization.
56     pub recursion_limit: Cell<uint>,
57
58     pub can_print_warnings: bool
59 }
60
61 impl Session {
62     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
63         self.diagnostic().span_fatal(sp, msg)
64     }
65     pub fn fatal(&self, msg: &str) -> ! {
66         self.diagnostic().handler().fatal(msg)
67     }
68     pub fn span_err(&self, sp: Span, msg: &str) {
69         self.diagnostic().span_err(sp, msg)
70     }
71     pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
72         self.diagnostic().span_err_with_code(sp, msg, code)
73     }
74     pub fn err(&self, msg: &str) {
75         self.diagnostic().handler().err(msg)
76     }
77     pub fn err_count(&self) -> uint {
78         self.diagnostic().handler().err_count()
79     }
80     pub fn has_errors(&self) -> bool {
81         self.diagnostic().handler().has_errors()
82     }
83     pub fn abort_if_errors(&self) {
84         self.diagnostic().handler().abort_if_errors()
85     }
86     pub fn span_warn(&self, sp: Span, msg: &str) {
87         if self.can_print_warnings {
88             self.diagnostic().span_warn(sp, msg)
89         }
90     }
91     pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
92         if self.can_print_warnings {
93             self.diagnostic().span_warn_with_code(sp, msg, code)
94         }
95     }
96     pub fn warn(&self, msg: &str) {
97         if self.can_print_warnings {
98             self.diagnostic().handler().warn(msg)
99         }
100     }
101     pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
102         match opt_sp {
103             Some(sp) => self.span_warn(sp, msg),
104             None => self.warn(msg),
105         }
106     }
107     pub fn span_note(&self, sp: Span, msg: &str) {
108         self.diagnostic().span_note(sp, msg)
109     }
110     pub fn span_end_note(&self, sp: Span, msg: &str) {
111         self.diagnostic().span_end_note(sp, msg)
112     }
113     pub fn span_help(&self, sp: Span, msg: &str) {
114         self.diagnostic().span_help(sp, msg)
115     }
116     pub fn fileline_note(&self, sp: Span, msg: &str) {
117         self.diagnostic().fileline_note(sp, msg)
118     }
119     pub fn note(&self, msg: &str) {
120         self.diagnostic().handler().note(msg)
121     }
122     pub fn help(&self, msg: &str) {
123         self.diagnostic().handler().note(msg)
124     }
125     pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
126         match opt_sp {
127             Some(sp) => self.span_bug(sp, msg),
128             None => self.bug(msg),
129         }
130     }
131     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
132         self.diagnostic().span_bug(sp, msg)
133     }
134     pub fn bug(&self, msg: &str) -> ! {
135         self.diagnostic().handler().bug(msg)
136     }
137     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
138         self.diagnostic().span_unimpl(sp, msg)
139     }
140     pub fn unimpl(&self, msg: &str) -> ! {
141         self.diagnostic().handler().unimpl(msg)
142     }
143     pub fn add_lint(&self,
144                     lint: &'static lint::Lint,
145                     id: ast::NodeId,
146                     sp: Span,
147                     msg: String) {
148         let lint_id = lint::LintId::of(lint);
149         let mut lints = self.lints.borrow_mut();
150         match lints.get_mut(&id) {
151             Some(arr) => { arr.push((lint_id, sp, msg)); return; }
152             None => {}
153         }
154         lints.insert(id, vec!((lint_id, sp, msg)));
155     }
156     pub fn next_node_id(&self) -> ast::NodeId {
157         self.parse_sess.next_node_id()
158     }
159     pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
160         self.parse_sess.reserve_node_ids(count)
161     }
162     pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler {
163         &self.parse_sess.span_diagnostic
164     }
165     pub fn debugging_opt(&self, opt: u64) -> bool {
166         (self.opts.debugging_opts & opt) != 0
167     }
168     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
169         &self.parse_sess.span_diagnostic.cm
170     }
171     // This exists to help with refactoring to eliminate impossible
172     // cases later on
173     pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
174         self.span_bug(sp,
175                       format!("impossible case reached: {}", msg).as_slice());
176     }
177     pub fn verbose(&self) -> bool { self.debugging_opt(config::VERBOSE) }
178     pub fn time_passes(&self) -> bool { self.debugging_opt(config::TIME_PASSES) }
179     pub fn count_llvm_insns(&self) -> bool {
180         self.debugging_opt(config::COUNT_LLVM_INSNS)
181     }
182     pub fn count_type_sizes(&self) -> bool {
183         self.debugging_opt(config::COUNT_TYPE_SIZES)
184     }
185     pub fn time_llvm_passes(&self) -> bool {
186         self.debugging_opt(config::TIME_LLVM_PASSES)
187     }
188     pub fn trans_stats(&self) -> bool { self.debugging_opt(config::TRANS_STATS) }
189     pub fn meta_stats(&self) -> bool { self.debugging_opt(config::META_STATS) }
190     pub fn asm_comments(&self) -> bool { self.debugging_opt(config::ASM_COMMENTS) }
191     pub fn no_verify(&self) -> bool { self.debugging_opt(config::NO_VERIFY) }
192     pub fn borrowck_stats(&self) -> bool { self.debugging_opt(config::BORROWCK_STATS) }
193     pub fn print_llvm_passes(&self) -> bool {
194         self.debugging_opt(config::PRINT_LLVM_PASSES)
195     }
196     pub fn lto(&self) -> bool {
197         self.opts.cg.lto
198     }
199     pub fn no_landing_pads(&self) -> bool {
200         self.debugging_opt(config::NO_LANDING_PADS)
201     }
202     pub fn show_span(&self) -> bool {
203         self.debugging_opt(config::SHOW_SPAN)
204     }
205     pub fn sysroot<'a>(&'a self) -> &'a Path {
206         match self.opts.maybe_sysroot {
207             Some (ref sysroot) => sysroot,
208             None => self.default_sysroot.as_ref()
209                         .expect("missing sysroot and default_sysroot in Session")
210         }
211     }
212     pub fn target_filesearch<'a>(&'a self) -> filesearch::FileSearch<'a> {
213         filesearch::FileSearch::new(self.sysroot(),
214                                     self.opts.target_triple.as_slice(),
215                                     &self.opts.addl_lib_search_paths)
216     }
217     pub fn host_filesearch<'a>(&'a self) -> filesearch::FileSearch<'a> {
218         filesearch::FileSearch::new(
219             self.sysroot(),
220             config::host_triple(),
221             &self.opts.addl_lib_search_paths)
222     }
223 }
224
225 pub fn build_session(sopts: config::Options,
226                      local_crate_source_file: Option<Path>,
227                      registry: diagnostics::registry::Registry)
228                      -> Session {
229     let codemap = codemap::CodeMap::new();
230     let diagnostic_handler =
231         diagnostic::default_handler(sopts.color, Some(registry));
232     let span_diagnostic_handler =
233         diagnostic::mk_span_handler(diagnostic_handler, codemap);
234
235     build_session_(sopts, local_crate_source_file, span_diagnostic_handler)
236 }
237
238 pub fn build_session_(sopts: config::Options,
239                       local_crate_source_file: Option<Path>,
240                       span_diagnostic: diagnostic::SpanHandler)
241                       -> Session {
242     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
243     let p_s = parse::new_parse_sess_special_handler(span_diagnostic);
244     let default_sysroot = match sopts.maybe_sysroot {
245         Some(_) => None,
246         None => Some(filesearch::get_or_default_sysroot())
247     };
248
249     // Make the path absolute, if necessary
250     let local_crate_source_file = local_crate_source_file.map(|path|
251         if path.is_absolute() {
252             path.clone()
253         } else {
254             os::getcwd().unwrap().join(&path)
255         }
256     );
257
258     let can_print_warnings = sopts.lint_opts
259         .iter()
260         .filter(|&&(ref key, _)| *key == "warnings")
261         .map(|&(_, ref level)| *level != lint::Allow)
262         .last()
263         .unwrap_or(true);
264
265     let sess = Session {
266         target: target_cfg,
267         opts: sopts,
268         cstore: CStore::new(token::get_ident_interner()),
269         parse_sess: p_s,
270         // For a library crate, this is always none
271         entry_fn: RefCell::new(None),
272         entry_type: Cell::new(None),
273         plugin_registrar_fn: Cell::new(None),
274         default_sysroot: default_sysroot,
275         local_crate_source_file: local_crate_source_file,
276         working_dir: os::getcwd().unwrap(),
277         lint_store: RefCell::new(lint::LintStore::new()),
278         lints: RefCell::new(NodeMap::new()),
279         crate_types: RefCell::new(Vec::new()),
280         crate_metadata: RefCell::new(Vec::new()),
281         features: RefCell::new(feature_gate::Features::new()),
282         recursion_limit: Cell::new(64),
283         can_print_warnings: can_print_warnings
284     };
285
286     sess.lint_store.borrow_mut().register_builtin(Some(&sess));
287     sess
288 }
289
290 // Seems out of place, but it uses session, so I'm putting it here
291 pub fn expect<T>(sess: &Session, opt: Option<T>, msg: || -> String) -> T {
292     diagnostic::expect(sess.diagnostic(), opt, msg)
293 }
294
295 pub fn early_error(msg: &str) -> ! {
296     let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
297     emitter.emit(None, msg, None, diagnostic::Fatal);
298     panic!(diagnostic::FatalError);
299 }
300
301 pub fn early_warn(msg: &str) {
302     let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
303     emitter.emit(None, msg, None, diagnostic::Warning);
304 }
305