rustc_interface/
passes.rs

1use std::any::Any;
2use std::ffi::{OsStr, OsString};
3use std::io::{self, BufWriter, Write};
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, LazyLock, OnceLock};
6use std::{env, fs, iter};
7
8use rustc_ast as ast;
9use rustc_codegen_ssa::traits::CodegenBackend;
10use rustc_data_structures::jobserver::Proxy;
11use rustc_data_structures::parallel;
12use rustc_data_structures::steal::Steal;
13use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, WorkerLocal};
14use rustc_expand::base::{ExtCtxt, LintStoreExpand};
15use rustc_feature::Features;
16use rustc_fs_util::try_canonicalize;
17use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
18use rustc_hir::definitions::Definitions;
19use rustc_incremental::setup_dep_graph;
20use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
21use rustc_metadata::creader::CStore;
22use rustc_middle::arena::Arena;
23use rustc_middle::dep_graph::DepsType;
24use rustc_middle::ty::{self, CurrentGcx, GlobalCtxt, RegisteredTools, TyCtxt};
25use rustc_middle::util::Providers;
26use rustc_parse::{
27    new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal, validate_attr,
28};
29use rustc_passes::{abi_test, input_stats, layout_test};
30use rustc_resolve::Resolver;
31use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
32use rustc_session::cstore::Untracked;
33use rustc_session::output::{collect_crate_types, filename_for_input};
34use rustc_session::parse::feature_err;
35use rustc_session::search_paths::PathKind;
36use rustc_session::{Limit, Session};
37use rustc_span::{
38    DUMMY_SP, ErrorGuaranteed, FileName, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
39};
40use rustc_target::spec::PanicStrategy;
41use rustc_trait_selection::traits;
42use tracing::{info, instrument};
43
44use crate::interface::Compiler;
45use crate::{errors, limits, proc_macro_decls, util};
46
47pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
48    let krate = sess
49        .time("parse_crate", || {
50            let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
51                Input::File(file) => new_parser_from_file(&sess.psess, file, None),
52                Input::Str { input, name } => {
53                    new_parser_from_source_str(&sess.psess, name.clone(), input.clone())
54                }
55            });
56            parser.parse_crate_mod()
57        })
58        .unwrap_or_else(|parse_error| {
59            let guar: ErrorGuaranteed = parse_error.emit();
60            guar.raise_fatal();
61        });
62
63    if sess.opts.unstable_opts.input_stats {
64        input_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS", "ast-stats-1");
65    }
66
67    krate
68}
69
70fn pre_expansion_lint<'a>(
71    sess: &Session,
72    features: &Features,
73    lint_store: &LintStore,
74    registered_tools: &RegisteredTools,
75    check_node: impl EarlyCheckNode<'a>,
76    node_name: Symbol,
77) {
78    sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
79        || {
80            rustc_lint::check_ast_node(
81                sess,
82                None,
83                features,
84                true,
85                lint_store,
86                registered_tools,
87                None,
88                rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
89                check_node,
90            );
91        },
92    );
93}
94
95// Cannot implement directly for `LintStore` due to trait coherence.
96struct LintStoreExpandImpl<'a>(&'a LintStore);
97
98impl LintStoreExpand for LintStoreExpandImpl<'_> {
99    fn pre_expansion_lint(
100        &self,
101        sess: &Session,
102        features: &Features,
103        registered_tools: &RegisteredTools,
104        node_id: ast::NodeId,
105        attrs: &[ast::Attribute],
106        items: &[rustc_ast::ptr::P<ast::Item>],
107        name: Symbol,
108    ) {
109        pre_expansion_lint(sess, features, self.0, registered_tools, (node_id, attrs, items), name);
110    }
111}
112
113/// Runs the "early phases" of the compiler: initial `cfg` processing,
114/// syntax expansion, secondary `cfg` expansion, synthesis of a test
115/// harness if one is to be provided, injection of a dependency on the
116/// standard library and prelude, and name resolution.
117#[instrument(level = "trace", skip(krate, resolver))]
118fn configure_and_expand(
119    mut krate: ast::Crate,
120    pre_configured_attrs: &[ast::Attribute],
121    resolver: &mut Resolver<'_, '_>,
122) -> ast::Crate {
123    let tcx = resolver.tcx();
124    let sess = tcx.sess;
125    let features = tcx.features();
126    let lint_store = unerased_lint_store(tcx.sess);
127    let crate_name = tcx.crate_name(LOCAL_CRATE);
128    let lint_check_node = (&krate, pre_configured_attrs);
129    pre_expansion_lint(
130        sess,
131        features,
132        lint_store,
133        tcx.registered_tools(()),
134        lint_check_node,
135        crate_name,
136    );
137    rustc_builtin_macros::register_builtin_macros(resolver);
138
139    let num_standard_library_imports = sess.time("crate_injection", || {
140        rustc_builtin_macros::standard_library_imports::inject(
141            &mut krate,
142            pre_configured_attrs,
143            resolver,
144            sess,
145            features,
146        )
147    });
148
149    util::check_attr_crate_type(sess, pre_configured_attrs, resolver.lint_buffer());
150
151    // Expand all macros
152    krate = sess.time("macro_expand_crate", || {
153        // Windows dlls do not have rpaths, so they don't know how to find their
154        // dependencies. It's up to us to tell the system where to find all the
155        // dependent dlls. Note that this uses cfg!(windows) as opposed to
156        // targ_cfg because syntax extensions are always loaded for the host
157        // compiler, not for the target.
158        //
159        // This is somewhat of an inherently racy operation, however, as
160        // multiple threads calling this function could possibly continue
161        // extending PATH far beyond what it should. To solve this for now we
162        // just don't add any new elements to PATH which are already there
163        // within PATH. This is basically a targeted fix at #17360 for rustdoc
164        // which runs rustc in parallel but has been seen (#33844) to cause
165        // problems with PATH becoming too long.
166        let mut old_path = OsString::new();
167        if cfg!(windows) {
168            old_path = env::var_os("PATH").unwrap_or(old_path);
169            let mut new_path = Vec::from_iter(
170                sess.host_filesearch().search_paths(PathKind::All).map(|p| p.dir.clone()),
171            );
172            for path in env::split_paths(&old_path) {
173                if !new_path.contains(&path) {
174                    new_path.push(path);
175                }
176            }
177            unsafe {
178                env::set_var(
179                    "PATH",
180                    &env::join_paths(
181                        new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
182                    )
183                    .unwrap(),
184                );
185            }
186        }
187
188        // Create the config for macro expansion
189        let recursion_limit = get_recursion_limit(pre_configured_attrs, sess);
190        let cfg = rustc_expand::expand::ExpansionConfig {
191            crate_name: crate_name.to_string(),
192            features,
193            recursion_limit,
194            trace_mac: sess.opts.unstable_opts.trace_macros,
195            should_test: sess.is_test_crate(),
196            span_debug: sess.opts.unstable_opts.span_debug,
197            proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
198        };
199
200        let lint_store = LintStoreExpandImpl(lint_store);
201        let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
202        ecx.num_standard_library_imports = num_standard_library_imports;
203        // Expand macros now!
204        let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
205
206        // The rest is error reporting
207
208        sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
209            buffered_lints.append(&mut ecx.buffered_early_lint);
210        });
211
212        sess.time("check_unused_macros", || {
213            ecx.check_unused_macros();
214        });
215
216        // If we hit a recursion limit, exit early to avoid later passes getting overwhelmed
217        // with a large AST
218        if ecx.reduced_recursion_limit.is_some() {
219            sess.dcx().abort_if_errors();
220            unreachable!();
221        }
222
223        if cfg!(windows) {
224            unsafe {
225                env::set_var("PATH", &old_path);
226            }
227        }
228
229        krate
230    });
231
232    sess.time("maybe_building_test_harness", || {
233        rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
234    });
235
236    let has_proc_macro_decls = sess.time("AST_validation", || {
237        rustc_ast_passes::ast_validation::check_crate(
238            sess,
239            features,
240            &krate,
241            tcx.is_sdylib_interface_build(),
242            resolver.lint_buffer(),
243        )
244    });
245
246    let crate_types = tcx.crate_types();
247    let is_executable_crate = crate_types.contains(&CrateType::Executable);
248    let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
249
250    if crate_types.len() > 1 {
251        if is_executable_crate {
252            sess.dcx().emit_err(errors::MixedBinCrate);
253        }
254        if is_proc_macro_crate {
255            sess.dcx().emit_err(errors::MixedProcMacroCrate);
256        }
257    }
258    if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
259        feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
260    }
261
262    if is_proc_macro_crate && sess.panic_strategy() == PanicStrategy::Abort {
263        sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort);
264    }
265
266    sess.time("maybe_create_a_macro_crate", || {
267        let is_test_crate = sess.is_test_crate();
268        rustc_builtin_macros::proc_macro_harness::inject(
269            &mut krate,
270            sess,
271            features,
272            resolver,
273            is_proc_macro_crate,
274            has_proc_macro_decls,
275            is_test_crate,
276            sess.dcx(),
277        )
278    });
279
280    // Done with macro expansion!
281
282    resolver.resolve_crate(&krate);
283
284    CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate);
285    krate
286}
287
288fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
289    let sess = tcx.sess;
290    let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
291    let mut lint_buffer = resolver.lint_buffer.steal();
292
293    if sess.opts.unstable_opts.input_stats {
294        input_stats::print_ast_stats(krate, "POST EXPANSION AST STATS", "ast-stats-2");
295    }
296
297    // Needs to go *after* expansion to be able to check the results of macro expansion.
298    sess.time("complete_gated_feature_checking", || {
299        rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
300    });
301
302    // Add all buffered lints from the `ParseSess` to the `Session`.
303    sess.psess.buffered_lints.with_lock(|buffered_lints| {
304        info!("{} parse sess buffered_lints", buffered_lints.len());
305        for early_lint in buffered_lints.drain(..) {
306            lint_buffer.add_early_lint(early_lint);
307        }
308    });
309
310    // Gate identifiers containing invalid Unicode codepoints that were recovered during lexing.
311    sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
312        for (ident, mut spans) in identifiers.drain(..) {
313            spans.sort();
314            if ident == sym::ferris {
315                enum FerrisFix {
316                    SnakeCase,
317                    ScreamingSnakeCase,
318                    PascalCase,
319                }
320
321                impl FerrisFix {
322                    const fn as_str(self) -> &'static str {
323                        match self {
324                            FerrisFix::SnakeCase => "ferris",
325                            FerrisFix::ScreamingSnakeCase => "FERRIS",
326                            FerrisFix::PascalCase => "Ferris",
327                        }
328                    }
329                }
330
331                let first_span = spans[0];
332                let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
333                let ferris_fix = prev_source
334                    .map_or(FerrisFix::SnakeCase, |source| {
335                        let mut source_before_ferris = source.trim_end().split_whitespace().rev();
336                        match source_before_ferris.next() {
337                            Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
338                                FerrisFix::PascalCase
339                            }
340                            Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
341                            Some("mut") if source_before_ferris.next() == Some("static") => {
342                                FerrisFix::ScreamingSnakeCase
343                            }
344                            _ => FerrisFix::SnakeCase,
345                        }
346                    })
347                    .as_str();
348
349                sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix });
350            } else {
351                sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident });
352            }
353        }
354    });
355
356    let lint_store = unerased_lint_store(tcx.sess);
357    rustc_lint::check_ast_node(
358        sess,
359        Some(tcx),
360        tcx.features(),
361        false,
362        lint_store,
363        tcx.registered_tools(()),
364        Some(lint_buffer),
365        rustc_lint::BuiltinCombinedEarlyLintPass::new(),
366        (&**krate, &*krate.attrs),
367    )
368}
369
370fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
371    let value = env::var_os(key);
372
373    let value_tcx = value.as_ref().map(|value| {
374        let encoded_bytes = tcx.arena.alloc_slice(value.as_encoded_bytes());
375        debug_assert_eq!(value.as_encoded_bytes(), encoded_bytes);
376        // SAFETY: The bytes came from `as_encoded_bytes`, and we assume that
377        // `alloc_slice` is implemented correctly, and passes the same bytes
378        // back (debug asserted above).
379        unsafe { OsStr::from_encoded_bytes_unchecked(encoded_bytes) }
380    });
381
382    // Also add the variable to Cargo's dependency tracking
383    //
384    // NOTE: This only works for passes run before `write_dep_info`. See that
385    // for extension points for configuring environment variables to be
386    // properly change-tracked.
387    tcx.sess.psess.env_depinfo.borrow_mut().insert((
388        Symbol::intern(&key.to_string_lossy()),
389        value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(&value)),
390    ));
391
392    value_tcx
393}
394
395// Returns all the paths that correspond to generated files.
396fn generated_output_paths(
397    tcx: TyCtxt<'_>,
398    outputs: &OutputFilenames,
399    exact_name: bool,
400    crate_name: Symbol,
401) -> Vec<PathBuf> {
402    let sess = tcx.sess;
403    let mut out_filenames = Vec::new();
404    for output_type in sess.opts.output_types.keys() {
405        let out_filename = outputs.path(*output_type);
406        let file = out_filename.as_path().to_path_buf();
407        match *output_type {
408            // If the filename has been overridden using `-o`, it will not be modified
409            // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
410            OutputType::Exe if !exact_name => {
411                for crate_type in tcx.crate_types().iter() {
412                    let p = filename_for_input(sess, *crate_type, crate_name, outputs);
413                    out_filenames.push(p.as_path().to_path_buf());
414                }
415            }
416            OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
417                // Don't add the dep-info output when omitting it from dep-info targets
418            }
419            OutputType::DepInfo if out_filename.is_stdout() => {
420                // Don't add the dep-info output when it goes to stdout
421            }
422            _ => {
423                out_filenames.push(file);
424            }
425        }
426    }
427    out_filenames
428}
429
430fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
431    let input_path = try_canonicalize(input_path).ok();
432    if input_path.is_none() {
433        return false;
434    }
435    output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
436}
437
438fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
439    output_paths.iter().find(|output_path| output_path.is_dir())
440}
441
442fn escape_dep_filename(filename: &str) -> String {
443    // Apparently clang and gcc *only* escape spaces:
444    // https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
445    filename.replace(' ', "\\ ")
446}
447
448// Makefile comments only need escaping newlines and `\`.
449// The result can be unescaped by anything that can unescape `escape_default` and friends.
450fn escape_dep_env(symbol: Symbol) -> String {
451    let s = symbol.as_str();
452    let mut escaped = String::with_capacity(s.len());
453    for c in s.chars() {
454        match c {
455            '\n' => escaped.push_str(r"\n"),
456            '\r' => escaped.push_str(r"\r"),
457            '\\' => escaped.push_str(r"\\"),
458            _ => escaped.push(c),
459        }
460    }
461    escaped
462}
463
464fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
465    // Write out dependency rules to the dep-info file if requested
466    let sess = tcx.sess;
467    if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
468        return;
469    }
470    let deps_output = outputs.path(OutputType::DepInfo);
471    let deps_filename = deps_output.as_path();
472
473    let result: io::Result<()> = try {
474        // Build a list of files used to compile the output and
475        // write Makefile-compatible dependency rules
476        let mut files: Vec<(String, u64, Option<SourceFileHash>)> = sess
477            .source_map()
478            .files()
479            .iter()
480            .filter(|fmap| fmap.is_real_file())
481            .filter(|fmap| !fmap.is_imported())
482            .map(|fmap| {
483                (
484                    escape_dep_filename(&fmap.name.prefer_local().to_string()),
485                    fmap.source_len.0 as u64,
486                    fmap.checksum_hash,
487                )
488            })
489            .collect();
490
491        let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
492
493        // Account for explicitly marked-to-track files
494        // (e.g. accessed in proc macros).
495        let file_depinfo = sess.psess.file_depinfo.borrow();
496
497        let normalize_path = |path: PathBuf| {
498            let file = FileName::from(path);
499            escape_dep_filename(&file.prefer_local().to_string())
500        };
501
502        // The entries will be used to declare dependencies between files in a
503        // Makefile-like output, so the iteration order does not matter.
504        fn hash_iter_files<P: AsRef<Path>>(
505            it: impl Iterator<Item = P>,
506            checksum_hash_algo: Option<SourceFileHashAlgorithm>,
507        ) -> impl Iterator<Item = (P, u64, Option<SourceFileHash>)> {
508            it.map(move |path| {
509                match checksum_hash_algo.and_then(|algo| {
510                    fs::File::open(path.as_ref())
511                        .and_then(|mut file| {
512                            SourceFileHash::new(algo, &mut file).map(|h| (file, h))
513                        })
514                        .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
515                        .map_err(|e| {
516                            tracing::error!(
517                                "failed to compute checksum, omitting it from dep-info {} {e}",
518                                path.as_ref().display()
519                            )
520                        })
521                        .ok()
522                }) {
523                    Some((file_len, checksum)) => (path, file_len, Some(checksum)),
524                    None => (path, 0, None),
525                }
526            })
527        }
528
529        let extra_tracked_files = hash_iter_files(
530            file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
531            checksum_hash_algo,
532        );
533        files.extend(extra_tracked_files);
534
535        // We also need to track used PGO profile files
536        if let Some(ref profile_instr) = sess.opts.cg.profile_use {
537            files.extend(hash_iter_files(
538                iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
539                checksum_hash_algo,
540            ));
541        }
542        if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
543            files.extend(hash_iter_files(
544                iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
545                checksum_hash_algo,
546            ));
547        }
548
549        // Debugger visualizer files
550        for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
551            files.extend(hash_iter_files(
552                iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
553                checksum_hash_algo,
554            ));
555        }
556
557        if sess.binary_dep_depinfo() {
558            if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
559                if backend.contains('.') {
560                    // If the backend name contain a `.`, it is the path to an external dynamic
561                    // library. If not, it is not a path.
562                    files.extend(hash_iter_files(
563                        iter::once(backend.to_string()),
564                        checksum_hash_algo,
565                    ));
566                }
567            }
568
569            for &cnum in tcx.crates(()) {
570                let source = tcx.used_crate_source(cnum);
571                if let Some((path, _)) = &source.dylib {
572                    files.extend(hash_iter_files(
573                        iter::once(escape_dep_filename(&path.display().to_string())),
574                        checksum_hash_algo,
575                    ));
576                }
577                if let Some((path, _)) = &source.rlib {
578                    files.extend(hash_iter_files(
579                        iter::once(escape_dep_filename(&path.display().to_string())),
580                        checksum_hash_algo,
581                    ));
582                }
583                if let Some((path, _)) = &source.rmeta {
584                    files.extend(hash_iter_files(
585                        iter::once(escape_dep_filename(&path.display().to_string())),
586                        checksum_hash_algo,
587                    ));
588                }
589            }
590        }
591
592        let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
593            for path in out_filenames {
594                writeln!(
595                    file,
596                    "{}: {}\n",
597                    path.display(),
598                    files
599                        .iter()
600                        .map(|(path, _file_len, _checksum_hash_algo)| path.as_str())
601                        .intersperse(" ")
602                        .collect::<String>()
603                )?;
604            }
605
606            // Emit a fake target for each input file to the compilation. This
607            // prevents `make` from spitting out an error if a file is later
608            // deleted. For more info see #28735
609            for (path, _file_len, _checksum_hash_algo) in &files {
610                writeln!(file, "{path}:")?;
611            }
612
613            // Emit special comments with information about accessed environment variables.
614            let env_depinfo = sess.psess.env_depinfo.borrow();
615            if !env_depinfo.is_empty() {
616                // We will soon sort, so the initial order does not matter.
617                #[allow(rustc::potential_query_instability)]
618                let mut envs: Vec<_> = env_depinfo
619                    .iter()
620                    .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
621                    .collect();
622                envs.sort_unstable();
623                writeln!(file)?;
624                for (k, v) in envs {
625                    write!(file, "# env-dep:{k}")?;
626                    if let Some(v) = v {
627                        write!(file, "={v}")?;
628                    }
629                    writeln!(file)?;
630                }
631            }
632
633            // If caller requested this information, add special comments about source file checksums.
634            // These are not necessarily the same checksums as was used in the debug files.
635            if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
636                files
637                    .iter()
638                    .filter_map(|(path, file_len, hash_algo)| {
639                        hash_algo.map(|hash_algo| (path, file_len, hash_algo))
640                    })
641                    .try_for_each(|(path, file_len, checksum_hash)| {
642                        writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
643                    })?;
644            }
645
646            Ok(())
647        };
648
649        match deps_output {
650            OutFileName::Stdout => {
651                let mut file = BufWriter::new(io::stdout());
652                write_deps_to_file(&mut file)?;
653            }
654            OutFileName::Real(ref path) => {
655                let mut file = fs::File::create_buffered(path)?;
656                write_deps_to_file(&mut file)?;
657            }
658        }
659    };
660
661    match result {
662        Ok(_) => {
663            if sess.opts.json_artifact_notifications {
664                sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
665            }
666        }
667        Err(error) => {
668            sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
669        }
670    }
671}
672
673fn resolver_for_lowering_raw<'tcx>(
674    tcx: TyCtxt<'tcx>,
675    (): (),
676) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
677    let arenas = Resolver::arenas();
678    let _ = tcx.registered_tools(()); // Uses `crate_for_resolver`.
679    let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
680    let mut resolver = Resolver::new(
681        tcx,
682        &pre_configured_attrs,
683        krate.spans.inner_span,
684        krate.spans.inject_use_span,
685        &arenas,
686    );
687    let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
688
689    // Make sure we don't mutate the cstore from here on.
690    tcx.untracked().cstore.freeze();
691
692    let ty::ResolverOutputs {
693        global_ctxt: untracked_resolutions,
694        ast_lowering: untracked_resolver_for_lowering,
695    } = resolver.into_outputs();
696
697    let resolutions = tcx.arena.alloc(untracked_resolutions);
698    (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
699}
700
701pub fn write_dep_info(tcx: TyCtxt<'_>) {
702    // Make sure name resolution and macro expansion is run for
703    // the side-effect of providing a complete set of all
704    // accessed files and env vars.
705    let _ = tcx.resolver_for_lowering();
706
707    let sess = tcx.sess;
708    let _timer = sess.timer("write_dep_info");
709    let crate_name = tcx.crate_name(LOCAL_CRATE);
710
711    let outputs = tcx.output_filenames(());
712    let output_paths =
713        generated_output_paths(tcx, &outputs, sess.io.output_file.is_some(), crate_name);
714
715    // Ensure the source file isn't accidentally overwritten during compilation.
716    if let Some(input_path) = sess.io.input.opt_path() {
717        if sess.opts.will_create_output_file() {
718            if output_contains_path(&output_paths, input_path) {
719                sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
720            }
721            if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
722                sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
723                    input_path,
724                    dir_path,
725                });
726            }
727        }
728    }
729
730    if let Some(ref dir) = sess.io.temps_dir {
731        if fs::create_dir_all(dir).is_err() {
732            sess.dcx().emit_fatal(errors::TempsDirError);
733        }
734    }
735
736    write_out_deps(tcx, &outputs, &output_paths);
737
738    let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
739        && sess.opts.output_types.len() == 1;
740
741    if !only_dep_info {
742        if let Some(ref dir) = sess.io.output_dir {
743            if fs::create_dir_all(dir).is_err() {
744                sess.dcx().emit_fatal(errors::OutDirError);
745            }
746        }
747    }
748}
749
750pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
751    if !tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
752        return;
753    }
754    let _timer = tcx.sess.timer("write_interface");
755    let (_, krate) = &*tcx.resolver_for_lowering().borrow();
756
757    let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
758        krate,
759        tcx.sess.psess.edition,
760        &tcx.sess.psess.attr_id_generator,
761    );
762    let export_output = tcx.output_filenames(()).interface_path();
763    let mut file = fs::File::create_buffered(export_output).unwrap();
764    if let Err(err) = write!(file, "{}", krate) {
765        tcx.dcx().fatal(format!("error writing interface file: {}", err));
766    }
767}
768
769pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
770    let providers = &mut Providers::default();
771    providers.analysis = analysis;
772    providers.hir_crate = rustc_ast_lowering::lower_to_hir;
773    providers.resolver_for_lowering_raw = resolver_for_lowering_raw;
774    providers.stripped_cfg_items =
775        |tcx, _| tcx.arena.alloc_from_iter(tcx.resolutions(()).stripped_cfg_items.steal());
776    providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
777    providers.early_lint_checks = early_lint_checks;
778    providers.env_var_os = env_var_os;
779    limits::provide(providers);
780    proc_macro_decls::provide(providers);
781    rustc_const_eval::provide(providers);
782    rustc_middle::hir::provide(providers);
783    rustc_borrowck::provide(providers);
784    rustc_incremental::provide(providers);
785    rustc_mir_build::provide(providers);
786    rustc_mir_transform::provide(providers);
787    rustc_monomorphize::provide(providers);
788    rustc_privacy::provide(providers);
789    rustc_query_impl::provide(providers);
790    rustc_resolve::provide(providers);
791    rustc_hir_analysis::provide(providers);
792    rustc_hir_typeck::provide(providers);
793    ty::provide(providers);
794    traits::provide(providers);
795    rustc_passes::provide(providers);
796    rustc_traits::provide(providers);
797    rustc_ty_utils::provide(providers);
798    rustc_metadata::provide(providers);
799    rustc_lint::provide(providers);
800    rustc_symbol_mangling::provide(providers);
801    rustc_codegen_ssa::provide(providers);
802    *providers
803});
804
805pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
806    compiler: &Compiler,
807    mut krate: rustc_ast::Crate,
808    f: F,
809) -> T {
810    let sess = &compiler.sess;
811
812    rustc_builtin_macros::cmdline_attrs::inject(
813        &mut krate,
814        &sess.psess,
815        &sess.opts.unstable_opts.crate_attr,
816    );
817
818    let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
819
820    let crate_name = get_crate_name(sess, &pre_configured_attrs);
821    let crate_types = collect_crate_types(sess, &pre_configured_attrs);
822    let stable_crate_id = StableCrateId::new(
823        crate_name,
824        crate_types.contains(&CrateType::Executable),
825        sess.opts.cg.metadata.clone(),
826        sess.cfg_version,
827    );
828
829    let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
830
831    let dep_type = DepsType { dep_names: rustc_query_impl::dep_kind_names() };
832    let dep_graph = setup_dep_graph(sess, crate_name, &dep_type);
833
834    let cstore =
835        FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
836    let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
837
838    let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
839    let untracked =
840        Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
841
842    // We're constructing the HIR here; we don't care what we will
843    // read, since we haven't even constructed the *input* to
844    // incr. comp. yet.
845    dep_graph.assert_ignored();
846
847    let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
848
849    let codegen_backend = &compiler.codegen_backend;
850    let mut providers = *DEFAULT_QUERY_PROVIDERS;
851    codegen_backend.provide(&mut providers);
852
853    if let Some(callback) = compiler.override_queries {
854        callback(sess, &mut providers);
855    }
856
857    let incremental = dep_graph.is_fully_enabled();
858
859    let gcx_cell = OnceLock::new();
860    let arena = WorkerLocal::new(|_| Arena::default());
861    let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
862
863    // This closure is necessary to force rustc to perform the correct lifetime
864    // subtyping for GlobalCtxt::enter to be allowed.
865    let inner: Box<
866        dyn for<'tcx> FnOnce(
867            &'tcx Session,
868            CurrentGcx,
869            Arc<Proxy>,
870            &'tcx OnceLock<GlobalCtxt<'tcx>>,
871            &'tcx WorkerLocal<Arena<'tcx>>,
872            &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
873            F,
874        ) -> T,
875    > = Box::new(move |sess, current_gcx, jobserver_proxy, gcx_cell, arena, hir_arena, f| {
876        TyCtxt::create_global_ctxt(
877            gcx_cell,
878            sess,
879            crate_types,
880            stable_crate_id,
881            arena,
882            hir_arena,
883            untracked,
884            dep_graph,
885            rustc_query_impl::query_callbacks(arena),
886            rustc_query_impl::query_system(
887                providers.queries,
888                providers.extern_queries,
889                query_result_on_disk_cache,
890                incremental,
891            ),
892            providers.hooks,
893            current_gcx,
894            jobserver_proxy,
895            |tcx| {
896                let feed = tcx.create_crate_num(stable_crate_id).unwrap();
897                assert_eq!(feed.key(), LOCAL_CRATE);
898                feed.crate_name(crate_name);
899
900                let feed = tcx.feed_unit_query();
901                feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
902                    tcx.sess,
903                    &pre_configured_attrs,
904                    crate_name,
905                )));
906                feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
907                feed.output_filenames(Arc::new(outputs));
908
909                let res = f(tcx);
910                // FIXME maybe run finish even when a fatal error occured? or at least tcx.alloc_self_profile_query_strings()?
911                tcx.finish();
912                res
913            },
914        )
915    });
916
917    inner(
918        &compiler.sess,
919        compiler.current_gcx.clone(),
920        Arc::clone(&compiler.jobserver_proxy),
921        &gcx_cell,
922        &arena,
923        &hir_arena,
924        f,
925    )
926}
927
928/// Runs all analyses that we guarantee to run, even if errors were reported in earlier analyses.
929/// This function never fails.
930fn run_required_analyses(tcx: TyCtxt<'_>) {
931    if tcx.sess.opts.unstable_opts.input_stats {
932        rustc_passes::input_stats::print_hir_stats(tcx);
933    }
934    // When using rustdoc's "jump to def" feature, it enters this code and `check_crate`
935    // is not defined. So we need to cfg it out.
936    #[cfg(all(not(doc), debug_assertions))]
937    rustc_passes::hir_id_validator::check_crate(tcx);
938
939    // Prefetch this to prevent multiple threads from blocking on it later.
940    // This is needed since the `hir_id_validator::check_crate` call above is not guaranteed
941    // to use `hir_crate`.
942    tcx.ensure_done().hir_crate(());
943
944    let sess = tcx.sess;
945    sess.time("misc_checking_1", || {
946        parallel!(
947            {
948                sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
949
950                sess.time("looking_for_derive_registrar", || {
951                    tcx.ensure_ok().proc_macro_decls_static(())
952                });
953
954                CStore::from_tcx(tcx).report_unused_deps(tcx);
955            },
956            {
957                tcx.ensure_ok().exportable_items(LOCAL_CRATE);
958                tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
959                tcx.par_hir_for_each_module(|module| {
960                    tcx.ensure_ok().check_mod_loops(module);
961                    tcx.ensure_ok().check_mod_attrs(module);
962                    tcx.ensure_ok().check_mod_naked_functions(module);
963                    tcx.ensure_ok().check_mod_unstable_api_usage(module);
964                });
965            },
966            {
967                sess.time("unused_lib_feature_checking", || {
968                    rustc_passes::stability::check_unused_or_stable_features(tcx)
969                });
970            },
971            {
972                // We force these queries to run,
973                // since they might not otherwise get called.
974                // This marks the corresponding crate-level attributes
975                // as used, and ensures that their values are valid.
976                tcx.ensure_ok().limits(());
977                tcx.ensure_ok().stability_index(());
978            }
979        );
980    });
981
982    rustc_hir_analysis::check_crate(tcx);
983    sess.time("MIR_coroutine_by_move_body", || {
984        tcx.par_hir_body_owners(|def_id| {
985            if tcx.needs_coroutine_by_move_body_def_id(def_id.to_def_id()) {
986                tcx.ensure_done().coroutine_by_move_body_def_id(def_id);
987            }
988        });
989    });
990    // Freeze definitions as we don't add new ones at this point.
991    // We need to wait until now since we synthesize a by-move body
992    // for all coroutine-closures.
993    //
994    // This improves performance by allowing lock-free access to them.
995    tcx.untracked().definitions.freeze();
996
997    sess.time("MIR_borrow_checking", || {
998        tcx.par_hir_body_owners(|def_id| {
999            // Run unsafety check because it's responsible for stealing and
1000            // deallocating THIR.
1001            tcx.ensure_ok().check_unsafety(def_id);
1002            if !tcx.is_typeck_child(def_id.to_def_id()) {
1003                tcx.ensure_ok().mir_borrowck(def_id)
1004            }
1005        });
1006    });
1007    sess.time("MIR_effect_checking", || {
1008        tcx.par_hir_body_owners(|def_id| {
1009            tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1010
1011            // If we need to codegen, ensure that we emit all errors from
1012            // `mir_drops_elaborated_and_const_checked` now, to avoid discovering
1013            // them later during codegen.
1014            if tcx.sess.opts.output_types.should_codegen()
1015                || tcx.hir_body_const_context(def_id).is_some()
1016            {
1017                tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1018            }
1019        });
1020    });
1021    sess.time("coroutine_obligations", || {
1022        tcx.par_hir_body_owners(|def_id| {
1023            if tcx.is_coroutine(def_id.to_def_id()) {
1024                tcx.ensure_ok().mir_coroutine_witnesses(def_id);
1025                let _ = tcx.ensure_ok().check_coroutine_obligations(
1026                    tcx.typeck_root_def_id(def_id.to_def_id()).expect_local(),
1027                );
1028                if !tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()) {
1029                    // Eagerly check the unsubstituted layout for cycles.
1030                    tcx.ensure_ok().layout_of(
1031                        ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
1032                            .as_query_input(tcx.type_of(def_id).instantiate_identity()),
1033                    );
1034                }
1035            }
1036        });
1037    });
1038
1039    sess.time("layout_testing", || layout_test::test_layout(tcx));
1040    sess.time("abi_testing", || abi_test::test_abi(tcx));
1041
1042    // If `-Zvalidate-mir` is set, we also want to compute the final MIR for each item
1043    // (either its `mir_for_ctfe` or `optimized_mir`) since that helps uncover any bugs
1044    // in MIR optimizations that may only be reachable through codegen, or other codepaths
1045    // that requires the optimized/ctfe MIR, coroutine bodies, or evaluating consts.
1046    if tcx.sess.opts.unstable_opts.validate_mir {
1047        sess.time("ensuring_final_MIR_is_computable", || {
1048            tcx.par_hir_body_owners(|def_id| {
1049                tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1050            });
1051        });
1052    }
1053}
1054
1055/// Runs the type-checking, region checking and other miscellaneous analysis
1056/// passes on the crate.
1057fn analysis(tcx: TyCtxt<'_>, (): ()) {
1058    run_required_analyses(tcx);
1059
1060    let sess = tcx.sess;
1061
1062    // Avoid overwhelming user with errors if borrow checking failed.
1063    // I'm not sure how helpful this is, to be honest, but it avoids a
1064    // lot of annoying errors in the ui tests (basically,
1065    // lint warnings and so on -- kindck used to do this abort, but
1066    // kindck is gone now). -nmatsakis
1067    //
1068    // But we exclude lint errors from this, because lint errors are typically
1069    // less serious and we're more likely to want to continue (#87337).
1070    if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1071        guar.raise_fatal();
1072    }
1073
1074    sess.time("misc_checking_3", || {
1075        parallel!(
1076            {
1077                tcx.ensure_ok().effective_visibilities(());
1078
1079                parallel!(
1080                    {
1081                        tcx.ensure_ok().check_private_in_public(());
1082                    },
1083                    {
1084                        tcx.par_hir_for_each_module(|module| {
1085                            tcx.ensure_ok().check_mod_deathness(module)
1086                        });
1087                    },
1088                    {
1089                        sess.time("lint_checking", || {
1090                            rustc_lint::check_crate(tcx);
1091                        });
1092                    },
1093                    {
1094                        tcx.ensure_ok().clashing_extern_declarations(());
1095                    }
1096                );
1097            },
1098            {
1099                sess.time("privacy_checking_modules", || {
1100                    tcx.par_hir_for_each_module(|module| {
1101                        tcx.ensure_ok().check_mod_privacy(module);
1102                    });
1103                });
1104            }
1105        );
1106
1107        // This check has to be run after all lints are done processing. We don't
1108        // define a lint filter, as all lint checks should have finished at this point.
1109        sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1110
1111        // This query is only invoked normally if a diagnostic is emitted that needs any
1112        // diagnostic item. If the crate compiles without checking any diagnostic items,
1113        // we will fail to emit overlap diagnostics. Thus we invoke it here unconditionally.
1114        let _ = tcx.all_diagnostic_items(());
1115    });
1116}
1117
1118/// Runs the codegen backend, after which the AST and analysis can
1119/// be discarded.
1120pub(crate) fn start_codegen<'tcx>(
1121    codegen_backend: &dyn CodegenBackend,
1122    tcx: TyCtxt<'tcx>,
1123) -> Box<dyn Any> {
1124    // Hook for tests.
1125    if let Some((def_id, _)) = tcx.entry_fn(())
1126        && tcx.has_attr(def_id, sym::rustc_delayed_bug_from_inside_query)
1127    {
1128        tcx.ensure_ok().trigger_delayed_bug(def_id);
1129    }
1130
1131    // Don't run this test assertions when not doing codegen. Compiletest tries to build
1132    // build-fail tests in check mode first and expects it to not give an error in that case.
1133    if tcx.sess.opts.output_types.should_codegen() {
1134        rustc_symbol_mangling::test::report_symbol_names(tcx);
1135    }
1136
1137    // Don't do code generation if there were any errors. Likewise if
1138    // there were any delayed bugs, because codegen will likely cause
1139    // more ICEs, obscuring the original problem.
1140    if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1141        guar.raise_fatal();
1142    }
1143
1144    info!("Pre-codegen\n{:?}", tcx.debug_stats());
1145
1146    let (metadata, need_metadata_module) = rustc_metadata::fs::encode_and_write_metadata(tcx);
1147
1148    let codegen = tcx.sess.time("codegen_crate", move || {
1149        codegen_backend.codegen_crate(tcx, metadata, need_metadata_module)
1150    });
1151
1152    info!("Post-codegen\n{:?}", tcx.debug_stats());
1153
1154    // This must run after monomorphization so that all generic types
1155    // have been instantiated.
1156    if tcx.sess.opts.unstable_opts.print_type_sizes {
1157        tcx.sess.code_stats.print_type_sizes();
1158    }
1159
1160    codegen
1161}
1162
1163/// Compute and validate the crate name.
1164pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1165    // We validate *all* occurrences of `#![crate_name]`, pick the first find and
1166    // if a crate name was passed on the command line via `--crate-name` we enforce
1167    // that they match.
1168    // We perform the validation step here instead of later to ensure it gets run
1169    // in all code paths that require the crate name very early on, namely before
1170    // macro expansion.
1171
1172    let attr_crate_name =
1173        validate_and_find_value_str_builtin_attr(sym::crate_name, sess, krate_attrs);
1174
1175    let validate = |name, span| {
1176        rustc_session::output::validate_crate_name(sess, name, span);
1177        name
1178    };
1179
1180    if let Some(crate_name) = &sess.opts.crate_name {
1181        let crate_name = Symbol::intern(crate_name);
1182        if let Some((attr_crate_name, span)) = attr_crate_name
1183            && attr_crate_name != crate_name
1184        {
1185            sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1186                span,
1187                crate_name,
1188                attr_crate_name,
1189            });
1190        }
1191        return validate(crate_name, None);
1192    }
1193
1194    if let Some((crate_name, span)) = attr_crate_name {
1195        return validate(crate_name, Some(span));
1196    }
1197
1198    if let Input::File(ref path) = sess.io.input
1199        && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1200    {
1201        if file_stem.starts_with('-') {
1202            sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1203        } else {
1204            return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1205        }
1206    }
1207
1208    sym::rust_out
1209}
1210
1211fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1212    // We don't permit macro calls inside of the attribute (e.g., #![recursion_limit = `expand!()`])
1213    // because that would require expanding this while in the middle of expansion, which needs to
1214    // know the limit before expanding.
1215    let _ = validate_and_find_value_str_builtin_attr(sym::recursion_limit, sess, krate_attrs);
1216    crate::limits::get_recursion_limit(krate_attrs, sess)
1217}
1218
1219/// Validate *all* occurrences of the given "[value-str]" built-in attribute and return the first find.
1220///
1221/// This validator is intended for built-in attributes whose value needs to be known very early
1222/// during compilation (namely, before macro expansion) and it mainly exists to reject macro calls
1223/// inside of the attributes, such as in `#![name = expand!()]`. Normal attribute validation happens
1224/// during semantic analysis via [`TyCtxt::check_mod_attrs`] which happens *after* macro expansion
1225/// when such macro calls (here: `expand`) have already been expanded and we can no longer check for
1226/// their presence.
1227///
1228/// [value-str]: ast::Attribute::value_str
1229fn validate_and_find_value_str_builtin_attr(
1230    name: Symbol,
1231    sess: &Session,
1232    krate_attrs: &[ast::Attribute],
1233) -> Option<(Symbol, Span)> {
1234    let mut result = None;
1235    // Validate *all* relevant attributes, not just the first occurrence.
1236    for attr in ast::attr::filter_by_name(krate_attrs, name) {
1237        let Some(value) = attr.value_str() else {
1238            validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, attr, name)
1239        };
1240        // Choose the first occurrence as our result.
1241        result.get_or_insert((value, attr.span));
1242    }
1243    result
1244}