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