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::early_buffered_lints::BufferedEarlyLint;
56 use syntax::ext::base::ExtCtxt;
57 use syntax::fold::Folder;
58 use syntax::parse::{self, PResult};
59 use syntax::util::node_count::NodeCounter;
60 use syntax_pos::FileName;
64 use pretty::ReplaceBodyWithLoop;
68 #[cfg(not(parallel_queries))]
69 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
70 opts: config::Options,
73 ty::tls::GCX_PTR.set(&Lock::new(0), || {
78 #[cfg(parallel_queries)]
79 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
80 opts: config::Options,
85 use rayon::{ThreadPoolBuilder, ThreadPool};
87 let gcx_ptr = &Lock::new(0);
89 let config = ThreadPoolBuilder::new()
90 .num_threads(Session::query_threads_from_opts(&opts))
91 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() })
92 .stack_size(16 * 1024 * 1024);
94 let with_pool = move |pool: &ThreadPool| {
95 pool.install(move || f(opts))
98 syntax::GLOBALS.with(|syntax_globals| {
99 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
100 // The main handler run for each Rayon worker thread and sets up
101 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
102 // captured and set on the new threads. ty::tls::with_thread_locals sets up
103 // thread local callbacks from libsyntax
104 let main_handler = move |worker: &mut dyn FnMut()| {
105 syntax::GLOBALS.set(syntax_globals, || {
106 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
107 ty::tls::with_thread_locals(|| {
108 ty::tls::GCX_PTR.set(gcx_ptr, || {
116 ThreadPool::scoped_pool(config, main_handler, with_pool).unwrap()
121 pub fn compile_input(
122 codegen_backend: Box<dyn CodegenBackend>,
125 input_path: &Option<PathBuf>,
127 outdir: &Option<PathBuf>,
128 output: &Option<PathBuf>,
129 addl_plugins: Option<Vec<String>>,
130 control: &CompileController,
132 macro_rules! controller_entry_point {
133 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
134 let state = &mut $make_state;
135 let phase_result: &CompileResult = &$phase_result;
136 if phase_result.is_ok() || control.$point.run_callback_on_error {
137 (control.$point.callback)(state);
140 if control.$point.stop == Compilation::Stop {
141 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
142 // if there are no errors?
143 return $tsess.compile_status();
148 if sess.profile_queries() {
149 profile::begin(sess);
152 // We need nested scopes here, because the intermediate results can keep
153 // large chunks of memory alive and we want to free them as soon as
154 // possible to keep the peak memory usage low
155 let (outputs, ongoing_codegen, dep_graph) = {
156 let krate = match phase_1_parse_input(control, sess, input) {
158 Err(mut parse_error) => {
160 return Err(CompileIncomplete::Errored(ErrorReported));
164 let (krate, registry) = {
165 let mut compile_state =
166 CompileState::state_after_parse(input, sess, outdir, output, krate, &cstore);
167 controller_entry_point!(after_parse, sess, compile_state, Ok(()));
169 (compile_state.krate.unwrap(), compile_state.registry)
172 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
174 ::rustc_codegen_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
175 install_panic_hook();
177 let ExpansionResult {
184 phase_2_configure_and_expand(
191 control.make_glob_map,
193 let mut state = CompileState::state_after_expand(
202 controller_entry_point!(after_expand, sess, state, Ok(()));
208 let output_paths = generated_output_paths(sess, &outputs, output.is_some(), &crate_name);
210 // Ensure the source file isn't accidentally overwritten during compilation.
211 if let Some(ref input_path) = *input_path {
212 if sess.opts.will_create_output_file() {
213 if output_contains_path(&output_paths, input_path) {
215 "the input file \"{}\" would be overwritten by the generated \
219 return Err(CompileIncomplete::Stopped);
221 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
223 "the generated executable for the input file \"{}\" conflicts with the \
224 existing directory \"{}\"",
225 input_path.display(),
228 return Err(CompileIncomplete::Stopped);
233 write_out_deps(sess, &outputs, &output_paths);
234 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
235 && sess.opts.output_types.len() == 1
240 if let &Some(ref dir) = outdir {
241 if fs::create_dir_all(dir).is_err() {
242 sess.err("failed to find or create the directory specified by --out-dir");
243 return Err(CompileIncomplete::Stopped);
247 let arenas = AllArenas::new();
249 // Construct the HIR map
250 let hir_map = time(sess, "indexing hir", || {
251 hir_map::map_crate(sess, cstore, &mut hir_forest, &defs)
255 hir_map.dep_graph.assert_ignored();
256 controller_entry_point!(
259 CompileState::state_after_hir_lowering(
278 let opt_crate = if control.keep_ast {
279 Some(&expanded_crate)
281 drop(expanded_crate);
285 phase_3_run_analysis_passes(
296 |tcx, analysis, rx, result| {
298 // Eventually, we will want to track plugins.
299 tcx.dep_graph.with_ignore(|| {
300 let mut state = CompileState::state_after_analysis(
311 (control.after_analysis.callback)(&mut state);
314 if control.after_analysis.stop == Compilation::Stop {
315 return result.and_then(|_| Err(CompileIncomplete::Stopped));
321 if log_enabled!(::log::Level::Info) {
322 println!("Pre-codegen");
323 tcx.print_debug_stats();
326 let ongoing_codegen = phase_4_codegen(&*codegen_backend, tcx, rx);
328 if log_enabled!(::log::Level::Info) {
329 println!("Post-codegen");
330 tcx.print_debug_stats();
333 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
334 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
335 sess.err(&format!("could not emit MIR: {}", e));
336 sess.abort_if_errors();
340 Ok((outputs.clone(), ongoing_codegen, tcx.dep_graph.clone()))
345 if sess.opts.debugging_opts.print_type_sizes {
346 sess.code_stats.borrow().print_type_sizes();
349 codegen_backend.join_codegen_and_link(ongoing_codegen, sess, &dep_graph, &outputs)?;
351 if sess.opts.debugging_opts.perf_stats {
352 sess.print_perf_stats();
355 controller_entry_point!(
358 CompileState::state_when_compilation_done(input, sess, outdir, output),
365 pub fn source_name(input: &Input) -> FileName {
367 Input::File(ref ifile) => ifile.clone().into(),
368 Input::Str { ref name, .. } => name.clone(),
372 /// CompileController is used to customize compilation, it allows compilation to
373 /// be stopped and/or to call arbitrary code at various points in compilation.
374 /// It also allows for various flags to be set to influence what information gets
375 /// collected during compilation.
377 /// This is a somewhat higher level controller than a Session - the Session
378 /// controls what happens in each phase, whereas the CompileController controls
379 /// whether a phase is run at all and whether other code (from outside the
380 /// compiler) is run between phases.
382 /// Note that if compilation is set to stop and a callback is provided for a
383 /// given entry point, the callback is called before compilation is stopped.
385 /// Expect more entry points to be added in the future.
386 pub struct CompileController<'a> {
387 pub after_parse: PhaseController<'a>,
388 pub after_expand: PhaseController<'a>,
389 pub after_hir_lowering: PhaseController<'a>,
390 pub after_analysis: PhaseController<'a>,
391 pub compilation_done: PhaseController<'a>,
393 // FIXME we probably want to group the below options together and offer a
394 // better API, rather than this ad-hoc approach.
395 pub make_glob_map: MakeGlobMap,
396 // Whether the compiler should keep the ast beyond parsing.
398 // -Zcontinue-parse-after-error
399 pub continue_parse_after_error: bool,
401 /// Allows overriding default rustc query providers,
402 /// after `default_provide` has installed them.
403 pub provide: Box<dyn Fn(&mut ty::query::Providers) + 'a>,
404 /// Same as `provide`, but only for non-local crates,
405 /// applied after `default_provide_extern`.
406 pub provide_extern: Box<dyn Fn(&mut ty::query::Providers) + 'a>,
409 impl<'a> CompileController<'a> {
410 pub fn basic() -> CompileController<'a> {
412 after_parse: PhaseController::basic(),
413 after_expand: PhaseController::basic(),
414 after_hir_lowering: PhaseController::basic(),
415 after_analysis: PhaseController::basic(),
416 compilation_done: PhaseController::basic(),
417 make_glob_map: MakeGlobMap::No,
419 continue_parse_after_error: false,
421 provide_extern: box |_| {},
426 /// This implementation makes it easier to create a custom driver when you only want to hook
427 /// into callbacks from `CompileController`.
432 /// # extern crate rustc_driver;
433 /// # use rustc_driver::driver::CompileController;
434 /// let mut controller = CompileController::basic();
435 /// controller.after_analysis.callback = Box::new(move |_state| {});
436 /// rustc_driver::run_compiler(&[], Box::new(controller), None, None);
438 impl<'a> ::CompilerCalls<'a> for CompileController<'a> {
441 matches: &::getopts::Matches,
442 sopts: &config::Options,
443 cfg: &ast::CrateConfig,
444 descriptions: &::errors::registry::Registry,
445 output: ::ErrorOutputType,
447 ::RustcDefaultCalls.early_callback(
457 matches: &::getopts::Matches,
458 sopts: &config::Options,
459 cfg: &ast::CrateConfig,
460 odir: &Option<PathBuf>,
461 ofile: &Option<PathBuf>,
462 descriptions: &::errors::registry::Registry,
463 ) -> Option<(Input, Option<PathBuf>)> {
464 ::RustcDefaultCalls.no_input(
475 codegen_backend: &dyn (::CodegenBackend),
476 matches: &::getopts::Matches,
478 cstore: &dyn (::CrateStore),
480 odir: &Option<PathBuf>,
481 ofile: &Option<PathBuf>,
484 .late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
489 _: &::getopts::Matches
490 ) -> CompileController<'a> {
495 pub struct PhaseController<'a> {
496 pub stop: Compilation,
497 // If true then the compiler will try to run the callback even if the phase
498 // ends with an error. Note that this is not always possible.
499 pub run_callback_on_error: bool,
500 pub callback: Box<dyn Fn(&mut CompileState) + 'a>,
503 impl<'a> PhaseController<'a> {
504 pub fn basic() -> PhaseController<'a> {
506 stop: Compilation::Continue,
507 run_callback_on_error: false,
508 callback: box |_| {},
513 /// State that is passed to a callback. What state is available depends on when
514 /// during compilation the callback is made. See the various constructor methods
515 /// (`state_*`) in the impl to see which data is provided for any given entry point.
516 pub struct CompileState<'a, 'tcx: 'a> {
517 pub input: &'a Input,
518 pub session: &'tcx Session,
519 pub krate: Option<ast::Crate>,
520 pub registry: Option<Registry<'a>>,
521 pub cstore: Option<&'tcx CStore>,
522 pub crate_name: Option<&'a str>,
523 pub output_filenames: Option<&'a OutputFilenames>,
524 pub out_dir: Option<&'a Path>,
525 pub out_file: Option<&'a Path>,
526 pub arenas: Option<&'tcx AllArenas<'tcx>>,
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 analysis: Option<&'a ty::CrateAnalysis>,
532 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
535 impl<'a, 'tcx> CompileState<'a, 'tcx> {
536 fn empty(input: &'a Input, session: &'tcx Session, out_dir: &'a Option<PathBuf>) -> Self {
540 out_dir: out_dir.as_ref().map(|s| &**s),
547 output_filenames: None,
548 expanded_crate: None,
557 fn state_after_parse(
559 session: &'tcx Session,
560 out_dir: &'a Option<PathBuf>,
561 out_file: &'a Option<PathBuf>,
563 cstore: &'tcx CStore,
566 // Initialize the registry before moving `krate`
567 registry: Some(Registry::new(&session, krate.span)),
569 cstore: Some(cstore),
570 out_file: out_file.as_ref().map(|s| &**s),
571 ..CompileState::empty(input, session, out_dir)
575 fn state_after_expand(
577 session: &'tcx Session,
578 out_dir: &'a Option<PathBuf>,
579 out_file: &'a Option<PathBuf>,
580 cstore: &'tcx CStore,
581 expanded_crate: &'a ast::Crate,
585 crate_name: Some(crate_name),
586 cstore: Some(cstore),
587 expanded_crate: Some(expanded_crate),
588 out_file: out_file.as_ref().map(|s| &**s),
589 ..CompileState::empty(input, session, out_dir)
593 fn state_after_hir_lowering(
595 session: &'tcx Session,
596 out_dir: &'a Option<PathBuf>,
597 out_file: &'a Option<PathBuf>,
598 arenas: &'tcx AllArenas<'tcx>,
599 cstore: &'tcx CStore,
600 hir_map: &'a hir_map::Map<'tcx>,
601 analysis: &'a ty::CrateAnalysis,
602 resolutions: &'a Resolutions,
603 krate: &'a ast::Crate,
604 hir_crate: &'a hir::Crate,
605 output_filenames: &'a OutputFilenames,
609 crate_name: Some(crate_name),
610 arenas: Some(arenas),
611 cstore: Some(cstore),
612 hir_map: Some(hir_map),
613 analysis: Some(analysis),
614 resolutions: Some(resolutions),
615 expanded_crate: Some(krate),
616 hir_crate: Some(hir_crate),
617 output_filenames: Some(output_filenames),
618 out_file: out_file.as_ref().map(|s| &**s),
619 ..CompileState::empty(input, session, out_dir)
623 fn state_after_analysis(
625 session: &'tcx Session,
626 out_dir: &'a Option<PathBuf>,
627 out_file: &'a Option<PathBuf>,
628 krate: Option<&'a ast::Crate>,
629 hir_crate: &'a hir::Crate,
630 analysis: &'a ty::CrateAnalysis,
631 tcx: TyCtxt<'a, 'tcx, 'tcx>,
635 analysis: Some(analysis),
637 expanded_crate: krate,
638 hir_crate: Some(hir_crate),
639 crate_name: Some(crate_name),
640 out_file: out_file.as_ref().map(|s| &**s),
641 ..CompileState::empty(input, session, out_dir)
645 fn state_when_compilation_done(
647 session: &'tcx Session,
648 out_dir: &'a Option<PathBuf>,
649 out_file: &'a Option<PathBuf>,
652 out_file: out_file.as_ref().map(|s| &**s),
653 ..CompileState::empty(input, session, out_dir)
658 pub fn phase_1_parse_input<'a>(
659 control: &CompileController,
662 ) -> PResult<'a, ast::Crate> {
664 .set_continue_after_error(control.continue_parse_after_error);
666 if sess.profile_queries() {
667 profile::begin(sess);
670 let krate = time(sess, "parsing", || match *input {
671 Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
675 } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
678 sess.diagnostic().set_continue_after_error(true);
680 if sess.opts.debugging_opts.ast_json_noexpand {
681 println!("{}", json::as_json(&krate));
684 if sess.opts.debugging_opts.input_stats {
687 sess.codemap().count_lines()
689 println!("Pre-expansion node count: {}", count_nodes(&krate));
692 if let Some(ref s) = sess.opts.debugging_opts.show_span {
693 syntax::show_span::run(sess.diagnostic(), s, &krate);
696 if sess.opts.debugging_opts.hir_stats {
697 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
703 fn count_nodes(krate: &ast::Crate) -> usize {
704 let mut counter = NodeCounter::new();
705 visit::walk_crate(&mut counter, krate);
709 // For continuing compilation after a parsed crate has been
712 pub struct ExpansionResult {
713 pub expanded_crate: ast::Crate,
714 pub defs: hir_map::Definitions,
715 pub analysis: ty::CrateAnalysis,
716 pub resolutions: Resolutions,
717 pub hir_forest: hir_map::Forest,
720 pub struct InnerExpansionResult<'a> {
721 pub expanded_crate: ast::Crate,
722 pub resolver: Resolver<'a>,
723 pub hir_forest: hir_map::Forest,
726 /// Run the "early phases" of the compiler: initial `cfg` processing,
727 /// loading compiler plugins (including those from `addl_plugins`),
728 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
729 /// harness if one is to be provided, injection of a dependency on the
730 /// standard library and prelude, and name resolution.
732 /// Returns `None` if we're aborting after handling -W help.
733 pub fn phase_2_configure_and_expand<F>(
737 registry: Option<Registry>,
739 addl_plugins: Option<Vec<String>>,
740 make_glob_map: MakeGlobMap,
742 ) -> Result<ExpansionResult, CompileIncomplete>
744 F: FnOnce(&ast::Crate) -> CompileResult,
746 // Currently, we ignore the name resolution data structures for the purposes of dependency
747 // tracking. Instead we will run name resolution and include its output in the hash of each
748 // item, much like we do for macro expansion. In other words, the hash reflects not just
749 // its contents but the results of name resolution on those contents. Hopefully we'll push
750 // this back at some point.
751 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
752 let resolver_arenas = Resolver::arenas();
753 let result = phase_2_configure_and_expand_inner(
766 Ok(InnerExpansionResult {
770 }) => Ok(ExpansionResult {
772 defs: resolver.definitions,
774 resolutions: Resolutions {
775 freevars: resolver.freevars,
776 export_map: resolver.export_map,
777 trait_map: resolver.trait_map,
778 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
779 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
782 analysis: ty::CrateAnalysis {
783 access_levels: Lrc::new(AccessLevels::default()),
784 name: crate_name.to_string(),
785 glob_map: if resolver.make_glob_map {
786 Some(resolver.glob_map)
796 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
798 pub fn phase_2_configure_and_expand_inner<'a, F>(
801 mut krate: ast::Crate,
802 registry: Option<Registry>,
804 addl_plugins: Option<Vec<String>>,
805 make_glob_map: MakeGlobMap,
806 resolver_arenas: &'a ResolverArenas<'a>,
807 crate_loader: &'a mut CrateLoader,
809 ) -> Result<InnerExpansionResult<'a>, CompileIncomplete>
811 F: FnOnce(&ast::Crate) -> CompileResult,
813 krate = time(sess, "attributes injection", || {
814 syntax::attr::inject(krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr)
817 let (mut krate, features) = syntax::config::features(
823 // these need to be set "early" so that expansion sees `quote` if enabled.
824 sess.init_features(features);
826 let crate_types = collect_crate_types(sess, &krate.attrs);
827 sess.crate_types.set(crate_types);
829 let disambiguator = compute_crate_disambiguator(sess);
830 sess.crate_disambiguator.set(disambiguator);
831 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
833 if sess.opts.incremental.is_some() {
834 time(sess, "garbage collect incremental cache directory", || {
835 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
837 "Error while trying to garbage collect incremental \
838 compilation cache directory: {}",
845 // If necessary, compute the dependency graph (in the background).
846 let future_dep_graph = if sess.opts.build_dep_graph() {
847 Some(rustc_incremental::load_dep_graph(sess))
852 time(sess, "recursion limit", || {
853 middle::recursion_limit::update_limits(sess, &krate);
856 krate = time(sess, "crate injection", || {
857 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
858 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
861 let mut addl_plugins = Some(addl_plugins);
862 let registrars = time(sess, "plugin loading", || {
863 plugin::load::load_plugins(
868 addl_plugins.take().unwrap(),
872 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
874 time(sess, "plugin registration", || {
875 if sess.features_untracked().rustc_diagnostic_macros {
876 registry.register_macro(
878 diagnostics::plugin::expand_diagnostic_used,
880 registry.register_macro(
881 "__register_diagnostic",
882 diagnostics::plugin::expand_register_diagnostic,
884 registry.register_macro(
885 "__build_diagnostic_array",
886 diagnostics::plugin::expand_build_diagnostic_array,
890 for registrar in registrars {
891 registry.args_hidden = Some(registrar.args);
892 (registrar.fun)(&mut registry);
896 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
907 sess.track_errors(|| {
908 let mut ls = sess.lint_store.borrow_mut();
909 for pass in early_lint_passes {
910 ls.register_early_pass(Some(sess), true, pass);
912 for pass in late_lint_passes {
913 ls.register_late_pass(Some(sess), true, pass);
916 for (name, to) in lint_groups {
917 ls.register_group(Some(sess), true, name, to);
920 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
921 *sess.plugin_attributes.borrow_mut() = attributes.clone();
924 // Lint plugins are registered; now we can process command line flags.
925 if sess.opts.describe_lints {
926 super::describe_lints(&sess, &sess.lint_store.borrow(), true);
927 return Err(CompileIncomplete::Stopped);
930 time(sess, "pre ast expansion lint checks", || {
931 lint::check_ast_crate(sess, &krate, true)
934 let mut resolver = Resolver::new(
943 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
944 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features_untracked().quote);
947 krate = time(sess, "expansion", || {
948 // Windows dlls do not have rpaths, so they don't know how to find their
949 // dependencies. It's up to us to tell the system where to find all the
950 // dependent dlls. Note that this uses cfg!(windows) as opposed to
951 // targ_cfg because syntax extensions are always loaded for the host
952 // compiler, not for the target.
954 // This is somewhat of an inherently racy operation, however, as
955 // multiple threads calling this function could possibly continue
956 // extending PATH far beyond what it should. To solve this for now we
957 // just don't add any new elements to PATH which are already there
958 // within PATH. This is basically a targeted fix at #17360 for rustdoc
959 // which runs rustc in parallel but has been seen (#33844) to cause
960 // problems with PATH becoming too long.
961 let mut old_path = OsString::new();
963 old_path = env::var_os("PATH").unwrap_or(old_path);
964 let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
965 for path in env::split_paths(&old_path) {
966 if !new_path.contains(&path) {
975 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
980 // Create the config for macro expansion
981 let features = sess.features_untracked();
982 let cfg = syntax::ext::expand::ExpansionConfig {
983 features: Some(&features),
984 recursion_limit: *sess.recursion_limit.get(),
985 trace_mac: sess.opts.debugging_opts.trace_macros,
986 should_test: sess.opts.test,
987 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
990 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
991 let err_count = ecx.parse_sess.span_diagnostic.err_count();
993 // Expand macros now!
994 let krate = time(sess, "expand crate", || {
995 ecx.monotonic_expander().expand_crate(krate)
998 // The rest is error reporting
1000 time(sess, "check unused macros", || {
1001 ecx.check_unused_macros();
1004 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
1005 .missing_fragment_specifiers
1010 missing_fragment_specifiers.sort();
1011 for span in missing_fragment_specifiers {
1012 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
1013 let msg = "missing fragment specifier";
1014 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
1016 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
1017 ecx.parse_sess.span_diagnostic.abort_if_errors();
1020 env::set_var("PATH", &old_path);
1025 krate = time(sess, "maybe building test harness", || {
1026 syntax::test::modify_for_testing(
1032 &sess.features_untracked(),
1036 // If we're actually rustdoc then there's no need to actually compile
1037 // anything, so switch everything to just looping
1038 if sess.opts.actually_rustdoc {
1039 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
1042 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
1043 // bunch of checks in the `modify` function below. For now just skip this
1044 // step entirely if we're rustdoc as it's not too useful anyway.
1045 if !sess.opts.actually_rustdoc {
1046 krate = time(sess, "maybe creating a macro crate", || {
1047 let crate_types = sess.crate_types.borrow();
1048 let num_crate_types = crate_types.len();
1049 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
1050 let is_test_crate = sess.opts.test;
1051 syntax_ext::proc_macro_registrar::modify(
1055 is_proc_macro_crate,
1063 // Expand global allocators, which are treated as an in-tree proc macro
1064 krate = time(sess, "creating allocators", || {
1065 allocator::expand::modify(
1069 crate_name.to_string(),
1074 // Add all buffered lints from the `ParseSess` to the `Session`.
1075 sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
1076 info!("{} parse sess buffered_lints", buffered_lints.len());
1077 for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) {
1078 let lint = lint::Lint::from_parser_lint_id(lint_id);
1079 sess.buffer_lint(lint, id, span, &msg);
1083 // Done with macro expansion!
1085 after_expand(&krate)?;
1087 if sess.opts.debugging_opts.input_stats {
1088 println!("Post-expansion node count: {}", count_nodes(&krate));
1091 if sess.opts.debugging_opts.hir_stats {
1092 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
1095 if sess.opts.debugging_opts.ast_json {
1096 println!("{}", json::as_json(&krate));
1099 time(sess, "AST validation", || {
1100 ast_validation::check_crate(sess, &krate)
1103 time(sess, "name resolution", || -> CompileResult {
1104 resolver.resolve_crate(&krate);
1108 // Needs to go *after* expansion to be able to check the results of macro expansion.
1109 time(sess, "complete gated feature checking", || {
1110 sess.track_errors(|| {
1111 syntax::feature_gate::check_crate(
1114 &sess.features_untracked(),
1116 sess.opts.unstable_features,
1121 // Unresolved macros might be due to mistyped `#[macro_use]`,
1122 // so abort after checking for unknown attributes. (#49074)
1123 if resolver.found_unresolved_macro {
1124 sess.parse_sess.span_diagnostic.abort_if_errors();
1127 // Lower ast -> hir.
1128 // First, we need to collect the dep_graph.
1129 let dep_graph = match future_dep_graph {
1130 None => DepGraph::new_disabled(),
1132 let (prev_graph, prev_work_products) =
1133 time(sess, "blocked while dep-graph loading finishes", || {
1136 .unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
1137 message: format!("could not decode incremental cache: {:?}", e),
1141 DepGraph::new(prev_graph, prev_work_products)
1144 let hir_forest = time(sess, "lowering ast -> hir", || {
1145 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
1147 if sess.opts.debugging_opts.hir_stats {
1148 hir_stats::print_hir_stats(&hir_crate);
1151 hir_map::Forest::new(hir_crate, &dep_graph)
1154 time(sess, "early lint checks", || {
1155 lint::check_ast_crate(sess, &krate, false)
1158 // Discard hygiene data, which isn't required after lowering to HIR.
1159 if !sess.opts.debugging_opts.keep_hygiene_data {
1160 syntax::ext::hygiene::clear_markings();
1163 Ok(InnerExpansionResult {
1164 expanded_crate: krate,
1170 pub fn default_provide(providers: &mut ty::query::Providers) {
1171 hir::provide(providers);
1172 borrowck::provide(providers);
1173 mir::provide(providers);
1174 reachable::provide(providers);
1175 resolve_lifetime::provide(providers);
1176 rustc_privacy::provide(providers);
1177 typeck::provide(providers);
1178 ty::provide(providers);
1179 traits::provide(providers);
1180 reachable::provide(providers);
1181 rustc_passes::provide(providers);
1182 rustc_traits::provide(providers);
1183 middle::region::provide(providers);
1184 cstore::provide(providers);
1185 lint::provide(providers);
1188 pub fn default_provide_extern(providers: &mut ty::query::Providers) {
1189 cstore::provide_extern(providers);
1192 /// Run the resolution, typechecking, region checking and other
1193 /// miscellaneous analysis passes on the crate. Return various
1194 /// structures carrying the results of the analysis.
1195 pub fn phase_3_run_analysis_passes<'tcx, F, R>(
1196 codegen_backend: &dyn CodegenBackend,
1197 control: &CompileController,
1198 sess: &'tcx Session,
1199 cstore: &'tcx CrateStoreDyn,
1200 hir_map: hir_map::Map<'tcx>,
1201 mut analysis: ty::CrateAnalysis,
1202 resolutions: Resolutions,
1203 arenas: &'tcx AllArenas<'tcx>,
1205 output_filenames: &OutputFilenames,
1207 ) -> Result<R, CompileIncomplete>
1210 TyCtxt<'a, 'tcx, 'tcx>,
1212 mpsc::Receiver<Box<dyn Any + Send>>,
1216 let query_result_on_disk_cache = time(sess, "load query result cache", || {
1217 rustc_incremental::load_query_result_cache(sess)
1220 time(sess, "looking for entry point", || {
1221 middle::entry::find_entry_point(sess, &hir_map, name)
1224 sess.plugin_registrar_fn
1225 .set(time(sess, "looking for plugin registrar", || {
1226 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
1228 sess.derive_registrar_fn
1229 .set(derive_registrar::find(&hir_map));
1231 time(sess, "loop checking", || loops::check_crate(sess, &hir_map));
1233 let mut local_providers = ty::query::Providers::default();
1234 default_provide(&mut local_providers);
1235 codegen_backend.provide(&mut local_providers);
1236 (control.provide)(&mut local_providers);
1238 let mut extern_providers = local_providers;
1239 default_provide_extern(&mut extern_providers);
1240 codegen_backend.provide_extern(&mut extern_providers);
1241 (control.provide_extern)(&mut extern_providers);
1243 let (tx, rx) = mpsc::channel();
1245 TyCtxt::create_and_enter(
1253 query_result_on_disk_cache,
1258 // Do some initialization of the DepGraph that can only be done with the
1260 rustc_incremental::dep_graph_tcx_init(tcx);
1262 time(sess, "attribute checking", || {
1263 hir::check_attr::check_crate(tcx)
1266 time(sess, "stability checking", || {
1267 stability::check_unstable_api_usage(tcx)
1270 // passes are timed inside typeck
1271 match typeck::check_crate(tcx) {
1274 f(tcx, analysis, rx, Err(x));
1279 time(sess, "rvalue promotion", || {
1280 rvalue_promotion::check_crate(tcx)
1283 analysis.access_levels =
1284 time(sess, "privacy checking", || rustc_privacy::check_crate(tcx));
1286 time(sess, "intrinsic checking", || {
1287 middle::intrinsicck::check_crate(tcx)
1290 time(sess, "match checking", || mir::matchck_crate(tcx));
1292 // this must run before MIR dump, because
1293 // "not all control paths return a value" is reported here.
1295 // maybe move the check to a MIR pass?
1296 time(sess, "liveness checking", || {
1297 middle::liveness::check_crate(tcx)
1300 time(sess, "borrow checking", || {
1301 if tcx.use_ast_borrowck() {
1302 borrowck::check_crate(tcx);
1307 "MIR borrow checking",
1308 || tcx.par_body_owners(|def_id| { tcx.mir_borrowck(def_id); }));
1310 time(sess, "dumping chalk-like clauses", || {
1311 rustc_traits::lowering::dump_program_clauses(tcx);
1314 time(sess, "MIR effect checking", || {
1315 for def_id in tcx.body_owners() {
1316 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1319 // Avoid overwhelming user with errors if type checking failed.
1320 // I'm not sure how helpful this is, to be honest, but it avoids
1322 // lot of annoying errors in the compile-fail tests (basically,
1323 // lint warnings and so on -- kindck used to do this abort, but
1324 // kindck is gone now). -nmatsakis
1325 if sess.err_count() > 0 {
1326 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1329 time(sess, "death checking", || middle::dead::check_crate(tcx));
1331 time(sess, "unused lib feature checking", || {
1332 stability::check_unused_or_stable_features(tcx)
1335 time(sess, "lint checking", || lint::check_crate(tcx));
1337 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1342 /// Run 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 let codegen = time(tcx.sess, "codegen", move || codegen_backend.codegen_crate(tcx, rx));
1354 if tcx.sess.profile_queries() {
1355 profile::dump(&tcx.sess, "profile_queries".to_string())
1361 fn escape_dep_filename(filename: &FileName) -> String {
1362 // Apparently clang and gcc *only* escape spaces:
1363 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1364 filename.to_string().replace(" ", "\\ ")
1367 // Returns all the paths that correspond to generated files.
1368 fn generated_output_paths(
1370 outputs: &OutputFilenames,
1374 let mut out_filenames = Vec::new();
1375 for output_type in sess.opts.output_types.keys() {
1376 let file = outputs.path(*output_type);
1377 match *output_type {
1378 // If the filename has been overridden using `-o`, it will not be modified
1379 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1380 OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
1381 let p = ::rustc_codegen_utils::link::filename_for_input(
1387 out_filenames.push(p);
1389 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1390 // Don't add the dep-info output when omitting it from dep-info targets
1393 out_filenames.push(file);
1400 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1401 // returns None for every file path.
1402 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
1404 F: Fn(&PathBuf) -> Option<T>,
1406 for output_path in output_paths {
1407 if let Some(result) = f(output_path) {
1408 return Some(result);
1414 pub fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
1415 let input_path = input_path.canonicalize().ok();
1416 if input_path.is_none() {
1419 let check = |output_path: &PathBuf| {
1420 if output_path.canonicalize().ok() == input_path {
1426 check_output(output_paths, check).is_some()
1429 pub fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
1430 let check = |output_path: &PathBuf| {
1431 if output_path.is_dir() {
1432 Some(output_path.clone())
1437 check_output(output_paths, check)
1440 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
1441 // Write out dependency rules to the dep-info file if requested
1442 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1445 let deps_filename = outputs.path(OutputType::DepInfo);
1447 let result = (|| -> io::Result<()> {
1448 // Build a list of files used to compile the output and
1449 // write Makefile-compatible dependency rules
1450 let files: Vec<String> = sess.codemap()
1453 .filter(|fmap| fmap.is_real_file())
1454 .filter(|fmap| !fmap.is_imported())
1455 .map(|fmap| escape_dep_filename(&fmap.name))
1457 let mut file = fs::File::create(&deps_filename)?;
1458 for path in out_filenames {
1459 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1462 // Emit a fake target for each input file to the compilation. This
1463 // prevents `make` from spitting out an error if a file is later
1464 // deleted. For more info see #28735
1466 writeln!(file, "{}:", path)?;
1474 sess.fatal(&format!(
1475 "error writing dependencies to `{}`: {}",
1476 deps_filename.display(),
1483 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1484 // Unconditionally collect crate types from attributes to make them used
1485 let attr_types: Vec<config::CrateType> = attrs
1488 if a.check_name("crate_type") {
1489 match a.value_str() {
1490 Some(ref n) if *n == "rlib" => Some(config::CrateTypeRlib),
1491 Some(ref n) if *n == "dylib" => Some(config::CrateTypeDylib),
1492 Some(ref n) if *n == "cdylib" => Some(config::CrateTypeCdylib),
1493 Some(ref n) if *n == "lib" => Some(config::default_lib_output()),
1494 Some(ref n) if *n == "staticlib" => Some(config::CrateTypeStaticlib),
1495 Some(ref n) if *n == "proc-macro" => Some(config::CrateTypeProcMacro),
1496 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1498 session.buffer_lint(
1499 lint::builtin::UNKNOWN_CRATE_TYPES,
1502 "invalid `crate_type` value",
1508 .struct_span_err(a.span, "`crate_type` requires a value")
1509 .note("for example: `#![crate_type=\"lib\"]`")
1520 // If we're generating a test executable, then ignore all other output
1521 // styles at all other locations
1522 if session.opts.test {
1523 return vec![config::CrateTypeExecutable];
1526 // Only check command line flags if present. If no types are specified by
1527 // command line, then reuse the empty `base` Vec to hold the types that
1528 // will be found in crate attributes.
1529 let mut base = session.opts.crate_types.clone();
1530 if base.is_empty() {
1531 base.extend(attr_types);
1532 if base.is_empty() {
1533 base.push(::rustc_codegen_utils::link::default_output_for_target(
1542 .filter(|crate_type| {
1543 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
1546 session.warn(&format!(
1547 "dropping unsupported crate type `{}` for target `{}`",
1548 *crate_type, session.opts.target_triple
1557 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1558 use std::hash::Hasher;
1560 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1561 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1562 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1563 // should still be safe enough to avoid collisions in practice.
1564 let mut hasher = StableHasher::<Fingerprint>::new();
1566 let mut metadata = session.opts.cg.metadata.clone();
1567 // We don't want the crate_disambiguator to dependent on the order
1568 // -C metadata arguments, so sort them:
1570 // Every distinct -C metadata value is only incorporated once:
1573 hasher.write(b"metadata");
1574 for s in &metadata {
1575 // Also incorporate the length of a metadata string, so that we generate
1576 // different values for `-Cmetadata=ab -Cmetadata=c` and
1577 // `-Cmetadata=a -Cmetadata=bc`
1578 hasher.write_usize(s.len());
1579 hasher.write(s.as_bytes());
1582 // Also incorporate crate type, so that we don't get symbol conflicts when
1583 // linking against a library of the same name, if this is an executable.
1584 let is_exe = session
1587 .contains(&config::CrateTypeExecutable);
1588 hasher.write(if is_exe { b"exe" } else { b"lib" });
1590 CrateDisambiguator::from(hasher.finish())
1593 pub fn build_output_filenames(
1595 odir: &Option<PathBuf>,
1596 ofile: &Option<PathBuf>,
1597 attrs: &[ast::Attribute],
1599 ) -> OutputFilenames {
1602 // "-" as input file will cause the parser to read from stdin so we
1603 // have to make up a name
1604 // We want to toss everything after the final '.'
1605 let dirpath = match *odir {
1606 Some(ref d) => d.clone(),
1607 None => PathBuf::new(),
1610 // If a crate name is present, we use it as the link name
1611 let stem = sess.opts
1614 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1615 .unwrap_or(input.filestem());
1618 out_directory: dirpath,
1620 single_output_file: None,
1621 extra: sess.opts.cg.extra_filename.clone(),
1622 outputs: sess.opts.output_types.clone(),
1626 Some(ref out_file) => {
1627 let unnamed_output_types = sess.opts
1630 .filter(|a| a.is_none())
1632 let ofile = if unnamed_output_types > 1 {
1634 "due to multiple output types requested, the explicitly specified \
1635 output file name will be adapted for each output type",
1639 Some(out_file.clone())
1642 sess.warn("ignoring --out-dir flag due to -o flag");
1644 if !sess.opts.cg.extra_filename.is_empty() {
1645 sess.warn("ignoring -C extra-filename flag due to -o flag");
1648 let cur_dir = Path::new("");
1651 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1652 out_filestem: out_file
1654 .unwrap_or(OsStr::new(""))
1658 single_output_file: ofile,
1659 extra: sess.opts.cg.extra_filename.clone(),
1660 outputs: sess.opts.output_types.clone(),