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