1 use rustc::dep_graph::DepGraph;
3 use rustc::hir::lowering::lower_crate;
4 use rustc::hir::map as hir_map;
6 use rustc::middle::{self, reachable, resolve_lifetime, stability};
7 use rustc::ty::{self, AllArenas, Resolutions, TyCtxt};
9 use rustc::util::common::{install_panic_hook, time, ErrorReported};
10 use rustc::util::profiling::ProfileCategory;
11 use rustc::session::{CompileResult, CrateDisambiguator, Session};
12 use rustc::session::CompileIncomplete;
13 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
14 use rustc::session::search_paths::PathKind;
15 use rustc_allocator as allocator;
16 use rustc_borrowck as borrowck;
17 use rustc_codegen_utils::codegen_backend::CodegenBackend;
18 use rustc_data_structures::fingerprint::Fingerprint;
19 use rustc_data_structures::stable_hasher::StableHasher;
20 use rustc_data_structures::sync::{self, Lock};
21 use rustc_incremental;
22 use rustc_metadata::creader::CrateLoader;
23 use rustc_metadata::cstore::{self, CStore};
25 use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion, layout_test};
26 use rustc_plugin as plugin;
27 use rustc_plugin::registry::Registry;
29 use rustc_resolve::{Resolver, ResolverArenas};
31 use rustc_typeck as typeck;
32 use syntax::{self, ast, attr, diagnostics, visit};
33 use syntax::early_buffered_lints::BufferedEarlyLint;
34 use syntax::ext::base::ExtCtxt;
35 use syntax::mut_visit::MutVisitor;
36 use syntax::parse::{self, PResult};
37 use syntax::util::node_count::NodeCounter;
38 use syntax::util::lev_distance::find_best_match_for_name;
39 use syntax::symbol::Symbol;
40 use syntax_pos::{FileName, hygiene};
47 use std::ffi::OsString;
49 use std::io::{self, Write};
51 use std::path::{Path, PathBuf};
54 use pretty::ReplaceBodyWithLoop;
57 use super::Compilation;
59 #[cfg(not(parallel_compiler))]
60 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
61 opts: config::Options,
64 ty::tls::GCX_PTR.set(&Lock::new(0), || {
69 #[cfg(parallel_compiler)]
70 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
71 opts: config::Options,
76 use rayon::{ThreadPoolBuilder, ThreadPool};
78 let gcx_ptr = &Lock::new(0);
80 let config = ThreadPoolBuilder::new()
81 .num_threads(Session::threads_from_opts(&opts))
82 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() })
83 .stack_size(::STACK_SIZE);
85 let with_pool = move |pool: &ThreadPool| {
86 pool.install(move || f(opts))
89 syntax::GLOBALS.with(|syntax_globals| {
90 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
91 // The main handler run for each Rayon worker thread and sets up
92 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
93 // captured and set on the new threads. ty::tls::with_thread_locals sets up
94 // thread local callbacks from libsyntax
95 let main_handler = move |worker: &mut dyn FnMut()| {
96 syntax::GLOBALS.set(syntax_globals, || {
97 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
98 ty::tls::with_thread_locals(|| {
99 ty::tls::GCX_PTR.set(gcx_ptr, || {
107 ThreadPool::scoped_pool(config, main_handler, with_pool).unwrap()
112 pub fn compile_input(
113 codegen_backend: Box<dyn CodegenBackend>,
116 input_path: &Option<PathBuf>,
118 outdir: &Option<PathBuf>,
119 output: &Option<PathBuf>,
120 addl_plugins: Option<Vec<String>>,
121 control: &CompileController,
123 macro_rules! controller_entry_point {
124 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
125 let state = &mut $make_state;
126 let phase_result: &CompileResult = &$phase_result;
127 if phase_result.is_ok() || control.$point.run_callback_on_error {
128 (control.$point.callback)(state);
131 if control.$point.stop == Compilation::Stop {
132 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
133 // if there are no errors?
134 return $tsess.compile_status();
139 if sess.profile_queries() {
140 profile::begin(sess);
143 // We need nested scopes here, because the intermediate results can keep
144 // large chunks of memory alive and we want to free them as soon as
145 // possible to keep the peak memory usage low
146 let (outputs, ongoing_codegen, dep_graph) = {
147 let krate = match phase_1_parse_input(control, sess, input) {
149 Err(mut parse_error) => {
151 return Err(CompileIncomplete::Errored(ErrorReported));
155 let (krate, registry) = {
156 let mut compile_state =
157 CompileState::state_after_parse(input, sess, outdir, output, krate, &cstore);
158 controller_entry_point!(after_parse, sess, compile_state, Ok(()));
160 (compile_state.krate.unwrap(), compile_state.registry)
163 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
165 ::rustc_codegen_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
166 install_panic_hook();
168 let ExpansionResult {
174 phase_2_configure_and_expand(
182 let mut state = CompileState::state_after_expand(
191 controller_entry_point!(after_expand, sess, state, Ok(()));
197 let output_paths = generated_output_paths(sess, &outputs, output.is_some(), &crate_name);
199 // Ensure the source file isn't accidentally overwritten during compilation.
200 if let Some(ref input_path) = *input_path {
201 if sess.opts.will_create_output_file() {
202 if output_contains_path(&output_paths, input_path) {
204 "the input file \"{}\" would be overwritten by the generated \
208 return Err(CompileIncomplete::Stopped);
210 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
212 "the generated executable for the input file \"{}\" conflicts with the \
213 existing directory \"{}\"",
214 input_path.display(),
217 return Err(CompileIncomplete::Stopped);
222 write_out_deps(sess, &outputs, &output_paths);
223 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
224 && sess.opts.output_types.len() == 1
229 if let &Some(ref dir) = outdir {
230 if fs::create_dir_all(dir).is_err() {
231 sess.err("failed to find or create the directory specified by --out-dir");
232 return Err(CompileIncomplete::Stopped);
236 // Construct the HIR map
237 let hir_map = time(sess, "indexing hir", || {
238 hir_map::map_crate(sess, cstore, &mut hir_forest, &defs)
242 hir_map.dep_graph.assert_ignored();
243 controller_entry_point!(
246 CompileState::state_after_hir_lowering(
263 let opt_crate = if control.keep_ast {
264 Some(&expanded_crate)
266 drop(expanded_crate);
270 let mut arenas = AllArenas::new();
272 phase_3_run_analysis_passes(
284 // Eventually, we will want to track plugins.
285 tcx.dep_graph.with_ignore(|| {
286 let mut state = CompileState::state_after_analysis(
296 (control.after_analysis.callback)(&mut state);
299 // Plugins like clippy and rust-semverver stop the analysis early,
300 // but want to still return an error if errors during the analysis
302 tcx.sess.compile_status()?;
304 if control.after_analysis.stop == Compilation::Stop {
305 return result.and_then(|_| Err(CompileIncomplete::Stopped));
311 if log_enabled!(::log::Level::Info) {
312 println!("Pre-codegen");
313 tcx.print_debug_stats();
316 let ongoing_codegen = phase_4_codegen(&*codegen_backend, tcx, rx);
318 if log_enabled!(::log::Level::Info) {
319 println!("Post-codegen");
320 tcx.print_debug_stats();
323 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
324 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
325 sess.err(&format!("could not emit MIR: {}", e));
326 sess.abort_if_errors();
330 if tcx.sess.opts.debugging_opts.query_stats {
331 tcx.queries.print_stats();
334 Ok((outputs.clone(), ongoing_codegen, tcx.dep_graph.clone()))
339 if sess.opts.debugging_opts.print_type_sizes {
340 sess.code_stats.borrow().print_type_sizes();
343 codegen_backend.join_codegen_and_link(ongoing_codegen, sess, &dep_graph, &outputs)?;
345 if sess.opts.debugging_opts.perf_stats {
346 sess.print_perf_stats();
349 if sess.opts.debugging_opts.self_profile {
350 sess.print_profiler_results();
353 if sess.opts.debugging_opts.profile_json {
354 sess.save_json_results();
357 controller_entry_point!(
360 CompileState::state_when_compilation_done(input, sess, outdir, output),
367 pub fn source_name(input: &Input) -> FileName {
369 Input::File(ref ifile) => ifile.clone().into(),
370 Input::Str { ref name, .. } => name.clone(),
374 /// CompileController is used to customize compilation, it allows compilation to
375 /// be stopped and/or to call arbitrary code at various points in compilation.
376 /// It also allows for various flags to be set to influence what information gets
377 /// collected during compilation.
379 /// This is a somewhat higher level controller than a Session - the Session
380 /// controls what happens in each phase, whereas the CompileController controls
381 /// whether a phase is run at all and whether other code (from outside the
382 /// compiler) is run between phases.
384 /// Note that if compilation is set to stop and a callback is provided for a
385 /// given entry point, the callback is called before compilation is stopped.
387 /// Expect more entry points to be added in the future.
388 pub struct CompileController<'a> {
389 pub after_parse: PhaseController<'a>,
390 pub after_expand: PhaseController<'a>,
391 pub after_hir_lowering: PhaseController<'a>,
392 pub after_analysis: PhaseController<'a>,
393 pub compilation_done: PhaseController<'a>,
395 // FIXME we probably want to group the below options together and offer a
396 // better API, rather than this ad-hoc approach.
397 // Whether the compiler should keep the ast beyond parsing.
399 // -Zcontinue-parse-after-error
400 pub continue_parse_after_error: bool,
402 /// Allows overriding default rustc query providers,
403 /// after `default_provide` has installed them.
404 pub provide: Box<dyn Fn(&mut ty::query::Providers) + 'a + sync::Send>,
405 /// Same as `provide`, but only for non-local crates,
406 /// applied after `default_provide_extern`.
407 pub provide_extern: Box<dyn Fn(&mut ty::query::Providers) + 'a + sync::Send>,
410 impl<'a> CompileController<'a> {
411 pub fn basic() -> CompileController<'a> {
412 sync::assert_send::<Self>();
414 after_parse: PhaseController::basic(),
415 after_expand: PhaseController::basic(),
416 after_hir_lowering: PhaseController::basic(),
417 after_analysis: PhaseController::basic(),
418 compilation_done: PhaseController::basic(),
420 continue_parse_after_error: false,
422 provide_extern: box |_| {},
427 /// This implementation makes it easier to create a custom driver when you only want to hook
428 /// into callbacks from `CompileController`.
433 /// # extern crate rustc_driver;
434 /// # use rustc_driver::driver::CompileController;
435 /// let mut controller = CompileController::basic();
436 /// controller.after_analysis.callback = Box::new(move |_state| {});
437 /// rustc_driver::run_compiler(&[], Box::new(controller), None, None);
439 impl<'a> ::CompilerCalls<'a> for CompileController<'a> {
442 matches: &::getopts::Matches,
443 sopts: &config::Options,
444 cfg: &ast::CrateConfig,
445 descriptions: &::errors::registry::Registry,
446 output: ::ErrorOutputType,
448 ::RustcDefaultCalls.early_callback(
458 matches: &::getopts::Matches,
459 sopts: &config::Options,
460 cfg: &ast::CrateConfig,
461 odir: &Option<PathBuf>,
462 ofile: &Option<PathBuf>,
463 descriptions: &::errors::registry::Registry,
464 ) -> Option<(Input, Option<PathBuf>)> {
465 ::RustcDefaultCalls.no_input(
476 codegen_backend: &dyn (::CodegenBackend),
477 matches: &::getopts::Matches,
481 odir: &Option<PathBuf>,
482 ofile: &Option<PathBuf>,
485 .late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
490 _: &::getopts::Matches
491 ) -> CompileController<'a> {
496 pub struct PhaseController<'a> {
497 pub stop: Compilation,
498 // If true then the compiler will try to run the callback even if the phase
499 // ends with an error. Note that this is not always possible.
500 pub run_callback_on_error: bool,
501 pub callback: Box<dyn Fn(&mut CompileState) + 'a + sync::Send>,
504 impl<'a> PhaseController<'a> {
505 pub fn basic() -> PhaseController<'a> {
507 stop: Compilation::Continue,
508 run_callback_on_error: false,
509 callback: box |_| {},
514 /// State that is passed to a callback. What state is available depends on when
515 /// during compilation the callback is made. See the various constructor methods
516 /// (`state_*`) in the impl to see which data is provided for any given entry point.
517 pub struct CompileState<'a, 'tcx: 'a> {
518 pub input: &'a Input,
519 pub session: &'tcx Session,
520 pub krate: Option<ast::Crate>,
521 pub registry: Option<Registry<'a>>,
522 pub cstore: Option<&'tcx CStore>,
523 pub crate_name: Option<&'a str>,
524 pub output_filenames: Option<&'a OutputFilenames>,
525 pub out_dir: Option<&'a Path>,
526 pub out_file: Option<&'a Path>,
527 pub expanded_crate: Option<&'a ast::Crate>,
528 pub hir_crate: Option<&'a hir::Crate>,
529 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
530 pub resolutions: Option<&'a Resolutions>,
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),
545 output_filenames: None,
546 expanded_crate: None,
554 fn state_after_parse(
556 session: &'tcx Session,
557 out_dir: &'a Option<PathBuf>,
558 out_file: &'a Option<PathBuf>,
560 cstore: &'tcx CStore,
563 // Initialize the registry before moving `krate`
564 registry: Some(Registry::new(&session, krate.span)),
566 cstore: Some(cstore),
567 out_file: out_file.as_ref().map(|s| &**s),
568 ..CompileState::empty(input, session, out_dir)
572 fn state_after_expand(
574 session: &'tcx Session,
575 out_dir: &'a Option<PathBuf>,
576 out_file: &'a Option<PathBuf>,
577 cstore: &'tcx CStore,
578 expanded_crate: &'a ast::Crate,
582 crate_name: Some(crate_name),
583 cstore: Some(cstore),
584 expanded_crate: Some(expanded_crate),
585 out_file: out_file.as_ref().map(|s| &**s),
586 ..CompileState::empty(input, session, out_dir)
590 fn state_after_hir_lowering(
592 session: &'tcx Session,
593 out_dir: &'a Option<PathBuf>,
594 out_file: &'a Option<PathBuf>,
595 cstore: &'tcx CStore,
596 hir_map: &'a hir_map::Map<'tcx>,
597 resolutions: &'a Resolutions,
598 krate: &'a ast::Crate,
599 hir_crate: &'a hir::Crate,
600 output_filenames: &'a OutputFilenames,
604 crate_name: Some(crate_name),
605 cstore: Some(cstore),
606 hir_map: Some(hir_map),
607 resolutions: Some(resolutions),
608 expanded_crate: Some(krate),
609 hir_crate: Some(hir_crate),
610 output_filenames: Some(output_filenames),
611 out_file: out_file.as_ref().map(|s| &**s),
612 ..CompileState::empty(input, session, out_dir)
616 fn state_after_analysis(
618 session: &'tcx Session,
619 out_dir: &'a Option<PathBuf>,
620 out_file: &'a Option<PathBuf>,
621 krate: Option<&'a ast::Crate>,
622 hir_crate: &'a hir::Crate,
623 tcx: TyCtxt<'a, 'tcx, 'tcx>,
628 expanded_crate: krate,
629 hir_crate: Some(hir_crate),
630 crate_name: Some(crate_name),
631 out_file: out_file.as_ref().map(|s| &**s),
632 ..CompileState::empty(input, session, out_dir)
636 fn state_when_compilation_done(
638 session: &'tcx Session,
639 out_dir: &'a Option<PathBuf>,
640 out_file: &'a Option<PathBuf>,
643 out_file: out_file.as_ref().map(|s| &**s),
644 ..CompileState::empty(input, session, out_dir)
649 pub fn phase_1_parse_input<'a>(
650 control: &CompileController,
653 ) -> PResult<'a, ast::Crate> {
655 .set_continue_after_error(control.continue_parse_after_error);
656 hygiene::set_default_edition(sess.edition());
658 if sess.profile_queries() {
659 profile::begin(sess);
662 sess.profiler(|p| p.start_activity(ProfileCategory::Parsing));
663 let krate = time(sess, "parsing", || match *input {
664 Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
668 } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
670 sess.profiler(|p| p.end_activity(ProfileCategory::Parsing));
672 sess.diagnostic().set_continue_after_error(true);
674 if sess.opts.debugging_opts.ast_json_noexpand {
675 println!("{}", json::as_json(&krate));
678 if sess.opts.debugging_opts.input_stats {
681 sess.source_map().count_lines()
683 println!("Pre-expansion node count: {}", count_nodes(&krate));
686 if let Some(ref s) = sess.opts.debugging_opts.show_span {
687 syntax::show_span::run(sess.diagnostic(), s, &krate);
690 if sess.opts.debugging_opts.hir_stats {
691 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
697 fn count_nodes(krate: &ast::Crate) -> usize {
698 let mut counter = NodeCounter::new();
699 visit::walk_crate(&mut counter, krate);
703 // For continuing compilation after a parsed crate has been
706 pub struct ExpansionResult {
707 pub expanded_crate: ast::Crate,
708 pub defs: hir_map::Definitions,
709 pub resolutions: Resolutions,
710 pub hir_forest: hir_map::Forest,
713 pub struct InnerExpansionResult<'a> {
714 pub expanded_crate: ast::Crate,
715 pub resolver: Resolver<'a>,
716 pub hir_forest: hir_map::Forest,
719 /// Runs the "early phases" of the compiler: initial `cfg` processing,
720 /// loading compiler plugins (including those from `addl_plugins`),
721 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
722 /// harness if one is to be provided, injection of a dependency on the
723 /// standard library and prelude, and name resolution.
725 /// Returns `None` if we're aborting after handling -W help.
726 pub fn phase_2_configure_and_expand<F>(
730 registry: Option<Registry>,
732 addl_plugins: Option<Vec<String>>,
734 ) -> Result<ExpansionResult, CompileIncomplete>
736 F: FnOnce(&ast::Crate) -> CompileResult,
738 // Currently, we ignore the name resolution data structures for the purposes of dependency
739 // tracking. Instead we will run name resolution and include its output in the hash of each
740 // item, much like we do for macro expansion. In other words, the hash reflects not just
741 // its contents but the results of name resolution on those contents. Hopefully we'll push
742 // this back at some point.
743 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
744 let resolver_arenas = Resolver::arenas();
745 let result = phase_2_configure_and_expand_inner(
757 Ok(InnerExpansionResult {
761 }) => Ok(ExpansionResult {
763 defs: resolver.definitions,
765 resolutions: Resolutions {
766 freevars: resolver.freevars,
767 export_map: resolver.export_map,
768 trait_map: resolver.trait_map,
769 glob_map: resolver.glob_map,
770 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
771 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
772 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
773 (ident.name, entry.introduced_by_item)
781 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
783 pub fn phase_2_configure_and_expand_inner<'a, F>(
786 mut krate: ast::Crate,
787 registry: Option<Registry>,
789 addl_plugins: Option<Vec<String>>,
790 resolver_arenas: &'a ResolverArenas<'a>,
791 crate_loader: &'a mut CrateLoader<'a>,
793 ) -> Result<InnerExpansionResult<'a>, CompileIncomplete>
795 F: FnOnce(&ast::Crate) -> CompileResult,
797 krate = time(sess, "attributes injection", || {
798 syntax::attr::inject(krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr)
801 let (mut krate, features) = syntax::config::features(
806 // these need to be set "early" so that expansion sees `quote` if enabled.
807 sess.init_features(features);
809 let crate_types = collect_crate_types(sess, &krate.attrs);
810 sess.crate_types.set(crate_types);
812 let disambiguator = compute_crate_disambiguator(sess);
813 sess.crate_disambiguator.set(disambiguator);
814 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
816 if sess.opts.incremental.is_some() {
817 time(sess, "garbage collect incremental cache directory", || {
818 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
820 "Error while trying to garbage collect incremental \
821 compilation cache directory: {}",
828 // If necessary, compute the dependency graph (in the background).
829 let future_dep_graph = if sess.opts.build_dep_graph() {
830 Some(rustc_incremental::load_dep_graph(sess))
835 time(sess, "recursion limit", || {
836 middle::recursion_limit::update_limits(sess, &krate);
839 krate = time(sess, "crate injection", || {
840 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
841 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name, sess.edition())
844 let mut addl_plugins = Some(addl_plugins);
845 let registrars = time(sess, "plugin loading", || {
846 plugin::load::load_plugins(
851 addl_plugins.take().unwrap(),
855 let mut registry = registry.unwrap_or_else(|| Registry::new(sess, krate.span));
857 time(sess, "plugin registration", || {
858 if sess.features_untracked().rustc_diagnostic_macros {
859 registry.register_macro(
861 diagnostics::plugin::expand_diagnostic_used,
863 registry.register_macro(
864 "__register_diagnostic",
865 diagnostics::plugin::expand_register_diagnostic,
867 registry.register_macro(
868 "__build_diagnostic_array",
869 diagnostics::plugin::expand_build_diagnostic_array,
873 for registrar in registrars {
874 registry.args_hidden = Some(registrar.args);
875 (registrar.fun)(&mut registry);
889 sess.track_errors(|| {
890 let mut ls = sess.lint_store.borrow_mut();
891 for pass in early_lint_passes {
892 ls.register_early_pass(Some(sess), true, false, pass);
894 for pass in late_lint_passes {
895 ls.register_late_pass(Some(sess), true, pass);
898 for (name, (to, deprecated_name)) in lint_groups {
899 ls.register_group(Some(sess), true, name, deprecated_name, to);
902 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
903 *sess.plugin_attributes.borrow_mut() = attributes.clone();
906 // Lint plugins are registered; now we can process command line flags.
907 if sess.opts.describe_lints {
908 super::describe_lints(&sess, &sess.lint_store.borrow(), true);
909 return Err(CompileIncomplete::Stopped);
912 time(sess, "pre ast expansion lint checks", || {
913 lint::check_ast_crate(
917 rustc_lint::BuiltinCombinedPreExpansionLintPass::new());
920 let mut resolver = Resolver::new(
928 syntax_ext::register_builtins(&mut resolver, syntax_exts);
931 sess.profiler(|p| p.start_activity(ProfileCategory::Expansion));
932 krate = time(sess, "expansion", || {
933 // Windows dlls do not have rpaths, so they don't know how to find their
934 // dependencies. It's up to us to tell the system where to find all the
935 // dependent dlls. Note that this uses cfg!(windows) as opposed to
936 // targ_cfg because syntax extensions are always loaded for the host
937 // compiler, not for the target.
939 // This is somewhat of an inherently racy operation, however, as
940 // multiple threads calling this function could possibly continue
941 // extending PATH far beyond what it should. To solve this for now we
942 // just don't add any new elements to PATH which are already there
943 // within PATH. This is basically a targeted fix at #17360 for rustdoc
944 // which runs rustc in parallel but has been seen (#33844) to cause
945 // problems with PATH becoming too long.
946 let mut old_path = OsString::new();
948 old_path = env::var_os("PATH").unwrap_or(old_path);
949 let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
950 for path in env::split_paths(&old_path) {
951 if !new_path.contains(&path) {
960 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
965 // Create the config for macro expansion
966 let features = sess.features_untracked();
967 let cfg = syntax::ext::expand::ExpansionConfig {
968 features: Some(&features),
969 recursion_limit: *sess.recursion_limit.get(),
970 trace_mac: sess.opts.debugging_opts.trace_macros,
971 should_test: sess.opts.test,
972 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
975 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
977 // Expand macros now!
978 let krate = time(sess, "expand crate", || {
979 ecx.monotonic_expander().expand_crate(krate)
982 // The rest is error reporting
984 time(sess, "check unused macros", || {
985 ecx.check_unused_macros();
988 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
989 .missing_fragment_specifiers
994 missing_fragment_specifiers.sort();
996 for span in missing_fragment_specifiers {
997 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
998 let msg = "missing fragment specifier";
999 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
1002 env::set_var("PATH", &old_path);
1006 sess.profiler(|p| p.end_activity(ProfileCategory::Expansion));
1008 time(sess, "maybe building test harness", || {
1009 syntax::test::modify_for_testing(
1015 &sess.features_untracked(),
1019 // If we're actually rustdoc then there's no need to actually compile
1020 // anything, so switch everything to just looping
1021 if sess.opts.actually_rustdoc {
1022 ReplaceBodyWithLoop::new(sess).visit_crate(&mut krate);
1025 let (has_proc_macro_decls, has_global_allocator) = time(sess, "AST validation", || {
1026 ast_validation::check_crate(sess, &krate)
1029 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
1030 // bunch of checks in the `modify` function below. For now just skip this
1031 // step entirely if we're rustdoc as it's not too useful anyway.
1032 if !sess.opts.actually_rustdoc {
1033 krate = time(sess, "maybe creating a macro crate", || {
1034 let crate_types = sess.crate_types.borrow();
1035 let num_crate_types = crate_types.len();
1036 let is_proc_macro_crate = crate_types.contains(&config::CrateType::ProcMacro);
1037 let is_test_crate = sess.opts.test;
1038 syntax_ext::proc_macro_decls::modify(
1042 is_proc_macro_crate,
1043 has_proc_macro_decls,
1051 if has_global_allocator {
1052 // Expand global allocators, which are treated as an in-tree proc macro
1053 time(sess, "creating allocators", || {
1054 allocator::expand::modify(
1058 crate_name.to_string(),
1064 // Done with macro expansion!
1066 after_expand(&krate)?;
1068 if sess.opts.debugging_opts.input_stats {
1069 println!("Post-expansion node count: {}", count_nodes(&krate));
1072 if sess.opts.debugging_opts.hir_stats {
1073 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
1076 if sess.opts.debugging_opts.ast_json {
1077 println!("{}", json::as_json(&krate));
1080 time(sess, "name resolution", || {
1081 resolver.resolve_crate(&krate);
1084 // Needs to go *after* expansion to be able to check the results of macro expansion.
1085 time(sess, "complete gated feature checking", || {
1086 syntax::feature_gate::check_crate(
1089 &sess.features_untracked(),
1091 sess.opts.unstable_features,
1095 // Add all buffered lints from the `ParseSess` to the `Session`.
1096 sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
1097 info!("{} parse sess buffered_lints", buffered_lints.len());
1098 for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) {
1099 let lint = lint::Lint::from_parser_lint_id(lint_id);
1100 sess.buffer_lint(lint, id, span, &msg);
1104 // Lower ast -> hir.
1105 // First, we need to collect the dep_graph.
1106 let dep_graph = match future_dep_graph {
1107 None => DepGraph::new_disabled(),
1109 let (prev_graph, prev_work_products) =
1110 time(sess, "blocked while dep-graph loading finishes", || {
1113 .unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
1114 message: format!("could not decode incremental cache: {:?}", e),
1118 DepGraph::new(prev_graph, prev_work_products)
1121 let hir_forest = time(sess, "lowering ast -> hir", || {
1122 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
1124 if sess.opts.debugging_opts.hir_stats {
1125 hir_stats::print_hir_stats(&hir_crate);
1128 hir_map::Forest::new(hir_crate, &dep_graph)
1131 time(sess, "early lint checks", || {
1132 lint::check_ast_crate(sess, &krate, false, rustc_lint::BuiltinCombinedEarlyLintPass::new())
1135 // Discard hygiene data, which isn't required after lowering to HIR.
1136 if !sess.opts.debugging_opts.keep_hygiene_data {
1137 syntax::ext::hygiene::clear_markings();
1140 Ok(InnerExpansionResult {
1141 expanded_crate: krate,
1147 pub fn default_provide(providers: &mut ty::query::Providers) {
1148 proc_macro_decls::provide(providers);
1149 plugin::build::provide(providers);
1150 hir::provide(providers);
1151 borrowck::provide(providers);
1152 mir::provide(providers);
1153 reachable::provide(providers);
1154 resolve_lifetime::provide(providers);
1155 rustc_privacy::provide(providers);
1156 typeck::provide(providers);
1157 ty::provide(providers);
1158 traits::provide(providers);
1159 stability::provide(providers);
1160 middle::intrinsicck::provide(providers);
1161 middle::liveness::provide(providers);
1162 reachable::provide(providers);
1163 rustc_passes::provide(providers);
1164 rustc_traits::provide(providers);
1165 middle::region::provide(providers);
1166 middle::entry::provide(providers);
1167 cstore::provide(providers);
1168 lint::provide(providers);
1171 pub fn default_provide_extern(providers: &mut ty::query::Providers) {
1172 cstore::provide_extern(providers);
1175 /// Runs the resolution, type-checking, region checking and other
1176 /// miscellaneous analysis passes on the crate. Return various
1177 /// structures carrying the results of the analysis.
1178 pub fn phase_3_run_analysis_passes<'tcx, F, R>(
1179 codegen_backend: &dyn CodegenBackend,
1180 control: &CompileController,
1181 sess: &'tcx Session,
1182 cstore: &'tcx CStore,
1183 hir_map: hir_map::Map<'tcx>,
1184 resolutions: Resolutions,
1185 arenas: &'tcx mut AllArenas<'tcx>,
1187 output_filenames: &OutputFilenames,
1189 ) -> Result<R, CompileIncomplete>
1192 TyCtxt<'a, 'tcx, 'tcx>,
1193 mpsc::Receiver<Box<dyn Any + Send>>,
1197 let query_result_on_disk_cache = time(sess, "load query result cache", || {
1198 rustc_incremental::load_query_result_cache(sess)
1201 let mut local_providers = ty::query::Providers::default();
1202 default_provide(&mut local_providers);
1203 codegen_backend.provide(&mut local_providers);
1204 (control.provide)(&mut local_providers);
1206 let mut extern_providers = local_providers;
1207 default_provide_extern(&mut extern_providers);
1208 codegen_backend.provide_extern(&mut extern_providers);
1209 (control.provide_extern)(&mut extern_providers);
1211 let (tx, rx) = mpsc::channel();
1213 TyCtxt::create_and_enter(
1221 query_result_on_disk_cache,
1226 // Do some initialization of the DepGraph that can only be done with the
1228 time(sess, "dep graph tcx init", || rustc_incremental::dep_graph_tcx_init(tcx));
1231 time(sess, "looking for entry point", || {
1232 middle::entry::find_entry_point(tcx)
1235 time(sess, "looking for plugin registrar", || {
1236 plugin::build::find_plugin_registrar(tcx)
1239 time(sess, "looking for derive registrar", || {
1240 proc_macro_decls::find(tcx)
1243 time(sess, "loop checking", || loops::check_crate(tcx));
1245 time(sess, "attribute checking", || {
1246 hir::check_attr::check_crate(tcx)
1249 time(sess, "stability checking", || {
1250 stability::check_unstable_api_usage(tcx)
1254 // passes are timed inside typeck
1255 match typeck::check_crate(tcx) {
1263 time(sess, "misc checking", || {
1265 time(sess, "rvalue promotion", || {
1266 rvalue_promotion::check_crate(tcx)
1269 time(sess, "intrinsic checking", || {
1270 middle::intrinsicck::check_crate(tcx)
1273 time(sess, "match checking", || mir::matchck_crate(tcx));
1275 // this must run before MIR dump, because
1276 // "not all control paths return a value" is reported here.
1278 // maybe move the check to a MIR pass?
1279 time(sess, "liveness checking", || {
1280 middle::liveness::check_crate(tcx)
1285 // Abort so we don't try to construct MIR with liveness errors.
1286 // We also won't want to continue with errors from rvalue promotion
1287 tcx.sess.abort_if_errors();
1289 time(sess, "borrow checking", || {
1290 if tcx.use_ast_borrowck() {
1291 borrowck::check_crate(tcx);
1296 "MIR borrow checking",
1297 || tcx.par_body_owners(|def_id| { tcx.ensure().mir_borrowck(def_id); }));
1299 time(sess, "dumping chalk-like clauses", || {
1300 rustc_traits::lowering::dump_program_clauses(tcx);
1303 time(sess, "MIR effect checking", || {
1304 for def_id in tcx.body_owners() {
1305 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1309 time(sess, "layout testing", || layout_test::test_layout(tcx));
1311 // Avoid overwhelming user with errors if borrow checking failed.
1312 // I'm not sure how helpful this is, to be honest, but it avoids
1314 // lot of annoying errors in the compile-fail tests (basically,
1315 // lint warnings and so on -- kindck used to do this abort, but
1316 // kindck is gone now). -nmatsakis
1317 if sess.err_count() > 0 {
1318 return Ok(f(tcx, rx, sess.compile_status()));
1321 time(sess, "misc checking", || {
1323 time(sess, "privacy checking", || {
1324 rustc_privacy::check_crate(tcx)
1327 time(sess, "death checking", || middle::dead::check_crate(tcx));
1329 time(sess, "unused lib feature checking", || {
1330 stability::check_unused_or_stable_features(tcx)
1333 time(sess, "lint checking", || lint::check_crate(tcx));
1337 return Ok(f(tcx, rx, tcx.sess.compile_status()));
1342 /// Runs the codegen backend, after which the AST and analysis can
1344 pub fn phase_4_codegen<'a, 'tcx>(
1345 codegen_backend: &dyn CodegenBackend,
1346 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1347 rx: mpsc::Receiver<Box<dyn Any + Send>>,
1349 time(tcx.sess, "resolving dependency formats", || {
1350 ::rustc::middle::dependency_format::calculate(tcx)
1353 tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
1354 let codegen = time(tcx.sess, "codegen", move || codegen_backend.codegen_crate(tcx, rx));
1355 tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
1356 if tcx.sess.profile_queries() {
1357 profile::dump(&tcx.sess, "profile_queries".to_string())
1363 fn escape_dep_filename(filename: &FileName) -> String {
1364 // Apparently clang and gcc *only* escape spaces:
1365 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1366 filename.to_string().replace(" ", "\\ ")
1369 // Returns all the paths that correspond to generated files.
1370 fn generated_output_paths(
1372 outputs: &OutputFilenames,
1376 let mut out_filenames = Vec::new();
1377 for output_type in sess.opts.output_types.keys() {
1378 let file = outputs.path(*output_type);
1379 match *output_type {
1380 // If the filename has been overridden using `-o`, it will not be modified
1381 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1382 OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
1383 let p = ::rustc_codegen_utils::link::filename_for_input(
1389 out_filenames.push(p);
1391 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1392 // Don't add the dep-info output when omitting it from dep-info targets
1395 out_filenames.push(file);
1402 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1403 // returns None for every file path.
1404 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
1406 F: Fn(&PathBuf) -> Option<T>,
1408 for output_path in output_paths {
1409 if let Some(result) = f(output_path) {
1410 return Some(result);
1416 pub fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
1417 let input_path = input_path.canonicalize().ok();
1418 if input_path.is_none() {
1421 let check = |output_path: &PathBuf| {
1422 if output_path.canonicalize().ok() == input_path {
1428 check_output(output_paths, check).is_some()
1431 pub fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
1432 let check = |output_path: &PathBuf| {
1433 if output_path.is_dir() {
1434 Some(output_path.clone())
1439 check_output(output_paths, check)
1442 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
1443 // Write out dependency rules to the dep-info file if requested
1444 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1447 let deps_filename = outputs.path(OutputType::DepInfo);
1449 let result = (|| -> io::Result<()> {
1450 // Build a list of files used to compile the output and
1451 // write Makefile-compatible dependency rules
1452 let files: Vec<String> = sess.source_map()
1455 .filter(|fmap| fmap.is_real_file())
1456 .filter(|fmap| !fmap.is_imported())
1457 .map(|fmap| escape_dep_filename(&fmap.name))
1459 let mut file = fs::File::create(&deps_filename)?;
1460 for path in out_filenames {
1461 writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
1464 // Emit a fake target for each input file to the compilation. This
1465 // prevents `make` from spitting out an error if a file is later
1466 // deleted. For more info see #28735
1468 writeln!(file, "{}:", path)?;
1473 if let Err(e) = result {
1474 sess.fatal(&format!(
1475 "error writing dependencies to `{}`: {}",
1476 deps_filename.display(),
1482 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1483 // Unconditionally collect crate types from attributes to make them used
1484 let attr_types: Vec<config::CrateType> = attrs
1487 if a.check_name("crate_type") {
1488 match a.value_str() {
1489 Some(ref n) if *n == "rlib" => Some(config::CrateType::Rlib),
1490 Some(ref n) if *n == "dylib" => Some(config::CrateType::Dylib),
1491 Some(ref n) if *n == "cdylib" => Some(config::CrateType::Cdylib),
1492 Some(ref n) if *n == "lib" => Some(config::default_lib_output()),
1493 Some(ref n) if *n == "staticlib" => Some(config::CrateType::Staticlib),
1494 Some(ref n) if *n == "proc-macro" => Some(config::CrateType::ProcMacro),
1495 Some(ref n) if *n == "bin" => Some(config::CrateType::Executable),
1497 let crate_types = vec![
1498 Symbol::intern("rlib"),
1499 Symbol::intern("dylib"),
1500 Symbol::intern("cdylib"),
1501 Symbol::intern("lib"),
1502 Symbol::intern("staticlib"),
1503 Symbol::intern("proc-macro"),
1504 Symbol::intern("bin")
1507 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().node {
1508 let span = spanned.span;
1509 let lev_candidate = find_best_match_for_name(
1514 if let Some(candidate) = lev_candidate {
1515 session.buffer_lint_with_diagnostic(
1516 lint::builtin::UNKNOWN_CRATE_TYPES,
1519 "invalid `crate_type` value",
1520 lint::builtin::BuiltinLintDiagnostics::
1523 "did you mean".to_string(),
1524 format!("\"{}\"", candidate)
1528 session.buffer_lint(
1529 lint::builtin::UNKNOWN_CRATE_TYPES,
1532 "invalid `crate_type` value"
1546 // If we're generating a test executable, then ignore all other output
1547 // styles at all other locations
1548 if session.opts.test {
1549 return vec![config::CrateType::Executable];
1552 // Only check command line flags if present. If no types are specified by
1553 // command line, then reuse the empty `base` Vec to hold the types that
1554 // will be found in crate attributes.
1555 let mut base = session.opts.crate_types.clone();
1556 if base.is_empty() {
1557 base.extend(attr_types);
1558 if base.is_empty() {
1559 base.push(::rustc_codegen_utils::link::default_output_for_target(
1568 base.retain(|crate_type| {
1569 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
1572 session.warn(&format!(
1573 "dropping unsupported crate type `{}` for target `{}`",
1574 *crate_type, session.opts.target_triple
1584 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1585 use std::hash::Hasher;
1587 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1588 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1589 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1590 // should still be safe enough to avoid collisions in practice.
1591 let mut hasher = StableHasher::<Fingerprint>::new();
1593 let mut metadata = session.opts.cg.metadata.clone();
1594 // We don't want the crate_disambiguator to dependent on the order
1595 // -C metadata arguments, so sort them:
1597 // Every distinct -C metadata value is only incorporated once:
1600 hasher.write(b"metadata");
1601 for s in &metadata {
1602 // Also incorporate the length of a metadata string, so that we generate
1603 // different values for `-Cmetadata=ab -Cmetadata=c` and
1604 // `-Cmetadata=a -Cmetadata=bc`
1605 hasher.write_usize(s.len());
1606 hasher.write(s.as_bytes());
1609 // Also incorporate crate type, so that we don't get symbol conflicts when
1610 // linking against a library of the same name, if this is an executable.
1611 let is_exe = session
1614 .contains(&config::CrateType::Executable);
1615 hasher.write(if is_exe { b"exe" } else { b"lib" });
1617 CrateDisambiguator::from(hasher.finish())
1620 pub fn build_output_filenames(
1622 odir: &Option<PathBuf>,
1623 ofile: &Option<PathBuf>,
1624 attrs: &[ast::Attribute],
1626 ) -> OutputFilenames {
1629 // "-" as input file will cause the parser to read from stdin so we
1630 // have to make up a name
1631 // We want to toss everything after the final '.'
1632 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
1634 // If a crate name is present, we use it as the link name
1635 let stem = sess.opts
1638 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1639 .unwrap_or_else(|| input.filestem().to_owned());
1642 out_directory: dirpath,
1644 single_output_file: None,
1645 extra: sess.opts.cg.extra_filename.clone(),
1646 outputs: sess.opts.output_types.clone(),
1650 Some(ref out_file) => {
1651 let unnamed_output_types = sess.opts
1654 .filter(|a| a.is_none())
1656 let ofile = if unnamed_output_types > 1 {
1658 "due to multiple output types requested, the explicitly specified \
1659 output file name will be adapted for each output type",
1663 Some(out_file.clone())
1666 sess.warn("ignoring --out-dir flag due to -o flag");
1668 if !sess.opts.cg.extra_filename.is_empty() {
1669 sess.warn("ignoring -C extra-filename flag due to -o flag");
1673 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
1674 out_filestem: out_file
1676 .unwrap_or_default()
1680 single_output_file: ofile,
1681 extra: sess.opts.cg.extra_filename.clone(),
1682 outputs: sess.opts.output_types.clone(),