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.
11 use dep_graph::DepGraph;
12 use hir::def_id::{CrateNum, DefIndex};
15 use middle::cstore::CrateStore;
16 use middle::dependency_format;
17 use session::search_paths::PathKind;
18 use session::config::{DebugInfoLevel, PanicStrategy};
20 use util::nodemap::{NodeMap, FnvHashMap};
21 use util::common::duration_to_secs_str;
22 use mir::transform as mir_pass;
24 use syntax::ast::NodeId;
25 use errors::{self, DiagnosticBuilder};
26 use errors::emitter::{Emitter, EmitterWriter};
27 use syntax::json::JsonEmitter;
28 use syntax::feature_gate;
30 use syntax::parse::ParseSess;
31 use syntax::parse::token;
32 use syntax::{ast, codemap};
33 use syntax::feature_gate::AttributeType;
34 use syntax_pos::{Span, MultiSpan};
36 use rustc_back::target::Target;
37 use rustc_data_structures::flock;
40 use std::path::{Path, PathBuf};
41 use std::cell::{self, Cell, RefCell};
42 use std::collections::HashMap;
44 use std::ffi::CString;
48 use std::time::Duration;
55 // Represents the data associated with a compilation
56 // session for a single crate.
58 pub dep_graph: DepGraph,
59 pub target: config::Config,
61 pub opts: config::Options,
62 pub cstore: Rc<for<'a> CrateStore<'a>>,
63 pub parse_sess: ParseSess,
64 // For a library crate, this is always none
65 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
66 pub entry_type: Cell<Option<config::EntryFnType>>,
67 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
68 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
69 pub default_sysroot: Option<PathBuf>,
70 // The name of the root source file of the crate, in the local file system.
71 // The path is always expected to be absolute. `None` means that there is no
73 pub local_crate_source_file: Option<PathBuf>,
74 pub working_dir: PathBuf,
75 pub lint_store: RefCell<lint::LintStore>,
76 pub lints: RefCell<NodeMap<Vec<(lint::LintId, Span, String)>>>,
77 pub plugin_llvm_passes: RefCell<Vec<String>>,
78 pub mir_passes: RefCell<mir_pass::Passes>,
79 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
80 pub crate_types: RefCell<Vec<config::CrateType>>,
81 pub dependency_formats: RefCell<dependency_format::Dependencies>,
82 // The crate_disambiguator is constructed out of all the `-C metadata`
83 // arguments passed to the compiler. Its value together with the crate-name
84 // forms a unique global identifier for the crate. It is used to allow
85 // multiple crates with the same name to coexist. See the
86 // trans::back::symbol_names module for more information.
87 pub crate_disambiguator: RefCell<token::InternedString>,
88 pub features: RefCell<feature_gate::Features>,
90 /// The maximum recursion limit for potentially infinitely recursive
91 /// operations such as auto-dereference and monomorphization.
92 pub recursion_limit: Cell<usize>,
94 /// The metadata::creader module may inject an allocator/panic_runtime
95 /// dependency if it didn't already find one, and this tracks what was
97 pub injected_allocator: Cell<Option<CrateNum>>,
98 pub injected_panic_runtime: Cell<Option<CrateNum>>,
100 /// Map from imported macro spans (which consist of
101 /// the localized span for the macro body) to the
102 /// macro name and defintion span in the source crate.
103 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
105 incr_comp_session: RefCell<IncrCompSession>,
107 /// Some measurements that are being gathered during compilation.
108 pub perf_stats: PerfStats,
110 next_node_id: Cell<ast::NodeId>,
113 pub struct PerfStats {
114 // The accumulated time needed for computing the SVH of the crate
115 pub svh_time: Cell<Duration>,
116 // The accumulated time spent on computing incr. comp. hashes
117 pub incr_comp_hashes_time: Cell<Duration>,
118 // The number of incr. comp. hash computations performed
119 pub incr_comp_hashes_count: Cell<u64>,
120 // The accumulated time spent on computing symbol hashes
121 pub symbol_hash_time: Cell<Duration>,
125 pub fn local_crate_disambiguator(&self) -> token::InternedString {
126 self.crate_disambiguator.borrow().clone()
128 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
131 -> DiagnosticBuilder<'a> {
132 self.diagnostic().struct_span_warn(sp, msg)
134 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
138 -> DiagnosticBuilder<'a> {
139 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
141 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
142 self.diagnostic().struct_warn(msg)
144 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
147 -> DiagnosticBuilder<'a> {
148 self.diagnostic().struct_span_err(sp, msg)
150 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
154 -> DiagnosticBuilder<'a> {
155 self.diagnostic().struct_span_err_with_code(sp, msg, code)
157 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
158 self.diagnostic().struct_err(msg)
160 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
163 -> DiagnosticBuilder<'a> {
164 self.diagnostic().struct_span_fatal(sp, msg)
166 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
170 -> DiagnosticBuilder<'a> {
171 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
173 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
174 self.diagnostic().struct_fatal(msg)
177 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
178 panic!(self.diagnostic().span_fatal(sp, msg))
180 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
181 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
183 pub fn fatal(&self, msg: &str) -> ! {
184 panic!(self.diagnostic().fatal(msg))
186 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
188 self.span_warn(sp, msg);
190 self.span_err(sp, msg);
193 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
194 self.diagnostic().span_err(sp, msg)
196 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
197 self.diagnostic().span_err_with_code(sp, &msg, code)
199 pub fn err(&self, msg: &str) {
200 self.diagnostic().err(msg)
202 pub fn err_count(&self) -> usize {
203 self.diagnostic().err_count()
205 pub fn has_errors(&self) -> bool {
206 self.diagnostic().has_errors()
208 pub fn abort_if_errors(&self) {
209 self.diagnostic().abort_if_errors();
211 pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
212 where F: FnOnce() -> T
214 let old_count = self.err_count();
216 let errors = self.err_count() - old_count;
223 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
224 self.diagnostic().span_warn(sp, msg)
226 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
227 self.diagnostic().span_warn_with_code(sp, msg, code)
229 pub fn warn(&self, msg: &str) {
230 self.diagnostic().warn(msg)
232 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
234 Some(sp) => self.span_warn(sp, msg),
235 None => self.warn(msg),
238 /// Delay a span_bug() call until abort_if_errors()
239 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
240 self.diagnostic().delay_span_bug(sp, msg)
242 pub fn note_without_error(&self, msg: &str) {
243 self.diagnostic().note_without_error(msg)
245 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
246 self.diagnostic().span_note_without_error(sp, msg)
248 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
249 self.diagnostic().span_unimpl(sp, msg)
251 pub fn unimpl(&self, msg: &str) -> ! {
252 self.diagnostic().unimpl(msg)
254 pub fn add_lint(&self,
255 lint: &'static lint::Lint,
259 let lint_id = lint::LintId::of(lint);
260 let mut lints = self.lints.borrow_mut();
261 if let Some(arr) = lints.get_mut(&id) {
262 let tuple = (lint_id, sp, msg);
263 if !arr.contains(&tuple) {
268 lints.insert(id, vec!((lint_id, sp, msg)));
270 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
271 let id = self.next_node_id.get();
273 match id.as_usize().checked_add(count) {
275 self.next_node_id.set(ast::NodeId::new(next));
277 None => bug!("Input too large, ran out of node ids!")
282 pub fn next_node_id(&self) -> NodeId {
283 self.reserve_node_ids(1)
285 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
286 &self.parse_sess.span_diagnostic
288 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
289 self.parse_sess.codemap()
291 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
292 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
293 pub fn count_llvm_insns(&self) -> bool {
294 self.opts.debugging_opts.count_llvm_insns
296 pub fn time_llvm_passes(&self) -> bool {
297 self.opts.debugging_opts.time_llvm_passes
299 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
300 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
301 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
302 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
303 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
304 pub fn print_llvm_passes(&self) -> bool {
305 self.opts.debugging_opts.print_llvm_passes
307 pub fn lto(&self) -> bool {
310 pub fn no_landing_pads(&self) -> bool {
311 self.opts.debugging_opts.no_landing_pads ||
312 self.opts.cg.panic == PanicStrategy::Abort
314 pub fn unstable_options(&self) -> bool {
315 self.opts.debugging_opts.unstable_options
317 pub fn nonzeroing_move_hints(&self) -> bool {
318 self.opts.debugging_opts.enable_nonzeroing_move_hints
321 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
322 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
323 !self.target.target.options.eliminate_frame_pointer
326 /// Returns the symbol name for the registrar function,
327 /// given the crate Svh and the function DefIndex.
328 pub fn generate_plugin_registrar_symbol(&self, svh: &Svh, index: DefIndex)
330 format!("__rustc_plugin_registrar__{}_{}", svh, index.as_usize())
333 pub fn generate_derive_registrar_symbol(&self,
335 index: DefIndex) -> String {
336 format!("__rustc_derive_registrar__{}_{}", svh, index.as_usize())
339 pub fn sysroot<'a>(&'a self) -> &'a Path {
340 match self.opts.maybe_sysroot {
341 Some (ref sysroot) => sysroot,
342 None => self.default_sysroot.as_ref()
343 .expect("missing sysroot and default_sysroot in Session")
346 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
347 filesearch::FileSearch::new(self.sysroot(),
348 &self.opts.target_triple,
349 &self.opts.search_paths,
352 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
353 filesearch::FileSearch::new(
355 config::host_triple(),
356 &self.opts.search_paths,
360 pub fn init_incr_comp_session(&self,
361 session_dir: PathBuf,
362 lock_file: flock::Lock) {
363 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
365 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
366 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
369 *incr_comp_session = IncrCompSession::Active {
370 session_directory: session_dir,
371 lock_file: lock_file,
375 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
376 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
378 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
379 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
382 // Note: This will also drop the lock file, thus unlocking the directory
383 *incr_comp_session = IncrCompSession::Finalized {
384 session_directory: new_directory_path,
388 pub fn mark_incr_comp_session_as_invalid(&self) {
389 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
391 let session_directory = match *incr_comp_session {
392 IncrCompSession::Active { ref session_directory, .. } => {
393 session_directory.clone()
395 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
399 // Note: This will also drop the lock file, thus unlocking the directory
400 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
401 session_directory: session_directory
405 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
406 let incr_comp_session = self.incr_comp_session.borrow();
407 cell::Ref::map(incr_comp_session, |incr_comp_session| {
408 match *incr_comp_session {
409 IncrCompSession::NotInitialized => {
410 bug!("Trying to get session directory from IncrCompSession `{:?}`",
413 IncrCompSession::Active { ref session_directory, .. } |
414 IncrCompSession::Finalized { ref session_directory } |
415 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
422 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
423 if self.opts.incremental.is_some() {
424 Some(self.incr_comp_session_dir())
430 pub fn print_perf_stats(&self) {
431 println!("Total time spent computing SVHs: {}",
432 duration_to_secs_str(self.perf_stats.svh_time.get()));
433 println!("Total time spent computing incr. comp. hashes: {}",
434 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
435 println!("Total number of incr. comp. hashes computed: {}",
436 self.perf_stats.incr_comp_hashes_count.get());
437 println!("Total time spent computing symbol hashes: {}",
438 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
442 pub fn build_session(sopts: config::Options,
443 dep_graph: &DepGraph,
444 local_crate_source_file: Option<PathBuf>,
445 registry: errors::registry::Registry,
446 cstore: Rc<for<'a> CrateStore<'a>>)
448 build_session_with_codemap(sopts,
450 local_crate_source_file,
453 Rc::new(codemap::CodeMap::new()),
457 pub fn build_session_with_codemap(sopts: config::Options,
458 dep_graph: &DepGraph,
459 local_crate_source_file: Option<PathBuf>,
460 registry: errors::registry::Registry,
461 cstore: Rc<for<'a> CrateStore<'a>>,
462 codemap: Rc<codemap::CodeMap>,
463 emitter_dest: Option<Box<Write + Send>>)
465 // FIXME: This is not general enough to make the warning lint completely override
466 // normal diagnostic warnings, since the warning lint can also be denied and changed
467 // later via the source code.
468 let can_print_warnings = sopts.lint_opts
470 .filter(|&&(ref key, _)| *key == "warnings")
471 .map(|&(_, ref level)| *level != lint::Allow)
474 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
476 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
477 (config::ErrorOutputType::HumanReadable(color_config), None) => {
478 Box::new(EmitterWriter::stderr(color_config,
479 Some(codemap.clone())))
481 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
482 Box::new(EmitterWriter::new(dst,
483 Some(codemap.clone())))
485 (config::ErrorOutputType::Json, None) => {
486 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
488 (config::ErrorOutputType::Json, Some(dst)) => {
489 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
493 let diagnostic_handler =
494 errors::Handler::with_emitter(can_print_warnings,
498 build_session_(sopts,
500 local_crate_source_file,
506 pub fn build_session_(sopts: config::Options,
507 dep_graph: &DepGraph,
508 local_crate_source_file: Option<PathBuf>,
509 span_diagnostic: errors::Handler,
510 codemap: Rc<codemap::CodeMap>,
511 cstore: Rc<for<'a> CrateStore<'a>>)
513 let host = match Target::search(config::host_triple()) {
516 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
519 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
520 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
521 let default_sysroot = match sopts.maybe_sysroot {
523 None => Some(filesearch::get_or_default_sysroot())
526 // Make the path absolute, if necessary
527 let local_crate_source_file = local_crate_source_file.map(|path|
528 if path.is_absolute() {
531 env::current_dir().unwrap().join(&path)
536 dep_graph: dep_graph.clone(),
542 // For a library crate, this is always none
543 entry_fn: RefCell::new(None),
544 entry_type: Cell::new(None),
545 plugin_registrar_fn: Cell::new(None),
546 derive_registrar_fn: Cell::new(None),
547 default_sysroot: default_sysroot,
548 local_crate_source_file: local_crate_source_file,
549 working_dir: env::current_dir().unwrap(),
550 lint_store: RefCell::new(lint::LintStore::new()),
551 lints: RefCell::new(NodeMap()),
552 plugin_llvm_passes: RefCell::new(Vec::new()),
553 mir_passes: RefCell::new(mir_pass::Passes::new()),
554 plugin_attributes: RefCell::new(Vec::new()),
555 crate_types: RefCell::new(Vec::new()),
556 dependency_formats: RefCell::new(FnvHashMap()),
557 crate_disambiguator: RefCell::new(token::intern("").as_str()),
558 features: RefCell::new(feature_gate::Features::new()),
559 recursion_limit: Cell::new(64),
560 next_node_id: Cell::new(NodeId::new(1)),
561 injected_allocator: Cell::new(None),
562 injected_panic_runtime: Cell::new(None),
563 imported_macro_spans: RefCell::new(HashMap::new()),
564 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
565 perf_stats: PerfStats {
566 svh_time: Cell::new(Duration::from_secs(0)),
567 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
568 incr_comp_hashes_count: Cell::new(0),
569 symbol_hash_time: Cell::new(Duration::from_secs(0)),
578 /// Holds data on the current incremental compilation session, if there is one.
580 pub enum IncrCompSession {
581 // This is the state the session will be in until the incr. comp. dir is
584 // This is the state during which the session directory is private and can
587 session_directory: PathBuf,
588 lock_file: flock::Lock,
590 // This is the state after the session directory has been finalized. In this
591 // state, the contents of the directory must not be modified any more.
593 session_directory: PathBuf,
595 // This is an error state that is reached when some compilation error has
596 // occurred. It indicates that the contents of the session directory must
597 // not be used, since they might be invalid.
598 InvalidBecauseOfErrors {
599 session_directory: PathBuf,
603 fn init_llvm(sess: &Session) {
605 // Before we touch LLVM, make sure that multithreading is enabled.
607 static INIT: Once = Once::new();
608 static mut POISONED: bool = false;
610 if llvm::LLVMStartMultithreaded() != 1 {
611 // use an extra bool to make sure that all future usage of LLVM
612 // cannot proceed despite the Once not running more than once.
616 configure_llvm(sess);
620 bug!("couldn't enable multi-threaded LLVM");
625 unsafe fn configure_llvm(sess: &Session) {
626 let mut llvm_c_strs = Vec::new();
627 let mut llvm_args = Vec::new();
630 let mut add = |arg: &str| {
631 let s = CString::new(arg).unwrap();
632 llvm_args.push(s.as_ptr());
635 add("rustc"); // fake program name
636 if sess.time_llvm_passes() { add("-time-passes"); }
637 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
639 for arg in &sess.opts.cg.llvm_args {
644 llvm::LLVMInitializePasses();
646 llvm::initialize_available_targets();
648 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
652 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
653 let emitter: Box<Emitter> = match output {
654 config::ErrorOutputType::HumanReadable(color_config) => {
655 Box::new(EmitterWriter::stderr(color_config,
658 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
660 let handler = errors::Handler::with_emitter(true, false, emitter);
661 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
662 panic!(errors::FatalError);
665 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
666 let emitter: Box<Emitter> = match output {
667 config::ErrorOutputType::HumanReadable(color_config) => {
668 Box::new(EmitterWriter::stderr(color_config,
671 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
673 let handler = errors::Handler::with_emitter(true, false, emitter);
674 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
677 // Err(0) means compilation was stopped, but no errors were found.
678 // This would be better as a dedicated enum, but using try! is so convenient.
679 pub type CompileResult = Result<(), usize>;
681 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
691 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
692 // this wrapper mostly exists so I don't have to write a fully
693 // qualified path of None::<Span> inside the bug!() macro defintion
694 opt_span_bug_fmt(file, line, None::<Span>, args);
699 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
702 args: fmt::Arguments) -> ! {
703 opt_span_bug_fmt(file, line, Some(span), args);
706 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
709 args: fmt::Arguments) -> ! {
710 tls::with_opt(move |tcx| {
711 let msg = format!("{}:{}: {}", file, line, args);
713 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
714 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
715 (None, _) => panic!(msg)