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 if control.after_analysis.stop == Compilation::Stop {
300 return result.and_then(|_| Err(CompileIncomplete::Stopped));
306 if log_enabled!(::log::Level::Info) {
307 println!("Pre-codegen");
308 tcx.print_debug_stats();
311 let ongoing_codegen = phase_4_codegen(&*codegen_backend, tcx, rx);
313 if log_enabled!(::log::Level::Info) {
314 println!("Post-codegen");
315 tcx.print_debug_stats();
318 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
319 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
320 sess.err(&format!("could not emit MIR: {}", e));
321 sess.abort_if_errors();
325 if tcx.sess.opts.debugging_opts.query_stats {
326 tcx.queries.print_stats();
329 Ok((outputs.clone(), ongoing_codegen, tcx.dep_graph.clone()))
334 if sess.opts.debugging_opts.print_type_sizes {
335 sess.code_stats.borrow().print_type_sizes();
338 codegen_backend.join_codegen_and_link(ongoing_codegen, sess, &dep_graph, &outputs)?;
340 if sess.opts.debugging_opts.perf_stats {
341 sess.print_perf_stats();
344 if sess.opts.debugging_opts.self_profile {
345 sess.print_profiler_results();
348 if sess.opts.debugging_opts.profile_json {
349 sess.save_json_results();
352 controller_entry_point!(
355 CompileState::state_when_compilation_done(input, sess, outdir, output),
362 pub fn source_name(input: &Input) -> FileName {
364 Input::File(ref ifile) => ifile.clone().into(),
365 Input::Str { ref name, .. } => name.clone(),
369 /// CompileController is used to customize compilation, it allows compilation to
370 /// be stopped and/or to call arbitrary code at various points in compilation.
371 /// It also allows for various flags to be set to influence what information gets
372 /// collected during compilation.
374 /// This is a somewhat higher level controller than a Session - the Session
375 /// controls what happens in each phase, whereas the CompileController controls
376 /// whether a phase is run at all and whether other code (from outside the
377 /// compiler) is run between phases.
379 /// Note that if compilation is set to stop and a callback is provided for a
380 /// given entry point, the callback is called before compilation is stopped.
382 /// Expect more entry points to be added in the future.
383 pub struct CompileController<'a> {
384 pub after_parse: PhaseController<'a>,
385 pub after_expand: PhaseController<'a>,
386 pub after_hir_lowering: PhaseController<'a>,
387 pub after_analysis: PhaseController<'a>,
388 pub compilation_done: PhaseController<'a>,
390 // FIXME we probably want to group the below options together and offer a
391 // better API, rather than this ad-hoc approach.
392 // Whether the compiler should keep the ast beyond parsing.
394 // -Zcontinue-parse-after-error
395 pub continue_parse_after_error: bool,
397 /// Allows overriding default rustc query providers,
398 /// after `default_provide` has installed them.
399 pub provide: Box<dyn Fn(&mut ty::query::Providers) + 'a + sync::Send>,
400 /// Same as `provide`, but only for non-local crates,
401 /// applied after `default_provide_extern`.
402 pub provide_extern: Box<dyn Fn(&mut ty::query::Providers) + 'a + sync::Send>,
405 impl<'a> CompileController<'a> {
406 pub fn basic() -> CompileController<'a> {
407 sync::assert_send::<Self>();
409 after_parse: PhaseController::basic(),
410 after_expand: PhaseController::basic(),
411 after_hir_lowering: PhaseController::basic(),
412 after_analysis: PhaseController::basic(),
413 compilation_done: PhaseController::basic(),
415 continue_parse_after_error: false,
417 provide_extern: box |_| {},
422 /// This implementation makes it easier to create a custom driver when you only want to hook
423 /// into callbacks from `CompileController`.
428 /// # extern crate rustc_driver;
429 /// # use rustc_driver::driver::CompileController;
430 /// let mut controller = CompileController::basic();
431 /// controller.after_analysis.callback = Box::new(move |_state| {});
432 /// rustc_driver::run_compiler(&[], Box::new(controller), None, None);
434 impl<'a> ::CompilerCalls<'a> for CompileController<'a> {
437 matches: &::getopts::Matches,
438 sopts: &config::Options,
439 cfg: &ast::CrateConfig,
440 descriptions: &::errors::registry::Registry,
441 output: ::ErrorOutputType,
443 ::RustcDefaultCalls.early_callback(
453 matches: &::getopts::Matches,
454 sopts: &config::Options,
455 cfg: &ast::CrateConfig,
456 odir: &Option<PathBuf>,
457 ofile: &Option<PathBuf>,
458 descriptions: &::errors::registry::Registry,
459 ) -> Option<(Input, Option<PathBuf>)> {
460 ::RustcDefaultCalls.no_input(
471 codegen_backend: &dyn (::CodegenBackend),
472 matches: &::getopts::Matches,
476 odir: &Option<PathBuf>,
477 ofile: &Option<PathBuf>,
480 .late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
485 _: &::getopts::Matches
486 ) -> CompileController<'a> {
491 pub struct PhaseController<'a> {
492 pub stop: Compilation,
493 // If true then the compiler will try to run the callback even if the phase
494 // ends with an error. Note that this is not always possible.
495 pub run_callback_on_error: bool,
496 pub callback: Box<dyn Fn(&mut CompileState) + 'a + sync::Send>,
499 impl<'a> PhaseController<'a> {
500 pub fn basic() -> PhaseController<'a> {
502 stop: Compilation::Continue,
503 run_callback_on_error: false,
504 callback: box |_| {},
509 /// State that is passed to a callback. What state is available depends on when
510 /// during compilation the callback is made. See the various constructor methods
511 /// (`state_*`) in the impl to see which data is provided for any given entry point.
512 pub struct CompileState<'a, 'tcx: 'a> {
513 pub input: &'a Input,
514 pub session: &'tcx Session,
515 pub krate: Option<ast::Crate>,
516 pub registry: Option<Registry<'a>>,
517 pub cstore: Option<&'tcx CStore>,
518 pub crate_name: Option<&'a str>,
519 pub output_filenames: Option<&'a OutputFilenames>,
520 pub out_dir: Option<&'a Path>,
521 pub out_file: Option<&'a Path>,
522 pub expanded_crate: Option<&'a ast::Crate>,
523 pub hir_crate: Option<&'a hir::Crate>,
524 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
525 pub resolutions: Option<&'a Resolutions>,
526 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
529 impl<'a, 'tcx> CompileState<'a, 'tcx> {
530 fn empty(input: &'a Input, session: &'tcx Session, out_dir: &'a Option<PathBuf>) -> Self {
534 out_dir: out_dir.as_ref().map(|s| &**s),
540 output_filenames: None,
541 expanded_crate: None,
549 fn state_after_parse(
551 session: &'tcx Session,
552 out_dir: &'a Option<PathBuf>,
553 out_file: &'a Option<PathBuf>,
555 cstore: &'tcx CStore,
558 // Initialize the registry before moving `krate`
559 registry: Some(Registry::new(&session, krate.span)),
561 cstore: Some(cstore),
562 out_file: out_file.as_ref().map(|s| &**s),
563 ..CompileState::empty(input, session, out_dir)
567 fn state_after_expand(
569 session: &'tcx Session,
570 out_dir: &'a Option<PathBuf>,
571 out_file: &'a Option<PathBuf>,
572 cstore: &'tcx CStore,
573 expanded_crate: &'a ast::Crate,
577 crate_name: Some(crate_name),
578 cstore: Some(cstore),
579 expanded_crate: Some(expanded_crate),
580 out_file: out_file.as_ref().map(|s| &**s),
581 ..CompileState::empty(input, session, out_dir)
585 fn state_after_hir_lowering(
587 session: &'tcx Session,
588 out_dir: &'a Option<PathBuf>,
589 out_file: &'a Option<PathBuf>,
590 cstore: &'tcx CStore,
591 hir_map: &'a hir_map::Map<'tcx>,
592 resolutions: &'a Resolutions,
593 krate: &'a ast::Crate,
594 hir_crate: &'a hir::Crate,
595 output_filenames: &'a OutputFilenames,
599 crate_name: Some(crate_name),
600 cstore: Some(cstore),
601 hir_map: Some(hir_map),
602 resolutions: Some(resolutions),
603 expanded_crate: Some(krate),
604 hir_crate: Some(hir_crate),
605 output_filenames: Some(output_filenames),
606 out_file: out_file.as_ref().map(|s| &**s),
607 ..CompileState::empty(input, session, out_dir)
611 fn state_after_analysis(
613 session: &'tcx Session,
614 out_dir: &'a Option<PathBuf>,
615 out_file: &'a Option<PathBuf>,
616 krate: Option<&'a ast::Crate>,
617 hir_crate: &'a hir::Crate,
618 tcx: TyCtxt<'a, 'tcx, 'tcx>,
623 expanded_crate: krate,
624 hir_crate: Some(hir_crate),
625 crate_name: Some(crate_name),
626 out_file: out_file.as_ref().map(|s| &**s),
627 ..CompileState::empty(input, session, out_dir)
631 fn state_when_compilation_done(
633 session: &'tcx Session,
634 out_dir: &'a Option<PathBuf>,
635 out_file: &'a Option<PathBuf>,
638 out_file: out_file.as_ref().map(|s| &**s),
639 ..CompileState::empty(input, session, out_dir)
644 pub fn phase_1_parse_input<'a>(
645 control: &CompileController,
648 ) -> PResult<'a, ast::Crate> {
650 .set_continue_after_error(control.continue_parse_after_error);
651 hygiene::set_default_edition(sess.edition());
653 if sess.profile_queries() {
654 profile::begin(sess);
657 sess.profiler(|p| p.start_activity(ProfileCategory::Parsing));
658 let krate = time(sess, "parsing", || match *input {
659 Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
663 } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
665 sess.profiler(|p| p.end_activity(ProfileCategory::Parsing));
667 sess.diagnostic().set_continue_after_error(true);
669 if sess.opts.debugging_opts.ast_json_noexpand {
670 println!("{}", json::as_json(&krate));
673 if sess.opts.debugging_opts.input_stats {
676 sess.source_map().count_lines()
678 println!("Pre-expansion node count: {}", count_nodes(&krate));
681 if let Some(ref s) = sess.opts.debugging_opts.show_span {
682 syntax::show_span::run(sess.diagnostic(), s, &krate);
685 if sess.opts.debugging_opts.hir_stats {
686 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
692 fn count_nodes(krate: &ast::Crate) -> usize {
693 let mut counter = NodeCounter::new();
694 visit::walk_crate(&mut counter, krate);
698 // For continuing compilation after a parsed crate has been
701 pub struct ExpansionResult {
702 pub expanded_crate: ast::Crate,
703 pub defs: hir_map::Definitions,
704 pub resolutions: Resolutions,
705 pub hir_forest: hir_map::Forest,
708 pub struct InnerExpansionResult<'a> {
709 pub expanded_crate: ast::Crate,
710 pub resolver: Resolver<'a>,
711 pub hir_forest: hir_map::Forest,
714 /// Runs the "early phases" of the compiler: initial `cfg` processing,
715 /// loading compiler plugins (including those from `addl_plugins`),
716 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
717 /// harness if one is to be provided, injection of a dependency on the
718 /// standard library and prelude, and name resolution.
720 /// Returns `None` if we're aborting after handling -W help.
721 pub fn phase_2_configure_and_expand<F>(
725 registry: Option<Registry>,
727 addl_plugins: Option<Vec<String>>,
729 ) -> Result<ExpansionResult, CompileIncomplete>
731 F: FnOnce(&ast::Crate) -> CompileResult,
733 // Currently, we ignore the name resolution data structures for the purposes of dependency
734 // tracking. Instead we will run name resolution and include its output in the hash of each
735 // item, much like we do for macro expansion. In other words, the hash reflects not just
736 // its contents but the results of name resolution on those contents. Hopefully we'll push
737 // this back at some point.
738 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
739 let resolver_arenas = Resolver::arenas();
740 let result = phase_2_configure_and_expand_inner(
752 Ok(InnerExpansionResult {
756 }) => Ok(ExpansionResult {
758 defs: resolver.definitions,
760 resolutions: Resolutions {
761 freevars: resolver.freevars,
762 export_map: resolver.export_map,
763 trait_map: resolver.trait_map,
764 glob_map: resolver.glob_map,
765 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
766 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
767 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
768 (ident.name, entry.introduced_by_item)
776 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
778 pub fn phase_2_configure_and_expand_inner<'a, F>(
781 mut krate: ast::Crate,
782 registry: Option<Registry>,
784 addl_plugins: Option<Vec<String>>,
785 resolver_arenas: &'a ResolverArenas<'a>,
786 crate_loader: &'a mut CrateLoader<'a>,
788 ) -> Result<InnerExpansionResult<'a>, CompileIncomplete>
790 F: FnOnce(&ast::Crate) -> CompileResult,
792 krate = time(sess, "attributes injection", || {
793 syntax::attr::inject(krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr)
796 let (mut krate, features) = syntax::config::features(
801 // these need to be set "early" so that expansion sees `quote` if enabled.
802 sess.init_features(features);
804 let crate_types = collect_crate_types(sess, &krate.attrs);
805 sess.crate_types.set(crate_types);
807 let disambiguator = compute_crate_disambiguator(sess);
808 sess.crate_disambiguator.set(disambiguator);
809 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
811 if sess.opts.incremental.is_some() {
812 time(sess, "garbage collect incremental cache directory", || {
813 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
815 "Error while trying to garbage collect incremental \
816 compilation cache directory: {}",
823 // If necessary, compute the dependency graph (in the background).
824 let future_dep_graph = if sess.opts.build_dep_graph() {
825 Some(rustc_incremental::load_dep_graph(sess))
830 time(sess, "recursion limit", || {
831 middle::recursion_limit::update_limits(sess, &krate);
834 krate = time(sess, "crate injection", || {
835 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
836 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name, sess.edition())
839 let mut addl_plugins = Some(addl_plugins);
840 let registrars = time(sess, "plugin loading", || {
841 plugin::load::load_plugins(
846 addl_plugins.take().unwrap(),
850 let mut registry = registry.unwrap_or_else(|| Registry::new(sess, krate.span));
852 time(sess, "plugin registration", || {
853 if sess.features_untracked().rustc_diagnostic_macros {
854 registry.register_macro(
856 diagnostics::plugin::expand_diagnostic_used,
858 registry.register_macro(
859 "__register_diagnostic",
860 diagnostics::plugin::expand_register_diagnostic,
862 registry.register_macro(
863 "__build_diagnostic_array",
864 diagnostics::plugin::expand_build_diagnostic_array,
868 for registrar in registrars {
869 registry.args_hidden = Some(registrar.args);
870 (registrar.fun)(&mut registry);
884 sess.track_errors(|| {
885 let mut ls = sess.lint_store.borrow_mut();
886 for pass in early_lint_passes {
887 ls.register_early_pass(Some(sess), true, false, pass);
889 for pass in late_lint_passes {
890 ls.register_late_pass(Some(sess), true, pass);
893 for (name, (to, deprecated_name)) in lint_groups {
894 ls.register_group(Some(sess), true, name, deprecated_name, to);
897 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
898 *sess.plugin_attributes.borrow_mut() = attributes.clone();
901 // Lint plugins are registered; now we can process command line flags.
902 if sess.opts.describe_lints {
903 super::describe_lints(&sess, &sess.lint_store.borrow(), true);
904 return Err(CompileIncomplete::Stopped);
907 time(sess, "pre ast expansion lint checks", || {
908 lint::check_ast_crate(
912 rustc_lint::BuiltinCombinedPreExpansionLintPass::new());
915 let mut resolver = Resolver::new(
923 syntax_ext::register_builtins(&mut resolver, syntax_exts);
926 sess.profiler(|p| p.start_activity(ProfileCategory::Expansion));
927 krate = time(sess, "expansion", || {
928 // Windows dlls do not have rpaths, so they don't know how to find their
929 // dependencies. It's up to us to tell the system where to find all the
930 // dependent dlls. Note that this uses cfg!(windows) as opposed to
931 // targ_cfg because syntax extensions are always loaded for the host
932 // compiler, not for the target.
934 // This is somewhat of an inherently racy operation, however, as
935 // multiple threads calling this function could possibly continue
936 // extending PATH far beyond what it should. To solve this for now we
937 // just don't add any new elements to PATH which are already there
938 // within PATH. This is basically a targeted fix at #17360 for rustdoc
939 // which runs rustc in parallel but has been seen (#33844) to cause
940 // problems with PATH becoming too long.
941 let mut old_path = OsString::new();
943 old_path = env::var_os("PATH").unwrap_or(old_path);
944 let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
945 for path in env::split_paths(&old_path) {
946 if !new_path.contains(&path) {
955 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
960 // Create the config for macro expansion
961 let features = sess.features_untracked();
962 let cfg = syntax::ext::expand::ExpansionConfig {
963 features: Some(&features),
964 recursion_limit: *sess.recursion_limit.get(),
965 trace_mac: sess.opts.debugging_opts.trace_macros,
966 should_test: sess.opts.test,
967 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
970 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
972 // Expand macros now!
973 let krate = time(sess, "expand crate", || {
974 ecx.monotonic_expander().expand_crate(krate)
977 // The rest is error reporting
979 time(sess, "check unused macros", || {
980 ecx.check_unused_macros();
983 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
984 .missing_fragment_specifiers
989 missing_fragment_specifiers.sort();
991 for span in missing_fragment_specifiers {
992 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
993 let msg = "missing fragment specifier";
994 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
997 env::set_var("PATH", &old_path);
1001 sess.profiler(|p| p.end_activity(ProfileCategory::Expansion));
1003 time(sess, "maybe building test harness", || {
1004 syntax::test::modify_for_testing(
1010 &sess.features_untracked(),
1014 // If we're actually rustdoc then there's no need to actually compile
1015 // anything, so switch everything to just looping
1016 if sess.opts.actually_rustdoc {
1017 ReplaceBodyWithLoop::new(sess).visit_crate(&mut krate);
1020 let (has_proc_macro_decls, has_global_allocator) = time(sess, "AST validation", || {
1021 ast_validation::check_crate(sess, &krate)
1024 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
1025 // bunch of checks in the `modify` function below. For now just skip this
1026 // step entirely if we're rustdoc as it's not too useful anyway.
1027 if !sess.opts.actually_rustdoc {
1028 krate = time(sess, "maybe creating a macro crate", || {
1029 let crate_types = sess.crate_types.borrow();
1030 let num_crate_types = crate_types.len();
1031 let is_proc_macro_crate = crate_types.contains(&config::CrateType::ProcMacro);
1032 let is_test_crate = sess.opts.test;
1033 syntax_ext::proc_macro_decls::modify(
1037 is_proc_macro_crate,
1038 has_proc_macro_decls,
1046 if has_global_allocator {
1047 // Expand global allocators, which are treated as an in-tree proc macro
1048 time(sess, "creating allocators", || {
1049 allocator::expand::modify(
1053 crate_name.to_string(),
1059 // Done with macro expansion!
1061 after_expand(&krate)?;
1063 if sess.opts.debugging_opts.input_stats {
1064 println!("Post-expansion node count: {}", count_nodes(&krate));
1067 if sess.opts.debugging_opts.hir_stats {
1068 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
1071 if sess.opts.debugging_opts.ast_json {
1072 println!("{}", json::as_json(&krate));
1075 time(sess, "name resolution", || {
1076 resolver.resolve_crate(&krate);
1079 // Needs to go *after* expansion to be able to check the results of macro expansion.
1080 time(sess, "complete gated feature checking", || {
1081 syntax::feature_gate::check_crate(
1084 &sess.features_untracked(),
1086 sess.opts.unstable_features,
1090 // Add all buffered lints from the `ParseSess` to the `Session`.
1091 sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
1092 info!("{} parse sess buffered_lints", buffered_lints.len());
1093 for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) {
1094 let lint = lint::Lint::from_parser_lint_id(lint_id);
1095 sess.buffer_lint(lint, id, span, &msg);
1099 // Lower ast -> hir.
1100 // First, we need to collect the dep_graph.
1101 let dep_graph = match future_dep_graph {
1102 None => DepGraph::new_disabled(),
1104 let (prev_graph, prev_work_products) =
1105 time(sess, "blocked while dep-graph loading finishes", || {
1108 .unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
1109 message: format!("could not decode incremental cache: {:?}", e),
1113 DepGraph::new(prev_graph, prev_work_products)
1116 let hir_forest = time(sess, "lowering ast -> hir", || {
1117 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
1119 if sess.opts.debugging_opts.hir_stats {
1120 hir_stats::print_hir_stats(&hir_crate);
1123 hir_map::Forest::new(hir_crate, &dep_graph)
1126 time(sess, "early lint checks", || {
1127 lint::check_ast_crate(sess, &krate, false, rustc_lint::BuiltinCombinedEarlyLintPass::new())
1130 // Discard hygiene data, which isn't required after lowering to HIR.
1131 if !sess.opts.debugging_opts.keep_hygiene_data {
1132 syntax::ext::hygiene::clear_markings();
1135 Ok(InnerExpansionResult {
1136 expanded_crate: krate,
1142 pub fn default_provide(providers: &mut ty::query::Providers) {
1143 proc_macro_decls::provide(providers);
1144 plugin::build::provide(providers);
1145 hir::provide(providers);
1146 borrowck::provide(providers);
1147 mir::provide(providers);
1148 reachable::provide(providers);
1149 resolve_lifetime::provide(providers);
1150 rustc_privacy::provide(providers);
1151 typeck::provide(providers);
1152 ty::provide(providers);
1153 traits::provide(providers);
1154 stability::provide(providers);
1155 middle::intrinsicck::provide(providers);
1156 middle::liveness::provide(providers);
1157 reachable::provide(providers);
1158 rustc_passes::provide(providers);
1159 rustc_traits::provide(providers);
1160 middle::region::provide(providers);
1161 middle::entry::provide(providers);
1162 cstore::provide(providers);
1163 lint::provide(providers);
1166 pub fn default_provide_extern(providers: &mut ty::query::Providers) {
1167 cstore::provide_extern(providers);
1170 /// Runs the resolution, typec-hecking, region checking and other
1171 /// miscellaneous analysis passes on the crate. Return various
1172 /// structures carrying the results of the analysis.
1173 pub fn phase_3_run_analysis_passes<'tcx, F, R>(
1174 codegen_backend: &dyn CodegenBackend,
1175 control: &CompileController,
1176 sess: &'tcx Session,
1177 cstore: &'tcx CStore,
1178 hir_map: hir_map::Map<'tcx>,
1179 resolutions: Resolutions,
1180 arenas: &'tcx mut AllArenas<'tcx>,
1182 output_filenames: &OutputFilenames,
1184 ) -> Result<R, CompileIncomplete>
1187 TyCtxt<'a, 'tcx, 'tcx>,
1188 mpsc::Receiver<Box<dyn Any + Send>>,
1192 let query_result_on_disk_cache = time(sess, "load query result cache", || {
1193 rustc_incremental::load_query_result_cache(sess)
1196 let mut local_providers = ty::query::Providers::default();
1197 default_provide(&mut local_providers);
1198 codegen_backend.provide(&mut local_providers);
1199 (control.provide)(&mut local_providers);
1201 let mut extern_providers = local_providers;
1202 default_provide_extern(&mut extern_providers);
1203 codegen_backend.provide_extern(&mut extern_providers);
1204 (control.provide_extern)(&mut extern_providers);
1206 let (tx, rx) = mpsc::channel();
1208 TyCtxt::create_and_enter(
1216 query_result_on_disk_cache,
1221 // Do some initialization of the DepGraph that can only be done with the
1223 time(sess, "dep graph tcx init", || rustc_incremental::dep_graph_tcx_init(tcx));
1226 time(sess, "looking for entry point", || {
1227 middle::entry::find_entry_point(tcx)
1230 time(sess, "looking for plugin registrar", || {
1231 plugin::build::find_plugin_registrar(tcx)
1234 time(sess, "looking for derive registrar", || {
1235 proc_macro_decls::find(tcx)
1238 time(sess, "loop checking", || loops::check_crate(tcx));
1240 time(sess, "attribute checking", || {
1241 hir::check_attr::check_crate(tcx)
1244 time(sess, "stability checking", || {
1245 stability::check_unstable_api_usage(tcx)
1249 // passes are timed inside typeck
1250 match typeck::check_crate(tcx) {
1258 time(sess, "misc checking", || {
1260 time(sess, "rvalue promotion", || {
1261 rvalue_promotion::check_crate(tcx)
1264 time(sess, "intrinsic checking", || {
1265 middle::intrinsicck::check_crate(tcx)
1268 time(sess, "match checking", || mir::matchck_crate(tcx));
1270 // this must run before MIR dump, because
1271 // "not all control paths return a value" is reported here.
1273 // maybe move the check to a MIR pass?
1274 time(sess, "liveness checking", || {
1275 middle::liveness::check_crate(tcx)
1280 // Abort so we don't try to construct MIR with liveness errors.
1281 // We also won't want to continue with errors from rvalue promotion
1282 tcx.sess.abort_if_errors();
1284 time(sess, "borrow checking", || {
1285 if tcx.use_ast_borrowck() {
1286 borrowck::check_crate(tcx);
1291 "MIR borrow checking",
1292 || tcx.par_body_owners(|def_id| { tcx.ensure().mir_borrowck(def_id); }));
1294 time(sess, "dumping chalk-like clauses", || {
1295 rustc_traits::lowering::dump_program_clauses(tcx);
1298 time(sess, "MIR effect checking", || {
1299 for def_id in tcx.body_owners() {
1300 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1304 time(sess, "layout testing", || layout_test::test_layout(tcx));
1306 // Avoid overwhelming user with errors if borrow checking failed.
1307 // I'm not sure how helpful this is, to be honest, but it avoids
1309 // lot of annoying errors in the compile-fail tests (basically,
1310 // lint warnings and so on -- kindck used to do this abort, but
1311 // kindck is gone now). -nmatsakis
1312 if sess.err_count() > 0 {
1313 return Ok(f(tcx, rx, sess.compile_status()));
1316 time(sess, "misc checking", || {
1318 time(sess, "privacy checking", || {
1319 rustc_privacy::check_crate(tcx)
1322 time(sess, "death checking", || middle::dead::check_crate(tcx));
1324 time(sess, "unused lib feature checking", || {
1325 stability::check_unused_or_stable_features(tcx)
1328 time(sess, "lint checking", || lint::check_crate(tcx));
1332 return Ok(f(tcx, rx, tcx.sess.compile_status()));
1337 /// Runs the codegen backend, after which the AST and analysis can
1339 pub fn phase_4_codegen<'a, 'tcx>(
1340 codegen_backend: &dyn CodegenBackend,
1341 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1342 rx: mpsc::Receiver<Box<dyn Any + Send>>,
1344 time(tcx.sess, "resolving dependency formats", || {
1345 ::rustc::middle::dependency_format::calculate(tcx)
1348 tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
1349 let codegen = time(tcx.sess, "codegen", move || codegen_backend.codegen_crate(tcx, rx));
1350 tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
1351 if tcx.sess.profile_queries() {
1352 profile::dump(&tcx.sess, "profile_queries".to_string())
1358 fn escape_dep_filename(filename: &FileName) -> String {
1359 // Apparently clang and gcc *only* escape spaces:
1360 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1361 filename.to_string().replace(" ", "\\ ")
1364 // Returns all the paths that correspond to generated files.
1365 fn generated_output_paths(
1367 outputs: &OutputFilenames,
1371 let mut out_filenames = Vec::new();
1372 for output_type in sess.opts.output_types.keys() {
1373 let file = outputs.path(*output_type);
1374 match *output_type {
1375 // If the filename has been overridden using `-o`, it will not be modified
1376 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1377 OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
1378 let p = ::rustc_codegen_utils::link::filename_for_input(
1384 out_filenames.push(p);
1386 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1387 // Don't add the dep-info output when omitting it from dep-info targets
1390 out_filenames.push(file);
1397 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1398 // returns None for every file path.
1399 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
1401 F: Fn(&PathBuf) -> Option<T>,
1403 for output_path in output_paths {
1404 if let Some(result) = f(output_path) {
1405 return Some(result);
1411 pub fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
1412 let input_path = input_path.canonicalize().ok();
1413 if input_path.is_none() {
1416 let check = |output_path: &PathBuf| {
1417 if output_path.canonicalize().ok() == input_path {
1423 check_output(output_paths, check).is_some()
1426 pub fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
1427 let check = |output_path: &PathBuf| {
1428 if output_path.is_dir() {
1429 Some(output_path.clone())
1434 check_output(output_paths, check)
1437 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
1438 // Write out dependency rules to the dep-info file if requested
1439 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1442 let deps_filename = outputs.path(OutputType::DepInfo);
1444 let result = (|| -> io::Result<()> {
1445 // Build a list of files used to compile the output and
1446 // write Makefile-compatible dependency rules
1447 let files: Vec<String> = sess.source_map()
1450 .filter(|fmap| fmap.is_real_file())
1451 .filter(|fmap| !fmap.is_imported())
1452 .map(|fmap| escape_dep_filename(&fmap.name))
1454 let mut file = fs::File::create(&deps_filename)?;
1455 for path in out_filenames {
1456 writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
1459 // Emit a fake target for each input file to the compilation. This
1460 // prevents `make` from spitting out an error if a file is later
1461 // deleted. For more info see #28735
1463 writeln!(file, "{}:", path)?;
1468 if let Err(e) = result {
1469 sess.fatal(&format!(
1470 "error writing dependencies to `{}`: {}",
1471 deps_filename.display(),
1477 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1478 // Unconditionally collect crate types from attributes to make them used
1479 let attr_types: Vec<config::CrateType> = attrs
1482 if a.check_name("crate_type") {
1483 match a.value_str() {
1484 Some(ref n) if *n == "rlib" => Some(config::CrateType::Rlib),
1485 Some(ref n) if *n == "dylib" => Some(config::CrateType::Dylib),
1486 Some(ref n) if *n == "cdylib" => Some(config::CrateType::Cdylib),
1487 Some(ref n) if *n == "lib" => Some(config::default_lib_output()),
1488 Some(ref n) if *n == "staticlib" => Some(config::CrateType::Staticlib),
1489 Some(ref n) if *n == "proc-macro" => Some(config::CrateType::ProcMacro),
1490 Some(ref n) if *n == "bin" => Some(config::CrateType::Executable),
1492 let crate_types = vec![
1493 Symbol::intern("rlib"),
1494 Symbol::intern("dylib"),
1495 Symbol::intern("cdylib"),
1496 Symbol::intern("lib"),
1497 Symbol::intern("staticlib"),
1498 Symbol::intern("proc-macro"),
1499 Symbol::intern("bin")
1502 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().node {
1503 let span = spanned.span;
1504 let lev_candidate = find_best_match_for_name(
1509 if let Some(candidate) = lev_candidate {
1510 session.buffer_lint_with_diagnostic(
1511 lint::builtin::UNKNOWN_CRATE_TYPES,
1514 "invalid `crate_type` value",
1515 lint::builtin::BuiltinLintDiagnostics::
1518 "did you mean".to_string(),
1519 format!("\"{}\"", candidate)
1523 session.buffer_lint(
1524 lint::builtin::UNKNOWN_CRATE_TYPES,
1527 "invalid `crate_type` value"
1541 // If we're generating a test executable, then ignore all other output
1542 // styles at all other locations
1543 if session.opts.test {
1544 return vec![config::CrateType::Executable];
1547 // Only check command line flags if present. If no types are specified by
1548 // command line, then reuse the empty `base` Vec to hold the types that
1549 // will be found in crate attributes.
1550 let mut base = session.opts.crate_types.clone();
1551 if base.is_empty() {
1552 base.extend(attr_types);
1553 if base.is_empty() {
1554 base.push(::rustc_codegen_utils::link::default_output_for_target(
1563 base.retain(|crate_type| {
1564 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
1567 session.warn(&format!(
1568 "dropping unsupported crate type `{}` for target `{}`",
1569 *crate_type, session.opts.target_triple
1579 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1580 use std::hash::Hasher;
1582 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1583 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1584 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1585 // should still be safe enough to avoid collisions in practice.
1586 let mut hasher = StableHasher::<Fingerprint>::new();
1588 let mut metadata = session.opts.cg.metadata.clone();
1589 // We don't want the crate_disambiguator to dependent on the order
1590 // -C metadata arguments, so sort them:
1592 // Every distinct -C metadata value is only incorporated once:
1595 hasher.write(b"metadata");
1596 for s in &metadata {
1597 // Also incorporate the length of a metadata string, so that we generate
1598 // different values for `-Cmetadata=ab -Cmetadata=c` and
1599 // `-Cmetadata=a -Cmetadata=bc`
1600 hasher.write_usize(s.len());
1601 hasher.write(s.as_bytes());
1604 // Also incorporate crate type, so that we don't get symbol conflicts when
1605 // linking against a library of the same name, if this is an executable.
1606 let is_exe = session
1609 .contains(&config::CrateType::Executable);
1610 hasher.write(if is_exe { b"exe" } else { b"lib" });
1612 CrateDisambiguator::from(hasher.finish())
1615 pub fn build_output_filenames(
1617 odir: &Option<PathBuf>,
1618 ofile: &Option<PathBuf>,
1619 attrs: &[ast::Attribute],
1621 ) -> OutputFilenames {
1624 // "-" as input file will cause the parser to read from stdin so we
1625 // have to make up a name
1626 // We want to toss everything after the final '.'
1627 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
1629 // If a crate name is present, we use it as the link name
1630 let stem = sess.opts
1633 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1634 .unwrap_or_else(|| input.filestem().to_owned());
1637 out_directory: dirpath,
1639 single_output_file: None,
1640 extra: sess.opts.cg.extra_filename.clone(),
1641 outputs: sess.opts.output_types.clone(),
1645 Some(ref out_file) => {
1646 let unnamed_output_types = sess.opts
1649 .filter(|a| a.is_none())
1651 let ofile = if unnamed_output_types > 1 {
1653 "due to multiple output types requested, the explicitly specified \
1654 output file name will be adapted for each output type",
1658 Some(out_file.clone())
1661 sess.warn("ignoring --out-dir flag due to -o flag");
1663 if !sess.opts.cg.extra_filename.is_empty() {
1664 sess.warn("ignoring -C extra-filename flag due to -o flag");
1668 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
1669 out_filestem: out_file
1671 .unwrap_or_default()
1675 single_output_file: ofile,
1676 extra: sess.opts.cg.extra_filename.clone(),
1677 outputs: sess.opts.output_types.clone(),