]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
3ba82f34c3266a804fece8554e94707fb562c796
[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::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 no_landing_pads(&self) -> bool {
367         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
368     }
369     pub fn unstable_options(&self) -> bool {
370         self.opts.debugging_opts.unstable_options
371     }
372     pub fn nonzeroing_move_hints(&self) -> bool {
373         self.opts.debugging_opts.enable_nonzeroing_move_hints
374     }
375     pub fn overflow_checks(&self) -> bool {
376         self.opts.cg.overflow_checks
377             .or(self.opts.debugging_opts.force_overflow_checks)
378             .unwrap_or(self.opts.debug_assertions)
379     }
380
381     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
382         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
383         !self.target.target.options.eliminate_frame_pointer
384     }
385
386     /// Returns the symbol name for the registrar function,
387     /// given the crate Svh and the function DefIndex.
388     pub fn generate_plugin_registrar_symbol(&self, svh: &Svh, index: DefIndex)
389                                             -> String {
390         format!("__rustc_plugin_registrar__{}_{}", svh, index.as_usize())
391     }
392
393     pub fn generate_derive_registrar_symbol(&self,
394                                             svh: &Svh,
395                                             index: DefIndex) -> String {
396         format!("__rustc_derive_registrar__{}_{}", svh, index.as_usize())
397     }
398
399     pub fn sysroot<'a>(&'a self) -> &'a Path {
400         match self.opts.maybe_sysroot {
401             Some (ref sysroot) => sysroot,
402             None => self.default_sysroot.as_ref()
403                         .expect("missing sysroot and default_sysroot in Session")
404         }
405     }
406     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
407         filesearch::FileSearch::new(self.sysroot(),
408                                     &self.opts.target_triple,
409                                     &self.opts.search_paths,
410                                     kind)
411     }
412     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
413         filesearch::FileSearch::new(
414             self.sysroot(),
415             config::host_triple(),
416             &self.opts.search_paths,
417             kind)
418     }
419
420     pub fn init_incr_comp_session(&self,
421                                   session_dir: PathBuf,
422                                   lock_file: flock::Lock) {
423         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
424
425         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
426             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
427         }
428
429         *incr_comp_session = IncrCompSession::Active {
430             session_directory: session_dir,
431             lock_file: lock_file,
432         };
433     }
434
435     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
436         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
437
438         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
439             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
440         }
441
442         // Note: This will also drop the lock file, thus unlocking the directory
443         *incr_comp_session = IncrCompSession::Finalized {
444             session_directory: new_directory_path,
445         };
446     }
447
448     pub fn mark_incr_comp_session_as_invalid(&self) {
449         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
450
451         let session_directory = match *incr_comp_session {
452             IncrCompSession::Active { ref session_directory, .. } => {
453                 session_directory.clone()
454             }
455             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
456                       *incr_comp_session),
457         };
458
459         // Note: This will also drop the lock file, thus unlocking the directory
460         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
461             session_directory: session_directory
462         };
463     }
464
465     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
466         let incr_comp_session = self.incr_comp_session.borrow();
467         cell::Ref::map(incr_comp_session, |incr_comp_session| {
468             match *incr_comp_session {
469                 IncrCompSession::NotInitialized => {
470                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
471                         *incr_comp_session)
472                 }
473                 IncrCompSession::Active { ref session_directory, .. } |
474                 IncrCompSession::Finalized { ref session_directory } |
475                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
476                     session_directory
477                 }
478             }
479         })
480     }
481
482     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
483         if self.opts.incremental.is_some() {
484             Some(self.incr_comp_session_dir())
485         } else {
486             None
487         }
488     }
489
490     pub fn print_perf_stats(&self) {
491         println!("Total time spent computing SVHs:               {}",
492                  duration_to_secs_str(self.perf_stats.svh_time.get()));
493         println!("Total time spent computing incr. comp. hashes: {}",
494                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
495         println!("Total number of incr. comp. hashes computed:   {}",
496                  self.perf_stats.incr_comp_hashes_count.get());
497         println!("Total number of bytes hashed for incr. comp.:  {}",
498                  self.perf_stats.incr_comp_bytes_hashed.get());
499         println!("Average bytes hashed per incr. comp. HIR node: {}",
500                  self.perf_stats.incr_comp_bytes_hashed.get() /
501                  self.perf_stats.incr_comp_hashes_count.get());
502         println!("Total time spent computing symbol hashes:      {}",
503                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
504         println!("Total time spent decoding DefPath tables:      {}",
505                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
506     }
507 }
508
509 pub fn build_session(sopts: config::Options,
510                      dep_graph: &DepGraph,
511                      local_crate_source_file: Option<PathBuf>,
512                      registry: errors::registry::Registry,
513                      cstore: Rc<CrateStore>)
514                      -> Session {
515     build_session_with_codemap(sopts,
516                                dep_graph,
517                                local_crate_source_file,
518                                registry,
519                                cstore,
520                                Rc::new(codemap::CodeMap::new()),
521                                None)
522 }
523
524 pub fn build_session_with_codemap(sopts: config::Options,
525                                   dep_graph: &DepGraph,
526                                   local_crate_source_file: Option<PathBuf>,
527                                   registry: errors::registry::Registry,
528                                   cstore: Rc<CrateStore>,
529                                   codemap: Rc<codemap::CodeMap>,
530                                   emitter_dest: Option<Box<Write + Send>>)
531                                   -> Session {
532     // FIXME: This is not general enough to make the warning lint completely override
533     // normal diagnostic warnings, since the warning lint can also be denied and changed
534     // later via the source code.
535     let can_print_warnings = sopts.lint_opts
536         .iter()
537         .filter(|&&(ref key, _)| *key == "warnings")
538         .map(|&(_, ref level)| *level != lint::Allow)
539         .last()
540         .unwrap_or(true);
541     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
542
543     let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
544         (config::ErrorOutputType::HumanReadable(color_config), None) => {
545             Box::new(EmitterWriter::stderr(color_config,
546                                            Some(codemap.clone())))
547         }
548         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
549             Box::new(EmitterWriter::new(dst,
550                                         Some(codemap.clone())))
551         }
552         (config::ErrorOutputType::Json, None) => {
553             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
554         }
555         (config::ErrorOutputType::Json, Some(dst)) => {
556             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
557         }
558     };
559
560     let diagnostic_handler =
561         errors::Handler::with_emitter(can_print_warnings,
562                                       treat_err_as_bug,
563                                       emitter);
564
565     build_session_(sopts,
566                    dep_graph,
567                    local_crate_source_file,
568                    diagnostic_handler,
569                    codemap,
570                    cstore)
571 }
572
573 pub fn build_session_(sopts: config::Options,
574                       dep_graph: &DepGraph,
575                       local_crate_source_file: Option<PathBuf>,
576                       span_diagnostic: errors::Handler,
577                       codemap: Rc<codemap::CodeMap>,
578                       cstore: Rc<CrateStore>)
579                       -> Session {
580     let host = match Target::search(config::host_triple()) {
581         Ok(t) => t,
582         Err(e) => {
583             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
584     }
585     };
586     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
587     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
588     let default_sysroot = match sopts.maybe_sysroot {
589         Some(_) => None,
590         None => Some(filesearch::get_or_default_sysroot())
591     };
592
593     // Make the path absolute, if necessary
594     let local_crate_source_file = local_crate_source_file.map(|path|
595         if path.is_absolute() {
596             path.clone()
597         } else {
598             env::current_dir().unwrap().join(&path)
599         }
600     );
601
602     let sess = Session {
603         dep_graph: dep_graph.clone(),
604         target: target_cfg,
605         host: host,
606         opts: sopts,
607         cstore: cstore,
608         parse_sess: p_s,
609         // For a library crate, this is always none
610         entry_fn: RefCell::new(None),
611         entry_type: Cell::new(None),
612         plugin_registrar_fn: Cell::new(None),
613         derive_registrar_fn: Cell::new(None),
614         default_sysroot: default_sysroot,
615         local_crate_source_file: local_crate_source_file,
616         working_dir: env::current_dir().unwrap(),
617         lint_store: RefCell::new(lint::LintStore::new()),
618         lints: RefCell::new(lint::LintTable::new()),
619         one_time_diagnostics: RefCell::new(FxHashSet()),
620         plugin_llvm_passes: RefCell::new(Vec::new()),
621         mir_passes: RefCell::new(mir_pass::Passes::new()),
622         plugin_attributes: RefCell::new(Vec::new()),
623         crate_types: RefCell::new(Vec::new()),
624         dependency_formats: RefCell::new(FxHashMap()),
625         crate_disambiguator: RefCell::new(Symbol::intern("")),
626         features: RefCell::new(feature_gate::Features::new()),
627         recursion_limit: Cell::new(64),
628         type_length_limit: Cell::new(1048576),
629         next_node_id: Cell::new(NodeId::new(1)),
630         injected_allocator: Cell::new(None),
631         injected_panic_runtime: Cell::new(None),
632         imported_macro_spans: RefCell::new(HashMap::new()),
633         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
634         perf_stats: PerfStats {
635             svh_time: Cell::new(Duration::from_secs(0)),
636             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
637             incr_comp_hashes_count: Cell::new(0),
638             incr_comp_bytes_hashed: Cell::new(0),
639             symbol_hash_time: Cell::new(Duration::from_secs(0)),
640             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
641         },
642         code_stats: RefCell::new(CodeStats::new()),
643     };
644
645     init_llvm(&sess);
646
647     sess
648 }
649
650 /// Holds data on the current incremental compilation session, if there is one.
651 #[derive(Debug)]
652 pub enum IncrCompSession {
653     // This is the state the session will be in until the incr. comp. dir is
654     // needed.
655     NotInitialized,
656     // This is the state during which the session directory is private and can
657     // be modified.
658     Active {
659         session_directory: PathBuf,
660         lock_file: flock::Lock,
661     },
662     // This is the state after the session directory has been finalized. In this
663     // state, the contents of the directory must not be modified any more.
664     Finalized {
665         session_directory: PathBuf,
666     },
667     // This is an error state that is reached when some compilation error has
668     // occurred. It indicates that the contents of the session directory must
669     // not be used, since they might be invalid.
670     InvalidBecauseOfErrors {
671         session_directory: PathBuf,
672     }
673 }
674
675 fn init_llvm(sess: &Session) {
676     unsafe {
677         // Before we touch LLVM, make sure that multithreading is enabled.
678         use std::sync::Once;
679         static INIT: Once = Once::new();
680         static mut POISONED: bool = false;
681         INIT.call_once(|| {
682             if llvm::LLVMStartMultithreaded() != 1 {
683                 // use an extra bool to make sure that all future usage of LLVM
684                 // cannot proceed despite the Once not running more than once.
685                 POISONED = true;
686             }
687
688             configure_llvm(sess);
689         });
690
691         if POISONED {
692             bug!("couldn't enable multi-threaded LLVM");
693         }
694     }
695 }
696
697 unsafe fn configure_llvm(sess: &Session) {
698     let mut llvm_c_strs = Vec::new();
699     let mut llvm_args = Vec::new();
700
701     {
702         let mut add = |arg: &str| {
703             let s = CString::new(arg).unwrap();
704             llvm_args.push(s.as_ptr());
705             llvm_c_strs.push(s);
706         };
707         add("rustc"); // fake program name
708         if sess.time_llvm_passes() { add("-time-passes"); }
709         if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
710
711         for arg in &sess.opts.cg.llvm_args {
712             add(&(*arg));
713         }
714     }
715
716     llvm::LLVMInitializePasses();
717
718     llvm::initialize_available_targets();
719
720     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
721                                  llvm_args.as_ptr());
722 }
723
724 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
725     let emitter: Box<Emitter> = match output {
726         config::ErrorOutputType::HumanReadable(color_config) => {
727             Box::new(EmitterWriter::stderr(color_config,
728                                            None))
729         }
730         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
731     };
732     let handler = errors::Handler::with_emitter(true, false, emitter);
733     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
734     panic!(errors::FatalError);
735 }
736
737 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
738     let emitter: Box<Emitter> = match output {
739         config::ErrorOutputType::HumanReadable(color_config) => {
740             Box::new(EmitterWriter::stderr(color_config,
741                                            None))
742         }
743         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
744     };
745     let handler = errors::Handler::with_emitter(true, false, emitter);
746     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
747 }
748
749 // Err(0) means compilation was stopped, but no errors were found.
750 // This would be better as a dedicated enum, but using try! is so convenient.
751 pub type CompileResult = Result<(), usize>;
752
753 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
754     if err_count == 0 {
755         Ok(())
756     } else {
757         Err(err_count)
758     }
759 }
760
761 #[cold]
762 #[inline(never)]
763 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
764     // this wrapper mostly exists so I don't have to write a fully
765     // qualified path of None::<Span> inside the bug!() macro defintion
766     opt_span_bug_fmt(file, line, None::<Span>, args);
767 }
768
769 #[cold]
770 #[inline(never)]
771 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
772                                         line: u32,
773                                         span: S,
774                                         args: fmt::Arguments) -> ! {
775     opt_span_bug_fmt(file, line, Some(span), args);
776 }
777
778 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
779                                         line: u32,
780                                         span: Option<S>,
781                                         args: fmt::Arguments) -> ! {
782     tls::with_opt(move |tcx| {
783         let msg = format!("{}:{}: {}", file, line, args);
784         match (tcx, span) {
785             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
786             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
787             (None, _) => panic!(msg)
788         }
789     });
790     unreachable!();
791 }