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