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 hir::def_id::{CrateNum, DefIndex};
18 use middle::allocator::AllocatorKind;
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, ErrorReported};
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::{ast, codemap};
34 use syntax::feature_gate::AttributeType;
35 use syntax_pos::{Span, MultiSpan};
37 use rustc_back::{LinkerFlavor, PanicStrategy};
38 use rustc_back::target::Target;
39 use rustc_data_structures::flock;
40 use jobserver::Client;
42 use std::cell::{self, Cell, RefCell};
43 use std::collections::HashMap;
47 use std::path::{Path, PathBuf};
49 use std::sync::{Once, ONCE_INIT};
50 use std::time::Duration;
57 /// Represents the data associated with a compilation
58 /// session for a single crate.
60 pub target: config::Config,
62 pub opts: config::Options,
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 /// `None` means that there is no source file.
72 pub local_crate_source_file: Option<String>,
73 /// The directory the compiler has been executed in plus a flag indicating
74 /// if the value stored here has been affected by path remapping.
75 pub working_dir: (String, bool),
76 pub lint_store: RefCell<lint::LintStore>,
77 pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
78 /// Set of (LintId, Option<Span>, message) tuples tracking lint
79 /// (sub)diagnostics that have been set once, but should not be set again,
80 /// in order to avoid redundantly verbose output (Issue #24690).
81 pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Option<Span>, String)>>,
82 pub plugin_llvm_passes: RefCell<Vec<String>>,
83 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
84 pub crate_types: RefCell<Vec<config::CrateType>>,
85 pub dependency_formats: RefCell<dependency_format::Dependencies>,
86 /// The crate_disambiguator is constructed out of all the `-C metadata`
87 /// arguments passed to the compiler. Its value together with the crate-name
88 /// forms a unique global identifier for the crate. It is used to allow
89 /// multiple crates with the same name to coexist. See the
90 /// trans::back::symbol_names module for more information.
91 pub crate_disambiguator: RefCell<Option<CrateDisambiguator>>,
92 pub features: RefCell<feature_gate::Features>,
94 /// The maximum recursion limit for potentially infinitely recursive
95 /// operations such as auto-dereference and monomorphization.
96 pub recursion_limit: Cell<usize>,
98 /// The maximum length of types during monomorphization.
99 pub type_length_limit: Cell<usize>,
101 /// The metadata::creader module may inject an allocator/panic_runtime
102 /// dependency if it didn't already find one, and this tracks what was
104 pub injected_allocator: Cell<Option<CrateNum>>,
105 pub allocator_kind: Cell<Option<AllocatorKind>>,
106 pub injected_panic_runtime: Cell<Option<CrateNum>>,
108 /// Map from imported macro spans (which consist of
109 /// the localized span for the macro body) to the
110 /// macro name and definition span in the source crate.
111 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
113 incr_comp_session: RefCell<IncrCompSession>,
115 /// Some measurements that are being gathered during compilation.
116 pub perf_stats: PerfStats,
118 /// Data about code being compiled, gathered during compilation.
119 pub code_stats: RefCell<CodeStats>,
121 next_node_id: Cell<ast::NodeId>,
123 /// If -zfuel=crate=n is specified, Some(crate).
124 optimization_fuel_crate: Option<String>,
125 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
126 optimization_fuel_limit: Cell<u64>,
127 /// We're rejecting all further optimizations.
128 out_of_fuel: Cell<bool>,
130 // The next two are public because the driver needs to read them.
132 /// If -zprint-fuel=crate, Some(crate).
133 pub print_fuel_crate: Option<String>,
134 /// Always set to zero and incremented so that we can print fuel expended by a crate.
135 pub print_fuel: Cell<u64>,
137 /// Loaded up early on in the initialization of this `Session` to avoid
138 /// false positives about a job server in our environment.
139 pub jobserver_from_env: Option<Client>,
141 /// Metadata about the allocators for the current crate being compiled
142 pub has_global_allocator: Cell<bool>,
145 pub struct PerfStats {
146 /// The accumulated time needed for computing the SVH of the crate
147 pub svh_time: Cell<Duration>,
148 /// The accumulated time spent on computing incr. comp. hashes
149 pub incr_comp_hashes_time: Cell<Duration>,
150 /// The number of incr. comp. hash computations performed
151 pub incr_comp_hashes_count: Cell<u64>,
152 /// The number of bytes hashed when computing ICH values
153 pub incr_comp_bytes_hashed: Cell<u64>,
154 /// The accumulated time spent on computing symbol hashes
155 pub symbol_hash_time: Cell<Duration>,
156 /// The accumulated time spent decoding def path tables from metadata
157 pub decode_def_path_tables_time: Cell<Duration>,
160 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
161 enum DiagnosticBuilderMethod {
164 // add more variants as needed to support one-time diagnostics
168 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
169 match *self.crate_disambiguator.borrow() {
170 Some(value) => value,
171 None => bug!("accessing disambiguator before initialization"),
174 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
177 -> DiagnosticBuilder<'a> {
178 self.diagnostic().struct_span_warn(sp, msg)
180 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
184 -> DiagnosticBuilder<'a> {
185 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
187 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
188 self.diagnostic().struct_warn(msg)
190 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
193 -> DiagnosticBuilder<'a> {
194 self.diagnostic().struct_span_err(sp, msg)
196 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
200 -> DiagnosticBuilder<'a> {
201 self.diagnostic().struct_span_err_with_code(sp, msg, code)
203 // FIXME: This method should be removed (every error should have an associated error code).
204 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
205 self.diagnostic().struct_err(msg)
207 pub fn struct_err_with_code<'a>(&'a self, msg: &str, code: &str) -> DiagnosticBuilder<'a> {
208 self.diagnostic().struct_err_with_code(msg, code)
210 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
213 -> DiagnosticBuilder<'a> {
214 self.diagnostic().struct_span_fatal(sp, msg)
216 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
220 -> DiagnosticBuilder<'a> {
221 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
223 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
224 self.diagnostic().struct_fatal(msg)
227 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
228 panic!(self.diagnostic().span_fatal(sp, msg))
230 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
231 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
233 pub fn fatal(&self, msg: &str) -> ! {
234 panic!(self.diagnostic().fatal(msg))
236 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
238 self.span_warn(sp, msg);
240 self.span_err(sp, msg);
243 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
244 self.diagnostic().span_err(sp, msg)
246 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
247 self.diagnostic().span_err_with_code(sp, &msg, code)
249 pub fn err(&self, msg: &str) {
250 self.diagnostic().err(msg)
252 pub fn err_count(&self) -> usize {
253 self.diagnostic().err_count()
255 pub fn has_errors(&self) -> bool {
256 self.diagnostic().has_errors()
258 pub fn abort_if_errors(&self) {
259 self.diagnostic().abort_if_errors();
261 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
262 compile_result_from_err_count(self.err_count())
264 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
265 where F: FnOnce() -> T
267 let old_count = self.err_count();
269 let errors = self.err_count() - old_count;
276 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
277 self.diagnostic().span_warn(sp, msg)
279 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
280 self.diagnostic().span_warn_with_code(sp, msg, code)
282 pub fn warn(&self, msg: &str) {
283 self.diagnostic().warn(msg)
285 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
287 Some(sp) => self.span_warn(sp, msg),
288 None => self.warn(msg),
291 /// Delay a span_bug() call until abort_if_errors()
292 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
293 self.diagnostic().delay_span_bug(sp, msg)
295 pub fn note_without_error(&self, msg: &str) {
296 self.diagnostic().note_without_error(msg)
298 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
299 self.diagnostic().span_note_without_error(sp, msg)
301 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
302 self.diagnostic().span_unimpl(sp, msg)
304 pub fn unimpl(&self, msg: &str) -> ! {
305 self.diagnostic().unimpl(msg)
308 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
309 lint: &'static lint::Lint,
313 match *self.buffered_lints.borrow_mut() {
314 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg),
315 None => bug!("can't buffer lints after HIR lowering"),
319 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
320 let id = self.next_node_id.get();
322 match id.as_usize().checked_add(count) {
324 self.next_node_id.set(ast::NodeId::new(next));
326 None => bug!("Input too large, ran out of node ids!")
331 pub fn next_node_id(&self) -> NodeId {
332 self.reserve_node_ids(1)
334 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
335 &self.parse_sess.span_diagnostic
338 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
339 /// deduplicates on lint ID, span (if any), and message for this `Session`
340 /// if we're not outputting in JSON mode.
341 fn diag_once<'a, 'b>(&'a self,
342 diag_builder: &'b mut DiagnosticBuilder<'a>,
343 method: DiagnosticBuilderMethod,
344 lint: &'static lint::Lint, message: &str, span: Option<Span>) {
345 let mut do_method = || {
347 DiagnosticBuilderMethod::Note => {
348 diag_builder.note(message);
350 DiagnosticBuilderMethod::SpanNote => {
351 diag_builder.span_note(span.expect("span_note expects a span"), message);
356 match self.opts.error_format {
357 // when outputting JSON for tool consumption, the tool might want
359 config::ErrorOutputType::Json => {
363 let lint_id = lint::LintId::of(lint);
364 let id_span_message = (lint_id, span, message.to_owned());
365 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
373 pub fn diag_span_note_once<'a, 'b>(&'a self,
374 diag_builder: &'b mut DiagnosticBuilder<'a>,
375 lint: &'static lint::Lint, span: Span, message: &str) {
376 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote, lint, message, Some(span));
379 pub fn diag_note_once<'a, 'b>(&'a self,
380 diag_builder: &'b mut DiagnosticBuilder<'a>,
381 lint: &'static lint::Lint, message: &str) {
382 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, lint, message, None);
385 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
386 self.parse_sess.codemap()
388 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
389 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
390 pub fn profile_queries(&self) -> bool {
391 self.opts.debugging_opts.profile_queries ||
392 self.opts.debugging_opts.profile_queries_and_keys
394 pub fn profile_queries_and_keys(&self) -> bool {
395 self.opts.debugging_opts.profile_queries_and_keys
397 pub fn count_llvm_insns(&self) -> bool {
398 self.opts.debugging_opts.count_llvm_insns
400 pub fn time_llvm_passes(&self) -> bool {
401 self.opts.debugging_opts.time_llvm_passes
403 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
404 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
405 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
406 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
407 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
408 pub fn print_llvm_passes(&self) -> bool {
409 self.opts.debugging_opts.print_llvm_passes
411 pub fn emit_end_regions(&self) -> bool {
412 self.opts.debugging_opts.emit_end_regions ||
413 (self.opts.debugging_opts.mir_emit_validate > 0) ||
414 self.opts.debugging_opts.borrowck_mir
416 pub fn lto(&self) -> bool {
419 /// Returns the panic strategy for this compile session. If the user explicitly selected one
420 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
421 pub fn panic_strategy(&self) -> PanicStrategy {
422 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
424 pub fn linker_flavor(&self) -> LinkerFlavor {
425 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
427 pub fn no_landing_pads(&self) -> bool {
428 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
430 pub fn unstable_options(&self) -> bool {
431 self.opts.debugging_opts.unstable_options
433 pub fn nonzeroing_move_hints(&self) -> bool {
434 self.opts.debugging_opts.enable_nonzeroing_move_hints
436 pub fn overflow_checks(&self) -> bool {
437 self.opts.cg.overflow_checks
438 .or(self.opts.debugging_opts.force_overflow_checks)
439 .unwrap_or(self.opts.debug_assertions)
442 pub fn crt_static(&self) -> bool {
443 // If the target does not opt in to crt-static support, use its default.
444 if self.target.target.options.crt_static_respected {
445 self.crt_static_feature()
447 self.target.target.options.crt_static_default
451 pub fn crt_static_feature(&self) -> bool {
452 let requested_features = self.opts.cg.target_feature.split(',');
453 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
454 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
456 // If the target we're compiling for requests a static crt by default,
457 // then see if the `-crt-static` feature was passed to disable that.
458 // Otherwise if we don't have a static crt by default then see if the
459 // `+crt-static` feature was passed.
460 if self.target.target.options.crt_static_default {
467 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
468 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
469 !self.target.target.options.eliminate_frame_pointer
472 /// Returns the symbol name for the registrar function,
473 /// given the crate Svh and the function DefIndex.
474 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator,
477 format!("__rustc_plugin_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
481 pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator,
484 format!("__rustc_derive_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
488 pub fn sysroot<'a>(&'a self) -> &'a Path {
489 match self.opts.maybe_sysroot {
490 Some (ref sysroot) => sysroot,
491 None => self.default_sysroot.as_ref()
492 .expect("missing sysroot and default_sysroot in Session")
495 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
496 filesearch::FileSearch::new(self.sysroot(),
497 &self.opts.target_triple,
498 &self.opts.search_paths,
501 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
502 filesearch::FileSearch::new(
504 config::host_triple(),
505 &self.opts.search_paths,
509 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
510 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
512 match *incr_comp_session {
513 IncrCompSession::Active { ref mut load_dep_graph, .. } => {
514 *load_dep_graph = load;
520 pub fn incr_session_load_dep_graph(&self) -> bool {
521 let incr_comp_session = self.incr_comp_session.borrow();
522 match *incr_comp_session {
523 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
528 pub fn init_incr_comp_session(&self,
529 session_dir: PathBuf,
530 lock_file: flock::Lock,
531 load_dep_graph: bool) {
532 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
534 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
535 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
538 *incr_comp_session = IncrCompSession::Active {
539 session_directory: session_dir,
545 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
546 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
548 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
549 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
552 // Note: This will also drop the lock file, thus unlocking the directory
553 *incr_comp_session = IncrCompSession::Finalized {
554 session_directory: new_directory_path,
558 pub fn mark_incr_comp_session_as_invalid(&self) {
559 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
561 let session_directory = match *incr_comp_session {
562 IncrCompSession::Active { ref session_directory, .. } => {
563 session_directory.clone()
565 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
569 // Note: This will also drop the lock file, thus unlocking the directory
570 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
575 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
576 let incr_comp_session = self.incr_comp_session.borrow();
577 cell::Ref::map(incr_comp_session, |incr_comp_session| {
578 match *incr_comp_session {
579 IncrCompSession::NotInitialized => {
580 bug!("Trying to get session directory from IncrCompSession `{:?}`",
583 IncrCompSession::Active { ref session_directory, .. } |
584 IncrCompSession::Finalized { ref session_directory } |
585 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
592 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
593 if self.opts.incremental.is_some() {
594 Some(self.incr_comp_session_dir())
600 pub fn print_perf_stats(&self) {
601 println!("Total time spent computing SVHs: {}",
602 duration_to_secs_str(self.perf_stats.svh_time.get()));
603 println!("Total time spent computing incr. comp. hashes: {}",
604 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
605 println!("Total number of incr. comp. hashes computed: {}",
606 self.perf_stats.incr_comp_hashes_count.get());
607 println!("Total number of bytes hashed for incr. comp.: {}",
608 self.perf_stats.incr_comp_bytes_hashed.get());
609 println!("Average bytes hashed per incr. comp. HIR node: {}",
610 self.perf_stats.incr_comp_bytes_hashed.get() /
611 self.perf_stats.incr_comp_hashes_count.get());
612 println!("Total time spent computing symbol hashes: {}",
613 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
614 println!("Total time spent decoding DefPath tables: {}",
615 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
618 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
619 /// This expends fuel if applicable, and records fuel if applicable.
620 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
622 match self.optimization_fuel_crate {
623 Some(ref c) if c == crate_name => {
624 let fuel = self.optimization_fuel_limit.get();
626 if fuel == 0 && !self.out_of_fuel.get() {
627 println!("optimization-fuel-exhausted: {}", msg());
628 self.out_of_fuel.set(true);
630 self.optimization_fuel_limit.set(fuel-1);
635 match self.print_fuel_crate {
636 Some(ref c) if c == crate_name=> {
637 self.print_fuel.set(self.print_fuel.get()+1);
644 /// Returns the number of codegen units that should be used for this
646 pub fn codegen_units(&self) -> usize {
647 if let Some(n) = self.opts.cli_forced_codegen_units {
650 if let Some(n) = self.target.target.options.default_codegen_units {
654 match self.opts.optimize {
655 // If we're compiling at `-O0` then default to 16 codegen units.
656 // The number here shouldn't matter too too much as debug mode
657 // builds don't rely on performance at all, meaning that lost
658 // opportunities for inlining through multiple codegen units is
661 // Note that the high number here doesn't mean that we'll be
662 // spawning a large number of threads in parallel. The backend
663 // of rustc contains global rate limiting through the
664 // `jobserver` crate so we'll never overload the system with too
665 // much work, but rather we'll only be optimizing when we're
666 // otherwise cooperating with other instances of rustc.
668 // Rather the high number here means that we should be able to
669 // keep a lot of idle cpus busy. By ensuring that no codegen
670 // unit takes *too* long to build we'll be guaranteed that all
671 // cpus will finish pretty closely to one another and we should
672 // make relatively optimal use of system resources
673 config::OptLevel::No => 16,
675 // All other optimization levels default use one codegen unit,
676 // the historical default in Rust for a Long Time.
682 pub fn build_session(sopts: config::Options,
683 local_crate_source_file: Option<PathBuf>,
684 registry: errors::registry::Registry)
686 let file_path_mapping = sopts.file_path_mapping();
688 build_session_with_codemap(sopts,
689 local_crate_source_file,
691 Rc::new(codemap::CodeMap::new(file_path_mapping)),
695 pub fn build_session_with_codemap(sopts: config::Options,
696 local_crate_source_file: Option<PathBuf>,
697 registry: errors::registry::Registry,
698 codemap: Rc<codemap::CodeMap>,
699 emitter_dest: Option<Box<Write + Send>>)
701 // FIXME: This is not general enough to make the warning lint completely override
702 // normal diagnostic warnings, since the warning lint can also be denied and changed
703 // later via the source code.
704 let warnings_allow = sopts.lint_opts
706 .filter(|&&(ref key, _)| *key == "warnings")
707 .map(|&(_, ref level)| *level == lint::Allow)
710 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
712 let can_print_warnings = !(warnings_allow || cap_lints_allow);
714 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
716 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
717 (config::ErrorOutputType::HumanReadable(color_config), None) => {
718 Box::new(EmitterWriter::stderr(color_config,
719 Some(codemap.clone())))
721 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
722 Box::new(EmitterWriter::new(dst,
723 Some(codemap.clone())))
725 (config::ErrorOutputType::Json, None) => {
726 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
728 (config::ErrorOutputType::Json, Some(dst)) => {
729 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
733 let diagnostic_handler =
734 errors::Handler::with_emitter(can_print_warnings,
738 build_session_(sopts,
739 local_crate_source_file,
744 pub fn build_session_(sopts: config::Options,
745 local_crate_source_file: Option<PathBuf>,
746 span_diagnostic: errors::Handler,
747 codemap: Rc<codemap::CodeMap>)
749 let host = match Target::search(config::host_triple()) {
752 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
755 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
757 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
758 let default_sysroot = match sopts.maybe_sysroot {
760 None => Some(filesearch::get_or_default_sysroot())
763 let file_path_mapping = sopts.file_path_mapping();
765 let local_crate_source_file = local_crate_source_file.map(|path| {
766 file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
769 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
770 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
771 .map(|i| i.1).unwrap_or(0));
772 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
773 let print_fuel = Cell::new(0);
775 let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
776 let working_dir = file_path_mapping.map_prefix(working_dir);
783 // For a library crate, this is always none
784 entry_fn: RefCell::new(None),
785 entry_type: Cell::new(None),
786 plugin_registrar_fn: Cell::new(None),
787 derive_registrar_fn: Cell::new(None),
789 local_crate_source_file,
791 lint_store: RefCell::new(lint::LintStore::new()),
792 buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
793 one_time_diagnostics: RefCell::new(FxHashSet()),
794 plugin_llvm_passes: RefCell::new(Vec::new()),
795 plugin_attributes: RefCell::new(Vec::new()),
796 crate_types: RefCell::new(Vec::new()),
797 dependency_formats: RefCell::new(FxHashMap()),
798 crate_disambiguator: RefCell::new(None),
799 features: RefCell::new(feature_gate::Features::new()),
800 recursion_limit: Cell::new(64),
801 type_length_limit: Cell::new(1048576),
802 next_node_id: Cell::new(NodeId::new(1)),
803 injected_allocator: Cell::new(None),
804 allocator_kind: Cell::new(None),
805 injected_panic_runtime: Cell::new(None),
806 imported_macro_spans: RefCell::new(HashMap::new()),
807 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
808 perf_stats: PerfStats {
809 svh_time: Cell::new(Duration::from_secs(0)),
810 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
811 incr_comp_hashes_count: Cell::new(0),
812 incr_comp_bytes_hashed: Cell::new(0),
813 symbol_hash_time: Cell::new(Duration::from_secs(0)),
814 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
816 code_stats: RefCell::new(CodeStats::new()),
817 optimization_fuel_crate,
818 optimization_fuel_limit,
821 out_of_fuel: Cell::new(false),
822 // Note that this is unsafe because it may misinterpret file descriptors
823 // on Unix as jobserver file descriptors. We hopefully execute this near
824 // the beginning of the process though to ensure we don't get false
825 // positives, or in other words we try to execute this before we open
826 // any file descriptors ourselves.
828 // Also note that we stick this in a global because there could be
829 // multiple `Session` instances in this process, and the jobserver is
831 jobserver_from_env: unsafe {
832 static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
833 static INIT: Once = ONCE_INIT;
835 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
837 (*GLOBAL_JOBSERVER).clone()
839 has_global_allocator: Cell::new(false),
845 /// Hash value constructed out of all the `-C metadata` arguments passed to the
846 /// compiler. Together with the crate-name forms a unique global identifier for
848 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
849 pub struct CrateDisambiguator(Fingerprint);
851 impl CrateDisambiguator {
852 pub fn to_fingerprint(self) -> Fingerprint {
857 impl From<Fingerprint> for CrateDisambiguator {
858 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
859 CrateDisambiguator(fingerprint)
863 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
865 /// Holds data on the current incremental compilation session, if there is one.
867 pub enum IncrCompSession {
868 /// This is the state the session will be in until the incr. comp. dir is
871 /// This is the state during which the session directory is private and can
874 session_directory: PathBuf,
875 lock_file: flock::Lock,
876 load_dep_graph: bool,
878 /// This is the state after the session directory has been finalized. In this
879 /// state, the contents of the directory must not be modified any more.
881 session_directory: PathBuf,
883 /// This is an error state that is reached when some compilation error has
884 /// occurred. It indicates that the contents of the session directory must
885 /// not be used, since they might be invalid.
886 InvalidBecauseOfErrors {
887 session_directory: PathBuf,
891 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
892 let emitter: Box<Emitter> = match output {
893 config::ErrorOutputType::HumanReadable(color_config) => {
894 Box::new(EmitterWriter::stderr(color_config,
897 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
899 let handler = errors::Handler::with_emitter(true, false, emitter);
900 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
901 panic!(errors::FatalError);
904 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
905 let emitter: Box<Emitter> = match output {
906 config::ErrorOutputType::HumanReadable(color_config) => {
907 Box::new(EmitterWriter::stderr(color_config,
910 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
912 let handler = errors::Handler::with_emitter(true, false, emitter);
913 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
916 #[derive(Copy, Clone, Debug)]
917 pub enum CompileIncomplete {
919 Errored(ErrorReported)
921 impl From<ErrorReported> for CompileIncomplete {
922 fn from(err: ErrorReported) -> CompileIncomplete {
923 CompileIncomplete::Errored(err)
926 pub type CompileResult = Result<(), CompileIncomplete>;
928 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
932 Err(CompileIncomplete::Errored(ErrorReported))
938 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
939 // this wrapper mostly exists so I don't have to write a fully
940 // qualified path of None::<Span> inside the bug!() macro definition
941 opt_span_bug_fmt(file, line, None::<Span>, args);
946 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
949 args: fmt::Arguments) -> ! {
950 opt_span_bug_fmt(file, line, Some(span), args);
953 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
956 args: fmt::Arguments) -> ! {
957 tls::with_opt(move |tcx| {
958 let msg = format!("{}:{}: {}", file, line, args);
960 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
961 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
962 (None, _) => panic!(msg)