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