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::allocator::AllocatorKind;
20 use middle::dependency_format;
21 use session::search_paths::PathKind;
22 use session::config::DebugInfoLevel;
24 use util::nodemap::{FxHashMap, FxHashSet};
25 use util::common::{duration_to_secs_str, ErrorReported};
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;
42 use jobserver::Client;
44 use std::cell::{self, Cell, RefCell};
45 use std::collections::HashMap;
49 use std::path::{Path, PathBuf};
51 use std::sync::{Once, ONCE_INIT};
52 use std::time::Duration;
59 // Represents the data associated with a compilation
60 // session for a single crate.
62 pub dep_graph: DepGraph,
63 pub target: config::Config,
65 pub opts: config::Options,
66 pub cstore: Rc<CrateStore>,
67 pub parse_sess: ParseSess,
68 // For a library crate, this is always none
69 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
70 pub entry_type: Cell<Option<config::EntryFnType>>,
71 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
72 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
73 pub default_sysroot: Option<PathBuf>,
74 // The name of the root source file of the crate, in the local file system.
75 // The path is always expected to be absolute. `None` means that there is no
77 pub local_crate_source_file: Option<String>,
78 // The directory the compiler has been executed in plus a flag indicating
79 // if the value stored here has been affected by path remapping.
80 pub working_dir: (String, bool),
81 pub lint_store: RefCell<lint::LintStore>,
82 pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
83 /// Set of (LintId, Option<Span>, message) tuples tracking lint
84 /// (sub)diagnostics that have been set once, but should not be set again,
85 /// in order to avoid redundantly verbose output (Issue #24690).
86 pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Option<Span>, String)>>,
87 pub plugin_llvm_passes: RefCell<Vec<String>>,
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 allocator_kind: Cell<Option<AllocatorKind>>,
111 pub injected_panic_runtime: Cell<Option<CrateNum>>,
113 /// Map from imported macro spans (which consist of
114 /// the localized span for the macro body) to the
115 /// macro name and definition span in the source crate.
116 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
118 incr_comp_session: RefCell<IncrCompSession>,
120 /// Some measurements that are being gathered during compilation.
121 pub perf_stats: PerfStats,
123 /// Data about code being compiled, gathered during compilation.
124 pub code_stats: RefCell<CodeStats>,
126 next_node_id: Cell<ast::NodeId>,
128 /// If -zfuel=crate=n is specified, Some(crate).
129 optimization_fuel_crate: Option<String>,
130 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
131 optimization_fuel_limit: Cell<u64>,
132 /// We're rejecting all further optimizations.
133 out_of_fuel: Cell<bool>,
135 // The next two are public because the driver needs to read them.
137 /// If -zprint-fuel=crate, Some(crate).
138 pub print_fuel_crate: Option<String>,
139 /// Always set to zero and incremented so that we can print fuel expended by a crate.
140 pub print_fuel: Cell<u64>,
142 /// Loaded up early on in the initialization of this `Session` to avoid
143 /// false positives about a job server in our environment.
144 pub jobserver_from_env: Option<Client>,
146 /// Metadata about the allocators for the current crate being compiled
147 pub has_global_allocator: Cell<bool>,
150 pub struct PerfStats {
151 // The accumulated time needed for computing the SVH of the crate
152 pub svh_time: Cell<Duration>,
153 // The accumulated time spent on computing incr. comp. hashes
154 pub incr_comp_hashes_time: Cell<Duration>,
155 // The number of incr. comp. hash computations performed
156 pub incr_comp_hashes_count: Cell<u64>,
157 // The number of bytes hashed when computing ICH values
158 pub incr_comp_bytes_hashed: Cell<u64>,
159 // The accumulated time spent on computing symbol hashes
160 pub symbol_hash_time: Cell<Duration>,
161 // The accumulated time spent decoding def path tables from metadata
162 pub decode_def_path_tables_time: Cell<Duration>,
165 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
166 enum DiagnosticBuilderMethod {
169 // add more variants as needed to support one-time diagnostics
173 pub fn local_crate_disambiguator(&self) -> Symbol {
174 *self.crate_disambiguator.borrow()
176 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
179 -> DiagnosticBuilder<'a> {
180 self.diagnostic().struct_span_warn(sp, msg)
182 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
186 -> DiagnosticBuilder<'a> {
187 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
189 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
190 self.diagnostic().struct_warn(msg)
192 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
195 -> DiagnosticBuilder<'a> {
196 self.diagnostic().struct_span_err(sp, msg)
198 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
202 -> DiagnosticBuilder<'a> {
203 self.diagnostic().struct_span_err_with_code(sp, msg, code)
205 // FIXME: This method should be removed (every error should have an associated error code).
206 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
207 self.diagnostic().struct_err(msg)
209 pub fn struct_err_with_code<'a>(&'a self, msg: &str, code: &str) -> DiagnosticBuilder<'a> {
210 self.diagnostic().struct_err_with_code(msg, code)
212 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
215 -> DiagnosticBuilder<'a> {
216 self.diagnostic().struct_span_fatal(sp, msg)
218 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
222 -> DiagnosticBuilder<'a> {
223 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
225 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
226 self.diagnostic().struct_fatal(msg)
229 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
230 panic!(self.diagnostic().span_fatal(sp, msg))
232 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
233 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
235 pub fn fatal(&self, msg: &str) -> ! {
236 panic!(self.diagnostic().fatal(msg))
238 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
240 self.span_warn(sp, msg);
242 self.span_err(sp, msg);
245 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
246 self.diagnostic().span_err(sp, msg)
248 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
249 self.diagnostic().span_err_with_code(sp, &msg, code)
251 pub fn err(&self, msg: &str) {
252 self.diagnostic().err(msg)
254 pub fn err_count(&self) -> usize {
255 self.diagnostic().err_count()
257 pub fn has_errors(&self) -> bool {
258 self.diagnostic().has_errors()
260 pub fn abort_if_errors(&self) {
261 self.diagnostic().abort_if_errors();
263 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
264 compile_result_from_err_count(self.err_count())
266 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
267 where F: FnOnce() -> T
269 let old_count = self.err_count();
271 let errors = self.err_count() - old_count;
278 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
279 self.diagnostic().span_warn(sp, msg)
281 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
282 self.diagnostic().span_warn_with_code(sp, msg, code)
284 pub fn warn(&self, msg: &str) {
285 self.diagnostic().warn(msg)
287 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
289 Some(sp) => self.span_warn(sp, msg),
290 None => self.warn(msg),
293 /// Delay a span_bug() call until abort_if_errors()
294 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
295 self.diagnostic().delay_span_bug(sp, msg)
297 pub fn note_without_error(&self, msg: &str) {
298 self.diagnostic().note_without_error(msg)
300 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
301 self.diagnostic().span_note_without_error(sp, msg)
303 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
304 self.diagnostic().span_unimpl(sp, msg)
306 pub fn unimpl(&self, msg: &str) -> ! {
307 self.diagnostic().unimpl(msg)
310 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
311 lint: &'static lint::Lint,
315 match *self.buffered_lints.borrow_mut() {
316 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg),
317 None => bug!("can't buffer lints after HIR lowering"),
321 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
322 let id = self.next_node_id.get();
324 match id.as_usize().checked_add(count) {
326 self.next_node_id.set(ast::NodeId::new(next));
328 None => bug!("Input too large, ran out of node ids!")
333 pub fn next_node_id(&self) -> NodeId {
334 self.reserve_node_ids(1)
336 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
337 &self.parse_sess.span_diagnostic
340 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
341 /// deduplicates on lint ID, span (if any), and message for this `Session`
342 /// if we're not outputting in JSON mode.
343 fn diag_once<'a, 'b>(&'a self,
344 diag_builder: &'b mut DiagnosticBuilder<'a>,
345 method: DiagnosticBuilderMethod,
346 lint: &'static lint::Lint, message: &str, span: Option<Span>) {
347 let mut do_method = || {
349 DiagnosticBuilderMethod::Note => {
350 diag_builder.note(message);
352 DiagnosticBuilderMethod::SpanNote => {
353 diag_builder.span_note(span.expect("span_note expects a span"), message);
358 match self.opts.error_format {
359 // when outputting JSON for tool consumption, the tool might want
361 config::ErrorOutputType::Json => {
365 let lint_id = lint::LintId::of(lint);
366 let id_span_message = (lint_id, span, message.to_owned());
367 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
375 pub fn diag_span_note_once<'a, 'b>(&'a self,
376 diag_builder: &'b mut DiagnosticBuilder<'a>,
377 lint: &'static lint::Lint, span: Span, message: &str) {
378 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote, lint, message, Some(span));
381 pub fn diag_note_once<'a, 'b>(&'a self,
382 diag_builder: &'b mut DiagnosticBuilder<'a>,
383 lint: &'static lint::Lint, message: &str) {
384 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, lint, message, None);
387 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
388 self.parse_sess.codemap()
390 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
391 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
392 pub fn count_llvm_insns(&self) -> bool {
393 self.opts.debugging_opts.count_llvm_insns
395 pub fn time_llvm_passes(&self) -> bool {
396 self.opts.debugging_opts.time_llvm_passes
398 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
399 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
400 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
401 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
402 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
403 pub fn print_llvm_passes(&self) -> bool {
404 self.opts.debugging_opts.print_llvm_passes
406 pub fn lto(&self) -> bool {
409 /// Returns the panic strategy for this compile session. If the user explicitly selected one
410 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
411 pub fn panic_strategy(&self) -> PanicStrategy {
412 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
414 pub fn linker_flavor(&self) -> LinkerFlavor {
415 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
417 pub fn no_landing_pads(&self) -> bool {
418 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
420 pub fn unstable_options(&self) -> bool {
421 self.opts.debugging_opts.unstable_options
423 pub fn nonzeroing_move_hints(&self) -> bool {
424 self.opts.debugging_opts.enable_nonzeroing_move_hints
426 pub fn overflow_checks(&self) -> bool {
427 self.opts.cg.overflow_checks
428 .or(self.opts.debugging_opts.force_overflow_checks)
429 .unwrap_or(self.opts.debug_assertions)
432 pub fn crt_static(&self) -> bool {
433 let requested_features = self.opts.cg.target_feature.split(',');
434 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
435 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
437 // If the target we're compiling for requests a static crt by default,
438 // then see if the `-crt-static` feature was passed to disable that.
439 // Otherwise if we don't have a static crt by default then see if the
440 // `+crt-static` feature was passed.
441 if self.target.target.options.crt_static_default {
448 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
449 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
450 !self.target.target.options.eliminate_frame_pointer
453 /// Returns the symbol name for the registrar function,
454 /// given the crate Svh and the function DefIndex.
455 pub fn generate_plugin_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
457 format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
460 pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
462 format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
465 pub fn sysroot<'a>(&'a self) -> &'a Path {
466 match self.opts.maybe_sysroot {
467 Some (ref sysroot) => sysroot,
468 None => self.default_sysroot.as_ref()
469 .expect("missing sysroot and default_sysroot in Session")
472 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
473 filesearch::FileSearch::new(self.sysroot(),
474 &self.opts.target_triple,
475 &self.opts.search_paths,
478 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
479 filesearch::FileSearch::new(
481 config::host_triple(),
482 &self.opts.search_paths,
486 pub fn init_incr_comp_session(&self,
487 session_dir: PathBuf,
488 lock_file: flock::Lock) {
489 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
491 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
492 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
495 *incr_comp_session = IncrCompSession::Active {
496 session_directory: session_dir,
501 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
502 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
504 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
505 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
508 // Note: This will also drop the lock file, thus unlocking the directory
509 *incr_comp_session = IncrCompSession::Finalized {
510 session_directory: new_directory_path,
514 pub fn mark_incr_comp_session_as_invalid(&self) {
515 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
517 let session_directory = match *incr_comp_session {
518 IncrCompSession::Active { ref session_directory, .. } => {
519 session_directory.clone()
521 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
525 // Note: This will also drop the lock file, thus unlocking the directory
526 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
531 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
532 let incr_comp_session = self.incr_comp_session.borrow();
533 cell::Ref::map(incr_comp_session, |incr_comp_session| {
534 match *incr_comp_session {
535 IncrCompSession::NotInitialized => {
536 bug!("Trying to get session directory from IncrCompSession `{:?}`",
539 IncrCompSession::Active { ref session_directory, .. } |
540 IncrCompSession::Finalized { ref session_directory } |
541 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
548 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
549 if self.opts.incremental.is_some() {
550 Some(self.incr_comp_session_dir())
556 pub fn print_perf_stats(&self) {
557 println!("Total time spent computing SVHs: {}",
558 duration_to_secs_str(self.perf_stats.svh_time.get()));
559 println!("Total time spent computing incr. comp. hashes: {}",
560 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
561 println!("Total number of incr. comp. hashes computed: {}",
562 self.perf_stats.incr_comp_hashes_count.get());
563 println!("Total number of bytes hashed for incr. comp.: {}",
564 self.perf_stats.incr_comp_bytes_hashed.get());
565 println!("Average bytes hashed per incr. comp. HIR node: {}",
566 self.perf_stats.incr_comp_bytes_hashed.get() /
567 self.perf_stats.incr_comp_hashes_count.get());
568 println!("Total time spent computing symbol hashes: {}",
569 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
570 println!("Total time spent decoding DefPath tables: {}",
571 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
574 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
575 /// This expends fuel if applicable, and records fuel if applicable.
576 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
578 match self.optimization_fuel_crate {
579 Some(ref c) if c == crate_name => {
580 let fuel = self.optimization_fuel_limit.get();
582 if fuel == 0 && !self.out_of_fuel.get() {
583 println!("optimization-fuel-exhausted: {}", msg());
584 self.out_of_fuel.set(true);
586 self.optimization_fuel_limit.set(fuel-1);
591 match self.print_fuel_crate {
592 Some(ref c) if c == crate_name=> {
593 self.print_fuel.set(self.print_fuel.get()+1);
601 pub fn build_session(sopts: config::Options,
602 dep_graph: &DepGraph,
603 local_crate_source_file: Option<PathBuf>,
604 registry: errors::registry::Registry,
605 cstore: Rc<CrateStore>)
607 let file_path_mapping = sopts.file_path_mapping();
609 build_session_with_codemap(sopts,
611 local_crate_source_file,
614 Rc::new(codemap::CodeMap::new(file_path_mapping)),
618 pub fn build_session_with_codemap(sopts: config::Options,
619 dep_graph: &DepGraph,
620 local_crate_source_file: Option<PathBuf>,
621 registry: errors::registry::Registry,
622 cstore: Rc<CrateStore>,
623 codemap: Rc<codemap::CodeMap>,
624 emitter_dest: Option<Box<Write + Send>>)
626 // FIXME: This is not general enough to make the warning lint completely override
627 // normal diagnostic warnings, since the warning lint can also be denied and changed
628 // later via the source code.
629 let can_print_warnings = sopts.lint_opts
631 .filter(|&&(ref key, _)| *key == "warnings")
632 .map(|&(_, ref level)| *level != lint::Allow)
635 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
637 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
638 (config::ErrorOutputType::HumanReadable(color_config), None) => {
639 Box::new(EmitterWriter::stderr(color_config,
640 Some(codemap.clone())))
642 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
643 Box::new(EmitterWriter::new(dst,
644 Some(codemap.clone())))
646 (config::ErrorOutputType::Json, None) => {
647 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
649 (config::ErrorOutputType::Json, Some(dst)) => {
650 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
654 let diagnostic_handler =
655 errors::Handler::with_emitter(can_print_warnings,
659 build_session_(sopts,
661 local_crate_source_file,
667 pub fn build_session_(sopts: config::Options,
668 dep_graph: &DepGraph,
669 local_crate_source_file: Option<PathBuf>,
670 span_diagnostic: errors::Handler,
671 codemap: Rc<codemap::CodeMap>,
672 cstore: Rc<CrateStore>)
674 let host = match Target::search(config::host_triple()) {
677 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
680 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
682 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
683 let default_sysroot = match sopts.maybe_sysroot {
685 None => Some(filesearch::get_or_default_sysroot())
688 let file_path_mapping = sopts.file_path_mapping();
690 // Make the path absolute, if necessary
691 let local_crate_source_file = local_crate_source_file.map(|path| {
692 file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
695 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
696 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
697 .map(|i| i.1).unwrap_or(0));
698 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
699 let print_fuel = Cell::new(0);
701 let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
702 let working_dir = file_path_mapping.map_prefix(working_dir);
705 dep_graph: dep_graph.clone(),
711 // For a library crate, this is always none
712 entry_fn: RefCell::new(None),
713 entry_type: Cell::new(None),
714 plugin_registrar_fn: Cell::new(None),
715 derive_registrar_fn: Cell::new(None),
717 local_crate_source_file,
719 lint_store: RefCell::new(lint::LintStore::new()),
720 buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
721 one_time_diagnostics: RefCell::new(FxHashSet()),
722 plugin_llvm_passes: RefCell::new(Vec::new()),
723 plugin_attributes: RefCell::new(Vec::new()),
724 crate_types: RefCell::new(Vec::new()),
725 dependency_formats: RefCell::new(FxHashMap()),
726 crate_disambiguator: RefCell::new(Symbol::intern("")),
727 features: RefCell::new(feature_gate::Features::new()),
728 recursion_limit: Cell::new(64),
729 type_length_limit: Cell::new(1048576),
730 next_node_id: Cell::new(NodeId::new(1)),
731 injected_allocator: Cell::new(None),
732 allocator_kind: Cell::new(None),
733 injected_panic_runtime: Cell::new(None),
734 imported_macro_spans: RefCell::new(HashMap::new()),
735 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
736 perf_stats: PerfStats {
737 svh_time: Cell::new(Duration::from_secs(0)),
738 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
739 incr_comp_hashes_count: Cell::new(0),
740 incr_comp_bytes_hashed: Cell::new(0),
741 symbol_hash_time: Cell::new(Duration::from_secs(0)),
742 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
744 code_stats: RefCell::new(CodeStats::new()),
745 optimization_fuel_crate,
746 optimization_fuel_limit,
749 out_of_fuel: Cell::new(false),
750 // Note that this is unsafe because it may misinterpret file descriptors
751 // on Unix as jobserver file descriptors. We hopefully execute this near
752 // the beginning of the process though to ensure we don't get false
753 // positives, or in other words we try to execute this before we open
754 // any file descriptors ourselves.
756 // Also note that we stick this in a global because there could be
757 // multiple `Session` instances in this process, and the jobserver is
759 jobserver_from_env: unsafe {
760 static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
761 static INIT: Once = ONCE_INIT;
763 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
765 (*GLOBAL_JOBSERVER).clone()
767 has_global_allocator: Cell::new(false),
773 /// Holds data on the current incremental compilation session, if there is one.
775 pub enum IncrCompSession {
776 // This is the state the session will be in until the incr. comp. dir is
779 // This is the state during which the session directory is private and can
782 session_directory: PathBuf,
783 lock_file: flock::Lock,
785 // This is the state after the session directory has been finalized. In this
786 // state, the contents of the directory must not be modified any more.
788 session_directory: PathBuf,
790 // This is an error state that is reached when some compilation error has
791 // occurred. It indicates that the contents of the session directory must
792 // not be used, since they might be invalid.
793 InvalidBecauseOfErrors {
794 session_directory: PathBuf,
798 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
799 let emitter: Box<Emitter> = match output {
800 config::ErrorOutputType::HumanReadable(color_config) => {
801 Box::new(EmitterWriter::stderr(color_config,
804 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
806 let handler = errors::Handler::with_emitter(true, false, emitter);
807 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
808 panic!(errors::FatalError);
811 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
812 let emitter: Box<Emitter> = match output {
813 config::ErrorOutputType::HumanReadable(color_config) => {
814 Box::new(EmitterWriter::stderr(color_config,
817 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
819 let handler = errors::Handler::with_emitter(true, false, emitter);
820 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
823 #[derive(Copy, Clone, Debug)]
824 pub enum CompileIncomplete {
826 Errored(ErrorReported)
828 impl From<ErrorReported> for CompileIncomplete {
829 fn from(err: ErrorReported) -> CompileIncomplete {
830 CompileIncomplete::Errored(err)
833 pub type CompileResult = Result<(), CompileIncomplete>;
835 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
839 Err(CompileIncomplete::Errored(ErrorReported))
845 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
846 // this wrapper mostly exists so I don't have to write a fully
847 // qualified path of None::<Span> inside the bug!() macro definition
848 opt_span_bug_fmt(file, line, None::<Span>, args);
853 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
856 args: fmt::Arguments) -> ! {
857 opt_span_bug_fmt(file, line, Some(span), args);
860 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
863 args: fmt::Arguments) -> ! {
864 tls::with_opt(move |tcx| {
865 let msg = format!("{}:{}: {}", file, line, args);
867 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
868 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
869 (None, _) => panic!(msg)