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