1 use crate::interface::{Compiler, Result};
2 use crate::proc_macro_decls;
5 use rustc_ast::mut_visit::MutVisitor;
6 use rustc_ast::{self as ast, visit};
7 use rustc_codegen_ssa::back::link::emit_metadata;
8 use rustc_codegen_ssa::traits::CodegenBackend;
9 use rustc_data_structures::parallel;
10 use rustc_data_structures::steal::Steal;
11 use rustc_data_structures::sync::{par_iter, Lrc, OnceCell, ParallelIterator, WorkerLocal};
12 use rustc_data_structures::temp_dir::MaybeTempDir;
13 use rustc_errors::{ErrorReported, PResult};
14 use rustc_expand::base::ExtCtxt;
15 use rustc_hir::def_id::LOCAL_CRATE;
17 use rustc_lint::LintStore;
18 use rustc_metadata::creader::CStore;
19 use rustc_middle::arena::Arena;
20 use rustc_middle::dep_graph::DepGraph;
21 use rustc_middle::middle;
22 use rustc_middle::middle::cstore::{CrateStore, MetadataLoader, MetadataLoaderDyn};
23 use rustc_middle::ty::query::Providers;
24 use rustc_middle::ty::{self, GlobalCtxt, ResolverOutputs, TyCtxt};
26 use rustc_mir_build as mir_build;
27 use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str};
28 use rustc_passes::{self, hir_stats, layout_test};
29 use rustc_plugin_impl as plugin;
30 use rustc_query_impl::Queries as TcxQueries;
31 use rustc_resolve::{Resolver, ResolverArenas};
32 use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType, PpMode, PpSourceMode};
33 use rustc_session::lint;
34 use rustc_session::output::{filename_for_input, filename_for_metadata};
35 use rustc_session::search_paths::PathKind;
36 use rustc_session::Session;
37 use rustc_span::symbol::{Ident, Symbol};
38 use rustc_trait_selection::traits;
39 use rustc_typeck as typeck;
40 use tracing::{info, warn};
42 use rustc_serialize::json;
43 use tempfile::Builder as TempFileBuilder;
46 use std::cell::RefCell;
47 use std::ffi::OsString;
48 use std::io::{self, BufWriter, Write};
49 use std::lazy::SyncLazy;
50 use std::marker::PhantomData;
51 use std::ops::{Generator, GeneratorState};
52 use std::path::PathBuf;
55 use std::{env, fs, iter};
57 pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
58 let krate = sess.time("parse_crate", || match input {
59 Input::File(file) => parse_crate_from_file(file, &sess.parse_sess),
60 Input::Str { input, name } => {
61 parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
65 if sess.opts.debugging_opts.ast_json_noexpand {
66 println!("{}", json::as_json(&krate));
69 if sess.opts.debugging_opts.input_stats {
70 eprintln!("Lines of code: {}", sess.source_map().count_lines());
71 eprintln!("Pre-expansion node count: {}", count_nodes(&krate));
74 if let Some(ref s) = sess.opts.debugging_opts.show_span {
75 rustc_ast_passes::show_span::run(sess.diagnostic(), s, &krate);
78 if sess.opts.debugging_opts.hir_stats {
79 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
85 fn count_nodes(krate: &ast::Crate) -> usize {
86 let mut counter = rustc_ast_passes::node_count::NodeCounter::new();
87 visit::walk_crate(&mut counter, krate);
91 #[derive(Copy, Clone)]
92 pub struct AccessAction(*mut dyn FnMut());
95 pub fn get(self) -> *mut dyn FnMut() {
100 #[derive(Copy, Clone)]
103 Access(AccessAction),
107 pub struct PinnedGenerator<I, A, R> {
108 generator: Pin<Box<dyn Generator<Action, Yield = YieldType<I, A>, Return = R>>>,
111 impl<I, A, R> PinnedGenerator<I, A, R> {
112 pub fn new<T: Generator<Action, Yield = YieldType<I, A>, Return = R> + 'static>(
115 let mut result = PinnedGenerator { generator: Box::pin(generator) };
117 // Run it to the first yield to set it up
118 let init = match Pin::new(&mut result.generator).resume(Action::Initial) {
119 GeneratorState::Yielded(YieldType::Initial(y)) => y,
126 pub unsafe fn access(&mut self, closure: *mut dyn FnMut()) {
127 // Call the generator, which in turn will call the closure
128 if let GeneratorState::Complete(_) =
129 Pin::new(&mut self.generator).resume(Action::Access(AccessAction(closure)))
135 pub fn complete(&mut self) -> R {
136 // Tell the generator we want it to complete, consuming it and yielding a result
137 let result = Pin::new(&mut self.generator).resume(Action::Complete);
138 if let GeneratorState::Complete(r) = result { r } else { panic!() }
143 pub struct Marker<T>(PhantomData<T>);
146 pub unsafe fn new() -> Self {
151 pub enum YieldType<I, A> {
156 pub struct BoxedResolver(
157 PinnedGenerator<Result<ast::Crate>, fn(&mut Resolver<'_>), ResolverOutputs>,
161 fn new<T>(generator: T) -> (Result<ast::Crate>, Self)
163 T: ::std::ops::Generator<
165 Yield = YieldType<Result<ast::Crate>, fn(&mut Resolver<'_>)>,
166 Return = ResolverOutputs,
169 let (initial, pinned) = PinnedGenerator::new(generator);
170 (initial, BoxedResolver(pinned))
173 pub fn access<F: FnOnce(&mut Resolver<'_>) -> R, R>(&mut self, f: F) -> R {
174 // Turn the FnOnce closure into *mut dyn FnMut()
175 // so we can pass it in to the generator
178 let mut_f: &mut dyn FnMut(&mut Resolver<'_>) = &mut |resolver| {
179 let f = f.take().unwrap();
180 r = Some(f(resolver));
182 let mut_f = mut_f as *mut dyn FnMut(&mut Resolver<'_>);
184 // Get the generator to call our closure
186 self.0.access(::std::mem::transmute(mut_f));
193 pub fn complete(mut self) -> ResolverOutputs {
198 value: Result<ast::Crate>,
199 ) -> YieldType<Result<ast::Crate>, fn(&mut Resolver<'_>)> {
200 YieldType::Initial(value)
204 /// Runs the "early phases" of the compiler: initial `cfg` processing, loading compiler plugins,
205 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
206 /// harness if one is to be provided, injection of a dependency on the
207 /// standard library and prelude, and name resolution.
209 /// Returns [`None`] if we're aborting after handling -W help.
210 pub fn configure_and_expand(
212 lint_store: Lrc<LintStore>,
213 metadata_loader: Box<MetadataLoaderDyn>,
216 ) -> Result<(ast::Crate, BoxedResolver)> {
217 tracing::trace!("configure_and_expand");
218 // Currently, we ignore the name resolution data structures for the purposes of dependency
219 // tracking. Instead we will run name resolution and include its output in the hash of each
220 // item, much like we do for macro expansion. In other words, the hash reflects not just
221 // its contents but the results of name resolution on those contents. Hopefully we'll push
222 // this back at some point.
223 let crate_name = crate_name.to_string();
224 let (result, resolver) = BoxedResolver::new(static move |mut action| {
227 let resolver_arenas = Resolver::arenas();
228 let res = configure_and_expand_inner(
236 let mut resolver = match res {
238 yield BoxedResolver::initial_yield(Err(v));
241 Ok((krate, resolver)) => {
242 action = yield BoxedResolver::initial_yield(Ok(krate));
249 Action::Access(accessor) => {
250 let accessor: &mut dyn FnMut(&mut Resolver<'_>) =
251 unsafe { ::std::mem::transmute(accessor.get()) };
252 (*accessor)(&mut resolver);
254 let marker = Marker::<fn(&mut Resolver<'_>)>::new();
255 action = yield YieldType::Accessor(marker);
258 Action::Complete => break,
260 panic!("unexpected box_region action: Initial")
265 resolver.into_outputs()
267 result.map(|k| (k, resolver))
271 pub fn to_resolver_outputs(resolver: Rc<RefCell<BoxedResolver>>) -> ResolverOutputs {
272 match Rc::try_unwrap(resolver) {
273 Ok(resolver) => resolver.into_inner().complete(),
274 Err(resolver) => resolver.borrow_mut().access(|resolver| resolver.clone_outputs()),
279 pub fn register_plugins<'a>(
281 metadata_loader: &'a dyn MetadataLoader,
282 register_lints: impl Fn(&Session, &mut LintStore),
283 mut krate: ast::Crate,
285 ) -> Result<(ast::Crate, Lrc<LintStore>)> {
286 krate = sess.time("attributes_injection", || {
287 rustc_builtin_macros::cmdline_attrs::inject(
290 &sess.opts.debugging_opts.crate_attr,
294 let (krate, features) = rustc_expand::config::features(sess, krate);
295 // these need to be set "early" so that expansion sees `quote` if enabled.
296 sess.init_features(features);
298 let crate_types = util::collect_crate_types(sess, &krate.attrs);
299 sess.init_crate_types(crate_types);
301 let disambiguator = util::compute_crate_disambiguator(sess);
302 sess.crate_disambiguator.set(disambiguator).expect("not yet initialized");
303 rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator)?;
305 if sess.opts.incremental.is_some() {
306 sess.time("incr_comp_garbage_collect_session_directories", || {
307 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
309 "Error while trying to garbage collect incremental \
310 compilation cache directory: {}",
317 sess.time("recursion_limit", || {
318 middle::limits::update_limits(sess, &krate);
321 let mut lint_store = rustc_lint::new_lint_store(
322 sess.opts.debugging_opts.no_interleave_lints,
323 sess.unstable_options(),
325 register_lints(&sess, &mut lint_store);
328 sess.time("plugin_loading", || plugin::load::load_plugins(sess, metadata_loader, &krate));
329 sess.time("plugin_registration", || {
330 let mut registry = plugin::Registry { lint_store: &mut lint_store };
331 for registrar in registrars {
332 registrar(&mut registry);
336 let lint_store = Lrc::new(lint_store);
337 sess.init_lint_store(lint_store.clone());
339 Ok((krate, lint_store))
342 fn pre_expansion_lint(
344 lint_store: &LintStore,
348 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", crate_name).run(|| {
349 rustc_lint::check_ast_crate(
355 rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
360 fn configure_and_expand_inner<'a>(
362 lint_store: &'a LintStore,
363 mut krate: ast::Crate,
365 resolver_arenas: &'a ResolverArenas<'a>,
366 metadata_loader: &'a MetadataLoaderDyn,
367 ) -> Result<(ast::Crate, Resolver<'a>)> {
368 tracing::trace!("configure_and_expand_inner");
369 pre_expansion_lint(sess, lint_store, &krate, crate_name);
371 let mut resolver = Resolver::new(sess, &krate, crate_name, metadata_loader, &resolver_arenas);
372 rustc_builtin_macros::register_builtin_macros(&mut resolver);
374 krate = sess.time("crate_injection", || {
375 let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| Symbol::intern(s));
376 rustc_builtin_macros::standard_library_imports::inject(
384 util::check_attr_crate_type(&sess, &krate.attrs, &mut resolver.lint_buffer());
387 krate = sess.time("macro_expand_crate", || {
388 // Windows dlls do not have rpaths, so they don't know how to find their
389 // dependencies. It's up to us to tell the system where to find all the
390 // dependent dlls. Note that this uses cfg!(windows) as opposed to
391 // targ_cfg because syntax extensions are always loaded for the host
392 // compiler, not for the target.
394 // This is somewhat of an inherently racy operation, however, as
395 // multiple threads calling this function could possibly continue
396 // extending PATH far beyond what it should. To solve this for now we
397 // just don't add any new elements to PATH which are already there
398 // within PATH. This is basically a targeted fix at #17360 for rustdoc
399 // which runs rustc in parallel but has been seen (#33844) to cause
400 // problems with PATH becoming too long.
401 let mut old_path = OsString::new();
403 old_path = env::var_os("PATH").unwrap_or(old_path);
404 let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
405 for path in env::split_paths(&old_path) {
406 if !new_path.contains(&path) {
413 new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
419 // Create the config for macro expansion
420 let features = sess.features_untracked();
421 let cfg = rustc_expand::expand::ExpansionConfig {
422 features: Some(&features),
423 recursion_limit: sess.recursion_limit(),
424 trace_mac: sess.opts.debugging_opts.trace_macros,
425 should_test: sess.opts.test,
426 span_debug: sess.opts.debugging_opts.span_debug,
427 proc_macro_backtrace: sess.opts.debugging_opts.proc_macro_backtrace,
428 ..rustc_expand::expand::ExpansionConfig::default(crate_name.to_string())
431 let extern_mod_loaded = |ident: Ident, attrs, items, span| {
432 let krate = ast::Crate { attrs, items, span, proc_macros: vec![] };
433 pre_expansion_lint(sess, lint_store, &krate, &ident.name.as_str());
434 (krate.attrs, krate.items)
436 let mut ecx = ExtCtxt::new(&sess, cfg, &mut resolver, Some(&extern_mod_loaded));
438 // Expand macros now!
439 let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
441 // The rest is error reporting
443 sess.time("check_unused_macros", || {
444 ecx.check_unused_macros();
447 let mut missing_fragment_specifiers: Vec<_> = ecx
450 .missing_fragment_specifiers
453 .map(|(span, node_id)| (*span, *node_id))
455 missing_fragment_specifiers.sort_unstable_by_key(|(span, _)| *span);
457 let recursion_limit_hit = ecx.reduced_recursion_limit.is_some();
459 for (span, node_id) in missing_fragment_specifiers {
460 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
461 let msg = "missing fragment specifier";
462 resolver.lint_buffer().buffer_lint(lint, node_id, span, msg);
465 env::set_var("PATH", &old_path);
468 if recursion_limit_hit {
469 // If we hit a recursion limit, exit early to avoid later passes getting overwhelmed
477 sess.time("maybe_building_test_harness", || {
478 rustc_builtin_macros::test_harness::inject(&sess, &mut resolver, &mut krate)
481 if let Some(PpMode::Source(PpSourceMode::EveryBodyLoops)) = sess.opts.pretty {
482 tracing::debug!("replacing bodies with loop {{}}");
483 util::ReplaceBodyWithLoop::new(&mut resolver).visit_crate(&mut krate);
486 let has_proc_macro_decls = sess.time("AST_validation", || {
487 rustc_ast_passes::ast_validation::check_crate(sess, &krate, &mut resolver.lint_buffer())
490 let crate_types = sess.crate_types();
491 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
493 // For backwards compatibility, we don't try to run proc macro injection
494 // if rustdoc is run on a proc macro crate without '--crate-type proc-macro' being
495 // specified. This should only affect users who manually invoke 'rustdoc', as
496 // 'cargo doc' will automatically pass the proper '--crate-type' flags.
497 // However, we do emit a warning, to let such users know that they should
498 // start passing '--crate-type proc-macro'
499 if has_proc_macro_decls && sess.opts.actually_rustdoc && !is_proc_macro_crate {
500 let mut msg = sess.diagnostic().struct_warn(
501 &"Trying to document proc macro crate \
502 without passing '--crate-type proc-macro to rustdoc",
505 msg.warn("The generated documentation may be incorrect");
508 krate = sess.time("maybe_create_a_macro_crate", || {
509 let num_crate_types = crate_types.len();
510 let is_test_crate = sess.opts.test;
511 rustc_builtin_macros::proc_macro_harness::inject(
516 has_proc_macro_decls,
524 // Done with macro expansion!
526 if sess.opts.debugging_opts.input_stats {
527 eprintln!("Post-expansion node count: {}", count_nodes(&krate));
530 if sess.opts.debugging_opts.hir_stats {
531 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
534 if sess.opts.debugging_opts.ast_json {
535 println!("{}", json::as_json(&krate));
538 resolver.resolve_crate(&krate);
540 // Needs to go *after* expansion to be able to check the results of macro expansion.
541 sess.time("complete_gated_feature_checking", || {
542 rustc_ast_passes::feature_gate::check_crate(&krate, sess);
545 // Add all buffered lints from the `ParseSess` to the `Session`.
546 sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
547 info!("{} parse sess buffered_lints", buffered_lints.len());
548 for early_lint in buffered_lints.drain(..) {
549 resolver.lint_buffer().add_early_lint(early_lint);
553 Ok((krate, resolver))
556 pub fn lower_to_hir<'res, 'tcx>(
558 lint_store: &LintStore,
559 resolver: &'res mut Resolver<'_>,
560 dep_graph: &'res DepGraph,
561 krate: &'res ast::Crate,
562 arena: &'tcx rustc_ast_lowering::Arena<'tcx>,
564 // We're constructing the HIR here; we don't care what we will
565 // read, since we haven't even constructed the *input* to
567 dep_graph.assert_ignored();
570 let hir_crate = rustc_ast_lowering::lower_crate(
574 rustc_parse::nt_to_tokenstream,
578 if sess.opts.debugging_opts.hir_stats {
579 hir_stats::print_hir_stats(&hir_crate);
582 sess.time("early_lint_checks", || {
583 rustc_lint::check_ast_crate(
588 Some(std::mem::take(resolver.lint_buffer())),
589 rustc_lint::BuiltinCombinedEarlyLintPass::new(),
593 // Discard hygiene data, which isn't required after lowering to HIR.
594 if !sess.opts.debugging_opts.keep_hygiene_data {
595 rustc_span::hygiene::clear_syntax_context_map();
601 // Returns all the paths that correspond to generated files.
602 fn generated_output_paths(
604 outputs: &OutputFilenames,
608 let mut out_filenames = Vec::new();
609 for output_type in sess.opts.output_types.keys() {
610 let file = outputs.path(*output_type);
612 // If the filename has been overridden using `-o`, it will not be modified
613 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
614 OutputType::Exe if !exact_name => {
615 for crate_type in sess.crate_types().iter() {
616 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
617 out_filenames.push(p);
620 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
621 // Don't add the dep-info output when omitting it from dep-info targets
624 out_filenames.push(file);
631 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
632 // returns None for every file path.
633 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
635 F: Fn(&PathBuf) -> Option<T>,
637 for output_path in output_paths {
638 if let Some(result) = f(output_path) {
645 fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
646 let input_path = input_path.canonicalize().ok();
647 if input_path.is_none() {
650 let check = |output_path: &PathBuf| {
651 if output_path.canonicalize().ok() == input_path { Some(()) } else { None }
653 check_output(output_paths, check).is_some()
656 fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
657 let check = |output_path: &PathBuf| output_path.is_dir().then(|| output_path.clone());
658 check_output(output_paths, check)
661 fn escape_dep_filename(filename: &String) -> String {
662 // Apparently clang and gcc *only* escape spaces:
663 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
664 filename.replace(" ", "\\ ")
667 // Makefile comments only need escaping newlines and `\`.
668 // The result can be unescaped by anything that can unescape `escape_default` and friends.
669 fn escape_dep_env(symbol: Symbol) -> String {
670 let s = symbol.as_str();
671 let mut escaped = String::with_capacity(s.len());
674 '\n' => escaped.push_str(r"\n"),
675 '\r' => escaped.push_str(r"\r"),
676 '\\' => escaped.push_str(r"\\"),
677 _ => escaped.push(c),
685 boxed_resolver: &Steal<Rc<RefCell<BoxedResolver>>>,
686 outputs: &OutputFilenames,
687 out_filenames: &[PathBuf],
689 // Write out dependency rules to the dep-info file if requested
690 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
693 let deps_filename = outputs.path(OutputType::DepInfo);
695 let result = (|| -> io::Result<()> {
696 // Build a list of files used to compile the output and
697 // write Makefile-compatible dependency rules
698 let mut files: Vec<String> = sess
702 .filter(|fmap| fmap.is_real_file())
703 .filter(|fmap| !fmap.is_imported())
704 .map(|fmap| escape_dep_filename(&fmap.name.prefer_local().to_string()))
707 if let Some(ref backend) = sess.opts.debugging_opts.codegen_backend {
708 files.push(backend.to_string());
711 if sess.binary_dep_depinfo() {
712 boxed_resolver.borrow().borrow_mut().access(|resolver| {
713 for cnum in resolver.cstore().crates_untracked() {
714 let source = resolver.cstore().crate_source_untracked(cnum);
715 if let Some((path, _)) = source.dylib {
716 files.push(escape_dep_filename(&path.display().to_string()));
718 if let Some((path, _)) = source.rlib {
719 files.push(escape_dep_filename(&path.display().to_string()));
721 if let Some((path, _)) = source.rmeta {
722 files.push(escape_dep_filename(&path.display().to_string()));
728 let mut file = BufWriter::new(fs::File::create(&deps_filename)?);
729 for path in out_filenames {
730 writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
733 // Emit a fake target for each input file to the compilation. This
734 // prevents `make` from spitting out an error if a file is later
735 // deleted. For more info see #28735
737 writeln!(file, "{}:", path)?;
740 // Emit special comments with information about accessed environment variables.
741 let env_depinfo = sess.parse_sess.env_depinfo.borrow();
742 if !env_depinfo.is_empty() {
743 let mut envs: Vec<_> = env_depinfo
745 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
747 envs.sort_unstable();
750 write!(file, "# env-dep:{}", k)?;
752 write!(file, "={}", v)?;
763 if sess.opts.json_artifact_notifications {
766 .emit_artifact_notification(&deps_filename, "dep-info");
769 Err(e) => sess.fatal(&format!(
770 "error writing dependencies to `{}`: {}",
771 deps_filename.display(),
777 pub fn prepare_outputs(
781 boxed_resolver: &Steal<Rc<RefCell<BoxedResolver>>>,
783 ) -> Result<OutputFilenames> {
784 let _timer = sess.timer("prepare_outputs");
786 // FIXME: rustdoc passes &[] instead of &krate.attrs here
787 let outputs = util::build_output_filenames(
789 &compiler.output_dir,
790 &compiler.output_file,
796 generated_output_paths(sess, &outputs, compiler.output_file.is_some(), &crate_name);
798 // Ensure the source file isn't accidentally overwritten during compilation.
799 if let Some(ref input_path) = compiler.input_path {
800 if sess.opts.will_create_output_file() {
801 if output_contains_path(&output_paths, input_path) {
803 "the input file \"{}\" would be overwritten by the generated \
807 return Err(ErrorReported);
809 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
811 "the generated executable for the input file \"{}\" conflicts with the \
812 existing directory \"{}\"",
813 input_path.display(),
816 return Err(ErrorReported);
821 write_out_deps(sess, boxed_resolver, &outputs, &output_paths);
823 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
824 && sess.opts.output_types.len() == 1;
827 if let Some(ref dir) = compiler.output_dir {
828 if fs::create_dir_all(dir).is_err() {
829 sess.err("failed to find or create the directory specified by `--out-dir`");
830 return Err(ErrorReported);
838 pub static DEFAULT_QUERY_PROVIDERS: SyncLazy<Providers> = SyncLazy::new(|| {
839 let providers = &mut Providers::default();
840 providers.analysis = analysis;
841 proc_macro_decls::provide(providers);
842 plugin::build::provide(providers);
843 rustc_middle::hir::provide(providers);
844 mir::provide(providers);
845 mir_build::provide(providers);
846 rustc_privacy::provide(providers);
847 typeck::provide(providers);
848 ty::provide(providers);
849 traits::provide(providers);
850 rustc_passes::provide(providers);
851 rustc_resolve::provide(providers);
852 rustc_traits::provide(providers);
853 rustc_ty_utils::provide(providers);
854 rustc_metadata::provide(providers);
855 rustc_lint::provide(providers);
856 rustc_symbol_mangling::provide(providers);
857 rustc_codegen_ssa::provide(providers);
861 pub static DEFAULT_EXTERN_QUERY_PROVIDERS: SyncLazy<Providers> = SyncLazy::new(|| {
862 let mut extern_providers = *DEFAULT_QUERY_PROVIDERS;
863 rustc_metadata::provide_extern(&mut extern_providers);
864 rustc_codegen_ssa::provide_extern(&mut extern_providers);
868 pub struct QueryContext<'tcx> {
869 gcx: &'tcx GlobalCtxt<'tcx>,
872 impl<'tcx> QueryContext<'tcx> {
873 pub fn enter<F, R>(&mut self, f: F) -> R
875 F: FnOnce(TyCtxt<'tcx>) -> R,
877 let icx = ty::tls::ImplicitCtxt::new(self.gcx);
878 ty::tls::enter_context(&icx, |_| f(icx.tcx))
882 pub fn create_global_ctxt<'tcx>(
883 compiler: &'tcx Compiler,
884 lint_store: Lrc<LintStore>,
885 krate: &'tcx Crate<'tcx>,
887 resolver_outputs: ResolverOutputs,
888 outputs: OutputFilenames,
890 queries: &'tcx OnceCell<TcxQueries<'tcx>>,
891 global_ctxt: &'tcx OnceCell<GlobalCtxt<'tcx>>,
892 arena: &'tcx WorkerLocal<Arena<'tcx>>,
893 ) -> QueryContext<'tcx> {
894 let sess = &compiler.session();
896 let def_path_table = resolver_outputs.definitions.def_path_table();
897 let query_result_on_disk_cache =
898 rustc_incremental::load_query_result_cache(sess, def_path_table);
900 let codegen_backend = compiler.codegen_backend();
901 let mut local_providers = *DEFAULT_QUERY_PROVIDERS;
902 codegen_backend.provide(&mut local_providers);
904 let mut extern_providers = *DEFAULT_EXTERN_QUERY_PROVIDERS;
905 codegen_backend.provide(&mut extern_providers);
906 codegen_backend.provide_extern(&mut extern_providers);
908 if let Some(callback) = compiler.override_queries {
909 callback(sess, &mut local_providers, &mut extern_providers);
912 let queries = queries.get_or_init(|| TcxQueries::new(local_providers, extern_providers));
914 let gcx = sess.time("setup_global_ctxt", || {
915 global_ctxt.get_or_init(|| {
916 TyCtxt::create_global_ctxt(
923 query_result_on_disk_cache,
934 /// Runs the resolution, type-checking, region checking and other
935 /// miscellaneous analysis passes on the crate.
936 fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> {
937 rustc_passes::hir_id_validator::check_crate(tcx);
940 let mut entry_point = None;
942 sess.time("misc_checking_1", || {
945 entry_point = sess.time("looking_for_entry_point", || tcx.entry_fn(()));
947 sess.time("looking_for_plugin_registrar", || tcx.ensure().plugin_registrar_fn(()));
949 sess.time("looking_for_derive_registrar", || {
950 tcx.ensure().proc_macro_decls_static(())
955 .downcast_ref::<CStore>()
956 .expect("`tcx.cstore` is not a `CStore`");
957 cstore.report_unused_deps(tcx);
960 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
961 tcx.ensure().check_mod_loops(module);
962 tcx.ensure().check_mod_attrs(module);
963 tcx.ensure().check_mod_naked_functions(module);
964 tcx.ensure().check_mod_unstable_api_usage(module);
965 tcx.ensure().check_mod_const_bodies(module);
971 // passes are timed inside typeck
972 typeck::check_crate(tcx)?;
974 sess.time("misc_checking_2", || {
977 sess.time("match_checking", || {
978 tcx.par_body_owners(|def_id| {
979 tcx.ensure().check_match(def_id.to_def_id());
984 sess.time("liveness_and_intrinsic_checking", || {
985 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
986 // this must run before MIR dump, because
987 // "not all control paths return a value" is reported here.
989 // maybe move the check to a MIR pass?
990 tcx.ensure().check_mod_liveness(module);
991 tcx.ensure().check_mod_intrinsics(module);
998 sess.time("MIR_borrow_checking", || {
999 tcx.par_body_owners(|def_id| tcx.ensure().mir_borrowck(def_id));
1002 sess.time("MIR_effect_checking", || {
1003 for def_id in tcx.body_owners() {
1004 tcx.ensure().thir_check_unsafety(def_id);
1005 if !tcx.sess.opts.debugging_opts.thir_unsafeck {
1006 mir::transform::check_unsafety::check_unsafety(tcx, def_id);
1009 if tcx.hir().body_const_context(def_id).is_some() {
1011 .mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(def_id));
1016 sess.time("layout_testing", || layout_test::test_layout(tcx));
1018 // Avoid overwhelming user with errors if borrow checking failed.
1019 // I'm not sure how helpful this is, to be honest, but it avoids a
1020 // lot of annoying errors in the ui tests (basically,
1021 // lint warnings and so on -- kindck used to do this abort, but
1022 // kindck is gone now). -nmatsakis
1023 if sess.has_errors() {
1024 return Err(ErrorReported);
1027 sess.time("misc_checking_3", || {
1030 tcx.ensure().privacy_access_levels(());
1034 tcx.ensure().check_private_in_public(());
1037 sess.time("death_checking", || rustc_passes::dead::check_crate(tcx));
1040 sess.time("unused_lib_feature_checking", || {
1041 rustc_passes::stability::check_unused_or_stable_features(tcx)
1045 sess.time("lint_checking", || {
1046 rustc_lint::check_crate(tcx, || {
1047 rustc_lint::BuiltinCombinedLateLintPass::new()
1054 sess.time("privacy_checking_modules", || {
1055 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
1056 tcx.ensure().check_mod_privacy(module);
1066 fn encode_and_write_metadata(
1068 outputs: &OutputFilenames,
1069 ) -> (middle::cstore::EncodedMetadata, bool) {
1070 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1077 let metadata_kind = tcx
1081 .map(|ty| match *ty {
1082 CrateType::Executable | CrateType::Staticlib | CrateType::Cdylib => MetadataKind::None,
1084 CrateType::Rlib => MetadataKind::Uncompressed,
1086 CrateType::Dylib | CrateType::ProcMacro => MetadataKind::Compressed,
1089 .unwrap_or(MetadataKind::None);
1091 let metadata = match metadata_kind {
1092 MetadataKind::None => middle::cstore::EncodedMetadata::new(),
1093 MetadataKind::Uncompressed | MetadataKind::Compressed => tcx.encode_metadata(),
1096 let _prof_timer = tcx.sess.prof.generic_activity("write_crate_metadata");
1098 let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
1099 if need_metadata_file {
1100 let crate_name = &tcx.crate_name(LOCAL_CRATE).as_str();
1101 let out_filename = filename_for_metadata(tcx.sess, crate_name, outputs);
1102 // To avoid races with another rustc process scanning the output directory,
1103 // we need to write the file somewhere else and atomically move it to its
1104 // final destination, with an `fs::rename` call. In order for the rename to
1105 // always succeed, the temporary file needs to be on the same filesystem,
1106 // which is why we create it inside the output directory specifically.
1107 let metadata_tmpdir = TempFileBuilder::new()
1109 .tempdir_in(out_filename.parent().unwrap())
1110 .unwrap_or_else(|err| tcx.sess.fatal(&format!("couldn't create a temp dir: {}", err)));
1111 let metadata_tmpdir = MaybeTempDir::new(metadata_tmpdir, tcx.sess.opts.cg.save_temps);
1112 let metadata_filename = emit_metadata(tcx.sess, &metadata.raw_data, &metadata_tmpdir);
1113 if let Err(e) = util::non_durable_rename(&metadata_filename, &out_filename) {
1114 tcx.sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
1116 if tcx.sess.opts.json_artifact_notifications {
1120 .emit_artifact_notification(&out_filename, "metadata");
1124 let need_metadata_module = metadata_kind == MetadataKind::Compressed;
1126 (metadata, need_metadata_module)
1129 /// Runs the codegen backend, after which the AST and analysis can
1131 pub fn start_codegen<'tcx>(
1132 codegen_backend: &dyn CodegenBackend,
1134 outputs: &OutputFilenames,
1136 info!("Pre-codegen\n{:?}", tcx.debug_stats());
1138 let (metadata, need_metadata_module) = encode_and_write_metadata(tcx, outputs);
1140 let codegen = tcx.sess.time("codegen_crate", move || {
1141 codegen_backend.codegen_crate(tcx, metadata, need_metadata_module)
1144 // Don't run these test assertions when not doing codegen. Compiletest tries to build
1145 // build-fail tests in check mode first and expects it to not give an error in that case.
1146 if tcx.sess.opts.output_types.should_codegen() {
1147 rustc_incremental::assert_module_sources::assert_module_sources(tcx);
1148 rustc_symbol_mangling::test::report_symbol_names(tcx);
1151 info!("Post-codegen\n{:?}", tcx.debug_stats());
1153 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
1154 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, outputs) {
1155 tcx.sess.err(&format!("could not emit MIR: {}", e));
1156 tcx.sess.abort_if_errors();