]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
Auto merge of #42709 - stepancheg:discriminant-hash, r=jseyfried
[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::dependency_format;
20 use session::search_paths::PathKind;
21 use session::config::DebugInfoLevel;
22 use ty::tls;
23 use util::nodemap::{FxHashMap, FxHashSet};
24 use util::common::duration_to_secs_str;
25
26 use syntax::ast::NodeId;
27 use errors::{self, DiagnosticBuilder};
28 use errors::emitter::{Emitter, EmitterWriter};
29 use syntax::json::JsonEmitter;
30 use syntax::feature_gate;
31 use syntax::parse;
32 use syntax::parse::ParseSess;
33 use syntax::symbol::Symbol;
34 use syntax::{ast, codemap};
35 use syntax::feature_gate::AttributeType;
36 use syntax_pos::{Span, MultiSpan};
37
38 use rustc_back::{LinkerFlavor, PanicStrategy};
39 use rustc_back::target::Target;
40 use rustc_data_structures::flock;
41 use jobserver::Client;
42
43 use std::cell::{self, Cell, RefCell};
44 use std::collections::HashMap;
45 use std::env;
46 use std::fmt;
47 use std::io::Write;
48 use std::path::{Path, PathBuf};
49 use std::rc::Rc;
50 use std::sync::{Once, ONCE_INIT};
51 use std::time::Duration;
52
53 mod code_stats;
54 pub mod config;
55 pub mod filesearch;
56 pub mod search_paths;
57
58 // Represents the data associated with a compilation
59 // session for a single crate.
60 pub struct Session {
61     pub dep_graph: DepGraph,
62     pub target: config::Config,
63     pub host: Target,
64     pub opts: config::Options,
65     pub cstore: Rc<CrateStore>,
66     pub parse_sess: ParseSess,
67     // For a library crate, this is always none
68     pub entry_fn: RefCell<Option<(NodeId, Span)>>,
69     pub entry_type: Cell<Option<config::EntryFnType>>,
70     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
71     pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
72     pub default_sysroot: Option<PathBuf>,
73     // The name of the root source file of the crate, in the local file system.
74     // The path is always expected to be absolute. `None` means that there is no
75     // source file.
76     pub local_crate_source_file: Option<String>,
77     // The directory the compiler has been executed in plus a flag indicating
78     // if the value stored here has been affected by path remapping.
79     pub working_dir: (String, bool),
80     pub lint_store: RefCell<lint::LintStore>,
81     pub lints: RefCell<lint::LintTable>,
82     /// Set of (LintId, span, message) tuples tracking lint (sub)diagnostics
83     /// that have been set once, but should not be set again, in order to avoid
84     /// redundantly verbose output (Issue #24690).
85     pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Span, String)>>,
86     pub plugin_llvm_passes: RefCell<Vec<String>>,
87     pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
88     pub crate_types: RefCell<Vec<config::CrateType>>,
89     pub dependency_formats: RefCell<dependency_format::Dependencies>,
90     // The crate_disambiguator is constructed out of all the `-C metadata`
91     // arguments passed to the compiler. Its value together with the crate-name
92     // forms a unique global identifier for the crate. It is used to allow
93     // multiple crates with the same name to coexist. See the
94     // trans::back::symbol_names module for more information.
95     pub crate_disambiguator: RefCell<Symbol>,
96     pub features: RefCell<feature_gate::Features>,
97
98     /// The maximum recursion limit for potentially infinitely recursive
99     /// operations such as auto-dereference and monomorphization.
100     pub recursion_limit: Cell<usize>,
101
102     /// The maximum length of types during monomorphization.
103     pub type_length_limit: Cell<usize>,
104
105     /// The metadata::creader module may inject an allocator/panic_runtime
106     /// dependency if it didn't already find one, and this tracks what was
107     /// injected.
108     pub injected_allocator: Cell<Option<CrateNum>>,
109     pub injected_panic_runtime: Cell<Option<CrateNum>>,
110
111     /// Map from imported macro spans (which consist of
112     /// the localized span for the macro body) to the
113     /// macro name and defintion span in the source crate.
114     pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
115
116     incr_comp_session: RefCell<IncrCompSession>,
117
118     /// Some measurements that are being gathered during compilation.
119     pub perf_stats: PerfStats,
120
121     /// Data about code being compiled, gathered during compilation.
122     pub code_stats: RefCell<CodeStats>,
123
124     next_node_id: Cell<ast::NodeId>,
125
126     /// If -zfuel=crate=n is specified, Some(crate).
127     optimization_fuel_crate: Option<String>,
128     /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
129     optimization_fuel_limit: Cell<u64>,
130     /// We're rejecting all further optimizations.
131     out_of_fuel: Cell<bool>,
132
133     // The next two are public because the driver needs to read them.
134
135     /// If -zprint-fuel=crate, Some(crate).
136     pub print_fuel_crate: Option<String>,
137     /// Always set to zero and incremented so that we can print fuel expended by a crate.
138     pub print_fuel: Cell<u64>,
139
140     /// Loaded up early on in the initialization of this `Session` to avoid
141     /// false positives about a job server in our environment.
142     pub jobserver_from_env: Option<Client>,
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 impl Session {
161     pub fn local_crate_disambiguator(&self) -> Symbol {
162         *self.crate_disambiguator.borrow()
163     }
164     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
165                                                     sp: S,
166                                                     msg: &str)
167                                                     -> DiagnosticBuilder<'a> {
168         self.diagnostic().struct_span_warn(sp, msg)
169     }
170     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
171                                                               sp: S,
172                                                               msg: &str,
173                                                               code: &str)
174                                                               -> DiagnosticBuilder<'a> {
175         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
176     }
177     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
178         self.diagnostic().struct_warn(msg)
179     }
180     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
181                                                    sp: S,
182                                                    msg: &str)
183                                                    -> DiagnosticBuilder<'a> {
184         self.diagnostic().struct_span_err(sp, msg)
185     }
186     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
187                                                              sp: S,
188                                                              msg: &str,
189                                                              code: &str)
190                                                              -> DiagnosticBuilder<'a> {
191         self.diagnostic().struct_span_err_with_code(sp, msg, code)
192     }
193     // FIXME: This method should be removed (every error should have an associated error code).
194     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
195         self.diagnostic().struct_err(msg)
196     }
197     pub fn struct_err_with_code<'a>(&'a self, msg: &str, code: &str) -> DiagnosticBuilder<'a> {
198         self.diagnostic().struct_err_with_code(msg, code)
199     }
200     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
201                                                      sp: S,
202                                                      msg: &str)
203                                                      -> DiagnosticBuilder<'a> {
204         self.diagnostic().struct_span_fatal(sp, msg)
205     }
206     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
207                                                                sp: S,
208                                                                msg: &str,
209                                                                code: &str)
210                                                                -> DiagnosticBuilder<'a> {
211         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
212     }
213     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
214         self.diagnostic().struct_fatal(msg)
215     }
216
217     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
218         panic!(self.diagnostic().span_fatal(sp, msg))
219     }
220     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
221         panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
222     }
223     pub fn fatal(&self, msg: &str) -> ! {
224         panic!(self.diagnostic().fatal(msg))
225     }
226     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
227         if is_warning {
228             self.span_warn(sp, msg);
229         } else {
230             self.span_err(sp, msg);
231         }
232     }
233     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
234         self.diagnostic().span_err(sp, msg)
235     }
236     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
237         self.diagnostic().span_err_with_code(sp, &msg, code)
238     }
239     pub fn err(&self, msg: &str) {
240         self.diagnostic().err(msg)
241     }
242     pub fn err_count(&self) -> usize {
243         self.diagnostic().err_count()
244     }
245     pub fn has_errors(&self) -> bool {
246         self.diagnostic().has_errors()
247     }
248     pub fn abort_if_errors(&self) {
249         self.diagnostic().abort_if_errors();
250     }
251     pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
252         where F: FnOnce() -> T
253     {
254         let old_count = self.err_count();
255         let result = f();
256         let errors = self.err_count() - old_count;
257         if errors == 0 {
258             Ok(result)
259         } else {
260             Err(errors)
261         }
262     }
263     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
264         self.diagnostic().span_warn(sp, msg)
265     }
266     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
267         self.diagnostic().span_warn_with_code(sp, msg, code)
268     }
269     pub fn warn(&self, msg: &str) {
270         self.diagnostic().warn(msg)
271     }
272     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
273         match opt_sp {
274             Some(sp) => self.span_warn(sp, msg),
275             None => self.warn(msg),
276         }
277     }
278     /// Delay a span_bug() call until abort_if_errors()
279     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
280         self.diagnostic().delay_span_bug(sp, msg)
281     }
282     pub fn note_without_error(&self, msg: &str) {
283         self.diagnostic().note_without_error(msg)
284     }
285     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
286         self.diagnostic().span_note_without_error(sp, msg)
287     }
288     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
289         self.diagnostic().span_unimpl(sp, msg)
290     }
291     pub fn unimpl(&self, msg: &str) -> ! {
292         self.diagnostic().unimpl(msg)
293     }
294
295     pub fn add_lint<S: Into<MultiSpan>>(&self,
296                                         lint: &'static lint::Lint,
297                                         id: ast::NodeId,
298                                         sp: S,
299                                         msg: String)
300     {
301         self.lints.borrow_mut().add_lint(lint, id, sp, msg);
302     }
303
304     pub fn add_lint_diagnostic<M>(&self,
305                                   lint: &'static lint::Lint,
306                                   id: ast::NodeId,
307                                   msg: M)
308         where M: lint::IntoEarlyLint,
309     {
310         self.lints.borrow_mut().add_lint_diagnostic(lint, id, msg);
311     }
312
313     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
314         let id = self.next_node_id.get();
315
316         match id.as_usize().checked_add(count) {
317             Some(next) => {
318                 self.next_node_id.set(ast::NodeId::new(next));
319             }
320             None => bug!("Input too large, ran out of node ids!")
321         }
322
323         id
324     }
325     pub fn next_node_id(&self) -> NodeId {
326         self.reserve_node_ids(1)
327     }
328     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
329         &self.parse_sess.span_diagnostic
330     }
331
332     /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but
333     /// deduplicates on lint ID, span, and message for this `Session` if we're
334     /// not outputting in JSON mode.
335     //
336     // FIXME: if the need arises for one-time diagnostics other than
337     // `span_note`, we almost certainly want to generalize this
338     // "check/insert-into the one-time diagnostics map, then set message if
339     // it's not already there" code to accomodate all of them
340     pub fn diag_span_note_once<'a, 'b>(&'a self,
341                                        diag_builder: &'b mut DiagnosticBuilder<'a>,
342                                        lint: &'static lint::Lint, span: Span, message: &str) {
343         match self.opts.error_format {
344             // when outputting JSON for tool consumption, the tool might want
345             // the duplicates
346             config::ErrorOutputType::Json => {
347                 diag_builder.span_note(span, &message);
348             },
349             _ => {
350                 let lint_id = lint::LintId::of(lint);
351                 let id_span_message = (lint_id, span, message.to_owned());
352                 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
353                 if fresh {
354                     diag_builder.span_note(span, &message);
355                 }
356             }
357         }
358     }
359
360     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
361         self.parse_sess.codemap()
362     }
363     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
364     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
365     pub fn count_llvm_insns(&self) -> bool {
366         self.opts.debugging_opts.count_llvm_insns
367     }
368     pub fn time_llvm_passes(&self) -> bool {
369         self.opts.debugging_opts.time_llvm_passes
370     }
371     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
372     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
373     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
374     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
375     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
376     pub fn print_llvm_passes(&self) -> bool {
377         self.opts.debugging_opts.print_llvm_passes
378     }
379     pub fn lto(&self) -> bool {
380         self.opts.cg.lto
381     }
382     /// Returns the panic strategy for this compile session. If the user explicitly selected one
383     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
384     pub fn panic_strategy(&self) -> PanicStrategy {
385         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
386     }
387     pub fn linker_flavor(&self) -> LinkerFlavor {
388         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
389     }
390     pub fn no_landing_pads(&self) -> bool {
391         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
392     }
393     pub fn unstable_options(&self) -> bool {
394         self.opts.debugging_opts.unstable_options
395     }
396     pub fn nonzeroing_move_hints(&self) -> bool {
397         self.opts.debugging_opts.enable_nonzeroing_move_hints
398     }
399     pub fn overflow_checks(&self) -> bool {
400         self.opts.cg.overflow_checks
401             .or(self.opts.debugging_opts.force_overflow_checks)
402             .unwrap_or(self.opts.debug_assertions)
403     }
404
405     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
406         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
407         !self.target.target.options.eliminate_frame_pointer
408     }
409
410     /// Returns the symbol name for the registrar function,
411     /// given the crate Svh and the function DefIndex.
412     pub fn generate_plugin_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
413                                             -> String {
414         format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
415     }
416
417     pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
418                                             -> String {
419         format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
420     }
421
422     pub fn sysroot<'a>(&'a self) -> &'a Path {
423         match self.opts.maybe_sysroot {
424             Some (ref sysroot) => sysroot,
425             None => self.default_sysroot.as_ref()
426                         .expect("missing sysroot and default_sysroot in Session")
427         }
428     }
429     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
430         filesearch::FileSearch::new(self.sysroot(),
431                                     &self.opts.target_triple,
432                                     &self.opts.search_paths,
433                                     kind)
434     }
435     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
436         filesearch::FileSearch::new(
437             self.sysroot(),
438             config::host_triple(),
439             &self.opts.search_paths,
440             kind)
441     }
442
443     pub fn init_incr_comp_session(&self,
444                                   session_dir: PathBuf,
445                                   lock_file: flock::Lock) {
446         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
447
448         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
449             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
450         }
451
452         *incr_comp_session = IncrCompSession::Active {
453             session_directory: session_dir,
454             lock_file: lock_file,
455         };
456     }
457
458     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
459         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
460
461         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
462             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
463         }
464
465         // Note: This will also drop the lock file, thus unlocking the directory
466         *incr_comp_session = IncrCompSession::Finalized {
467             session_directory: new_directory_path,
468         };
469     }
470
471     pub fn mark_incr_comp_session_as_invalid(&self) {
472         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
473
474         let session_directory = match *incr_comp_session {
475             IncrCompSession::Active { ref session_directory, .. } => {
476                 session_directory.clone()
477             }
478             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
479                       *incr_comp_session),
480         };
481
482         // Note: This will also drop the lock file, thus unlocking the directory
483         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
484             session_directory: session_directory
485         };
486     }
487
488     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
489         let incr_comp_session = self.incr_comp_session.borrow();
490         cell::Ref::map(incr_comp_session, |incr_comp_session| {
491             match *incr_comp_session {
492                 IncrCompSession::NotInitialized => {
493                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
494                         *incr_comp_session)
495                 }
496                 IncrCompSession::Active { ref session_directory, .. } |
497                 IncrCompSession::Finalized { ref session_directory } |
498                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
499                     session_directory
500                 }
501             }
502         })
503     }
504
505     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
506         if self.opts.incremental.is_some() {
507             Some(self.incr_comp_session_dir())
508         } else {
509             None
510         }
511     }
512
513     pub fn print_perf_stats(&self) {
514         println!("Total time spent computing SVHs:               {}",
515                  duration_to_secs_str(self.perf_stats.svh_time.get()));
516         println!("Total time spent computing incr. comp. hashes: {}",
517                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
518         println!("Total number of incr. comp. hashes computed:   {}",
519                  self.perf_stats.incr_comp_hashes_count.get());
520         println!("Total number of bytes hashed for incr. comp.:  {}",
521                  self.perf_stats.incr_comp_bytes_hashed.get());
522         println!("Average bytes hashed per incr. comp. HIR node: {}",
523                  self.perf_stats.incr_comp_bytes_hashed.get() /
524                  self.perf_stats.incr_comp_hashes_count.get());
525         println!("Total time spent computing symbol hashes:      {}",
526                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
527         println!("Total time spent decoding DefPath tables:      {}",
528                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
529     }
530
531     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
532     /// This expends fuel if applicable, and records fuel if applicable.
533     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
534         let mut ret = true;
535         match self.optimization_fuel_crate {
536             Some(ref c) if c == crate_name => {
537                 let fuel = self.optimization_fuel_limit.get();
538                 ret = fuel != 0;
539                 if fuel == 0 && !self.out_of_fuel.get() {
540                     println!("optimization-fuel-exhausted: {}", msg());
541                     self.out_of_fuel.set(true);
542                 } else if fuel > 0 {
543                     self.optimization_fuel_limit.set(fuel-1);
544                 }
545             }
546             _ => {}
547         }
548         match self.print_fuel_crate {
549             Some(ref c) if c == crate_name=> {
550                 self.print_fuel.set(self.print_fuel.get()+1);
551             },
552             _ => {}
553         }
554         ret
555     }
556 }
557
558 pub fn build_session(sopts: config::Options,
559                      dep_graph: &DepGraph,
560                      local_crate_source_file: Option<PathBuf>,
561                      registry: errors::registry::Registry,
562                      cstore: Rc<CrateStore>)
563                      -> Session {
564     let file_path_mapping = sopts.file_path_mapping();
565
566     build_session_with_codemap(sopts,
567                                dep_graph,
568                                local_crate_source_file,
569                                registry,
570                                cstore,
571                                Rc::new(codemap::CodeMap::new(file_path_mapping)),
572                                None)
573 }
574
575 pub fn build_session_with_codemap(sopts: config::Options,
576                                   dep_graph: &DepGraph,
577                                   local_crate_source_file: Option<PathBuf>,
578                                   registry: errors::registry::Registry,
579                                   cstore: Rc<CrateStore>,
580                                   codemap: Rc<codemap::CodeMap>,
581                                   emitter_dest: Option<Box<Write + Send>>)
582                                   -> Session {
583     // FIXME: This is not general enough to make the warning lint completely override
584     // normal diagnostic warnings, since the warning lint can also be denied and changed
585     // later via the source code.
586     let can_print_warnings = sopts.lint_opts
587         .iter()
588         .filter(|&&(ref key, _)| *key == "warnings")
589         .map(|&(_, ref level)| *level != lint::Allow)
590         .last()
591         .unwrap_or(true);
592     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
593
594     let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
595         (config::ErrorOutputType::HumanReadable(color_config), None) => {
596             Box::new(EmitterWriter::stderr(color_config,
597                                            Some(codemap.clone())))
598         }
599         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
600             Box::new(EmitterWriter::new(dst,
601                                         Some(codemap.clone())))
602         }
603         (config::ErrorOutputType::Json, None) => {
604             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
605         }
606         (config::ErrorOutputType::Json, Some(dst)) => {
607             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
608         }
609     };
610
611     let diagnostic_handler =
612         errors::Handler::with_emitter(can_print_warnings,
613                                       treat_err_as_bug,
614                                       emitter);
615
616     build_session_(sopts,
617                    dep_graph,
618                    local_crate_source_file,
619                    diagnostic_handler,
620                    codemap,
621                    cstore)
622 }
623
624 pub fn build_session_(sopts: config::Options,
625                       dep_graph: &DepGraph,
626                       local_crate_source_file: Option<PathBuf>,
627                       span_diagnostic: errors::Handler,
628                       codemap: Rc<codemap::CodeMap>,
629                       cstore: Rc<CrateStore>)
630                       -> Session {
631     let host = match Target::search(config::host_triple()) {
632         Ok(t) => t,
633         Err(e) => {
634             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
635         }
636     };
637     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
638
639     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
640     let default_sysroot = match sopts.maybe_sysroot {
641         Some(_) => None,
642         None => Some(filesearch::get_or_default_sysroot())
643     };
644
645     let file_path_mapping = sopts.file_path_mapping();
646
647     // Make the path absolute, if necessary
648     let local_crate_source_file = local_crate_source_file.map(|path| {
649         file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
650     });
651
652     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
653     let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
654         .map(|i| i.1).unwrap_or(0));
655     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
656     let print_fuel = Cell::new(0);
657
658     let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
659     let working_dir = file_path_mapping.map_prefix(working_dir);
660
661     let sess = Session {
662         dep_graph: dep_graph.clone(),
663         target: target_cfg,
664         host: host,
665         opts: sopts,
666         cstore: cstore,
667         parse_sess: p_s,
668         // For a library crate, this is always none
669         entry_fn: RefCell::new(None),
670         entry_type: Cell::new(None),
671         plugin_registrar_fn: Cell::new(None),
672         derive_registrar_fn: Cell::new(None),
673         default_sysroot: default_sysroot,
674         local_crate_source_file: local_crate_source_file,
675         working_dir: working_dir,
676         lint_store: RefCell::new(lint::LintStore::new()),
677         lints: RefCell::new(lint::LintTable::new()),
678         one_time_diagnostics: RefCell::new(FxHashSet()),
679         plugin_llvm_passes: RefCell::new(Vec::new()),
680         plugin_attributes: RefCell::new(Vec::new()),
681         crate_types: RefCell::new(Vec::new()),
682         dependency_formats: RefCell::new(FxHashMap()),
683         crate_disambiguator: RefCell::new(Symbol::intern("")),
684         features: RefCell::new(feature_gate::Features::new()),
685         recursion_limit: Cell::new(64),
686         type_length_limit: Cell::new(1048576),
687         next_node_id: Cell::new(NodeId::new(1)),
688         injected_allocator: Cell::new(None),
689         injected_panic_runtime: Cell::new(None),
690         imported_macro_spans: RefCell::new(HashMap::new()),
691         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
692         perf_stats: PerfStats {
693             svh_time: Cell::new(Duration::from_secs(0)),
694             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
695             incr_comp_hashes_count: Cell::new(0),
696             incr_comp_bytes_hashed: Cell::new(0),
697             symbol_hash_time: Cell::new(Duration::from_secs(0)),
698             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
699         },
700         code_stats: RefCell::new(CodeStats::new()),
701         optimization_fuel_crate: optimization_fuel_crate,
702         optimization_fuel_limit: optimization_fuel_limit,
703         print_fuel_crate: print_fuel_crate,
704         print_fuel: print_fuel,
705         out_of_fuel: Cell::new(false),
706
707         // Note that this is unsafe because it may misinterpret file descriptors
708         // on Unix as jobserver file descriptors. We hopefully execute this near
709         // the beginning of the process though to ensure we don't get false
710         // positives, or in other words we try to execute this before we open
711         // any file descriptors ourselves.
712         //
713         // Also note that we stick this in a global because there could be
714         // multiple `Session` instances in this process, and the jobserver is
715         // per-process.
716         jobserver_from_env: unsafe {
717             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
718             static INIT: Once = ONCE_INIT;
719             INIT.call_once(|| {
720                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
721             });
722             (*GLOBAL_JOBSERVER).clone()
723         },
724     };
725
726     sess
727 }
728
729 /// Holds data on the current incremental compilation session, if there is one.
730 #[derive(Debug)]
731 pub enum IncrCompSession {
732     // This is the state the session will be in until the incr. comp. dir is
733     // needed.
734     NotInitialized,
735     // This is the state during which the session directory is private and can
736     // be modified.
737     Active {
738         session_directory: PathBuf,
739         lock_file: flock::Lock,
740     },
741     // This is the state after the session directory has been finalized. In this
742     // state, the contents of the directory must not be modified any more.
743     Finalized {
744         session_directory: PathBuf,
745     },
746     // This is an error state that is reached when some compilation error has
747     // occurred. It indicates that the contents of the session directory must
748     // not be used, since they might be invalid.
749     InvalidBecauseOfErrors {
750         session_directory: PathBuf,
751     }
752 }
753
754 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
755     let emitter: Box<Emitter> = match output {
756         config::ErrorOutputType::HumanReadable(color_config) => {
757             Box::new(EmitterWriter::stderr(color_config,
758                                            None))
759         }
760         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
761     };
762     let handler = errors::Handler::with_emitter(true, false, emitter);
763     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
764     panic!(errors::FatalError);
765 }
766
767 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
768     let emitter: Box<Emitter> = match output {
769         config::ErrorOutputType::HumanReadable(color_config) => {
770             Box::new(EmitterWriter::stderr(color_config,
771                                            None))
772         }
773         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
774     };
775     let handler = errors::Handler::with_emitter(true, false, emitter);
776     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
777 }
778
779 // Err(0) means compilation was stopped, but no errors were found.
780 // This would be better as a dedicated enum, but using try! is so convenient.
781 pub type CompileResult = Result<(), usize>;
782
783 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
784     if err_count == 0 {
785         Ok(())
786     } else {
787         Err(err_count)
788     }
789 }
790
791 #[cold]
792 #[inline(never)]
793 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
794     // this wrapper mostly exists so I don't have to write a fully
795     // qualified path of None::<Span> inside the bug!() macro defintion
796     opt_span_bug_fmt(file, line, None::<Span>, args);
797 }
798
799 #[cold]
800 #[inline(never)]
801 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
802                                         line: u32,
803                                         span: S,
804                                         args: fmt::Arguments) -> ! {
805     opt_span_bug_fmt(file, line, Some(span), args);
806 }
807
808 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
809                                         line: u32,
810                                         span: Option<S>,
811                                         args: fmt::Arguments) -> ! {
812     tls::with_opt(move |tcx| {
813         let msg = format!("{}:{}: {}", file, line, args);
814         match (tcx, span) {
815             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
816             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
817             (None, _) => panic!(msg)
818         }
819     });
820     unreachable!();
821 }