]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
rustc: Don't ICE if we invalidate an invalid incr dir
[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::{BorrowckMode, 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, DiagnosticId};
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<PathBuf>,
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: (PathBuf, bool),
76     pub lint_store: RefCell<lint::LintStore>,
77     pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
78     /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
79     /// (sub)diagnostics that have been set once, but should not be set again,
80     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
81     pub one_time_diagnostics: RefCell<FxHashSet<(DiagnosticMessageId, 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     SpanSuggestion(String), // suggestion
165     // add more variants as needed to support one-time diagnostics
166 }
167
168 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
169 /// emitting the same message more than once
170 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171 pub enum DiagnosticMessageId {
172     ErrorId(u16), // EXXXX error code as integer
173     LintId(lint::LintId),
174     StabilityId(u32) // issue number
175 }
176
177 impl From<&'static lint::Lint> for DiagnosticMessageId {
178     fn from(lint: &'static lint::Lint) -> Self {
179         DiagnosticMessageId::LintId(lint::LintId::of(lint))
180     }
181 }
182
183 impl Session {
184     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
185         match *self.crate_disambiguator.borrow() {
186             Some(value) => value,
187             None => bug!("accessing disambiguator before initialization"),
188         }
189     }
190     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
191                                                     sp: S,
192                                                     msg: &str)
193                                                     -> DiagnosticBuilder<'a> {
194         self.diagnostic().struct_span_warn(sp, msg)
195     }
196     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
197                                                               sp: S,
198                                                               msg: &str,
199                                                               code: DiagnosticId)
200                                                               -> DiagnosticBuilder<'a> {
201         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
202     }
203     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
204         self.diagnostic().struct_warn(msg)
205     }
206     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
207                                                    sp: S,
208                                                    msg: &str)
209                                                    -> DiagnosticBuilder<'a> {
210         self.diagnostic().struct_span_err(sp, msg)
211     }
212     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
213                                                              sp: S,
214                                                              msg: &str,
215                                                              code: DiagnosticId)
216                                                              -> DiagnosticBuilder<'a> {
217         self.diagnostic().struct_span_err_with_code(sp, msg, code)
218     }
219     // FIXME: This method should be removed (every error should have an associated error code).
220     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
221         self.diagnostic().struct_err(msg)
222     }
223     pub fn struct_err_with_code<'a>(
224         &'a self,
225         msg: &str,
226         code: DiagnosticId,
227     ) -> DiagnosticBuilder<'a> {
228         self.diagnostic().struct_err_with_code(msg, code)
229     }
230     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
231                                                      sp: S,
232                                                      msg: &str)
233                                                      -> DiagnosticBuilder<'a> {
234         self.diagnostic().struct_span_fatal(sp, msg)
235     }
236     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
237                                                                sp: S,
238                                                                msg: &str,
239                                                                code: DiagnosticId)
240                                                                -> DiagnosticBuilder<'a> {
241         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
242     }
243     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
244         self.diagnostic().struct_fatal(msg)
245     }
246
247     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
248         panic!(self.diagnostic().span_fatal(sp, msg))
249     }
250     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
251         &self,
252         sp: S,
253         msg: &str,
254         code: DiagnosticId,
255     ) -> ! {
256         panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
257     }
258     pub fn fatal(&self, msg: &str) -> ! {
259         panic!(self.diagnostic().fatal(msg))
260     }
261     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
262         if is_warning {
263             self.span_warn(sp, msg);
264         } else {
265             self.span_err(sp, msg);
266         }
267     }
268     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
269         self.diagnostic().span_err(sp, msg)
270     }
271     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
272         self.diagnostic().span_err_with_code(sp, &msg, code)
273     }
274     pub fn err(&self, msg: &str) {
275         self.diagnostic().err(msg)
276     }
277     pub fn err_count(&self) -> usize {
278         self.diagnostic().err_count()
279     }
280     pub fn has_errors(&self) -> bool {
281         self.diagnostic().has_errors()
282     }
283     pub fn abort_if_errors(&self) {
284         self.diagnostic().abort_if_errors();
285     }
286     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
287         compile_result_from_err_count(self.err_count())
288     }
289     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
290         where F: FnOnce() -> T
291     {
292         let old_count = self.err_count();
293         let result = f();
294         let errors = self.err_count() - old_count;
295         if errors == 0 {
296             Ok(result)
297         } else {
298             Err(ErrorReported)
299         }
300     }
301     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
302         self.diagnostic().span_warn(sp, msg)
303     }
304     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
305         self.diagnostic().span_warn_with_code(sp, msg, code)
306     }
307     pub fn warn(&self, msg: &str) {
308         self.diagnostic().warn(msg)
309     }
310     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
311         match opt_sp {
312             Some(sp) => self.span_warn(sp, msg),
313             None => self.warn(msg),
314         }
315     }
316     /// Delay a span_bug() call until abort_if_errors()
317     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
318         self.diagnostic().delay_span_bug(sp, msg)
319     }
320     pub fn note_without_error(&self, msg: &str) {
321         self.diagnostic().note_without_error(msg)
322     }
323     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
324         self.diagnostic().span_note_without_error(sp, msg)
325     }
326     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
327         self.diagnostic().span_unimpl(sp, msg)
328     }
329     pub fn unimpl(&self, msg: &str) -> ! {
330         self.diagnostic().unimpl(msg)
331     }
332
333     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
334                                            lint: &'static lint::Lint,
335                                            id: ast::NodeId,
336                                            sp: S,
337                                            msg: &str) {
338         match *self.buffered_lints.borrow_mut() {
339             Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg),
340             None => bug!("can't buffer lints after HIR lowering"),
341         }
342     }
343
344     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
345         let id = self.next_node_id.get();
346
347         match id.as_usize().checked_add(count) {
348             Some(next) => {
349                 self.next_node_id.set(ast::NodeId::new(next));
350             }
351             None => bug!("Input too large, ran out of node ids!")
352         }
353
354         id
355     }
356     pub fn next_node_id(&self) -> NodeId {
357         self.reserve_node_ids(1)
358     }
359     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
360         &self.parse_sess.span_diagnostic
361     }
362
363     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
364     /// deduplicates on lint ID, span (if any), and message for this `Session`
365     fn diag_once<'a, 'b>(&'a self,
366                          diag_builder: &'b mut DiagnosticBuilder<'a>,
367                          method: DiagnosticBuilderMethod,
368                          msg_id: DiagnosticMessageId,
369                          message: &str,
370                          span_maybe: Option<Span>) {
371
372         let id_span_message = (msg_id, span_maybe, message.to_owned());
373         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
374         if fresh {
375             match method {
376                 DiagnosticBuilderMethod::Note => {
377                     diag_builder.note(message);
378                 },
379                 DiagnosticBuilderMethod::SpanNote => {
380                     let span = span_maybe.expect("span_note needs a span");
381                     diag_builder.span_note(span, message);
382                 },
383                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
384                     let span = span_maybe.expect("span_suggestion needs a span");
385                     diag_builder.span_suggestion(span, message, suggestion);
386                 }
387             }
388         }
389     }
390
391     pub fn diag_span_note_once<'a, 'b>(&'a self,
392                                        diag_builder: &'b mut DiagnosticBuilder<'a>,
393                                        msg_id: DiagnosticMessageId, span: Span, message: &str) {
394         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
395                        msg_id, message, Some(span));
396     }
397
398     pub fn diag_note_once<'a, 'b>(&'a self,
399                                   diag_builder: &'b mut DiagnosticBuilder<'a>,
400                                   msg_id: DiagnosticMessageId, message: &str) {
401         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
402     }
403
404     pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
405                                              diag_builder: &'b mut DiagnosticBuilder<'a>,
406                                              msg_id: DiagnosticMessageId,
407                                              span: Span,
408                                              message: &str,
409                                              suggestion: String) {
410         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
411                        msg_id, message, Some(span));
412     }
413
414     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
415         self.parse_sess.codemap()
416     }
417     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
418     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
419     pub fn profile_queries(&self) -> bool {
420         self.opts.debugging_opts.profile_queries ||
421             self.opts.debugging_opts.profile_queries_and_keys
422     }
423     pub fn profile_queries_and_keys(&self) -> bool {
424         self.opts.debugging_opts.profile_queries_and_keys
425     }
426     pub fn count_llvm_insns(&self) -> bool {
427         self.opts.debugging_opts.count_llvm_insns
428     }
429     pub fn time_llvm_passes(&self) -> bool {
430         self.opts.debugging_opts.time_llvm_passes
431     }
432     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
433     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
434     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
435     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
436     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
437     pub fn print_llvm_passes(&self) -> bool {
438         self.opts.debugging_opts.print_llvm_passes
439     }
440
441     /// If true, we should use NLL-style region checking instead of
442     /// lexical style.
443     pub fn nll(&self) -> bool {
444         self.features.borrow().nll || self.opts.debugging_opts.nll
445     }
446
447     /// If true, we should use the MIR-based borrowck (we may *also* use
448     /// the AST-based borrowck).
449     pub fn use_mir(&self) -> bool {
450         self.borrowck_mode().use_mir()
451     }
452
453     /// If true, we should gather causal information during NLL
454     /// checking. This will eventually be the normal thing, but right
455     /// now it is too unoptimized.
456     pub fn nll_dump_cause(&self) -> bool {
457         self.opts.debugging_opts.nll_dump_cause
458     }
459
460     /// If true, we should enable two-phase borrows checks. This is
461     /// done with either `-Ztwo-phase-borrows` or with
462     /// `#![feature(nll)]`.
463     pub fn two_phase_borrows(&self) -> bool {
464         self.features.borrow().nll || self.opts.debugging_opts.two_phase_borrows
465     }
466
467     /// What mode(s) of borrowck should we run? AST? MIR? both?
468     /// (Also considers the `#![feature(nll)]` setting.)
469     pub fn borrowck_mode(&self) -> BorrowckMode {
470         match self.opts.borrowck_mode {
471             mode @ BorrowckMode::Mir |
472             mode @ BorrowckMode::Compare => mode,
473
474             mode @ BorrowckMode::Ast => {
475                 if self.nll() {
476                     BorrowckMode::Mir
477                 } else {
478                     mode
479                 }
480             }
481
482         }
483     }
484
485     /// Should we emit EndRegion MIR statements? These are consumed by
486     /// MIR borrowck, but not when NLL is used. They are also consumed
487     /// by the validation stuff.
488     pub fn emit_end_regions(&self) -> bool {
489         // FIXME(#46875) -- we should not emit end regions when NLL is enabled,
490         // but for now we can't stop doing so because it causes false positives
491         self.opts.debugging_opts.emit_end_regions ||
492             self.opts.debugging_opts.mir_emit_validate > 0 ||
493             self.use_mir()
494     }
495
496     pub fn lto(&self) -> bool {
497         self.opts.cg.lto || self.target.target.options.requires_lto
498     }
499     /// Returns the panic strategy for this compile session. If the user explicitly selected one
500     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
501     pub fn panic_strategy(&self) -> PanicStrategy {
502         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
503     }
504     pub fn linker_flavor(&self) -> LinkerFlavor {
505         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
506     }
507     pub fn no_landing_pads(&self) -> bool {
508         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
509     }
510     pub fn unstable_options(&self) -> bool {
511         self.opts.debugging_opts.unstable_options
512     }
513     pub fn nonzeroing_move_hints(&self) -> bool {
514         self.opts.debugging_opts.enable_nonzeroing_move_hints
515     }
516     pub fn overflow_checks(&self) -> bool {
517         self.opts.cg.overflow_checks
518             .or(self.opts.debugging_opts.force_overflow_checks)
519             .unwrap_or(self.opts.debug_assertions)
520     }
521
522     pub fn crt_static(&self) -> bool {
523         // If the target does not opt in to crt-static support, use its default.
524         if self.target.target.options.crt_static_respected {
525             self.crt_static_feature()
526         } else {
527             self.target.target.options.crt_static_default
528         }
529     }
530
531     pub fn crt_static_feature(&self) -> bool {
532         let requested_features = self.opts.cg.target_feature.split(',');
533         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
534         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
535
536         // If the target we're compiling for requests a static crt by default,
537         // then see if the `-crt-static` feature was passed to disable that.
538         // Otherwise if we don't have a static crt by default then see if the
539         // `+crt-static` feature was passed.
540         if self.target.target.options.crt_static_default {
541             !found_negative
542         } else {
543             found_positive
544         }
545     }
546
547     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
548         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
549         !self.target.target.options.eliminate_frame_pointer
550     }
551
552     /// Returns the symbol name for the registrar function,
553     /// given the crate Svh and the function DefIndex.
554     pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator,
555                                             index: DefIndex)
556                                             -> String {
557         format!("__rustc_plugin_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
558                                                    index.as_usize())
559     }
560
561     pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator,
562                                             index: DefIndex)
563                                             -> String {
564         format!("__rustc_derive_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
565                                                    index.as_usize())
566     }
567
568     pub fn sysroot<'a>(&'a self) -> &'a Path {
569         match self.opts.maybe_sysroot {
570             Some (ref sysroot) => sysroot,
571             None => self.default_sysroot.as_ref()
572                         .expect("missing sysroot and default_sysroot in Session")
573         }
574     }
575     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
576         filesearch::FileSearch::new(self.sysroot(),
577                                     &self.opts.target_triple,
578                                     &self.opts.search_paths,
579                                     kind)
580     }
581     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
582         filesearch::FileSearch::new(
583             self.sysroot(),
584             config::host_triple(),
585             &self.opts.search_paths,
586             kind)
587     }
588
589     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
590         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
591
592         match *incr_comp_session {
593             IncrCompSession::Active { ref mut load_dep_graph, .. } => {
594                 *load_dep_graph = load;
595             }
596             _ => {}
597         }
598     }
599
600     pub fn incr_session_load_dep_graph(&self) -> bool {
601         let incr_comp_session = self.incr_comp_session.borrow();
602         match *incr_comp_session {
603             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
604             _ => false,
605         }
606     }
607
608     pub fn init_incr_comp_session(&self,
609                                   session_dir: PathBuf,
610                                   lock_file: flock::Lock,
611                                   load_dep_graph: bool) {
612         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
613
614         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
615             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
616         }
617
618         *incr_comp_session = IncrCompSession::Active {
619             session_directory: session_dir,
620             lock_file,
621             load_dep_graph,
622         };
623     }
624
625     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
626         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
627
628         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
629             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
630         }
631
632         // Note: This will also drop the lock file, thus unlocking the directory
633         *incr_comp_session = IncrCompSession::Finalized {
634             session_directory: new_directory_path,
635         };
636     }
637
638     pub fn mark_incr_comp_session_as_invalid(&self) {
639         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
640
641         let session_directory = match *incr_comp_session {
642             IncrCompSession::Active { ref session_directory, .. } => {
643                 session_directory.clone()
644             }
645             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
646             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
647                       *incr_comp_session),
648         };
649
650         // Note: This will also drop the lock file, thus unlocking the directory
651         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
652             session_directory,
653         };
654     }
655
656     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
657         let incr_comp_session = self.incr_comp_session.borrow();
658         cell::Ref::map(incr_comp_session, |incr_comp_session| {
659             match *incr_comp_session {
660                 IncrCompSession::NotInitialized => {
661                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
662                         *incr_comp_session)
663                 }
664                 IncrCompSession::Active { ref session_directory, .. } |
665                 IncrCompSession::Finalized { ref session_directory } |
666                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
667                     session_directory
668                 }
669             }
670         })
671     }
672
673     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
674         if self.opts.incremental.is_some() {
675             Some(self.incr_comp_session_dir())
676         } else {
677             None
678         }
679     }
680
681     pub fn print_perf_stats(&self) {
682         println!("Total time spent computing SVHs:               {}",
683                  duration_to_secs_str(self.perf_stats.svh_time.get()));
684         println!("Total time spent computing incr. comp. hashes: {}",
685                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
686         println!("Total number of incr. comp. hashes computed:   {}",
687                  self.perf_stats.incr_comp_hashes_count.get());
688         println!("Total number of bytes hashed for incr. comp.:  {}",
689                  self.perf_stats.incr_comp_bytes_hashed.get());
690         if self.perf_stats.incr_comp_hashes_count.get() != 0 {
691             println!("Average bytes hashed per incr. comp. HIR node: {}",
692                     self.perf_stats.incr_comp_bytes_hashed.get() /
693                     self.perf_stats.incr_comp_hashes_count.get());
694         } else {
695             println!("Average bytes hashed per incr. comp. HIR node: N/A");
696         }
697         println!("Total time spent computing symbol hashes:      {}",
698                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
699         println!("Total time spent decoding DefPath tables:      {}",
700                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
701     }
702
703     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
704     /// This expends fuel if applicable, and records fuel if applicable.
705     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
706         let mut ret = true;
707         match self.optimization_fuel_crate {
708             Some(ref c) if c == crate_name => {
709                 let fuel = self.optimization_fuel_limit.get();
710                 ret = fuel != 0;
711                 if fuel == 0 && !self.out_of_fuel.get() {
712                     println!("optimization-fuel-exhausted: {}", msg());
713                     self.out_of_fuel.set(true);
714                 } else if fuel > 0 {
715                     self.optimization_fuel_limit.set(fuel-1);
716                 }
717             }
718             _ => {}
719         }
720         match self.print_fuel_crate {
721             Some(ref c) if c == crate_name=> {
722                 self.print_fuel.set(self.print_fuel.get()+1);
723             },
724             _ => {}
725         }
726         ret
727     }
728
729     /// Returns the number of query threads that should be used for this
730     /// compilation
731     pub fn query_threads(&self) -> usize {
732         self.opts.debugging_opts.query_threads.unwrap_or(1)
733     }
734
735     /// Returns the number of codegen units that should be used for this
736     /// compilation
737     pub fn codegen_units(&self) -> usize {
738         if let Some(n) = self.opts.cli_forced_codegen_units {
739             return n
740         }
741         if let Some(n) = self.target.target.options.default_codegen_units {
742             return n as usize
743         }
744
745         // Why is 16 codegen units the default all the time?
746         //
747         // The main reason for enabling multiple codegen units by default is to
748         // leverage the ability for the trans backend to do translation and
749         // codegen in parallel. This allows us, especially for large crates, to
750         // make good use of all available resources on the machine once we've
751         // hit that stage of compilation. Large crates especially then often
752         // take a long time in trans/codegen and this helps us amortize that
753         // cost.
754         //
755         // Note that a high number here doesn't mean that we'll be spawning a
756         // large number of threads in parallel. The backend of rustc contains
757         // global rate limiting through the `jobserver` crate so we'll never
758         // overload the system with too much work, but rather we'll only be
759         // optimizing when we're otherwise cooperating with other instances of
760         // rustc.
761         //
762         // Rather a high number here means that we should be able to keep a lot
763         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
764         // to build we'll be guaranteed that all cpus will finish pretty closely
765         // to one another and we should make relatively optimal use of system
766         // resources
767         //
768         // Note that the main cost of codegen units is that it prevents LLVM
769         // from inlining across codegen units. Users in general don't have a lot
770         // of control over how codegen units are split up so it's our job in the
771         // compiler to ensure that undue performance isn't lost when using
772         // codegen units (aka we can't require everyone to slap `#[inline]` on
773         // everything).
774         //
775         // If we're compiling at `-O0` then the number doesn't really matter too
776         // much because performance doesn't matter and inlining is ok to lose.
777         // In debug mode we just want to try to guarantee that no cpu is stuck
778         // doing work that could otherwise be farmed to others.
779         //
780         // In release mode, however (O1 and above) performance does indeed
781         // matter! To recover the loss in performance due to inlining we'll be
782         // enabling ThinLTO by default (the function for which is just below).
783         // This will ensure that we recover any inlining wins we otherwise lost
784         // through codegen unit partitioning.
785         //
786         // ---
787         //
788         // Ok that's a lot of words but the basic tl;dr; is that we want a high
789         // number here -- but not too high. Additionally we're "safe" to have it
790         // always at the same number at all optimization levels.
791         //
792         // As a result 16 was chosen here! Mostly because it was a power of 2
793         // and most benchmarks agreed it was roughly a local optimum. Not very
794         // scientific.
795         16
796     }
797
798     /// Returns whether ThinLTO is enabled for this compilation
799     pub fn thinlto(&self) -> bool {
800         // If processing command line options determined that we're incompatible
801         // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
802         if let Some(enabled) = self.opts.cli_forced_thinlto {
803             return enabled
804         }
805
806         // If explicitly specified, use that with the next highest priority
807         if let Some(enabled) = self.opts.debugging_opts.thinlto {
808             return enabled
809         }
810
811         // If there's only one codegen unit and LTO isn't enabled then there's
812         // no need for ThinLTO so just return false.
813         if self.codegen_units() == 1 && !self.lto() {
814             return false
815         }
816
817         // Right now ThinLTO isn't compatible with incremental compilation.
818         if self.opts.incremental.is_some() {
819             return false
820         }
821
822         // Now we're in "defaults" territory. By default we enable ThinLTO for
823         // optimized compiles (anything greater than O0).
824         match self.opts.optimize {
825             config::OptLevel::No => false,
826             _ => true,
827         }
828     }
829 }
830
831 pub fn build_session(sopts: config::Options,
832                      local_crate_source_file: Option<PathBuf>,
833                      registry: errors::registry::Registry)
834                      -> Session {
835     let file_path_mapping = sopts.file_path_mapping();
836
837     build_session_with_codemap(sopts,
838                                local_crate_source_file,
839                                registry,
840                                Rc::new(codemap::CodeMap::new(file_path_mapping)),
841                                None)
842 }
843
844 pub fn build_session_with_codemap(sopts: config::Options,
845                                   local_crate_source_file: Option<PathBuf>,
846                                   registry: errors::registry::Registry,
847                                   codemap: Rc<codemap::CodeMap>,
848                                   emitter_dest: Option<Box<Write + Send>>)
849                                   -> Session {
850     // FIXME: This is not general enough to make the warning lint completely override
851     // normal diagnostic warnings, since the warning lint can also be denied and changed
852     // later via the source code.
853     let warnings_allow = sopts.lint_opts
854         .iter()
855         .filter(|&&(ref key, _)| *key == "warnings")
856         .map(|&(_, ref level)| *level == lint::Allow)
857         .last()
858         .unwrap_or(false);
859     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
860
861     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
862
863     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
864
865     let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
866
867     let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
868         (config::ErrorOutputType::HumanReadable(color_config), None) => {
869             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), false))
870         }
871         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
872             Box::new(EmitterWriter::new(dst, Some(codemap.clone()), false))
873         }
874         (config::ErrorOutputType::Json(pretty), None) => {
875             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(), pretty))
876         }
877         (config::ErrorOutputType::Json(pretty), Some(dst)) => {
878             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(), pretty))
879         }
880         (config::ErrorOutputType::Short(color_config), None) => {
881             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true))
882         }
883         (config::ErrorOutputType::Short(_), Some(dst)) => {
884             Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true))
885         }
886     };
887
888     let diagnostic_handler =
889         errors::Handler::with_emitter_and_flags(
890             emitter,
891             errors::HandlerFlags {
892                 can_emit_warnings,
893                 treat_err_as_bug,
894                 external_macro_backtrace,
895                 .. Default::default()
896             });
897
898     build_session_(sopts,
899                    local_crate_source_file,
900                    diagnostic_handler,
901                    codemap)
902 }
903
904 pub fn build_session_(sopts: config::Options,
905                       local_crate_source_file: Option<PathBuf>,
906                       span_diagnostic: errors::Handler,
907                       codemap: Rc<codemap::CodeMap>)
908                       -> Session {
909     let host = match Target::search(config::host_triple()) {
910         Ok(t) => t,
911         Err(e) => {
912             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
913         }
914     };
915     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
916
917     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
918     let default_sysroot = match sopts.maybe_sysroot {
919         Some(_) => None,
920         None => Some(filesearch::get_or_default_sysroot())
921     };
922
923     let file_path_mapping = sopts.file_path_mapping();
924
925     let local_crate_source_file = local_crate_source_file.map(|path| {
926         file_path_mapping.map_prefix(path).0
927     });
928
929     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
930     let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
931         .map(|i| i.1).unwrap_or(0));
932     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
933     let print_fuel = Cell::new(0);
934
935     let working_dir = match env::current_dir() {
936         Ok(dir) => dir,
937         Err(e) => {
938             panic!(p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)))
939         }
940     };
941     let working_dir = file_path_mapping.map_prefix(working_dir);
942
943     let sess = Session {
944         target: target_cfg,
945         host,
946         opts: sopts,
947         parse_sess: p_s,
948         // For a library crate, this is always none
949         entry_fn: RefCell::new(None),
950         entry_type: Cell::new(None),
951         plugin_registrar_fn: Cell::new(None),
952         derive_registrar_fn: Cell::new(None),
953         default_sysroot,
954         local_crate_source_file,
955         working_dir,
956         lint_store: RefCell::new(lint::LintStore::new()),
957         buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
958         one_time_diagnostics: RefCell::new(FxHashSet()),
959         plugin_llvm_passes: RefCell::new(Vec::new()),
960         plugin_attributes: RefCell::new(Vec::new()),
961         crate_types: RefCell::new(Vec::new()),
962         dependency_formats: RefCell::new(FxHashMap()),
963         crate_disambiguator: RefCell::new(None),
964         features: RefCell::new(feature_gate::Features::new()),
965         recursion_limit: Cell::new(64),
966         type_length_limit: Cell::new(1048576),
967         next_node_id: Cell::new(NodeId::new(1)),
968         injected_allocator: Cell::new(None),
969         allocator_kind: Cell::new(None),
970         injected_panic_runtime: Cell::new(None),
971         imported_macro_spans: RefCell::new(HashMap::new()),
972         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
973         perf_stats: PerfStats {
974             svh_time: Cell::new(Duration::from_secs(0)),
975             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
976             incr_comp_hashes_count: Cell::new(0),
977             incr_comp_bytes_hashed: Cell::new(0),
978             symbol_hash_time: Cell::new(Duration::from_secs(0)),
979             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
980         },
981         code_stats: RefCell::new(CodeStats::new()),
982         optimization_fuel_crate,
983         optimization_fuel_limit,
984         print_fuel_crate,
985         print_fuel,
986         out_of_fuel: Cell::new(false),
987         // Note that this is unsafe because it may misinterpret file descriptors
988         // on Unix as jobserver file descriptors. We hopefully execute this near
989         // the beginning of the process though to ensure we don't get false
990         // positives, or in other words we try to execute this before we open
991         // any file descriptors ourselves.
992         //
993         // Also note that we stick this in a global because there could be
994         // multiple `Session` instances in this process, and the jobserver is
995         // per-process.
996         jobserver_from_env: unsafe {
997             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
998             static INIT: Once = ONCE_INIT;
999             INIT.call_once(|| {
1000                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
1001             });
1002             (*GLOBAL_JOBSERVER).clone()
1003         },
1004         has_global_allocator: Cell::new(false),
1005     };
1006
1007     sess
1008 }
1009
1010 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1011 /// compiler. Together with the crate-name forms a unique global identifier for
1012 /// the crate.
1013 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1014 pub struct CrateDisambiguator(Fingerprint);
1015
1016 impl CrateDisambiguator {
1017     pub fn to_fingerprint(self) -> Fingerprint {
1018         self.0
1019     }
1020 }
1021
1022 impl From<Fingerprint> for CrateDisambiguator {
1023     fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1024         CrateDisambiguator(fingerprint)
1025     }
1026 }
1027
1028 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1029
1030 /// Holds data on the current incremental compilation session, if there is one.
1031 #[derive(Debug)]
1032 pub enum IncrCompSession {
1033     /// This is the state the session will be in until the incr. comp. dir is
1034     /// needed.
1035     NotInitialized,
1036     /// This is the state during which the session directory is private and can
1037     /// be modified.
1038     Active {
1039         session_directory: PathBuf,
1040         lock_file: flock::Lock,
1041         load_dep_graph: bool,
1042     },
1043     /// This is the state after the session directory has been finalized. In this
1044     /// state, the contents of the directory must not be modified any more.
1045     Finalized {
1046         session_directory: PathBuf,
1047     },
1048     /// This is an error state that is reached when some compilation error has
1049     /// occurred. It indicates that the contents of the session directory must
1050     /// not be used, since they might be invalid.
1051     InvalidBecauseOfErrors {
1052         session_directory: PathBuf,
1053     }
1054 }
1055
1056 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1057     let emitter: Box<Emitter> = match output {
1058         config::ErrorOutputType::HumanReadable(color_config) => {
1059             Box::new(EmitterWriter::stderr(color_config, None, false))
1060         }
1061         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1062         config::ErrorOutputType::Short(color_config) => {
1063             Box::new(EmitterWriter::stderr(color_config, None, true))
1064         }
1065     };
1066     let handler = errors::Handler::with_emitter(true, false, emitter);
1067     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1068     panic!(errors::FatalError);
1069 }
1070
1071 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1072     let emitter: Box<Emitter> = match output {
1073         config::ErrorOutputType::HumanReadable(color_config) => {
1074             Box::new(EmitterWriter::stderr(color_config, None, false))
1075         }
1076         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1077         config::ErrorOutputType::Short(color_config) => {
1078             Box::new(EmitterWriter::stderr(color_config, None, true))
1079         }
1080     };
1081     let handler = errors::Handler::with_emitter(true, false, emitter);
1082     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1083 }
1084
1085 #[derive(Copy, Clone, Debug)]
1086 pub enum CompileIncomplete {
1087     Stopped,
1088     Errored(ErrorReported)
1089 }
1090 impl From<ErrorReported> for CompileIncomplete {
1091     fn from(err: ErrorReported) -> CompileIncomplete {
1092         CompileIncomplete::Errored(err)
1093     }
1094 }
1095 pub type CompileResult = Result<(), CompileIncomplete>;
1096
1097 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1098     if err_count == 0 {
1099         Ok(())
1100     } else {
1101         Err(CompileIncomplete::Errored(ErrorReported))
1102     }
1103 }
1104
1105 #[cold]
1106 #[inline(never)]
1107 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1108     // this wrapper mostly exists so I don't have to write a fully
1109     // qualified path of None::<Span> inside the bug!() macro definition
1110     opt_span_bug_fmt(file, line, None::<Span>, args);
1111 }
1112
1113 #[cold]
1114 #[inline(never)]
1115 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1116                                         line: u32,
1117                                         span: S,
1118                                         args: fmt::Arguments) -> ! {
1119     opt_span_bug_fmt(file, line, Some(span), args);
1120 }
1121
1122 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1123                                         line: u32,
1124                                         span: Option<S>,
1125                                         args: fmt::Arguments) -> ! {
1126     tls::with_opt(move |tcx| {
1127         let msg = format!("{}:{}: {}", file, line, args);
1128         match (tcx, span) {
1129             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1130             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1131             (None, _) => panic!(msg)
1132         }
1133     });
1134     unreachable!();
1135 }