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