]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
a3aa7594c6c2dbd229a5f6f774f21021ef5b25ca
[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 dep_graph::DepGraph;
15 use hir::def_id::{CrateNum, DefIndex};
16
17 use lint;
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;
23 use ty::tls;
24 use util::nodemap::{FxHashMap, FxHashSet};
25 use util::common::{duration_to_secs_str, ErrorReported};
26
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;
32 use syntax::parse;
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};
38
39 use rustc_back::{LinkerFlavor, PanicStrategy};
40 use rustc_back::target::Target;
41 use rustc_data_structures::flock;
42 use jobserver::Client;
43
44 use std::cell::{self, Cell, RefCell};
45 use std::collections::HashMap;
46 use std::env;
47 use std::fmt;
48 use std::io::Write;
49 use std::path::{Path, PathBuf};
50 use std::rc::Rc;
51 use std::sync::{Once, ONCE_INIT};
52 use std::time::Duration;
53
54 mod code_stats;
55 pub mod config;
56 pub mod filesearch;
57 pub mod search_paths;
58
59 // Represents the data associated with a compilation
60 // session for a single crate.
61 pub struct Session {
62     pub dep_graph: DepGraph,
63     pub target: config::Config,
64     pub host: Target,
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
76     // source file.
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>,
98
99     /// The maximum recursion limit for potentially infinitely recursive
100     /// operations such as auto-dereference and monomorphization.
101     pub recursion_limit: Cell<usize>,
102
103     /// The maximum length of types during monomorphization.
104     pub type_length_limit: Cell<usize>,
105
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
108     /// injected.
109     pub injected_allocator: Cell<Option<CrateNum>>,
110     pub allocator_kind: Cell<Option<AllocatorKind>>,
111     pub injected_panic_runtime: Cell<Option<CrateNum>>,
112
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)>>,
117
118     incr_comp_session: RefCell<IncrCompSession>,
119
120     /// Some measurements that are being gathered during compilation.
121     pub perf_stats: PerfStats,
122
123     /// Data about code being compiled, gathered during compilation.
124     pub code_stats: RefCell<CodeStats>,
125
126     next_node_id: Cell<ast::NodeId>,
127
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>,
134
135     // The next two are public because the driver needs to read them.
136
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>,
141
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>,
145
146     /// Metadata about the allocators for the current crate being compiled
147     pub has_global_allocator: Cell<bool>,
148 }
149
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>,
163 }
164
165 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
166 enum DiagnosticBuilderMethod {
167     Note,
168     SpanNote,
169     // add more variants as needed to support one-time diagnostics
170 }
171
172 impl Session {
173     pub fn local_crate_disambiguator(&self) -> Symbol {
174         *self.crate_disambiguator.borrow()
175     }
176     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
177                                                     sp: S,
178                                                     msg: &str)
179                                                     -> DiagnosticBuilder<'a> {
180         self.diagnostic().struct_span_warn(sp, msg)
181     }
182     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
183                                                               sp: S,
184                                                               msg: &str,
185                                                               code: &str)
186                                                               -> DiagnosticBuilder<'a> {
187         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
188     }
189     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
190         self.diagnostic().struct_warn(msg)
191     }
192     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
193                                                    sp: S,
194                                                    msg: &str)
195                                                    -> DiagnosticBuilder<'a> {
196         self.diagnostic().struct_span_err(sp, msg)
197     }
198     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
199                                                              sp: S,
200                                                              msg: &str,
201                                                              code: &str)
202                                                              -> DiagnosticBuilder<'a> {
203         self.diagnostic().struct_span_err_with_code(sp, msg, code)
204     }
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)
208     }
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)
211     }
212     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
213                                                      sp: S,
214                                                      msg: &str)
215                                                      -> DiagnosticBuilder<'a> {
216         self.diagnostic().struct_span_fatal(sp, msg)
217     }
218     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
219                                                                sp: S,
220                                                                msg: &str,
221                                                                code: &str)
222                                                                -> DiagnosticBuilder<'a> {
223         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
224     }
225     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
226         self.diagnostic().struct_fatal(msg)
227     }
228
229     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
230         panic!(self.diagnostic().span_fatal(sp, msg))
231     }
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))
234     }
235     pub fn fatal(&self, msg: &str) -> ! {
236         panic!(self.diagnostic().fatal(msg))
237     }
238     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
239         if is_warning {
240             self.span_warn(sp, msg);
241         } else {
242             self.span_err(sp, msg);
243         }
244     }
245     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
246         self.diagnostic().span_err(sp, msg)
247     }
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)
250     }
251     pub fn err(&self, msg: &str) {
252         self.diagnostic().err(msg)
253     }
254     pub fn err_count(&self) -> usize {
255         self.diagnostic().err_count()
256     }
257     pub fn has_errors(&self) -> bool {
258         self.diagnostic().has_errors()
259     }
260     pub fn abort_if_errors(&self) {
261         self.diagnostic().abort_if_errors();
262     }
263     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
264         compile_result_from_err_count(self.err_count())
265     }
266     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
267         where F: FnOnce() -> T
268     {
269         let old_count = self.err_count();
270         let result = f();
271         let errors = self.err_count() - old_count;
272         if errors == 0 {
273             Ok(result)
274         } else {
275             Err(ErrorReported)
276         }
277     }
278     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
279         self.diagnostic().span_warn(sp, msg)
280     }
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)
283     }
284     pub fn warn(&self, msg: &str) {
285         self.diagnostic().warn(msg)
286     }
287     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
288         match opt_sp {
289             Some(sp) => self.span_warn(sp, msg),
290             None => self.warn(msg),
291         }
292     }
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)
296     }
297     pub fn note_without_error(&self, msg: &str) {
298         self.diagnostic().note_without_error(msg)
299     }
300     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
301         self.diagnostic().span_note_without_error(sp, msg)
302     }
303     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
304         self.diagnostic().span_unimpl(sp, msg)
305     }
306     pub fn unimpl(&self, msg: &str) -> ! {
307         self.diagnostic().unimpl(msg)
308     }
309
310     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
311                                            lint: &'static lint::Lint,
312                                            id: ast::NodeId,
313                                            sp: S,
314                                            msg: &str) {
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"),
318         }
319     }
320
321     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
322         let id = self.next_node_id.get();
323
324         match id.as_usize().checked_add(count) {
325             Some(next) => {
326                 self.next_node_id.set(ast::NodeId::new(next));
327             }
328             None => bug!("Input too large, ran out of node ids!")
329         }
330
331         id
332     }
333     pub fn next_node_id(&self) -> NodeId {
334         self.reserve_node_ids(1)
335     }
336     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
337         &self.parse_sess.span_diagnostic
338     }
339
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 = || {
348             match method {
349                 DiagnosticBuilderMethod::Note => {
350                     diag_builder.note(message);
351                 },
352                 DiagnosticBuilderMethod::SpanNote => {
353                     diag_builder.span_note(span.expect("span_note expects a span"), message);
354                 }
355             }
356         };
357
358         match self.opts.error_format {
359             // when outputting JSON for tool consumption, the tool might want
360             // the duplicates
361             config::ErrorOutputType::Json => {
362                 do_method()
363             },
364             _ => {
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);
368                 if fresh {
369                     do_method()
370                 }
371             }
372         }
373     }
374
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));
379     }
380
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);
385     }
386
387     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
388         self.parse_sess.codemap()
389     }
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
394     }
395     pub fn time_llvm_passes(&self) -> bool {
396         self.opts.debugging_opts.time_llvm_passes
397     }
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
405     }
406     pub fn lto(&self) -> bool {
407         self.opts.cg.lto
408     }
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)
413     }
414     pub fn linker_flavor(&self) -> LinkerFlavor {
415         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
416     }
417     pub fn no_landing_pads(&self) -> bool {
418         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
419     }
420     pub fn unstable_options(&self) -> bool {
421         self.opts.debugging_opts.unstable_options
422     }
423     pub fn nonzeroing_move_hints(&self) -> bool {
424         self.opts.debugging_opts.enable_nonzeroing_move_hints
425     }
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)
430     }
431
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");
436
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 {
442             !found_negative
443         } else {
444             found_positive
445         }
446     }
447
448     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
449         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
450         !self.target.target.options.eliminate_frame_pointer
451     }
452
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)
456                                             -> String {
457         format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
458     }
459
460     pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
461                                             -> String {
462         format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
463     }
464
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")
470         }
471     }
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,
476                                     kind)
477     }
478     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
479         filesearch::FileSearch::new(
480             self.sysroot(),
481             config::host_triple(),
482             &self.opts.search_paths,
483             kind)
484     }
485
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();
490
491         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
492             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
493         }
494
495         *incr_comp_session = IncrCompSession::Active {
496             session_directory: session_dir,
497             lock_file,
498         };
499     }
500
501     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
502         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
503
504         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
505             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
506         }
507
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,
511         };
512     }
513
514     pub fn mark_incr_comp_session_as_invalid(&self) {
515         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
516
517         let session_directory = match *incr_comp_session {
518             IncrCompSession::Active { ref session_directory, .. } => {
519                 session_directory.clone()
520             }
521             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
522                       *incr_comp_session),
523         };
524
525         // Note: This will also drop the lock file, thus unlocking the directory
526         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
527             session_directory,
528         };
529     }
530
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 `{:?}`",
537                         *incr_comp_session)
538                 }
539                 IncrCompSession::Active { ref session_directory, .. } |
540                 IncrCompSession::Finalized { ref session_directory } |
541                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
542                     session_directory
543                 }
544             }
545         })
546     }
547
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())
551         } else {
552             None
553         }
554     }
555
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()));
572     }
573
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 {
577         let mut ret = true;
578         match self.optimization_fuel_crate {
579             Some(ref c) if c == crate_name => {
580                 let fuel = self.optimization_fuel_limit.get();
581                 ret = fuel != 0;
582                 if fuel == 0 && !self.out_of_fuel.get() {
583                     println!("optimization-fuel-exhausted: {}", msg());
584                     self.out_of_fuel.set(true);
585                 } else if fuel > 0 {
586                     self.optimization_fuel_limit.set(fuel-1);
587                 }
588             }
589             _ => {}
590         }
591         match self.print_fuel_crate {
592             Some(ref c) if c == crate_name=> {
593                 self.print_fuel.set(self.print_fuel.get()+1);
594             },
595             _ => {}
596         }
597         ret
598     }
599 }
600
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>)
606                      -> Session {
607     let file_path_mapping = sopts.file_path_mapping();
608
609     build_session_with_codemap(sopts,
610                                dep_graph,
611                                local_crate_source_file,
612                                registry,
613                                cstore,
614                                Rc::new(codemap::CodeMap::new(file_path_mapping)),
615                                None)
616 }
617
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>>)
625                                   -> Session {
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
630         .iter()
631         .filter(|&&(ref key, _)| *key == "warnings")
632         .map(|&(_, ref level)| *level != lint::Allow)
633         .last()
634         .unwrap_or(true);
635     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
636
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())))
641         }
642         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
643             Box::new(EmitterWriter::new(dst,
644                                         Some(codemap.clone())))
645         }
646         (config::ErrorOutputType::Json, None) => {
647             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
648         }
649         (config::ErrorOutputType::Json, Some(dst)) => {
650             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
651         }
652     };
653
654     let diagnostic_handler =
655         errors::Handler::with_emitter(can_print_warnings,
656                                       treat_err_as_bug,
657                                       emitter);
658
659     build_session_(sopts,
660                    dep_graph,
661                    local_crate_source_file,
662                    diagnostic_handler,
663                    codemap,
664                    cstore)
665 }
666
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>)
673                       -> Session {
674     let host = match Target::search(config::host_triple()) {
675         Ok(t) => t,
676         Err(e) => {
677             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
678         }
679     };
680     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
681
682     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
683     let default_sysroot = match sopts.maybe_sysroot {
684         Some(_) => None,
685         None => Some(filesearch::get_or_default_sysroot())
686     };
687
688     let file_path_mapping = sopts.file_path_mapping();
689
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
693     });
694
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);
700
701     let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
702     let working_dir = file_path_mapping.map_prefix(working_dir);
703
704     let sess = Session {
705         dep_graph: dep_graph.clone(),
706         target: target_cfg,
707         host,
708         opts: sopts,
709         cstore,
710         parse_sess: p_s,
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),
716         default_sysroot,
717         local_crate_source_file,
718         working_dir,
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)),
743         },
744         code_stats: RefCell::new(CodeStats::new()),
745         optimization_fuel_crate,
746         optimization_fuel_limit,
747         print_fuel_crate,
748         print_fuel,
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.
755         //
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
758         // per-process.
759         jobserver_from_env: unsafe {
760             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
761             static INIT: Once = ONCE_INIT;
762             INIT.call_once(|| {
763                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
764             });
765             (*GLOBAL_JOBSERVER).clone()
766         },
767         has_global_allocator: Cell::new(false),
768     };
769
770     sess
771 }
772
773 /// Holds data on the current incremental compilation session, if there is one.
774 #[derive(Debug)]
775 pub enum IncrCompSession {
776     // This is the state the session will be in until the incr. comp. dir is
777     // needed.
778     NotInitialized,
779     // This is the state during which the session directory is private and can
780     // be modified.
781     Active {
782         session_directory: PathBuf,
783         lock_file: flock::Lock,
784     },
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.
787     Finalized {
788         session_directory: PathBuf,
789     },
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,
795     }
796 }
797
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,
802                                            None))
803         }
804         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
805     };
806     let handler = errors::Handler::with_emitter(true, false, emitter);
807     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
808     panic!(errors::FatalError);
809 }
810
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,
815                                            None))
816         }
817         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
818     };
819     let handler = errors::Handler::with_emitter(true, false, emitter);
820     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
821 }
822
823 #[derive(Copy, Clone, Debug)]
824 pub enum CompileIncomplete {
825     Stopped,
826     Errored(ErrorReported)
827 }
828 impl From<ErrorReported> for CompileIncomplete {
829     fn from(err: ErrorReported) -> CompileIncomplete {
830         CompileIncomplete::Errored(err)
831     }
832 }
833 pub type CompileResult = Result<(), CompileIncomplete>;
834
835 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
836     if err_count == 0 {
837         Ok(())
838     } else {
839         Err(CompileIncomplete::Errored(ErrorReported))
840     }
841 }
842
843 #[cold]
844 #[inline(never)]
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);
849 }
850
851 #[cold]
852 #[inline(never)]
853 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
854                                         line: u32,
855                                         span: S,
856                                         args: fmt::Arguments) -> ! {
857     opt_span_bug_fmt(file, line, Some(span), args);
858 }
859
860 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
861                                         line: u32,
862                                         span: Option<S>,
863                                         args: fmt::Arguments) -> ! {
864     tls::with_opt(move |tcx| {
865         let msg = format!("{}:{}: {}", file, line, args);
866         match (tcx, span) {
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)
870         }
871     });
872     unreachable!();
873 }