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