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