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.
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.
12 use middle::cstore::CrateStore;
13 use middle::dependency_format;
14 use session::search_paths::PathKind;
15 use util::nodemap::{NodeMap, FnvHashMap};
17 use syntax::ast::{NodeId, NodeIdAssigner, Name};
18 use syntax::codemap::Span;
19 use syntax::errors::{self, DiagnosticBuilder};
20 use syntax::errors::emitter::{Emitter, BasicEmitter};
21 use syntax::diagnostics;
22 use syntax::feature_gate;
24 use syntax::parse::ParseSess;
25 use syntax::{ast, codemap};
26 use syntax::feature_gate::AttributeType;
28 use rustc_back::target::Target;
30 use std::path::{Path, PathBuf};
31 use std::cell::{Cell, RefCell};
32 use std::collections::HashSet;
40 // Represents the data associated with a compilation
41 // session for a single crate.
43 pub target: config::Config,
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
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>,
67 /// The maximum recursion limit for potentially infinitely recursive
68 /// operations such as auto-dereference and monomorphization.
69 pub recursion_limit: Cell<usize>,
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>>,
75 /// Names of all bang-style macros and syntax extensions
76 /// available in this crate
77 pub available_macros: RefCell<HashSet<Name>>,
79 next_node_id: Cell<ast::NodeId>,
83 pub fn struct_span_warn<'a>(&'a self,
86 -> DiagnosticBuilder<'a> {
87 self.diagnostic().struct_span_warn(sp, msg)
89 pub fn struct_span_warn_with_code<'a>(&'a self,
93 -> DiagnosticBuilder<'a> {
94 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
96 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
97 self.diagnostic().struct_warn(msg)
99 pub fn struct_span_err<'a>(&'a self,
102 -> DiagnosticBuilder<'a> {
103 match split_msg_into_multilines(msg) {
104 Some(ref msg) => self.diagnostic().struct_span_err(sp, msg),
105 None => self.diagnostic().struct_span_err(sp, msg),
108 pub fn struct_span_err_with_code<'a>(&'a self,
112 -> DiagnosticBuilder<'a> {
113 match split_msg_into_multilines(msg) {
114 Some(ref msg) => self.diagnostic().struct_span_err_with_code(sp, msg, code),
115 None => self.diagnostic().struct_span_err_with_code(sp, msg, code),
118 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
119 self.diagnostic().struct_err(msg)
121 pub fn struct_span_fatal<'a>(&'a self,
124 -> DiagnosticBuilder<'a> {
125 self.diagnostic().struct_span_fatal(sp, msg)
127 pub fn struct_span_fatal_with_code<'a>(&'a self,
131 -> DiagnosticBuilder<'a> {
132 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
134 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
135 self.diagnostic().struct_fatal(msg)
138 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
139 panic!(self.diagnostic().span_fatal(sp, msg))
141 pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
142 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
144 pub fn fatal(&self, msg: &str) -> ! {
145 panic!(self.diagnostic().fatal(msg))
147 pub fn span_err_or_warn(&self, is_warning: bool, sp: Span, msg: &str) {
149 self.span_warn(sp, msg);
151 self.span_err(sp, msg);
154 pub fn span_err(&self, sp: Span, msg: &str) {
155 match split_msg_into_multilines(msg) {
156 Some(msg) => self.diagnostic().span_err(sp, &msg),
157 None => self.diagnostic().span_err(sp, msg)
160 pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
161 match split_msg_into_multilines(msg) {
162 Some(msg) => self.diagnostic().span_err_with_code(sp, &msg, code),
163 None => self.diagnostic().span_err_with_code(sp, msg, code)
166 pub fn err(&self, msg: &str) {
167 self.diagnostic().err(msg)
169 pub fn err_count(&self) -> usize {
170 self.diagnostic().err_count()
172 pub fn has_errors(&self) -> bool {
173 self.diagnostic().has_errors()
175 pub fn abort_if_errors(&self) {
176 self.diagnostic().abort_if_errors();
178 pub fn abort_if_new_errors<F>(&self, mut f: F)
181 let count = self.err_count();
183 if self.err_count() > count {
184 self.abort_if_errors();
187 pub fn span_warn(&self, sp: Span, msg: &str) {
188 self.diagnostic().span_warn(sp, msg)
190 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
191 self.diagnostic().span_warn_with_code(sp, msg, code)
193 pub fn warn(&self, msg: &str) {
194 self.diagnostic().warn(msg)
196 pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
198 Some(sp) => self.span_warn(sp, msg),
199 None => self.warn(msg),
202 pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
204 Some(sp) => self.span_bug(sp, msg),
205 None => self.bug(msg),
208 /// Delay a span_bug() call until abort_if_errors()
209 pub fn delay_span_bug(&self, sp: Span, msg: &str) {
210 self.diagnostic().delay_span_bug(sp, msg)
212 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
213 self.diagnostic().span_bug(sp, msg)
215 pub fn bug(&self, msg: &str) -> ! {
216 self.diagnostic().bug(msg)
218 pub fn note_without_error(&self, msg: &str) {
219 self.diagnostic().note_without_error(msg)
221 pub fn span_note_without_error(&self, sp: Span, msg: &str) {
222 self.diagnostic().span_note_without_error(sp, msg)
224 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
225 self.diagnostic().span_unimpl(sp, msg)
227 pub fn unimpl(&self, msg: &str) -> ! {
228 self.diagnostic().unimpl(msg)
230 pub fn add_lint(&self,
231 lint: &'static lint::Lint,
235 let lint_id = lint::LintId::of(lint);
236 let mut lints = self.lints.borrow_mut();
237 match lints.get_mut(&id) {
238 Some(arr) => { arr.push((lint_id, sp, msg)); return; }
241 lints.insert(id, vec!((lint_id, sp, msg)));
243 pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
244 let id = self.next_node_id.get();
246 match id.checked_add(count) {
247 Some(next) => self.next_node_id.set(next),
248 None => self.bug("Input too large, ran out of node ids!")
253 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
254 &self.parse_sess.span_diagnostic
256 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
257 self.parse_sess.codemap()
259 // This exists to help with refactoring to eliminate impossible
261 pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
262 self.span_bug(sp, &format!("impossible case reached: {}", msg));
264 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
265 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
266 pub fn count_llvm_insns(&self) -> bool {
267 self.opts.debugging_opts.count_llvm_insns
269 pub fn count_type_sizes(&self) -> bool {
270 self.opts.debugging_opts.count_type_sizes
272 pub fn time_llvm_passes(&self) -> bool {
273 self.opts.debugging_opts.time_llvm_passes
275 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
276 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
277 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
278 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
279 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
280 pub fn print_llvm_passes(&self) -> bool {
281 self.opts.debugging_opts.print_llvm_passes
283 pub fn lto(&self) -> bool {
286 pub fn no_landing_pads(&self) -> bool {
287 self.opts.debugging_opts.no_landing_pads
289 pub fn unstable_options(&self) -> bool {
290 self.opts.debugging_opts.unstable_options
292 pub fn print_enum_sizes(&self) -> bool {
293 self.opts.debugging_opts.print_enum_sizes
295 pub fn nonzeroing_move_hints(&self) -> bool {
296 self.opts.debugging_opts.enable_nonzeroing_move_hints
298 pub fn sysroot<'a>(&'a self) -> &'a Path {
299 match self.opts.maybe_sysroot {
300 Some (ref sysroot) => sysroot,
301 None => self.default_sysroot.as_ref()
302 .expect("missing sysroot and default_sysroot in Session")
305 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
306 filesearch::FileSearch::new(self.sysroot(),
307 &self.opts.target_triple,
308 &self.opts.search_paths,
311 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
312 filesearch::FileSearch::new(
314 config::host_triple(),
315 &self.opts.search_paths,
320 impl NodeIdAssigner for Session {
321 fn next_node_id(&self) -> NodeId {
322 self.reserve_node_ids(1)
325 fn peek_node_id(&self) -> NodeId {
326 self.next_node_id.get().checked_add(1).unwrap()
330 fn split_msg_into_multilines(msg: &str) -> Option<String> {
331 // Conditions for enabling multi-line errors:
332 if !msg.contains("mismatched types") &&
333 !msg.contains("type mismatch resolving") &&
334 !msg.contains("if and else have incompatible types") &&
335 !msg.contains("if may be missing an else clause") &&
336 !msg.contains("match arms have incompatible types") &&
337 !msg.contains("structure constructor specifies a structure of type") &&
338 !msg.contains("has an incompatible type for trait") {
341 let first = msg.match_indices("expected").filter(|s| {
342 s.0 > 0 && (msg.char_at_reverse(s.0) == ' ' ||
343 msg.char_at_reverse(s.0) == '(')
344 }).map(|(a, b)| (a - 1, a + b.len()));
345 let second = msg.match_indices("found").filter(|s| {
346 msg.char_at_reverse(s.0) == ' '
347 }).map(|(a, b)| (a - 1, a + b.len()));
349 let mut new_msg = String::new();
352 // Insert `\n` before expected and found.
353 for (pos1, pos2) in first.zip(second) {
355 // A `(` may be preceded by a space and it should be trimmed
356 msg[head..pos1.0].trim_right() + // prefix
357 "\n" + // insert before first
358 &msg[pos1.0..pos1.1] + // insert what first matched
359 &msg[pos1.1..pos2.0] + // between matches
360 "\n " + // insert before second
362 // `expected` is 3 char longer than `found`. To align the types,
363 // `found` gets 3 spaces prepended.
364 &msg[pos2.0..pos2.1]; // insert what second matched
369 let mut tail = &msg[head..];
370 let third = tail.find("(values differ")
371 .or(tail.find("(lifetime"))
372 .or(tail.find("(cyclic type of infinite size"));
373 // Insert `\n` before any remaining messages which match.
374 if let Some(pos) = third {
375 // The end of the message may just be wrapped in `()` without
376 // `expected`/`found`. Push this also to a new line and add the
379 // `(` is usually preceded by a space and should be trimmed.
380 tail[..pos].trim_right() + // prefix
381 "\n" + // insert before paren
382 &tail[pos..]; // append the tail
387 new_msg.push_str(tail);
388 return Some(new_msg);
391 pub fn build_session(sopts: config::Options,
392 local_crate_source_file: Option<PathBuf>,
393 registry: diagnostics::registry::Registry,
394 cstore: Rc<for<'a> CrateStore<'a>>)
396 // FIXME: This is not general enough to make the warning lint completely override
397 // normal diagnostic warnings, since the warning lint can also be denied and changed
398 // later via the source code.
399 let can_print_warnings = sopts.lint_opts
401 .filter(|&&(ref key, _)| *key == "warnings")
402 .map(|&(_, ref level)| *level != lint::Allow)
405 let treat_err_as_bug = sopts.treat_err_as_bug;
407 let codemap = Rc::new(codemap::CodeMap::new());
408 let diagnostic_handler =
409 errors::Handler::new(sopts.color,
415 build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap, cstore)
418 pub fn build_session_(sopts: config::Options,
419 local_crate_source_file: Option<PathBuf>,
420 span_diagnostic: errors::Handler,
421 codemap: Rc<codemap::CodeMap>,
422 cstore: Rc<for<'a> CrateStore<'a>>)
424 let host = match Target::search(config::host_triple()) {
427 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
430 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
431 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
432 let default_sysroot = match sopts.maybe_sysroot {
434 None => Some(filesearch::get_or_default_sysroot())
437 // Make the path absolute, if necessary
438 let local_crate_source_file = local_crate_source_file.map(|path|
439 if path.is_absolute() {
442 env::current_dir().unwrap().join(&path)
452 // For a library crate, this is always none
453 entry_fn: RefCell::new(None),
454 entry_type: Cell::new(None),
455 plugin_registrar_fn: Cell::new(None),
456 default_sysroot: default_sysroot,
457 local_crate_source_file: local_crate_source_file,
458 working_dir: env::current_dir().unwrap(),
459 lint_store: RefCell::new(lint::LintStore::new()),
460 lints: RefCell::new(NodeMap()),
461 plugin_llvm_passes: RefCell::new(Vec::new()),
462 plugin_attributes: RefCell::new(Vec::new()),
463 crate_types: RefCell::new(Vec::new()),
464 dependency_formats: RefCell::new(FnvHashMap()),
465 crate_metadata: RefCell::new(Vec::new()),
466 features: RefCell::new(feature_gate::Features::new()),
467 recursion_limit: Cell::new(64),
468 next_node_id: Cell::new(1),
469 injected_allocator: Cell::new(None),
470 available_macros: RefCell::new(HashSet::new()),
476 pub fn early_error(color: errors::ColorConfig, msg: &str) -> ! {
477 let mut emitter = BasicEmitter::stderr(color);
478 emitter.emit(None, msg, None, errors::Level::Fatal);
479 panic!(errors::FatalError);
482 pub fn early_warn(color: errors::ColorConfig, msg: &str) {
483 let mut emitter = BasicEmitter::stderr(color);
484 emitter.emit(None, msg, None, errors::Level::Warning);