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;
26 use syntax::ast::NodeId;
27 use errors::{self, DiagnosticBuilder};
28 use errors::emitter::{Emitter, EmitterWriter};
29 use syntax::json::JsonEmitter;
30 use syntax::feature_gate;
32 use syntax::parse::ParseSess;
33 use syntax::symbol::Symbol;
34 use syntax::{ast, codemap};
35 use syntax::feature_gate::AttributeType;
36 use syntax_pos::{Span, MultiSpan};
38 use rustc_back::{LinkerFlavor, PanicStrategy};
39 use rustc_back::target::Target;
40 use rustc_data_structures::flock;
42 use std::path::{Path, PathBuf};
43 use std::cell::{self, Cell, RefCell};
44 use std::collections::HashMap;
49 use std::time::Duration;
56 // Represents the data associated with a compilation
57 // session for a single crate.
59 pub dep_graph: DepGraph,
60 pub target: config::Config,
62 pub opts: config::Options,
63 pub cstore: Rc<CrateStore>,
64 pub parse_sess: ParseSess,
65 // For a library crate, this is always none
66 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
67 pub entry_type: Cell<Option<config::EntryFnType>>,
68 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
69 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
70 pub default_sysroot: Option<PathBuf>,
71 // The name of the root source file of the crate, in the local file system.
72 // The path is always expected to be absolute. `None` means that there is no
74 pub local_crate_source_file: Option<String>,
75 // The directory the compiler has been executed in plus a flag indicating
76 // if the value stored here has been affected by path remapping.
77 pub working_dir: (String, bool),
78 pub lint_store: RefCell<lint::LintStore>,
79 pub lints: RefCell<lint::LintTable>,
80 /// Set of (LintId, span, message) tuples tracking lint (sub)diagnostics
81 /// that have been set once, but should not be set again, in order to avoid
82 /// redundantly verbose output (Issue #24690).
83 pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Span, String)>>,
84 pub plugin_llvm_passes: RefCell<Vec<String>>,
85 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
86 pub crate_types: RefCell<Vec<config::CrateType>>,
87 pub dependency_formats: RefCell<dependency_format::Dependencies>,
88 // The crate_disambiguator is constructed out of all the `-C metadata`
89 // arguments passed to the compiler. Its value together with the crate-name
90 // forms a unique global identifier for the crate. It is used to allow
91 // multiple crates with the same name to coexist. See the
92 // trans::back::symbol_names module for more information.
93 pub crate_disambiguator: RefCell<Symbol>,
94 pub features: RefCell<feature_gate::Features>,
96 /// The maximum recursion limit for potentially infinitely recursive
97 /// operations such as auto-dereference and monomorphization.
98 pub recursion_limit: Cell<usize>,
100 /// The maximum length of types during monomorphization.
101 pub type_length_limit: Cell<usize>,
103 /// The metadata::creader module may inject an allocator/panic_runtime
104 /// dependency if it didn't already find one, and this tracks what was
106 pub injected_allocator: Cell<Option<CrateNum>>,
107 pub injected_panic_runtime: Cell<Option<CrateNum>>,
109 /// Map from imported macro spans (which consist of
110 /// the localized span for the macro body) to the
111 /// macro name and defintion span in the source crate.
112 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
114 incr_comp_session: RefCell<IncrCompSession>,
116 /// Some measurements that are being gathered during compilation.
117 pub perf_stats: PerfStats,
119 /// Data about code being compiled, gathered during compilation.
120 pub code_stats: RefCell<CodeStats>,
122 next_node_id: Cell<ast::NodeId>,
124 /// If -zfuel=crate=n is specified, Some(crate).
125 optimization_fuel_crate: Option<String>,
126 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
127 optimization_fuel_limit: Cell<u64>,
128 /// We're rejecting all further optimizations.
129 out_of_fuel: Cell<bool>,
131 // The next two are public because the driver needs to read them.
133 /// If -zprint-fuel=crate, Some(crate).
134 pub print_fuel_crate: Option<String>,
135 /// Always set to zero and incremented so that we can print fuel expended by a crate.
136 pub print_fuel: Cell<u64>,
139 pub struct PerfStats {
140 // The accumulated time needed for computing the SVH of the crate
141 pub svh_time: Cell<Duration>,
142 // The accumulated time spent on computing incr. comp. hashes
143 pub incr_comp_hashes_time: Cell<Duration>,
144 // The number of incr. comp. hash computations performed
145 pub incr_comp_hashes_count: Cell<u64>,
146 // The number of bytes hashed when computing ICH values
147 pub incr_comp_bytes_hashed: Cell<u64>,
148 // The accumulated time spent on computing symbol hashes
149 pub symbol_hash_time: Cell<Duration>,
150 // The accumulated time spent decoding def path tables from metadata
151 pub decode_def_path_tables_time: Cell<Duration>,
155 pub fn local_crate_disambiguator(&self) -> Symbol {
156 *self.crate_disambiguator.borrow()
158 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
161 -> DiagnosticBuilder<'a> {
162 self.diagnostic().struct_span_warn(sp, msg)
164 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
168 -> DiagnosticBuilder<'a> {
169 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
171 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
172 self.diagnostic().struct_warn(msg)
174 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
177 -> DiagnosticBuilder<'a> {
178 self.diagnostic().struct_span_err(sp, msg)
180 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
184 -> DiagnosticBuilder<'a> {
185 self.diagnostic().struct_span_err_with_code(sp, msg, code)
187 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
188 self.diagnostic().struct_err(msg)
190 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
193 -> DiagnosticBuilder<'a> {
194 self.diagnostic().struct_span_fatal(sp, msg)
196 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
200 -> DiagnosticBuilder<'a> {
201 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
203 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
204 self.diagnostic().struct_fatal(msg)
207 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
208 panic!(self.diagnostic().span_fatal(sp, msg))
210 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
211 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
213 pub fn fatal(&self, msg: &str) -> ! {
214 panic!(self.diagnostic().fatal(msg))
216 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
218 self.span_warn(sp, msg);
220 self.span_err(sp, msg);
223 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
224 self.diagnostic().span_err(sp, msg)
226 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
227 self.diagnostic().span_err_with_code(sp, &msg, code)
229 pub fn err(&self, msg: &str) {
230 self.diagnostic().err(msg)
232 pub fn err_count(&self) -> usize {
233 self.diagnostic().err_count()
235 pub fn has_errors(&self) -> bool {
236 self.diagnostic().has_errors()
238 pub fn abort_if_errors(&self) {
239 self.diagnostic().abort_if_errors();
241 pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
242 where F: FnOnce() -> T
244 let old_count = self.err_count();
246 let errors = self.err_count() - old_count;
253 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
254 self.diagnostic().span_warn(sp, msg)
256 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
257 self.diagnostic().span_warn_with_code(sp, msg, code)
259 pub fn warn(&self, msg: &str) {
260 self.diagnostic().warn(msg)
262 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
264 Some(sp) => self.span_warn(sp, msg),
265 None => self.warn(msg),
268 /// Delay a span_bug() call until abort_if_errors()
269 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
270 self.diagnostic().delay_span_bug(sp, msg)
272 pub fn note_without_error(&self, msg: &str) {
273 self.diagnostic().note_without_error(msg)
275 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
276 self.diagnostic().span_note_without_error(sp, msg)
278 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
279 self.diagnostic().span_unimpl(sp, msg)
281 pub fn unimpl(&self, msg: &str) -> ! {
282 self.diagnostic().unimpl(msg)
285 pub fn add_lint<S: Into<MultiSpan>>(&self,
286 lint: &'static lint::Lint,
291 self.lints.borrow_mut().add_lint(lint, id, sp, msg);
294 pub fn add_lint_diagnostic<M>(&self,
295 lint: &'static lint::Lint,
298 where M: lint::IntoEarlyLint,
300 self.lints.borrow_mut().add_lint_diagnostic(lint, id, msg);
303 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
304 let id = self.next_node_id.get();
306 match id.as_usize().checked_add(count) {
308 self.next_node_id.set(ast::NodeId::new(next));
310 None => bug!("Input too large, ran out of node ids!")
315 pub fn next_node_id(&self) -> NodeId {
316 self.reserve_node_ids(1)
318 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
319 &self.parse_sess.span_diagnostic
322 /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but
323 /// deduplicates on lint ID, span, and message for this `Session` if we're
324 /// not outputting in JSON mode.
326 // FIXME: if the need arises for one-time diagnostics other than
327 // `span_note`, we almost certainly want to generalize this
328 // "check/insert-into the one-time diagnostics map, then set message if
329 // it's not already there" code to accomodate all of them
330 pub fn diag_span_note_once<'a, 'b>(&'a self,
331 diag_builder: &'b mut DiagnosticBuilder<'a>,
332 lint: &'static lint::Lint, span: Span, message: &str) {
333 match self.opts.error_format {
334 // when outputting JSON for tool consumption, the tool might want
336 config::ErrorOutputType::Json => {
337 diag_builder.span_note(span, &message);
340 let lint_id = lint::LintId::of(lint);
341 let id_span_message = (lint_id, span, message.to_owned());
342 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
344 diag_builder.span_note(span, &message);
350 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
351 self.parse_sess.codemap()
353 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
354 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
355 pub fn count_llvm_insns(&self) -> bool {
356 self.opts.debugging_opts.count_llvm_insns
358 pub fn time_llvm_passes(&self) -> bool {
359 self.opts.debugging_opts.time_llvm_passes
361 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
362 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
363 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
364 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
365 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
366 pub fn print_llvm_passes(&self) -> bool {
367 self.opts.debugging_opts.print_llvm_passes
369 pub fn lto(&self) -> bool {
372 /// Returns the panic strategy for this compile session. If the user explicitly selected one
373 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
374 pub fn panic_strategy(&self) -> PanicStrategy {
375 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
377 pub fn linker_flavor(&self) -> LinkerFlavor {
378 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
380 pub fn no_landing_pads(&self) -> bool {
381 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
383 pub fn unstable_options(&self) -> bool {
384 self.opts.debugging_opts.unstable_options
386 pub fn nonzeroing_move_hints(&self) -> bool {
387 self.opts.debugging_opts.enable_nonzeroing_move_hints
389 pub fn overflow_checks(&self) -> bool {
390 self.opts.cg.overflow_checks
391 .or(self.opts.debugging_opts.force_overflow_checks)
392 .unwrap_or(self.opts.debug_assertions)
395 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
396 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
397 !self.target.target.options.eliminate_frame_pointer
400 /// Returns the symbol name for the registrar function,
401 /// given the crate Svh and the function DefIndex.
402 pub fn generate_plugin_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
404 format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
407 pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
409 format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
412 pub fn sysroot<'a>(&'a self) -> &'a Path {
413 match self.opts.maybe_sysroot {
414 Some (ref sysroot) => sysroot,
415 None => self.default_sysroot.as_ref()
416 .expect("missing sysroot and default_sysroot in Session")
419 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
420 filesearch::FileSearch::new(self.sysroot(),
421 &self.opts.target_triple,
422 &self.opts.search_paths,
425 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
426 filesearch::FileSearch::new(
428 config::host_triple(),
429 &self.opts.search_paths,
433 pub fn init_incr_comp_session(&self,
434 session_dir: PathBuf,
435 lock_file: flock::Lock) {
436 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
438 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
439 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
442 *incr_comp_session = IncrCompSession::Active {
443 session_directory: session_dir,
444 lock_file: lock_file,
448 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
449 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
451 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
452 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
455 // Note: This will also drop the lock file, thus unlocking the directory
456 *incr_comp_session = IncrCompSession::Finalized {
457 session_directory: new_directory_path,
461 pub fn mark_incr_comp_session_as_invalid(&self) {
462 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
464 let session_directory = match *incr_comp_session {
465 IncrCompSession::Active { ref session_directory, .. } => {
466 session_directory.clone()
468 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
472 // Note: This will also drop the lock file, thus unlocking the directory
473 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
474 session_directory: session_directory
478 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
479 let incr_comp_session = self.incr_comp_session.borrow();
480 cell::Ref::map(incr_comp_session, |incr_comp_session| {
481 match *incr_comp_session {
482 IncrCompSession::NotInitialized => {
483 bug!("Trying to get session directory from IncrCompSession `{:?}`",
486 IncrCompSession::Active { ref session_directory, .. } |
487 IncrCompSession::Finalized { ref session_directory } |
488 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
495 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
496 if self.opts.incremental.is_some() {
497 Some(self.incr_comp_session_dir())
503 pub fn print_perf_stats(&self) {
504 println!("Total time spent computing SVHs: {}",
505 duration_to_secs_str(self.perf_stats.svh_time.get()));
506 println!("Total time spent computing incr. comp. hashes: {}",
507 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
508 println!("Total number of incr. comp. hashes computed: {}",
509 self.perf_stats.incr_comp_hashes_count.get());
510 println!("Total number of bytes hashed for incr. comp.: {}",
511 self.perf_stats.incr_comp_bytes_hashed.get());
512 println!("Average bytes hashed per incr. comp. HIR node: {}",
513 self.perf_stats.incr_comp_bytes_hashed.get() /
514 self.perf_stats.incr_comp_hashes_count.get());
515 println!("Total time spent computing symbol hashes: {}",
516 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
517 println!("Total time spent decoding DefPath tables: {}",
518 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
521 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
522 /// This expends fuel if applicable, and records fuel if applicable.
523 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
525 match self.optimization_fuel_crate {
526 Some(ref c) if c == crate_name => {
527 let fuel = self.optimization_fuel_limit.get();
529 if fuel == 0 && !self.out_of_fuel.get() {
530 println!("optimization-fuel-exhausted: {}", msg());
531 self.out_of_fuel.set(true);
533 self.optimization_fuel_limit.set(fuel-1);
538 match self.print_fuel_crate {
539 Some(ref c) if c == crate_name=> {
540 self.print_fuel.set(self.print_fuel.get()+1);
548 pub fn build_session(sopts: config::Options,
549 dep_graph: &DepGraph,
550 local_crate_source_file: Option<PathBuf>,
551 registry: errors::registry::Registry,
552 cstore: Rc<CrateStore>)
554 let file_path_mapping = sopts.file_path_mapping();
556 build_session_with_codemap(sopts,
558 local_crate_source_file,
561 Rc::new(codemap::CodeMap::new(file_path_mapping)),
565 pub fn build_session_with_codemap(sopts: config::Options,
566 dep_graph: &DepGraph,
567 local_crate_source_file: Option<PathBuf>,
568 registry: errors::registry::Registry,
569 cstore: Rc<CrateStore>,
570 codemap: Rc<codemap::CodeMap>,
571 emitter_dest: Option<Box<Write + Send>>)
573 // FIXME: This is not general enough to make the warning lint completely override
574 // normal diagnostic warnings, since the warning lint can also be denied and changed
575 // later via the source code.
576 let can_print_warnings = sopts.lint_opts
578 .filter(|&&(ref key, _)| *key == "warnings")
579 .map(|&(_, ref level)| *level != lint::Allow)
582 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
584 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
585 (config::ErrorOutputType::HumanReadable(color_config), None) => {
586 Box::new(EmitterWriter::stderr(color_config,
587 Some(codemap.clone())))
589 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
590 Box::new(EmitterWriter::new(dst,
591 Some(codemap.clone())))
593 (config::ErrorOutputType::Json, None) => {
594 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
596 (config::ErrorOutputType::Json, Some(dst)) => {
597 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
601 let diagnostic_handler =
602 errors::Handler::with_emitter(can_print_warnings,
606 build_session_(sopts,
608 local_crate_source_file,
614 pub fn build_session_(sopts: config::Options,
615 dep_graph: &DepGraph,
616 local_crate_source_file: Option<PathBuf>,
617 span_diagnostic: errors::Handler,
618 codemap: Rc<codemap::CodeMap>,
619 cstore: Rc<CrateStore>)
621 let host = match Target::search(config::host_triple()) {
624 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
627 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
629 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
630 let default_sysroot = match sopts.maybe_sysroot {
632 None => Some(filesearch::get_or_default_sysroot())
635 let file_path_mapping = sopts.file_path_mapping();
637 // Make the path absolute, if necessary
638 let local_crate_source_file = local_crate_source_file.map(|path| {
639 file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
642 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
643 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
644 .map(|i| i.1).unwrap_or(0));
645 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
646 let print_fuel = Cell::new(0);
648 let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
649 let working_dir = file_path_mapping.map_prefix(working_dir);
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: working_dir,
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 plugin_attributes: RefCell::new(Vec::new()),
671 crate_types: RefCell::new(Vec::new()),
672 dependency_formats: RefCell::new(FxHashMap()),
673 crate_disambiguator: RefCell::new(Symbol::intern("")),
674 features: RefCell::new(feature_gate::Features::new()),
675 recursion_limit: Cell::new(64),
676 type_length_limit: Cell::new(1048576),
677 next_node_id: Cell::new(NodeId::new(1)),
678 injected_allocator: Cell::new(None),
679 injected_panic_runtime: Cell::new(None),
680 imported_macro_spans: RefCell::new(HashMap::new()),
681 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
682 perf_stats: PerfStats {
683 svh_time: Cell::new(Duration::from_secs(0)),
684 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
685 incr_comp_hashes_count: Cell::new(0),
686 incr_comp_bytes_hashed: Cell::new(0),
687 symbol_hash_time: Cell::new(Duration::from_secs(0)),
688 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
690 code_stats: RefCell::new(CodeStats::new()),
691 optimization_fuel_crate: optimization_fuel_crate,
692 optimization_fuel_limit: optimization_fuel_limit,
693 print_fuel_crate: print_fuel_crate,
694 print_fuel: print_fuel,
695 out_of_fuel: Cell::new(false),
701 /// Holds data on the current incremental compilation session, if there is one.
703 pub enum IncrCompSession {
704 // This is the state the session will be in until the incr. comp. dir is
707 // This is the state during which the session directory is private and can
710 session_directory: PathBuf,
711 lock_file: flock::Lock,
713 // This is the state after the session directory has been finalized. In this
714 // state, the contents of the directory must not be modified any more.
716 session_directory: PathBuf,
718 // This is an error state that is reached when some compilation error has
719 // occurred. It indicates that the contents of the session directory must
720 // not be used, since they might be invalid.
721 InvalidBecauseOfErrors {
722 session_directory: PathBuf,
726 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
727 let emitter: Box<Emitter> = match output {
728 config::ErrorOutputType::HumanReadable(color_config) => {
729 Box::new(EmitterWriter::stderr(color_config,
732 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
734 let handler = errors::Handler::with_emitter(true, false, emitter);
735 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
736 panic!(errors::FatalError);
739 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
740 let emitter: Box<Emitter> = match output {
741 config::ErrorOutputType::HumanReadable(color_config) => {
742 Box::new(EmitterWriter::stderr(color_config,
745 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
747 let handler = errors::Handler::with_emitter(true, false, emitter);
748 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
751 // Err(0) means compilation was stopped, but no errors were found.
752 // This would be better as a dedicated enum, but using try! is so convenient.
753 pub type CompileResult = Result<(), usize>;
755 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
765 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
766 // this wrapper mostly exists so I don't have to write a fully
767 // qualified path of None::<Span> inside the bug!() macro defintion
768 opt_span_bug_fmt(file, line, None::<Span>, args);
773 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
776 args: fmt::Arguments) -> ! {
777 opt_span_bug_fmt(file, line, Some(span), args);
780 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
783 args: fmt::Arguments) -> ! {
784 tls::with_opt(move |tcx| {
785 let msg = format!("{}:{}: {}", file, line, args);
787 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
788 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
789 (None, _) => panic!(msg)