Skip to main content

rustc_interface/
passes.rs

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