]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
Introduce CrateDisambiguator newtype and fix tests
[rust.git] / src / librustc / session / mod.rs
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.
4 //
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.
10
11 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
13
14 use hir::def_id::{CrateNum, DefIndex};
15 use ich::Fingerprint;
16
17 use lint;
18 use middle::allocator::AllocatorKind;
19 use middle::dependency_format;
20 use session::search_paths::PathKind;
21 use session::config::DebugInfoLevel;
22 use ty::tls;
23 use util::nodemap::{FxHashMap, FxHashSet};
24 use util::common::{duration_to_secs_str, ErrorReported};
25
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;
31 use syntax::parse;
32 use syntax::parse::ParseSess;
33 use syntax::{ast, codemap};
34 use syntax::feature_gate::AttributeType;
35 use syntax_pos::{Span, MultiSpan};
36
37 use rustc_back::{LinkerFlavor, PanicStrategy};
38 use rustc_back::target::Target;
39 use rustc_data_structures::flock;
40 use jobserver::Client;
41
42 use std::cell::{self, Cell, RefCell};
43 use std::collections::HashMap;
44 use std::env;
45 use std::fmt;
46 use std::io::Write;
47 use std::path::{Path, PathBuf};
48 use std::rc::Rc;
49 use std::sync::{Once, ONCE_INIT};
50 use std::time::Duration;
51
52 mod code_stats;
53 pub mod config;
54 pub mod filesearch;
55 pub mod search_paths;
56
57 /// Represents the data associated with a compilation
58 /// session for a single crate.
59 pub struct Session {
60     pub target: config::Config,
61     pub host: Target,
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>,
93
94     /// The maximum recursion limit for potentially infinitely recursive
95     /// operations such as auto-dereference and monomorphization.
96     pub recursion_limit: Cell<usize>,
97
98     /// The maximum length of types during monomorphization.
99     pub type_length_limit: Cell<usize>,
100
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
103     /// injected.
104     pub injected_allocator: Cell<Option<CrateNum>>,
105     pub allocator_kind: Cell<Option<AllocatorKind>>,
106     pub injected_panic_runtime: Cell<Option<CrateNum>>,
107
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)>>,
112
113     incr_comp_session: RefCell<IncrCompSession>,
114
115     /// Some measurements that are being gathered during compilation.
116     pub perf_stats: PerfStats,
117
118     /// Data about code being compiled, gathered during compilation.
119     pub code_stats: RefCell<CodeStats>,
120
121     next_node_id: Cell<ast::NodeId>,
122
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>,
129
130     // The next two are public because the driver needs to read them.
131
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>,
136
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>,
140
141     /// Metadata about the allocators for the current crate being compiled
142     pub has_global_allocator: Cell<bool>,
143 }
144
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>,
158 }
159
160 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
161 enum DiagnosticBuilderMethod {
162     Note,
163     SpanNote,
164     // add more variants as needed to support one-time diagnostics
165 }
166
167 impl Session {
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"),
172         }
173     }
174     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
175                                                     sp: S,
176                                                     msg: &str)
177                                                     -> DiagnosticBuilder<'a> {
178         self.diagnostic().struct_span_warn(sp, msg)
179     }
180     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
181                                                               sp: S,
182                                                               msg: &str,
183                                                               code: &str)
184                                                               -> DiagnosticBuilder<'a> {
185         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
186     }
187     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
188         self.diagnostic().struct_warn(msg)
189     }
190     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
191                                                    sp: S,
192                                                    msg: &str)
193                                                    -> DiagnosticBuilder<'a> {
194         self.diagnostic().struct_span_err(sp, msg)
195     }
196     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
197                                                              sp: S,
198                                                              msg: &str,
199                                                              code: &str)
200                                                              -> DiagnosticBuilder<'a> {
201         self.diagnostic().struct_span_err_with_code(sp, msg, code)
202     }
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)
206     }
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)
209     }
210     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
211                                                      sp: S,
212                                                      msg: &str)
213                                                      -> DiagnosticBuilder<'a> {
214         self.diagnostic().struct_span_fatal(sp, msg)
215     }
216     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
217                                                                sp: S,
218                                                                msg: &str,
219                                                                code: &str)
220                                                                -> DiagnosticBuilder<'a> {
221         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
222     }
223     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
224         self.diagnostic().struct_fatal(msg)
225     }
226
227     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
228         panic!(self.diagnostic().span_fatal(sp, msg))
229     }
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))
232     }
233     pub fn fatal(&self, msg: &str) -> ! {
234         panic!(self.diagnostic().fatal(msg))
235     }
236     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
237         if is_warning {
238             self.span_warn(sp, msg);
239         } else {
240             self.span_err(sp, msg);
241         }
242     }
243     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
244         self.diagnostic().span_err(sp, msg)
245     }
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)
248     }
249     pub fn err(&self, msg: &str) {
250         self.diagnostic().err(msg)
251     }
252     pub fn err_count(&self) -> usize {
253         self.diagnostic().err_count()
254     }
255     pub fn has_errors(&self) -> bool {
256         self.diagnostic().has_errors()
257     }
258     pub fn abort_if_errors(&self) {
259         self.diagnostic().abort_if_errors();
260     }
261     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
262         compile_result_from_err_count(self.err_count())
263     }
264     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
265         where F: FnOnce() -> T
266     {
267         let old_count = self.err_count();
268         let result = f();
269         let errors = self.err_count() - old_count;
270         if errors == 0 {
271             Ok(result)
272         } else {
273             Err(ErrorReported)
274         }
275     }
276     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
277         self.diagnostic().span_warn(sp, msg)
278     }
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)
281     }
282     pub fn warn(&self, msg: &str) {
283         self.diagnostic().warn(msg)
284     }
285     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
286         match opt_sp {
287             Some(sp) => self.span_warn(sp, msg),
288             None => self.warn(msg),
289         }
290     }
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)
294     }
295     pub fn note_without_error(&self, msg: &str) {
296         self.diagnostic().note_without_error(msg)
297     }
298     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
299         self.diagnostic().span_note_without_error(sp, msg)
300     }
301     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
302         self.diagnostic().span_unimpl(sp, msg)
303     }
304     pub fn unimpl(&self, msg: &str) -> ! {
305         self.diagnostic().unimpl(msg)
306     }
307
308     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
309                                            lint: &'static lint::Lint,
310                                            id: ast::NodeId,
311                                            sp: S,
312                                            msg: &str) {
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"),
316         }
317     }
318
319     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
320         let id = self.next_node_id.get();
321
322         match id.as_usize().checked_add(count) {
323             Some(next) => {
324                 self.next_node_id.set(ast::NodeId::new(next));
325             }
326             None => bug!("Input too large, ran out of node ids!")
327         }
328
329         id
330     }
331     pub fn next_node_id(&self) -> NodeId {
332         self.reserve_node_ids(1)
333     }
334     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
335         &self.parse_sess.span_diagnostic
336     }
337
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 = || {
346             match method {
347                 DiagnosticBuilderMethod::Note => {
348                     diag_builder.note(message);
349                 },
350                 DiagnosticBuilderMethod::SpanNote => {
351                     diag_builder.span_note(span.expect("span_note expects a span"), message);
352                 }
353             }
354         };
355
356         match self.opts.error_format {
357             // when outputting JSON for tool consumption, the tool might want
358             // the duplicates
359             config::ErrorOutputType::Json => {
360                 do_method()
361             },
362             _ => {
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);
366                 if fresh {
367                     do_method()
368                 }
369             }
370         }
371     }
372
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));
377     }
378
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);
383     }
384
385     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
386         self.parse_sess.codemap()
387     }
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
393     }
394     pub fn profile_queries_and_keys(&self) -> bool {
395         self.opts.debugging_opts.profile_queries_and_keys
396     }
397     pub fn count_llvm_insns(&self) -> bool {
398         self.opts.debugging_opts.count_llvm_insns
399     }
400     pub fn time_llvm_passes(&self) -> bool {
401         self.opts.debugging_opts.time_llvm_passes
402     }
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
410     }
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
415     }
416     pub fn lto(&self) -> bool {
417         self.opts.cg.lto
418     }
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)
423     }
424     pub fn linker_flavor(&self) -> LinkerFlavor {
425         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
426     }
427     pub fn no_landing_pads(&self) -> bool {
428         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
429     }
430     pub fn unstable_options(&self) -> bool {
431         self.opts.debugging_opts.unstable_options
432     }
433     pub fn nonzeroing_move_hints(&self) -> bool {
434         self.opts.debugging_opts.enable_nonzeroing_move_hints
435     }
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)
440     }
441
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()
446         } else {
447             self.target.target.options.crt_static_default
448         }
449     }
450
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");
455
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 {
461             !found_negative
462         } else {
463             found_positive
464         }
465     }
466
467     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
468         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
469         !self.target.target.options.eliminate_frame_pointer
470     }
471
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,
475                                             index: DefIndex)
476                                             -> String {
477         format!("__rustc_plugin_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
478                                                    index.as_usize())
479     }
480
481     pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator,
482                                             index: DefIndex)
483                                             -> String {
484         format!("__rustc_derive_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
485                                                    index.as_usize())
486     }
487
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")
493         }
494     }
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,
499                                     kind)
500     }
501     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
502         filesearch::FileSearch::new(
503             self.sysroot(),
504             config::host_triple(),
505             &self.opts.search_paths,
506             kind)
507     }
508
509     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
510         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
511
512         match *incr_comp_session {
513             IncrCompSession::Active { ref mut load_dep_graph, .. } => {
514                 *load_dep_graph = load;
515             }
516             _ => {}
517         }
518     }
519
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,
524             _ => false,
525         }
526     }
527
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();
533
534         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
535             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
536         }
537
538         *incr_comp_session = IncrCompSession::Active {
539             session_directory: session_dir,
540             lock_file,
541             load_dep_graph,
542         };
543     }
544
545     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
546         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
547
548         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
549             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
550         }
551
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,
555         };
556     }
557
558     pub fn mark_incr_comp_session_as_invalid(&self) {
559         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
560
561         let session_directory = match *incr_comp_session {
562             IncrCompSession::Active { ref session_directory, .. } => {
563                 session_directory.clone()
564             }
565             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
566                       *incr_comp_session),
567         };
568
569         // Note: This will also drop the lock file, thus unlocking the directory
570         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
571             session_directory,
572         };
573     }
574
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 `{:?}`",
581                         *incr_comp_session)
582                 }
583                 IncrCompSession::Active { ref session_directory, .. } |
584                 IncrCompSession::Finalized { ref session_directory } |
585                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
586                     session_directory
587                 }
588             }
589         })
590     }
591
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())
595         } else {
596             None
597         }
598     }
599
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()));
616     }
617
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 {
621         let mut ret = true;
622         match self.optimization_fuel_crate {
623             Some(ref c) if c == crate_name => {
624                 let fuel = self.optimization_fuel_limit.get();
625                 ret = fuel != 0;
626                 if fuel == 0 && !self.out_of_fuel.get() {
627                     println!("optimization-fuel-exhausted: {}", msg());
628                     self.out_of_fuel.set(true);
629                 } else if fuel > 0 {
630                     self.optimization_fuel_limit.set(fuel-1);
631                 }
632             }
633             _ => {}
634         }
635         match self.print_fuel_crate {
636             Some(ref c) if c == crate_name=> {
637                 self.print_fuel.set(self.print_fuel.get()+1);
638             },
639             _ => {}
640         }
641         ret
642     }
643
644     /// Returns the number of codegen units that should be used for this
645     /// compilation
646     pub fn codegen_units(&self) -> usize {
647         if let Some(n) = self.opts.cli_forced_codegen_units {
648             return n
649         }
650         if let Some(n) = self.target.target.options.default_codegen_units {
651             return n as usize
652         }
653
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
659             // a non-issue.
660             //
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.
667             //
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,
674
675             // All other optimization levels default use one codegen unit,
676             // the historical default in Rust for a Long Time.
677             _ => 1,
678         }
679     }
680 }
681
682 pub fn build_session(sopts: config::Options,
683                      local_crate_source_file: Option<PathBuf>,
684                      registry: errors::registry::Registry)
685                      -> Session {
686     let file_path_mapping = sopts.file_path_mapping();
687
688     build_session_with_codemap(sopts,
689                                local_crate_source_file,
690                                registry,
691                                Rc::new(codemap::CodeMap::new(file_path_mapping)),
692                                None)
693 }
694
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>>)
700                                   -> Session {
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
705         .iter()
706         .filter(|&&(ref key, _)| *key == "warnings")
707         .map(|&(_, ref level)| *level == lint::Allow)
708         .last()
709         .unwrap_or(false);
710     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
711
712     let can_print_warnings = !(warnings_allow || cap_lints_allow);
713
714     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
715
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())))
720         }
721         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
722             Box::new(EmitterWriter::new(dst,
723                                         Some(codemap.clone())))
724         }
725         (config::ErrorOutputType::Json, None) => {
726             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
727         }
728         (config::ErrorOutputType::Json, Some(dst)) => {
729             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
730         }
731     };
732
733     let diagnostic_handler =
734         errors::Handler::with_emitter(can_print_warnings,
735                                       treat_err_as_bug,
736                                       emitter);
737
738     build_session_(sopts,
739                    local_crate_source_file,
740                    diagnostic_handler,
741                    codemap)
742 }
743
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>)
748                       -> Session {
749     let host = match Target::search(config::host_triple()) {
750         Ok(t) => t,
751         Err(e) => {
752             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
753         }
754     };
755     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
756
757     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
758     let default_sysroot = match sopts.maybe_sysroot {
759         Some(_) => None,
760         None => Some(filesearch::get_or_default_sysroot())
761     };
762
763     let file_path_mapping = sopts.file_path_mapping();
764
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
767     });
768
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);
774
775     let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
776     let working_dir = file_path_mapping.map_prefix(working_dir);
777
778     let sess = Session {
779         target: target_cfg,
780         host,
781         opts: sopts,
782         parse_sess: p_s,
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),
788         default_sysroot,
789         local_crate_source_file,
790         working_dir,
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)),
815         },
816         code_stats: RefCell::new(CodeStats::new()),
817         optimization_fuel_crate,
818         optimization_fuel_limit,
819         print_fuel_crate,
820         print_fuel,
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.
827         //
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
830         // per-process.
831         jobserver_from_env: unsafe {
832             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
833             static INIT: Once = ONCE_INIT;
834             INIT.call_once(|| {
835                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
836             });
837             (*GLOBAL_JOBSERVER).clone()
838         },
839         has_global_allocator: Cell::new(false),
840     };
841
842     sess
843 }
844
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
847 /// the crate.
848 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
849 pub struct CrateDisambiguator(Fingerprint);
850
851 impl CrateDisambiguator {
852     pub fn to_fingerprint(self) -> Fingerprint {
853         self.0
854     }
855 }
856
857 impl From<Fingerprint> for CrateDisambiguator {
858     fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
859         CrateDisambiguator(fingerprint)
860     }
861 }
862
863 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
864
865 /// Holds data on the current incremental compilation session, if there is one.
866 #[derive(Debug)]
867 pub enum IncrCompSession {
868     /// This is the state the session will be in until the incr. comp. dir is
869     /// needed.
870     NotInitialized,
871     /// This is the state during which the session directory is private and can
872     /// be modified.
873     Active {
874         session_directory: PathBuf,
875         lock_file: flock::Lock,
876         load_dep_graph: bool,
877     },
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.
880     Finalized {
881         session_directory: PathBuf,
882     },
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,
888     }
889 }
890
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,
895                                            None))
896         }
897         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
898     };
899     let handler = errors::Handler::with_emitter(true, false, emitter);
900     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
901     panic!(errors::FatalError);
902 }
903
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,
908                                            None))
909         }
910         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
911     };
912     let handler = errors::Handler::with_emitter(true, false, emitter);
913     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
914 }
915
916 #[derive(Copy, Clone, Debug)]
917 pub enum CompileIncomplete {
918     Stopped,
919     Errored(ErrorReported)
920 }
921 impl From<ErrorReported> for CompileIncomplete {
922     fn from(err: ErrorReported) -> CompileIncomplete {
923         CompileIncomplete::Errored(err)
924     }
925 }
926 pub type CompileResult = Result<(), CompileIncomplete>;
927
928 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
929     if err_count == 0 {
930         Ok(())
931     } else {
932         Err(CompileIncomplete::Errored(ErrorReported))
933     }
934 }
935
936 #[cold]
937 #[inline(never)]
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);
942 }
943
944 #[cold]
945 #[inline(never)]
946 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
947                                         line: u32,
948                                         span: S,
949                                         args: fmt::Arguments) -> ! {
950     opt_span_bug_fmt(file, line, Some(span), args);
951 }
952
953 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
954                                         line: u32,
955                                         span: Option<S>,
956                                         args: fmt::Arguments) -> ! {
957     tls::with_opt(move |tcx| {
958         let msg = format!("{}:{}: {}", file, line, args);
959         match (tcx, span) {
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)
963         }
964     });
965     unreachable!();
966 }