Skip to main content

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_ir::{Attribute, AttributeKind, find_attr};
10use rustc_attr_parsing::{AttributeParser, ShouldEmit};
11use rustc_codegen_ssa::traits::CodegenBackend;
12use rustc_codegen_ssa::{CompiledModules, CrateInfo};
13use rustc_crate_store::Untracked;
14use rustc_data_structures::indexmap::IndexMap;
15use rustc_data_structures::steal::Steal;
16use rustc_data_structures::sync::{
17    AppendOnlyIndexVec, DynSend, DynSync, FreezeLock, WorkerLocal, par_fns,
18};
19use rustc_data_structures::thousands;
20use rustc_errors::timings::TimingSection;
21use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
22use rustc_expand::base::{ExtCtxt, LintStoreExpand};
23use rustc_feature::Features;
24use rustc_fs_util::try_canonicalize;
25use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
26use rustc_hir::definitions::Definitions;
27use rustc_incremental::setup_dep_graph;
28use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
29use rustc_metadata::EncodedMetadata;
30use rustc_metadata::creader::CStore;
31use rustc_middle::arena::Arena;
32use rustc_middle::middle::resolve::{ResolverAstLowering, ResolverGlobalCtxt};
33use rustc_middle::ty::{self, RegisteredTools, TyCtxt};
34use rustc_middle::util::Providers;
35use rustc_parse::lexer::StripTokens;
36use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
37use rustc_passes::{abi_test, input_stats, layout_test};
38use rustc_resolve::{Resolver, ResolverOutputs};
39use rustc_session::config::{Input, OutFileName, OutputFilenames, OutputType};
40use rustc_session::diagnostics::feature_err;
41use rustc_session::output::{filename_for_input, invalid_output_for_target};
42use rustc_session::search_paths::PathKind;
43use rustc_session::{IncrCompSession, Session};
44use rustc_span::{
45    DUMMY_SP, ErrorGuaranteed, ExpnKind, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
46};
47use rustc_structures::{CrateType, Limit};
48use rustc_trait_selection::{solve, traits};
49use tracing::{info, instrument};
50
51use crate::interface::Compiler;
52use crate::{diagnostics, limits, util};
53
54pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
55    let mut krate = sess
56        .time("parse_crate", || {
57            let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
58                Input::File(file) => new_parser_from_file(
59                    &sess.psess,
60                    file,
61                    StripTokens::ShebangAndFrontmatter,
62                    None,
63                ),
64                Input::Str { input, name } => new_parser_from_source_str(
65                    &sess.psess,
66                    name.clone(),
67                    input.clone(),
68                    StripTokens::ShebangAndFrontmatter,
69                ),
70            });
71            parser.parse_crate_mod()
72        })
73        .unwrap_or_else(|parse_error| {
74            let guar: ErrorGuaranteed = parse_error.emit_err();
75            guar.raise_fatal();
76        });
77
78    rustc_builtin_macros::cmdline_attrs::inject(
79        &mut krate,
80        &sess.psess,
81        &sess.opts.unstable_opts.crate_attr,
82    );
83
84    krate
85}
86
87fn pre_expansion_lint<'a>(
88    sess: &Session,
89    features: &Features,
90    lint_store: &LintStore,
91    registered_lint_tools: &RegisteredTools,
92    check_node: EarlyCheckNode<'a>,
93    node_name: Symbol,
94) {
95    sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
96        || {
97            rustc_lint::check_ast_node(
98                sess,
99                features,
100                true,
101                lint_store,
102                registered_lint_tools,
103                None,
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_lint_tools: &RegisteredTools,
119        node_id: ast::NodeId,
120        attrs: &[ast::Attribute],
121        items: &[Box<ast::Item>],
122        name: Symbol,
123    ) {
124        let check_node = EarlyCheckNode::LoadedMod(node_id, attrs, items);
125        pre_expansion_lint(sess, features, self.0, registered_lint_tools, check_node, name);
126    }
127}
128
129/// Runs the "early phases" of the compiler: initial `cfg` processing,
130/// syntax expansion, secondary `cfg` expansion, synthesis of a test
131/// harness if one is to be provided, injection of a dependency on the
132/// standard library and prelude, and name resolution.
133{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("configure_and_expand",
                                    "rustc_interface::passes", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs"),
                                    ::tracing_core::__macro_support::Option::Some(133u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pre_configured_attrs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pre_configured_attrs");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pre_configured_attrs)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ast::Crate = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = resolver.tcx();
            let sess = tcx.sess;
            let features = tcx.features();
            let lint_store = unerased_lint_store(sess);
            let crate_name = tcx.crate_name(LOCAL_CRATE);
            pre_expansion_lint(sess, features, lint_store,
                tcx.registered_lint_tools(()),
                EarlyCheckNode::CrateRoot(&krate, pre_configured_attrs),
                crate_name);
            rustc_builtin_macros::register_builtin_macros(resolver);
            let num_standard_library_imports =
                sess.time("crate_injection",
                    ||
                        {
                            rustc_builtin_macros::standard_library_imports::inject(&mut krate,
                                pre_configured_attrs, resolver, sess, features)
                        });
            krate =
                sess.time("macro_expand_crate",
                    ||
                        {
                            let mut old_path = OsString::new();
                            if false {
                                old_path = env::var_os("PATH").unwrap_or(old_path);
                                let mut new_path =
                                    Vec::from_iter(sess.host_filesearch().search_paths(PathKind::Native).map(|p|
                                                p.dir.to_path_buf()));
                                for path in env::split_paths(&old_path) {
                                    if !new_path.contains(&path) { new_path.push(path); }
                                }
                                unsafe {
                                    env::set_var("PATH",
                                        env::join_paths(new_path.iter().filter(|p|
                                                        env::join_paths(iter::once(p)).is_ok())).unwrap());
                                }
                            }
                            let recursion_limit =
                                get_recursion_limit(pre_configured_attrs, sess);
                            let cfg =
                                rustc_expand::expand::ExpansionConfig {
                                    crate_name,
                                    features,
                                    recursion_limit,
                                    trace_mac: sess.opts.unstable_opts.trace_macros,
                                    should_test: sess.is_test_crate(),
                                    span_debug: sess.opts.unstable_opts.span_debug,
                                    proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
                                };
                            let lint_store = LintStoreExpandImpl(lint_store);
                            let mut ecx =
                                ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
                            ecx.num_standard_library_imports =
                                num_standard_library_imports;
                            let krate =
                                sess.time("expand_crate",
                                    || ecx.monotonic_expander().expand_crate(krate));
                            if ecx.nb_macro_errors > 0 { sess.dcx().abort_if_errors(); }
                            sess.psess.buffered_lints.with_lock(|buffered_lints:
                                        &mut Vec<BufferedEarlyLint>|
                                    { buffered_lints.append(&mut ecx.buffered_early_lint); });
                            sess.time("check_unused_macros",
                                || { ecx.check_unused_macros(); });
                            if ecx.reduced_recursion_limit.is_some() {
                                sess.dcx().abort_if_errors();
                                ::core::panicking::panic("internal error: entered unreachable code");
                            }
                            if false { unsafe { env::set_var("PATH", &old_path); } }
                            if ecx.sess.opts.unstable_opts.macro_stats {
                                print_macro_stats(&ecx);
                            }
                            krate
                        });
            sess.time("maybe_building_test_harness",
                ||
                    {
                        rustc_builtin_macros::test_harness::inject(&mut krate, sess,
                            features, resolver)
                    });
            let has_proc_macro_decls =
                sess.time("AST_validation",
                    ||
                        {
                            rustc_ast_passes::ast_validation::check_crate(sess,
                                features, &krate, tcx.is_sdylib_interface_build(),
                                resolver.lint_buffer())
                        });
            let crate_types = tcx.crate_types();
            let is_executable_crate =
                crate_types.contains(&CrateType::Executable);
            let is_proc_macro_crate =
                crate_types.contains(&CrateType::ProcMacro);
            if crate_types.len() > 1 {
                if is_executable_crate {
                    sess.dcx().emit_err(diagnostics::MixedBinCrate);
                }
                if is_proc_macro_crate {
                    sess.dcx().emit_err(diagnostics::MixedProcMacroCrate);
                }
            }
            if is_proc_macro_crate && sess.target.is_like_wasm &&
                    !sess.opts.unstable_opts.wasm_proc_macros {
                sess.dcx().emit_err(diagnostics::UnstableWasmProcMacro);
            }
            if crate_types.contains(&CrateType::Sdylib) &&
                    !tcx.features().export_stable() {
                feature_err(sess, sym::export_stable, DUMMY_SP,
                        "`sdylib` crate type is unstable").emit();
            }
            if is_proc_macro_crate && !sess.sanitizers().is_empty() {
                sess.dcx().emit_err(diagnostics::CannotSanitizeProcMacro);
            }
            if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
                sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort);
            }
            sess.time("maybe_create_a_macro_crate",
                ||
                    {
                        let is_test_crate = sess.is_test_crate();
                        rustc_builtin_macros::proc_macro_harness::inject(&mut krate,
                            sess, features, resolver, is_proc_macro_crate,
                            has_proc_macro_decls, is_test_crate, sess.dcx())
                    });
            resolver.resolve_crate(&krate);
            CStore::from_tcx(tcx).report_session_incompatibilities(tcx,
                &krate);
            krate
        }
    }
}#[instrument(level = "trace", skip(krate, resolver))]
134fn configure_and_expand(
135    mut krate: ast::Crate,
136    pre_configured_attrs: &[ast::Attribute],
137    resolver: &mut Resolver<'_, '_>,
138) -> ast::Crate {
139    let tcx = resolver.tcx();
140    let sess = tcx.sess;
141    let features = tcx.features();
142    let lint_store = unerased_lint_store(sess);
143    let crate_name = tcx.crate_name(LOCAL_CRATE);
144    pre_expansion_lint(
145        sess,
146        features,
147        lint_store,
148        tcx.registered_lint_tools(()),
149        EarlyCheckNode::CrateRoot(&krate, pre_configured_attrs),
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    // Expand all macros
165    krate = sess.time("macro_expand_crate", || {
166        // Windows dlls do not have rpaths, so they don't know how to find their
167        // dependencies. It's up to us to tell the system where to find all the
168        // dependent dlls. Note that this uses cfg!(windows) as opposed to
169        // targ_cfg because syntax extensions are always loaded for the host
170        // compiler, not for the target.
171        //
172        // This is somewhat of an inherently racy operation, however, as
173        // multiple threads calling this function could possibly continue
174        // extending PATH far beyond what it should. To solve this for now we
175        // just don't add any new elements to PATH which are already there
176        // within PATH. This is basically a targeted fix at #17360 for rustdoc
177        // which runs rustc in parallel but has been seen (#33844) to cause
178        // problems with PATH becoming too long.
179        let mut old_path = OsString::new();
180        if cfg!(windows) {
181            old_path = env::var_os("PATH").unwrap_or(old_path);
182            let mut new_path = Vec::from_iter(
183                sess.host_filesearch().search_paths(PathKind::Native).map(|p| p.dir.to_path_buf()),
184            );
185            for path in env::split_paths(&old_path) {
186                if !new_path.contains(&path) {
187                    new_path.push(path);
188                }
189            }
190            unsafe {
191                env::set_var(
192                    "PATH",
193                    env::join_paths(
194                        new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
195                    )
196                    .unwrap(),
197                );
198            }
199        }
200
201        // Create the config for macro expansion
202        let recursion_limit = get_recursion_limit(pre_configured_attrs, sess);
203        let cfg = rustc_expand::expand::ExpansionConfig {
204            crate_name,
205            features,
206            recursion_limit,
207            trace_mac: sess.opts.unstable_opts.trace_macros,
208            should_test: sess.is_test_crate(),
209            span_debug: sess.opts.unstable_opts.span_debug,
210            proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
211        };
212
213        let lint_store = LintStoreExpandImpl(lint_store);
214        let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
215        ecx.num_standard_library_imports = num_standard_library_imports;
216        // Expand macros now!
217        let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
218
219        if ecx.nb_macro_errors > 0 {
220            sess.dcx().abort_if_errors();
221        }
222
223        // The rest is error reporting and stats
224
225        sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
226            buffered_lints.append(&mut ecx.buffered_early_lint);
227        });
228
229        sess.time("check_unused_macros", || {
230            ecx.check_unused_macros();
231        });
232
233        // If we hit a recursion limit, exit early to avoid later passes getting overwhelmed
234        // with a large AST
235        if ecx.reduced_recursion_limit.is_some() {
236            sess.dcx().abort_if_errors();
237            unreachable!();
238        }
239
240        if cfg!(windows) {
241            unsafe {
242                env::set_var("PATH", &old_path);
243            }
244        }
245
246        if ecx.sess.opts.unstable_opts.macro_stats {
247            print_macro_stats(&ecx);
248        }
249
250        krate
251    });
252
253    sess.time("maybe_building_test_harness", || {
254        rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
255    });
256
257    let has_proc_macro_decls = sess.time("AST_validation", || {
258        rustc_ast_passes::ast_validation::check_crate(
259            sess,
260            features,
261            &krate,
262            tcx.is_sdylib_interface_build(),
263            resolver.lint_buffer(),
264        )
265    });
266
267    let crate_types = tcx.crate_types();
268    let is_executable_crate = crate_types.contains(&CrateType::Executable);
269    let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
270
271    if crate_types.len() > 1 {
272        if is_executable_crate {
273            sess.dcx().emit_err(diagnostics::MixedBinCrate);
274        }
275        if is_proc_macro_crate {
276            sess.dcx().emit_err(diagnostics::MixedProcMacroCrate);
277        }
278    }
279
280    if is_proc_macro_crate && sess.target.is_like_wasm && !sess.opts.unstable_opts.wasm_proc_macros
281    {
282        sess.dcx().emit_err(diagnostics::UnstableWasmProcMacro);
283    }
284
285    if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
286        feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
287    }
288
289    if is_proc_macro_crate && !sess.sanitizers().is_empty() {
290        sess.dcx().emit_err(diagnostics::CannotSanitizeProcMacro);
291    }
292
293    if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
294        sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort);
295    }
296
297    sess.time("maybe_create_a_macro_crate", || {
298        let is_test_crate = sess.is_test_crate();
299        rustc_builtin_macros::proc_macro_harness::inject(
300            &mut krate,
301            sess,
302            features,
303            resolver,
304            is_proc_macro_crate,
305            has_proc_macro_decls,
306            is_test_crate,
307            sess.dcx(),
308        )
309    });
310
311    // Done with macro expansion!
312
313    resolver.resolve_crate(&krate);
314
315    CStore::from_tcx(tcx).report_session_incompatibilities(tcx, &krate);
316    krate
317}
318
319fn print_macro_stats(ecx: &ExtCtxt<'_>) {
320    use std::fmt::Write;
321
322    let crate_name = ecx.ecfg.crate_name.as_str();
323    let crate_name = if crate_name == "build_script_build" {
324        // This is a build script. Get the package name from the environment.
325        let pkg_name =
326            std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
327        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} build script", pkg_name))
    })format!("{pkg_name} build script")
328    } else {
329        crate_name.to_string()
330    };
331
332    // No instability because we immediately sort the produced vector.
333    #[allow(rustc::potential_query_instability)]
334    let mut macro_stats: Vec<_> = ecx
335        .macro_stats
336        .iter()
337        .map(|((name, kind), stat)| {
338            // This gives the desired sort order: sort by bytes, then lines, etc.
339            (stat.bytes, stat.lines, stat.uses, name, *kind)
340        })
341        .collect();
342    macro_stats.sort_unstable();
343    macro_stats.reverse(); // bigger items first
344
345    let prefix = "macro-stats";
346    let name_w = 32;
347    let uses_w = 7;
348    let lines_w = 11;
349    let avg_lines_w = 11;
350    let bytes_w = 11;
351    let avg_bytes_w = 11;
352    let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
353
354    // We write all the text into a string and print it with a single
355    // `eprint!`. This is an attempt to minimize interleaved text if multiple
356    // rustc processes are printing macro-stats at the same time (e.g. with
357    // `RUSTFLAGS='-Zmacro-stats' cargo build`). It still doesn't guarantee
358    // non-interleaving, though.
359    let mut s = String::new();
360    _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
361    _ = s.write_fmt(format_args!("{1} MACRO EXPANSION STATS: {0}\n", crate_name,
        prefix))writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
362    _ = s.write_fmt(format_args!("{6} {0:<7$}{1:>8$}{2:>9$}{3:>10$}{4:>11$}{5:>12$}\n",
        "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
        prefix, name_w, uses_w, lines_w, avg_lines_w, bytes_w, avg_bytes_w))writeln!(
363        s,
364        "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
365        "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
366    );
367    _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
368    // It's helpful to print something when there are no entries, otherwise it
369    // might look like something went wrong.
370    if macro_stats.is_empty() {
371        _ = s.write_fmt(format_args!("{0} (none)\n", prefix))writeln!(s, "{prefix} (none)");
372    }
373    for (bytes, lines, uses, name, kind) in macro_stats {
374        let mut name = ExpnKind::Macro(kind, *name).descr();
375        let uses_with_underscores = thousands::usize_with_underscores(uses);
376        let avg_lines = lines as f64 / uses as f64;
377        let avg_bytes = bytes as f64 / uses as f64;
378
379        // Ensure the "Macro Name" and "Uses" columns are as compact as possible.
380        let mut uses_w = uses_w;
381        if name.len() + uses_with_underscores.len() >= name_w + uses_w {
382            // The name would abut or overlap the uses value. Print the name
383            // on a line by itself, then set the name to empty and print things
384            // normally, to show the stats on the next line.
385            _ = s.write_fmt(format_args!("{1} {0:<2$}\n", name, prefix, name_w))writeln!(s, "{prefix} {:<name_w$}", name);
386            name = String::new();
387        } else if name.len() >= name_w {
388            // The name won't abut or overlap with the uses value, but it does
389            // overlap with the empty part of the uses column. Shrink the width
390            // of the uses column to account for the excess name length.
391            uses_w -= name.len() - name_w;
392        };
393
394        _ = s.write_fmt(format_args!("{6} {0:<7$}{1:>8$}{2:>9$}{3:>10$}{4:>11$}{5:>12$}\n",
        name, uses_with_underscores, thousands::usize_with_underscores(lines),
        thousands::f64p1_with_underscores(avg_lines),
        thousands::usize_with_underscores(bytes),
        thousands::f64p1_with_underscores(avg_bytes), prefix, name_w, uses_w,
        lines_w, avg_lines_w, bytes_w, avg_bytes_w))writeln!(
395            s,
396            "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
397            name,
398            uses_with_underscores,
399            thousands::usize_with_underscores(lines),
400            thousands::f64p1_with_underscores(avg_lines),
401            thousands::usize_with_underscores(bytes),
402            thousands::f64p1_with_underscores(avg_bytes),
403        );
404    }
405    _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
406    { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
407}
408
409fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
410    let sess = tcx.sess;
411    let (resolver, krate) = tcx.resolver_for_lowering();
412    let resolver = &*resolver.borrow();
413    let krate = &*krate.borrow();
414    let mut lint_buffer = resolver.lint_buffer.steal();
415
416    if sess.opts.unstable_opts.input_stats {
417        input_stats::print_ast_stats(tcx, krate);
418    }
419
420    // Needs to go *after* expansion to be able to check the results of macro expansion.
421    sess.time("complete_gated_feature_checking", || {
422        rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
423    });
424
425    // Add all buffered lints from the `ParseSess` to the `Session`.
426    sess.psess.buffered_lints.with_lock(|buffered_lints| {
427        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs:427",
                        "rustc_interface::passes", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(427u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} parse sess buffered_lints",
                                                    buffered_lints.len()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("{} parse sess buffered_lints", buffered_lints.len());
428        for early_lint in buffered_lints.drain(..) {
429            lint_buffer.add_early_lint(early_lint);
430        }
431    });
432
433    // Gate identifiers containing invalid Unicode codepoints that were recovered during lexing.
434    sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
435        for (ident, mut spans) in identifiers.drain(..) {
436            spans.sort();
437            if ident == sym::ferris {
438                enum FerrisFix {
439                    SnakeCase,
440                    ScreamingSnakeCase,
441                    PascalCase,
442                }
443
444                impl FerrisFix {
445                    const fn as_str(self) -> &'static str {
446                        match self {
447                            FerrisFix::SnakeCase => "ferris",
448                            FerrisFix::ScreamingSnakeCase => "FERRIS",
449                            FerrisFix::PascalCase => "Ferris",
450                        }
451                    }
452                }
453
454                let first_span = spans[0];
455                let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
456                let ferris_fix = prev_source
457                    .map_or(FerrisFix::SnakeCase, |source| {
458                        let mut source_before_ferris = source.split_whitespace().rev();
459                        match source_before_ferris.next() {
460                            Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
461                                FerrisFix::PascalCase
462                            }
463                            Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
464                            Some("mut") if source_before_ferris.next() == Some("static") => {
465                                FerrisFix::ScreamingSnakeCase
466                            }
467                            _ => FerrisFix::SnakeCase,
468                        }
469                    })
470                    .as_str();
471
472                sess.dcx().emit_err(diagnostics::FerrisIdentifier {
473                    spans,
474                    first_span,
475                    ferris_fix,
476                });
477            } else {
478                sess.dcx().emit_err(diagnostics::EmojiIdentifier { spans, ident });
479            }
480        }
481    });
482
483    let lint_store = unerased_lint_store(tcx.sess);
484    rustc_lint::check_ast_node(
485        sess,
486        tcx.features(),
487        false,
488        lint_store,
489        tcx.registered_lint_tools(()),
490        Some(lint_buffer),
491        EarlyCheckNode::CrateRoot(&*krate, &*krate.attrs),
492    )
493}
494
495fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
496    let value = env::var_os(key);
497
498    let value_tcx = value.as_ref().map(|value| tcx.arena.alloc_os_str(value));
499
500    // Also add the variable to Cargo's dependency tracking
501    //
502    // NOTE: This only works for passes run before `write_dep_info`. See that
503    // for extension points for configuring environment variables to be
504    // properly change-tracked.
505    tcx.sess.env_depinfo.borrow_mut().insert((
506        Symbol::intern(&key.to_string_lossy()),
507        value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(value)),
508    ));
509
510    value_tcx
511}
512
513// Returns all the paths that correspond to generated files.
514fn generated_output_paths(
515    tcx: TyCtxt<'_>,
516    outputs: &OutputFilenames,
517    exact_name: bool,
518    crate_name: Symbol,
519) -> Vec<PathBuf> {
520    let sess = tcx.sess;
521    let mut out_filenames = Vec::new();
522    for output_type in sess.opts.output_types.keys() {
523        let out_filename = outputs.path(*output_type);
524        let file = out_filename.as_path().to_path_buf();
525        match *output_type {
526            // If the filename has been overridden using `-o`, it will not be modified
527            // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
528            OutputType::Exe if !exact_name => {
529                for crate_type in tcx.crate_types().iter() {
530                    let p = filename_for_input(sess, *crate_type, crate_name, outputs);
531                    out_filenames.push(p.as_path().to_path_buf());
532                }
533            }
534            OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
535                // Don't add the dep-info output when omitting it from dep-info targets
536            }
537            OutputType::DepInfo if out_filename.is_stdout() => {
538                // Don't add the dep-info output when it goes to stdout
539            }
540            _ => {
541                out_filenames.push(file);
542            }
543        }
544    }
545    out_filenames
546}
547
548fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
549    let input_path = try_canonicalize(input_path).ok();
550    if input_path.is_none() {
551        return false;
552    }
553    output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
554}
555
556fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
557    output_paths.iter().find(|output_path| output_path.is_dir())
558}
559
560fn escape_dep_filename(filename: &str) -> String {
561    // Apparently clang and gcc *only* escape spaces:
562    // https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
563    filename.replace(' ', "\\ ")
564}
565
566// Makefile comments only need escaping newlines and `\`.
567// The result can be unescaped by anything that can unescape `escape_default` and friends.
568fn escape_dep_env(symbol: Symbol) -> String {
569    let s = symbol.as_str();
570    let mut escaped = String::with_capacity(s.len());
571    for c in s.chars() {
572        match c {
573            '\n' => escaped.push_str(r"\n"),
574            '\r' => escaped.push_str(r"\r"),
575            '\\' => escaped.push_str(r"\\"),
576            _ => escaped.push(c),
577        }
578    }
579    escaped
580}
581
582fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
583    // Write out dependency rules to the dep-info file if requested
584    let sess = tcx.sess;
585    if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
586        return;
587    }
588    let deps_output = outputs.path(OutputType::DepInfo);
589    let deps_filename = deps_output.as_path();
590
591    let result = try {
592        // Build a list of files used to compile the output and
593        // write Makefile-compatible dependency rules
594        let mut files: IndexMap<String, (u64, Option<SourceFileHash>)> = sess
595            .source_map()
596            .files()
597            .iter()
598            .filter(|fmap| fmap.is_real_file())
599            .filter(|fmap| !fmap.is_imported())
600            .map(|fmap| {
601                (
602                    escape_dep_filename(&fmap.name.prefer_local_unconditionally().to_string()),
603                    (
604                        // This needs to be unnormalized,
605                        // as external tools wouldn't know how rustc normalizes them
606                        fmap.unnormalized_source_len as u64,
607                        fmap.checksum_hash,
608                    ),
609                )
610            })
611            .collect();
612
613        let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
614
615        // Account for explicitly marked-to-track files
616        // (e.g. accessed in proc macros).
617        let file_depinfo = sess.file_depinfo.borrow();
618
619        let normalize_path = |path: PathBuf| escape_dep_filename(&path.to_string_lossy());
620
621        // The entries will be used to declare dependencies between files in a
622        // Makefile-like output, so the iteration order does not matter.
623        fn hash_iter_files<P: AsRef<Path>>(
624            it: impl Iterator<Item = P>,
625            checksum_hash_algo: Option<SourceFileHashAlgorithm>,
626        ) -> impl Iterator<Item = (P, (u64, Option<SourceFileHash>))> {
627            it.map(move |path| {
628                match checksum_hash_algo.and_then(|algo| {
629                    fs::File::open(path.as_ref())
630                        .and_then(|mut file| {
631                            SourceFileHash::new(algo, &mut file).map(|h| (file, h))
632                        })
633                        .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
634                        .map_err(|e| {
635                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs:635",
                        "rustc_interface::passes", ::tracing::Level::ERROR,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(635u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::ERROR <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::ERROR <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("failed to compute checksum, omitting it from dep-info {0} {1}",
                                                    path.as_ref().display(), e) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
}tracing::error!(
636                                "failed to compute checksum, omitting it from dep-info {} {e}",
637                                path.as_ref().display()
638                            )
639                        })
640                        .ok()
641                }) {
642                    Some((file_len, checksum)) => (path, (file_len, Some(checksum))),
643                    None => (path, (0, None)),
644                }
645            })
646        }
647
648        let extra_tracked_files = hash_iter_files(
649            file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
650            checksum_hash_algo,
651        );
652        files.extend(extra_tracked_files);
653
654        // We also need to track used PGO profile files
655        if let Some(ref profile_instr) = sess.opts.cg.profile_use {
656            files.extend(hash_iter_files(
657                iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
658                checksum_hash_algo,
659            ));
660        }
661        if let Some(ref profile_sample) = sess.opts.cg.profile_sample_use {
662            files.extend(hash_iter_files(
663                iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
664                checksum_hash_algo,
665            ));
666        }
667
668        // Debugger visualizer files
669        for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
670            files.extend(hash_iter_files(
671                iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
672                checksum_hash_algo,
673            ));
674        }
675
676        if sess.binary_dep_depinfo() {
677            if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
678                if backend.contains('.') {
679                    // If the backend name contain a `.`, it is the path to an external dynamic
680                    // library. If not, it is not a path.
681                    files.extend(hash_iter_files(
682                        iter::once(backend.to_string()),
683                        checksum_hash_algo,
684                    ));
685                }
686            }
687
688            for &cnum in tcx.crates(()) {
689                let source = tcx.used_crate_source(cnum);
690                if let Some(path) = &source.dylib {
691                    files.extend(hash_iter_files(
692                        iter::once(escape_dep_filename(&path.display().to_string())),
693                        checksum_hash_algo,
694                    ));
695                }
696                if let Some(path) = &source.rlib {
697                    files.extend(hash_iter_files(
698                        iter::once(escape_dep_filename(&path.display().to_string())),
699                        checksum_hash_algo,
700                    ));
701                }
702                if let Some(path) = &source.rmeta {
703                    files.extend(hash_iter_files(
704                        iter::once(escape_dep_filename(&path.display().to_string())),
705                        checksum_hash_algo,
706                    ));
707                }
708            }
709        }
710
711        let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
712            for path in out_filenames {
713                file.write_fmt(format_args!("{0}: {1}\n\n", path.display(),
        files.keys().map(String::as_str).intersperse(" ").collect::<String>()))writeln!(
714                    file,
715                    "{}: {}\n",
716                    path.display(),
717                    files.keys().map(String::as_str).intersperse(" ").collect::<String>()
718                )?;
719            }
720
721            // Emit a fake target for each input file to the compilation. This
722            // prevents `make` from spitting out an error if a file is later
723            // deleted. For more info see #28735
724            for path in files.keys() {
725                file.write_fmt(format_args!("{0}:\n", path))writeln!(file, "{path}:")?;
726            }
727
728            // Emit special comments with information about accessed environment variables.
729            let env_depinfo = sess.env_depinfo.borrow();
730            if !env_depinfo.is_empty() {
731                // We will soon sort, so the initial order does not matter.
732                #[allow(rustc::potential_query_instability)]
733                let mut envs: Vec<_> = env_depinfo
734                    .iter()
735                    .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
736                    .collect();
737                envs.sort_unstable();
738                file.write_fmt(format_args!("\n"))writeln!(file)?;
739                for (k, v) in envs {
740                    file.write_fmt(format_args!("# env-dep:{0}", k))write!(file, "# env-dep:{k}")?;
741                    if let Some(v) = v {
742                        file.write_fmt(format_args!("={0}", v))write!(file, "={v}")?;
743                    }
744                    file.write_fmt(format_args!("\n"))writeln!(file)?;
745                }
746            }
747
748            // If caller requested this information, add special comments about source file checksums.
749            // These are not necessarily the same checksums as was used in the debug files.
750            if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
751                files
752                    .iter()
753                    .filter_map(|(path, (file_len, hash_algo))| {
754                        hash_algo.map(|hash_algo| (path, file_len, hash_algo))
755                    })
756                    .try_for_each(|(path, file_len, checksum_hash)| {
757                        file.write_fmt(format_args!("# checksum:{0} file_len:{1} {2}\n",
        checksum_hash, file_len, path))writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
758                    })?;
759            }
760
761            Ok(())
762        };
763
764        match deps_output {
765            OutFileName::Stdout => {
766                let mut file = BufWriter::new(io::stdout());
767                write_deps_to_file(&mut file)?;
768            }
769            OutFileName::Real(ref path) => {
770                let mut file = fs::File::create_buffered(path)?;
771                write_deps_to_file(&mut file)?;
772            }
773        }
774    };
775
776    match result {
777        Ok(_) => {
778            if sess.opts.json_artifact_notifications {
779                sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
780            }
781        }
782        Err(error) => {
783            sess.dcx()
784                .emit_fatal(diagnostics::ErrorWritingDependencies { path: deps_filename, error });
785        }
786    }
787}
788
789fn resolver_for_lowering_raw<'tcx>(
790    tcx: TyCtxt<'tcx>,
791    (): (),
792) -> (&'tcx Steal<ResolverAstLowering<'tcx>>, &'tcx Steal<ast::Crate>, &'tcx ResolverGlobalCtxt) {
793    let arenas = WorkerLocal::new(|_| Resolver::arenas());
794    let _ = tcx.registered_attr_tools(()); // Uses `crate_for_resolver`.
795    let _ = tcx.registered_lint_tools(()); // Uses `crate_for_resolver`.
796    let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
797    let mut resolver = Resolver::new(
798        tcx,
799        &pre_configured_attrs,
800        krate.spans.inner_span,
801        krate.spans.inject_use_span,
802        &arenas,
803    );
804    let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
805
806    // Don't mutate the cstore or stable crate id map from here on.
807    tcx.untracked().freeze_cstore();
808
809    let ResolverOutputs {
810        global_ctxt: untracked_resolutions,
811        ast_lowering: untracked_resolver_for_lowering,
812    } = resolver.into_outputs();
813
814    (
815        tcx.arena.alloc(Steal::new(untracked_resolver_for_lowering)),
816        tcx.arena.alloc(Steal::new(krate)),
817        tcx.arena.alloc(untracked_resolutions),
818    )
819}
820
821pub fn write_dep_info(tcx: TyCtxt<'_>) {
822    // Make sure name resolution and macro expansion is run for
823    // the side-effect of providing a complete set of all
824    // accessed files and env vars.
825    let _ = tcx.resolver_for_lowering();
826
827    let sess = tcx.sess;
828    let _timer = sess.timer("write_dep_info");
829    let crate_name = tcx.crate_name(LOCAL_CRATE);
830
831    let outputs = tcx.output_filenames(());
832    let output_paths =
833        generated_output_paths(tcx, outputs, sess.io.output_file.is_some(), crate_name);
834
835    // Ensure the source file isn't accidentally overwritten during compilation.
836    if let Some(input_path) = sess.io.input.opt_path() {
837        if sess.opts.will_create_output_file() {
838            if output_contains_path(&output_paths, input_path) {
839                sess.dcx()
840                    .emit_fatal(diagnostics::InputFileWouldBeOverWritten { path: input_path });
841            }
842            if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
843                sess.dcx().emit_fatal(diagnostics::GeneratedFileConflictsWithDirectory {
844                    input_path,
845                    dir_path,
846                });
847            }
848        }
849    }
850
851    if let Some(ref dir) = sess.io.temps_dir {
852        if fs::create_dir_all(dir).is_err() {
853            sess.dcx().emit_fatal(diagnostics::TempsDirError);
854        }
855    }
856
857    write_out_deps(tcx, outputs, &output_paths);
858
859    let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
860        && sess.opts.output_types.len() == 1;
861
862    if !only_dep_info {
863        if let Some(ref dir) = sess.io.output_dir {
864            if fs::create_dir_all(dir).is_err() {
865                sess.dcx().emit_fatal(diagnostics::OutDirError);
866            }
867        }
868    }
869}
870
871pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
872    if !tcx.crate_types().contains(&rustc_structures::CrateType::Sdylib) {
873        return;
874    }
875    let _timer = tcx.sess.timer("write_interface");
876    let (_, krate) = tcx.resolver_for_lowering();
877
878    let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
879        &*krate.borrow(),
880        tcx.sess.psess.edition,
881        &tcx.sess.psess.attr_id_generator,
882    );
883    let export_output = tcx.output_filenames(()).interface_path();
884    let mut file = fs::File::create_buffered(&export_output).unwrap_or_else(|error| {
885        tcx.dcx().emit_fatal(diagnostics::FailedWritingFile { path: &export_output, error })
886    });
887    if let Err(error) = file.write_fmt(format_args!("{0}", krate))write!(file, "{}", krate) {
888        tcx.dcx().emit_fatal(diagnostics::FailedWritingFile { path: &export_output, error });
889    }
890}
891
892pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
893    let providers = &mut Providers::default();
894    providers.queries.analysis = analysis;
895    providers.queries.resolver_for_lowering_raw = resolver_for_lowering_raw;
896    providers.queries.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
897    providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).2;
898    providers.queries.early_lint_checks = early_lint_checks;
899    providers.queries.env_var_os = env_var_os;
900    providers.queries.proc_macro_decls_static = |tcx, _| tcx.hir_crate_items(()).proc_macro_decls();
901    rustc_ast_lowering::provide(&mut providers.queries);
902    limits::provide(&mut providers.queries);
903    rustc_expand_queries::provide(&mut providers.queries);
904    rustc_const_eval::provide(providers);
905    rustc_middle::hir::provide(&mut providers.queries);
906    rustc_borrowck::provide(&mut providers.queries);
907    rustc_incremental::provide(providers);
908    rustc_mir_build::provide(providers);
909    rustc_mir_transform::provide(providers);
910    rustc_monomorphize::provide(providers);
911    rustc_privacy::provide(&mut providers.queries);
912    rustc_query_impl::provide(providers);
913    rustc_resolve::provide(&mut providers.queries);
914    rustc_hir_analysis::provide(&mut providers.queries);
915    rustc_hir_typeck::provide(&mut providers.queries);
916    ty::provide(&mut providers.queries);
917    traits::provide(&mut providers.queries);
918    solve::provide(&mut providers.queries);
919    rustc_passes::provide(&mut providers.queries);
920    rustc_traits::provide(&mut providers.queries);
921    rustc_ty_utils::provide(&mut providers.queries);
922    rustc_metadata::provide(providers);
923    rustc_lint::provide(&mut providers.queries);
924    rustc_symbol_mangling::provide(&mut providers.queries);
925    rustc_codegen_ssa::provide(providers);
926    *providers
927});
928
929pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
930    compiler: &Compiler,
931    krate: rustc_ast::Crate,
932    f: F,
933) -> (T, Option<IncrCompSession>) {
934    let sess = &compiler.sess;
935
936    let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
937
938    let crate_name = get_crate_name(sess, &pre_configured_attrs);
939    let crate_types = collect_crate_types(
940        sess,
941        &compiler.codegen_backend.supported_crate_types(sess),
942        compiler.codegen_backend.name(),
943        &pre_configured_attrs,
944        krate.spans.inner_span,
945    );
946    let stable_crate_id = StableCrateId::new(
947        crate_name,
948        crate_types.contains(&CrateType::Executable),
949        sess.opts.cg.metadata.clone(),
950        sess.cfg_version,
951    );
952
953    let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
954
955    let (dep_graph, incr_comp_session) = setup_dep_graph(sess, crate_name, stable_crate_id);
956
957    let cstore =
958        FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
959    let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
960
961    let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
962    let untracked = Untracked {
963        cstore,
964        source_span: AppendOnlyIndexVec::new(),
965        definitions,
966        stable_crate_ids,
967        local_crate_hash: OnceLock::new(),
968    };
969
970    // We're constructing the HIR here; we don't care what we will
971    // read, since we haven't even constructed the *input* to
972    // incr. comp. yet.
973    dep_graph.assert_ignored();
974
975    let query_result_on_disk_cache =
976        rustc_incremental::load_query_result_cache(sess, incr_comp_session.as_ref());
977
978    let codegen_backend = &compiler.codegen_backend;
979    let mut providers = *DEFAULT_QUERY_PROVIDERS;
980    codegen_backend.provide(&mut providers);
981
982    if let Some(callback) = compiler.override_queries {
983        callback(sess, &mut providers);
984    }
985
986    let incremental = dep_graph.is_fully_enabled();
987
988    // Note: this function body is the origin point of the widely-used 'tcx lifetime.
989    //
990    // `gcx_cell` is defined here and `&gcx_cell` is passed to `create_global_ctxt`, which then
991    // actually creates the `GlobalCtxt` with a `gcx_cell.get_or_init(...)` call. This is done so
992    // that the resulting reference has the type `&'tcx GlobalCtxt<'tcx>`, which is what `TyCtxt`
993    // needs. If we defined and created the `GlobalCtxt` within `create_global_ctxt` then its type
994    // would be `&'a GlobalCtxt<'tcx>`, with two lifetimes.
995    //
996    // Similarly, by creating `arena` here and passing in `&arena`, that reference has the type
997    // `&'tcx WorkerLocal<Arena<'tcx>>`, also with one lifetime. And likewise for `hir_arena`.
998
999    let gcx_cell = OnceLock::new();
1000    let arena = WorkerLocal::new(|_| Arena::default());
1001    let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
1002
1003    let res = TyCtxt::create_global_ctxt(
1004        &gcx_cell,
1005        &compiler.sess,
1006        crate_types,
1007        stable_crate_id,
1008        &arena,
1009        &hir_arena,
1010        untracked,
1011        incr_comp_session.as_ref(),
1012        dep_graph,
1013        rustc_query_impl::query_system(
1014            &arena,
1015            providers.queries,
1016            providers.extern_queries,
1017            query_result_on_disk_cache,
1018            incremental,
1019        ),
1020        providers.hooks,
1021        compiler.current_gcx.clone(),
1022        |tcx| {
1023            let feed = tcx.create_crate_num(stable_crate_id).unwrap();
1024            {
    match (&feed.key(), &LOCAL_CRATE) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(feed.key(), LOCAL_CRATE);
1025            feed.crate_name(crate_name);
1026
1027            let feed = tcx.feed_unit_query();
1028            feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
1029                tcx.sess,
1030                &pre_configured_attrs,
1031                crate_name,
1032            )));
1033            feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1034            feed.output_filenames(Arc::new(outputs));
1035
1036            // There are two paths out of `f`.
1037            // - Normal exit.
1038            // - Panic, e.g. triggered by `abort_if_errors` or a fatal error.
1039            //
1040            // If a panic occurs, we still need to wind down the self-profiler to correctly record
1041            // the query events that are still in flight. Otherwise, they will be invalid and will
1042            // show up as "<unknown>" in the profiling data.
1043            let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(tcx)));
1044            let res = match res {
1045                Ok(res) => res,
1046                Err(err) => {
1047                    tcx.alloc_self_profile_query_strings();
1048
1049                    // Resume unwinding if a panic happened.
1050                    std::panic::resume_unwind(err);
1051                }
1052            };
1053
1054            tcx.finish();
1055            res
1056        },
1057    );
1058
1059    (res, incr_comp_session)
1060}
1061
1062struct DiagCallback<'tcx> {
1063    callback: Box<
1064        dyn for<'b> FnOnce(DiagCtxtHandle<'b>, Level, &dyn Any) -> Diag<'b> + DynSend + DynSync,
1065    >,
1066    tcx: TyCtxt<'tcx>,
1067}
1068
1069impl<'a, 'tcx> Diagnostic<'a> for DiagCallback<'tcx> {
1070    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
1071        (self.callback)(dcx, level, self.tcx.sess)
1072    }
1073}
1074
1075pub fn emit_delayed_lints(tcx: TyCtxt<'_>) {
1076    for owner_id in tcx.hir_crate_items(()).owners() {
1077        if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id) {
1078            for lint in delayed_lints.steal() {
1079                tcx.emit_node_span_lint(
1080                    lint.lint_id.lint,
1081                    lint.id,
1082                    lint.span.clone(),
1083                    DiagCallback { callback: lint.callback, tcx },
1084                );
1085            }
1086        }
1087    }
1088}
1089
1090/// Runs all analyses that we guarantee to run, even if errors were reported in earlier analyses.
1091/// This function never fails.
1092fn run_required_analyses(tcx: TyCtxt<'_>) {
1093    if tcx.sess.opts.unstable_opts.input_stats {
1094        rustc_passes::input_stats::print_hir_stats(tcx);
1095    }
1096    // When using rustdoc's "jump to def" feature, it enters this code and `check_crate`
1097    // is not defined. So we need to cfg it out.
1098    #[cfg(all(not(doc), debug_assertions))]
1099    rustc_passes::hir_id_validator::check_crate(tcx);
1100
1101    // Prefetch this to prevent multiple threads from blocking on it later.
1102    // This is needed since the `hir_id_validator::check_crate` call above is not guaranteed
1103    // to use `hir_crate_items`.
1104    tcx.ensure_done().hir_crate_items(());
1105
1106    rustc_passes::delegation::check_glob_and_list_delegations_target_expr(tcx);
1107
1108    let sess = tcx.sess;
1109    sess.time("misc_checking_1", || {
1110        par_fns(&mut [
1111            &mut || {
1112                sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1113                sess.time("check_externally_implementable_items", || {
1114                    tcx.ensure_ok().check_externally_implementable_items(())
1115                });
1116
1117                sess.time("looking_for_derive_registrar", || {
1118                    tcx.ensure_ok().proc_macro_decls_static(())
1119                });
1120
1121                CStore::from_tcx(tcx).report_unused_deps(tcx);
1122            },
1123            &mut || {
1124                tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1125                tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1126                tcx.par_hir_for_each_module(|module| {
1127                    tcx.ensure_ok().check_mod_attrs(module);
1128                    tcx.ensure_ok().check_mod_unstable_api_usage(module);
1129                });
1130            },
1131            &mut || {
1132                // We force these queries to run,
1133                // since they might not otherwise get called.
1134                // This marks the corresponding crate-level attributes
1135                // as used, and ensures that their values are valid.
1136                tcx.ensure_ok().limits(());
1137            },
1138        ]);
1139    });
1140
1141    sess.time("emit_ast_lowering_delayed_lints", || {
1142        emit_delayed_lints(tcx);
1143    });
1144
1145    rustc_hir_analysis::check_crate(tcx);
1146    // Freeze definitions as we don't add new ones at this point.
1147    // We need to wait until now since we synthesize a by-move body
1148    // for all coroutine-closures.
1149    //
1150    // This improves performance by allowing lock-free access to them.
1151    tcx.untracked().definitions.freeze();
1152
1153    sess.time("MIR_borrow_checking", || {
1154        tcx.par_hir_body_owners(|def_id| {
1155            let not_typeck_child = !tcx.is_typeck_child(def_id.to_def_id());
1156            if not_typeck_child {
1157                // Child unsafety and borrowck happens together with the parent
1158                tcx.ensure_ok().check_unsafety(def_id);
1159            }
1160            if tcx.is_trivial_const(def_id) {
1161                return;
1162            }
1163            if not_typeck_child {
1164                tcx.ensure_ok().mir_borrowck(def_id);
1165                tcx.ensure_ok().check_transmutes(def_id);
1166                if !tcx.sess.opts.unstable_opts.offload.is_empty() {
1167                    tcx.ensure_ok().check_offloads(def_id);
1168                }
1169            }
1170            tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1171            tcx.ensure_ok().check_liveness(def_id);
1172
1173            // If we need to codegen, ensure that we emit all errors from
1174            // `mir_drops_elaborated_and_const_checked` now, to avoid discovering
1175            // them later during codegen.
1176            if tcx.sess.opts.output_types.should_codegen()
1177                || tcx.hir_body_const_context(def_id).is_some()
1178            {
1179                tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1180            }
1181            if tcx.is_coroutine(def_id.to_def_id())
1182                && (!tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()))
1183            {
1184                // Eagerly check the unsubstituted layout for cycles.
1185                tcx.ensure_ok()
1186                    .layout_of(ty::TypingEnv::codegen(tcx, def_id.to_def_id()).as_query_input(
1187                        tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
1188                    ));
1189            }
1190        });
1191    });
1192
1193    sess.time("layout_testing", || layout_test::test_layout(tcx));
1194    sess.time("abi_testing", || abi_test::test_abi(tcx));
1195}
1196
1197/// Runs the type-checking, region checking and other miscellaneous analysis
1198/// passes on the crate.
1199fn analysis(tcx: TyCtxt<'_>, (): ()) {
1200    run_required_analyses(tcx);
1201
1202    let sess = tcx.sess;
1203
1204    // Avoid overwhelming user with errors if borrow checking failed.
1205    // I'm not sure how helpful this is, to be honest, but it avoids a
1206    // lot of annoying errors in the ui tests (basically,
1207    // lint warnings and so on -- kindck used to do this abort, but
1208    // kindck is gone now). -nmatsakis
1209    //
1210    // But we exclude lint errors from this, because lint errors are typically
1211    // less serious and we're more likely to want to continue (#87337).
1212    if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1213        guar.raise_fatal();
1214    }
1215
1216    sess.time("misc_checking_3", || {
1217        par_fns(&mut [
1218            &mut || {
1219                tcx.ensure_ok().effective_visibilities(());
1220
1221                par_fns(&mut [
1222                    &mut || {
1223                        tcx.par_hir_for_each_module(|module| {
1224                            tcx.ensure_ok().check_private_in_public(module)
1225                        })
1226                    },
1227                    &mut || {
1228                        tcx.par_hir_for_each_module(|module| {
1229                            tcx.ensure_ok().check_mod_deathness(module)
1230                        });
1231                    },
1232                    &mut || {
1233                        sess.time("lint_checking", || {
1234                            rustc_lint::check_crate(tcx);
1235                        });
1236                    },
1237                    &mut || {
1238                        tcx.ensure_ok().clashing_extern_declarations(());
1239                    },
1240                ]);
1241            },
1242            &mut || {
1243                sess.time("privacy_checking_modules", || {
1244                    tcx.par_hir_for_each_module(|module| {
1245                        tcx.ensure_ok().check_mod_privacy(module);
1246                    });
1247                });
1248            },
1249        ]);
1250
1251        // This check has to be run after all lints are done processing. We don't
1252        // define a lint filter, as all lint checks should have finished at this point.
1253        sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1254
1255        // This query is only invoked normally if a diagnostic is emitted that needs any
1256        // diagnostic item. If the crate compiles without checking any diagnostic items,
1257        // we will fail to emit overlap diagnostics. Thus we invoke it here unconditionally.
1258        let _ = tcx.all_diagnostic_items(());
1259
1260        // This query is only invoked normally if a diagnostic is emitted that needs any
1261        // canonical symbol. If the crate compiles without checking any runtime symbols,
1262        // we will fail to emit overlap diagnostics. Thus we invoke it here unconditionally.
1263        let _ = tcx.all_canonical_symbols(());
1264    });
1265
1266    // If `-Zvalidate-mir` is set, we also want to compute the final MIR for each item
1267    // (either its `mir_for_ctfe` or `optimized_mir`) since that helps uncover any bugs
1268    // in MIR optimizations that may only be reachable through codegen, or other codepaths
1269    // that requires the optimized/ctfe MIR, coroutine bodies, or evaluating consts.
1270    // Nevertheless, wait after type checking is finished, as optimizing code that does not
1271    // type-check is very prone to ICEs.
1272    if tcx.sess.opts.unstable_opts.validate_mir {
1273        sess.time("ensuring_final_MIR_is_computable", || {
1274            tcx.par_hir_body_owners(|def_id| {
1275                if !tcx.is_trivial_const(def_id) {
1276                    tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1277                }
1278            });
1279        });
1280    }
1281}
1282
1283/// Runs the codegen backend, after which the AST and analysis can
1284/// be discarded.
1285pub(crate) fn start_codegen<'tcx>(
1286    codegen_backend: &dyn CodegenBackend,
1287    tcx: TyCtxt<'tcx>,
1288) -> (Box<dyn Any>, CrateInfo, EncodedMetadata) {
1289    tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1290
1291    // Hook for tests.
1292    if let Some((def_id, _)) = tcx.entry_fn(())
1293        && {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcDelayedBugFromInsideQuery)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery)
1294    {
1295        tcx.ensure_ok().trigger_delayed_bug(def_id);
1296    }
1297
1298    // Don't run this test assertions when not doing codegen. Compiletest tries to build
1299    // build-fail tests in check mode first and expects it to not give an error in that case.
1300    if tcx.sess.opts.output_types.should_codegen() {
1301        rustc_symbol_mangling::test::dump_symbol_names_and_def_paths(tcx);
1302    }
1303
1304    // Don't do code generation if there were any errors. Likewise if
1305    // there were any delayed bugs, because codegen will likely cause
1306    // more ICEs, obscuring the original problem.
1307    if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1308        guar.raise_fatal();
1309    }
1310
1311    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs:1311",
                        "rustc_interface::passes", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(1311u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Pre-codegen\n{0:?}",
                                                    tcx.debug_stats()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("Pre-codegen\n{:?}", tcx.debug_stats());
1312
1313    let metadata = match rustc_metadata::fs::encode_and_write_metadata(tcx) {
1314        Ok(metadata) => metadata,
1315        Err(guar) => guar.raise_fatal(),
1316    };
1317
1318    let is_host_metadata = tcx
1319        .sess
1320        .opts
1321        .unstable_opts
1322        .offload
1323        .iter()
1324        .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    rustc_session::config::Offload::HostMetadata(_) => true,
    _ => false,
}matches!(o, rustc_session::config::Offload::HostMetadata(_)));
1325
1326    let codegen = tcx.sess.time("codegen_crate", || {
1327        if tcx.sess.opts.unstable_opts.no_codegen
1328            || !tcx.sess.opts.output_types.should_codegen()
1329            || is_host_metadata
1330        {
1331            tcx.sess.dcx().abort_if_errors();
1332
1333            if is_host_metadata {
1334                rustc_monomorphize::write_host_metadata_offload_manifest(tcx);
1335            }
1336
1337            // Linker::link will skip join_codegen in case of a `CompiledModules` Any value.
1338            Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
1339        } else {
1340            codegen_backend.codegen_crate(tcx)
1341        }
1342    });
1343
1344    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs:1344",
                        "rustc_interface::passes", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(1344u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Post-codegen\n{0:?}",
                                                    tcx.debug_stats()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("Post-codegen\n{:?}", tcx.debug_stats());
1345
1346    // This must run after monomorphization so that all generic types
1347    // have been instantiated.
1348    if tcx.sess.opts.unstable_opts.print_type_sizes {
1349        tcx.sess.code_stats.print_type_sizes();
1350    }
1351
1352    let crate_info = CrateInfo::new(tcx, codegen_backend.target_cpu(tcx.sess));
1353
1354    (codegen, crate_info, metadata)
1355}
1356
1357/// Compute and validate the crate name.
1358pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1359    // We validate *all* occurrences of `#![crate_name]`, pick the first find and
1360    // if a crate name was passed on the command line via `--crate-name` we enforce
1361    // that they match.
1362    // We perform the validation step here instead of later to ensure it gets run
1363    // in all code paths that require the crate name very early on, namely before
1364    // macro expansion.
1365
1366    let attr_crate_name =
1367        parse_crate_name(sess, krate_attrs, ShouldEmit::EarlyFatal { also_emit_lints: true });
1368
1369    let validate = |name, span| {
1370        rustc_session::output::validate_crate_name(sess, name, span);
1371        name
1372    };
1373
1374    if let Some(crate_name) = &sess.opts.crate_name {
1375        let crate_name = Symbol::intern(crate_name);
1376        if let Some((attr_crate_name, span)) = attr_crate_name
1377            && attr_crate_name != crate_name
1378        {
1379            sess.dcx().emit_err(diagnostics::CrateNameDoesNotMatch {
1380                span,
1381                crate_name,
1382                attr_crate_name,
1383            });
1384        }
1385        return validate(crate_name, None);
1386    }
1387
1388    if let Some((crate_name, span)) = attr_crate_name {
1389        return validate(crate_name, Some(span));
1390    }
1391
1392    if let Input::File(ref path) = sess.io.input
1393        && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1394    {
1395        if file_stem.starts_with('-') {
1396            sess.dcx().emit_err(diagnostics::CrateNameInvalid { crate_name: file_stem });
1397        } else {
1398            return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1399        }
1400    }
1401
1402    sym::rust_out
1403}
1404
1405pub(crate) fn parse_crate_name(
1406    sess: &Session,
1407    attrs: &[ast::Attribute],
1408    emit_errors: ShouldEmit,
1409) -> Option<(Symbol, Span)> {
1410    let Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1411        AttributeParser::parse_limited_sym_should_emit(
1412            sess,
1413            attrs,
1414            &[sym::crate_name],
1415            DUMMY_SP,
1416            None,
1417            emit_errors,
1418        )?
1419    else {
1420        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("crate_name is the only attr we could\'ve parsed here")));
};unreachable!("crate_name is the only attr we could've parsed here");
1421    };
1422
1423    Some((name, name_span))
1424}
1425
1426pub fn collect_crate_types(
1427    session: &Session,
1428    backend_crate_types: &[CrateType],
1429    codegen_backend_name: &'static str,
1430    attrs: &[ast::Attribute],
1431    crate_span: Span,
1432) -> Vec<CrateType> {
1433    // If we're generating a test executable, then ignore all other output
1434    // styles at all other locations
1435    if session.opts.test {
1436        if !session.target.executables {
1437            session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1438                crate_type: CrateType::Executable,
1439                target_triple: &session.opts.target_triple,
1440            });
1441            return Vec::new();
1442        }
1443        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CrateType::Executable]))vec![CrateType::Executable];
1444    }
1445
1446    // Shadow `sdylib` crate type in interface build.
1447    if session.opts.unstable_opts.build_sdylib_interface {
1448        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CrateType::Rlib]))vec![CrateType::Rlib];
1449    }
1450
1451    // Only check command line flags if present. If no types are specified by
1452    // command line, then reuse the empty `base` Vec to hold the types that
1453    // will be found in crate attributes.
1454    // JUSTIFICATION: before wrapper fn is available
1455    #[allow(rustc::bad_opt_access)]
1456    let mut base = session.opts.crate_types.clone();
1457    if base.is_empty() {
1458        if let Some(Attribute::Parsed(AttributeKind::CrateType(crate_type))) =
1459            AttributeParser::parse_limited_sym_should_emit(
1460                session,
1461                attrs,
1462                &[sym::crate_type],
1463                crate_span,
1464                None,
1465                ShouldEmit::EarlyFatal { also_emit_lints: false },
1466            )
1467        {
1468            base.extend(crate_type);
1469        }
1470
1471        if base.is_empty() {
1472            base.push(default_output_for_target(session));
1473        } else {
1474            base.sort();
1475            base.dedup();
1476        }
1477    }
1478
1479    base.retain(|crate_type| {
1480        if invalid_output_for_target(session, *crate_type) {
1481            session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1482                crate_type: *crate_type,
1483                target_triple: &session.opts.target_triple,
1484            });
1485            false
1486        } else if !backend_crate_types.contains(crate_type) {
1487            session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForCodegenBackend {
1488                crate_type: *crate_type,
1489                codegen_backend: codegen_backend_name,
1490            });
1491            false
1492        } else {
1493            true
1494        }
1495    });
1496
1497    base
1498}
1499
1500/// Returns default crate type for target
1501///
1502/// Default crate type is used when crate type isn't provided neither
1503/// through cmd line arguments nor through crate attributes
1504///
1505/// It is CrateType::Executable for all platforms but iOS as there is no
1506/// way to run iOS binaries anyway without jailbreaking and
1507/// interaction with Rust code through static library is the only
1508/// option for now
1509fn default_output_for_target(sess: &Session) -> CrateType {
1510    if !sess.target.executables { CrateType::StaticLib } else { CrateType::Executable }
1511}
1512
1513fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1514    let attr = AttributeParser::parse_limited_sym_should_emit(
1515        sess,
1516        &krate_attrs,
1517        &[sym::recursion_limit],
1518        DUMMY_SP,
1519        None,
1520        // errors are fatal here, but lints aren't.
1521        // If things aren't fatal we continue, and will parse this again.
1522        // That makes the same lint trigger again.
1523        // So, no lints here to avoid duplicates.
1524        ShouldEmit::EarlyFatal { also_emit_lints: false },
1525    );
1526    crate::limits::get_recursion_limit(attr.as_slice(), sess)
1527}