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