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