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