Skip to main content

rustc_interface/
passes.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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