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.
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.
11 use dep_graph::DepGraph;
12 use hir::def_id::{CrateNum, DefIndex};
15 use middle::cstore::CrateStore;
16 use middle::dependency_format;
17 use session::search_paths::PathKind;
18 use session::config::DebugInfoLevel;
20 use util::nodemap::{NodeMap, FnvHashMap, FnvHashSet};
21 use util::common::duration_to_secs_str;
22 use mir::transform as mir_pass;
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;
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};
36 use rustc_back::PanicStrategy;
37 use rustc_back::target::Target;
38 use rustc_data_structures::flock;
41 use std::path::{Path, PathBuf};
42 use std::cell::{self, Cell, RefCell};
43 use std::collections::HashMap;
45 use std::ffi::CString;
49 use std::time::Duration;
56 // Represents the data associated with a compilation
57 // session for a single crate.
59 pub dep_graph: DepGraph,
60 pub target: config::Config,
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
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::LintId, Span, String)>>>,
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>,
95 /// The maximum recursion limit for potentially infinitely recursive
96 /// operations such as auto-dereference and monomorphization.
97 pub recursion_limit: Cell<usize>,
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
102 pub injected_allocator: Cell<Option<CrateNum>>,
103 pub injected_panic_runtime: Cell<Option<CrateNum>>,
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)>>,
110 incr_comp_session: RefCell<IncrCompSession>,
112 /// Some measurements that are being gathered during compilation.
113 pub perf_stats: PerfStats,
115 next_node_id: Cell<ast::NodeId>,
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>,
132 pub fn local_crate_disambiguator(&self) -> token::InternedString {
133 self.crate_disambiguator.borrow().clone()
135 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
138 -> DiagnosticBuilder<'a> {
139 self.diagnostic().struct_span_warn(sp, msg)
141 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
145 -> DiagnosticBuilder<'a> {
146 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
148 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
149 self.diagnostic().struct_warn(msg)
151 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
154 -> DiagnosticBuilder<'a> {
155 self.diagnostic().struct_span_err(sp, msg)
157 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
161 -> DiagnosticBuilder<'a> {
162 self.diagnostic().struct_span_err_with_code(sp, msg, code)
164 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
165 self.diagnostic().struct_err(msg)
167 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
170 -> DiagnosticBuilder<'a> {
171 self.diagnostic().struct_span_fatal(sp, msg)
173 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
177 -> DiagnosticBuilder<'a> {
178 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
180 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
181 self.diagnostic().struct_fatal(msg)
184 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
185 panic!(self.diagnostic().span_fatal(sp, msg))
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))
190 pub fn fatal(&self, msg: &str) -> ! {
191 panic!(self.diagnostic().fatal(msg))
193 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
195 self.span_warn(sp, msg);
197 self.span_err(sp, msg);
200 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
201 self.diagnostic().span_err(sp, msg)
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)
206 pub fn err(&self, msg: &str) {
207 self.diagnostic().err(msg)
209 pub fn err_count(&self) -> usize {
210 self.diagnostic().err_count()
212 pub fn has_errors(&self) -> bool {
213 self.diagnostic().has_errors()
215 pub fn abort_if_errors(&self) {
216 self.diagnostic().abort_if_errors();
218 pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
219 where F: FnOnce() -> T
221 let old_count = self.err_count();
223 let errors = self.err_count() - old_count;
230 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
231 self.diagnostic().span_warn(sp, msg)
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)
236 pub fn warn(&self, msg: &str) {
237 self.diagnostic().warn(msg)
239 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
241 Some(sp) => self.span_warn(sp, msg),
242 None => self.warn(msg),
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)
249 pub fn note_without_error(&self, msg: &str) {
250 self.diagnostic().note_without_error(msg)
252 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
253 self.diagnostic().span_note_without_error(sp, msg)
255 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
256 self.diagnostic().span_unimpl(sp, msg)
258 pub fn unimpl(&self, msg: &str) -> ! {
259 self.diagnostic().unimpl(msg)
261 pub fn add_lint(&self,
262 lint: &'static lint::Lint,
266 let lint_id = lint::LintId::of(lint);
267 let mut lints = self.lints.borrow_mut();
268 if let Some(arr) = lints.get_mut(&id) {
269 let tuple = (lint_id, sp, msg);
270 if !arr.contains(&tuple) {
275 lints.insert(id, vec!((lint_id, sp, msg)));
277 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
278 let id = self.next_node_id.get();
280 match id.as_usize().checked_add(count) {
282 self.next_node_id.set(ast::NodeId::new(next));
284 None => bug!("Input too large, ran out of node ids!")
289 pub fn next_node_id(&self) -> NodeId {
290 self.reserve_node_ids(1)
292 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
293 &self.parse_sess.span_diagnostic
296 /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but
297 /// deduplicates on lint ID, span, and message for this `Session` if we're
298 /// not outputting in JSON mode.
300 // FIXME: if the need arises for one-time diagnostics other than
301 // `span_note`, we almost certainly want to generalize this
302 // "check/insert-into the one-time diagnostics map, then set message if
303 // it's not already there" code to accomodate all of them
304 pub fn diag_span_note_once<'a, 'b>(&'a self,
305 diag_builder: &'b mut DiagnosticBuilder<'a>,
306 lint: &'static lint::Lint, span: Span, message: &str) {
307 match self.opts.error_format {
308 // when outputting JSON for tool consumption, the tool might want
310 config::ErrorOutputType::Json => {
311 diag_builder.span_note(span, &message);
314 let lint_id = lint::LintId::of(lint);
315 let id_span_message = (lint_id, span, message.to_owned());
316 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
318 diag_builder.span_note(span, &message);
324 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
325 self.parse_sess.codemap()
327 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
328 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
329 pub fn count_llvm_insns(&self) -> bool {
330 self.opts.debugging_opts.count_llvm_insns
332 pub fn time_llvm_passes(&self) -> bool {
333 self.opts.debugging_opts.time_llvm_passes
335 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
336 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
337 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
338 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
339 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
340 pub fn print_llvm_passes(&self) -> bool {
341 self.opts.debugging_opts.print_llvm_passes
343 pub fn lto(&self) -> bool {
346 /// Returns the panic strategy for this compile session. If the user explicitly selected one
347 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
348 pub fn panic_strategy(&self) -> PanicStrategy {
349 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
351 pub fn no_landing_pads(&self) -> bool {
352 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
354 pub fn unstable_options(&self) -> bool {
355 self.opts.debugging_opts.unstable_options
357 pub fn nonzeroing_move_hints(&self) -> bool {
358 self.opts.debugging_opts.enable_nonzeroing_move_hints
361 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
362 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
363 !self.target.target.options.eliminate_frame_pointer
366 /// Returns the symbol name for the registrar function,
367 /// given the crate Svh and the function DefIndex.
368 pub fn generate_plugin_registrar_symbol(&self, svh: &Svh, index: DefIndex)
370 format!("__rustc_plugin_registrar__{}_{}", svh, index.as_usize())
373 pub fn generate_derive_registrar_symbol(&self,
375 index: DefIndex) -> String {
376 format!("__rustc_derive_registrar__{}_{}", svh, index.as_usize())
379 pub fn sysroot<'a>(&'a self) -> &'a Path {
380 match self.opts.maybe_sysroot {
381 Some (ref sysroot) => sysroot,
382 None => self.default_sysroot.as_ref()
383 .expect("missing sysroot and default_sysroot in Session")
386 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
387 filesearch::FileSearch::new(self.sysroot(),
388 &self.opts.target_triple,
389 &self.opts.search_paths,
392 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
393 filesearch::FileSearch::new(
395 config::host_triple(),
396 &self.opts.search_paths,
400 pub fn init_incr_comp_session(&self,
401 session_dir: PathBuf,
402 lock_file: flock::Lock) {
403 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
405 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
406 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
409 *incr_comp_session = IncrCompSession::Active {
410 session_directory: session_dir,
411 lock_file: lock_file,
415 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
416 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
418 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
419 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
422 // Note: This will also drop the lock file, thus unlocking the directory
423 *incr_comp_session = IncrCompSession::Finalized {
424 session_directory: new_directory_path,
428 pub fn mark_incr_comp_session_as_invalid(&self) {
429 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
431 let session_directory = match *incr_comp_session {
432 IncrCompSession::Active { ref session_directory, .. } => {
433 session_directory.clone()
435 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
439 // Note: This will also drop the lock file, thus unlocking the directory
440 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
441 session_directory: session_directory
445 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
446 let incr_comp_session = self.incr_comp_session.borrow();
447 cell::Ref::map(incr_comp_session, |incr_comp_session| {
448 match *incr_comp_session {
449 IncrCompSession::NotInitialized => {
450 bug!("Trying to get session directory from IncrCompSession `{:?}`",
453 IncrCompSession::Active { ref session_directory, .. } |
454 IncrCompSession::Finalized { ref session_directory } |
455 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
462 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
463 if self.opts.incremental.is_some() {
464 Some(self.incr_comp_session_dir())
470 pub fn print_perf_stats(&self) {
471 println!("Total time spent computing SVHs: {}",
472 duration_to_secs_str(self.perf_stats.svh_time.get()));
473 println!("Total time spent computing incr. comp. hashes: {}",
474 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
475 println!("Total number of incr. comp. hashes computed: {}",
476 self.perf_stats.incr_comp_hashes_count.get());
477 println!("Total number of bytes hashed for incr. comp.: {}",
478 self.perf_stats.incr_comp_bytes_hashed.get());
479 println!("Average bytes hashed per incr. comp. HIR node: {}",
480 self.perf_stats.incr_comp_bytes_hashed.get() /
481 self.perf_stats.incr_comp_hashes_count.get());
482 println!("Total time spent computing symbol hashes: {}",
483 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
487 pub fn build_session(sopts: config::Options,
488 dep_graph: &DepGraph,
489 local_crate_source_file: Option<PathBuf>,
490 registry: errors::registry::Registry,
491 cstore: Rc<for<'a> CrateStore<'a>>)
493 build_session_with_codemap(sopts,
495 local_crate_source_file,
498 Rc::new(codemap::CodeMap::new()),
502 pub fn build_session_with_codemap(sopts: config::Options,
503 dep_graph: &DepGraph,
504 local_crate_source_file: Option<PathBuf>,
505 registry: errors::registry::Registry,
506 cstore: Rc<for<'a> CrateStore<'a>>,
507 codemap: Rc<codemap::CodeMap>,
508 emitter_dest: Option<Box<Write + Send>>)
510 // FIXME: This is not general enough to make the warning lint completely override
511 // normal diagnostic warnings, since the warning lint can also be denied and changed
512 // later via the source code.
513 let can_print_warnings = sopts.lint_opts
515 .filter(|&&(ref key, _)| *key == "warnings")
516 .map(|&(_, ref level)| *level != lint::Allow)
519 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
521 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
522 (config::ErrorOutputType::HumanReadable(color_config), None) => {
523 Box::new(EmitterWriter::stderr(color_config,
524 Some(codemap.clone())))
526 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
527 Box::new(EmitterWriter::new(dst,
528 Some(codemap.clone())))
530 (config::ErrorOutputType::Json, None) => {
531 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
533 (config::ErrorOutputType::Json, Some(dst)) => {
534 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
538 let diagnostic_handler =
539 errors::Handler::with_emitter(can_print_warnings,
543 build_session_(sopts,
545 local_crate_source_file,
551 pub fn build_session_(sopts: config::Options,
552 dep_graph: &DepGraph,
553 local_crate_source_file: Option<PathBuf>,
554 span_diagnostic: errors::Handler,
555 codemap: Rc<codemap::CodeMap>,
556 cstore: Rc<for<'a> CrateStore<'a>>)
558 let host = match Target::search(config::host_triple()) {
561 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
564 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
565 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
566 let default_sysroot = match sopts.maybe_sysroot {
568 None => Some(filesearch::get_or_default_sysroot())
571 // Make the path absolute, if necessary
572 let local_crate_source_file = local_crate_source_file.map(|path|
573 if path.is_absolute() {
576 env::current_dir().unwrap().join(&path)
581 dep_graph: dep_graph.clone(),
587 // For a library crate, this is always none
588 entry_fn: RefCell::new(None),
589 entry_type: Cell::new(None),
590 plugin_registrar_fn: Cell::new(None),
591 derive_registrar_fn: Cell::new(None),
592 default_sysroot: default_sysroot,
593 local_crate_source_file: local_crate_source_file,
594 working_dir: env::current_dir().unwrap(),
595 lint_store: RefCell::new(lint::LintStore::new()),
596 lints: RefCell::new(NodeMap()),
597 one_time_diagnostics: RefCell::new(FnvHashSet()),
598 plugin_llvm_passes: RefCell::new(Vec::new()),
599 mir_passes: RefCell::new(mir_pass::Passes::new()),
600 plugin_attributes: RefCell::new(Vec::new()),
601 crate_types: RefCell::new(Vec::new()),
602 dependency_formats: RefCell::new(FnvHashMap()),
603 crate_disambiguator: RefCell::new(token::intern("").as_str()),
604 features: RefCell::new(feature_gate::Features::new()),
605 recursion_limit: Cell::new(64),
606 next_node_id: Cell::new(NodeId::new(1)),
607 injected_allocator: Cell::new(None),
608 injected_panic_runtime: Cell::new(None),
609 imported_macro_spans: RefCell::new(HashMap::new()),
610 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
611 perf_stats: PerfStats {
612 svh_time: Cell::new(Duration::from_secs(0)),
613 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
614 incr_comp_hashes_count: Cell::new(0),
615 incr_comp_bytes_hashed: Cell::new(0),
616 symbol_hash_time: Cell::new(Duration::from_secs(0)),
625 /// Holds data on the current incremental compilation session, if there is one.
627 pub enum IncrCompSession {
628 // This is the state the session will be in until the incr. comp. dir is
631 // This is the state during which the session directory is private and can
634 session_directory: PathBuf,
635 lock_file: flock::Lock,
637 // This is the state after the session directory has been finalized. In this
638 // state, the contents of the directory must not be modified any more.
640 session_directory: PathBuf,
642 // This is an error state that is reached when some compilation error has
643 // occurred. It indicates that the contents of the session directory must
644 // not be used, since they might be invalid.
645 InvalidBecauseOfErrors {
646 session_directory: PathBuf,
650 fn init_llvm(sess: &Session) {
652 // Before we touch LLVM, make sure that multithreading is enabled.
654 static INIT: Once = Once::new();
655 static mut POISONED: bool = false;
657 if llvm::LLVMStartMultithreaded() != 1 {
658 // use an extra bool to make sure that all future usage of LLVM
659 // cannot proceed despite the Once not running more than once.
663 configure_llvm(sess);
667 bug!("couldn't enable multi-threaded LLVM");
672 unsafe fn configure_llvm(sess: &Session) {
673 let mut llvm_c_strs = Vec::new();
674 let mut llvm_args = Vec::new();
677 let mut add = |arg: &str| {
678 let s = CString::new(arg).unwrap();
679 llvm_args.push(s.as_ptr());
682 add("rustc"); // fake program name
683 if sess.time_llvm_passes() { add("-time-passes"); }
684 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
686 for arg in &sess.opts.cg.llvm_args {
691 llvm::LLVMInitializePasses();
693 llvm::initialize_available_targets();
695 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
699 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
700 let emitter: Box<Emitter> = match output {
701 config::ErrorOutputType::HumanReadable(color_config) => {
702 Box::new(EmitterWriter::stderr(color_config,
705 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
707 let handler = errors::Handler::with_emitter(true, false, emitter);
708 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
709 panic!(errors::FatalError);
712 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
713 let emitter: Box<Emitter> = match output {
714 config::ErrorOutputType::HumanReadable(color_config) => {
715 Box::new(EmitterWriter::stderr(color_config,
718 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
720 let handler = errors::Handler::with_emitter(true, false, emitter);
721 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
724 // Err(0) means compilation was stopped, but no errors were found.
725 // This would be better as a dedicated enum, but using try! is so convenient.
726 pub type CompileResult = Result<(), usize>;
728 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
738 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
739 // this wrapper mostly exists so I don't have to write a fully
740 // qualified path of None::<Span> inside the bug!() macro defintion
741 opt_span_bug_fmt(file, line, None::<Span>, args);
746 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
749 args: fmt::Arguments) -> ! {
750 opt_span_bug_fmt(file, line, Some(span), args);
753 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
756 args: fmt::Arguments) -> ! {
757 tls::with_opt(move |tcx| {
758 let msg = format!("{}:{}: {}", file, line, args);
760 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
761 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
762 (None, _) => panic!(msg)