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::middle::privacy::AccessLevels;
8 use rustc::ty::{self, AllArenas, Resolutions, TyCtxt};
10 use rustc::util::common::{install_panic_hook, time, ErrorReported};
11 use rustc::util::profiling::ProfileCategory;
12 use rustc::session::{CompileResult, CrateDisambiguator, Session};
13 use rustc::session::CompileIncomplete;
14 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
15 use rustc::session::search_paths::PathKind;
16 use rustc_allocator as allocator;
17 use rustc_borrowck as borrowck;
18 use rustc_codegen_utils::codegen_backend::CodegenBackend;
19 use rustc_data_structures::fingerprint::Fingerprint;
20 use rustc_data_structures::stable_hasher::StableHasher;
21 use rustc_data_structures::sync::{self, Lrc, Lock};
22 use rustc_incremental;
23 use rustc_metadata::creader::CrateLoader;
24 use rustc_metadata::cstore::{self, CStore};
26 use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion};
27 use rustc_plugin as plugin;
28 use rustc_plugin::registry::Registry;
30 use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas};
32 use rustc_typeck as typeck;
33 use syntax::{self, ast, attr, diagnostics, visit};
34 use syntax::early_buffered_lints::BufferedEarlyLint;
35 use syntax::ext::base::ExtCtxt;
36 use syntax::fold::Folder;
37 use syntax::parse::{self, PResult};
38 use syntax::util::node_count::NodeCounter;
39 use syntax::util::lev_distance::find_best_match_for_name;
40 use syntax::symbol::Symbol;
41 use syntax_pos::{FileName, hygiene};
48 use std::ffi::OsString;
50 use std::io::{self, Write};
52 use std::path::{Path, PathBuf};
55 use pretty::ReplaceBodyWithLoop;
58 use super::Compilation;
60 #[cfg(not(parallel_queries))]
61 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
62 opts: config::Options,
65 ty::tls::GCX_PTR.set(&Lock::new(0), || {
70 #[cfg(parallel_queries)]
71 pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
72 opts: config::Options,
77 use rayon::{ThreadPoolBuilder, ThreadPool};
79 let gcx_ptr = &Lock::new(0);
81 let config = ThreadPoolBuilder::new()
82 .num_threads(Session::query_threads_from_opts(&opts))
83 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() })
84 .stack_size(::STACK_SIZE);
86 let with_pool = move |pool: &ThreadPool| {
87 pool.install(move || f(opts))
90 syntax::GLOBALS.with(|syntax_globals| {
91 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
92 // The main handler run for each Rayon worker thread and sets up
93 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
94 // captured and set on the new threads. ty::tls::with_thread_locals sets up
95 // thread local callbacks from libsyntax
96 let main_handler = move |worker: &mut dyn FnMut()| {
97 syntax::GLOBALS.set(syntax_globals, || {
98 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
99 ty::tls::with_thread_locals(|| {
100 ty::tls::GCX_PTR.set(gcx_ptr, || {
108 ThreadPool::scoped_pool(config, main_handler, with_pool).unwrap()
113 pub fn compile_input(
114 codegen_backend: Box<dyn CodegenBackend>,
117 input_path: &Option<PathBuf>,
119 outdir: &Option<PathBuf>,
120 output: &Option<PathBuf>,
121 addl_plugins: Option<Vec<String>>,
122 control: &CompileController,
124 macro_rules! controller_entry_point {
125 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
126 let state = &mut $make_state;
127 let phase_result: &CompileResult = &$phase_result;
128 if phase_result.is_ok() || control.$point.run_callback_on_error {
129 (control.$point.callback)(state);
132 if control.$point.stop == Compilation::Stop {
133 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
134 // if there are no errors?
135 return $tsess.compile_status();
140 if sess.profile_queries() {
141 profile::begin(sess);
144 // We need nested scopes here, because the intermediate results can keep
145 // large chunks of memory alive and we want to free them as soon as
146 // possible to keep the peak memory usage low
147 let (outputs, ongoing_codegen, dep_graph) = {
148 let krate = match phase_1_parse_input(control, sess, input) {
150 Err(mut parse_error) => {
152 return Err(CompileIncomplete::Errored(ErrorReported));
156 let (krate, registry) = {
157 let mut compile_state =
158 CompileState::state_after_parse(input, sess, outdir, output, krate, &cstore);
159 controller_entry_point!(after_parse, sess, compile_state, Ok(()));
161 (compile_state.krate.unwrap(), compile_state.registry)
164 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
166 ::rustc_codegen_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
167 install_panic_hook();
169 let ExpansionResult {
176 phase_2_configure_and_expand(
183 control.make_glob_map,
185 let mut state = CompileState::state_after_expand(
194 controller_entry_point!(after_expand, sess, state, Ok(()));
200 let output_paths = generated_output_paths(sess, &outputs, output.is_some(), &crate_name);
202 // Ensure the source file isn't accidentally overwritten during compilation.
203 if let Some(ref input_path) = *input_path {
204 if sess.opts.will_create_output_file() {
205 if output_contains_path(&output_paths, input_path) {
207 "the input file \"{}\" would be overwritten by the generated \
211 return Err(CompileIncomplete::Stopped);
213 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
215 "the generated executable for the input file \"{}\" conflicts with the \
216 existing directory \"{}\"",
217 input_path.display(),
220 return Err(CompileIncomplete::Stopped);
225 write_out_deps(sess, &outputs, &output_paths);
226 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
227 && sess.opts.output_types.len() == 1
232 if let &Some(ref dir) = outdir {
233 if fs::create_dir_all(dir).is_err() {
234 sess.err("failed to find or create the directory specified by --out-dir");
235 return Err(CompileIncomplete::Stopped);
239 // Construct the HIR map
240 let hir_map = time(sess, "indexing hir", || {
241 hir_map::map_crate(sess, cstore, &mut hir_forest, &defs)
245 hir_map.dep_graph.assert_ignored();
246 controller_entry_point!(
249 CompileState::state_after_hir_lowering(
267 let opt_crate = if control.keep_ast {
268 Some(&expanded_crate)
270 drop(expanded_crate);
274 let mut arenas = AllArenas::new();
276 phase_3_run_analysis_passes(
287 |tcx, analysis, rx, result| {
289 // Eventually, we will want to track plugins.
290 tcx.dep_graph.with_ignore(|| {
291 let mut state = CompileState::state_after_analysis(
302 (control.after_analysis.callback)(&mut state);
305 if control.after_analysis.stop == Compilation::Stop {
306 return result.and_then(|_| Err(CompileIncomplete::Stopped));
312 if log_enabled!(::log::Level::Info) {
313 println!("Pre-codegen");
314 tcx.print_debug_stats();
317 let ongoing_codegen = phase_4_codegen(&*codegen_backend, tcx, rx);
319 if log_enabled!(::log::Level::Info) {
320 println!("Post-codegen");
321 tcx.print_debug_stats();
324 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
325 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
326 sess.err(&format!("could not emit MIR: {}", e));
327 sess.abort_if_errors();
331 if tcx.sess.opts.debugging_opts.query_stats {
332 tcx.queries.print_stats();
335 Ok((outputs.clone(), ongoing_codegen, tcx.dep_graph.clone()))
340 if sess.opts.debugging_opts.print_type_sizes {
341 sess.code_stats.borrow().print_type_sizes();
344 codegen_backend.join_codegen_and_link(ongoing_codegen, sess, &dep_graph, &outputs)?;
346 if sess.opts.debugging_opts.perf_stats {
347 sess.print_perf_stats();
350 if sess.opts.debugging_opts.self_profile {
351 sess.print_profiler_results();
354 if sess.opts.debugging_opts.profile_json {
355 sess.save_json_results();
358 controller_entry_point!(
361 CompileState::state_when_compilation_done(input, sess, outdir, output),
368 pub fn source_name(input: &Input) -> FileName {
370 Input::File(ref ifile) => ifile.clone().into(),
371 Input::Str { ref name, .. } => name.clone(),
375 /// CompileController is used to customize compilation, it allows compilation to
376 /// be stopped and/or to call arbitrary code at various points in compilation.
377 /// It also allows for various flags to be set to influence what information gets
378 /// collected during compilation.
380 /// This is a somewhat higher level controller than a Session - the Session
381 /// controls what happens in each phase, whereas the CompileController controls
382 /// whether a phase is run at all and whether other code (from outside the
383 /// compiler) is run between phases.
385 /// Note that if compilation is set to stop and a callback is provided for a
386 /// given entry point, the callback is called before compilation is stopped.
388 /// Expect more entry points to be added in the future.
389 pub struct CompileController<'a> {
390 pub after_parse: PhaseController<'a>,
391 pub after_expand: PhaseController<'a>,
392 pub after_hir_lowering: PhaseController<'a>,
393 pub after_analysis: PhaseController<'a>,
394 pub compilation_done: PhaseController<'a>,
396 // FIXME we probably want to group the below options together and offer a
397 // better API, rather than this ad-hoc approach.
398 pub make_glob_map: MakeGlobMap,
399 // Whether the compiler should keep the ast beyond parsing.
401 // -Zcontinue-parse-after-error
402 pub continue_parse_after_error: bool,
404 /// Allows overriding default rustc query providers,
405 /// after `default_provide` has installed them.
406 pub provide: Box<dyn Fn(&mut ty::query::Providers) + 'a>,
407 /// Same as `provide`, but only for non-local crates,
408 /// applied after `default_provide_extern`.
409 pub provide_extern: Box<dyn Fn(&mut ty::query::Providers) + 'a>,
412 impl<'a> CompileController<'a> {
413 pub fn basic() -> CompileController<'a> {
415 after_parse: PhaseController::basic(),
416 after_expand: PhaseController::basic(),
417 after_hir_lowering: PhaseController::basic(),
418 after_analysis: PhaseController::basic(),
419 compilation_done: PhaseController::basic(),
420 make_glob_map: MakeGlobMap::No,
422 continue_parse_after_error: false,
424 provide_extern: box |_| {},
429 /// This implementation makes it easier to create a custom driver when you only want to hook
430 /// into callbacks from `CompileController`.
435 /// # extern crate rustc_driver;
436 /// # use rustc_driver::driver::CompileController;
437 /// let mut controller = CompileController::basic();
438 /// controller.after_analysis.callback = Box::new(move |_state| {});
439 /// rustc_driver::run_compiler(&[], Box::new(controller), None, None);
441 impl<'a> ::CompilerCalls<'a> for CompileController<'a> {
444 matches: &::getopts::Matches,
445 sopts: &config::Options,
446 cfg: &ast::CrateConfig,
447 descriptions: &::errors::registry::Registry,
448 output: ::ErrorOutputType,
450 ::RustcDefaultCalls.early_callback(
460 matches: &::getopts::Matches,
461 sopts: &config::Options,
462 cfg: &ast::CrateConfig,
463 odir: &Option<PathBuf>,
464 ofile: &Option<PathBuf>,
465 descriptions: &::errors::registry::Registry,
466 ) -> Option<(Input, Option<PathBuf>)> {
467 ::RustcDefaultCalls.no_input(
478 codegen_backend: &dyn (::CodegenBackend),
479 matches: &::getopts::Matches,
483 odir: &Option<PathBuf>,
484 ofile: &Option<PathBuf>,
487 .late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
492 _: &::getopts::Matches
493 ) -> CompileController<'a> {
498 pub struct PhaseController<'a> {
499 pub stop: Compilation,
500 // If true then the compiler will try to run the callback even if the phase
501 // ends with an error. Note that this is not always possible.
502 pub run_callback_on_error: bool,
503 pub callback: Box<dyn Fn(&mut CompileState) + 'a>,
506 impl<'a> PhaseController<'a> {
507 pub fn basic() -> PhaseController<'a> {
509 stop: Compilation::Continue,
510 run_callback_on_error: false,
511 callback: box |_| {},
516 /// State that is passed to a callback. What state is available depends on when
517 /// during compilation the callback is made. See the various constructor methods
518 /// (`state_*`) in the impl to see which data is provided for any given entry point.
519 pub struct CompileState<'a, 'tcx: 'a> {
520 pub input: &'a Input,
521 pub session: &'tcx Session,
522 pub krate: Option<ast::Crate>,
523 pub registry: Option<Registry<'a>>,
524 pub cstore: Option<&'tcx CStore>,
525 pub crate_name: Option<&'a str>,
526 pub output_filenames: Option<&'a OutputFilenames>,
527 pub out_dir: Option<&'a Path>,
528 pub out_file: Option<&'a Path>,
529 pub expanded_crate: Option<&'a ast::Crate>,
530 pub hir_crate: Option<&'a hir::Crate>,
531 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
532 pub resolutions: Option<&'a Resolutions>,
533 pub analysis: Option<&'a ty::CrateAnalysis>,
534 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
537 impl<'a, 'tcx> CompileState<'a, 'tcx> {
538 fn empty(input: &'a Input, session: &'tcx Session, out_dir: &'a Option<PathBuf>) -> Self {
542 out_dir: out_dir.as_ref().map(|s| &**s),
548 output_filenames: None,
549 expanded_crate: None,
558 fn state_after_parse(
560 session: &'tcx Session,
561 out_dir: &'a Option<PathBuf>,
562 out_file: &'a Option<PathBuf>,
564 cstore: &'tcx CStore,
567 // Initialize the registry before moving `krate`
568 registry: Some(Registry::new(&session, krate.span)),
570 cstore: Some(cstore),
571 out_file: out_file.as_ref().map(|s| &**s),
572 ..CompileState::empty(input, session, out_dir)
576 fn state_after_expand(
578 session: &'tcx Session,
579 out_dir: &'a Option<PathBuf>,
580 out_file: &'a Option<PathBuf>,
581 cstore: &'tcx CStore,
582 expanded_crate: &'a ast::Crate,
586 crate_name: Some(crate_name),
587 cstore: Some(cstore),
588 expanded_crate: Some(expanded_crate),
589 out_file: out_file.as_ref().map(|s| &**s),
590 ..CompileState::empty(input, session, out_dir)
594 fn state_after_hir_lowering(
596 session: &'tcx Session,
597 out_dir: &'a Option<PathBuf>,
598 out_file: &'a Option<PathBuf>,
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 cstore: Some(cstore),
611 hir_map: Some(hir_map),
612 analysis: Some(analysis),
613 resolutions: Some(resolutions),
614 expanded_crate: Some(krate),
615 hir_crate: Some(hir_crate),
616 output_filenames: Some(output_filenames),
617 out_file: out_file.as_ref().map(|s| &**s),
618 ..CompileState::empty(input, session, out_dir)
622 fn state_after_analysis(
624 session: &'tcx Session,
625 out_dir: &'a Option<PathBuf>,
626 out_file: &'a Option<PathBuf>,
627 krate: Option<&'a ast::Crate>,
628 hir_crate: &'a hir::Crate,
629 analysis: &'a ty::CrateAnalysis,
630 tcx: TyCtxt<'a, 'tcx, 'tcx>,
634 analysis: Some(analysis),
636 expanded_crate: krate,
637 hir_crate: Some(hir_crate),
638 crate_name: Some(crate_name),
639 out_file: out_file.as_ref().map(|s| &**s),
640 ..CompileState::empty(input, session, out_dir)
644 fn state_when_compilation_done(
646 session: &'tcx Session,
647 out_dir: &'a Option<PathBuf>,
648 out_file: &'a Option<PathBuf>,
651 out_file: out_file.as_ref().map(|s| &**s),
652 ..CompileState::empty(input, session, out_dir)
657 pub fn phase_1_parse_input<'a>(
658 control: &CompileController,
661 ) -> PResult<'a, ast::Crate> {
663 .set_continue_after_error(control.continue_parse_after_error);
664 hygiene::set_default_edition(sess.edition());
666 if sess.profile_queries() {
667 profile::begin(sess);
670 sess.profiler(|p| p.start_activity(ProfileCategory::Parsing));
671 let krate = time(sess, "parsing", || match *input {
672 Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
676 } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
678 sess.profiler(|p| p.end_activity(ProfileCategory::Parsing));
680 sess.diagnostic().set_continue_after_error(true);
682 if sess.opts.debugging_opts.ast_json_noexpand {
683 println!("{}", json::as_json(&krate));
686 if sess.opts.debugging_opts.input_stats {
689 sess.source_map().count_lines()
691 println!("Pre-expansion node count: {}", count_nodes(&krate));
694 if let Some(ref s) = sess.opts.debugging_opts.show_span {
695 syntax::show_span::run(sess.diagnostic(), s, &krate);
698 if sess.opts.debugging_opts.hir_stats {
699 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
705 fn count_nodes(krate: &ast::Crate) -> usize {
706 let mut counter = NodeCounter::new();
707 visit::walk_crate(&mut counter, krate);
711 // For continuing compilation after a parsed crate has been
714 pub struct ExpansionResult {
715 pub expanded_crate: ast::Crate,
716 pub defs: hir_map::Definitions,
717 pub analysis: ty::CrateAnalysis,
718 pub resolutions: Resolutions,
719 pub hir_forest: hir_map::Forest,
722 pub struct InnerExpansionResult<'a> {
723 pub expanded_crate: ast::Crate,
724 pub resolver: Resolver<'a>,
725 pub hir_forest: hir_map::Forest,
728 /// Run the "early phases" of the compiler: initial `cfg` processing,
729 /// loading compiler plugins (including those from `addl_plugins`),
730 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
731 /// harness if one is to be provided, injection of a dependency on the
732 /// standard library and prelude, and name resolution.
734 /// Returns `None` if we're aborting after handling -W help.
735 pub fn phase_2_configure_and_expand<F>(
739 registry: Option<Registry>,
741 addl_plugins: Option<Vec<String>>,
742 make_glob_map: MakeGlobMap,
744 ) -> Result<ExpansionResult, CompileIncomplete>
746 F: FnOnce(&ast::Crate) -> CompileResult,
748 // Currently, we ignore the name resolution data structures for the purposes of dependency
749 // tracking. Instead we will run name resolution and include its output in the hash of each
750 // item, much like we do for macro expansion. In other words, the hash reflects not just
751 // its contents but the results of name resolution on those contents. Hopefully we'll push
752 // this back at some point.
753 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
754 let resolver_arenas = Resolver::arenas();
755 let result = phase_2_configure_and_expand_inner(
768 Ok(InnerExpansionResult {
772 }) => Ok(ExpansionResult {
774 defs: resolver.definitions,
776 resolutions: Resolutions {
777 freevars: resolver.freevars,
778 export_map: resolver.export_map,
779 trait_map: resolver.trait_map,
780 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
781 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
782 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
783 (ident.name, entry.introduced_by_item)
787 analysis: ty::CrateAnalysis {
788 access_levels: Lrc::new(AccessLevels::default()),
789 name: crate_name.to_string(),
790 glob_map: if resolver.make_glob_map {
791 Some(resolver.glob_map)
801 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
803 pub fn phase_2_configure_and_expand_inner<'a, F>(
806 mut krate: ast::Crate,
807 registry: Option<Registry>,
809 addl_plugins: Option<Vec<String>>,
810 make_glob_map: MakeGlobMap,
811 resolver_arenas: &'a ResolverArenas<'a>,
812 crate_loader: &'a mut CrateLoader<'a>,
814 ) -> Result<InnerExpansionResult<'a>, CompileIncomplete>
816 F: FnOnce(&ast::Crate) -> CompileResult,
818 krate = time(sess, "attributes injection", || {
819 syntax::attr::inject(krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr)
822 let (mut krate, features) = syntax::config::features(
827 // these need to be set "early" so that expansion sees `quote` if enabled.
828 sess.init_features(features);
830 let crate_types = collect_crate_types(sess, &krate.attrs);
831 sess.crate_types.set(crate_types);
833 let disambiguator = compute_crate_disambiguator(sess);
834 sess.crate_disambiguator.set(disambiguator);
835 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
837 if sess.opts.incremental.is_some() {
838 time(sess, "garbage collect incremental cache directory", || {
839 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
841 "Error while trying to garbage collect incremental \
842 compilation cache directory: {}",
849 // If necessary, compute the dependency graph (in the background).
850 let future_dep_graph = if sess.opts.build_dep_graph() {
851 Some(rustc_incremental::load_dep_graph(sess))
856 time(sess, "recursion limit", || {
857 middle::recursion_limit::update_limits(sess, &krate);
860 krate = time(sess, "crate injection", || {
861 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
862 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name, sess.edition())
865 let mut addl_plugins = Some(addl_plugins);
866 let registrars = time(sess, "plugin loading", || {
867 plugin::load::load_plugins(
872 addl_plugins.take().unwrap(),
876 let mut registry = registry.unwrap_or_else(|| Registry::new(sess, krate.span));
878 time(sess, "plugin registration", || {
879 if sess.features_untracked().rustc_diagnostic_macros {
880 registry.register_macro(
882 diagnostics::plugin::expand_diagnostic_used,
884 registry.register_macro(
885 "__register_diagnostic",
886 diagnostics::plugin::expand_register_diagnostic,
888 registry.register_macro(
889 "__build_diagnostic_array",
890 diagnostics::plugin::expand_build_diagnostic_array,
894 for registrar in registrars {
895 registry.args_hidden = Some(registrar.args);
896 (registrar.fun)(&mut registry);
910 sess.track_errors(|| {
911 let mut ls = sess.lint_store.borrow_mut();
912 for pass in early_lint_passes {
913 ls.register_early_pass(Some(sess), true, pass);
915 for pass in late_lint_passes {
916 ls.register_late_pass(Some(sess), true, pass);
919 for (name, (to, deprecated_name)) in lint_groups {
920 ls.register_group(Some(sess), true, name, deprecated_name, to);
923 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
924 *sess.plugin_attributes.borrow_mut() = attributes.clone();
927 // Lint plugins are registered; now we can process command line flags.
928 if sess.opts.describe_lints {
929 super::describe_lints(&sess, &sess.lint_store.borrow(), true);
930 return Err(CompileIncomplete::Stopped);
933 time(sess, "pre ast expansion lint checks", || {
934 lint::check_ast_crate(sess, &krate, true)
937 let mut resolver = Resolver::new(
946 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features_untracked().quote);
949 sess.profiler(|p| p.start_activity(ProfileCategory::Expansion));
950 krate = time(sess, "expansion", || {
951 // Windows dlls do not have rpaths, so they don't know how to find their
952 // dependencies. It's up to us to tell the system where to find all the
953 // dependent dlls. Note that this uses cfg!(windows) as opposed to
954 // targ_cfg because syntax extensions are always loaded for the host
955 // compiler, not for the target.
957 // This is somewhat of an inherently racy operation, however, as
958 // multiple threads calling this function could possibly continue
959 // extending PATH far beyond what it should. To solve this for now we
960 // just don't add any new elements to PATH which are already there
961 // within PATH. This is basically a targeted fix at #17360 for rustdoc
962 // which runs rustc in parallel but has been seen (#33844) to cause
963 // problems with PATH becoming too long.
964 let mut old_path = OsString::new();
966 old_path = env::var_os("PATH").unwrap_or(old_path);
967 let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
968 for path in env::split_paths(&old_path) {
969 if !new_path.contains(&path) {
978 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
983 // Create the config for macro expansion
984 let features = sess.features_untracked();
985 let cfg = syntax::ext::expand::ExpansionConfig {
986 features: Some(&features),
987 recursion_limit: *sess.recursion_limit.get(),
988 trace_mac: sess.opts.debugging_opts.trace_macros,
989 should_test: sess.opts.test,
990 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
993 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
995 // Expand macros now!
996 let krate = time(sess, "expand crate", || {
997 ecx.monotonic_expander().expand_crate(krate)
1000 // The rest is error reporting
1002 time(sess, "check unused macros", || {
1003 ecx.check_unused_macros();
1006 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
1007 .missing_fragment_specifiers
1012 missing_fragment_specifiers.sort();
1014 for span in missing_fragment_specifiers {
1015 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
1016 let msg = "missing fragment specifier";
1017 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
1020 env::set_var("PATH", &old_path);
1024 sess.profiler(|p| p.end_activity(ProfileCategory::Expansion));
1026 krate = time(sess, "maybe building test harness", || {
1027 syntax::test::modify_for_testing(
1033 &sess.features_untracked(),
1037 // If we're actually rustdoc then there's no need to actually compile
1038 // anything, so switch everything to just looping
1039 if sess.opts.actually_rustdoc {
1040 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
1043 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
1044 // bunch of checks in the `modify` function below. For now just skip this
1045 // step entirely if we're rustdoc as it's not too useful anyway.
1046 if !sess.opts.actually_rustdoc {
1047 krate = time(sess, "maybe creating a macro crate", || {
1048 let crate_types = sess.crate_types.borrow();
1049 let num_crate_types = crate_types.len();
1050 let is_proc_macro_crate = crate_types.contains(&config::CrateType::ProcMacro);
1051 let is_test_crate = sess.opts.test;
1052 syntax_ext::proc_macro_decls::modify(
1056 is_proc_macro_crate,
1064 // Expand global allocators, which are treated as an in-tree proc macro
1065 krate = time(sess, "creating allocators", || {
1066 allocator::expand::modify(
1070 crate_name.to_string(),
1075 // Add all buffered lints from the `ParseSess` to the `Session`.
1076 sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
1077 info!("{} parse sess buffered_lints", buffered_lints.len());
1078 for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) {
1079 let lint = lint::Lint::from_parser_lint_id(lint_id);
1080 sess.buffer_lint(lint, id, span, &msg);
1084 // Done with macro expansion!
1086 after_expand(&krate)?;
1088 if sess.opts.debugging_opts.input_stats {
1089 println!("Post-expansion node count: {}", count_nodes(&krate));
1092 if sess.opts.debugging_opts.hir_stats {
1093 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
1096 if sess.opts.debugging_opts.ast_json {
1097 println!("{}", json::as_json(&krate));
1100 time(sess, "AST validation", || {
1101 ast_validation::check_crate(sess, &krate)
1104 time(sess, "name resolution", || -> CompileResult {
1105 resolver.resolve_crate(&krate);
1109 // Needs to go *after* expansion to be able to check the results of macro expansion.
1110 time(sess, "complete gated feature checking", || {
1111 sess.track_errors(|| {
1112 syntax::feature_gate::check_crate(
1115 &sess.features_untracked(),
1117 sess.opts.unstable_features,
1122 // Lower ast -> hir.
1123 // First, we need to collect the dep_graph.
1124 let dep_graph = match future_dep_graph {
1125 None => DepGraph::new_disabled(),
1127 let (prev_graph, prev_work_products) =
1128 time(sess, "blocked while dep-graph loading finishes", || {
1131 .unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
1132 message: format!("could not decode incremental cache: {:?}", e),
1136 DepGraph::new(prev_graph, prev_work_products)
1139 let hir_forest = time(sess, "lowering ast -> hir", || {
1140 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
1142 if sess.opts.debugging_opts.hir_stats {
1143 hir_stats::print_hir_stats(&hir_crate);
1146 hir_map::Forest::new(hir_crate, &dep_graph)
1149 time(sess, "early lint checks", || {
1150 lint::check_ast_crate(sess, &krate, false)
1153 // Discard hygiene data, which isn't required after lowering to HIR.
1154 if !sess.opts.debugging_opts.keep_hygiene_data {
1155 syntax::ext::hygiene::clear_markings();
1158 Ok(InnerExpansionResult {
1159 expanded_crate: krate,
1165 pub fn default_provide(providers: &mut ty::query::Providers) {
1166 hir::provide(providers);
1167 borrowck::provide(providers);
1168 mir::provide(providers);
1169 reachable::provide(providers);
1170 resolve_lifetime::provide(providers);
1171 rustc_privacy::provide(providers);
1172 typeck::provide(providers);
1173 ty::provide(providers);
1174 traits::provide(providers);
1175 reachable::provide(providers);
1176 rustc_passes::provide(providers);
1177 rustc_traits::provide(providers);
1178 middle::region::provide(providers);
1179 cstore::provide(providers);
1180 lint::provide(providers);
1183 pub fn default_provide_extern(providers: &mut ty::query::Providers) {
1184 cstore::provide_extern(providers);
1187 /// Run the resolution, typechecking, region checking and other
1188 /// miscellaneous analysis passes on the crate. Return various
1189 /// structures carrying the results of the analysis.
1190 pub fn phase_3_run_analysis_passes<'tcx, F, R>(
1191 codegen_backend: &dyn CodegenBackend,
1192 control: &CompileController,
1193 sess: &'tcx Session,
1194 cstore: &'tcx CStore,
1195 hir_map: hir_map::Map<'tcx>,
1196 mut analysis: ty::CrateAnalysis,
1197 resolutions: Resolutions,
1198 arenas: &'tcx mut AllArenas<'tcx>,
1200 output_filenames: &OutputFilenames,
1202 ) -> Result<R, CompileIncomplete>
1205 TyCtxt<'a, 'tcx, 'tcx>,
1207 mpsc::Receiver<Box<dyn Any + Send>>,
1211 let query_result_on_disk_cache = time(sess, "load query result cache", || {
1212 rustc_incremental::load_query_result_cache(sess)
1215 time(sess, "looking for entry point", || {
1216 middle::entry::find_entry_point(sess, &hir_map, name)
1219 sess.plugin_registrar_fn
1220 .set(time(sess, "looking for plugin registrar", || {
1221 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
1223 sess.proc_macro_decls_static
1224 .set(proc_macro_decls::find(&hir_map));
1226 time(sess, "loop checking", || loops::check_crate(sess, &hir_map));
1228 let mut local_providers = ty::query::Providers::default();
1229 default_provide(&mut local_providers);
1230 codegen_backend.provide(&mut local_providers);
1231 (control.provide)(&mut local_providers);
1233 let mut extern_providers = local_providers;
1234 default_provide_extern(&mut extern_providers);
1235 codegen_backend.provide_extern(&mut extern_providers);
1236 (control.provide_extern)(&mut extern_providers);
1238 let (tx, rx) = mpsc::channel();
1240 TyCtxt::create_and_enter(
1248 query_result_on_disk_cache,
1253 // Do some initialization of the DepGraph that can only be done with the
1255 rustc_incremental::dep_graph_tcx_init(tcx);
1257 time(sess, "attribute checking", || {
1258 hir::check_attr::check_crate(tcx)
1261 time(sess, "stability checking", || {
1262 stability::check_unstable_api_usage(tcx)
1265 // passes are timed inside typeck
1266 match typeck::check_crate(tcx) {
1269 f(tcx, analysis, rx, Err(x));
1274 time(sess, "rvalue promotion", || {
1275 rvalue_promotion::check_crate(tcx)
1278 analysis.access_levels =
1279 time(sess, "privacy checking", || rustc_privacy::check_crate(tcx));
1281 time(sess, "intrinsic checking", || {
1282 middle::intrinsicck::check_crate(tcx)
1285 time(sess, "match checking", || mir::matchck_crate(tcx));
1287 // this must run before MIR dump, because
1288 // "not all control paths return a value" is reported here.
1290 // maybe move the check to a MIR pass?
1291 time(sess, "liveness checking", || {
1292 middle::liveness::check_crate(tcx)
1295 time(sess, "borrow checking", || {
1296 if tcx.use_ast_borrowck() {
1297 borrowck::check_crate(tcx);
1302 "MIR borrow checking",
1303 || tcx.par_body_owners(|def_id| { tcx.mir_borrowck(def_id); }));
1305 time(sess, "dumping chalk-like clauses", || {
1306 rustc_traits::lowering::dump_program_clauses(tcx);
1309 time(sess, "MIR effect checking", || {
1310 for def_id in tcx.body_owners() {
1311 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1314 // Avoid overwhelming user with errors if type checking failed.
1315 // I'm not sure how helpful this is, to be honest, but it avoids
1317 // lot of annoying errors in the compile-fail tests (basically,
1318 // lint warnings and so on -- kindck used to do this abort, but
1319 // kindck is gone now). -nmatsakis
1320 if sess.err_count() > 0 {
1321 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1324 time(sess, "death checking", || middle::dead::check_crate(tcx));
1326 time(sess, "unused lib feature checking", || {
1327 stability::check_unused_or_stable_features(tcx)
1330 time(sess, "lint checking", || lint::check_crate(tcx));
1332 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1337 /// Run 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"
1535 .struct_span_err(a.span, "`crate_type` requires a value")
1536 .note("for example: `#![crate_type=\"lib\"]`")
1547 // If we're generating a test executable, then ignore all other output
1548 // styles at all other locations
1549 if session.opts.test {
1550 return vec![config::CrateType::Executable];
1553 // Only check command line flags if present. If no types are specified by
1554 // command line, then reuse the empty `base` Vec to hold the types that
1555 // will be found in crate attributes.
1556 let mut base = session.opts.crate_types.clone();
1557 if base.is_empty() {
1558 base.extend(attr_types);
1559 if base.is_empty() {
1560 base.push(::rustc_codegen_utils::link::default_output_for_target(
1569 base.retain(|crate_type| {
1570 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
1573 session.warn(&format!(
1574 "dropping unsupported crate type `{}` for target `{}`",
1575 *crate_type, session.opts.target_triple
1585 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1586 use std::hash::Hasher;
1588 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1589 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1590 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1591 // should still be safe enough to avoid collisions in practice.
1592 let mut hasher = StableHasher::<Fingerprint>::new();
1594 let mut metadata = session.opts.cg.metadata.clone();
1595 // We don't want the crate_disambiguator to dependent on the order
1596 // -C metadata arguments, so sort them:
1598 // Every distinct -C metadata value is only incorporated once:
1601 hasher.write(b"metadata");
1602 for s in &metadata {
1603 // Also incorporate the length of a metadata string, so that we generate
1604 // different values for `-Cmetadata=ab -Cmetadata=c` and
1605 // `-Cmetadata=a -Cmetadata=bc`
1606 hasher.write_usize(s.len());
1607 hasher.write(s.as_bytes());
1610 // Also incorporate crate type, so that we don't get symbol conflicts when
1611 // linking against a library of the same name, if this is an executable.
1612 let is_exe = session
1615 .contains(&config::CrateType::Executable);
1616 hasher.write(if is_exe { b"exe" } else { b"lib" });
1618 CrateDisambiguator::from(hasher.finish())
1621 pub fn build_output_filenames(
1623 odir: &Option<PathBuf>,
1624 ofile: &Option<PathBuf>,
1625 attrs: &[ast::Attribute],
1627 ) -> OutputFilenames {
1630 // "-" as input file will cause the parser to read from stdin so we
1631 // have to make up a name
1632 // We want to toss everything after the final '.'
1633 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
1635 // If a crate name is present, we use it as the link name
1636 let stem = sess.opts
1639 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1640 .unwrap_or_else(|| input.filestem().to_owned());
1643 out_directory: dirpath,
1645 single_output_file: None,
1646 extra: sess.opts.cg.extra_filename.clone(),
1647 outputs: sess.opts.output_types.clone(),
1651 Some(ref out_file) => {
1652 let unnamed_output_types = sess.opts
1655 .filter(|a| a.is_none())
1657 let ofile = if unnamed_output_types > 1 {
1659 "due to multiple output types requested, the explicitly specified \
1660 output file name will be adapted for each output type",
1664 Some(out_file.clone())
1667 sess.warn("ignoring --out-dir flag due to -o flag");
1669 if !sess.opts.cg.extra_filename.is_empty() {
1670 sess.warn("ignoring -C extra-filename flag due to -o flag");
1674 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
1675 out_filestem: out_file
1677 .unwrap_or_default()
1681 single_output_file: ofile,
1682 extra: sess.opts.cg.extra_filename.clone(),
1683 outputs: sess.opts.output_types.clone(),