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};
17 use middle::allocator::AllocatorKind;
18 use middle::dependency_format;
19 use session::search_paths::PathKind;
20 use session::config::DebugInfoLevel;
22 use util::nodemap::{FxHashMap, FxHashSet};
23 use util::common::{duration_to_secs_str, ErrorReported};
25 use syntax::ast::NodeId;
26 use errors::{self, DiagnosticBuilder};
27 use errors::emitter::{Emitter, EmitterWriter};
28 use syntax::json::JsonEmitter;
29 use syntax::feature_gate;
31 use syntax::parse::ParseSess;
32 use syntax::symbol::Symbol;
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 // The path is always expected to be absolute. `None` means that there is no
73 pub local_crate_source_file: Option<String>,
74 // The directory the compiler has been executed in plus a flag indicating
75 // if the value stored here has been affected by path remapping.
76 pub working_dir: (String, bool),
77 pub lint_store: RefCell<lint::LintStore>,
78 pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
79 /// Set of (LintId, Option<Span>, message) tuples tracking lint
80 /// (sub)diagnostics that have been set once, but should not be set again,
81 /// in order to avoid redundantly verbose output (Issue #24690).
82 pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Option<Span>, String)>>,
83 pub plugin_llvm_passes: RefCell<Vec<String>>,
84 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
85 pub crate_types: RefCell<Vec<config::CrateType>>,
86 pub dependency_formats: RefCell<dependency_format::Dependencies>,
87 // The crate_disambiguator is constructed out of all the `-C metadata`
88 // arguments passed to the compiler. Its value together with the crate-name
89 // forms a unique global identifier for the crate. It is used to allow
90 // multiple crates with the same name to coexist. See the
91 // trans::back::symbol_names module for more information.
92 pub crate_disambiguator: RefCell<Option<Symbol>>,
93 pub features: RefCell<feature_gate::Features>,
95 /// The maximum recursion limit for potentially infinitely recursive
96 /// operations such as auto-dereference and monomorphization.
97 pub recursion_limit: Cell<usize>,
99 /// The maximum length of types during monomorphization.
100 pub type_length_limit: Cell<usize>,
102 /// The metadata::creader module may inject an allocator/panic_runtime
103 /// dependency if it didn't already find one, and this tracks what was
105 pub injected_allocator: Cell<Option<CrateNum>>,
106 pub allocator_kind: Cell<Option<AllocatorKind>>,
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 definition 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>,
138 /// Loaded up early on in the initialization of this `Session` to avoid
139 /// false positives about a job server in our environment.
140 pub jobserver_from_env: Option<Client>,
142 /// Metadata about the allocators for the current crate being compiled
143 pub has_global_allocator: Cell<bool>,
146 pub struct PerfStats {
147 // The accumulated time needed for computing the SVH of the crate
148 pub svh_time: Cell<Duration>,
149 // The accumulated time spent on computing incr. comp. hashes
150 pub incr_comp_hashes_time: Cell<Duration>,
151 // The number of incr. comp. hash computations performed
152 pub incr_comp_hashes_count: Cell<u64>,
153 // The number of bytes hashed when computing ICH values
154 pub incr_comp_bytes_hashed: Cell<u64>,
155 // The accumulated time spent on computing symbol hashes
156 pub symbol_hash_time: Cell<Duration>,
157 // The accumulated time spent decoding def path tables from metadata
158 pub decode_def_path_tables_time: Cell<Duration>,
161 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
162 enum DiagnosticBuilderMethod {
165 // add more variants as needed to support one-time diagnostics
169 pub fn local_crate_disambiguator(&self) -> Symbol {
170 match *self.crate_disambiguator.borrow() {
172 None => bug!("accessing disambiguator before initialization"),
175 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
178 -> DiagnosticBuilder<'a> {
179 self.diagnostic().struct_span_warn(sp, msg)
181 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
185 -> DiagnosticBuilder<'a> {
186 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
188 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
189 self.diagnostic().struct_warn(msg)
191 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
194 -> DiagnosticBuilder<'a> {
195 self.diagnostic().struct_span_err(sp, msg)
197 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
201 -> DiagnosticBuilder<'a> {
202 self.diagnostic().struct_span_err_with_code(sp, msg, code)
204 // FIXME: This method should be removed (every error should have an associated error code).
205 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
206 self.diagnostic().struct_err(msg)
208 pub fn struct_err_with_code<'a>(&'a self, msg: &str, code: &str) -> DiagnosticBuilder<'a> {
209 self.diagnostic().struct_err_with_code(msg, code)
211 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
214 -> DiagnosticBuilder<'a> {
215 self.diagnostic().struct_span_fatal(sp, msg)
217 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
221 -> DiagnosticBuilder<'a> {
222 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
224 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
225 self.diagnostic().struct_fatal(msg)
228 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
229 panic!(self.diagnostic().span_fatal(sp, msg))
231 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
232 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
234 pub fn fatal(&self, msg: &str) -> ! {
235 panic!(self.diagnostic().fatal(msg))
237 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
239 self.span_warn(sp, msg);
241 self.span_err(sp, msg);
244 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
245 self.diagnostic().span_err(sp, msg)
247 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
248 self.diagnostic().span_err_with_code(sp, &msg, code)
250 pub fn err(&self, msg: &str) {
251 self.diagnostic().err(msg)
253 pub fn err_count(&self) -> usize {
254 self.diagnostic().err_count()
256 pub fn has_errors(&self) -> bool {
257 self.diagnostic().has_errors()
259 pub fn abort_if_errors(&self) {
260 self.diagnostic().abort_if_errors();
262 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
263 compile_result_from_err_count(self.err_count())
265 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
266 where F: FnOnce() -> T
268 let old_count = self.err_count();
270 let errors = self.err_count() - old_count;
277 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
278 self.diagnostic().span_warn(sp, msg)
280 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
281 self.diagnostic().span_warn_with_code(sp, msg, code)
283 pub fn warn(&self, msg: &str) {
284 self.diagnostic().warn(msg)
286 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
288 Some(sp) => self.span_warn(sp, msg),
289 None => self.warn(msg),
292 /// Delay a span_bug() call until abort_if_errors()
293 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
294 self.diagnostic().delay_span_bug(sp, msg)
296 pub fn note_without_error(&self, msg: &str) {
297 self.diagnostic().note_without_error(msg)
299 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
300 self.diagnostic().span_note_without_error(sp, msg)
302 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
303 self.diagnostic().span_unimpl(sp, msg)
305 pub fn unimpl(&self, msg: &str) -> ! {
306 self.diagnostic().unimpl(msg)
309 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
310 lint: &'static lint::Lint,
314 match *self.buffered_lints.borrow_mut() {
315 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg),
316 None => bug!("can't buffer lints after HIR lowering"),
320 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
321 let id = self.next_node_id.get();
323 match id.as_usize().checked_add(count) {
325 self.next_node_id.set(ast::NodeId::new(next));
327 None => bug!("Input too large, ran out of node ids!")
332 pub fn next_node_id(&self) -> NodeId {
333 self.reserve_node_ids(1)
335 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
336 &self.parse_sess.span_diagnostic
339 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
340 /// deduplicates on lint ID, span (if any), and message for this `Session`
341 /// if we're not outputting in JSON mode.
342 fn diag_once<'a, 'b>(&'a self,
343 diag_builder: &'b mut DiagnosticBuilder<'a>,
344 method: DiagnosticBuilderMethod,
345 lint: &'static lint::Lint, message: &str, span: Option<Span>) {
346 let mut do_method = || {
348 DiagnosticBuilderMethod::Note => {
349 diag_builder.note(message);
351 DiagnosticBuilderMethod::SpanNote => {
352 diag_builder.span_note(span.expect("span_note expects a span"), message);
357 match self.opts.error_format {
358 // when outputting JSON for tool consumption, the tool might want
360 config::ErrorOutputType::Json => {
364 let lint_id = lint::LintId::of(lint);
365 let id_span_message = (lint_id, span, message.to_owned());
366 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
374 pub fn diag_span_note_once<'a, 'b>(&'a self,
375 diag_builder: &'b mut DiagnosticBuilder<'a>,
376 lint: &'static lint::Lint, span: Span, message: &str) {
377 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote, lint, message, Some(span));
380 pub fn diag_note_once<'a, 'b>(&'a self,
381 diag_builder: &'b mut DiagnosticBuilder<'a>,
382 lint: &'static lint::Lint, message: &str) {
383 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, lint, message, None);
386 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
387 self.parse_sess.codemap()
389 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
390 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
391 pub fn profile_queries(&self) -> bool {
392 self.opts.debugging_opts.profile_queries ||
393 self.opts.debugging_opts.profile_queries_and_keys
395 pub fn profile_queries_and_keys(&self) -> bool {
396 self.opts.debugging_opts.profile_queries_and_keys
398 pub fn count_llvm_insns(&self) -> bool {
399 self.opts.debugging_opts.count_llvm_insns
401 pub fn time_llvm_passes(&self) -> bool {
402 self.opts.debugging_opts.time_llvm_passes
404 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
405 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
406 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
407 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
408 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
409 pub fn print_llvm_passes(&self) -> bool {
410 self.opts.debugging_opts.print_llvm_passes
412 pub fn emit_end_regions(&self) -> bool {
413 self.opts.debugging_opts.emit_end_regions ||
414 (self.opts.debugging_opts.mir_emit_validate > 0)
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: Symbol, index: DefIndex)
476 format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
479 pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
481 format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
484 pub fn sysroot<'a>(&'a self) -> &'a Path {
485 match self.opts.maybe_sysroot {
486 Some (ref sysroot) => sysroot,
487 None => self.default_sysroot.as_ref()
488 .expect("missing sysroot and default_sysroot in Session")
491 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
492 filesearch::FileSearch::new(self.sysroot(),
493 &self.opts.target_triple,
494 &self.opts.search_paths,
497 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
498 filesearch::FileSearch::new(
500 config::host_triple(),
501 &self.opts.search_paths,
505 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
506 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
508 match *incr_comp_session {
509 IncrCompSession::Active { ref mut load_dep_graph, .. } => {
510 *load_dep_graph = load;
516 pub fn incr_session_load_dep_graph(&self) -> bool {
517 let incr_comp_session = self.incr_comp_session.borrow();
518 match *incr_comp_session {
519 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
524 pub fn init_incr_comp_session(&self,
525 session_dir: PathBuf,
526 lock_file: flock::Lock,
527 load_dep_graph: bool) {
528 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
530 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
531 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
534 *incr_comp_session = IncrCompSession::Active {
535 session_directory: session_dir,
541 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
542 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
544 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
545 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
548 // Note: This will also drop the lock file, thus unlocking the directory
549 *incr_comp_session = IncrCompSession::Finalized {
550 session_directory: new_directory_path,
554 pub fn mark_incr_comp_session_as_invalid(&self) {
555 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
557 let session_directory = match *incr_comp_session {
558 IncrCompSession::Active { ref session_directory, .. } => {
559 session_directory.clone()
561 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
565 // Note: This will also drop the lock file, thus unlocking the directory
566 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
571 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
572 let incr_comp_session = self.incr_comp_session.borrow();
573 cell::Ref::map(incr_comp_session, |incr_comp_session| {
574 match *incr_comp_session {
575 IncrCompSession::NotInitialized => {
576 bug!("Trying to get session directory from IncrCompSession `{:?}`",
579 IncrCompSession::Active { ref session_directory, .. } |
580 IncrCompSession::Finalized { ref session_directory } |
581 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
588 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
589 if self.opts.incremental.is_some() {
590 Some(self.incr_comp_session_dir())
596 pub fn print_perf_stats(&self) {
597 println!("Total time spent computing SVHs: {}",
598 duration_to_secs_str(self.perf_stats.svh_time.get()));
599 println!("Total time spent computing incr. comp. hashes: {}",
600 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
601 println!("Total number of incr. comp. hashes computed: {}",
602 self.perf_stats.incr_comp_hashes_count.get());
603 println!("Total number of bytes hashed for incr. comp.: {}",
604 self.perf_stats.incr_comp_bytes_hashed.get());
605 println!("Average bytes hashed per incr. comp. HIR node: {}",
606 self.perf_stats.incr_comp_bytes_hashed.get() /
607 self.perf_stats.incr_comp_hashes_count.get());
608 println!("Total time spent computing symbol hashes: {}",
609 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
610 println!("Total time spent decoding DefPath tables: {}",
611 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
614 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
615 /// This expends fuel if applicable, and records fuel if applicable.
616 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
618 match self.optimization_fuel_crate {
619 Some(ref c) if c == crate_name => {
620 let fuel = self.optimization_fuel_limit.get();
622 if fuel == 0 && !self.out_of_fuel.get() {
623 println!("optimization-fuel-exhausted: {}", msg());
624 self.out_of_fuel.set(true);
626 self.optimization_fuel_limit.set(fuel-1);
631 match self.print_fuel_crate {
632 Some(ref c) if c == crate_name=> {
633 self.print_fuel.set(self.print_fuel.get()+1);
641 pub fn build_session(sopts: config::Options,
642 local_crate_source_file: Option<PathBuf>,
643 registry: errors::registry::Registry)
645 let file_path_mapping = sopts.file_path_mapping();
647 build_session_with_codemap(sopts,
648 local_crate_source_file,
650 Rc::new(codemap::CodeMap::new(file_path_mapping)),
654 pub fn build_session_with_codemap(sopts: config::Options,
655 local_crate_source_file: Option<PathBuf>,
656 registry: errors::registry::Registry,
657 codemap: Rc<codemap::CodeMap>,
658 emitter_dest: Option<Box<Write + Send>>)
660 // FIXME: This is not general enough to make the warning lint completely override
661 // normal diagnostic warnings, since the warning lint can also be denied and changed
662 // later via the source code.
663 let can_print_warnings = sopts.lint_opts
665 .filter(|&&(ref key, _)| *key == "warnings")
666 .map(|&(_, ref level)| *level != lint::Allow)
669 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
671 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
672 (config::ErrorOutputType::HumanReadable(color_config), None) => {
673 Box::new(EmitterWriter::stderr(color_config,
674 Some(codemap.clone())))
676 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
677 Box::new(EmitterWriter::new(dst,
678 Some(codemap.clone())))
680 (config::ErrorOutputType::Json, None) => {
681 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
683 (config::ErrorOutputType::Json, Some(dst)) => {
684 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
688 let diagnostic_handler =
689 errors::Handler::with_emitter(can_print_warnings,
693 build_session_(sopts,
694 local_crate_source_file,
699 pub fn build_session_(sopts: config::Options,
700 local_crate_source_file: Option<PathBuf>,
701 span_diagnostic: errors::Handler,
702 codemap: Rc<codemap::CodeMap>)
704 let host = match Target::search(config::host_triple()) {
707 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
710 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
712 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
713 let default_sysroot = match sopts.maybe_sysroot {
715 None => Some(filesearch::get_or_default_sysroot())
718 let file_path_mapping = sopts.file_path_mapping();
720 // Make the path absolute, if necessary
721 let local_crate_source_file = local_crate_source_file.map(|path| {
722 file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
725 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
726 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
727 .map(|i| i.1).unwrap_or(0));
728 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
729 let print_fuel = Cell::new(0);
731 let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
732 let working_dir = file_path_mapping.map_prefix(working_dir);
739 // For a library crate, this is always none
740 entry_fn: RefCell::new(None),
741 entry_type: Cell::new(None),
742 plugin_registrar_fn: Cell::new(None),
743 derive_registrar_fn: Cell::new(None),
745 local_crate_source_file,
747 lint_store: RefCell::new(lint::LintStore::new()),
748 buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
749 one_time_diagnostics: RefCell::new(FxHashSet()),
750 plugin_llvm_passes: RefCell::new(Vec::new()),
751 plugin_attributes: RefCell::new(Vec::new()),
752 crate_types: RefCell::new(Vec::new()),
753 dependency_formats: RefCell::new(FxHashMap()),
754 crate_disambiguator: RefCell::new(None),
755 features: RefCell::new(feature_gate::Features::new()),
756 recursion_limit: Cell::new(64),
757 type_length_limit: Cell::new(1048576),
758 next_node_id: Cell::new(NodeId::new(1)),
759 injected_allocator: Cell::new(None),
760 allocator_kind: Cell::new(None),
761 injected_panic_runtime: Cell::new(None),
762 imported_macro_spans: RefCell::new(HashMap::new()),
763 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
764 perf_stats: PerfStats {
765 svh_time: Cell::new(Duration::from_secs(0)),
766 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
767 incr_comp_hashes_count: Cell::new(0),
768 incr_comp_bytes_hashed: Cell::new(0),
769 symbol_hash_time: Cell::new(Duration::from_secs(0)),
770 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
772 code_stats: RefCell::new(CodeStats::new()),
773 optimization_fuel_crate,
774 optimization_fuel_limit,
777 out_of_fuel: Cell::new(false),
778 // Note that this is unsafe because it may misinterpret file descriptors
779 // on Unix as jobserver file descriptors. We hopefully execute this near
780 // the beginning of the process though to ensure we don't get false
781 // positives, or in other words we try to execute this before we open
782 // any file descriptors ourselves.
784 // Also note that we stick this in a global because there could be
785 // multiple `Session` instances in this process, and the jobserver is
787 jobserver_from_env: unsafe {
788 static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
789 static INIT: Once = ONCE_INIT;
791 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
793 (*GLOBAL_JOBSERVER).clone()
795 has_global_allocator: Cell::new(false),
801 /// Holds data on the current incremental compilation session, if there is one.
803 pub enum IncrCompSession {
804 // This is the state the session will be in until the incr. comp. dir is
807 // This is the state during which the session directory is private and can
810 session_directory: PathBuf,
811 lock_file: flock::Lock,
812 load_dep_graph: bool,
814 // This is the state after the session directory has been finalized. In this
815 // state, the contents of the directory must not be modified any more.
817 session_directory: PathBuf,
819 // This is an error state that is reached when some compilation error has
820 // occurred. It indicates that the contents of the session directory must
821 // not be used, since they might be invalid.
822 InvalidBecauseOfErrors {
823 session_directory: PathBuf,
827 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
828 let emitter: Box<Emitter> = match output {
829 config::ErrorOutputType::HumanReadable(color_config) => {
830 Box::new(EmitterWriter::stderr(color_config,
833 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
835 let handler = errors::Handler::with_emitter(true, false, emitter);
836 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
837 panic!(errors::FatalError);
840 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
841 let emitter: Box<Emitter> = match output {
842 config::ErrorOutputType::HumanReadable(color_config) => {
843 Box::new(EmitterWriter::stderr(color_config,
846 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
848 let handler = errors::Handler::with_emitter(true, false, emitter);
849 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
852 #[derive(Copy, Clone, Debug)]
853 pub enum CompileIncomplete {
855 Errored(ErrorReported)
857 impl From<ErrorReported> for CompileIncomplete {
858 fn from(err: ErrorReported) -> CompileIncomplete {
859 CompileIncomplete::Errored(err)
862 pub type CompileResult = Result<(), CompileIncomplete>;
864 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
868 Err(CompileIncomplete::Errored(ErrorReported))
874 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
875 // this wrapper mostly exists so I don't have to write a fully
876 // qualified path of None::<Span> inside the bug!() macro definition
877 opt_span_bug_fmt(file, line, None::<Span>, args);
882 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
885 args: fmt::Arguments) -> ! {
886 opt_span_bug_fmt(file, line, Some(span), args);
889 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
892 args: fmt::Arguments) -> ! {
893 tls::with_opt(move |tcx| {
894 let msg = format!("{}:{}: {}", file, line, args);
896 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
897 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
898 (None, _) => panic!(msg)