1 // Copyright 2012-2015 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 rustc::dep_graph::DepGraph;
12 use rustc::hir::{self, map as hir_map};
13 use rustc::hir::lowering::lower_crate;
14 use rustc::ich::Fingerprint;
15 use rustc_data_structures::stable_hasher::StableHasher;
17 use rustc::session::{CompileResult, CrateDisambiguator, Session};
18 use rustc::session::CompileIncomplete;
19 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
20 use rustc::session::search_paths::PathKind;
22 use rustc::middle::{self, reachable, resolve_lifetime, stability};
23 use rustc::middle::cstore::CrateStoreDyn;
24 use rustc::middle::privacy::AccessLevels;
25 use rustc::ty::{self, AllArenas, Resolutions, TyCtxt};
27 use rustc::util::common::{install_panic_hook, time, ErrorReported};
28 use rustc_allocator as allocator;
29 use rustc_borrowck as borrowck;
30 use rustc_incremental;
31 use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas};
32 use rustc_metadata::creader::CrateLoader;
33 use rustc_metadata::cstore::{self, CStore};
35 use rustc_codegen_utils::codegen_backend::CodegenBackend;
36 use rustc_typeck as typeck;
38 use rustc_plugin::registry::Registry;
39 use rustc_plugin as plugin;
40 use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion};
41 use super::Compilation;
47 use std::ffi::{OsStr, OsString};
49 use std::io::{self, Write};
51 use std::path::{Path, PathBuf};
52 use rustc_data_structures::sync::{self, Lrc, Lock};
54 use syntax::{self, ast, attr, diagnostics, visit};
55 use syntax::ext::base::ExtCtxt;
56 use syntax::fold::Folder;
57 use syntax::parse::{self, PResult};
58 use syntax::util::node_count::NodeCounter;
59 use syntax_pos::FileName;
63 use pretty::ReplaceBodyWithLoop;
67 #[cfg(not(parallel_queries))]
68 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
69 opts: config::Options,
72 ty::tls::GCX_PTR.set(&Lock::new(0), || {
77 #[cfg(parallel_queries)]
78 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
79 opts: config::Options,
84 use rayon::{ThreadPoolBuilder, ThreadPool};
86 let gcx_ptr = &Lock::new(0);
88 let config = ThreadPoolBuilder::new()
89 .num_threads(Session::query_threads_from_opts(&opts))
90 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() })
91 .stack_size(16 * 1024 * 1024);
93 let with_pool = move |pool: &ThreadPool| {
94 pool.install(move || f(opts))
97 syntax::GLOBALS.with(|syntax_globals| {
98 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
99 // The main handler run for each Rayon worker thread and sets up
100 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
101 // captured and set on the new threads. ty::tls::with_thread_locals sets up
102 // thread local callbacks from libsyntax
103 let main_handler = move |worker: &mut FnMut()| {
104 syntax::GLOBALS.set(syntax_globals, || {
105 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
106 ty::tls::with_thread_locals(|| {
107 ty::tls::GCX_PTR.set(gcx_ptr, || {
115 ThreadPool::scoped_pool(config, main_handler, with_pool).unwrap()
120 pub fn compile_input(
121 codegen_backend: Box<CodegenBackend>,
124 input_path: &Option<PathBuf>,
126 outdir: &Option<PathBuf>,
127 output: &Option<PathBuf>,
128 addl_plugins: Option<Vec<String>>,
129 control: &CompileController,
131 macro_rules! controller_entry_point {
132 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
133 let state = &mut $make_state;
134 let phase_result: &CompileResult = &$phase_result;
135 if phase_result.is_ok() || control.$point.run_callback_on_error {
136 (control.$point.callback)(state);
139 if control.$point.stop == Compilation::Stop {
140 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
141 // if there are no errors?
142 return $tsess.compile_status();
147 if sess.profile_queries() {
148 profile::begin(sess);
151 // We need nested scopes here, because the intermediate results can keep
152 // large chunks of memory alive and we want to free them as soon as
153 // possible to keep the peak memory usage low
154 let (outputs, ongoing_codegen, dep_graph) = {
155 let krate = match phase_1_parse_input(control, sess, input) {
157 Err(mut parse_error) => {
159 return Err(CompileIncomplete::Errored(ErrorReported));
163 let (krate, registry) = {
164 let mut compile_state =
165 CompileState::state_after_parse(input, sess, outdir, output, krate, &cstore);
166 controller_entry_point!(after_parse, sess, compile_state, Ok(()));
168 (compile_state.krate.unwrap(), compile_state.registry)
171 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
173 ::rustc_codegen_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
174 install_panic_hook();
176 let ExpansionResult {
183 phase_2_configure_and_expand(
190 control.make_glob_map,
192 let mut state = CompileState::state_after_expand(
201 controller_entry_point!(after_expand, sess, state, Ok(()));
207 let output_paths = generated_output_paths(sess, &outputs, output.is_some(), &crate_name);
209 // Ensure the source file isn't accidentally overwritten during compilation.
210 if let Some(ref input_path) = *input_path {
211 if sess.opts.will_create_output_file() {
212 if output_contains_path(&output_paths, input_path) {
214 "the input file \"{}\" would be overwritten by the generated \
218 return Err(CompileIncomplete::Stopped);
220 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
222 "the generated executable for the input file \"{}\" conflicts with the \
223 existing directory \"{}\"",
224 input_path.display(),
227 return Err(CompileIncomplete::Stopped);
232 write_out_deps(sess, &outputs, &output_paths);
233 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
234 && sess.opts.output_types.len() == 1
239 if let &Some(ref dir) = outdir {
240 if fs::create_dir_all(dir).is_err() {
241 sess.err("failed to find or create the directory specified by --out-dir");
242 return Err(CompileIncomplete::Stopped);
246 let arenas = AllArenas::new();
248 // Construct the HIR map
249 let hir_map = time(sess, "indexing hir", || {
250 hir_map::map_crate(sess, cstore, &mut hir_forest, &defs)
254 hir_map.dep_graph.assert_ignored();
255 controller_entry_point!(
258 CompileState::state_after_hir_lowering(
277 let opt_crate = if control.keep_ast {
278 Some(&expanded_crate)
280 drop(expanded_crate);
284 phase_3_run_analysis_passes(
295 |tcx, analysis, rx, result| {
297 // Eventually, we will want to track plugins.
298 tcx.dep_graph.with_ignore(|| {
299 let mut state = CompileState::state_after_analysis(
310 (control.after_analysis.callback)(&mut state);
313 if control.after_analysis.stop == Compilation::Stop {
314 return result.and_then(|_| Err(CompileIncomplete::Stopped));
320 if log_enabled!(::log::Level::Info) {
321 println!("Pre-codegen");
322 tcx.print_debug_stats();
325 let ongoing_codegen = phase_4_codegen(&*codegen_backend, tcx, rx);
327 if log_enabled!(::log::Level::Info) {
328 println!("Post-codegen");
329 tcx.print_debug_stats();
332 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
333 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
334 sess.err(&format!("could not emit MIR: {}", e));
335 sess.abort_if_errors();
339 Ok((outputs.clone(), ongoing_codegen, tcx.dep_graph.clone()))
344 if sess.opts.debugging_opts.print_type_sizes {
345 sess.code_stats.borrow().print_type_sizes();
348 codegen_backend.join_codegen_and_link(ongoing_codegen, sess, &dep_graph, &outputs)?;
350 if sess.opts.debugging_opts.perf_stats {
351 sess.print_perf_stats();
354 controller_entry_point!(
357 CompileState::state_when_compilation_done(input, sess, outdir, output),
364 pub fn source_name(input: &Input) -> FileName {
366 Input::File(ref ifile) => ifile.clone().into(),
367 Input::Str { ref name, .. } => name.clone(),
371 /// CompileController is used to customize compilation, it allows compilation to
372 /// be stopped and/or to call arbitrary code at various points in compilation.
373 /// It also allows for various flags to be set to influence what information gets
374 /// collected during compilation.
376 /// This is a somewhat higher level controller than a Session - the Session
377 /// controls what happens in each phase, whereas the CompileController controls
378 /// whether a phase is run at all and whether other code (from outside the
379 /// compiler) is run between phases.
381 /// Note that if compilation is set to stop and a callback is provided for a
382 /// given entry point, the callback is called before compilation is stopped.
384 /// Expect more entry points to be added in the future.
385 pub struct CompileController<'a> {
386 pub after_parse: PhaseController<'a>,
387 pub after_expand: PhaseController<'a>,
388 pub after_hir_lowering: PhaseController<'a>,
389 pub after_analysis: PhaseController<'a>,
390 pub compilation_done: PhaseController<'a>,
392 // FIXME we probably want to group the below options together and offer a
393 // better API, rather than this ad-hoc approach.
394 pub make_glob_map: MakeGlobMap,
395 // Whether the compiler should keep the ast beyond parsing.
397 // -Zcontinue-parse-after-error
398 pub continue_parse_after_error: bool,
400 /// Allows overriding default rustc query providers,
401 /// after `default_provide` has installed them.
402 pub provide: Box<Fn(&mut ty::query::Providers) + 'a>,
403 /// Same as `provide`, but only for non-local crates,
404 /// applied after `default_provide_extern`.
405 pub provide_extern: Box<Fn(&mut ty::query::Providers) + 'a>,
408 impl<'a> CompileController<'a> {
409 pub fn basic() -> CompileController<'a> {
411 after_parse: PhaseController::basic(),
412 after_expand: PhaseController::basic(),
413 after_hir_lowering: PhaseController::basic(),
414 after_analysis: PhaseController::basic(),
415 compilation_done: PhaseController::basic(),
416 make_glob_map: MakeGlobMap::No,
418 continue_parse_after_error: false,
420 provide_extern: box |_| {},
425 /// This implementation makes it easier to create a custom driver when you only want to hook
426 /// into callbacks from `CompileController`.
431 /// # extern crate rustc_driver;
432 /// # use rustc_driver::driver::CompileController;
433 /// let mut controller = CompileController::basic();
434 /// controller.after_analysis.callback = Box::new(move |_state| {});
435 /// rustc_driver::run_compiler(&[], Box::new(controller), None, None);
437 impl<'a> ::CompilerCalls<'a> for CompileController<'a> {
440 matches: &::getopts::Matches,
441 sopts: &config::Options,
442 cfg: &ast::CrateConfig,
443 descriptions: &::errors::registry::Registry,
444 output: ::ErrorOutputType,
446 ::RustcDefaultCalls.early_callback(
456 matches: &::getopts::Matches,
457 sopts: &config::Options,
458 cfg: &ast::CrateConfig,
459 odir: &Option<PathBuf>,
460 ofile: &Option<PathBuf>,
461 descriptions: &::errors::registry::Registry,
462 ) -> Option<(Input, Option<PathBuf>)> {
463 ::RustcDefaultCalls.no_input(
474 codegen_backend: &::CodegenBackend,
475 matches: &::getopts::Matches,
477 cstore: &::CrateStore,
479 odir: &Option<PathBuf>,
480 ofile: &Option<PathBuf>,
483 .late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
488 _: &::getopts::Matches
489 ) -> CompileController<'a> {
494 pub struct PhaseController<'a> {
495 pub stop: Compilation,
496 // If true then the compiler will try to run the callback even if the phase
497 // ends with an error. Note that this is not always possible.
498 pub run_callback_on_error: bool,
499 pub callback: Box<Fn(&mut CompileState) + 'a>,
502 impl<'a> PhaseController<'a> {
503 pub fn basic() -> PhaseController<'a> {
505 stop: Compilation::Continue,
506 run_callback_on_error: false,
507 callback: box |_| {},
512 /// State that is passed to a callback. What state is available depends on when
513 /// during compilation the callback is made. See the various constructor methods
514 /// (`state_*`) in the impl to see which data is provided for any given entry point.
515 pub struct CompileState<'a, 'tcx: 'a> {
516 pub input: &'a Input,
517 pub session: &'tcx Session,
518 pub krate: Option<ast::Crate>,
519 pub registry: Option<Registry<'a>>,
520 pub cstore: Option<&'tcx CStore>,
521 pub crate_name: Option<&'a str>,
522 pub output_filenames: Option<&'a OutputFilenames>,
523 pub out_dir: Option<&'a Path>,
524 pub out_file: Option<&'a Path>,
525 pub arenas: Option<&'tcx AllArenas<'tcx>>,
526 pub expanded_crate: Option<&'a ast::Crate>,
527 pub hir_crate: Option<&'a hir::Crate>,
528 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
529 pub resolutions: Option<&'a Resolutions>,
530 pub analysis: Option<&'a ty::CrateAnalysis>,
531 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
534 impl<'a, 'tcx> CompileState<'a, 'tcx> {
535 fn empty(input: &'a Input, session: &'tcx Session, out_dir: &'a Option<PathBuf>) -> Self {
539 out_dir: out_dir.as_ref().map(|s| &**s),
546 output_filenames: None,
547 expanded_crate: None,
556 fn state_after_parse(
558 session: &'tcx Session,
559 out_dir: &'a Option<PathBuf>,
560 out_file: &'a Option<PathBuf>,
562 cstore: &'tcx CStore,
565 // Initialize the registry before moving `krate`
566 registry: Some(Registry::new(&session, krate.span)),
568 cstore: Some(cstore),
569 out_file: out_file.as_ref().map(|s| &**s),
570 ..CompileState::empty(input, session, out_dir)
574 fn state_after_expand(
576 session: &'tcx Session,
577 out_dir: &'a Option<PathBuf>,
578 out_file: &'a Option<PathBuf>,
579 cstore: &'tcx CStore,
580 expanded_crate: &'a ast::Crate,
584 crate_name: Some(crate_name),
585 cstore: Some(cstore),
586 expanded_crate: Some(expanded_crate),
587 out_file: out_file.as_ref().map(|s| &**s),
588 ..CompileState::empty(input, session, out_dir)
592 fn state_after_hir_lowering(
594 session: &'tcx Session,
595 out_dir: &'a Option<PathBuf>,
596 out_file: &'a Option<PathBuf>,
597 arenas: &'tcx AllArenas<'tcx>,
598 cstore: &'tcx CStore,
599 hir_map: &'a hir_map::Map<'tcx>,
600 analysis: &'a ty::CrateAnalysis,
601 resolutions: &'a Resolutions,
602 krate: &'a ast::Crate,
603 hir_crate: &'a hir::Crate,
604 output_filenames: &'a OutputFilenames,
608 crate_name: Some(crate_name),
609 arenas: Some(arenas),
610 cstore: Some(cstore),
611 hir_map: Some(hir_map),
612 analysis: Some(analysis),
613 resolutions: Some(resolutions),
614 expanded_crate: Some(krate),
615 hir_crate: Some(hir_crate),
616 output_filenames: Some(output_filenames),
617 out_file: out_file.as_ref().map(|s| &**s),
618 ..CompileState::empty(input, session, out_dir)
622 fn state_after_analysis(
624 session: &'tcx Session,
625 out_dir: &'a Option<PathBuf>,
626 out_file: &'a Option<PathBuf>,
627 krate: Option<&'a ast::Crate>,
628 hir_crate: &'a hir::Crate,
629 analysis: &'a ty::CrateAnalysis,
630 tcx: TyCtxt<'a, 'tcx, 'tcx>,
634 analysis: Some(analysis),
636 expanded_crate: krate,
637 hir_crate: Some(hir_crate),
638 crate_name: Some(crate_name),
639 out_file: out_file.as_ref().map(|s| &**s),
640 ..CompileState::empty(input, session, out_dir)
644 fn state_when_compilation_done(
646 session: &'tcx Session,
647 out_dir: &'a Option<PathBuf>,
648 out_file: &'a Option<PathBuf>,
651 out_file: out_file.as_ref().map(|s| &**s),
652 ..CompileState::empty(input, session, out_dir)
657 pub fn phase_1_parse_input<'a>(
658 control: &CompileController,
661 ) -> PResult<'a, ast::Crate> {
663 .set_continue_after_error(control.continue_parse_after_error);
665 if sess.profile_queries() {
666 profile::begin(sess);
669 let krate = time(sess, "parsing", || match *input {
670 Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
674 } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
677 sess.diagnostic().set_continue_after_error(true);
679 if sess.opts.debugging_opts.ast_json_noexpand {
680 println!("{}", json::as_json(&krate));
683 if sess.opts.debugging_opts.input_stats {
686 sess.codemap().count_lines()
688 println!("Pre-expansion node count: {}", count_nodes(&krate));
691 if let Some(ref s) = sess.opts.debugging_opts.show_span {
692 syntax::show_span::run(sess.diagnostic(), s, &krate);
695 if sess.opts.debugging_opts.hir_stats {
696 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
702 fn count_nodes(krate: &ast::Crate) -> usize {
703 let mut counter = NodeCounter::new();
704 visit::walk_crate(&mut counter, krate);
708 // For continuing compilation after a parsed crate has been
711 pub struct ExpansionResult {
712 pub expanded_crate: ast::Crate,
713 pub defs: hir_map::Definitions,
714 pub analysis: ty::CrateAnalysis,
715 pub resolutions: Resolutions,
716 pub hir_forest: hir_map::Forest,
719 pub struct InnerExpansionResult<'a> {
720 pub expanded_crate: ast::Crate,
721 pub resolver: Resolver<'a>,
722 pub hir_forest: hir_map::Forest,
725 /// Run the "early phases" of the compiler: initial `cfg` processing,
726 /// loading compiler plugins (including those from `addl_plugins`),
727 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
728 /// harness if one is to be provided, injection of a dependency on the
729 /// standard library and prelude, and name resolution.
731 /// Returns `None` if we're aborting after handling -W help.
732 pub fn phase_2_configure_and_expand<F>(
736 registry: Option<Registry>,
738 addl_plugins: Option<Vec<String>>,
739 make_glob_map: MakeGlobMap,
741 ) -> Result<ExpansionResult, CompileIncomplete>
743 F: FnOnce(&ast::Crate) -> CompileResult,
745 // Currently, we ignore the name resolution data structures for the purposes of dependency
746 // tracking. Instead we will run name resolution and include its output in the hash of each
747 // item, much like we do for macro expansion. In other words, the hash reflects not just
748 // its contents but the results of name resolution on those contents. Hopefully we'll push
749 // this back at some point.
750 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
751 let resolver_arenas = Resolver::arenas();
752 let result = phase_2_configure_and_expand_inner(
765 Ok(InnerExpansionResult {
769 }) => Ok(ExpansionResult {
771 defs: resolver.definitions,
773 resolutions: Resolutions {
774 freevars: resolver.freevars,
775 export_map: resolver.export_map,
776 trait_map: resolver.trait_map,
777 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
778 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
781 analysis: ty::CrateAnalysis {
782 access_levels: Lrc::new(AccessLevels::default()),
783 name: crate_name.to_string(),
784 glob_map: if resolver.make_glob_map {
785 Some(resolver.glob_map)
795 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
797 pub fn phase_2_configure_and_expand_inner<'a, F>(
801 registry: Option<Registry>,
803 addl_plugins: Option<Vec<String>>,
804 make_glob_map: MakeGlobMap,
805 resolver_arenas: &'a ResolverArenas<'a>,
806 crate_loader: &'a mut CrateLoader,
808 ) -> Result<InnerExpansionResult<'a>, CompileIncomplete>
810 F: FnOnce(&ast::Crate) -> CompileResult,
812 let (mut krate, features) = syntax::config::features(
818 // these need to be set "early" so that expansion sees `quote` if enabled.
819 sess.init_features(features);
821 let crate_types = collect_crate_types(sess, &krate.attrs);
822 sess.crate_types.set(crate_types);
824 let disambiguator = compute_crate_disambiguator(sess);
825 sess.crate_disambiguator.set(disambiguator);
826 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
828 if sess.opts.incremental.is_some() {
829 time(sess, "garbage collect incremental cache directory", || {
830 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
832 "Error while trying to garbage collect incremental \
833 compilation cache directory: {}",
840 // If necessary, compute the dependency graph (in the background).
841 let future_dep_graph = if sess.opts.build_dep_graph() {
842 Some(rustc_incremental::load_dep_graph(sess))
847 time(sess, "recursion limit", || {
848 middle::recursion_limit::update_limits(sess, &krate);
851 krate = time(sess, "crate injection", || {
852 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
853 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
856 let mut addl_plugins = Some(addl_plugins);
857 let registrars = time(sess, "plugin loading", || {
858 plugin::load::load_plugins(
863 addl_plugins.take().unwrap(),
867 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
869 time(sess, "plugin registration", || {
870 if sess.features_untracked().rustc_diagnostic_macros {
871 registry.register_macro(
873 diagnostics::plugin::expand_diagnostic_used,
875 registry.register_macro(
876 "__register_diagnostic",
877 diagnostics::plugin::expand_register_diagnostic,
879 registry.register_macro(
880 "__build_diagnostic_array",
881 diagnostics::plugin::expand_build_diagnostic_array,
885 for registrar in registrars {
886 registry.args_hidden = Some(registrar.args);
887 (registrar.fun)(&mut registry);
891 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
902 sess.track_errors(|| {
903 let mut ls = sess.lint_store.borrow_mut();
904 for pass in early_lint_passes {
905 ls.register_early_pass(Some(sess), true, pass);
907 for pass in late_lint_passes {
908 ls.register_late_pass(Some(sess), true, pass);
911 for (name, to) in lint_groups {
912 ls.register_group(Some(sess), true, name, to);
915 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
916 *sess.plugin_attributes.borrow_mut() = attributes.clone();
919 // Lint plugins are registered; now we can process command line flags.
920 if sess.opts.describe_lints {
921 super::describe_lints(&sess, &sess.lint_store.borrow(), true);
922 return Err(CompileIncomplete::Stopped);
925 let mut resolver = Resolver::new(
934 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
935 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features_untracked().quote);
938 krate = time(sess, "expansion", || {
939 // Windows dlls do not have rpaths, so they don't know how to find their
940 // dependencies. It's up to us to tell the system where to find all the
941 // dependent dlls. Note that this uses cfg!(windows) as opposed to
942 // targ_cfg because syntax extensions are always loaded for the host
943 // compiler, not for the target.
945 // This is somewhat of an inherently racy operation, however, as
946 // multiple threads calling this function could possibly continue
947 // extending PATH far beyond what it should. To solve this for now we
948 // just don't add any new elements to PATH which are already there
949 // within PATH. This is basically a targeted fix at #17360 for rustdoc
950 // which runs rustc in parallel but has been seen (#33844) to cause
951 // problems with PATH becoming too long.
952 let mut old_path = OsString::new();
954 old_path = env::var_os("PATH").unwrap_or(old_path);
955 let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
956 for path in env::split_paths(&old_path) {
957 if !new_path.contains(&path) {
966 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
971 // Create the config for macro expansion
972 let features = sess.features_untracked();
973 let cfg = syntax::ext::expand::ExpansionConfig {
974 features: Some(&features),
975 recursion_limit: *sess.recursion_limit.get(),
976 trace_mac: sess.opts.debugging_opts.trace_macros,
977 should_test: sess.opts.test,
978 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
981 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
982 let err_count = ecx.parse_sess.span_diagnostic.err_count();
984 // Expand macros now!
985 let krate = time(sess, "expand crate", || {
986 ecx.monotonic_expander().expand_crate(krate)
989 // The rest is error reporting
991 time(sess, "check unused macros", || {
992 ecx.check_unused_macros();
995 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
996 .missing_fragment_specifiers
1001 missing_fragment_specifiers.sort();
1002 for span in missing_fragment_specifiers {
1003 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
1004 let msg = "missing fragment specifier";
1005 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
1007 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
1008 ecx.parse_sess.span_diagnostic.abort_if_errors();
1011 env::set_var("PATH", &old_path);
1016 krate = time(sess, "maybe building test harness", || {
1017 syntax::test::modify_for_testing(
1023 &sess.features_untracked(),
1027 // If we're actually rustdoc then there's no need to actually compile
1028 // anything, so switch everything to just looping
1029 if sess.opts.actually_rustdoc {
1030 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
1033 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
1034 // bunch of checks in the `modify` function below. For now just skip this
1035 // step entirely if we're rustdoc as it's not too useful anyway.
1036 if !sess.opts.actually_rustdoc {
1037 krate = time(sess, "maybe creating a macro crate", || {
1038 let crate_types = sess.crate_types.borrow();
1039 let num_crate_types = crate_types.len();
1040 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
1041 let is_test_crate = sess.opts.test;
1042 syntax_ext::proc_macro_registrar::modify(
1046 is_proc_macro_crate,
1054 // Expand global allocators, which are treated as an in-tree proc macro
1055 krate = time(sess, "creating allocators", || {
1056 allocator::expand::modify(
1060 crate_name.to_string(),
1065 // Done with macro expansion!
1067 after_expand(&krate)?;
1069 if sess.opts.debugging_opts.input_stats {
1070 println!("Post-expansion node count: {}", count_nodes(&krate));
1073 if sess.opts.debugging_opts.hir_stats {
1074 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
1077 if sess.opts.debugging_opts.ast_json {
1078 println!("{}", json::as_json(&krate));
1081 time(sess, "AST validation", || {
1082 ast_validation::check_crate(sess, &krate)
1085 time(sess, "name resolution", || -> CompileResult {
1086 resolver.resolve_crate(&krate);
1090 // Needs to go *after* expansion to be able to check the results of macro expansion.
1091 time(sess, "complete gated feature checking", || {
1092 sess.track_errors(|| {
1093 syntax::feature_gate::check_crate(
1096 &sess.features_untracked(),
1098 sess.opts.unstable_features,
1103 // Unresolved macros might be due to mistyped `#[macro_use]`,
1104 // so abort after checking for unknown attributes. (#49074)
1105 if resolver.found_unresolved_macro {
1106 sess.parse_sess.span_diagnostic.abort_if_errors();
1109 // Lower ast -> hir.
1110 // First, we need to collect the dep_graph.
1111 let dep_graph = match future_dep_graph {
1112 None => DepGraph::new_disabled(),
1114 let (prev_graph, prev_work_products) =
1115 time(sess, "blocked while dep-graph loading finishes", || {
1118 .unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
1119 message: format!("could not decode incremental cache: {:?}", e),
1123 DepGraph::new(prev_graph, prev_work_products)
1126 let hir_forest = time(sess, "lowering ast -> hir", || {
1127 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
1129 if sess.opts.debugging_opts.hir_stats {
1130 hir_stats::print_hir_stats(&hir_crate);
1133 hir_map::Forest::new(hir_crate, &dep_graph)
1136 time(sess, "early lint checks", || {
1137 lint::check_ast_crate(sess, &krate)
1140 // Discard hygiene data, which isn't required after lowering to HIR.
1141 if !sess.opts.debugging_opts.keep_hygiene_data {
1142 syntax::ext::hygiene::clear_markings();
1145 Ok(InnerExpansionResult {
1146 expanded_crate: krate,
1152 pub fn default_provide(providers: &mut ty::query::Providers) {
1153 hir::provide(providers);
1154 borrowck::provide(providers);
1155 mir::provide(providers);
1156 reachable::provide(providers);
1157 resolve_lifetime::provide(providers);
1158 rustc_privacy::provide(providers);
1159 typeck::provide(providers);
1160 ty::provide(providers);
1161 traits::provide(providers);
1162 reachable::provide(providers);
1163 rustc_passes::provide(providers);
1164 rustc_traits::provide(providers);
1165 middle::region::provide(providers);
1166 cstore::provide(providers);
1167 lint::provide(providers);
1170 pub fn default_provide_extern(providers: &mut ty::query::Providers) {
1171 cstore::provide_extern(providers);
1174 /// Run the resolution, typechecking, region checking and other
1175 /// miscellaneous analysis passes on the crate. Return various
1176 /// structures carrying the results of the analysis.
1177 pub fn phase_3_run_analysis_passes<'tcx, F, R>(
1178 codegen_backend: &CodegenBackend,
1179 control: &CompileController,
1180 sess: &'tcx Session,
1181 cstore: &'tcx CrateStoreDyn,
1182 hir_map: hir_map::Map<'tcx>,
1183 mut analysis: ty::CrateAnalysis,
1184 resolutions: Resolutions,
1185 arenas: &'tcx AllArenas<'tcx>,
1187 output_filenames: &OutputFilenames,
1189 ) -> Result<R, CompileIncomplete>
1192 TyCtxt<'a, 'tcx, 'tcx>,
1194 mpsc::Receiver<Box<Any + Send>>,
1198 let query_result_on_disk_cache = time(sess, "load query result cache", || {
1199 rustc_incremental::load_query_result_cache(sess)
1202 time(sess, "looking for entry point", || {
1203 middle::entry::find_entry_point(sess, &hir_map, name)
1206 sess.plugin_registrar_fn
1207 .set(time(sess, "looking for plugin registrar", || {
1208 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
1210 sess.derive_registrar_fn
1211 .set(derive_registrar::find(&hir_map));
1213 time(sess, "loop checking", || loops::check_crate(sess, &hir_map));
1215 let mut local_providers = ty::query::Providers::default();
1216 default_provide(&mut local_providers);
1217 codegen_backend.provide(&mut local_providers);
1218 (control.provide)(&mut local_providers);
1220 let mut extern_providers = local_providers;
1221 default_provide_extern(&mut extern_providers);
1222 codegen_backend.provide_extern(&mut extern_providers);
1223 (control.provide_extern)(&mut extern_providers);
1225 let (tx, rx) = mpsc::channel();
1227 TyCtxt::create_and_enter(
1235 query_result_on_disk_cache,
1240 // Do some initialization of the DepGraph that can only be done with the
1242 rustc_incremental::dep_graph_tcx_init(tcx);
1244 time(sess, "attribute checking", || {
1245 hir::check_attr::check_crate(tcx)
1248 time(sess, "stability checking", || {
1249 stability::check_unstable_api_usage(tcx)
1252 // passes are timed inside typeck
1253 match typeck::check_crate(tcx) {
1256 f(tcx, analysis, rx, Err(x));
1261 time(sess, "rvalue promotion", || {
1262 rvalue_promotion::check_crate(tcx)
1265 analysis.access_levels =
1266 time(sess, "privacy checking", || rustc_privacy::check_crate(tcx));
1268 time(sess, "intrinsic checking", || {
1269 middle::intrinsicck::check_crate(tcx)
1272 time(sess, "match checking", || mir::matchck_crate(tcx));
1274 // this must run before MIR dump, because
1275 // "not all control paths return a value" is reported here.
1277 // maybe move the check to a MIR pass?
1278 time(sess, "liveness checking", || {
1279 middle::liveness::check_crate(tcx)
1282 time(sess, "borrow checking", || borrowck::check_crate(tcx));
1285 "MIR borrow checking",
1286 || tcx.par_body_owners(|def_id| { tcx.mir_borrowck(def_id); }));
1288 time(sess, "dumping chalk-like clauses", || {
1289 rustc_traits::lowering::dump_program_clauses(tcx);
1292 time(sess, "MIR effect checking", || {
1293 for def_id in tcx.body_owners() {
1294 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1297 // Avoid overwhelming user with errors if type checking failed.
1298 // I'm not sure how helpful this is, to be honest, but it avoids
1300 // lot of annoying errors in the compile-fail tests (basically,
1301 // lint warnings and so on -- kindck used to do this abort, but
1302 // kindck is gone now). -nmatsakis
1303 if sess.err_count() > 0 {
1304 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1307 time(sess, "death checking", || middle::dead::check_crate(tcx));
1309 time(sess, "unused lib feature checking", || {
1310 stability::check_unused_or_stable_features(tcx)
1313 time(sess, "lint checking", || lint::check_crate(tcx));
1315 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1320 /// Run the codegen backend, after which the AST and analysis can
1322 pub fn phase_4_codegen<'a, 'tcx>(
1323 codegen_backend: &CodegenBackend,
1324 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1325 rx: mpsc::Receiver<Box<Any + Send>>,
1327 time(tcx.sess, "resolving dependency formats", || {
1328 ::rustc::middle::dependency_format::calculate(tcx)
1331 let codegen = time(tcx.sess, "codegen", move || codegen_backend.codegen_crate(tcx, rx));
1332 if tcx.sess.profile_queries() {
1333 profile::dump(&tcx.sess, "profile_queries".to_string())
1339 fn escape_dep_filename(filename: &FileName) -> String {
1340 // Apparently clang and gcc *only* escape spaces:
1341 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1342 filename.to_string().replace(" ", "\\ ")
1345 // Returns all the paths that correspond to generated files.
1346 fn generated_output_paths(
1348 outputs: &OutputFilenames,
1352 let mut out_filenames = Vec::new();
1353 for output_type in sess.opts.output_types.keys() {
1354 let file = outputs.path(*output_type);
1355 match *output_type {
1356 // If the filename has been overridden using `-o`, it will not be modified
1357 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1358 OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
1359 let p = ::rustc_codegen_utils::link::filename_for_input(
1365 out_filenames.push(p);
1367 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1368 // Don't add the dep-info output when omitting it from dep-info targets
1371 out_filenames.push(file);
1378 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1379 // returns None for every file path.
1380 fn check_output<F, T>(output_paths: &Vec<PathBuf>, f: F) -> Option<T>
1382 F: Fn(&PathBuf) -> Option<T>,
1384 for output_path in output_paths {
1385 if let Some(result) = f(output_path) {
1386 return Some(result);
1392 pub fn output_contains_path(output_paths: &Vec<PathBuf>, input_path: &PathBuf) -> bool {
1393 let input_path = input_path.canonicalize().ok();
1394 if input_path.is_none() {
1397 let check = |output_path: &PathBuf| {
1398 if output_path.canonicalize().ok() == input_path {
1404 check_output(output_paths, check).is_some()
1407 pub fn output_conflicts_with_dir(output_paths: &Vec<PathBuf>) -> Option<PathBuf> {
1408 let check = |output_path: &PathBuf| {
1409 if output_path.is_dir() {
1410 Some(output_path.clone())
1415 check_output(output_paths, check)
1418 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &Vec<PathBuf>) {
1419 // Write out dependency rules to the dep-info file if requested
1420 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1423 let deps_filename = outputs.path(OutputType::DepInfo);
1425 let result = (|| -> io::Result<()> {
1426 // Build a list of files used to compile the output and
1427 // write Makefile-compatible dependency rules
1428 let files: Vec<String> = sess.codemap()
1431 .filter(|fmap| fmap.is_real_file())
1432 .filter(|fmap| !fmap.is_imported())
1433 .map(|fmap| escape_dep_filename(&fmap.name))
1435 let mut file = fs::File::create(&deps_filename)?;
1436 for path in out_filenames {
1437 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1440 // Emit a fake target for each input file to the compilation. This
1441 // prevents `make` from spitting out an error if a file is later
1442 // deleted. For more info see #28735
1444 writeln!(file, "{}:", path)?;
1452 sess.fatal(&format!(
1453 "error writing dependencies to `{}`: {}",
1454 deps_filename.display(),
1461 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1462 // Unconditionally collect crate types from attributes to make them used
1463 let attr_types: Vec<config::CrateType> = attrs
1466 if a.check_name("crate_type") {
1467 match a.value_str() {
1468 Some(ref n) if *n == "rlib" => Some(config::CrateTypeRlib),
1469 Some(ref n) if *n == "dylib" => Some(config::CrateTypeDylib),
1470 Some(ref n) if *n == "cdylib" => Some(config::CrateTypeCdylib),
1471 Some(ref n) if *n == "lib" => Some(config::default_lib_output()),
1472 Some(ref n) if *n == "staticlib" => Some(config::CrateTypeStaticlib),
1473 Some(ref n) if *n == "proc-macro" => Some(config::CrateTypeProcMacro),
1474 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1476 session.buffer_lint(
1477 lint::builtin::UNKNOWN_CRATE_TYPES,
1480 "invalid `crate_type` value",
1486 .struct_span_err(a.span, "`crate_type` requires a value")
1487 .note("for example: `#![crate_type=\"lib\"]`")
1498 // If we're generating a test executable, then ignore all other output
1499 // styles at all other locations
1500 if session.opts.test {
1501 return vec![config::CrateTypeExecutable];
1504 // Only check command line flags if present. If no types are specified by
1505 // command line, then reuse the empty `base` Vec to hold the types that
1506 // will be found in crate attributes.
1507 let mut base = session.opts.crate_types.clone();
1508 if base.is_empty() {
1509 base.extend(attr_types);
1510 if base.is_empty() {
1511 base.push(::rustc_codegen_utils::link::default_output_for_target(
1520 .filter(|crate_type| {
1521 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
1524 session.warn(&format!(
1525 "dropping unsupported crate type `{}` for target `{}`",
1526 *crate_type, session.opts.target_triple
1535 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1536 use std::hash::Hasher;
1538 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1539 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1540 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1541 // should still be safe enough to avoid collisions in practice.
1542 let mut hasher = StableHasher::<Fingerprint>::new();
1544 let mut metadata = session.opts.cg.metadata.clone();
1545 // We don't want the crate_disambiguator to dependent on the order
1546 // -C metadata arguments, so sort them:
1548 // Every distinct -C metadata value is only incorporated once:
1551 hasher.write(b"metadata");
1552 for s in &metadata {
1553 // Also incorporate the length of a metadata string, so that we generate
1554 // different values for `-Cmetadata=ab -Cmetadata=c` and
1555 // `-Cmetadata=a -Cmetadata=bc`
1556 hasher.write_usize(s.len());
1557 hasher.write(s.as_bytes());
1560 // Also incorporate crate type, so that we don't get symbol conflicts when
1561 // linking against a library of the same name, if this is an executable.
1562 let is_exe = session
1565 .contains(&config::CrateTypeExecutable);
1566 hasher.write(if is_exe { b"exe" } else { b"lib" });
1568 CrateDisambiguator::from(hasher.finish())
1571 pub fn build_output_filenames(
1573 odir: &Option<PathBuf>,
1574 ofile: &Option<PathBuf>,
1575 attrs: &[ast::Attribute],
1577 ) -> OutputFilenames {
1580 // "-" as input file will cause the parser to read from stdin so we
1581 // have to make up a name
1582 // We want to toss everything after the final '.'
1583 let dirpath = match *odir {
1584 Some(ref d) => d.clone(),
1585 None => PathBuf::new(),
1588 // If a crate name is present, we use it as the link name
1589 let stem = sess.opts
1592 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1593 .unwrap_or(input.filestem());
1596 out_directory: dirpath,
1598 single_output_file: None,
1599 extra: sess.opts.cg.extra_filename.clone(),
1600 outputs: sess.opts.output_types.clone(),
1604 Some(ref out_file) => {
1605 let unnamed_output_types = sess.opts
1608 .filter(|a| a.is_none())
1610 let ofile = if unnamed_output_types > 1 {
1612 "due to multiple output types requested, the explicitly specified \
1613 output file name will be adapted for each output type",
1617 Some(out_file.clone())
1620 sess.warn("ignoring --out-dir flag due to -o flag");
1622 if !sess.opts.cg.extra_filename.is_empty() {
1623 sess.warn("ignoring -C extra-filename flag due to -o flag");
1626 let cur_dir = Path::new("");
1629 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1630 out_filestem: out_file
1632 .unwrap_or(OsStr::new(""))
1636 single_output_file: ofile,
1637 extra: sess.opts.cg.extra_filename.clone(),
1638 outputs: sess.opts.output_types.clone(),