rust/src/librustc/session/mod.rs

453 lines
16 KiB
Rust
Raw Normal View History

// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use lint;
use middle::cstore::CrateStore;
use middle::dependency_format;
use session::search_paths::PathKind;
use util::nodemap::{NodeMap, FnvHashMap};
use syntax::ast::{NodeId, NodeIdAssigner, Name};
use syntax::codemap::Span;
use syntax::errors;
use syntax::errors::emitter::{Emitter, BasicEmitter};
use syntax::diagnostics;
2014-09-10 19:55:42 -05:00
use syntax::feature_gate;
use syntax::parse;
use syntax::parse::ParseSess;
use syntax::{ast, codemap};
use syntax::feature_gate::AttributeType;
use rustc_back::target::Target;
use std::path::{Path, PathBuf};
use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::env;
use std::rc::Rc;
pub mod config;
pub mod filesearch;
pub mod search_paths;
// Represents the data associated with a compilation
// session for a single crate.
2014-03-05 08:36:01 -06:00
pub struct Session {
pub target: config::Config,
pub host: Target,
pub opts: config::Options,
pub cstore: Rc<for<'a> CrateStore<'a>>,
pub parse_sess: ParseSess,
// For a library crate, this is always none
pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
pub entry_type: Cell<Option<config::EntryFnType>>,
pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
pub default_sysroot: Option<PathBuf>,
// The name of the root source file of the crate, in the local file system.
// The path is always expected to be absolute. `None` means that there is no
// source file.
pub local_crate_source_file: Option<PathBuf>,
pub working_dir: PathBuf,
pub lint_store: RefCell<lint::LintStore>,
2014-06-01 18:21:52 -05:00
pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
2015-04-08 14:52:58 -05:00
pub plugin_llvm_passes: RefCell<Vec<String>>,
pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
pub crate_types: RefCell<Vec<config::CrateType>>,
pub dependency_formats: RefCell<dependency_format::Dependencies>,
pub crate_metadata: RefCell<Vec<String>>,
2014-09-10 19:55:42 -05:00
pub features: RefCell<feature_gate::Features>,
/// The maximum recursion limit for potentially infinitely recursive
/// operations such as auto-dereference and monomorphization.
pub recursion_limit: Cell<usize>,
/// The metadata::creader module may inject an allocator dependency if it
/// didn't already find one, and this tracks what was injected.
pub injected_allocator: Cell<Option<ast::CrateNum>>,
/// Names of all bang-style macros and syntax extensions
/// available in this crate
pub available_macros: RefCell<HashSet<Name>>,
next_node_id: Cell<ast::NodeId>,
}
2014-03-05 08:36:01 -06:00
impl Session {
pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
panic!(self.diagnostic().span_fatal(sp, msg))
}
pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
}
pub fn fatal(&self, msg: &str) -> ! {
panic!(self.diagnostic().fatal(msg))
}
pub fn span_err_or_warn(&self, is_warning: bool, sp: Span, msg: &str) {
if is_warning {
self.span_warn(sp, msg);
} else {
self.span_err(sp, msg);
}
}
pub fn span_err(&self, sp: Span, msg: &str) {
2015-01-20 16:18:35 -06:00
match split_msg_into_multilines(msg) {
Some(msg) => self.diagnostic().span_err(sp, &msg[..]),
2015-01-20 16:18:35 -06:00
None => self.diagnostic().span_err(sp, msg)
2015-01-11 22:18:52 -06:00
}
}
pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
2015-01-20 16:18:35 -06:00
match split_msg_into_multilines(msg) {
Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[..], code),
2015-01-20 16:18:35 -06:00
None => self.diagnostic().span_err_with_code(sp, msg, code)
}
}
pub fn err(&self, msg: &str) {
self.diagnostic().err(msg)
}
pub fn err_count(&self) -> usize {
self.diagnostic().err_count()
}
pub fn has_errors(&self) -> bool {
self.diagnostic().has_errors()
}
pub fn abort_if_errors(&self) {
self.diagnostic().abort_if_errors();
}
2015-12-11 01:59:11 -06:00
pub fn abort_if_new_errors<F>(&self, mut f: F)
where F: FnMut()
{
let count = self.err_count();
f();
if self.err_count() > count {
self.abort_if_errors();
}
}
pub fn span_warn(&self, sp: Span, msg: &str) {
self.diagnostic().span_warn(sp, msg)
}
pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
self.diagnostic().span_warn_with_code(sp, msg, code)
}
pub fn warn(&self, msg: &str) {
self.diagnostic().warn(msg)
}
pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
match opt_sp {
Some(sp) => self.span_warn(sp, msg),
None => self.warn(msg),
}
}
pub fn span_note(&self, sp: Span, msg: &str) {
2014-03-16 13:56:24 -05:00
self.diagnostic().span_note(sp, msg)
}
pub fn span_end_note(&self, sp: Span, msg: &str) {
2014-03-16 13:56:24 -05:00
self.diagnostic().span_end_note(sp, msg)
}
/// Prints out a message with a suggested edit of the code.
///
/// See `errors::RenderSpan::Suggestion` for more information.
pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
self.diagnostic().span_suggestion(sp, msg, suggestion)
}
pub fn span_help(&self, sp: Span, msg: &str) {
self.diagnostic().span_help(sp, msg)
}
pub fn fileline_note(&self, sp: Span, msg: &str) {
self.diagnostic().fileline_note(sp, msg)
}
pub fn fileline_help(&self, sp: Span, msg: &str) {
self.diagnostic().fileline_help(sp, msg)
}
pub fn note(&self, msg: &str) {
self.diagnostic().note(msg)
}
pub fn help(&self, msg: &str) {
self.diagnostic().help(msg)
}
pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
match opt_sp {
Some(sp) => self.span_bug(sp, msg),
None => self.bug(msg),
}
}
/// Delay a span_bug() call until abort_if_errors()
pub fn delay_span_bug(&self, sp: Span, msg: &str) {
self.diagnostic().delay_span_bug(sp, msg)
}
pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
2014-03-16 13:56:24 -05:00
self.diagnostic().span_bug(sp, msg)
}
pub fn bug(&self, msg: &str) -> ! {
self.diagnostic().bug(msg)
}
pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
2014-03-16 13:56:24 -05:00
self.diagnostic().span_unimpl(sp, msg)
}
pub fn unimpl(&self, msg: &str) -> ! {
self.diagnostic().unimpl(msg)
}
pub fn add_lint(&self,
lint: &'static lint::Lint,
id: ast::NodeId,
sp: Span,
msg: String) {
let lint_id = lint::LintId::of(lint);
let mut lints = self.lints.borrow_mut();
2014-11-06 11:25:16 -06:00
match lints.get_mut(&id) {
Some(arr) => { arr.push((lint_id, sp, msg)); return; }
None => {}
}
lints.insert(id, vec!((lint_id, sp, msg)));
}
pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
let id = self.next_node_id.get();
match id.checked_add(count) {
Some(next) => self.next_node_id.set(next),
None => self.bug("Input too large, ran out of node ids!")
}
id
}
pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
2014-03-16 13:56:24 -05:00
&self.parse_sess.span_diagnostic
}
2014-03-16 13:56:24 -05:00
pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
self.parse_sess.codemap()
2014-03-16 13:56:24 -05:00
}
2012-08-21 19:22:45 -05:00
// This exists to help with refactoring to eliminate impossible
// cases later on
pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
self.span_bug(sp, &format!("impossible case reached: {}", msg));
2012-08-21 19:22:45 -05:00
}
pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
pub fn count_llvm_insns(&self) -> bool {
self.opts.debugging_opts.count_llvm_insns
2013-02-22 00:41:37 -06:00
}
pub fn count_type_sizes(&self) -> bool {
self.opts.debugging_opts.count_type_sizes
2013-02-22 00:41:37 -06:00
}
pub fn time_llvm_passes(&self) -> bool {
self.opts.debugging_opts.time_llvm_passes
2013-02-22 00:41:37 -06:00
}
pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
pub fn print_llvm_passes(&self) -> bool {
self.opts.debugging_opts.print_llvm_passes
2013-08-22 22:58:42 -05:00
}
Implement LTO This commit implements LTO for rust leveraging LLVM's passes. What this means is: * When compiling an rlib, in addition to insdering foo.o into the archive, also insert foo.bc (the LLVM bytecode) of the optimized module. * When the compiler detects the -Z lto option, it will attempt to perform LTO on a staticlib or binary output. The compiler will emit an error if a dylib or rlib output is being generated. * The actual act of performing LTO is as follows: 1. Force all upstream libraries to have an rlib version available. 2. Load the bytecode of each upstream library from the rlib. 3. Link all this bytecode into the current LLVM module (just using llvm apis) 4. Run an internalization pass which internalizes all symbols except those found reachable for the local crate of compilation. 5. Run the LLVM LTO pass manager over this entire module 6a. If assembling an archive, then add all upstream rlibs into the output archive. This ignores all of the object/bitcode/metadata files rust generated and placed inside the rlibs. 6b. If linking a binary, create copies of all upstream rlibs, remove the rust-generated object-file, and then link everything as usual. As I have explained in #10741, this process is excruciatingly slow, so this is *not* turned on by default, and it is also why I have decided to hide it behind a -Z flag for now. The good news is that the binary sizes are about as small as they can be as a result of LTO, so it's definitely working. Closes #10741 Closes #10740
2013-12-03 01:19:29 -06:00
pub fn lto(&self) -> bool {
2014-09-20 23:36:17 -05:00
self.opts.cg.lto
Implement LTO This commit implements LTO for rust leveraging LLVM's passes. What this means is: * When compiling an rlib, in addition to insdering foo.o into the archive, also insert foo.bc (the LLVM bytecode) of the optimized module. * When the compiler detects the -Z lto option, it will attempt to perform LTO on a staticlib or binary output. The compiler will emit an error if a dylib or rlib output is being generated. * The actual act of performing LTO is as follows: 1. Force all upstream libraries to have an rlib version available. 2. Load the bytecode of each upstream library from the rlib. 3. Link all this bytecode into the current LLVM module (just using llvm apis) 4. Run an internalization pass which internalizes all symbols except those found reachable for the local crate of compilation. 5. Run the LLVM LTO pass manager over this entire module 6a. If assembling an archive, then add all upstream rlibs into the output archive. This ignores all of the object/bitcode/metadata files rust generated and placed inside the rlibs. 6b. If linking a binary, create copies of all upstream rlibs, remove the rust-generated object-file, and then link everything as usual. As I have explained in #10741, this process is excruciatingly slow, so this is *not* turned on by default, and it is also why I have decided to hide it behind a -Z flag for now. The good news is that the binary sizes are about as small as they can be as a result of LTO, so it's definitely working. Closes #10741 Closes #10740
2013-12-03 01:19:29 -06:00
}
pub fn no_landing_pads(&self) -> bool {
self.opts.debugging_opts.no_landing_pads
}
2014-12-27 03:19:27 -06:00
pub fn unstable_options(&self) -> bool {
self.opts.debugging_opts.unstable_options
2014-02-07 04:50:07 -06:00
}
pub fn print_enum_sizes(&self) -> bool {
self.opts.debugging_opts.print_enum_sizes
}
pub fn nonzeroing_move_hints(&self) -> bool {
self.opts.debugging_opts.enable_nonzeroing_move_hints
}
pub fn sysroot<'a>(&'a self) -> &'a Path {
match self.opts.maybe_sysroot {
Some (ref sysroot) => sysroot,
2014-03-09 07:24:58 -05:00
None => self.default_sysroot.as_ref()
.expect("missing sysroot and default_sysroot in Session")
}
}
pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
filesearch::FileSearch::new(self.sysroot(),
&self.opts.target_triple,
&self.opts.search_paths,
kind)
2014-03-09 07:24:58 -05:00
}
pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
filesearch::FileSearch::new(
self.sysroot(),
config::host_triple(),
&self.opts.search_paths,
kind)
}
}
2015-09-27 21:00:15 -05:00
impl NodeIdAssigner for Session {
fn next_node_id(&self) -> NodeId {
self.reserve_node_ids(1)
}
fn peek_node_id(&self) -> NodeId {
self.next_node_id.get().checked_add(1).unwrap()
}
2015-09-27 21:00:15 -05:00
}
2015-01-20 16:18:35 -06:00
fn split_msg_into_multilines(msg: &str) -> Option<String> {
// Conditions for enabling multi-line errors:
if !msg.contains("mismatched types") &&
!msg.contains("type mismatch resolving") &&
!msg.contains("if and else have incompatible types") &&
!msg.contains("if may be missing an else clause") &&
!msg.contains("match arms have incompatible types") &&
!msg.contains("structure constructor specifies a structure of type") &&
!msg.contains("has an incompatible type for trait") {
2015-01-20 16:18:35 -06:00
return None
}
let first = msg.match_indices("expected").filter(|s| {
s.0 > 0 && (msg.char_at_reverse(s.0) == ' ' ||
msg.char_at_reverse(s.0) == '(')
}).map(|(a, b)| (a - 1, a + b.len()));
let second = msg.match_indices("found").filter(|s| {
msg.char_at_reverse(s.0) == ' '
}).map(|(a, b)| (a - 1, a + b.len()));
2015-01-20 16:18:35 -06:00
let mut new_msg = String::new();
let mut head = 0;
2015-01-20 16:18:35 -06:00
// Insert `\n` before expected and found.
for (pos1, pos2) in first.zip(second) {
2015-01-20 16:18:35 -06:00
new_msg = new_msg +
// A `(` may be preceded by a space and it should be trimmed
msg[head..pos1.0].trim_right() + // prefix
"\n" + // insert before first
&msg[pos1.0..pos1.1] + // insert what first matched
&msg[pos1.1..pos2.0] + // between matches
"\n " + // insert before second
// 123
// `expected` is 3 char longer than `found`. To align the types,
// `found` gets 3 spaces prepended.
&msg[pos2.0..pos2.1]; // insert what second matched
2015-01-20 16:18:35 -06:00
head = pos2.1;
}
let mut tail = &msg[head..];
2015-02-19 07:36:58 -06:00
let third = tail.find("(values differ")
.or(tail.find("(lifetime"))
.or(tail.find("(cyclic type of infinite size"));
2015-01-20 16:18:35 -06:00
// Insert `\n` before any remaining messages which match.
if let Some(pos) = third {
// The end of the message may just be wrapped in `()` without
// `expected`/`found`. Push this also to a new line and add the
// final tail after.
2015-01-20 16:18:35 -06:00
new_msg = new_msg +
// `(` is usually preceded by a space and should be trimmed.
tail[..pos].trim_right() + // prefix
"\n" + // insert before paren
&tail[pos..]; // append the tail
2015-01-20 16:18:35 -06:00
tail = "";
}
new_msg.push_str(tail);
return Some(new_msg);
2015-01-20 16:18:35 -06:00
}
pub fn build_session(sopts: config::Options,
local_crate_source_file: Option<PathBuf>,
registry: diagnostics::registry::Registry,
cstore: Rc<for<'a> CrateStore<'a>>)
-> Session {
// FIXME: This is not general enough to make the warning lint completely override
// normal diagnostic warnings, since the warning lint can also be denied and changed
// later via the source code.
let can_print_warnings = sopts.lint_opts
.iter()
.filter(|&&(ref key, _)| *key == "warnings")
.map(|&(_, ref level)| *level != lint::Allow)
.last()
.unwrap_or(true);
let treat_err_as_bug = sopts.treat_err_as_bug;
let codemap = Rc::new(codemap::CodeMap::new());
let diagnostic_handler =
errors::Handler::new(sopts.color,
Some(registry),
can_print_warnings,
treat_err_as_bug,
codemap.clone());
build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap, cstore)
}
pub fn build_session_(sopts: config::Options,
local_crate_source_file: Option<PathBuf>,
span_diagnostic: errors::Handler,
codemap: Rc<codemap::CodeMap>,
cstore: Rc<for<'a> CrateStore<'a>>)
-> Session {
let host = match Target::search(config::host_triple()) {
Ok(t) => t,
Err(e) => {
panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
}
};
let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
let default_sysroot = match sopts.maybe_sysroot {
Some(_) => None,
None => Some(filesearch::get_or_default_sysroot())
};
// Make the path absolute, if necessary
let local_crate_source_file = local_crate_source_file.map(|path|
if path.is_absolute() {
path.clone()
} else {
env::current_dir().unwrap().join(&path)
}
);
let sess = Session {
target: target_cfg,
host: host,
opts: sopts,
cstore: cstore,
parse_sess: p_s,
// For a library crate, this is always none
entry_fn: RefCell::new(None),
entry_type: Cell::new(None),
plugin_registrar_fn: Cell::new(None),
default_sysroot: default_sysroot,
local_crate_source_file: local_crate_source_file,
working_dir: env::current_dir().unwrap(),
lint_store: RefCell::new(lint::LintStore::new()),
lints: RefCell::new(NodeMap()),
2015-04-08 14:52:58 -05:00
plugin_llvm_passes: RefCell::new(Vec::new()),
plugin_attributes: RefCell::new(Vec::new()),
crate_types: RefCell::new(Vec::new()),
dependency_formats: RefCell::new(FnvHashMap()),
crate_metadata: RefCell::new(Vec::new()),
2014-09-10 19:55:42 -05:00
features: RefCell::new(feature_gate::Features::new()),
recursion_limit: Cell::new(64),
next_node_id: Cell::new(1),
injected_allocator: Cell::new(None),
available_macros: RefCell::new(HashSet::new()),
};
sess
}
pub fn early_error(color: errors::ColorConfig, msg: &str) -> ! {
let mut emitter = BasicEmitter::stderr(color);
emitter.emit(None, msg, None, errors::Level::Fatal);
panic!(errors::FatalError);
}
pub fn early_warn(color: errors::ColorConfig, msg: &str) {
let mut emitter = BasicEmitter::stderr(color);
emitter.emit(None, msg, None, errors::Level::Warning);
}