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