]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
report the total number of errors on compilation failure
[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, ErrorReported};
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 jobserver::Client;
42
43 use std::cell::{self, Cell, RefCell};
44 use std::collections::HashMap;
45 use std::env;
46 use std::fmt;
47 use std::io::Write;
48 use std::path::{Path, PathBuf};
49 use std::rc::Rc;
50 use std::sync::{Once, ONCE_INIT};
51 use std::time::Duration;
52
53 mod code_stats;
54 pub mod config;
55 pub mod filesearch;
56 pub mod search_paths;
57
58 // Represents the data associated with a compilation
59 // session for a single crate.
60 pub struct Session {
61     pub dep_graph: DepGraph,
62     pub target: config::Config,
63     pub host: Target,
64     pub opts: config::Options,
65     pub cstore: Rc<CrateStore>,
66     pub parse_sess: ParseSess,
67     // For a library crate, this is always none
68     pub entry_fn: RefCell<Option<(NodeId, Span)>>,
69     pub entry_type: Cell<Option<config::EntryFnType>>,
70     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
71     pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
72     pub default_sysroot: Option<PathBuf>,
73     // The name of the root source file of the crate, in the local file system.
74     // The path is always expected to be absolute. `None` means that there is no
75     // source file.
76     pub local_crate_source_file: Option<String>,
77     // The directory the compiler has been executed in plus a flag indicating
78     // if the value stored here has been affected by path remapping.
79     pub working_dir: (String, bool),
80     pub lint_store: RefCell<lint::LintStore>,
81     pub lints: RefCell<lint::LintTable>,
82     /// Set of (LintId, Option<Span>, message) tuples tracking lint
83     /// (sub)diagnostics that have been set once, but should not be set again,
84     /// in order to avoid redundantly verbose output (Issue #24690).
85     pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Option<Span>, String)>>,
86     pub plugin_llvm_passes: RefCell<Vec<String>>,
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     /// Loaded up early on in the initialization of this `Session` to avoid
141     /// false positives about a job server in our environment.
142     pub jobserver_from_env: Option<Client>,
143 }
144
145 pub struct PerfStats {
146     // The accumulated time needed for computing the SVH of the crate
147     pub svh_time: Cell<Duration>,
148     // The accumulated time spent on computing incr. comp. hashes
149     pub incr_comp_hashes_time: Cell<Duration>,
150     // The number of incr. comp. hash computations performed
151     pub incr_comp_hashes_count: Cell<u64>,
152     // The number of bytes hashed when computing ICH values
153     pub incr_comp_bytes_hashed: Cell<u64>,
154     // The accumulated time spent on computing symbol hashes
155     pub symbol_hash_time: Cell<Duration>,
156     // The accumulated time spent decoding def path tables from metadata
157     pub decode_def_path_tables_time: Cell<Duration>,
158 }
159
160 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
161 enum DiagnosticBuilderMethod {
162     Note,
163     SpanNote,
164     // add more variants as needed to support one-time diagnostics
165 }
166
167 impl Session {
168     pub fn local_crate_disambiguator(&self) -> Symbol {
169         *self.crate_disambiguator.borrow()
170     }
171     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
172                                                     sp: S,
173                                                     msg: &str)
174                                                     -> DiagnosticBuilder<'a> {
175         self.diagnostic().struct_span_warn(sp, msg)
176     }
177     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
178                                                               sp: S,
179                                                               msg: &str,
180                                                               code: &str)
181                                                               -> DiagnosticBuilder<'a> {
182         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
183     }
184     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
185         self.diagnostic().struct_warn(msg)
186     }
187     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
188                                                    sp: S,
189                                                    msg: &str)
190                                                    -> DiagnosticBuilder<'a> {
191         self.diagnostic().struct_span_err(sp, msg)
192     }
193     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
194                                                              sp: S,
195                                                              msg: &str,
196                                                              code: &str)
197                                                              -> DiagnosticBuilder<'a> {
198         self.diagnostic().struct_span_err_with_code(sp, msg, code)
199     }
200     // FIXME: This method should be removed (every error should have an associated error code).
201     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
202         self.diagnostic().struct_err(msg)
203     }
204     pub fn struct_err_with_code<'a>(&'a self, msg: &str, code: &str) -> DiagnosticBuilder<'a> {
205         self.diagnostic().struct_err_with_code(msg, code)
206     }
207     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
208                                                      sp: S,
209                                                      msg: &str)
210                                                      -> DiagnosticBuilder<'a> {
211         self.diagnostic().struct_span_fatal(sp, msg)
212     }
213     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
214                                                                sp: S,
215                                                                msg: &str,
216                                                                code: &str)
217                                                                -> DiagnosticBuilder<'a> {
218         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
219     }
220     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
221         self.diagnostic().struct_fatal(msg)
222     }
223
224     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
225         panic!(self.diagnostic().span_fatal(sp, msg))
226     }
227     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
228         panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
229     }
230     pub fn fatal(&self, msg: &str) -> ! {
231         panic!(self.diagnostic().fatal(msg))
232     }
233     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
234         if is_warning {
235             self.span_warn(sp, msg);
236         } else {
237             self.span_err(sp, msg);
238         }
239     }
240     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
241         self.diagnostic().span_err(sp, msg)
242     }
243     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
244         self.diagnostic().span_err_with_code(sp, &msg, code)
245     }
246     pub fn err(&self, msg: &str) {
247         self.diagnostic().err(msg)
248     }
249     pub fn err_count(&self) -> usize {
250         self.diagnostic().err_count()
251     }
252     pub fn has_errors(&self) -> bool {
253         self.diagnostic().has_errors()
254     }
255     pub fn abort_if_errors(&self) {
256         self.diagnostic().abort_if_errors();
257     }
258     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
259         compile_result_from_err_count(self.err_count())
260     }
261     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
262         where F: FnOnce() -> T
263     {
264         let old_count = self.err_count();
265         let result = f();
266         let errors = self.err_count() - old_count;
267         if errors == 0 {
268             Ok(result)
269         } else {
270             Err(ErrorReported)
271         }
272     }
273     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
274         self.diagnostic().span_warn(sp, msg)
275     }
276     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
277         self.diagnostic().span_warn_with_code(sp, msg, code)
278     }
279     pub fn warn(&self, msg: &str) {
280         self.diagnostic().warn(msg)
281     }
282     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
283         match opt_sp {
284             Some(sp) => self.span_warn(sp, msg),
285             None => self.warn(msg),
286         }
287     }
288     /// Delay a span_bug() call until abort_if_errors()
289     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
290         self.diagnostic().delay_span_bug(sp, msg)
291     }
292     pub fn note_without_error(&self, msg: &str) {
293         self.diagnostic().note_without_error(msg)
294     }
295     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
296         self.diagnostic().span_note_without_error(sp, msg)
297     }
298     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
299         self.diagnostic().span_unimpl(sp, msg)
300     }
301     pub fn unimpl(&self, msg: &str) -> ! {
302         self.diagnostic().unimpl(msg)
303     }
304
305     pub fn add_lint<S: Into<MultiSpan>>(&self,
306                                         lint: &'static lint::Lint,
307                                         id: ast::NodeId,
308                                         sp: S,
309                                         msg: String)
310     {
311         self.lints.borrow_mut().add_lint(lint, id, sp, msg);
312     }
313
314     pub fn add_lint_diagnostic<M>(&self,
315                                   lint: &'static lint::Lint,
316                                   id: ast::NodeId,
317                                   msg: M)
318         where M: lint::IntoEarlyLint,
319     {
320         self.lints.borrow_mut().add_lint_diagnostic(lint, id, msg);
321     }
322
323     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
324         let id = self.next_node_id.get();
325
326         match id.as_usize().checked_add(count) {
327             Some(next) => {
328                 self.next_node_id.set(ast::NodeId::new(next));
329             }
330             None => bug!("Input too large, ran out of node ids!")
331         }
332
333         id
334     }
335     pub fn next_node_id(&self) -> NodeId {
336         self.reserve_node_ids(1)
337     }
338     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
339         &self.parse_sess.span_diagnostic
340     }
341
342     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
343     /// deduplicates on lint ID, span (if any), and message for this `Session`
344     /// if we're not outputting in JSON mode.
345     fn diag_once<'a, 'b>(&'a self,
346                          diag_builder: &'b mut DiagnosticBuilder<'a>,
347                          method: DiagnosticBuilderMethod,
348                          lint: &'static lint::Lint, message: &str, span: Option<Span>) {
349         let mut do_method = || {
350             match method {
351                 DiagnosticBuilderMethod::Note => {
352                     diag_builder.note(message);
353                 },
354                 DiagnosticBuilderMethod::SpanNote => {
355                     diag_builder.span_note(span.expect("span_note expects a span"), message);
356                 }
357             }
358         };
359
360         match self.opts.error_format {
361             // when outputting JSON for tool consumption, the tool might want
362             // the duplicates
363             config::ErrorOutputType::Json => {
364                 do_method()
365             },
366             _ => {
367                 let lint_id = lint::LintId::of(lint);
368                 let id_span_message = (lint_id, span, message.to_owned());
369                 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
370                 if fresh {
371                     do_method()
372                 }
373             }
374         }
375     }
376
377     pub fn diag_span_note_once<'a, 'b>(&'a self,
378                                        diag_builder: &'b mut DiagnosticBuilder<'a>,
379                                        lint: &'static lint::Lint, span: Span, message: &str) {
380         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote, lint, message, Some(span));
381     }
382
383     pub fn diag_note_once<'a, 'b>(&'a self,
384                                   diag_builder: &'b mut DiagnosticBuilder<'a>,
385                                   lint: &'static lint::Lint, message: &str) {
386         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, lint, message, None);
387     }
388
389     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
390         self.parse_sess.codemap()
391     }
392     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
393     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
394     pub fn count_llvm_insns(&self) -> bool {
395         self.opts.debugging_opts.count_llvm_insns
396     }
397     pub fn time_llvm_passes(&self) -> bool {
398         self.opts.debugging_opts.time_llvm_passes
399     }
400     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
401     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
402     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
403     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
404     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
405     pub fn print_llvm_passes(&self) -> bool {
406         self.opts.debugging_opts.print_llvm_passes
407     }
408     pub fn lto(&self) -> bool {
409         self.opts.cg.lto
410     }
411     /// Returns the panic strategy for this compile session. If the user explicitly selected one
412     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
413     pub fn panic_strategy(&self) -> PanicStrategy {
414         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
415     }
416     pub fn linker_flavor(&self) -> LinkerFlavor {
417         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
418     }
419     pub fn no_landing_pads(&self) -> bool {
420         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
421     }
422     pub fn unstable_options(&self) -> bool {
423         self.opts.debugging_opts.unstable_options
424     }
425     pub fn nonzeroing_move_hints(&self) -> bool {
426         self.opts.debugging_opts.enable_nonzeroing_move_hints
427     }
428     pub fn overflow_checks(&self) -> bool {
429         self.opts.cg.overflow_checks
430             .or(self.opts.debugging_opts.force_overflow_checks)
431             .unwrap_or(self.opts.debug_assertions)
432     }
433
434     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
435         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
436         !self.target.target.options.eliminate_frame_pointer
437     }
438
439     /// Returns the symbol name for the registrar function,
440     /// given the crate Svh and the function DefIndex.
441     pub fn generate_plugin_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
442                                             -> String {
443         format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
444     }
445
446     pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
447                                             -> String {
448         format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
449     }
450
451     pub fn sysroot<'a>(&'a self) -> &'a Path {
452         match self.opts.maybe_sysroot {
453             Some (ref sysroot) => sysroot,
454             None => self.default_sysroot.as_ref()
455                         .expect("missing sysroot and default_sysroot in Session")
456         }
457     }
458     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
459         filesearch::FileSearch::new(self.sysroot(),
460                                     &self.opts.target_triple,
461                                     &self.opts.search_paths,
462                                     kind)
463     }
464     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
465         filesearch::FileSearch::new(
466             self.sysroot(),
467             config::host_triple(),
468             &self.opts.search_paths,
469             kind)
470     }
471
472     pub fn init_incr_comp_session(&self,
473                                   session_dir: PathBuf,
474                                   lock_file: flock::Lock) {
475         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
476
477         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
478             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
479         }
480
481         *incr_comp_session = IncrCompSession::Active {
482             session_directory: session_dir,
483             lock_file: lock_file,
484         };
485     }
486
487     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
488         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
489
490         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
491             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
492         }
493
494         // Note: This will also drop the lock file, thus unlocking the directory
495         *incr_comp_session = IncrCompSession::Finalized {
496             session_directory: new_directory_path,
497         };
498     }
499
500     pub fn mark_incr_comp_session_as_invalid(&self) {
501         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
502
503         let session_directory = match *incr_comp_session {
504             IncrCompSession::Active { ref session_directory, .. } => {
505                 session_directory.clone()
506             }
507             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
508                       *incr_comp_session),
509         };
510
511         // Note: This will also drop the lock file, thus unlocking the directory
512         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
513             session_directory: session_directory
514         };
515     }
516
517     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
518         let incr_comp_session = self.incr_comp_session.borrow();
519         cell::Ref::map(incr_comp_session, |incr_comp_session| {
520             match *incr_comp_session {
521                 IncrCompSession::NotInitialized => {
522                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
523                         *incr_comp_session)
524                 }
525                 IncrCompSession::Active { ref session_directory, .. } |
526                 IncrCompSession::Finalized { ref session_directory } |
527                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
528                     session_directory
529                 }
530             }
531         })
532     }
533
534     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
535         if self.opts.incremental.is_some() {
536             Some(self.incr_comp_session_dir())
537         } else {
538             None
539         }
540     }
541
542     pub fn print_perf_stats(&self) {
543         println!("Total time spent computing SVHs:               {}",
544                  duration_to_secs_str(self.perf_stats.svh_time.get()));
545         println!("Total time spent computing incr. comp. hashes: {}",
546                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
547         println!("Total number of incr. comp. hashes computed:   {}",
548                  self.perf_stats.incr_comp_hashes_count.get());
549         println!("Total number of bytes hashed for incr. comp.:  {}",
550                  self.perf_stats.incr_comp_bytes_hashed.get());
551         println!("Average bytes hashed per incr. comp. HIR node: {}",
552                  self.perf_stats.incr_comp_bytes_hashed.get() /
553                  self.perf_stats.incr_comp_hashes_count.get());
554         println!("Total time spent computing symbol hashes:      {}",
555                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
556         println!("Total time spent decoding DefPath tables:      {}",
557                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
558     }
559
560     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
561     /// This expends fuel if applicable, and records fuel if applicable.
562     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
563         let mut ret = true;
564         match self.optimization_fuel_crate {
565             Some(ref c) if c == crate_name => {
566                 let fuel = self.optimization_fuel_limit.get();
567                 ret = fuel != 0;
568                 if fuel == 0 && !self.out_of_fuel.get() {
569                     println!("optimization-fuel-exhausted: {}", msg());
570                     self.out_of_fuel.set(true);
571                 } else if fuel > 0 {
572                     self.optimization_fuel_limit.set(fuel-1);
573                 }
574             }
575             _ => {}
576         }
577         match self.print_fuel_crate {
578             Some(ref c) if c == crate_name=> {
579                 self.print_fuel.set(self.print_fuel.get()+1);
580             },
581             _ => {}
582         }
583         ret
584     }
585 }
586
587 pub fn build_session(sopts: config::Options,
588                      dep_graph: &DepGraph,
589                      local_crate_source_file: Option<PathBuf>,
590                      registry: errors::registry::Registry,
591                      cstore: Rc<CrateStore>)
592                      -> Session {
593     let file_path_mapping = sopts.file_path_mapping();
594
595     build_session_with_codemap(sopts,
596                                dep_graph,
597                                local_crate_source_file,
598                                registry,
599                                cstore,
600                                Rc::new(codemap::CodeMap::new(file_path_mapping)),
601                                None)
602 }
603
604 pub fn build_session_with_codemap(sopts: config::Options,
605                                   dep_graph: &DepGraph,
606                                   local_crate_source_file: Option<PathBuf>,
607                                   registry: errors::registry::Registry,
608                                   cstore: Rc<CrateStore>,
609                                   codemap: Rc<codemap::CodeMap>,
610                                   emitter_dest: Option<Box<Write + Send>>)
611                                   -> Session {
612     // FIXME: This is not general enough to make the warning lint completely override
613     // normal diagnostic warnings, since the warning lint can also be denied and changed
614     // later via the source code.
615     let can_print_warnings = sopts.lint_opts
616         .iter()
617         .filter(|&&(ref key, _)| *key == "warnings")
618         .map(|&(_, ref level)| *level != lint::Allow)
619         .last()
620         .unwrap_or(true);
621     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
622
623     let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
624         (config::ErrorOutputType::HumanReadable(color_config), None) => {
625             Box::new(EmitterWriter::stderr(color_config,
626                                            Some(codemap.clone())))
627         }
628         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
629             Box::new(EmitterWriter::new(dst,
630                                         Some(codemap.clone())))
631         }
632         (config::ErrorOutputType::Json, None) => {
633             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
634         }
635         (config::ErrorOutputType::Json, Some(dst)) => {
636             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
637         }
638     };
639
640     let diagnostic_handler =
641         errors::Handler::with_emitter(can_print_warnings,
642                                       treat_err_as_bug,
643                                       emitter);
644
645     build_session_(sopts,
646                    dep_graph,
647                    local_crate_source_file,
648                    diagnostic_handler,
649                    codemap,
650                    cstore)
651 }
652
653 pub fn build_session_(sopts: config::Options,
654                       dep_graph: &DepGraph,
655                       local_crate_source_file: Option<PathBuf>,
656                       span_diagnostic: errors::Handler,
657                       codemap: Rc<codemap::CodeMap>,
658                       cstore: Rc<CrateStore>)
659                       -> Session {
660     let host = match Target::search(config::host_triple()) {
661         Ok(t) => t,
662         Err(e) => {
663             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
664         }
665     };
666     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
667
668     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
669     let default_sysroot = match sopts.maybe_sysroot {
670         Some(_) => None,
671         None => Some(filesearch::get_or_default_sysroot())
672     };
673
674     let file_path_mapping = sopts.file_path_mapping();
675
676     // Make the path absolute, if necessary
677     let local_crate_source_file = local_crate_source_file.map(|path| {
678         file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
679     });
680
681     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
682     let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
683         .map(|i| i.1).unwrap_or(0));
684     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
685     let print_fuel = Cell::new(0);
686
687     let working_dir = env::current_dir().unwrap().to_string_lossy().into_owned();
688     let working_dir = file_path_mapping.map_prefix(working_dir);
689
690     let sess = Session {
691         dep_graph: dep_graph.clone(),
692         target: target_cfg,
693         host: host,
694         opts: sopts,
695         cstore: cstore,
696         parse_sess: p_s,
697         // For a library crate, this is always none
698         entry_fn: RefCell::new(None),
699         entry_type: Cell::new(None),
700         plugin_registrar_fn: Cell::new(None),
701         derive_registrar_fn: Cell::new(None),
702         default_sysroot: default_sysroot,
703         local_crate_source_file: local_crate_source_file,
704         working_dir: working_dir,
705         lint_store: RefCell::new(lint::LintStore::new()),
706         lints: RefCell::new(lint::LintTable::new()),
707         one_time_diagnostics: RefCell::new(FxHashSet()),
708         plugin_llvm_passes: RefCell::new(Vec::new()),
709         plugin_attributes: RefCell::new(Vec::new()),
710         crate_types: RefCell::new(Vec::new()),
711         dependency_formats: RefCell::new(FxHashMap()),
712         crate_disambiguator: RefCell::new(Symbol::intern("")),
713         features: RefCell::new(feature_gate::Features::new()),
714         recursion_limit: Cell::new(64),
715         type_length_limit: Cell::new(1048576),
716         next_node_id: Cell::new(NodeId::new(1)),
717         injected_allocator: Cell::new(None),
718         injected_panic_runtime: Cell::new(None),
719         imported_macro_spans: RefCell::new(HashMap::new()),
720         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
721         perf_stats: PerfStats {
722             svh_time: Cell::new(Duration::from_secs(0)),
723             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
724             incr_comp_hashes_count: Cell::new(0),
725             incr_comp_bytes_hashed: Cell::new(0),
726             symbol_hash_time: Cell::new(Duration::from_secs(0)),
727             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
728         },
729         code_stats: RefCell::new(CodeStats::new()),
730         optimization_fuel_crate: optimization_fuel_crate,
731         optimization_fuel_limit: optimization_fuel_limit,
732         print_fuel_crate: print_fuel_crate,
733         print_fuel: print_fuel,
734         out_of_fuel: Cell::new(false),
735
736         // Note that this is unsafe because it may misinterpret file descriptors
737         // on Unix as jobserver file descriptors. We hopefully execute this near
738         // the beginning of the process though to ensure we don't get false
739         // positives, or in other words we try to execute this before we open
740         // any file descriptors ourselves.
741         //
742         // Also note that we stick this in a global because there could be
743         // multiple `Session` instances in this process, and the jobserver is
744         // per-process.
745         jobserver_from_env: unsafe {
746             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
747             static INIT: Once = ONCE_INIT;
748             INIT.call_once(|| {
749                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
750             });
751             (*GLOBAL_JOBSERVER).clone()
752         },
753     };
754
755     sess
756 }
757
758 /// Holds data on the current incremental compilation session, if there is one.
759 #[derive(Debug)]
760 pub enum IncrCompSession {
761     // This is the state the session will be in until the incr. comp. dir is
762     // needed.
763     NotInitialized,
764     // This is the state during which the session directory is private and can
765     // be modified.
766     Active {
767         session_directory: PathBuf,
768         lock_file: flock::Lock,
769     },
770     // This is the state after the session directory has been finalized. In this
771     // state, the contents of the directory must not be modified any more.
772     Finalized {
773         session_directory: PathBuf,
774     },
775     // This is an error state that is reached when some compilation error has
776     // occurred. It indicates that the contents of the session directory must
777     // not be used, since they might be invalid.
778     InvalidBecauseOfErrors {
779         session_directory: PathBuf,
780     }
781 }
782
783 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
784     let emitter: Box<Emitter> = match output {
785         config::ErrorOutputType::HumanReadable(color_config) => {
786             Box::new(EmitterWriter::stderr(color_config,
787                                            None))
788         }
789         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
790     };
791     let handler = errors::Handler::with_emitter(true, false, emitter);
792     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
793     panic!(errors::FatalError);
794 }
795
796 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
797     let emitter: Box<Emitter> = match output {
798         config::ErrorOutputType::HumanReadable(color_config) => {
799             Box::new(EmitterWriter::stderr(color_config,
800                                            None))
801         }
802         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
803     };
804     let handler = errors::Handler::with_emitter(true, false, emitter);
805     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
806 }
807
808 #[derive(Copy, Clone, Debug)]
809 pub enum CompileIncomplete {
810     Stopped,
811     Errored(ErrorReported)
812 }
813 impl From<ErrorReported> for CompileIncomplete {
814     fn from(err: ErrorReported) -> CompileIncomplete {
815         CompileIncomplete::Errored(err)
816     }
817 }
818 pub type CompileResult = Result<(), CompileIncomplete>;
819
820 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
821     if err_count == 0 {
822         Ok(())
823     } else {
824         Err(CompileIncomplete::Errored(ErrorReported))
825     }
826 }
827
828 #[cold]
829 #[inline(never)]
830 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
831     // this wrapper mostly exists so I don't have to write a fully
832     // qualified path of None::<Span> inside the bug!() macro defintion
833     opt_span_bug_fmt(file, line, None::<Span>, args);
834 }
835
836 #[cold]
837 #[inline(never)]
838 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
839                                         line: u32,
840                                         span: S,
841                                         args: fmt::Arguments) -> ! {
842     opt_span_bug_fmt(file, line, Some(span), args);
843 }
844
845 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
846                                         line: u32,
847                                         span: Option<S>,
848                                         args: fmt::Arguments) -> ! {
849     tls::with_opt(move |tcx| {
850         let msg = format!("{}:{}: {}", file, line, args);
851         match (tcx, span) {
852             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
853             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
854             (None, _) => panic!(msg)
855         }
856     });
857     unreachable!();
858 }