]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/passes.rs
Remove `-Zno-interleave-lints`.
[rust.git] / compiler / rustc_interface / src / passes.rs
1 use crate::errors::{
2     CantEmitMIR, EmojiIdentifier, ErrorWritingDependencies, FerrisIdentifier,
3     GeneratedFileConflictsWithDirectory, InputFileWouldBeOverWritten, MixedBinCrate,
4     MixedProcMacroCrate, OutDirError, ProcMacroDocWithoutArg, TempsDirError,
5 };
6 use crate::interface::{Compiler, Result};
7 use crate::proc_macro_decls;
8 use crate::util;
9
10 use ast::CRATE_NODE_ID;
11 use rustc_ast::{self as ast, visit};
12 use rustc_borrowck as mir_borrowck;
13 use rustc_codegen_ssa::traits::CodegenBackend;
14 use rustc_data_structures::parallel;
15 use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal};
16 use rustc_errors::{ErrorGuaranteed, PResult};
17 use rustc_expand::base::{ExtCtxt, LintStoreExpand, ResolverExpand};
18 use rustc_hir::def_id::StableCrateId;
19 use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore};
20 use rustc_metadata::creader::CStore;
21 use rustc_middle::arena::Arena;
22 use rustc_middle::dep_graph::DepGraph;
23 use rustc_middle::ty::query::{ExternProviders, Providers};
24 use rustc_middle::ty::{self, GlobalCtxt, RegisteredTools, TyCtxt};
25 use rustc_mir_build as mir_build;
26 use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str, validate_attr};
27 use rustc_passes::{self, hir_stats, layout_test};
28 use rustc_plugin_impl as plugin;
29 use rustc_query_impl::{OnDiskCache, Queries as TcxQueries};
30 use rustc_resolve::{Resolver, ResolverArenas};
31 use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType};
32 use rustc_session::cstore::{MetadataLoader, MetadataLoaderDyn};
33 use rustc_session::output::filename_for_input;
34 use rustc_session::search_paths::PathKind;
35 use rustc_session::{Limit, Session};
36 use rustc_span::symbol::{sym, Symbol};
37 use rustc_span::FileName;
38 use rustc_trait_selection::traits;
39
40 use std::any::Any;
41 use std::cell::RefCell;
42 use std::ffi::OsString;
43 use std::io::{self, BufWriter, Write};
44 use std::marker::PhantomPinned;
45 use std::path::{Path, PathBuf};
46 use std::pin::Pin;
47 use std::rc::Rc;
48 use std::sync::LazyLock;
49 use std::{env, fs, iter};
50
51 pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
52     let krate = sess.time("parse_crate", || match input {
53         Input::File(file) => parse_crate_from_file(file, &sess.parse_sess),
54         Input::Str { input, name } => {
55             parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
56         }
57     })?;
58
59     if sess.opts.unstable_opts.input_stats {
60         eprintln!("Lines of code:             {}", sess.source_map().count_lines());
61         eprintln!("Pre-expansion node count:  {}", count_nodes(&krate));
62     }
63
64     if let Some(ref s) = sess.opts.unstable_opts.show_span {
65         rustc_ast_passes::show_span::run(sess.diagnostic(), s, &krate);
66     }
67
68     if sess.opts.unstable_opts.hir_stats {
69         hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS", "ast-stats-1");
70     }
71
72     Ok(krate)
73 }
74
75 fn count_nodes(krate: &ast::Crate) -> usize {
76     let mut counter = rustc_ast_passes::node_count::NodeCounter::new();
77     visit::walk_crate(&mut counter, krate);
78     counter.count
79 }
80
81 pub use boxed_resolver::BoxedResolver;
82 mod boxed_resolver {
83     use super::*;
84
85     pub struct BoxedResolver(Pin<Box<BoxedResolverInner>>);
86
87     struct BoxedResolverInner {
88         session: Lrc<Session>,
89         resolver_arenas: Option<ResolverArenas<'static>>,
90         resolver: Option<Resolver<'static>>,
91         _pin: PhantomPinned,
92     }
93
94     // Note: Drop order is important to prevent dangling references. Resolver must be dropped first,
95     // then resolver_arenas and session.
96     impl Drop for BoxedResolverInner {
97         fn drop(&mut self) {
98             self.resolver.take();
99             self.resolver_arenas.take();
100         }
101     }
102
103     impl BoxedResolver {
104         pub(super) fn new(
105             session: Lrc<Session>,
106             make_resolver: impl for<'a> FnOnce(&'a Session, &'a ResolverArenas<'a>) -> Resolver<'a>,
107         ) -> BoxedResolver {
108             let mut boxed_resolver = Box::new(BoxedResolverInner {
109                 session,
110                 resolver_arenas: Some(Resolver::arenas()),
111                 resolver: None,
112                 _pin: PhantomPinned,
113             });
114             // SAFETY: `make_resolver` takes a resolver arena with an arbitrary lifetime and
115             // returns a resolver with the same lifetime as the arena. We ensure that the arena
116             // outlives the resolver in the drop impl and elsewhere so these transmutes are sound.
117             unsafe {
118                 let resolver = make_resolver(
119                     std::mem::transmute::<&Session, &Session>(&boxed_resolver.session),
120                     std::mem::transmute::<&ResolverArenas<'_>, &ResolverArenas<'_>>(
121                         boxed_resolver.resolver_arenas.as_ref().unwrap(),
122                     ),
123                 );
124                 boxed_resolver.resolver = Some(resolver);
125                 BoxedResolver(Pin::new_unchecked(boxed_resolver))
126             }
127         }
128
129         pub fn access<F: for<'a> FnOnce(&mut Resolver<'a>) -> R, R>(&mut self, f: F) -> R {
130             // SAFETY: The resolver doesn't need to be pinned.
131             let mut resolver = unsafe {
132                 self.0.as_mut().map_unchecked_mut(|boxed_resolver| &mut boxed_resolver.resolver)
133             };
134             f((&mut *resolver).as_mut().unwrap())
135         }
136
137         pub fn to_resolver_outputs(resolver: Rc<RefCell<BoxedResolver>>) -> ty::ResolverOutputs {
138             match Rc::try_unwrap(resolver) {
139                 Ok(resolver) => {
140                     let mut resolver = resolver.into_inner();
141                     // SAFETY: The resolver doesn't need to be pinned.
142                     let mut resolver = unsafe {
143                         resolver
144                             .0
145                             .as_mut()
146                             .map_unchecked_mut(|boxed_resolver| &mut boxed_resolver.resolver)
147                     };
148                     resolver.take().unwrap().into_outputs()
149                 }
150                 Err(resolver) => resolver.borrow_mut().access(|resolver| resolver.clone_outputs()),
151             }
152         }
153     }
154 }
155
156 pub fn create_resolver(
157     sess: Lrc<Session>,
158     metadata_loader: Box<MetadataLoaderDyn>,
159     krate: &ast::Crate,
160     crate_name: &str,
161 ) -> BoxedResolver {
162     trace!("create_resolver");
163     BoxedResolver::new(sess, move |sess, resolver_arenas| {
164         Resolver::new(sess, krate, crate_name, metadata_loader, resolver_arenas)
165     })
166 }
167
168 pub fn register_plugins<'a>(
169     sess: &'a Session,
170     metadata_loader: &'a dyn MetadataLoader,
171     register_lints: impl Fn(&Session, &mut LintStore),
172     mut krate: ast::Crate,
173     crate_name: &str,
174 ) -> Result<(ast::Crate, LintStore)> {
175     krate = sess.time("attributes_injection", || {
176         rustc_builtin_macros::cmdline_attrs::inject(
177             krate,
178             &sess.parse_sess,
179             &sess.opts.unstable_opts.crate_attr,
180         )
181     });
182
183     let (krate, features) = rustc_expand::config::features(sess, krate, CRATE_NODE_ID);
184     // these need to be set "early" so that expansion sees `quote` if enabled.
185     sess.init_features(features);
186
187     let crate_types = util::collect_crate_types(sess, &krate.attrs);
188     sess.init_crate_types(crate_types);
189
190     let stable_crate_id = StableCrateId::new(
191         crate_name,
192         sess.crate_types().contains(&CrateType::Executable),
193         sess.opts.cg.metadata.clone(),
194     );
195     sess.stable_crate_id.set(stable_crate_id).expect("not yet initialized");
196     rustc_incremental::prepare_session_directory(sess, crate_name, stable_crate_id)?;
197
198     if sess.opts.incremental.is_some() {
199         sess.time("incr_comp_garbage_collect_session_directories", || {
200             if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
201                 warn!(
202                     "Error while trying to garbage collect incremental \
203                      compilation cache directory: {}",
204                     e
205                 );
206             }
207         });
208     }
209
210     let mut lint_store = rustc_lint::new_lint_store(sess.enable_internal_lints());
211     register_lints(sess, &mut lint_store);
212
213     let registrars =
214         sess.time("plugin_loading", || plugin::load::load_plugins(sess, metadata_loader, &krate));
215     sess.time("plugin_registration", || {
216         let mut registry = plugin::Registry { lint_store: &mut lint_store };
217         for registrar in registrars {
218             registrar(&mut registry);
219         }
220     });
221
222     Ok((krate, lint_store))
223 }
224
225 fn pre_expansion_lint<'a>(
226     sess: &Session,
227     lint_store: &LintStore,
228     registered_tools: &RegisteredTools,
229     check_node: impl EarlyCheckNode<'a>,
230     node_name: &str,
231 ) {
232     sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name).run(|| {
233         rustc_lint::check_ast_node(
234             sess,
235             true,
236             lint_store,
237             registered_tools,
238             None,
239             rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
240             check_node,
241         );
242     });
243 }
244
245 // Cannot implement directly for `LintStore` due to trait coherence.
246 struct LintStoreExpandImpl<'a>(&'a LintStore);
247
248 impl LintStoreExpand for LintStoreExpandImpl<'_> {
249     fn pre_expansion_lint(
250         &self,
251         sess: &Session,
252         registered_tools: &RegisteredTools,
253         node_id: ast::NodeId,
254         attrs: &[ast::Attribute],
255         items: &[rustc_ast::ptr::P<ast::Item>],
256         name: &str,
257     ) {
258         pre_expansion_lint(sess, self.0, registered_tools, (node_id, attrs, items), name);
259     }
260 }
261
262 /// Runs the "early phases" of the compiler: initial `cfg` processing, loading compiler plugins,
263 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
264 /// harness if one is to be provided, injection of a dependency on the
265 /// standard library and prelude, and name resolution.
266 pub fn configure_and_expand(
267     sess: &Session,
268     lint_store: &LintStore,
269     mut krate: ast::Crate,
270     crate_name: &str,
271     resolver: &mut Resolver<'_>,
272 ) -> Result<ast::Crate> {
273     trace!("configure_and_expand");
274     pre_expansion_lint(sess, lint_store, resolver.registered_tools(), &krate, crate_name);
275     rustc_builtin_macros::register_builtin_macros(resolver);
276
277     krate = sess.time("crate_injection", || {
278         rustc_builtin_macros::standard_library_imports::inject(krate, resolver, sess)
279     });
280
281     util::check_attr_crate_type(sess, &krate.attrs, &mut resolver.lint_buffer());
282
283     // Expand all macros
284     krate = sess.time("macro_expand_crate", || {
285         // Windows dlls do not have rpaths, so they don't know how to find their
286         // dependencies. It's up to us to tell the system where to find all the
287         // dependent dlls. Note that this uses cfg!(windows) as opposed to
288         // targ_cfg because syntax extensions are always loaded for the host
289         // compiler, not for the target.
290         //
291         // This is somewhat of an inherently racy operation, however, as
292         // multiple threads calling this function could possibly continue
293         // extending PATH far beyond what it should. To solve this for now we
294         // just don't add any new elements to PATH which are already there
295         // within PATH. This is basically a targeted fix at #17360 for rustdoc
296         // which runs rustc in parallel but has been seen (#33844) to cause
297         // problems with PATH becoming too long.
298         let mut old_path = OsString::new();
299         if cfg!(windows) {
300             old_path = env::var_os("PATH").unwrap_or(old_path);
301             let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
302             for path in env::split_paths(&old_path) {
303                 if !new_path.contains(&path) {
304                     new_path.push(path);
305                 }
306             }
307             env::set_var(
308                 "PATH",
309                 &env::join_paths(
310                     new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
311                 )
312                 .unwrap(),
313             );
314         }
315
316         // Create the config for macro expansion
317         let features = sess.features_untracked();
318         let recursion_limit = get_recursion_limit(&krate.attrs, sess);
319         let cfg = rustc_expand::expand::ExpansionConfig {
320             features: Some(features),
321             recursion_limit,
322             trace_mac: sess.opts.unstable_opts.trace_macros,
323             should_test: sess.opts.test,
324             span_debug: sess.opts.unstable_opts.span_debug,
325             proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
326             ..rustc_expand::expand::ExpansionConfig::default(crate_name.to_string())
327         };
328
329         let lint_store = LintStoreExpandImpl(lint_store);
330         let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
331         // Expand macros now!
332         let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
333
334         // The rest is error reporting
335
336         sess.parse_sess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
337             buffered_lints.append(&mut ecx.buffered_early_lint);
338         });
339
340         sess.time("check_unused_macros", || {
341             ecx.check_unused_macros();
342         });
343
344         let recursion_limit_hit = ecx.reduced_recursion_limit.is_some();
345
346         if cfg!(windows) {
347             env::set_var("PATH", &old_path);
348         }
349
350         if recursion_limit_hit {
351             // If we hit a recursion limit, exit early to avoid later passes getting overwhelmed
352             // with a large AST
353             Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
354         } else {
355             Ok(krate)
356         }
357     })?;
358
359     sess.time("maybe_building_test_harness", || {
360         rustc_builtin_macros::test_harness::inject(sess, resolver, &mut krate)
361     });
362
363     let has_proc_macro_decls = sess.time("AST_validation", || {
364         rustc_ast_passes::ast_validation::check_crate(sess, &krate, resolver.lint_buffer())
365     });
366
367     let crate_types = sess.crate_types();
368     let is_executable_crate = crate_types.contains(&CrateType::Executable);
369     let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
370
371     if crate_types.len() > 1 {
372         if is_executable_crate {
373             sess.emit_err(MixedBinCrate);
374         }
375         if is_proc_macro_crate {
376             sess.emit_err(MixedProcMacroCrate);
377         }
378     }
379
380     // For backwards compatibility, we don't try to run proc macro injection
381     // if rustdoc is run on a proc macro crate without '--crate-type proc-macro' being
382     // specified. This should only affect users who manually invoke 'rustdoc', as
383     // 'cargo doc' will automatically pass the proper '--crate-type' flags.
384     // However, we do emit a warning, to let such users know that they should
385     // start passing '--crate-type proc-macro'
386     if has_proc_macro_decls && sess.opts.actually_rustdoc && !is_proc_macro_crate {
387         sess.emit_warning(ProcMacroDocWithoutArg);
388     } else {
389         krate = sess.time("maybe_create_a_macro_crate", || {
390             let is_test_crate = sess.opts.test;
391             rustc_builtin_macros::proc_macro_harness::inject(
392                 sess,
393                 resolver,
394                 krate,
395                 is_proc_macro_crate,
396                 has_proc_macro_decls,
397                 is_test_crate,
398                 sess.diagnostic(),
399             )
400         });
401     }
402
403     // Done with macro expansion!
404
405     if sess.opts.unstable_opts.input_stats {
406         eprintln!("Post-expansion node count: {}", count_nodes(&krate));
407     }
408
409     if sess.opts.unstable_opts.hir_stats {
410         hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS", "ast-stats-2");
411     }
412
413     resolver.resolve_crate(&krate);
414
415     // Needs to go *after* expansion to be able to check the results of macro expansion.
416     sess.time("complete_gated_feature_checking", || {
417         rustc_ast_passes::feature_gate::check_crate(&krate, sess);
418     });
419
420     // Add all buffered lints from the `ParseSess` to the `Session`.
421     sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
422         info!("{} parse sess buffered_lints", buffered_lints.len());
423         for early_lint in buffered_lints.drain(..) {
424             resolver.lint_buffer().add_early_lint(early_lint);
425         }
426     });
427
428     // Gate identifiers containing invalid Unicode codepoints that were recovered during lexing.
429     sess.parse_sess.bad_unicode_identifiers.with_lock(|identifiers| {
430         let mut identifiers: Vec<_> = identifiers.drain().collect();
431         identifiers.sort_by_key(|&(key, _)| key);
432         for (ident, mut spans) in identifiers.into_iter() {
433             spans.sort();
434             if ident == sym::ferris {
435                 let first_span = spans[0];
436                 sess.emit_err(FerrisIdentifier { spans, first_span });
437             } else {
438                 sess.emit_err(EmojiIdentifier { spans, ident });
439             }
440         }
441     });
442
443     sess.time("early_lint_checks", || {
444         let lint_buffer = Some(std::mem::take(resolver.lint_buffer()));
445         rustc_lint::check_ast_node(
446             sess,
447             false,
448             lint_store,
449             resolver.registered_tools(),
450             lint_buffer,
451             rustc_lint::BuiltinCombinedEarlyLintPass::new(),
452             &krate,
453         )
454     });
455
456     Ok(krate)
457 }
458
459 // Returns all the paths that correspond to generated files.
460 fn generated_output_paths(
461     sess: &Session,
462     outputs: &OutputFilenames,
463     exact_name: bool,
464     crate_name: &str,
465 ) -> Vec<PathBuf> {
466     let mut out_filenames = Vec::new();
467     for output_type in sess.opts.output_types.keys() {
468         let file = outputs.path(*output_type);
469         match *output_type {
470             // If the filename has been overridden using `-o`, it will not be modified
471             // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
472             OutputType::Exe if !exact_name => {
473                 for crate_type in sess.crate_types().iter() {
474                     let p = filename_for_input(sess, *crate_type, crate_name, outputs);
475                     out_filenames.push(p);
476                 }
477             }
478             OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
479                 // Don't add the dep-info output when omitting it from dep-info targets
480             }
481             _ => {
482                 out_filenames.push(file);
483             }
484         }
485     }
486     out_filenames
487 }
488
489 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
490 // returns None for every file path.
491 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
492 where
493     F: Fn(&PathBuf) -> Option<T>,
494 {
495     for output_path in output_paths {
496         if let Some(result) = f(output_path) {
497             return Some(result);
498         }
499     }
500     None
501 }
502
503 fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
504     let input_path = input_path.canonicalize().ok();
505     if input_path.is_none() {
506         return false;
507     }
508     let check = |output_path: &PathBuf| {
509         if output_path.canonicalize().ok() == input_path { Some(()) } else { None }
510     };
511     check_output(output_paths, check).is_some()
512 }
513
514 fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
515     let check = |output_path: &PathBuf| output_path.is_dir().then(|| output_path.clone());
516     check_output(output_paths, check)
517 }
518
519 fn escape_dep_filename(filename: &str) -> String {
520     // Apparently clang and gcc *only* escape spaces:
521     // https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
522     filename.replace(' ', "\\ ")
523 }
524
525 // Makefile comments only need escaping newlines and `\`.
526 // The result can be unescaped by anything that can unescape `escape_default` and friends.
527 fn escape_dep_env(symbol: Symbol) -> String {
528     let s = symbol.as_str();
529     let mut escaped = String::with_capacity(s.len());
530     for c in s.chars() {
531         match c {
532             '\n' => escaped.push_str(r"\n"),
533             '\r' => escaped.push_str(r"\r"),
534             '\\' => escaped.push_str(r"\\"),
535             _ => escaped.push(c),
536         }
537     }
538     escaped
539 }
540
541 fn write_out_deps(
542     sess: &Session,
543     boxed_resolver: &RefCell<BoxedResolver>,
544     outputs: &OutputFilenames,
545     out_filenames: &[PathBuf],
546 ) {
547     // Write out dependency rules to the dep-info file if requested
548     if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
549         return;
550     }
551     let deps_filename = outputs.path(OutputType::DepInfo);
552
553     let result = (|| -> io::Result<()> {
554         // Build a list of files used to compile the output and
555         // write Makefile-compatible dependency rules
556         let mut files: Vec<String> = sess
557             .source_map()
558             .files()
559             .iter()
560             .filter(|fmap| fmap.is_real_file())
561             .filter(|fmap| !fmap.is_imported())
562             .map(|fmap| escape_dep_filename(&fmap.name.prefer_local().to_string()))
563             .collect();
564
565         // Account for explicitly marked-to-track files
566         // (e.g. accessed in proc macros).
567         let file_depinfo = sess.parse_sess.file_depinfo.borrow();
568
569         let normalize_path = |path: PathBuf| {
570             let file = FileName::from(path);
571             escape_dep_filename(&file.prefer_local().to_string())
572         };
573
574         let extra_tracked_files =
575             file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str())));
576         files.extend(extra_tracked_files);
577
578         // We also need to track used PGO profile files
579         if let Some(ref profile_instr) = sess.opts.cg.profile_use {
580             files.push(normalize_path(profile_instr.as_path().to_path_buf()));
581         }
582         if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
583             files.push(normalize_path(profile_sample.as_path().to_path_buf()));
584         }
585
586         if sess.binary_dep_depinfo() {
587             if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
588                 if backend.contains('.') {
589                     // If the backend name contain a `.`, it is the path to an external dynamic
590                     // library. If not, it is not a path.
591                     files.push(backend.to_string());
592                 }
593             }
594
595             boxed_resolver.borrow_mut().access(|resolver| {
596                 for cnum in resolver.cstore().crates_untracked() {
597                     let source = resolver.cstore().crate_source_untracked(cnum);
598                     if let Some((path, _)) = &source.dylib {
599                         files.push(escape_dep_filename(&path.display().to_string()));
600                     }
601                     if let Some((path, _)) = &source.rlib {
602                         files.push(escape_dep_filename(&path.display().to_string()));
603                     }
604                     if let Some((path, _)) = &source.rmeta {
605                         files.push(escape_dep_filename(&path.display().to_string()));
606                     }
607                 }
608             });
609         }
610
611         let mut file = BufWriter::new(fs::File::create(&deps_filename)?);
612         for path in out_filenames {
613             writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
614         }
615
616         // Emit a fake target for each input file to the compilation. This
617         // prevents `make` from spitting out an error if a file is later
618         // deleted. For more info see #28735
619         for path in files {
620             writeln!(file, "{}:", path)?;
621         }
622
623         // Emit special comments with information about accessed environment variables.
624         let env_depinfo = sess.parse_sess.env_depinfo.borrow();
625         if !env_depinfo.is_empty() {
626             let mut envs: Vec<_> = env_depinfo
627                 .iter()
628                 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
629                 .collect();
630             envs.sort_unstable();
631             writeln!(file)?;
632             for (k, v) in envs {
633                 write!(file, "# env-dep:{}", k)?;
634                 if let Some(v) = v {
635                     write!(file, "={}", v)?;
636                 }
637                 writeln!(file)?;
638             }
639         }
640
641         Ok(())
642     })();
643
644     match result {
645         Ok(_) => {
646             if sess.opts.json_artifact_notifications {
647                 sess.parse_sess
648                     .span_diagnostic
649                     .emit_artifact_notification(&deps_filename, "dep-info");
650             }
651         }
652         Err(error) => {
653             sess.emit_fatal(ErrorWritingDependencies { path: &deps_filename, error });
654         }
655     }
656 }
657
658 pub fn prepare_outputs(
659     sess: &Session,
660     compiler: &Compiler,
661     krate: &ast::Crate,
662     boxed_resolver: &RefCell<BoxedResolver>,
663     crate_name: &str,
664 ) -> Result<OutputFilenames> {
665     let _timer = sess.timer("prepare_outputs");
666
667     // FIXME: rustdoc passes &[] instead of &krate.attrs here
668     let outputs = util::build_output_filenames(
669         &compiler.input,
670         &compiler.output_dir,
671         &compiler.output_file,
672         &compiler.temps_dir,
673         &krate.attrs,
674         sess,
675     );
676
677     let output_paths =
678         generated_output_paths(sess, &outputs, compiler.output_file.is_some(), crate_name);
679
680     // Ensure the source file isn't accidentally overwritten during compilation.
681     if let Some(ref input_path) = compiler.input_path {
682         if sess.opts.will_create_output_file() {
683             if output_contains_path(&output_paths, input_path) {
684                 let reported = sess.emit_err(InputFileWouldBeOverWritten { path: input_path });
685                 return Err(reported);
686             }
687             if let Some(ref dir_path) = output_conflicts_with_dir(&output_paths) {
688                 let reported =
689                     sess.emit_err(GeneratedFileConflictsWithDirectory { input_path, dir_path });
690                 return Err(reported);
691             }
692         }
693     }
694
695     if let Some(ref dir) = compiler.temps_dir {
696         if fs::create_dir_all(dir).is_err() {
697             let reported = sess.emit_err(TempsDirError);
698             return Err(reported);
699         }
700     }
701
702     write_out_deps(sess, boxed_resolver, &outputs, &output_paths);
703
704     let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
705         && sess.opts.output_types.len() == 1;
706
707     if !only_dep_info {
708         if let Some(ref dir) = compiler.output_dir {
709             if fs::create_dir_all(dir).is_err() {
710                 let reported = sess.emit_err(OutDirError);
711                 return Err(reported);
712             }
713         }
714     }
715
716     Ok(outputs)
717 }
718
719 pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
720     let providers = &mut Providers::default();
721     providers.analysis = analysis;
722     providers.hir_crate = rustc_ast_lowering::lower_to_hir;
723     proc_macro_decls::provide(providers);
724     rustc_const_eval::provide(providers);
725     rustc_middle::hir::provide(providers);
726     mir_borrowck::provide(providers);
727     mir_build::provide(providers);
728     rustc_mir_transform::provide(providers);
729     rustc_monomorphize::provide(providers);
730     rustc_privacy::provide(providers);
731     rustc_hir_analysis::provide(providers);
732     rustc_hir_typeck::provide(providers);
733     ty::provide(providers);
734     traits::provide(providers);
735     rustc_passes::provide(providers);
736     rustc_traits::provide(providers);
737     rustc_ty_utils::provide(providers);
738     rustc_metadata::provide(providers);
739     rustc_lint::provide(providers);
740     rustc_symbol_mangling::provide(providers);
741     rustc_codegen_ssa::provide(providers);
742     *providers
743 });
744
745 pub static DEFAULT_EXTERN_QUERY_PROVIDERS: LazyLock<ExternProviders> = LazyLock::new(|| {
746     let mut extern_providers = ExternProviders::default();
747     rustc_metadata::provide_extern(&mut extern_providers);
748     rustc_codegen_ssa::provide_extern(&mut extern_providers);
749     extern_providers
750 });
751
752 pub struct QueryContext<'tcx> {
753     gcx: &'tcx GlobalCtxt<'tcx>,
754 }
755
756 impl<'tcx> QueryContext<'tcx> {
757     pub fn enter<F, R>(&mut self, f: F) -> R
758     where
759         F: FnOnce(TyCtxt<'tcx>) -> R,
760     {
761         let icx = ty::tls::ImplicitCtxt::new(self.gcx);
762         ty::tls::enter_context(&icx, |_| f(icx.tcx))
763     }
764 }
765
766 pub fn create_global_ctxt<'tcx>(
767     compiler: &'tcx Compiler,
768     lint_store: Lrc<LintStore>,
769     krate: Lrc<ast::Crate>,
770     dep_graph: DepGraph,
771     resolver: Rc<RefCell<BoxedResolver>>,
772     outputs: OutputFilenames,
773     crate_name: &str,
774     queries: &'tcx OnceCell<TcxQueries<'tcx>>,
775     global_ctxt: &'tcx OnceCell<GlobalCtxt<'tcx>>,
776     arena: &'tcx WorkerLocal<Arena<'tcx>>,
777     hir_arena: &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
778 ) -> QueryContext<'tcx> {
779     // We're constructing the HIR here; we don't care what we will
780     // read, since we haven't even constructed the *input* to
781     // incr. comp. yet.
782     dep_graph.assert_ignored();
783
784     let resolver_outputs = BoxedResolver::to_resolver_outputs(resolver);
785
786     let sess = &compiler.session();
787     let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
788
789     let codegen_backend = compiler.codegen_backend();
790     let mut local_providers = *DEFAULT_QUERY_PROVIDERS;
791     codegen_backend.provide(&mut local_providers);
792
793     let mut extern_providers = *DEFAULT_EXTERN_QUERY_PROVIDERS;
794     codegen_backend.provide_extern(&mut extern_providers);
795
796     if let Some(callback) = compiler.override_queries {
797         callback(sess, &mut local_providers, &mut extern_providers);
798     }
799
800     let queries = queries.get_or_init(|| {
801         TcxQueries::new(local_providers, extern_providers, query_result_on_disk_cache)
802     });
803
804     let gcx = sess.time("setup_global_ctxt", || {
805         global_ctxt.get_or_init(move || {
806             TyCtxt::create_global_ctxt(
807                 sess,
808                 lint_store,
809                 arena,
810                 hir_arena,
811                 resolver_outputs,
812                 krate,
813                 dep_graph,
814                 queries.on_disk_cache.as_ref().map(OnDiskCache::as_dyn),
815                 queries.as_dyn(),
816                 rustc_query_impl::query_callbacks(arena),
817                 crate_name,
818                 outputs,
819             )
820         })
821     });
822
823     QueryContext { gcx }
824 }
825
826 /// Runs the resolution, type-checking, region checking and other
827 /// miscellaneous analysis passes on the crate.
828 fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> {
829     rustc_passes::hir_id_validator::check_crate(tcx);
830
831     let sess = tcx.sess;
832     let mut entry_point = None;
833
834     sess.time("misc_checking_1", || {
835         parallel!(
836             {
837                 entry_point = sess.time("looking_for_entry_point", || tcx.entry_fn(()));
838
839                 sess.time("looking_for_derive_registrar", || {
840                     tcx.ensure().proc_macro_decls_static(())
841                 });
842
843                 CStore::from_tcx(tcx).report_unused_deps(tcx);
844             },
845             {
846                 tcx.hir().par_for_each_module(|module| {
847                     tcx.ensure().check_mod_loops(module);
848                     tcx.ensure().check_mod_attrs(module);
849                     tcx.ensure().check_mod_naked_functions(module);
850                     tcx.ensure().check_mod_unstable_api_usage(module);
851                     tcx.ensure().check_mod_const_bodies(module);
852                 });
853             },
854             {
855                 sess.time("unused_lib_feature_checking", || {
856                     rustc_passes::stability::check_unused_or_stable_features(tcx)
857                 });
858             },
859             {
860                 // We force these queries to run,
861                 // since they might not otherwise get called.
862                 // This marks the corresponding crate-level attributes
863                 // as used, and ensures that their values are valid.
864                 tcx.ensure().limits(());
865                 tcx.ensure().stability_index(());
866             }
867         );
868     });
869
870     // passes are timed inside typeck
871     rustc_hir_analysis::check_crate(tcx)?;
872
873     sess.time("misc_checking_2", || {
874         parallel!(
875             {
876                 sess.time("match_checking", || {
877                     tcx.hir().par_body_owners(|def_id| tcx.ensure().check_match(def_id.to_def_id()))
878                 });
879             },
880             {
881                 sess.time("liveness_checking", || {
882                     tcx.hir().par_body_owners(|def_id| {
883                         // this must run before MIR dump, because
884                         // "not all control paths return a value" is reported here.
885                         //
886                         // maybe move the check to a MIR pass?
887                         tcx.ensure().check_liveness(def_id.to_def_id());
888                     });
889                 });
890             }
891         );
892     });
893
894     sess.time("MIR_borrow_checking", || {
895         tcx.hir().par_body_owners(|def_id| tcx.ensure().mir_borrowck(def_id));
896     });
897
898     sess.time("MIR_effect_checking", || {
899         for def_id in tcx.hir().body_owners() {
900             tcx.ensure().thir_check_unsafety(def_id);
901             if !tcx.sess.opts.unstable_opts.thir_unsafeck {
902                 rustc_mir_transform::check_unsafety::check_unsafety(tcx, def_id);
903             }
904             tcx.ensure().has_ffi_unwind_calls(def_id);
905
906             if tcx.hir().body_const_context(def_id).is_some() {
907                 tcx.ensure()
908                     .mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(def_id));
909             }
910         }
911     });
912
913     sess.time("layout_testing", || layout_test::test_layout(tcx));
914
915     // Avoid overwhelming user with errors if borrow checking failed.
916     // I'm not sure how helpful this is, to be honest, but it avoids a
917     // lot of annoying errors in the ui tests (basically,
918     // lint warnings and so on -- kindck used to do this abort, but
919     // kindck is gone now). -nmatsakis
920     if let Some(reported) = sess.has_errors() {
921         return Err(reported);
922     }
923
924     sess.time("misc_checking_3", || {
925         parallel!(
926             {
927                 tcx.ensure().effective_visibilities(());
928
929                 parallel!(
930                     {
931                         tcx.ensure().check_private_in_public(());
932                     },
933                     {
934                         tcx.hir()
935                             .par_for_each_module(|module| tcx.ensure().check_mod_deathness(module));
936                     },
937                     {
938                         sess.time("lint_checking", || {
939                             rustc_lint::check_crate(tcx, || {
940                                 rustc_lint::BuiltinCombinedLateLintPass::new()
941                             });
942                         });
943                     }
944                 );
945             },
946             {
947                 sess.time("privacy_checking_modules", || {
948                     tcx.hir().par_for_each_module(|module| {
949                         tcx.ensure().check_mod_privacy(module);
950                     });
951                 });
952             }
953         );
954
955         // This check has to be run after all lints are done processing. We don't
956         // define a lint filter, as all lint checks should have finished at this point.
957         sess.time("check_lint_expectations", || tcx.check_expectations(None));
958     });
959
960     Ok(())
961 }
962
963 /// Runs the codegen backend, after which the AST and analysis can
964 /// be discarded.
965 pub fn start_codegen<'tcx>(
966     codegen_backend: &dyn CodegenBackend,
967     tcx: TyCtxt<'tcx>,
968     outputs: &OutputFilenames,
969 ) -> Box<dyn Any> {
970     info!("Pre-codegen\n{:?}", tcx.debug_stats());
971
972     let (metadata, need_metadata_module) =
973         rustc_metadata::fs::encode_and_write_metadata(tcx, outputs);
974
975     let codegen = tcx.sess.time("codegen_crate", move || {
976         codegen_backend.codegen_crate(tcx, metadata, need_metadata_module)
977     });
978
979     // Don't run these test assertions when not doing codegen. Compiletest tries to build
980     // build-fail tests in check mode first and expects it to not give an error in that case.
981     if tcx.sess.opts.output_types.should_codegen() {
982         rustc_incremental::assert_module_sources::assert_module_sources(tcx);
983         rustc_symbol_mangling::test::report_symbol_names(tcx);
984     }
985
986     info!("Post-codegen\n{:?}", tcx.debug_stats());
987
988     if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
989         if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx, outputs) {
990             tcx.sess.emit_err(CantEmitMIR { error });
991             tcx.sess.abort_if_errors();
992         }
993     }
994
995     codegen
996 }
997
998 fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
999     if let Some(attr) = krate_attrs
1000         .iter()
1001         .find(|attr| attr.has_name(sym::recursion_limit) && attr.value_str().is_none())
1002     {
1003         // This is here mainly to check for using a macro, such as
1004         // #![recursion_limit = foo!()]. That is not supported since that
1005         // would require expanding this while in the middle of expansion,
1006         // which needs to know the limit before expanding. Otherwise,
1007         // validation would normally be caught in AstValidator (via
1008         // `check_builtin_attribute`), but by the time that runs the macro
1009         // is expanded, and it doesn't give an error.
1010         validate_attr::emit_fatal_malformed_builtin_attribute(
1011             &sess.parse_sess,
1012             attr,
1013             sym::recursion_limit,
1014         );
1015     }
1016     rustc_middle::middle::limits::get_recursion_limit(krate_attrs, sess)
1017 }