1 use crate::interface::{Compiler, Result};
3 use crate::proc_macro_decls;
5 use log::{debug, info, warn, log_enabled};
6 use rustc::dep_graph::DepGraph;
8 use rustc::hir::lowering::lower_crate;
9 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
11 use rustc::middle::{self, reachable, resolve_lifetime, stability};
12 use rustc::middle::privacy::AccessLevels;
13 use rustc::ty::{self, AllArenas, Resolutions, TyCtxt, GlobalCtxt};
14 use rustc::ty::steal::Steal;
16 use rustc::util::common::{time, ErrorReported};
17 use rustc::util::profiling::ProfileCategory;
18 use rustc::session::{CompileResult, CrateDisambiguator, Session};
19 use rustc::session::config::{self, CrateType, Input, OutputFilenames, OutputType};
20 use rustc::session::search_paths::PathKind;
21 use rustc_allocator as allocator;
22 use rustc_borrowck as borrowck;
23 use rustc_codegen_ssa::back::link::emit_metadata;
24 use rustc_codegen_utils::codegen_backend::CodegenBackend;
25 use rustc_codegen_utils::link::filename_for_metadata;
26 use rustc_data_structures::{box_region_allow_access, declare_box_region_type, parallel};
27 use rustc_data_structures::fingerprint::Fingerprint;
28 use rustc_data_structures::stable_hasher::StableHasher;
29 use rustc_data_structures::sync::{Lrc, ParallelIterator, par_iter};
30 use rustc_incremental;
31 use rustc_incremental::DepGraphFuture;
32 use rustc_metadata::creader::CrateLoader;
33 use rustc_metadata::cstore::{self, CStore};
35 use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion, layout_test};
36 use rustc_plugin as plugin;
37 use rustc_plugin::registry::Registry;
39 use rustc_resolve::{Resolver, ResolverArenas};
41 use rustc_typeck as typeck;
42 use syntax::{self, ast, attr, diagnostics, visit};
43 use syntax::early_buffered_lints::BufferedEarlyLint;
44 use syntax::ext::base::{NamedSyntaxExtension, ExtCtxt};
45 use syntax::mut_visit::MutVisitor;
46 use syntax::parse::{self, PResult};
47 use syntax::util::node_count::NodeCounter;
48 use syntax::util::lev_distance::find_best_match_for_name;
49 use syntax::symbol::Symbol;
50 use syntax::feature_gate::AttributeType;
51 use syntax_pos::{FileName, edition::Edition, hygiene};
55 use tempfile::Builder as TempFileBuilder;
59 use std::ffi::OsString;
61 use std::io::{self, Write};
63 use std::path::{Path, PathBuf};
65 use std::cell::RefCell;
68 use std::ops::Generator;
70 pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
72 .set_continue_after_error(sess.opts.debugging_opts.continue_parse_after_error);
73 sess.profiler(|p| p.start_activity("parsing"));
74 let krate = time(sess, "parsing", || match *input {
75 Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
79 } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
81 sess.profiler(|p| p.end_activity("parsing"));
83 sess.diagnostic().set_continue_after_error(true);
85 if sess.opts.debugging_opts.ast_json_noexpand {
86 println!("{}", json::as_json(&krate));
89 if sess.opts.debugging_opts.input_stats {
92 sess.source_map().count_lines()
94 println!("Pre-expansion node count: {}", count_nodes(&krate));
97 if let Some(ref s) = sess.opts.debugging_opts.show_span {
98 syntax::show_span::run(sess.diagnostic(), s, &krate);
101 if sess.opts.debugging_opts.hir_stats {
102 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
108 fn count_nodes(krate: &ast::Crate) -> usize {
109 let mut counter = NodeCounter::new();
110 visit::walk_crate(&mut counter, krate);
114 declare_box_region_type!(
117 (&mut Resolver<'_>) -> (Result<ast::Crate>, ExpansionResult)
120 /// Runs the "early phases" of the compiler: initial `cfg` processing,
121 /// loading compiler plugins (including those from `addl_plugins`),
122 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
123 /// harness if one is to be provided, injection of a dependency on the
124 /// standard library and prelude, and name resolution.
126 /// Returns `None` if we're aborting after handling -W help.
127 pub fn configure_and_expand(
132 plugin_info: PluginInfo,
133 ) -> Result<(ast::Crate, BoxedResolver)> {
134 // Currently, we ignore the name resolution data structures for the purposes of dependency
135 // tracking. Instead we will run name resolution and include its output in the hash of each
136 // item, much like we do for macro expansion. In other words, the hash reflects not just
137 // its contents but the results of name resolution on those contents. Hopefully we'll push
138 // this back at some point.
139 let crate_name = crate_name.to_string();
140 let (result, resolver) = BoxedResolver::new(static move || {
142 let mut crate_loader = CrateLoader::new(sess, &*cstore, &crate_name);
143 let resolver_arenas = Resolver::arenas();
144 let res = configure_and_expand_inner(
153 let mut resolver = match res {
155 yield BoxedResolver::initial_yield(Err(v));
158 Ok((krate, resolver)) => {
159 yield BoxedResolver::initial_yield(Ok(krate));
163 box_region_allow_access!(for(), (&mut Resolver<'_>), (&mut resolver));
164 ExpansionResult::from_owned_resolver(resolver)
166 result.map(|k| (k, resolver))
169 pub struct ExpansionResult {
170 pub defs: Steal<hir::map::Definitions>,
171 pub resolutions: Steal<Resolutions>,
174 impl ExpansionResult {
175 fn from_owned_resolver(
176 resolver: Resolver<'_>,
179 defs: Steal::new(resolver.definitions),
180 resolutions: Steal::new(Resolutions {
181 upvars: resolver.upvars,
182 export_map: resolver.export_map,
183 trait_map: resolver.trait_map,
184 glob_map: resolver.glob_map,
185 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
186 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
187 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
188 (ident.name, entry.introduced_by_item)
194 pub fn from_resolver_ref(
195 resolver: &Resolver<'_>,
198 defs: Steal::new(resolver.definitions.clone()),
199 resolutions: Steal::new(Resolutions {
200 upvars: resolver.upvars.clone(),
201 export_map: resolver.export_map.clone(),
202 trait_map: resolver.trait_map.clone(),
203 glob_map: resolver.glob_map.clone(),
204 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
205 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
206 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
207 (ident.name, entry.introduced_by_item)
215 pub fn to_expansion_result(
216 mut resolver: Rc<Option<RefCell<BoxedResolver>>>,
217 ) -> ExpansionResult {
218 if let Some(resolver) = Rc::get_mut(&mut resolver) {
219 mem::replace(resolver, None).unwrap().into_inner().complete()
221 let resolver = &*resolver;
222 resolver.as_ref().unwrap().borrow_mut().access(|resolver| {
223 ExpansionResult::from_resolver_ref(resolver)
229 pub struct PluginInfo {
230 syntax_exts: Vec<NamedSyntaxExtension>,
231 attributes: Vec<(Symbol, AttributeType)>,
234 pub fn register_plugins<'a>(
238 mut krate: ast::Crate,
240 ) -> Result<(ast::Crate, PluginInfo)> {
241 krate = time(sess, "attributes injection", || {
242 syntax::attr::inject(krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr)
245 let (mut krate, features) = syntax::config::features(
249 &sess.opts.debugging_opts.allow_features,
251 // these need to be set "early" so that expansion sees `quote` if enabled.
252 sess.init_features(features);
254 let crate_types = util::collect_crate_types(sess, &krate.attrs);
255 sess.crate_types.set(crate_types);
257 let disambiguator = util::compute_crate_disambiguator(sess);
258 sess.crate_disambiguator.set(disambiguator);
259 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
261 if sess.opts.incremental.is_some() {
262 time(sess, "garbage collect incremental cache directory", || {
263 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
265 "Error while trying to garbage collect incremental \
266 compilation cache directory: {}",
273 // If necessary, compute the dependency graph (in the background).
274 compiler.dep_graph_future().ok();
276 time(sess, "recursion limit", || {
277 middle::recursion_limit::update_limits(sess, &krate);
280 krate = time(sess, "crate injection", || {
281 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
282 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name, sess.edition())
285 let registrars = time(sess, "plugin loading", || {
286 plugin::load::load_plugins(
291 Some(sess.opts.debugging_opts.extra_plugins.clone()),
295 let mut registry = Registry::new(sess, krate.span);
297 time(sess, "plugin registration", || {
298 if sess.features_untracked().rustc_diagnostic_macros {
299 registry.register_macro(
301 diagnostics::plugin::expand_diagnostic_used,
303 registry.register_macro(
304 "__register_diagnostic",
305 diagnostics::plugin::expand_register_diagnostic,
307 registry.register_macro(
308 "__build_diagnostic_array",
309 diagnostics::plugin::expand_build_diagnostic_array,
313 for registrar in registrars {
314 registry.args_hidden = Some(registrar.args);
315 (registrar.fun)(&mut registry);
329 let mut ls = sess.lint_store.borrow_mut();
330 for pass in early_lint_passes {
331 ls.register_early_pass(Some(sess), true, false, pass);
333 for pass in late_lint_passes {
334 ls.register_late_pass(Some(sess), true, false, false, pass);
337 for (name, (to, deprecated_name)) in lint_groups {
338 ls.register_group(Some(sess), true, name, deprecated_name, to);
341 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
342 *sess.plugin_attributes.borrow_mut() = attributes.clone();
344 Ok((krate, PluginInfo {
350 fn configure_and_expand_inner<'a>(
353 mut krate: ast::Crate,
355 resolver_arenas: &'a ResolverArenas<'a>,
356 crate_loader: &'a mut CrateLoader<'a>,
357 plugin_info: PluginInfo,
358 ) -> Result<(ast::Crate, Resolver<'a>)> {
359 let attributes = plugin_info.attributes;
360 time(sess, "pre ast expansion lint checks", || {
361 lint::check_ast_crate(
365 rustc_lint::BuiltinCombinedPreExpansionLintPass::new());
368 let mut resolver = Resolver::new(
376 syntax_ext::register_builtins(&mut resolver, plugin_info.syntax_exts, sess.edition());
379 sess.profiler(|p| p.start_activity("macro expansion"));
380 krate = time(sess, "expansion", || {
381 // Windows dlls do not have rpaths, so they don't know how to find their
382 // dependencies. It's up to us to tell the system where to find all the
383 // dependent dlls. Note that this uses cfg!(windows) as opposed to
384 // targ_cfg because syntax extensions are always loaded for the host
385 // compiler, not for the target.
387 // This is somewhat of an inherently racy operation, however, as
388 // multiple threads calling this function could possibly continue
389 // extending PATH far beyond what it should. To solve this for now we
390 // just don't add any new elements to PATH which are already there
391 // within PATH. This is basically a targeted fix at #17360 for rustdoc
392 // which runs rustc in parallel but has been seen (#33844) to cause
393 // problems with PATH becoming too long.
394 let mut old_path = OsString::new();
396 old_path = env::var_os("PATH").unwrap_or(old_path);
397 let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
398 for path in env::split_paths(&old_path) {
399 if !new_path.contains(&path) {
408 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
413 // Create the config for macro expansion
414 let features = sess.features_untracked();
415 let cfg = syntax::ext::expand::ExpansionConfig {
416 features: Some(&features),
417 recursion_limit: *sess.recursion_limit.get(),
418 trace_mac: sess.opts.debugging_opts.trace_macros,
419 should_test: sess.opts.test,
420 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
423 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
425 // Expand macros now!
426 let krate = time(sess, "expand crate", || {
427 ecx.monotonic_expander().expand_crate(krate)
430 // The rest is error reporting
432 time(sess, "check unused macros", || {
433 ecx.check_unused_macros();
436 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
437 .missing_fragment_specifiers
442 missing_fragment_specifiers.sort();
444 for span in missing_fragment_specifiers {
445 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
446 let msg = "missing fragment specifier";
447 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
450 env::set_var("PATH", &old_path);
454 sess.profiler(|p| p.end_activity("macro expansion"));
456 time(sess, "maybe building test harness", || {
457 syntax::test::modify_for_testing(
463 &sess.features_untracked(),
467 // If we're actually rustdoc then there's no need to actually compile
468 // anything, so switch everything to just looping
469 if sess.opts.actually_rustdoc {
470 util::ReplaceBodyWithLoop::new(sess).visit_crate(&mut krate);
473 let (has_proc_macro_decls, has_global_allocator) = time(sess, "AST validation", || {
474 ast_validation::check_crate(sess, &krate)
477 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
478 // bunch of checks in the `modify` function below. For now just skip this
479 // step entirely if we're rustdoc as it's not too useful anyway.
480 if !sess.opts.actually_rustdoc {
481 krate = time(sess, "maybe creating a macro crate", || {
482 let crate_types = sess.crate_types.borrow();
483 let num_crate_types = crate_types.len();
484 let is_proc_macro_crate = crate_types.contains(&config::CrateType::ProcMacro);
485 let is_test_crate = sess.opts.test;
486 syntax_ext::proc_macro_decls::modify(
491 has_proc_macro_decls,
499 if has_global_allocator {
500 // Expand global allocators, which are treated as an in-tree proc macro
501 time(sess, "creating allocators", || {
502 allocator::expand::modify(
506 crate_name.to_string(),
512 // Done with macro expansion!
514 if sess.opts.debugging_opts.input_stats {
515 println!("Post-expansion node count: {}", count_nodes(&krate));
518 if sess.opts.debugging_opts.hir_stats {
519 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
522 if sess.opts.debugging_opts.ast_json {
523 println!("{}", json::as_json(&krate));
526 time(sess, "name resolution", || {
527 resolver.resolve_crate(&krate);
530 // Needs to go *after* expansion to be able to check the results of macro expansion.
531 time(sess, "complete gated feature checking", || {
532 syntax::feature_gate::check_crate(
535 &sess.features_untracked(),
537 sess.opts.unstable_features,
541 // Add all buffered lints from the `ParseSess` to the `Session`.
542 sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
543 info!("{} parse sess buffered_lints", buffered_lints.len());
544 for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) {
545 let lint = lint::Lint::from_parser_lint_id(lint_id);
546 sess.buffer_lint(lint, id, span, &msg);
550 Ok((krate, resolver))
556 resolver: &mut Resolver<'_>,
557 dep_graph: &DepGraph,
559 ) -> Result<hir::map::Forest> {
561 let hir_forest = time(sess, "lowering ast -> hir", || {
562 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, resolver);
564 if sess.opts.debugging_opts.hir_stats {
565 hir_stats::print_hir_stats(&hir_crate);
568 hir::map::Forest::new(hir_crate, &dep_graph)
571 time(sess, "early lint checks", || {
572 lint::check_ast_crate(sess, &krate, false, rustc_lint::BuiltinCombinedEarlyLintPass::new())
575 // Discard hygiene data, which isn't required after lowering to HIR.
576 if !sess.opts.debugging_opts.keep_hygiene_data {
577 syntax::ext::hygiene::clear_markings();
583 // Returns all the paths that correspond to generated files.
584 fn generated_output_paths(
586 outputs: &OutputFilenames,
590 let mut out_filenames = Vec::new();
591 for output_type in sess.opts.output_types.keys() {
592 let file = outputs.path(*output_type);
594 // If the filename has been overridden using `-o`, it will not be modified
595 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
596 OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
597 let p = ::rustc_codegen_utils::link::filename_for_input(
603 out_filenames.push(p);
605 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
606 // Don't add the dep-info output when omitting it from dep-info targets
609 out_filenames.push(file);
616 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
617 // returns None for every file path.
618 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
620 F: Fn(&PathBuf) -> Option<T>,
622 for output_path in output_paths {
623 if let Some(result) = f(output_path) {
630 fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
631 let input_path = input_path.canonicalize().ok();
632 if input_path.is_none() {
635 let check = |output_path: &PathBuf| {
636 if output_path.canonicalize().ok() == input_path {
642 check_output(output_paths, check).is_some()
645 fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
646 let check = |output_path: &PathBuf| {
647 if output_path.is_dir() {
648 Some(output_path.clone())
653 check_output(output_paths, check)
656 fn escape_dep_filename(filename: &FileName) -> String {
657 // Apparently clang and gcc *only* escape spaces:
658 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
659 filename.to_string().replace(" ", "\\ ")
662 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
663 // Write out dependency rules to the dep-info file if requested
664 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
667 let deps_filename = outputs.path(OutputType::DepInfo);
669 let result = (|| -> io::Result<()> {
670 // Build a list of files used to compile the output and
671 // write Makefile-compatible dependency rules
672 let files: Vec<String> = sess.source_map()
675 .filter(|fmap| fmap.is_real_file())
676 .filter(|fmap| !fmap.is_imported())
677 .map(|fmap| escape_dep_filename(&fmap.name))
679 let mut file = fs::File::create(&deps_filename)?;
680 for path in out_filenames {
681 writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
684 // Emit a fake target for each input file to the compilation. This
685 // prevents `make` from spitting out an error if a file is later
686 // deleted. For more info see #28735
688 writeln!(file, "{}:", path)?;
693 if let Err(e) = result {
695 "error writing dependencies to `{}`: {}",
696 deps_filename.display(),
702 pub fn prepare_outputs(
707 ) -> Result<OutputFilenames> {
708 // FIXME: rustdoc passes &[] instead of &krate.attrs here
709 let outputs = util::build_output_filenames(
711 &compiler.output_dir,
712 &compiler.output_file,
717 let output_paths = generated_output_paths(
720 compiler.output_file.is_some(),
724 // Ensure the source file isn't accidentally overwritten during compilation.
725 if let Some(ref input_path) = compiler.input_path {
726 if sess.opts.will_create_output_file() {
727 if output_contains_path(&output_paths, input_path) {
729 "the input file \"{}\" would be overwritten by the generated \
733 return Err(ErrorReported);
735 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
737 "the generated executable for the input file \"{}\" conflicts with the \
738 existing directory \"{}\"",
739 input_path.display(),
742 return Err(ErrorReported);
747 write_out_deps(sess, &outputs, &output_paths);
749 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
750 && sess.opts.output_types.len() == 1;
753 if let Some(ref dir) = compiler.output_dir {
754 if fs::create_dir_all(dir).is_err() {
755 sess.err("failed to find or create the directory specified by --out-dir");
756 return Err(ErrorReported);
764 pub fn default_provide(providers: &mut ty::query::Providers<'_>) {
765 providers.analysis = analysis;
766 proc_macro_decls::provide(providers);
767 plugin::build::provide(providers);
768 hir::provide(providers);
769 borrowck::provide(providers);
770 mir::provide(providers);
771 reachable::provide(providers);
772 resolve_lifetime::provide(providers);
773 rustc_privacy::provide(providers);
774 typeck::provide(providers);
775 ty::provide(providers);
776 traits::provide(providers);
777 stability::provide(providers);
778 middle::intrinsicck::provide(providers);
779 middle::liveness::provide(providers);
780 reachable::provide(providers);
781 rustc_passes::provide(providers);
782 rustc_traits::provide(providers);
783 middle::region::provide(providers);
784 middle::entry::provide(providers);
785 cstore::provide(providers);
786 lint::provide(providers);
787 rustc_lint::provide(providers);
790 pub fn default_provide_extern(providers: &mut ty::query::Providers<'_>) {
791 cstore::provide_extern(providers);
794 declare_box_region_type!(
797 (&'gcx GlobalCtxt<'gcx>) -> ((), ())
800 impl BoxedGlobalCtxt {
801 pub fn enter<F, R>(&mut self, f: F) -> R
803 F: for<'tcx> FnOnce(TyCtxt<'tcx, 'tcx, 'tcx>) -> R
805 self.access(|gcx| ty::tls::enter_global(gcx, |tcx| f(tcx)))
809 pub fn create_global_ctxt(
811 mut hir_forest: hir::map::Forest,
812 defs: hir::map::Definitions,
813 resolutions: Resolutions,
814 outputs: OutputFilenames,
815 tx: mpsc::Sender<Box<dyn Any + Send>>,
817 ) -> BoxedGlobalCtxt {
818 let sess = compiler.session().clone();
819 let cstore = compiler.cstore.clone();
820 let codegen_backend = compiler.codegen_backend().clone();
821 let crate_name = crate_name.to_string();
823 let ((), result) = BoxedGlobalCtxt::new(static move || {
825 let cstore = &*cstore;
827 let global_ctxt: Option<GlobalCtxt<'_>>;
828 let arenas = AllArenas::new();
830 // Construct the HIR map
831 let hir_map = time(sess, "indexing hir", || {
832 hir::map::map_crate(sess, cstore, &mut hir_forest, &defs)
835 let query_result_on_disk_cache = time(sess, "load query result cache", || {
836 rustc_incremental::load_query_result_cache(sess)
839 let mut local_providers = ty::query::Providers::default();
840 default_provide(&mut local_providers);
841 codegen_backend.provide(&mut local_providers);
843 let mut extern_providers = local_providers;
844 default_provide_extern(&mut extern_providers);
845 codegen_backend.provide_extern(&mut extern_providers);
847 let gcx = TyCtxt::create_global_ctxt(
855 query_result_on_disk_cache,
861 global_ctxt = Some(gcx);
862 let gcx = global_ctxt.as_ref().unwrap();
864 ty::tls::enter_global(gcx, |tcx| {
865 // Do some initialization of the DepGraph that can only be done with the
867 time(tcx.sess, "dep graph tcx init", || rustc_incremental::dep_graph_tcx_init(tcx));
870 yield BoxedGlobalCtxt::initial_yield(());
871 box_region_allow_access!(for('gcx), (&'gcx GlobalCtxt<'gcx>), (gcx));
873 if sess.opts.debugging_opts.query_stats {
874 gcx.queries.print_stats();
881 /// Runs the resolution, type-checking, region checking and other
882 /// miscellaneous analysis passes on the crate.
884 tcx: TyCtxt<'_, 'tcx, 'tcx>,
887 assert_eq!(cnum, LOCAL_CRATE);
890 let mut entry_point = None;
892 time(sess, "misc checking 1", || {
894 entry_point = time(sess, "looking for entry point", || {
895 middle::entry::find_entry_point(tcx)
898 time(sess, "looking for plugin registrar", || {
899 plugin::build::find_plugin_registrar(tcx)
902 time(sess, "looking for derive registrar", || {
903 proc_macro_decls::find(tcx)
906 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
907 tcx.ensure().check_mod_loops(tcx.hir().local_def_id(module));
908 tcx.ensure().check_mod_attrs(tcx.hir().local_def_id(module));
909 tcx.ensure().check_mod_unstable_api_usage(tcx.hir().local_def_id(module));
914 // passes are timed inside typeck
915 typeck::check_crate(tcx)?;
917 time(sess, "misc checking 2", || {
919 time(sess, "rvalue promotion + match checking", || {
920 tcx.par_body_owners(|def_id| {
921 tcx.ensure().const_is_rvalue_promotable_to_static(def_id);
922 tcx.ensure().check_match(def_id);
926 time(sess, "liveness checking + intrinsic checking", || {
927 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
928 // this must run before MIR dump, because
929 // "not all control paths return a value" is reported here.
931 // maybe move the check to a MIR pass?
932 tcx.ensure().check_mod_liveness(tcx.hir().local_def_id(module));
934 tcx.ensure().check_mod_intrinsics(tcx.hir().local_def_id(module));
940 time(sess, "borrow checking", || {
941 if tcx.use_ast_borrowck() {
942 borrowck::check_crate(tcx);
946 time(sess, "MIR borrow checking", || {
947 tcx.par_body_owners(|def_id| tcx.ensure().mir_borrowck(def_id));
950 time(sess, "dumping chalk-like clauses", || {
951 rustc_traits::lowering::dump_program_clauses(tcx);
954 time(sess, "MIR effect checking", || {
955 for def_id in tcx.body_owners() {
956 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
960 time(sess, "layout testing", || layout_test::test_layout(tcx));
962 // Avoid overwhelming user with errors if borrow checking failed.
963 // I'm not sure how helpful this is, to be honest, but it avoids a
964 // lot of annoying errors in the compile-fail tests (basically,
965 // lint warnings and so on -- kindck used to do this abort, but
966 // kindck is gone now). -nmatsakis
967 if sess.err_count() > 0 {
968 return Err(ErrorReported);
971 time(sess, "misc checking 3", || {
973 time(sess, "privacy access levels", || {
974 tcx.ensure().privacy_access_levels(LOCAL_CRATE);
977 time(sess, "private in public", || {
978 tcx.ensure().check_private_in_public(LOCAL_CRATE);
981 time(sess, "death checking", || middle::dead::check_crate(tcx));
983 time(sess, "unused lib feature checking", || {
984 stability::check_unused_or_stable_features(tcx)
987 time(sess, "lint checking", || {
988 lint::check_crate(tcx, || rustc_lint::BuiltinCombinedLateLintPass::new());
992 time(sess, "privacy checking modules", || {
993 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
994 tcx.ensure().check_mod_privacy(tcx.hir().local_def_id(module));
1003 fn encode_and_write_metadata<'tcx>(
1004 tcx: TyCtxt<'_, 'tcx, 'tcx>,
1005 outputs: &OutputFilenames,
1006 ) -> (middle::cstore::EncodedMetadata, bool) {
1007 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1014 let metadata_kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
1016 CrateType::Executable |
1017 CrateType::Staticlib |
1018 CrateType::Cdylib => MetadataKind::None,
1020 CrateType::Rlib => MetadataKind::Uncompressed,
1023 CrateType::ProcMacro => MetadataKind::Compressed,
1025 }).max().unwrap_or(MetadataKind::None);
1027 let metadata = match metadata_kind {
1028 MetadataKind::None => middle::cstore::EncodedMetadata::new(),
1029 MetadataKind::Uncompressed |
1030 MetadataKind::Compressed => tcx.encode_metadata(),
1033 let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
1034 if need_metadata_file {
1035 let crate_name = &tcx.crate_name(LOCAL_CRATE).as_str();
1036 let out_filename = filename_for_metadata(tcx.sess, crate_name, outputs);
1037 // To avoid races with another rustc process scanning the output directory,
1038 // we need to write the file somewhere else and atomically move it to its
1039 // final destination, with an `fs::rename` call. In order for the rename to
1040 // always succeed, the temporary file needs to be on the same filesystem,
1041 // which is why we create it inside the output directory specifically.
1042 let metadata_tmpdir = TempFileBuilder::new()
1044 .tempdir_in(out_filename.parent().unwrap())
1045 .unwrap_or_else(|err| {
1046 tcx.sess.fatal(&format!("couldn't create a temp dir: {}", err))
1048 let metadata_filename = emit_metadata(tcx.sess, &metadata, &metadata_tmpdir);
1049 if let Err(e) = fs::rename(&metadata_filename, &out_filename) {
1050 tcx.sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
1052 if tcx.sess.opts.debugging_opts.emit_artifact_notifications {
1053 tcx.sess.parse_sess.span_diagnostic
1054 .emit_artifact_notification(&out_filename, "metadata");
1058 let need_metadata_module = metadata_kind == MetadataKind::Compressed;
1060 (metadata, need_metadata_module)
1063 /// Runs the codegen backend, after which the AST and analysis can
1065 pub fn start_codegen<'tcx>(
1066 codegen_backend: &dyn CodegenBackend,
1067 tcx: TyCtxt<'_, 'tcx, 'tcx>,
1068 rx: mpsc::Receiver<Box<dyn Any + Send>>,
1069 outputs: &OutputFilenames,
1071 if log_enabled!(::log::Level::Info) {
1072 println!("Pre-codegen");
1073 tcx.print_debug_stats();
1076 time(tcx.sess, "resolving dependency formats", || {
1077 middle::dependency_format::calculate(tcx)
1080 let (metadata, need_metadata_module) = time(tcx.sess, "metadata encoding and writing", || {
1081 encode_and_write_metadata(tcx, outputs)
1084 tcx.sess.profiler(|p| p.start_activity("codegen crate"));
1085 let codegen = time(tcx.sess, "codegen", move || {
1086 codegen_backend.codegen_crate(tcx, metadata, need_metadata_module, rx)
1088 tcx.sess.profiler(|p| p.end_activity("codegen crate"));
1090 if log_enabled!(::log::Level::Info) {
1091 println!("Post-codegen");
1092 tcx.print_debug_stats();
1095 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
1096 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, outputs) {
1097 tcx.sess.err(&format!("could not emit MIR: {}", e));
1098 tcx.sess.abort_if_errors();