]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
Rollup merge of #44562 - eddyb:ugh-rustdoc, r=nikomatsakis
[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
16 use lint;
17 use middle::allocator::AllocatorKind;
18 use middle::dependency_format;
19 use session::search_paths::PathKind;
20 use session::config::DebugInfoLevel;
21 use ty::tls;
22 use util::nodemap::{FxHashMap, FxHashSet};
23 use util::common::{duration_to_secs_str, ErrorReported};
24
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;
30 use syntax::parse;
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};
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     // The path is always expected to be absolute. `None` means that there is no
72     // source file.
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>,
94
95     /// The maximum recursion limit for potentially infinitely recursive
96     /// operations such as auto-dereference and monomorphization.
97     pub recursion_limit: Cell<usize>,
98
99     /// The maximum length of types during monomorphization.
100     pub type_length_limit: Cell<usize>,
101
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
104     /// injected.
105     pub injected_allocator: Cell<Option<CrateNum>>,
106     pub allocator_kind: Cell<Option<AllocatorKind>>,
107     pub injected_panic_runtime: Cell<Option<CrateNum>>,
108
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)>>,
113
114     incr_comp_session: RefCell<IncrCompSession>,
115
116     /// Some measurements that are being gathered during compilation.
117     pub perf_stats: PerfStats,
118
119     /// Data about code being compiled, gathered during compilation.
120     pub code_stats: RefCell<CodeStats>,
121
122     next_node_id: Cell<ast::NodeId>,
123
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>,
130
131     // The next two are public because the driver needs to read them.
132
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>,
137
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>,
141
142     /// Metadata about the allocators for the current crate being compiled
143     pub has_global_allocator: Cell<bool>,
144 }
145
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>,
159 }
160
161 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
162 enum DiagnosticBuilderMethod {
163     Note,
164     SpanNote,
165     // add more variants as needed to support one-time diagnostics
166 }
167
168 impl Session {
169     pub fn local_crate_disambiguator(&self) -> Symbol {
170         match *self.crate_disambiguator.borrow() {
171             Some(sym) => sym,
172             None => bug!("accessing disambiguator before initialization"),
173         }
174     }
175     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
176                                                     sp: S,
177                                                     msg: &str)
178                                                     -> DiagnosticBuilder<'a> {
179         self.diagnostic().struct_span_warn(sp, msg)
180     }
181     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
182                                                               sp: S,
183                                                               msg: &str,
184                                                               code: &str)
185                                                               -> DiagnosticBuilder<'a> {
186         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
187     }
188     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
189         self.diagnostic().struct_warn(msg)
190     }
191     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
192                                                    sp: S,
193                                                    msg: &str)
194                                                    -> DiagnosticBuilder<'a> {
195         self.diagnostic().struct_span_err(sp, msg)
196     }
197     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
198                                                              sp: S,
199                                                              msg: &str,
200                                                              code: &str)
201                                                              -> DiagnosticBuilder<'a> {
202         self.diagnostic().struct_span_err_with_code(sp, msg, code)
203     }
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)
207     }
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)
210     }
211     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
212                                                      sp: S,
213                                                      msg: &str)
214                                                      -> DiagnosticBuilder<'a> {
215         self.diagnostic().struct_span_fatal(sp, msg)
216     }
217     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
218                                                                sp: S,
219                                                                msg: &str,
220                                                                code: &str)
221                                                                -> DiagnosticBuilder<'a> {
222         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
223     }
224     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
225         self.diagnostic().struct_fatal(msg)
226     }
227
228     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
229         panic!(self.diagnostic().span_fatal(sp, msg))
230     }
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))
233     }
234     pub fn fatal(&self, msg: &str) -> ! {
235         panic!(self.diagnostic().fatal(msg))
236     }
237     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
238         if is_warning {
239             self.span_warn(sp, msg);
240         } else {
241             self.span_err(sp, msg);
242         }
243     }
244     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
245         self.diagnostic().span_err(sp, msg)
246     }
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)
249     }
250     pub fn err(&self, msg: &str) {
251         self.diagnostic().err(msg)
252     }
253     pub fn err_count(&self) -> usize {
254         self.diagnostic().err_count()
255     }
256     pub fn has_errors(&self) -> bool {
257         self.diagnostic().has_errors()
258     }
259     pub fn abort_if_errors(&self) {
260         self.diagnostic().abort_if_errors();
261     }
262     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
263         compile_result_from_err_count(self.err_count())
264     }
265     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
266         where F: FnOnce() -> T
267     {
268         let old_count = self.err_count();
269         let result = f();
270         let errors = self.err_count() - old_count;
271         if errors == 0 {
272             Ok(result)
273         } else {
274             Err(ErrorReported)
275         }
276     }
277     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
278         self.diagnostic().span_warn(sp, msg)
279     }
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)
282     }
283     pub fn warn(&self, msg: &str) {
284         self.diagnostic().warn(msg)
285     }
286     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
287         match opt_sp {
288             Some(sp) => self.span_warn(sp, msg),
289             None => self.warn(msg),
290         }
291     }
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)
295     }
296     pub fn note_without_error(&self, msg: &str) {
297         self.diagnostic().note_without_error(msg)
298     }
299     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
300         self.diagnostic().span_note_without_error(sp, msg)
301     }
302     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
303         self.diagnostic().span_unimpl(sp, msg)
304     }
305     pub fn unimpl(&self, msg: &str) -> ! {
306         self.diagnostic().unimpl(msg)
307     }
308
309     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
310                                            lint: &'static lint::Lint,
311                                            id: ast::NodeId,
312                                            sp: S,
313                                            msg: &str) {
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"),
317         }
318     }
319
320     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
321         let id = self.next_node_id.get();
322
323         match id.as_usize().checked_add(count) {
324             Some(next) => {
325                 self.next_node_id.set(ast::NodeId::new(next));
326             }
327             None => bug!("Input too large, ran out of node ids!")
328         }
329
330         id
331     }
332     pub fn next_node_id(&self) -> NodeId {
333         self.reserve_node_ids(1)
334     }
335     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
336         &self.parse_sess.span_diagnostic
337     }
338
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 = || {
347             match method {
348                 DiagnosticBuilderMethod::Note => {
349                     diag_builder.note(message);
350                 },
351                 DiagnosticBuilderMethod::SpanNote => {
352                     diag_builder.span_note(span.expect("span_note expects a span"), message);
353                 }
354             }
355         };
356
357         match self.opts.error_format {
358             // when outputting JSON for tool consumption, the tool might want
359             // the duplicates
360             config::ErrorOutputType::Json => {
361                 do_method()
362             },
363             _ => {
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);
367                 if fresh {
368                     do_method()
369                 }
370             }
371         }
372     }
373
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));
378     }
379
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);
384     }
385
386     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
387         self.parse_sess.codemap()
388     }
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
394     }
395     pub fn profile_queries_and_keys(&self) -> bool {
396         self.opts.debugging_opts.profile_queries_and_keys
397     }
398     pub fn count_llvm_insns(&self) -> bool {
399         self.opts.debugging_opts.count_llvm_insns
400     }
401     pub fn time_llvm_passes(&self) -> bool {
402         self.opts.debugging_opts.time_llvm_passes
403     }
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
411     }
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)
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: Symbol, index: DefIndex)
475                                             -> String {
476         format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
477     }
478
479     pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
480                                             -> String {
481         format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
482     }
483
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")
489         }
490     }
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,
495                                     kind)
496     }
497     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
498         filesearch::FileSearch::new(
499             self.sysroot(),
500             config::host_triple(),
501             &self.opts.search_paths,
502             kind)
503     }
504
505     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
506         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
507
508         match *incr_comp_session {
509             IncrCompSession::Active { ref mut load_dep_graph, .. } => {
510                 *load_dep_graph = load;
511             }
512             _ => {}
513         }
514     }
515
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,
520             _ => false,
521         }
522     }
523
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();
529
530         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
531             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
532         }
533
534         *incr_comp_session = IncrCompSession::Active {
535             session_directory: session_dir,
536             lock_file,
537             load_dep_graph,
538         };
539     }
540
541     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
542         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
543
544         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
545             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
546         }
547
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,
551         };
552     }
553
554     pub fn mark_incr_comp_session_as_invalid(&self) {
555         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
556
557         let session_directory = match *incr_comp_session {
558             IncrCompSession::Active { ref session_directory, .. } => {
559                 session_directory.clone()
560             }
561             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
562                       *incr_comp_session),
563         };
564
565         // Note: This will also drop the lock file, thus unlocking the directory
566         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
567             session_directory,
568         };
569     }
570
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 `{:?}`",
577                         *incr_comp_session)
578                 }
579                 IncrCompSession::Active { ref session_directory, .. } |
580                 IncrCompSession::Finalized { ref session_directory } |
581                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
582                     session_directory
583                 }
584             }
585         })
586     }
587
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())
591         } else {
592             None
593         }
594     }
595
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()));
612     }
613
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 {
617         let mut ret = true;
618         match self.optimization_fuel_crate {
619             Some(ref c) if c == crate_name => {
620                 let fuel = self.optimization_fuel_limit.get();
621                 ret = fuel != 0;
622                 if fuel == 0 && !self.out_of_fuel.get() {
623                     println!("optimization-fuel-exhausted: {}", msg());
624                     self.out_of_fuel.set(true);
625                 } else if fuel > 0 {
626                     self.optimization_fuel_limit.set(fuel-1);
627                 }
628             }
629             _ => {}
630         }
631         match self.print_fuel_crate {
632             Some(ref c) if c == crate_name=> {
633                 self.print_fuel.set(self.print_fuel.get()+1);
634             },
635             _ => {}
636         }
637         ret
638     }
639 }
640
641 pub fn build_session(sopts: config::Options,
642                      local_crate_source_file: Option<PathBuf>,
643                      registry: errors::registry::Registry)
644                      -> Session {
645     let file_path_mapping = sopts.file_path_mapping();
646
647     build_session_with_codemap(sopts,
648                                local_crate_source_file,
649                                registry,
650                                Rc::new(codemap::CodeMap::new(file_path_mapping)),
651                                None)
652 }
653
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>>)
659                                   -> Session {
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
664         .iter()
665         .filter(|&&(ref key, _)| *key == "warnings")
666         .map(|&(_, ref level)| *level != lint::Allow)
667         .last()
668         .unwrap_or(true);
669     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
670
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())))
675         }
676         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
677             Box::new(EmitterWriter::new(dst,
678                                         Some(codemap.clone())))
679         }
680         (config::ErrorOutputType::Json, None) => {
681             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
682         }
683         (config::ErrorOutputType::Json, Some(dst)) => {
684             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
685         }
686     };
687
688     let diagnostic_handler =
689         errors::Handler::with_emitter(can_print_warnings,
690                                       treat_err_as_bug,
691                                       emitter);
692
693     build_session_(sopts,
694                    local_crate_source_file,
695                    diagnostic_handler,
696                    codemap)
697 }
698
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>)
703                       -> Session {
704     let host = match Target::search(config::host_triple()) {
705         Ok(t) => t,
706         Err(e) => {
707             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
708         }
709     };
710     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
711
712     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
713     let default_sysroot = match sopts.maybe_sysroot {
714         Some(_) => None,
715         None => Some(filesearch::get_or_default_sysroot())
716     };
717
718     let file_path_mapping = sopts.file_path_mapping();
719
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
723     });
724
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);
730
731     let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
732     let working_dir = file_path_mapping.map_prefix(working_dir);
733
734     let sess = Session {
735         target: target_cfg,
736         host,
737         opts: sopts,
738         parse_sess: p_s,
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),
744         default_sysroot,
745         local_crate_source_file,
746         working_dir,
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)),
771         },
772         code_stats: RefCell::new(CodeStats::new()),
773         optimization_fuel_crate,
774         optimization_fuel_limit,
775         print_fuel_crate,
776         print_fuel,
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.
783         //
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
786         // per-process.
787         jobserver_from_env: unsafe {
788             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
789             static INIT: Once = ONCE_INIT;
790             INIT.call_once(|| {
791                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
792             });
793             (*GLOBAL_JOBSERVER).clone()
794         },
795         has_global_allocator: Cell::new(false),
796     };
797
798     sess
799 }
800
801 /// Holds data on the current incremental compilation session, if there is one.
802 #[derive(Debug)]
803 pub enum IncrCompSession {
804     // This is the state the session will be in until the incr. comp. dir is
805     // needed.
806     NotInitialized,
807     // This is the state during which the session directory is private and can
808     // be modified.
809     Active {
810         session_directory: PathBuf,
811         lock_file: flock::Lock,
812         load_dep_graph: bool,
813     },
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.
816     Finalized {
817         session_directory: PathBuf,
818     },
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,
824     }
825 }
826
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,
831                                            None))
832         }
833         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
834     };
835     let handler = errors::Handler::with_emitter(true, false, emitter);
836     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
837     panic!(errors::FatalError);
838 }
839
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,
844                                            None))
845         }
846         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
847     };
848     let handler = errors::Handler::with_emitter(true, false, emitter);
849     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
850 }
851
852 #[derive(Copy, Clone, Debug)]
853 pub enum CompileIncomplete {
854     Stopped,
855     Errored(ErrorReported)
856 }
857 impl From<ErrorReported> for CompileIncomplete {
858     fn from(err: ErrorReported) -> CompileIncomplete {
859         CompileIncomplete::Errored(err)
860     }
861 }
862 pub type CompileResult = Result<(), CompileIncomplete>;
863
864 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
865     if err_count == 0 {
866         Ok(())
867     } else {
868         Err(CompileIncomplete::Errored(ErrorReported))
869     }
870 }
871
872 #[cold]
873 #[inline(never)]
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);
878 }
879
880 #[cold]
881 #[inline(never)]
882 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
883                                         line: u32,
884                                         span: S,
885                                         args: fmt::Arguments) -> ! {
886     opt_span_bug_fmt(file, line, Some(span), args);
887 }
888
889 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
890                                         line: u32,
891                                         span: Option<S>,
892                                         args: fmt::Arguments) -> ! {
893     tls::with_opt(move |tcx| {
894         let msg = format!("{}:{}: {}", file, line, args);
895         match (tcx, span) {
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)
899         }
900     });
901     unreachable!();
902 }