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