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 time(sess, "pre ast expansion lint checks", || {
926 lint::check_ast_crate(sess, &krate, true)
929 let mut resolver = Resolver::new(
938 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
939 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features_untracked().quote);
942 krate = time(sess, "expansion", || {
943 // Windows dlls do not have rpaths, so they don't know how to find their
944 // dependencies. It's up to us to tell the system where to find all the
945 // dependent dlls. Note that this uses cfg!(windows) as opposed to
946 // targ_cfg because syntax extensions are always loaded for the host
947 // compiler, not for the target.
949 // This is somewhat of an inherently racy operation, however, as
950 // multiple threads calling this function could possibly continue
951 // extending PATH far beyond what it should. To solve this for now we
952 // just don't add any new elements to PATH which are already there
953 // within PATH. This is basically a targeted fix at #17360 for rustdoc
954 // which runs rustc in parallel but has been seen (#33844) to cause
955 // problems with PATH becoming too long.
956 let mut old_path = OsString::new();
958 old_path = env::var_os("PATH").unwrap_or(old_path);
959 let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
960 for path in env::split_paths(&old_path) {
961 if !new_path.contains(&path) {
970 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
975 // Create the config for macro expansion
976 let features = sess.features_untracked();
977 let cfg = syntax::ext::expand::ExpansionConfig {
978 features: Some(&features),
979 recursion_limit: *sess.recursion_limit.get(),
980 trace_mac: sess.opts.debugging_opts.trace_macros,
981 should_test: sess.opts.test,
982 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
985 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
986 let err_count = ecx.parse_sess.span_diagnostic.err_count();
988 // Expand macros now!
989 let krate = time(sess, "expand crate", || {
990 ecx.monotonic_expander().expand_crate(krate)
993 // The rest is error reporting
995 time(sess, "check unused macros", || {
996 ecx.check_unused_macros();
999 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
1000 .missing_fragment_specifiers
1005 missing_fragment_specifiers.sort();
1006 for span in missing_fragment_specifiers {
1007 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
1008 let msg = "missing fragment specifier";
1009 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
1011 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
1012 ecx.parse_sess.span_diagnostic.abort_if_errors();
1015 env::set_var("PATH", &old_path);
1020 krate = time(sess, "maybe building test harness", || {
1021 syntax::test::modify_for_testing(
1027 &sess.features_untracked(),
1031 // If we're actually rustdoc then there's no need to actually compile
1032 // anything, so switch everything to just looping
1033 if sess.opts.actually_rustdoc {
1034 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
1037 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
1038 // bunch of checks in the `modify` function below. For now just skip this
1039 // step entirely if we're rustdoc as it's not too useful anyway.
1040 if !sess.opts.actually_rustdoc {
1041 krate = time(sess, "maybe creating a macro crate", || {
1042 let crate_types = sess.crate_types.borrow();
1043 let num_crate_types = crate_types.len();
1044 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
1045 let is_test_crate = sess.opts.test;
1046 syntax_ext::proc_macro_registrar::modify(
1050 is_proc_macro_crate,
1058 // Expand global allocators, which are treated as an in-tree proc macro
1059 krate = time(sess, "creating allocators", || {
1060 allocator::expand::modify(
1064 crate_name.to_string(),
1069 // Done with macro expansion!
1071 after_expand(&krate)?;
1073 if sess.opts.debugging_opts.input_stats {
1074 println!("Post-expansion node count: {}", count_nodes(&krate));
1077 if sess.opts.debugging_opts.hir_stats {
1078 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
1081 if sess.opts.debugging_opts.ast_json {
1082 println!("{}", json::as_json(&krate));
1085 time(sess, "AST validation", || {
1086 ast_validation::check_crate(sess, &krate)
1089 time(sess, "name resolution", || -> CompileResult {
1090 resolver.resolve_crate(&krate);
1094 // Needs to go *after* expansion to be able to check the results of macro expansion.
1095 time(sess, "complete gated feature checking", || {
1096 sess.track_errors(|| {
1097 syntax::feature_gate::check_crate(
1100 &sess.features_untracked(),
1102 sess.opts.unstable_features,
1107 // Unresolved macros might be due to mistyped `#[macro_use]`,
1108 // so abort after checking for unknown attributes. (#49074)
1109 if resolver.found_unresolved_macro {
1110 sess.parse_sess.span_diagnostic.abort_if_errors();
1113 // Lower ast -> hir.
1114 // First, we need to collect the dep_graph.
1115 let dep_graph = match future_dep_graph {
1116 None => DepGraph::new_disabled(),
1118 let (prev_graph, prev_work_products) =
1119 time(sess, "blocked while dep-graph loading finishes", || {
1122 .unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
1123 message: format!("could not decode incremental cache: {:?}", e),
1127 DepGraph::new(prev_graph, prev_work_products)
1130 let hir_forest = time(sess, "lowering ast -> hir", || {
1131 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
1133 if sess.opts.debugging_opts.hir_stats {
1134 hir_stats::print_hir_stats(&hir_crate);
1137 hir_map::Forest::new(hir_crate, &dep_graph)
1140 time(sess, "early lint checks", || {
1141 lint::check_ast_crate(sess, &krate, false)
1144 // Discard hygiene data, which isn't required after lowering to HIR.
1145 if !sess.opts.debugging_opts.keep_hygiene_data {
1146 syntax::ext::hygiene::clear_markings();
1149 Ok(InnerExpansionResult {
1150 expanded_crate: krate,
1156 pub fn default_provide(providers: &mut ty::query::Providers) {
1157 hir::provide(providers);
1158 borrowck::provide(providers);
1159 mir::provide(providers);
1160 reachable::provide(providers);
1161 resolve_lifetime::provide(providers);
1162 rustc_privacy::provide(providers);
1163 typeck::provide(providers);
1164 ty::provide(providers);
1165 traits::provide(providers);
1166 reachable::provide(providers);
1167 rustc_passes::provide(providers);
1168 rustc_traits::provide(providers);
1169 middle::region::provide(providers);
1170 cstore::provide(providers);
1171 lint::provide(providers);
1174 pub fn default_provide_extern(providers: &mut ty::query::Providers) {
1175 cstore::provide_extern(providers);
1178 /// Run the resolution, typechecking, region checking and other
1179 /// miscellaneous analysis passes on the crate. Return various
1180 /// structures carrying the results of the analysis.
1181 pub fn phase_3_run_analysis_passes<'tcx, F, R>(
1182 codegen_backend: &CodegenBackend,
1183 control: &CompileController,
1184 sess: &'tcx Session,
1185 cstore: &'tcx CrateStoreDyn,
1186 hir_map: hir_map::Map<'tcx>,
1187 mut analysis: ty::CrateAnalysis,
1188 resolutions: Resolutions,
1189 arenas: &'tcx AllArenas<'tcx>,
1191 output_filenames: &OutputFilenames,
1193 ) -> Result<R, CompileIncomplete>
1196 TyCtxt<'a, 'tcx, 'tcx>,
1198 mpsc::Receiver<Box<Any + Send>>,
1202 let query_result_on_disk_cache = time(sess, "load query result cache", || {
1203 rustc_incremental::load_query_result_cache(sess)
1206 time(sess, "looking for entry point", || {
1207 middle::entry::find_entry_point(sess, &hir_map, name)
1210 sess.plugin_registrar_fn
1211 .set(time(sess, "looking for plugin registrar", || {
1212 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
1214 sess.derive_registrar_fn
1215 .set(derive_registrar::find(&hir_map));
1217 time(sess, "loop checking", || loops::check_crate(sess, &hir_map));
1219 let mut local_providers = ty::query::Providers::default();
1220 default_provide(&mut local_providers);
1221 codegen_backend.provide(&mut local_providers);
1222 (control.provide)(&mut local_providers);
1224 let mut extern_providers = local_providers;
1225 default_provide_extern(&mut extern_providers);
1226 codegen_backend.provide_extern(&mut extern_providers);
1227 (control.provide_extern)(&mut extern_providers);
1229 let (tx, rx) = mpsc::channel();
1231 TyCtxt::create_and_enter(
1239 query_result_on_disk_cache,
1244 // Do some initialization of the DepGraph that can only be done with the
1246 rustc_incremental::dep_graph_tcx_init(tcx);
1248 time(sess, "attribute checking", || {
1249 hir::check_attr::check_crate(tcx)
1252 time(sess, "stability checking", || {
1253 stability::check_unstable_api_usage(tcx)
1256 // passes are timed inside typeck
1257 match typeck::check_crate(tcx) {
1260 f(tcx, analysis, rx, Err(x));
1265 time(sess, "rvalue promotion", || {
1266 rvalue_promotion::check_crate(tcx)
1269 analysis.access_levels =
1270 time(sess, "privacy checking", || rustc_privacy::check_crate(tcx));
1272 time(sess, "intrinsic checking", || {
1273 middle::intrinsicck::check_crate(tcx)
1276 time(sess, "match checking", || mir::matchck_crate(tcx));
1278 // this must run before MIR dump, because
1279 // "not all control paths return a value" is reported here.
1281 // maybe move the check to a MIR pass?
1282 time(sess, "liveness checking", || {
1283 middle::liveness::check_crate(tcx)
1286 time(sess, "borrow checking", || {
1287 if tcx.use_ast_borrowck() {
1288 borrowck::check_crate(tcx);
1293 "MIR borrow checking",
1294 || tcx.par_body_owners(|def_id| { tcx.mir_borrowck(def_id); }));
1296 time(sess, "dumping chalk-like clauses", || {
1297 rustc_traits::lowering::dump_program_clauses(tcx);
1300 time(sess, "MIR effect checking", || {
1301 for def_id in tcx.body_owners() {
1302 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1305 // Avoid overwhelming user with errors if type checking failed.
1306 // I'm not sure how helpful this is, to be honest, but it avoids
1308 // lot of annoying errors in the compile-fail tests (basically,
1309 // lint warnings and so on -- kindck used to do this abort, but
1310 // kindck is gone now). -nmatsakis
1311 if sess.err_count() > 0 {
1312 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1315 time(sess, "death checking", || middle::dead::check_crate(tcx));
1317 time(sess, "unused lib feature checking", || {
1318 stability::check_unused_or_stable_features(tcx)
1321 time(sess, "lint checking", || lint::check_crate(tcx));
1323 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1328 /// Run the codegen backend, after which the AST and analysis can
1330 pub fn phase_4_codegen<'a, 'tcx>(
1331 codegen_backend: &CodegenBackend,
1332 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1333 rx: mpsc::Receiver<Box<Any + Send>>,
1335 time(tcx.sess, "resolving dependency formats", || {
1336 ::rustc::middle::dependency_format::calculate(tcx)
1339 let codegen = time(tcx.sess, "codegen", move || codegen_backend.codegen_crate(tcx, rx));
1340 if tcx.sess.profile_queries() {
1341 profile::dump(&tcx.sess, "profile_queries".to_string())
1347 fn escape_dep_filename(filename: &FileName) -> String {
1348 // Apparently clang and gcc *only* escape spaces:
1349 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1350 filename.to_string().replace(" ", "\\ ")
1353 // Returns all the paths that correspond to generated files.
1354 fn generated_output_paths(
1356 outputs: &OutputFilenames,
1360 let mut out_filenames = Vec::new();
1361 for output_type in sess.opts.output_types.keys() {
1362 let file = outputs.path(*output_type);
1363 match *output_type {
1364 // If the filename has been overridden using `-o`, it will not be modified
1365 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1366 OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
1367 let p = ::rustc_codegen_utils::link::filename_for_input(
1373 out_filenames.push(p);
1375 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1376 // Don't add the dep-info output when omitting it from dep-info targets
1379 out_filenames.push(file);
1386 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1387 // returns None for every file path.
1388 fn check_output<F, T>(output_paths: &Vec<PathBuf>, f: F) -> Option<T>
1390 F: Fn(&PathBuf) -> Option<T>,
1392 for output_path in output_paths {
1393 if let Some(result) = f(output_path) {
1394 return Some(result);
1400 pub fn output_contains_path(output_paths: &Vec<PathBuf>, input_path: &PathBuf) -> bool {
1401 let input_path = input_path.canonicalize().ok();
1402 if input_path.is_none() {
1405 let check = |output_path: &PathBuf| {
1406 if output_path.canonicalize().ok() == input_path {
1412 check_output(output_paths, check).is_some()
1415 pub fn output_conflicts_with_dir(output_paths: &Vec<PathBuf>) -> Option<PathBuf> {
1416 let check = |output_path: &PathBuf| {
1417 if output_path.is_dir() {
1418 Some(output_path.clone())
1423 check_output(output_paths, check)
1426 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &Vec<PathBuf>) {
1427 // Write out dependency rules to the dep-info file if requested
1428 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1431 let deps_filename = outputs.path(OutputType::DepInfo);
1433 let result = (|| -> io::Result<()> {
1434 // Build a list of files used to compile the output and
1435 // write Makefile-compatible dependency rules
1436 let files: Vec<String> = sess.codemap()
1439 .filter(|fmap| fmap.is_real_file())
1440 .filter(|fmap| !fmap.is_imported())
1441 .map(|fmap| escape_dep_filename(&fmap.name))
1443 let mut file = fs::File::create(&deps_filename)?;
1444 for path in out_filenames {
1445 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1448 // Emit a fake target for each input file to the compilation. This
1449 // prevents `make` from spitting out an error if a file is later
1450 // deleted. For more info see #28735
1452 writeln!(file, "{}:", path)?;
1460 sess.fatal(&format!(
1461 "error writing dependencies to `{}`: {}",
1462 deps_filename.display(),
1469 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1470 // Unconditionally collect crate types from attributes to make them used
1471 let attr_types: Vec<config::CrateType> = attrs
1474 if a.check_name("crate_type") {
1475 match a.value_str() {
1476 Some(ref n) if *n == "rlib" => Some(config::CrateTypeRlib),
1477 Some(ref n) if *n == "dylib" => Some(config::CrateTypeDylib),
1478 Some(ref n) if *n == "cdylib" => Some(config::CrateTypeCdylib),
1479 Some(ref n) if *n == "lib" => Some(config::default_lib_output()),
1480 Some(ref n) if *n == "staticlib" => Some(config::CrateTypeStaticlib),
1481 Some(ref n) if *n == "proc-macro" => Some(config::CrateTypeProcMacro),
1482 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1484 session.buffer_lint(
1485 lint::builtin::UNKNOWN_CRATE_TYPES,
1488 "invalid `crate_type` value",
1494 .struct_span_err(a.span, "`crate_type` requires a value")
1495 .note("for example: `#![crate_type=\"lib\"]`")
1506 // If we're generating a test executable, then ignore all other output
1507 // styles at all other locations
1508 if session.opts.test {
1509 return vec![config::CrateTypeExecutable];
1512 // Only check command line flags if present. If no types are specified by
1513 // command line, then reuse the empty `base` Vec to hold the types that
1514 // will be found in crate attributes.
1515 let mut base = session.opts.crate_types.clone();
1516 if base.is_empty() {
1517 base.extend(attr_types);
1518 if base.is_empty() {
1519 base.push(::rustc_codegen_utils::link::default_output_for_target(
1528 .filter(|crate_type| {
1529 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
1532 session.warn(&format!(
1533 "dropping unsupported crate type `{}` for target `{}`",
1534 *crate_type, session.opts.target_triple
1543 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1544 use std::hash::Hasher;
1546 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1547 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1548 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1549 // should still be safe enough to avoid collisions in practice.
1550 let mut hasher = StableHasher::<Fingerprint>::new();
1552 let mut metadata = session.opts.cg.metadata.clone();
1553 // We don't want the crate_disambiguator to dependent on the order
1554 // -C metadata arguments, so sort them:
1556 // Every distinct -C metadata value is only incorporated once:
1559 hasher.write(b"metadata");
1560 for s in &metadata {
1561 // Also incorporate the length of a metadata string, so that we generate
1562 // different values for `-Cmetadata=ab -Cmetadata=c` and
1563 // `-Cmetadata=a -Cmetadata=bc`
1564 hasher.write_usize(s.len());
1565 hasher.write(s.as_bytes());
1568 // Also incorporate crate type, so that we don't get symbol conflicts when
1569 // linking against a library of the same name, if this is an executable.
1570 let is_exe = session
1573 .contains(&config::CrateTypeExecutable);
1574 hasher.write(if is_exe { b"exe" } else { b"lib" });
1576 CrateDisambiguator::from(hasher.finish())
1579 pub fn build_output_filenames(
1581 odir: &Option<PathBuf>,
1582 ofile: &Option<PathBuf>,
1583 attrs: &[ast::Attribute],
1585 ) -> OutputFilenames {
1588 // "-" as input file will cause the parser to read from stdin so we
1589 // have to make up a name
1590 // We want to toss everything after the final '.'
1591 let dirpath = match *odir {
1592 Some(ref d) => d.clone(),
1593 None => PathBuf::new(),
1596 // If a crate name is present, we use it as the link name
1597 let stem = sess.opts
1600 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1601 .unwrap_or(input.filestem());
1604 out_directory: dirpath,
1606 single_output_file: None,
1607 extra: sess.opts.cg.extra_filename.clone(),
1608 outputs: sess.opts.output_types.clone(),
1612 Some(ref out_file) => {
1613 let unnamed_output_types = sess.opts
1616 .filter(|a| a.is_none())
1618 let ofile = if unnamed_output_types > 1 {
1620 "due to multiple output types requested, the explicitly specified \
1621 output file name will be adapted for each output type",
1625 Some(out_file.clone())
1628 sess.warn("ignoring --out-dir flag due to -o flag");
1630 if !sess.opts.cg.extra_filename.is_empty() {
1631 sess.warn("ignoring -C extra-filename flag due to -o flag");
1634 let cur_dir = Path::new("");
1637 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1638 out_filestem: out_file
1640 .unwrap_or(OsStr::new(""))
1644 single_output_file: ofile,
1645 extra: sess.opts.cg.extra_filename.clone(),
1646 outputs: sess.opts.output_types.clone(),