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_utils::codegen_backend::CodegenBackend;
24 use rustc_data_structures::{box_region_allow_access, declare_box_region_type, parallel};
25 use rustc_data_structures::fingerprint::Fingerprint;
26 use rustc_data_structures::stable_hasher::StableHasher;
27 use rustc_data_structures::sync::{Lrc, ParallelIterator, par_iter};
28 use rustc_incremental;
29 use rustc_incremental::DepGraphFuture;
30 use rustc_metadata::creader::CrateLoader;
31 use rustc_metadata::cstore::{self, CStore};
33 use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion, layout_test};
34 use rustc_plugin as plugin;
35 use rustc_plugin::registry::Registry;
37 use rustc_resolve::{Resolver, ResolverArenas};
39 use rustc_typeck as typeck;
40 use syntax::{self, ast, attr, diagnostics, visit};
41 use syntax::early_buffered_lints::BufferedEarlyLint;
42 use syntax::ext::base::{NamedSyntaxExtension, ExtCtxt};
43 use syntax::mut_visit::MutVisitor;
44 use syntax::parse::{self, PResult};
45 use syntax::util::node_count::NodeCounter;
46 use syntax::util::lev_distance::find_best_match_for_name;
47 use syntax::symbol::Symbol;
48 use syntax::feature_gate::AttributeType;
49 use syntax_pos::{FileName, hygiene};
56 use std::ffi::OsString;
58 use std::io::{self, Write};
60 use std::path::{Path, PathBuf};
62 use std::cell::RefCell;
65 use std::ops::Generator;
67 pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
69 .set_continue_after_error(sess.opts.debugging_opts.continue_parse_after_error);
70 hygiene::set_default_edition(sess.edition());
72 sess.profiler(|p| p.start_activity("parsing"));
73 let krate = time(sess, "parsing", || match *input {
74 Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
78 } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
80 sess.profiler(|p| p.end_activity("parsing"));
82 sess.diagnostic().set_continue_after_error(true);
84 if sess.opts.debugging_opts.ast_json_noexpand {
85 println!("{}", json::as_json(&krate));
88 if sess.opts.debugging_opts.input_stats {
91 sess.source_map().count_lines()
93 println!("Pre-expansion node count: {}", count_nodes(&krate));
96 if let Some(ref s) = sess.opts.debugging_opts.show_span {
97 syntax::show_span::run(sess.diagnostic(), s, &krate);
100 if sess.opts.debugging_opts.hir_stats {
101 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
107 fn count_nodes(krate: &ast::Crate) -> usize {
108 let mut counter = NodeCounter::new();
109 visit::walk_crate(&mut counter, krate);
113 declare_box_region_type!(
116 (&mut Resolver<'_>) -> (Result<ast::Crate>, ExpansionResult)
119 /// Runs the "early phases" of the compiler: initial `cfg` processing,
120 /// loading compiler plugins (including those from `addl_plugins`),
121 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
122 /// harness if one is to be provided, injection of a dependency on the
123 /// standard library and prelude, and name resolution.
125 /// Returns `None` if we're aborting after handling -W help.
126 pub fn configure_and_expand(
131 plugin_info: PluginInfo,
132 ) -> Result<(ast::Crate, BoxedResolver)> {
133 // Currently, we ignore the name resolution data structures for the purposes of dependency
134 // tracking. Instead we will run name resolution and include its output in the hash of each
135 // item, much like we do for macro expansion. In other words, the hash reflects not just
136 // its contents but the results of name resolution on those contents. Hopefully we'll push
137 // this back at some point.
138 let crate_name = crate_name.to_string();
139 let (result, resolver) = BoxedResolver::new(static move || {
141 let mut crate_loader = CrateLoader::new(sess, &*cstore, &crate_name);
142 let resolver_arenas = Resolver::arenas();
143 let res = configure_and_expand_inner(
152 let mut resolver = match res {
154 yield BoxedResolver::initial_yield(Err(v));
157 Ok((krate, resolver)) => {
158 yield BoxedResolver::initial_yield(Ok(krate));
162 box_region_allow_access!(for(), (&mut Resolver<'_>), (&mut resolver));
163 ExpansionResult::from_owned_resolver(resolver)
165 result.map(|k| (k, resolver))
168 pub struct ExpansionResult {
169 pub defs: Steal<hir::map::Definitions>,
170 pub resolutions: Steal<Resolutions>,
173 impl ExpansionResult {
174 fn from_owned_resolver(
175 resolver: Resolver<'_>,
178 defs: Steal::new(resolver.definitions),
179 resolutions: Steal::new(Resolutions {
180 freevars: resolver.freevars,
181 export_map: resolver.export_map,
182 trait_map: resolver.trait_map,
183 glob_map: resolver.glob_map,
184 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
185 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
186 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
187 (ident.name, entry.introduced_by_item)
193 pub fn from_resolver_ref(
194 resolver: &Resolver<'_>,
197 defs: Steal::new(resolver.definitions.clone()),
198 resolutions: Steal::new(Resolutions {
199 freevars: resolver.freevars.clone(),
200 export_map: resolver.export_map.clone(),
201 trait_map: resolver.trait_map.clone(),
202 glob_map: resolver.glob_map.clone(),
203 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
204 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
205 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
206 (ident.name, entry.introduced_by_item)
214 pub fn to_expansion_result(
215 mut resolver: Rc<Option<RefCell<BoxedResolver>>>,
216 ) -> ExpansionResult {
217 if let Some(resolver) = Rc::get_mut(&mut resolver) {
218 mem::replace(resolver, None).unwrap().into_inner().complete()
220 let resolver = &*resolver;
221 resolver.as_ref().unwrap().borrow_mut().access(|resolver| {
222 ExpansionResult::from_resolver_ref(resolver)
228 pub struct PluginInfo {
229 syntax_exts: Vec<NamedSyntaxExtension>,
230 attributes: Vec<(String, AttributeType)>,
233 pub fn register_plugins<'a>(
237 mut krate: ast::Crate,
239 ) -> Result<(ast::Crate, PluginInfo)> {
240 krate = time(sess, "attributes injection", || {
241 syntax::attr::inject(krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr)
244 let (mut krate, features) = syntax::config::features(
248 &sess.opts.debugging_opts.allow_features,
250 // these need to be set "early" so that expansion sees `quote` if enabled.
251 sess.init_features(features);
253 let crate_types = util::collect_crate_types(sess, &krate.attrs);
254 sess.crate_types.set(crate_types);
256 let disambiguator = util::compute_crate_disambiguator(sess);
257 sess.crate_disambiguator.set(disambiguator);
258 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
260 if sess.opts.incremental.is_some() {
261 time(sess, "garbage collect incremental cache directory", || {
262 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
264 "Error while trying to garbage collect incremental \
265 compilation cache directory: {}",
272 // If necessary, compute the dependency graph (in the background).
273 compiler.dep_graph_future().ok();
275 time(sess, "recursion limit", || {
276 middle::recursion_limit::update_limits(sess, &krate);
279 krate = time(sess, "crate injection", || {
280 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
281 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name, sess.edition())
284 let registrars = time(sess, "plugin loading", || {
285 plugin::load::load_plugins(
290 Some(sess.opts.debugging_opts.extra_plugins.clone()),
294 let mut registry = Registry::new(sess, krate.span);
296 time(sess, "plugin registration", || {
297 if sess.features_untracked().rustc_diagnostic_macros {
298 registry.register_macro(
300 diagnostics::plugin::expand_diagnostic_used,
302 registry.register_macro(
303 "__register_diagnostic",
304 diagnostics::plugin::expand_register_diagnostic,
306 registry.register_macro(
307 "__build_diagnostic_array",
308 diagnostics::plugin::expand_build_diagnostic_array,
312 for registrar in registrars {
313 registry.args_hidden = Some(registrar.args);
314 (registrar.fun)(&mut registry);
328 let mut ls = sess.lint_store.borrow_mut();
329 for pass in early_lint_passes {
330 ls.register_early_pass(Some(sess), true, false, pass);
332 for pass in late_lint_passes {
333 ls.register_late_pass(Some(sess), true, false, false, pass);
336 for (name, (to, deprecated_name)) in lint_groups {
337 ls.register_group(Some(sess), true, name, deprecated_name, to);
340 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
341 *sess.plugin_attributes.borrow_mut() = attributes.clone();
343 Ok((krate, PluginInfo {
349 fn configure_and_expand_inner<'a>(
352 mut krate: ast::Crate,
354 resolver_arenas: &'a ResolverArenas<'a>,
355 crate_loader: &'a mut CrateLoader<'a>,
356 plugin_info: PluginInfo,
357 ) -> Result<(ast::Crate, Resolver<'a>)> {
358 let attributes = plugin_info.attributes;
359 time(sess, "pre ast expansion lint checks", || {
360 lint::check_ast_crate(
364 rustc_lint::BuiltinCombinedPreExpansionLintPass::new());
367 let mut resolver = Resolver::new(
375 syntax_ext::register_builtins(&mut resolver, plugin_info.syntax_exts);
378 sess.profiler(|p| p.start_activity("macro expansion"));
379 krate = time(sess, "expansion", || {
380 // Windows dlls do not have rpaths, so they don't know how to find their
381 // dependencies. It's up to us to tell the system where to find all the
382 // dependent dlls. Note that this uses cfg!(windows) as opposed to
383 // targ_cfg because syntax extensions are always loaded for the host
384 // compiler, not for the target.
386 // This is somewhat of an inherently racy operation, however, as
387 // multiple threads calling this function could possibly continue
388 // extending PATH far beyond what it should. To solve this for now we
389 // just don't add any new elements to PATH which are already there
390 // within PATH. This is basically a targeted fix at #17360 for rustdoc
391 // which runs rustc in parallel but has been seen (#33844) to cause
392 // problems with PATH becoming too long.
393 let mut old_path = OsString::new();
395 old_path = env::var_os("PATH").unwrap_or(old_path);
396 let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
397 for path in env::split_paths(&old_path) {
398 if !new_path.contains(&path) {
407 .filter(|p| env::join_paths(iter::once(p)).is_ok()),
412 // Create the config for macro expansion
413 let features = sess.features_untracked();
414 let cfg = syntax::ext::expand::ExpansionConfig {
415 features: Some(&features),
416 recursion_limit: *sess.recursion_limit.get(),
417 trace_mac: sess.opts.debugging_opts.trace_macros,
418 should_test: sess.opts.test,
419 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
422 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
424 // Expand macros now!
425 let krate = time(sess, "expand crate", || {
426 ecx.monotonic_expander().expand_crate(krate)
429 // The rest is error reporting
431 time(sess, "check unused macros", || {
432 ecx.check_unused_macros();
435 let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
436 .missing_fragment_specifiers
441 missing_fragment_specifiers.sort();
443 for span in missing_fragment_specifiers {
444 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
445 let msg = "missing fragment specifier";
446 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
449 env::set_var("PATH", &old_path);
453 sess.profiler(|p| p.end_activity("macro expansion"));
455 time(sess, "maybe building test harness", || {
456 syntax::test::modify_for_testing(
462 &sess.features_untracked(),
466 // If we're actually rustdoc then there's no need to actually compile
467 // anything, so switch everything to just looping
468 if sess.opts.actually_rustdoc {
469 util::ReplaceBodyWithLoop::new(sess).visit_crate(&mut krate);
472 let (has_proc_macro_decls, has_global_allocator) = time(sess, "AST validation", || {
473 ast_validation::check_crate(sess, &krate)
476 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
477 // bunch of checks in the `modify` function below. For now just skip this
478 // step entirely if we're rustdoc as it's not too useful anyway.
479 if !sess.opts.actually_rustdoc {
480 krate = time(sess, "maybe creating a macro crate", || {
481 let crate_types = sess.crate_types.borrow();
482 let num_crate_types = crate_types.len();
483 let is_proc_macro_crate = crate_types.contains(&config::CrateType::ProcMacro);
484 let is_test_crate = sess.opts.test;
485 syntax_ext::proc_macro_decls::modify(
490 has_proc_macro_decls,
498 if has_global_allocator {
499 // Expand global allocators, which are treated as an in-tree proc macro
500 time(sess, "creating allocators", || {
501 allocator::expand::modify(
505 crate_name.to_string(),
511 // Done with macro expansion!
513 if sess.opts.debugging_opts.input_stats {
514 println!("Post-expansion node count: {}", count_nodes(&krate));
517 if sess.opts.debugging_opts.hir_stats {
518 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
521 if sess.opts.debugging_opts.ast_json {
522 println!("{}", json::as_json(&krate));
525 time(sess, "name resolution", || {
526 resolver.resolve_crate(&krate);
529 // Needs to go *after* expansion to be able to check the results of macro expansion.
530 time(sess, "complete gated feature checking", || {
531 syntax::feature_gate::check_crate(
534 &sess.features_untracked(),
536 sess.opts.unstable_features,
540 // Add all buffered lints from the `ParseSess` to the `Session`.
541 sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
542 info!("{} parse sess buffered_lints", buffered_lints.len());
543 for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) {
544 let lint = lint::Lint::from_parser_lint_id(lint_id);
545 sess.buffer_lint(lint, id, span, &msg);
549 Ok((krate, resolver))
555 resolver: &mut Resolver<'_>,
556 dep_graph: &DepGraph,
558 ) -> Result<hir::map::Forest> {
560 let hir_forest = time(sess, "lowering ast -> hir", || {
561 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, resolver);
563 if sess.opts.debugging_opts.hir_stats {
564 hir_stats::print_hir_stats(&hir_crate);
567 hir::map::Forest::new(hir_crate, &dep_graph)
570 time(sess, "early lint checks", || {
571 lint::check_ast_crate(sess, &krate, false, rustc_lint::BuiltinCombinedEarlyLintPass::new())
574 // Discard hygiene data, which isn't required after lowering to HIR.
575 if !sess.opts.debugging_opts.keep_hygiene_data {
576 syntax::ext::hygiene::clear_markings();
582 // Returns all the paths that correspond to generated files.
583 fn generated_output_paths(
585 outputs: &OutputFilenames,
589 let mut out_filenames = Vec::new();
590 for output_type in sess.opts.output_types.keys() {
591 let file = outputs.path(*output_type);
593 // If the filename has been overridden using `-o`, it will not be modified
594 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
595 OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
596 let p = ::rustc_codegen_utils::link::filename_for_input(
602 out_filenames.push(p);
604 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
605 // Don't add the dep-info output when omitting it from dep-info targets
608 out_filenames.push(file);
615 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
616 // returns None for every file path.
617 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
619 F: Fn(&PathBuf) -> Option<T>,
621 for output_path in output_paths {
622 if let Some(result) = f(output_path) {
629 fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
630 let input_path = input_path.canonicalize().ok();
631 if input_path.is_none() {
634 let check = |output_path: &PathBuf| {
635 if output_path.canonicalize().ok() == input_path {
641 check_output(output_paths, check).is_some()
644 fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
645 let check = |output_path: &PathBuf| {
646 if output_path.is_dir() {
647 Some(output_path.clone())
652 check_output(output_paths, check)
655 fn escape_dep_filename(filename: &FileName) -> String {
656 // Apparently clang and gcc *only* escape spaces:
657 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
658 filename.to_string().replace(" ", "\\ ")
661 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
662 // Write out dependency rules to the dep-info file if requested
663 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
666 let deps_filename = outputs.path(OutputType::DepInfo);
668 let result = (|| -> io::Result<()> {
669 // Build a list of files used to compile the output and
670 // write Makefile-compatible dependency rules
671 let files: Vec<String> = sess.source_map()
674 .filter(|fmap| fmap.is_real_file())
675 .filter(|fmap| !fmap.is_imported())
676 .map(|fmap| escape_dep_filename(&fmap.name))
678 let mut file = fs::File::create(&deps_filename)?;
679 for path in out_filenames {
680 writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
683 // Emit a fake target for each input file to the compilation. This
684 // prevents `make` from spitting out an error if a file is later
685 // deleted. For more info see #28735
687 writeln!(file, "{}:", path)?;
692 if let Err(e) = result {
694 "error writing dependencies to `{}`: {}",
695 deps_filename.display(),
701 pub fn prepare_outputs(
706 ) -> Result<OutputFilenames> {
707 // FIXME: rustdoc passes &[] instead of &krate.attrs here
708 let outputs = util::build_output_filenames(
710 &compiler.output_dir,
711 &compiler.output_file,
716 let output_paths = generated_output_paths(
719 compiler.output_file.is_some(),
723 // Ensure the source file isn't accidentally overwritten during compilation.
724 if let Some(ref input_path) = compiler.input_path {
725 if sess.opts.will_create_output_file() {
726 if output_contains_path(&output_paths, input_path) {
728 "the input file \"{}\" would be overwritten by the generated \
732 return Err(ErrorReported);
734 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
736 "the generated executable for the input file \"{}\" conflicts with the \
737 existing directory \"{}\"",
738 input_path.display(),
741 return Err(ErrorReported);
746 write_out_deps(sess, &outputs, &output_paths);
748 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
749 && sess.opts.output_types.len() == 1;
752 if let Some(ref dir) = compiler.output_dir {
753 if fs::create_dir_all(dir).is_err() {
754 sess.err("failed to find or create the directory specified by --out-dir");
755 return Err(ErrorReported);
763 pub fn default_provide(providers: &mut ty::query::Providers<'_>) {
764 providers.analysis = analysis;
765 proc_macro_decls::provide(providers);
766 plugin::build::provide(providers);
767 hir::provide(providers);
768 borrowck::provide(providers);
769 mir::provide(providers);
770 reachable::provide(providers);
771 resolve_lifetime::provide(providers);
772 rustc_privacy::provide(providers);
773 typeck::provide(providers);
774 ty::provide(providers);
775 traits::provide(providers);
776 stability::provide(providers);
777 middle::intrinsicck::provide(providers);
778 middle::liveness::provide(providers);
779 reachable::provide(providers);
780 rustc_passes::provide(providers);
781 rustc_traits::provide(providers);
782 middle::region::provide(providers);
783 middle::entry::provide(providers);
784 cstore::provide(providers);
785 lint::provide(providers);
786 rustc_lint::provide(providers);
789 pub fn default_provide_extern(providers: &mut ty::query::Providers<'_>) {
790 cstore::provide_extern(providers);
793 declare_box_region_type!(
796 (&'gcx GlobalCtxt<'gcx>) -> ((), ())
799 impl BoxedGlobalCtxt {
800 pub fn enter<F, R>(&mut self, f: F) -> R
802 F: for<'tcx> FnOnce(TyCtxt<'tcx, 'tcx, 'tcx>) -> R
804 self.access(|gcx| ty::tls::enter_global(gcx, |tcx| f(tcx)))
808 pub fn create_global_ctxt(
810 mut hir_forest: hir::map::Forest,
811 defs: hir::map::Definitions,
812 resolutions: Resolutions,
813 outputs: OutputFilenames,
814 tx: mpsc::Sender<Box<dyn Any + Send>>,
816 ) -> BoxedGlobalCtxt {
817 let sess = compiler.session().clone();
818 let cstore = compiler.cstore.clone();
819 let codegen_backend = compiler.codegen_backend().clone();
820 let crate_name = crate_name.to_string();
822 let ((), result) = BoxedGlobalCtxt::new(static move || {
824 let cstore = &*cstore;
826 let global_ctxt: Option<GlobalCtxt<'_>>;
827 let arenas = AllArenas::new();
829 // Construct the HIR map
830 let hir_map = time(sess, "indexing hir", || {
831 hir::map::map_crate(sess, cstore, &mut hir_forest, &defs)
834 let query_result_on_disk_cache = time(sess, "load query result cache", || {
835 rustc_incremental::load_query_result_cache(sess)
838 let mut local_providers = ty::query::Providers::default();
839 default_provide(&mut local_providers);
840 codegen_backend.provide(&mut local_providers);
842 let mut extern_providers = local_providers;
843 default_provide_extern(&mut extern_providers);
844 codegen_backend.provide_extern(&mut extern_providers);
846 let gcx = TyCtxt::create_global_ctxt(
854 query_result_on_disk_cache,
860 global_ctxt = Some(gcx);
861 let gcx = global_ctxt.as_ref().unwrap();
863 ty::tls::enter_global(gcx, |tcx| {
864 // Do some initialization of the DepGraph that can only be done with the
866 time(tcx.sess, "dep graph tcx init", || rustc_incremental::dep_graph_tcx_init(tcx));
869 yield BoxedGlobalCtxt::initial_yield(());
870 box_region_allow_access!(for('gcx), (&'gcx GlobalCtxt<'gcx>), (gcx));
872 if sess.opts.debugging_opts.query_stats {
873 gcx.queries.print_stats();
880 /// Runs the resolution, type-checking, region checking and other
881 /// miscellaneous analysis passes on the crate.
883 tcx: TyCtxt<'_, 'tcx, 'tcx>,
886 assert_eq!(cnum, LOCAL_CRATE);
889 let mut entry_point = None;
891 time(sess, "misc checking 1", || {
893 entry_point = time(sess, "looking for entry point", || {
894 middle::entry::find_entry_point(tcx)
897 time(sess, "looking for plugin registrar", || {
898 plugin::build::find_plugin_registrar(tcx)
901 time(sess, "looking for derive registrar", || {
902 proc_macro_decls::find(tcx)
905 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
906 tcx.ensure().check_mod_loops(tcx.hir().local_def_id(module));
907 tcx.ensure().check_mod_attrs(tcx.hir().local_def_id(module));
908 tcx.ensure().check_mod_unstable_api_usage(tcx.hir().local_def_id(module));
913 // passes are timed inside typeck
914 typeck::check_crate(tcx)?;
916 time(sess, "misc checking 2", || {
918 time(sess, "rvalue promotion + match checking", || {
919 tcx.par_body_owners(|def_id| {
920 tcx.ensure().const_is_rvalue_promotable_to_static(def_id);
921 tcx.ensure().check_match(def_id);
925 time(sess, "liveness checking + intrinsic checking", || {
926 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
927 // this must run before MIR dump, because
928 // "not all control paths return a value" is reported here.
930 // maybe move the check to a MIR pass?
931 tcx.ensure().check_mod_liveness(tcx.hir().local_def_id(module));
933 tcx.ensure().check_mod_intrinsics(tcx.hir().local_def_id(module));
939 time(sess, "borrow checking", || {
940 if tcx.use_ast_borrowck() {
941 borrowck::check_crate(tcx);
945 time(sess, "MIR borrow checking", || {
946 tcx.par_body_owners(|def_id| tcx.ensure().mir_borrowck(def_id));
949 time(sess, "dumping chalk-like clauses", || {
950 rustc_traits::lowering::dump_program_clauses(tcx);
953 time(sess, "MIR effect checking", || {
954 for def_id in tcx.body_owners() {
955 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
959 time(sess, "layout testing", || layout_test::test_layout(tcx));
961 // Avoid overwhelming user with errors if borrow checking failed.
962 // I'm not sure how helpful this is, to be honest, but it avoids a
963 // lot of annoying errors in the compile-fail tests (basically,
964 // lint warnings and so on -- kindck used to do this abort, but
965 // kindck is gone now). -nmatsakis
966 if sess.err_count() > 0 {
967 return Err(ErrorReported);
970 time(sess, "misc checking 3", || {
972 time(sess, "privacy access levels", || {
973 tcx.ensure().privacy_access_levels(LOCAL_CRATE);
976 time(sess, "private in public", || {
977 tcx.ensure().check_private_in_public(LOCAL_CRATE);
980 time(sess, "death checking", || middle::dead::check_crate(tcx));
982 time(sess, "unused lib feature checking", || {
983 stability::check_unused_or_stable_features(tcx)
986 time(sess, "lint checking", || {
987 lint::check_crate(tcx, || rustc_lint::BuiltinCombinedLateLintPass::new());
991 time(sess, "privacy checking modules", || {
992 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
993 tcx.ensure().check_mod_privacy(tcx.hir().local_def_id(module));
1002 fn encode_metadata<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> (middle::cstore::EncodedMetadata, bool) {
1003 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1010 let metadata_kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
1012 CrateType::Executable |
1013 CrateType::Staticlib |
1014 CrateType::Cdylib => MetadataKind::None,
1016 CrateType::Rlib => MetadataKind::Uncompressed,
1019 CrateType::ProcMacro => MetadataKind::Compressed,
1021 }).max().unwrap_or(MetadataKind::None);
1023 let need_metadata_module = metadata_kind == MetadataKind::Compressed;
1025 let metadata = match metadata_kind {
1026 MetadataKind::None => middle::cstore::EncodedMetadata::new(),
1027 MetadataKind::Uncompressed |
1028 MetadataKind::Compressed => tcx.encode_metadata(),
1031 (metadata, need_metadata_module)
1034 /// Runs the codegen backend, after which the AST and analysis can
1036 pub fn start_codegen<'tcx>(
1037 codegen_backend: &dyn CodegenBackend,
1038 tcx: TyCtxt<'_, 'tcx, 'tcx>,
1039 rx: mpsc::Receiver<Box<dyn Any + Send>>,
1040 outputs: &OutputFilenames,
1042 if log_enabled!(::log::Level::Info) {
1043 println!("Pre-codegen");
1044 tcx.print_debug_stats();
1047 time(tcx.sess, "resolving dependency formats", || {
1048 middle::dependency_format::calculate(tcx)
1051 let (metadata, need_metadata_module) = time(tcx.sess, "metadata encoding", || {
1052 encode_metadata(tcx)
1055 tcx.sess.profiler(|p| p.start_activity("codegen crate"));
1056 let codegen = time(tcx.sess, "codegen", move || {
1057 codegen_backend.codegen_crate(tcx, metadata, need_metadata_module, rx)
1059 tcx.sess.profiler(|p| p.end_activity("codegen crate"));
1061 if log_enabled!(::log::Level::Info) {
1062 println!("Post-codegen");
1063 tcx.print_debug_stats();
1066 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
1067 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, outputs) {
1068 tcx.sess.err(&format!("could not emit MIR: {}", e));
1069 tcx.sess.abort_if_errors();