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