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 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
14 use dep_graph::DepGraph;
15 use hir::def_id::{CrateNum, DefIndex};
18 use middle::cstore::CrateStore;
19 use middle::dependency_format;
20 use session::search_paths::PathKind;
21 use session::config::DebugInfoLevel;
23 use util::nodemap::{FxHashMap, FxHashSet};
24 use util::common::duration_to_secs_str;
25 use mir::transform as mir_pass;
27 use syntax::ast::NodeId;
28 use errors::{self, DiagnosticBuilder};
29 use errors::emitter::{Emitter, EmitterWriter};
30 use syntax::json::JsonEmitter;
31 use syntax::feature_gate;
33 use syntax::parse::ParseSess;
34 use syntax::symbol::Symbol;
35 use syntax::{ast, codemap};
36 use syntax::feature_gate::AttributeType;
37 use syntax_pos::{Span, MultiSpan};
39 use rustc_back::{LinkerFlavor, PanicStrategy};
40 use rustc_back::target::Target;
41 use rustc_data_structures::flock;
44 use std::path::{Path, PathBuf};
45 use std::cell::{self, Cell, RefCell};
46 use std::collections::HashMap;
48 use std::ffi::CString;
52 use std::time::Duration;
60 // Represents the data associated with a compilation
61 // session for a single crate.
63 pub dep_graph: DepGraph,
64 pub target: config::Config,
66 pub opts: config::Options,
67 pub cstore: Rc<CrateStore>,
68 pub parse_sess: ParseSess,
69 // For a library crate, this is always none
70 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
71 pub entry_type: Cell<Option<config::EntryFnType>>,
72 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
73 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
74 pub default_sysroot: Option<PathBuf>,
75 // The name of the root source file of the crate, in the local file system.
76 // The path is always expected to be absolute. `None` means that there is no
78 pub local_crate_source_file: Option<PathBuf>,
79 pub working_dir: PathBuf,
80 pub lint_store: RefCell<lint::LintStore>,
81 pub lints: RefCell<lint::LintTable>,
82 /// Set of (LintId, span, message) tuples tracking lint (sub)diagnostics
83 /// that have been set once, but should not be set again, in order to avoid
84 /// redundantly verbose output (Issue #24690).
85 pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Span, String)>>,
86 pub plugin_llvm_passes: RefCell<Vec<String>>,
87 pub mir_passes: RefCell<mir_pass::Passes>,
88 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
89 pub crate_types: RefCell<Vec<config::CrateType>>,
90 pub dependency_formats: RefCell<dependency_format::Dependencies>,
91 // The crate_disambiguator is constructed out of all the `-C metadata`
92 // arguments passed to the compiler. Its value together with the crate-name
93 // forms a unique global identifier for the crate. It is used to allow
94 // multiple crates with the same name to coexist. See the
95 // trans::back::symbol_names module for more information.
96 pub crate_disambiguator: RefCell<Symbol>,
97 pub features: RefCell<feature_gate::Features>,
99 /// The maximum recursion limit for potentially infinitely recursive
100 /// operations such as auto-dereference and monomorphization.
101 pub recursion_limit: Cell<usize>,
103 /// The maximum length of types during monomorphization.
104 pub type_length_limit: Cell<usize>,
106 /// The metadata::creader module may inject an allocator/panic_runtime
107 /// dependency if it didn't already find one, and this tracks what was
109 pub injected_allocator: Cell<Option<CrateNum>>,
110 pub injected_panic_runtime: Cell<Option<CrateNum>>,
112 /// Map from imported macro spans (which consist of
113 /// the localized span for the macro body) to the
114 /// macro name and defintion span in the source crate.
115 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
117 incr_comp_session: RefCell<IncrCompSession>,
119 /// Some measurements that are being gathered during compilation.
120 pub perf_stats: PerfStats,
122 /// Data about code being compiled, gathered during compilation.
123 pub code_stats: RefCell<CodeStats>,
125 next_node_id: Cell<ast::NodeId>,
127 /// If -zfuel=crate=n is specified, Some(crate).
128 optimization_fuel_crate: Option<String>,
129 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
130 optimization_fuel_limit: Cell<u64>,
131 /// We're rejecting all further optimizations.
132 out_of_fuel: Cell<bool>,
134 // The next two are public because the driver needs to read them.
136 /// If -zprint-fuel=crate, Some(crate).
137 pub print_fuel_crate: Option<String>,
138 /// Always set to zero and incremented so that we can print fuel expended by a crate.
139 pub print_fuel: Cell<u64>,
142 pub struct PerfStats {
143 // The accumulated time needed for computing the SVH of the crate
144 pub svh_time: Cell<Duration>,
145 // The accumulated time spent on computing incr. comp. hashes
146 pub incr_comp_hashes_time: Cell<Duration>,
147 // The number of incr. comp. hash computations performed
148 pub incr_comp_hashes_count: Cell<u64>,
149 // The number of bytes hashed when computing ICH values
150 pub incr_comp_bytes_hashed: Cell<u64>,
151 // The accumulated time spent on computing symbol hashes
152 pub symbol_hash_time: Cell<Duration>,
153 // The accumulated time spent decoding def path tables from metadata
154 pub decode_def_path_tables_time: Cell<Duration>,
158 pub fn local_crate_disambiguator(&self) -> Symbol {
159 *self.crate_disambiguator.borrow()
161 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
164 -> DiagnosticBuilder<'a> {
165 self.diagnostic().struct_span_warn(sp, msg)
167 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
171 -> DiagnosticBuilder<'a> {
172 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
174 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
175 self.diagnostic().struct_warn(msg)
177 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
180 -> DiagnosticBuilder<'a> {
181 self.diagnostic().struct_span_err(sp, msg)
183 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
187 -> DiagnosticBuilder<'a> {
188 self.diagnostic().struct_span_err_with_code(sp, msg, code)
190 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
191 self.diagnostic().struct_err(msg)
193 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
196 -> DiagnosticBuilder<'a> {
197 self.diagnostic().struct_span_fatal(sp, msg)
199 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
203 -> DiagnosticBuilder<'a> {
204 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
206 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
207 self.diagnostic().struct_fatal(msg)
210 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
211 panic!(self.diagnostic().span_fatal(sp, msg))
213 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
214 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
216 pub fn fatal(&self, msg: &str) -> ! {
217 panic!(self.diagnostic().fatal(msg))
219 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
221 self.span_warn(sp, msg);
223 self.span_err(sp, msg);
226 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
227 self.diagnostic().span_err(sp, msg)
229 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
230 self.diagnostic().span_err_with_code(sp, &msg, code)
232 pub fn err(&self, msg: &str) {
233 self.diagnostic().err(msg)
235 pub fn err_count(&self) -> usize {
236 self.diagnostic().err_count()
238 pub fn has_errors(&self) -> bool {
239 self.diagnostic().has_errors()
241 pub fn abort_if_errors(&self) {
242 self.diagnostic().abort_if_errors();
244 pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
245 where F: FnOnce() -> T
247 let old_count = self.err_count();
249 let errors = self.err_count() - old_count;
256 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
257 self.diagnostic().span_warn(sp, msg)
259 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
260 self.diagnostic().span_warn_with_code(sp, msg, code)
262 pub fn warn(&self, msg: &str) {
263 self.diagnostic().warn(msg)
265 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
267 Some(sp) => self.span_warn(sp, msg),
268 None => self.warn(msg),
271 /// Delay a span_bug() call until abort_if_errors()
272 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
273 self.diagnostic().delay_span_bug(sp, msg)
275 pub fn note_without_error(&self, msg: &str) {
276 self.diagnostic().note_without_error(msg)
278 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
279 self.diagnostic().span_note_without_error(sp, msg)
281 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
282 self.diagnostic().span_unimpl(sp, msg)
284 pub fn unimpl(&self, msg: &str) -> ! {
285 self.diagnostic().unimpl(msg)
288 pub fn add_lint<S: Into<MultiSpan>>(&self,
289 lint: &'static lint::Lint,
294 self.lints.borrow_mut().add_lint(lint, id, sp, msg);
297 pub fn add_lint_diagnostic<M>(&self,
298 lint: &'static lint::Lint,
301 where M: lint::IntoEarlyLint,
303 self.lints.borrow_mut().add_lint_diagnostic(lint, id, msg);
306 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
307 let id = self.next_node_id.get();
309 match id.as_usize().checked_add(count) {
311 self.next_node_id.set(ast::NodeId::new(next));
313 None => bug!("Input too large, ran out of node ids!")
318 pub fn next_node_id(&self) -> NodeId {
319 self.reserve_node_ids(1)
321 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
322 &self.parse_sess.span_diagnostic
325 /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but
326 /// deduplicates on lint ID, span, and message for this `Session` if we're
327 /// not outputting in JSON mode.
329 // FIXME: if the need arises for one-time diagnostics other than
330 // `span_note`, we almost certainly want to generalize this
331 // "check/insert-into the one-time diagnostics map, then set message if
332 // it's not already there" code to accomodate all of them
333 pub fn diag_span_note_once<'a, 'b>(&'a self,
334 diag_builder: &'b mut DiagnosticBuilder<'a>,
335 lint: &'static lint::Lint, span: Span, message: &str) {
336 match self.opts.error_format {
337 // when outputting JSON for tool consumption, the tool might want
339 config::ErrorOutputType::Json => {
340 diag_builder.span_note(span, &message);
343 let lint_id = lint::LintId::of(lint);
344 let id_span_message = (lint_id, span, message.to_owned());
345 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
347 diag_builder.span_note(span, &message);
353 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
354 self.parse_sess.codemap()
356 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
357 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
358 pub fn count_llvm_insns(&self) -> bool {
359 self.opts.debugging_opts.count_llvm_insns
361 pub fn time_llvm_passes(&self) -> bool {
362 self.opts.debugging_opts.time_llvm_passes
364 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
365 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
366 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
367 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
368 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
369 pub fn print_llvm_passes(&self) -> bool {
370 self.opts.debugging_opts.print_llvm_passes
372 pub fn lto(&self) -> bool {
375 /// Returns the panic strategy for this compile session. If the user explicitly selected one
376 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
377 pub fn panic_strategy(&self) -> PanicStrategy {
378 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
380 pub fn linker_flavor(&self) -> LinkerFlavor {
381 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
383 pub fn no_landing_pads(&self) -> bool {
384 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
386 pub fn unstable_options(&self) -> bool {
387 self.opts.debugging_opts.unstable_options
389 pub fn nonzeroing_move_hints(&self) -> bool {
390 self.opts.debugging_opts.enable_nonzeroing_move_hints
392 pub fn overflow_checks(&self) -> bool {
393 self.opts.cg.overflow_checks
394 .or(self.opts.debugging_opts.force_overflow_checks)
395 .unwrap_or(self.opts.debug_assertions)
398 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
399 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
400 !self.target.target.options.eliminate_frame_pointer
403 /// Returns the symbol name for the registrar function,
404 /// given the crate Svh and the function DefIndex.
405 pub fn generate_plugin_registrar_symbol(&self, svh: &Svh, index: DefIndex)
407 format!("__rustc_plugin_registrar__{}_{}", svh, index.as_usize())
410 pub fn generate_derive_registrar_symbol(&self,
412 index: DefIndex) -> String {
413 format!("__rustc_derive_registrar__{}_{}", svh, index.as_usize())
416 pub fn sysroot<'a>(&'a self) -> &'a Path {
417 match self.opts.maybe_sysroot {
418 Some (ref sysroot) => sysroot,
419 None => self.default_sysroot.as_ref()
420 .expect("missing sysroot and default_sysroot in Session")
423 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
424 filesearch::FileSearch::new(self.sysroot(),
425 &self.opts.target_triple,
426 &self.opts.search_paths,
429 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
430 filesearch::FileSearch::new(
432 config::host_triple(),
433 &self.opts.search_paths,
437 pub fn init_incr_comp_session(&self,
438 session_dir: PathBuf,
439 lock_file: flock::Lock) {
440 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
442 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
443 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
446 *incr_comp_session = IncrCompSession::Active {
447 session_directory: session_dir,
448 lock_file: lock_file,
452 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
453 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
455 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
456 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
459 // Note: This will also drop the lock file, thus unlocking the directory
460 *incr_comp_session = IncrCompSession::Finalized {
461 session_directory: new_directory_path,
465 pub fn mark_incr_comp_session_as_invalid(&self) {
466 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
468 let session_directory = match *incr_comp_session {
469 IncrCompSession::Active { ref session_directory, .. } => {
470 session_directory.clone()
472 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
476 // Note: This will also drop the lock file, thus unlocking the directory
477 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
478 session_directory: session_directory
482 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
483 let incr_comp_session = self.incr_comp_session.borrow();
484 cell::Ref::map(incr_comp_session, |incr_comp_session| {
485 match *incr_comp_session {
486 IncrCompSession::NotInitialized => {
487 bug!("Trying to get session directory from IncrCompSession `{:?}`",
490 IncrCompSession::Active { ref session_directory, .. } |
491 IncrCompSession::Finalized { ref session_directory } |
492 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
499 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
500 if self.opts.incremental.is_some() {
501 Some(self.incr_comp_session_dir())
507 pub fn print_perf_stats(&self) {
508 println!("Total time spent computing SVHs: {}",
509 duration_to_secs_str(self.perf_stats.svh_time.get()));
510 println!("Total time spent computing incr. comp. hashes: {}",
511 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
512 println!("Total number of incr. comp. hashes computed: {}",
513 self.perf_stats.incr_comp_hashes_count.get());
514 println!("Total number of bytes hashed for incr. comp.: {}",
515 self.perf_stats.incr_comp_bytes_hashed.get());
516 println!("Average bytes hashed per incr. comp. HIR node: {}",
517 self.perf_stats.incr_comp_bytes_hashed.get() /
518 self.perf_stats.incr_comp_hashes_count.get());
519 println!("Total time spent computing symbol hashes: {}",
520 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
521 println!("Total time spent decoding DefPath tables: {}",
522 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
525 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
526 /// This expends fuel if applicable, and records fuel if applicable.
527 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
529 match self.optimization_fuel_crate {
530 Some(ref c) if c == crate_name => {
531 let fuel = self.optimization_fuel_limit.get();
533 if fuel == 0 && !self.out_of_fuel.get() {
534 println!("optimization-fuel-exhausted: {}", msg());
535 self.out_of_fuel.set(true);
537 self.optimization_fuel_limit.set(fuel-1);
542 match self.print_fuel_crate {
543 Some(ref c) if c == crate_name=> {
544 self.print_fuel.set(self.print_fuel.get()+1);
552 pub fn build_session(sopts: config::Options,
553 dep_graph: &DepGraph,
554 local_crate_source_file: Option<PathBuf>,
555 registry: errors::registry::Registry,
556 cstore: Rc<CrateStore>)
558 build_session_with_codemap(sopts,
560 local_crate_source_file,
563 Rc::new(codemap::CodeMap::new()),
567 pub fn build_session_with_codemap(sopts: config::Options,
568 dep_graph: &DepGraph,
569 local_crate_source_file: Option<PathBuf>,
570 registry: errors::registry::Registry,
571 cstore: Rc<CrateStore>,
572 codemap: Rc<codemap::CodeMap>,
573 emitter_dest: Option<Box<Write + Send>>)
575 // FIXME: This is not general enough to make the warning lint completely override
576 // normal diagnostic warnings, since the warning lint can also be denied and changed
577 // later via the source code.
578 let can_print_warnings = sopts.lint_opts
580 .filter(|&&(ref key, _)| *key == "warnings")
581 .map(|&(_, ref level)| *level != lint::Allow)
584 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
586 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
587 (config::ErrorOutputType::HumanReadable(color_config), None) => {
588 Box::new(EmitterWriter::stderr(color_config,
589 Some(codemap.clone())))
591 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
592 Box::new(EmitterWriter::new(dst,
593 Some(codemap.clone())))
595 (config::ErrorOutputType::Json, None) => {
596 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
598 (config::ErrorOutputType::Json, Some(dst)) => {
599 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
603 let diagnostic_handler =
604 errors::Handler::with_emitter(can_print_warnings,
608 build_session_(sopts,
610 local_crate_source_file,
616 pub fn build_session_(sopts: config::Options,
617 dep_graph: &DepGraph,
618 local_crate_source_file: Option<PathBuf>,
619 span_diagnostic: errors::Handler,
620 codemap: Rc<codemap::CodeMap>,
621 cstore: Rc<CrateStore>)
623 let host = match Target::search(config::host_triple()) {
626 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
629 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
630 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
631 let default_sysroot = match sopts.maybe_sysroot {
633 None => Some(filesearch::get_or_default_sysroot())
636 // Make the path absolute, if necessary
637 let local_crate_source_file = local_crate_source_file.map(|path|
638 if path.is_absolute() {
641 env::current_dir().unwrap().join(&path)
645 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
646 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
647 .map(|i| i.1).unwrap_or(0));
648 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
649 let print_fuel = Cell::new(0);
652 dep_graph: dep_graph.clone(),
658 // For a library crate, this is always none
659 entry_fn: RefCell::new(None),
660 entry_type: Cell::new(None),
661 plugin_registrar_fn: Cell::new(None),
662 derive_registrar_fn: Cell::new(None),
663 default_sysroot: default_sysroot,
664 local_crate_source_file: local_crate_source_file,
665 working_dir: env::current_dir().unwrap(),
666 lint_store: RefCell::new(lint::LintStore::new()),
667 lints: RefCell::new(lint::LintTable::new()),
668 one_time_diagnostics: RefCell::new(FxHashSet()),
669 plugin_llvm_passes: RefCell::new(Vec::new()),
670 mir_passes: RefCell::new(mir_pass::Passes::new()),
671 plugin_attributes: RefCell::new(Vec::new()),
672 crate_types: RefCell::new(Vec::new()),
673 dependency_formats: RefCell::new(FxHashMap()),
674 crate_disambiguator: RefCell::new(Symbol::intern("")),
675 features: RefCell::new(feature_gate::Features::new()),
676 recursion_limit: Cell::new(64),
677 type_length_limit: Cell::new(1048576),
678 next_node_id: Cell::new(NodeId::new(1)),
679 injected_allocator: Cell::new(None),
680 injected_panic_runtime: Cell::new(None),
681 imported_macro_spans: RefCell::new(HashMap::new()),
682 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
683 perf_stats: PerfStats {
684 svh_time: Cell::new(Duration::from_secs(0)),
685 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
686 incr_comp_hashes_count: Cell::new(0),
687 incr_comp_bytes_hashed: Cell::new(0),
688 symbol_hash_time: Cell::new(Duration::from_secs(0)),
689 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
691 code_stats: RefCell::new(CodeStats::new()),
692 optimization_fuel_crate: optimization_fuel_crate,
693 optimization_fuel_limit: optimization_fuel_limit,
694 print_fuel_crate: print_fuel_crate,
695 print_fuel: print_fuel,
696 out_of_fuel: Cell::new(false),
704 /// Holds data on the current incremental compilation session, if there is one.
706 pub enum IncrCompSession {
707 // This is the state the session will be in until the incr. comp. dir is
710 // This is the state during which the session directory is private and can
713 session_directory: PathBuf,
714 lock_file: flock::Lock,
716 // This is the state after the session directory has been finalized. In this
717 // state, the contents of the directory must not be modified any more.
719 session_directory: PathBuf,
721 // This is an error state that is reached when some compilation error has
722 // occurred. It indicates that the contents of the session directory must
723 // not be used, since they might be invalid.
724 InvalidBecauseOfErrors {
725 session_directory: PathBuf,
729 fn init_llvm(sess: &Session) {
731 // Before we touch LLVM, make sure that multithreading is enabled.
733 static INIT: Once = Once::new();
734 static mut POISONED: bool = false;
736 if llvm::LLVMStartMultithreaded() != 1 {
737 // use an extra bool to make sure that all future usage of LLVM
738 // cannot proceed despite the Once not running more than once.
742 configure_llvm(sess);
746 bug!("couldn't enable multi-threaded LLVM");
751 unsafe fn configure_llvm(sess: &Session) {
752 let mut llvm_c_strs = Vec::new();
753 let mut llvm_args = Vec::new();
756 let mut add = |arg: &str| {
757 let s = CString::new(arg).unwrap();
758 llvm_args.push(s.as_ptr());
761 add("rustc"); // fake program name
762 if sess.time_llvm_passes() { add("-time-passes"); }
763 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
765 for arg in &sess.opts.cg.llvm_args {
770 llvm::LLVMInitializePasses();
772 llvm::initialize_available_targets();
774 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
778 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
779 let emitter: Box<Emitter> = match output {
780 config::ErrorOutputType::HumanReadable(color_config) => {
781 Box::new(EmitterWriter::stderr(color_config,
784 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
786 let handler = errors::Handler::with_emitter(true, false, emitter);
787 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
788 panic!(errors::FatalError);
791 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
792 let emitter: Box<Emitter> = match output {
793 config::ErrorOutputType::HumanReadable(color_config) => {
794 Box::new(EmitterWriter::stderr(color_config,
797 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
799 let handler = errors::Handler::with_emitter(true, false, emitter);
800 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
803 // Err(0) means compilation was stopped, but no errors were found.
804 // This would be better as a dedicated enum, but using try! is so convenient.
805 pub type CompileResult = Result<(), usize>;
807 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
817 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
818 // this wrapper mostly exists so I don't have to write a fully
819 // qualified path of None::<Span> inside the bug!() macro defintion
820 opt_span_bug_fmt(file, line, None::<Span>, args);
825 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
828 args: fmt::Arguments) -> ! {
829 opt_span_bug_fmt(file, line, Some(span), args);
832 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
835 args: fmt::Arguments) -> ! {
836 tls::with_opt(move |tcx| {
837 let msg = format!("{}:{}: {}", file, line, args);
839 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
840 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
841 (None, _) => panic!(msg)