Skip to main content

rustc_metadata/
creader.rs

1//! Validates all used crates and extern libraries and loads their metadata
2
3use std::collections::BTreeMap;
4use std::path::Path;
5use std::str::FromStr;
6use std::{cmp, env, iter};
7
8use rustc_ast::expand::allocator::{ALLOC_ERROR_HANDLER, AllocatorKind, global_fn_name};
9use rustc_ast::{self as ast, *};
10use rustc_crate_store::{CrateDepKind, CrateSource, ExternCrate, ExternCrateSource};
11use rustc_data_structures::fx::FxHashSet;
12use rustc_data_structures::owned_slice::OwnedSlice;
13use rustc_data_structures::svh::Svh;
14use rustc_data_structures::sync::{self, FreezeReadGuard, FreezeWriteGuard};
15use rustc_data_structures::unord::{UnordMap, UnordSet};
16use rustc_expand::base::SyntaxExtension;
17use rustc_hir::def_id::{CrateNum, LOCAL_CRATE, LocalDefId, StableCrateId};
18use rustc_hir::definitions::{DefPathData, Definitions};
19use rustc_index::IndexVec;
20use rustc_lint_defs as lint;
21use rustc_lint_defs::builtin::{PARTIAL_STACK_PROTECTOR, UNUSED_CRATE_DEPENDENCIES};
22use rustc_middle::ty::data_structures::IndexSet;
23use rustc_middle::ty::{TyCtxt, TyCtxtFeed};
24use rustc_proc_macro::bridge::client::Client as ProcMacroClient;
25use rustc_session::Session;
26use rustc_session::config::mitigation_coverage::{
27    DeniedPartialMitigationKind, DeniedPartialMitigationLevel,
28};
29use rustc_session::config::{
30    ExtendedTargetModifierInfo, ExternLocation, Externs, OptionsTargetModifiers, TargetModifier,
31};
32use rustc_session::output::validate_crate_name;
33use rustc_session::search_paths::PathKind;
34use rustc_span::def_id::DefId;
35use rustc_span::edition::Edition;
36use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, sym};
37use rustc_structures::CrateType;
38use rustc_target::spec::{PanicStrategy, Target};
39use tracing::{debug, info};
40
41use crate::diagnostics;
42use crate::locator::{CrateError, CrateLocator, CratePaths, CrateRejections};
43use crate::rmeta::{
44    CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob, TargetModifiers,
45};
46
47/// The backend's way to give the crate store access to the metadata in a library.
48/// Note that it returns the raw metadata bytes stored in the library file, whether
49/// it is compressed, uncompressed, some weird mix, etc.
50/// rmeta files are backend independent and not handled here.
51pub trait MetadataLoader {
52    fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>;
53    fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>;
54}
55
56pub type MetadataLoaderDyn = dyn MetadataLoader + Send + Sync + sync::DynSend + sync::DynSync;
57
58pub struct CStore {
59    metadata_loader: Box<MetadataLoaderDyn>,
60
61    metas: IndexVec<CrateNum, Option<Box<CrateMetadata>>>,
62    injected_panic_runtime: Option<CrateNum>,
63    /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
64    /// If the above is true, then this field denotes the kind of the found allocator.
65    allocator_kind: Option<AllocatorKind>,
66    /// This crate needs an allocation error handler and either provides it itself, or finds it in a dependency.
67    /// If the above is true, then this field denotes the kind of the found allocator.
68    alloc_error_handler_kind: Option<AllocatorKind>,
69    /// This crate has a `#[global_allocator]` item.
70    has_global_allocator: bool,
71    /// This crate has a `#[alloc_error_handler]` item.
72    has_alloc_error_handler: bool,
73
74    /// Cached map from hash to CrateNum, to avoid scanning metas during crate resolution.
75    hash_to_cnum: UnordMap<Svh, CrateNum>,
76
77    /// Names that were used to load the crates via `extern crate` or paths.
78    resolved_externs: UnordMap<Symbol, CrateNum>,
79    /// Given a crate id, get their extern crate import name (given by `--extern`,
80    /// `extern crate foo as bar;` or from the extern prelude). A crate might be known by more than
81    /// one extern name, but we only keep track of one of them. This name should *only be used for
82    /// diagnostics*.
83    extern_crate_name: UnordMap<CrateNum, Symbol>,
84
85    /// Unused externs of the crate
86    unused_externs: Vec<Symbol>,
87
88    used_extern_options: FxHashSet<Symbol>,
89    /// Whether there was a failure in resolving crate,
90    /// it's used to suppress some diagnostics that would otherwise too noisey.
91    has_crate_resolve_with_fail: bool,
92}
93
94pub enum LoadedMacro {
95    MacroDef {
96        def: MacroDef,
97        ident: Ident,
98        attrs: Vec<rustc_attr_ir::Attribute>,
99        span: Span,
100        edition: Edition,
101    },
102    ProcMacro(SyntaxExtension),
103}
104
105pub(crate) struct Library {
106    pub source: CrateSource,
107    pub metadata: MetadataBlob,
108}
109
110enum LoadResult {
111    Previous(CrateNum),
112    Loaded(Library),
113}
114
115impl std::fmt::Debug for CStore {
116    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        fmt.write_fmt(format_args!("resolved crates:\n"))writeln!(fmt, "resolved crates:")?;
118        for (cnum, data) in self.iter_crate_data() {
119            fmt.write_fmt(format_args!("  name: {0}\n", data.name()))writeln!(fmt, "  name: {}", data.name())?;
120            fmt.write_fmt(format_args!("  cnum: {0}\n", cnum))writeln!(fmt, "  cnum: {cnum}")?;
121            fmt.write_fmt(format_args!("  hash: {0}\n", data.hash()))writeln!(fmt, "  hash: {}", data.hash())?;
122            fmt.write_fmt(format_args!("  reqd: {0:?}\n", data.dep_kind()))writeln!(fmt, "  reqd: {:?}", data.dep_kind())?;
123            fmt.write_fmt(format_args!("  priv: {0:?}\n", data.is_private_dep()))writeln!(fmt, "  priv: {:?}", data.is_private_dep())?;
124            let CrateSource { dylib, rlib, rmeta, sdylib_interface } = data.source();
125            if let Some(dylib) = dylib {
126                fmt.write_fmt(format_args!("  dylib: {0}\n", dylib.display()))writeln!(fmt, "  dylib: {}", dylib.display())?;
127            }
128            if let Some(rlib) = rlib {
129                fmt.write_fmt(format_args!("   rlib: {0}\n", rlib.display()))writeln!(fmt, "   rlib: {}", rlib.display())?;
130            }
131            if let Some(rmeta) = rmeta {
132                fmt.write_fmt(format_args!("   rmeta: {0}\n", rmeta.display()))writeln!(fmt, "   rmeta: {}", rmeta.display())?;
133            }
134            if let Some(sdylib_interface) = sdylib_interface {
135                fmt.write_fmt(format_args!("   sdylib interface: {0}\n",
        sdylib_interface.display()))writeln!(fmt, "   sdylib interface: {}", sdylib_interface.display())?;
136            }
137        }
138        Ok(())
139    }
140}
141
142/// Reason that a crate is being sourced as a dependency.
143#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'a>
    ::core::clone::TrivialClone for CrateOrigin<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for CrateOrigin<'a> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<&'a CratePaths>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<&'a CrateDep>;
        let _: ::core::clone::AssertParamIsClone<&'a str>;
        *self
    }
}Clone, #[automatically_derived]impl<'a> ::core::marker::Copy for CrateOrigin<'a> { }Copy)]
144enum CrateOrigin<'a> {
145    /// This crate was a dependency of another crate.
146    IndirectDependency {
147        /// Where this dependency was included from. Should only be used in error messages.
148        dep_root_for_errors: &'a CratePaths,
149        /// True if the parent is private, meaning the dependent should also be private.
150        parent_private: bool,
151        /// Dependency info about this crate.
152        dep: &'a CrateDep,
153        /// The dependency's `-C extra-filename`, used to narrow the search for it on disk. Stored
154        /// separately from `dep` because it is encoded outside the hashed crate root; see
155        /// `CrateRootUnhashed::dep_extra_filenames`.
156        dep_extra_filename: &'a str,
157    },
158    /// Injected by `rustc`.
159    Injected,
160    /// Provided by `extern crate foo` or as part of the extern prelude.
161    Extern,
162}
163
164impl<'a> CrateOrigin<'a> {
165    /// Return the dependency root, if any.
166    fn dep_root_for_errors(&self) -> Option<&'a CratePaths> {
167        match self {
168            CrateOrigin::IndirectDependency { dep_root_for_errors, .. } => {
169                Some(dep_root_for_errors)
170            }
171            _ => None,
172        }
173    }
174
175    /// Return dependency information, if any.
176    fn dep(&self) -> Option<&'a CrateDep> {
177        match self {
178            CrateOrigin::IndirectDependency { dep, .. } => Some(dep),
179            _ => None,
180        }
181    }
182
183    /// Return the dependency's `-C extra-filename`, if any.
184    fn dep_extra_filename(&self) -> Option<&'a str> {
185        match self {
186            CrateOrigin::IndirectDependency { dep_extra_filename, .. } => Some(dep_extra_filename),
187            _ => None,
188        }
189    }
190
191    /// `Some(true)` if the dependency is private or its parent is private, `Some(false)` if the
192    /// dependency is not private, `None` if it could not be determined.
193    fn private_dep(&self) -> Option<bool> {
194        match self {
195            CrateOrigin::IndirectDependency { parent_private, dep, .. } => {
196                Some(dep.is_private || *parent_private)
197            }
198            CrateOrigin::Injected => Some(true),
199            _ => None,
200        }
201    }
202}
203
204impl CStore {
205    pub fn from_tcx(tcx: TyCtxt<'_>) -> FreezeReadGuard<'_, CStore> {
206        FreezeReadGuard::map(tcx.untracked().cstore.read(), |cstore| {
207            cstore.as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
208        })
209    }
210
211    pub fn from_tcx_mut(tcx: TyCtxt<'_>) -> FreezeWriteGuard<'_, CStore> {
212        FreezeWriteGuard::map(tcx.untracked().cstore.write(), |cstore| {
213            cstore.untracked_as_any().downcast_mut().expect("`tcx.cstore` is not a `CStore`")
214        })
215    }
216
217    fn intern_stable_crate_id<'tcx>(
218        &mut self,
219        tcx: TyCtxt<'tcx>,
220        root: &CrateRoot,
221    ) -> Result<TyCtxtFeed<'tcx, CrateNum>, CrateError> {
222        {
    match (&self.metas.len(), &tcx.untracked().stable_crate_ids.read().len())
        {
        (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!(self.metas.len(), tcx.untracked().stable_crate_ids.read().len());
223        let num = tcx.create_crate_num(root.stable_crate_id()).map_err(|existing| {
224            // Check for (potential) conflicts with the local crate
225            if existing == LOCAL_CRATE {
226                CrateError::SymbolConflictsCurrent(root.name())
227            } else if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name())
228            {
229                let crate_name0 = root.name();
230                CrateError::StableCrateIdCollision(crate_name0, crate_name1)
231            } else {
232                CrateError::NotFound(root.name())
233            }
234        })?;
235
236        self.metas.push(None);
237        Ok(num)
238    }
239
240    pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
241        self.metas[cnum].is_some()
242    }
243
244    pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> &CrateMetadata {
245        self.metas[cnum].as_ref().unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Failed to get crate data for {0:?}",
            cnum));
}panic!("Failed to get crate data for {cnum:?}"))
246    }
247
248    pub(crate) fn get_crate_data_mut(&mut self, cnum: CrateNum) -> &mut CrateMetadata {
249        self.metas[cnum].as_mut().unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Failed to get crate data for {0:?}",
            cnum));
}panic!("Failed to get crate data for {cnum:?}"))
250    }
251
252    fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
253        if !self.metas[cnum].is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Overwriting crate metadata entry"));
    }
};assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
254        self.hash_to_cnum.insert(data.hash(), cnum);
255        self.metas[cnum] = Some(Box::new(data));
256    }
257
258    /// Save the name used to resolve the extern crate in the local crate
259    ///
260    /// The name isn't always the crate's own name, because `sess.opts.externs` can assign it another name.
261    /// It's also not always the same as the `DefId`'s symbol due to renames `extern crate resolved_name as defid_name`.
262    pub(crate) fn set_resolved_extern_crate_name(&mut self, name: Symbol, extern_crate: CrateNum) {
263        self.resolved_externs.insert(name, extern_crate);
264        self.extern_crate_name.insert(extern_crate, name);
265    }
266
267    /// Crate resolved and loaded via the given extern name
268    /// (corresponds to names in `sess.opts.externs`)
269    ///
270    /// May be `None` if the crate wasn't used
271    pub fn resolved_extern_crate(&self, externs_name: Symbol) -> Option<CrateNum> {
272        self.resolved_externs.get(&externs_name).copied()
273    }
274
275    /// A crate's extern crate import name.
276    ///
277    /// This name is given by `--extern`, `extern crate foo as bar;` or from the extern prelude. A
278    /// crate might be known by more than one extern name, but we only keep track of one of them.
279    /// This name should *only be used for diagnostics*.
280    // FIXME: find a way of making the provided name always suitable for structured suggestions, as
281    // right now this is will most of the time work, but could conceivably provide an incorrect name
282    // given the right circumstances.
283    pub fn opt_extern_crate_name(&self, c: CrateNum) -> Option<Symbol> {
284        self.extern_crate_name.get(&c).copied()
285    }
286
287    pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
288        self.metas
289            .iter_enumerated()
290            .filter_map(|(cnum, data)| data.as_deref().map(|data| (cnum, data)))
291    }
292
293    pub fn all_proc_macro_def_ids(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
294        self.iter_crate_data().flat_map(move |(krate, data)| data.proc_macros_for_crate(tcx, krate))
295    }
296
297    fn push_dependencies_in_postorder(&self, deps: &mut IndexSet<CrateNum>, cnum: CrateNum) {
298        if !deps.contains(&cnum) {
299            let cdata = self.get_crate_data(cnum);
300            for dep in cdata.dependencies() {
301                if dep != cnum {
302                    self.push_dependencies_in_postorder(deps, dep);
303                }
304            }
305
306            deps.insert(cnum);
307        }
308    }
309
310    pub(crate) fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> IndexSet<CrateNum> {
311        let mut deps = IndexSet::default();
312        if cnum == LOCAL_CRATE {
313            for (cnum, _) in self.iter_crate_data() {
314                self.push_dependencies_in_postorder(&mut deps, cnum);
315            }
316        } else {
317            self.push_dependencies_in_postorder(&mut deps, cnum);
318        }
319        deps
320    }
321
322    pub(crate) fn injected_panic_runtime(&self) -> Option<CrateNum> {
323        self.injected_panic_runtime
324    }
325
326    pub(crate) fn allocator_kind(&self) -> Option<AllocatorKind> {
327        self.allocator_kind
328    }
329
330    pub(crate) fn alloc_error_handler_kind(&self) -> Option<AllocatorKind> {
331        self.alloc_error_handler_kind
332    }
333
334    pub(crate) fn has_global_allocator(&self) -> bool {
335        self.has_global_allocator
336    }
337
338    pub(crate) fn has_alloc_error_handler(&self) -> bool {
339        self.has_alloc_error_handler
340    }
341
342    pub fn had_extern_crate_load_failure(&self) -> bool {
343        self.has_crate_resolve_with_fail
344    }
345
346    pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
347        let json_unused_externs = tcx.sess.opts.json_unused_externs;
348
349        // We put the check for the option before the lint_level_at_node call
350        // because the call mutates internal state and introducing it
351        // leads to some ui tests failing.
352        if !json_unused_externs.is_enabled() {
353            return;
354        }
355        let level =
356            tcx.lint_level_spec_at_node(UNUSED_CRATE_DEPENDENCIES, rustc_hir::CRATE_HIR_ID).level();
357        if level != lint::Level::Allow {
358            let unused_externs =
359                self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
360            let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
361            tcx.dcx().emit_unused_externs(level, json_unused_externs.is_loud(), &unused_externs);
362        }
363    }
364
365    fn report_target_modifiers_extended(
366        tcx: TyCtxt<'_>,
367        mods: &TargetModifiers,
368        dep_mods: &TargetModifiers,
369        data: &CrateMetadata,
370    ) {
371        let allowed_flag_mismatches = &tcx.sess.opts.cg.unsafe_allow_abi_mismatch;
372        let local_crate = tcx.crate_name(LOCAL_CRATE);
373        let tmod_extender = |tmod: &TargetModifier| (tmod.extend(), tmod.clone());
374        let report_diff = |prefix: &String,
375                           opt_name: &String,
376                           flag_local_value: Option<&String>,
377                           flag_extern_value: Option<&String>| {
378            if allowed_flag_mismatches.contains(&opt_name) {
379                return;
380            }
381            let extern_crate = data.name();
382
383            let emit = |mut diag: rustc_errors::Diag<'_>| {
384                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={1}` to silence this {0}",
                diag.level(), opt_name))
    })format!("if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={opt_name}` to silence this {}", diag.level()));
385                diag.emit();
386            };
387
388            if prefix.is_empty() {
389                // A synthetic target modifier, does not correspond to an actual flag.
390                match opt_name.as_str() {
391                    "target-feature" => {
392                        // Compute the features we have locally that don't exist in the other crate,
393                        // and the features the other crate has that are missing locally.
394                        let mut local_features = FxHashSet::from_iter(
395                            flag_local_value.unwrap().split(",").filter(|s| !s.is_empty()),
396                        );
397                        let mut extern_features = FxHashSet::from_iter(
398                            flag_extern_value.unwrap().split(",").filter(|s| !s.is_empty()),
399                        );
400                        #[allow(rustc::potential_query_instability)] // we are sorting below
401                        let both_features = FxHashSet::from_iter(
402                            local_features.intersection(&extern_features).copied(),
403                        );
404                        #[allow(rustc::potential_query_instability)] // we are sorting below
405                        for feature in both_features {
406                            local_features.remove(feature);
407                            extern_features.remove(feature);
408                        }
409                        let local_features =
410                            UnordSet::from(local_features).into_sorted_stable_ord();
411                        let extern_features =
412                            UnordSet::from(extern_features).into_sorted_stable_ord();
413                        if !(local_features.len() > 0 || extern_features.len() > 0) {
    ::core::panicking::panic("assertion failed: local_features.len() > 0 || extern_features.len() > 0")
};assert!(local_features.len() > 0 || extern_features.len() > 0);
414
415                        let diag = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("mixing target features may cause an ABI mismatch in crate `{0}`",
                local_crate))
    })format!(
416                            "mixing target features may cause an ABI mismatch in crate `{local_crate}`"
417                        );
418                        let mut diag = tcx.dcx().struct_warn(diag);
419                        diag.help("some target features modify the ABI so Rust crates compiled with different values for these target features cannot be used together safely");
420                        if local_features.len() > 0 {
421                            let features = local_features.join(", ");
422                            let before =
423                                if local_features.len() == 1 { "feature" } else { "features" };
424                            let after = if local_features.len() == 1 { "is" } else { "are" };
425                            diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the target {0} {1} {2} enabled in this crate but disabled in `{3}`",
                before, features, after, extern_crate))
    })format!("the target {before} {features} {after} enabled in this crate but disabled in `{extern_crate}`"));
426                        }
427                        if extern_features.len() > 0 {
428                            let features = extern_features.join(", ");
429                            let before =
430                                if extern_features.len() == 1 { "feature" } else { "features" };
431                            let after = if extern_features.len() == 1 { "is" } else { "are" };
432                            diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the target {0} {1} {2} enabled in `{3}` but disabled in this crate",
                before, features, after, extern_crate))
    })format!("the target {before} {features} {after} enabled in `{extern_crate}` but disabled in this crate"));
433                        }
434                        emit(diag);
435                    }
436                    "codegen-backend-name" => {
437                        let diag = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("mixing codegen backends while using backend-specific target features may cause an ABI mismatch in crate `{0}`",
                local_crate))
    })format!(
438                            "mixing codegen backends while using backend-specific target features may cause an ABI mismatch in crate `{local_crate}`"
439                        );
440                        let mut diag = tcx.dcx().struct_err(diag);
441                        diag.help("this crate has `-Zllvm-target-feature` set, which means different codegen backends could interpret the target features differently, or ignore them entirely");
442                        diag.help("some target features modify the ABI so Rust crates compiled with different target features cannot be used together safely");
443                        emit(diag)
444                    }
445                    _ => {
    ::core::panicking::panic_fmt(format_args!("unhandled synthetic target feature {0}",
            opt_name));
}panic!("unhandled synthetic target feature {opt_name}"),
446                }
447                return;
448            }
449
450            let flag_name_prefixed = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-{0}{1}", prefix, opt_name))
    })format!("-{}{}", prefix, opt_name);
451
452            let diag = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("mixing `{0}` will cause an ABI mismatch in crate `{1}`",
                flag_name_prefixed, local_crate))
    })format!(
453                "mixing `{flag_name_prefixed}` will cause an ABI mismatch in crate `{local_crate}`"
454            );
455            let mut diag = tcx.dcx().struct_err(diag);
456            diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the `{0}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely",
                flag_name_prefixed))
    })format!(
457                "the `{flag_name_prefixed}` flag modifies the ABI so Rust crates compiled \
458                with different values of this flag cannot be used together safely"
459            ));
460
461            match (flag_local_value, flag_extern_value) {
462                (Some(local_value), Some(extern_value)) => {
463                    diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}={1}` in this crate is incompatible with `{0}={2}` in dependency `{3}`",
                flag_name_prefixed, local_value, extern_value, extern_crate))
    })format!(
464                        "`{flag_name_prefixed}={local_value}` in this crate is incompatible \
465                        with `{flag_name_prefixed}={extern_value}` in dependency `{extern_crate}`"
466                    ));
467                    diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("set `{0}={1}` in this crate or `{0}={2}` in `{3}`",
                flag_name_prefixed, extern_value, local_value, extern_crate))
    })format!(
468                        "set `{flag_name_prefixed}={extern_value}` in this crate \
469                        or `{flag_name_prefixed}={local_value}` in `{extern_crate}`"
470                    ));
471                }
472                (None, Some(extern_value)) => {
473                    let has_extern_value = !extern_value.is_empty();
474                    diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{1}` is unset in this crate which is incompatible with {0} in dependency `{2}`",
                if has_extern_value {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}={1}`",
                                    flag_name_prefixed, extern_value))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` being set",
                                    flag_name_prefixed))
                        })
                }, flag_name_prefixed, extern_crate))
    })format!(
475                        "`{flag_name_prefixed}` is unset in this crate which is \
476                        incompatible with {} in dependency `{extern_crate}`",
477                        if has_extern_value {
478                            format!("`{flag_name_prefixed}={extern_value}`")
479                        } else {
480                            format!("`{flag_name_prefixed}` being set")
481                        }
482                    ));
483                    diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("set {0} in this crate or unset `{1}` in `{2}`",
                if has_extern_value {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}={1}`",
                                    flag_name_prefixed, extern_value))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}`",
                                    flag_name_prefixed))
                        })
                }, flag_name_prefixed, extern_crate))
    })format!(
484                        "set {} in this crate or unset `{flag_name_prefixed}` in `{extern_crate}`",
485                        if has_extern_value {
486                            format!("`{flag_name_prefixed}={extern_value}`")
487                        } else {
488                            format!("`{flag_name_prefixed}`")
489                        }
490                    ));
491                }
492                (Some(local_value), None) => {
493                    let has_local_value = !local_value.is_empty();
494                    diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} in this crate is incompatible with `{1}` being unset in dependency `{2}`",
                if has_local_value {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}={1}`",
                                    flag_name_prefixed, local_value))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` being set",
                                    flag_name_prefixed))
                        })
                }, flag_name_prefixed, extern_crate))
    })format!(
495                        "{} in this crate is incompatible with \
496                        `{flag_name_prefixed}` being unset in dependency `{extern_crate}`",
497                        if has_local_value {
498                            format!("`{flag_name_prefixed}={local_value}`")
499                        } else {
500                            format!("`{flag_name_prefixed}` being set")
501                        }
502                    ));
503                    diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unset `{1}` in this crate or set {0} in `{2}`",
                if has_local_value {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}={1}`",
                                    flag_name_prefixed, local_value))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}`",
                                    flag_name_prefixed))
                        })
                }, flag_name_prefixed, extern_crate))
    })format!(
504                        "unset `{flag_name_prefixed}` in this crate or set {} in `{extern_crate}`",
505                        if has_local_value {
506                            format!("`{flag_name_prefixed}={local_value}`")
507                        } else {
508                            format!("`{flag_name_prefixed}`")
509                        }
510                    ));
511                }
512                (None, None) => {
    ::core::panicking::panic_fmt(format_args!("Incorrect target modifiers report_diff(None, None)"));
}panic!("Incorrect target modifiers report_diff(None, None)"),
513            };
514
515            emit(diag);
516        };
517        let mut it1 = mods.iter().map(tmod_extender);
518        let mut it2 = dep_mods.iter().map(tmod_extender);
519        let mut left_name_val: Option<(ExtendedTargetModifierInfo, TargetModifier)> = None;
520        let mut right_name_val: Option<(ExtendedTargetModifierInfo, TargetModifier)> = None;
521        loop {
522            left_name_val = left_name_val.or_else(|| it1.next());
523            right_name_val = right_name_val.or_else(|| it2.next());
524            match (&left_name_val, &right_name_val) {
525                (Some(l), Some(r)) => match l.1.opt.cmp(&r.1.opt) {
526                    cmp::Ordering::Equal => {
527                        if !l.1.consistent(&tcx.sess, Some(&r.1)) {
528                            report_diff(
529                                &l.0.prefix,
530                                &l.0.name,
531                                Some(&l.1.value_name),
532                                Some(&r.1.value_name),
533                            );
534                        }
535                        left_name_val = None;
536                        right_name_val = None;
537                    }
538                    cmp::Ordering::Greater => {
539                        if !r.1.consistent(&tcx.sess, None) {
540                            report_diff(&r.0.prefix, &r.0.name, None, Some(&r.1.value_name));
541                        }
542                        right_name_val = None;
543                    }
544                    cmp::Ordering::Less => {
545                        if !l.1.consistent(&tcx.sess, None) {
546                            report_diff(&l.0.prefix, &l.0.name, Some(&l.1.value_name), None);
547                        }
548                        left_name_val = None;
549                    }
550                },
551                (Some(l), None) => {
552                    if !l.1.consistent(&tcx.sess, None) {
553                        report_diff(&l.0.prefix, &l.0.name, Some(&l.1.value_name), None);
554                    }
555                    left_name_val = None;
556                }
557                (None, Some(r)) => {
558                    if !r.1.consistent(&tcx.sess, None) {
559                        report_diff(&r.0.prefix, &r.0.name, None, Some(&r.1.value_name));
560                    }
561                    right_name_val = None;
562                }
563                (None, None) => break,
564            }
565        }
566    }
567
568    pub fn report_session_incompatibilities(&self, tcx: TyCtxt<'_>, krate: &Crate) {
569        self.report_incompatible_target_modifiers(tcx);
570        self.report_incompatible_partial_mitigations(tcx);
571        self.report_incompatible_async_drop_feature(tcx, krate);
572    }
573
574    pub fn report_incompatible_target_modifiers(&self, tcx: TyCtxt<'_>) {
575        for flag_name in &tcx.sess.opts.cg.unsafe_allow_abi_mismatch {
576            if !OptionsTargetModifiers::is_target_modifier(flag_name) {
577                tcx.dcx().emit_err(diagnostics::UnknownTargetModifierUnsafeAllowed {
578                    flag_name: flag_name.clone(),
579                });
580            }
581        }
582        let mods = tcx.sess.opts.gather_target_modifiers();
583        for (_cnum, data) in self.iter_crate_data() {
584            if data.is_proc_macro_crate() {
585                continue;
586            }
587            let dep_mods = data.target_modifiers();
588            if mods != dep_mods {
589                Self::report_target_modifiers_extended(tcx, &mods, &dep_mods, data);
590            }
591        }
592    }
593
594    pub fn report_incompatible_partial_mitigations(&self, tcx: TyCtxt<'_>) {
595        let my_mitigations = tcx.sess.gather_enabled_denied_partial_mitigations();
596        let mut my_mitigations: BTreeMap<_, _> =
597            my_mitigations.iter().map(|mitigation| (mitigation.kind, mitigation)).collect();
598        for skipped_mitigation in tcx.sess.opts.allowed_partial_mitigations(tcx.sess.edition()) {
599            my_mitigations.remove(&skipped_mitigation);
600        }
601        const MAX_ERRORS_PER_MITIGATION: usize = 5;
602        let mut errors_per_mitigation = BTreeMap::new();
603        for (_cnum, data) in self.iter_crate_data() {
604            if data.is_proc_macro_crate() {
605                continue;
606            }
607            let their_mitigations = data.enabled_denied_partial_mitigations();
608            for my_mitigation in my_mitigations.values() {
609                let their_mitigation = their_mitigations
610                    .iter()
611                    .find(|mitigation| mitigation.kind == my_mitigation.kind)
612                    .map_or(DeniedPartialMitigationLevel::Enabled(false), |m| m.level);
613                if their_mitigation < my_mitigation.level {
614                    let errors = errors_per_mitigation.entry(my_mitigation.kind).or_insert(0);
615                    if *errors >= MAX_ERRORS_PER_MITIGATION {
616                        continue;
617                    }
618                    *errors += 1;
619
620                    let diagnostic = diagnostics::MitigationLessStrictInDependency {
621                        mitigation_name: my_mitigation.kind.to_string(),
622                        mitigation_level: my_mitigation.level.level_str().to_string(),
623                        extern_crate: data.name(),
624                    };
625                    if my_mitigation.kind == DeniedPartialMitigationKind::StackProtector {
626                        // make stack-protector only a forward-compat warning since it was
627                        // pretty widely used
628                        tcx.sess.psess.buffer_crate_lint(PARTIAL_STACK_PROTECTOR, diagnostic);
629                    } else {
630                        tcx.dcx().emit_err(diagnostic);
631                    }
632                }
633            }
634        }
635    }
636
637    // Report about async drop types in dependency if async drop feature is disabled
638    pub fn report_incompatible_async_drop_feature(&self, tcx: TyCtxt<'_>, krate: &Crate) {
639        if tcx.features().async_drop() {
640            return;
641        }
642        for (_cnum, data) in self.iter_crate_data() {
643            if data.is_proc_macro_crate() {
644                continue;
645            }
646            if data.has_async_drops() {
647                let extern_crate = data.name();
648                let local_crate = tcx.crate_name(LOCAL_CRATE);
649                tcx.dcx().emit_warn(diagnostics::AsyncDropTypesInDependency {
650                    span: krate.spans.inner_span.shrink_to_lo(),
651                    extern_crate,
652                    local_crate,
653                });
654            }
655        }
656    }
657
658    pub fn new(metadata_loader: Box<MetadataLoaderDyn>) -> CStore {
659        CStore {
660            metadata_loader,
661            // We add an empty entry for LOCAL_CRATE (which maps to zero) in
662            // order to make array indices in `metas` match with the
663            // corresponding `CrateNum`. This first entry will always remain
664            // `None`.
665            metas: IndexVec::from_iter(iter::once(None)),
666            injected_panic_runtime: None,
667            allocator_kind: None,
668            alloc_error_handler_kind: None,
669            has_global_allocator: false,
670            has_alloc_error_handler: false,
671            hash_to_cnum: UnordMap::default(),
672            resolved_externs: UnordMap::default(),
673            extern_crate_name: UnordMap::default(),
674            unused_externs: Vec::new(),
675            used_extern_options: Default::default(),
676            has_crate_resolve_with_fail: false,
677        }
678    }
679
680    fn existing_match(&self, name: Symbol, hash: Option<Svh>) -> Option<CrateNum> {
681        let hash = hash?;
682        let cnum = *self.hash_to_cnum.get(&hash)?;
683        if true {
    {
        match (&self.get_crate_data(cnum).name(), &name) {
            (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!(self.get_crate_data(cnum).name(), name);
684        Some(cnum)
685    }
686
687    /// Determine whether a dependency should be considered private.
688    ///
689    /// Dependencies are private if they get extern option specified, e.g. `--extern priv:mycrate`.
690    /// This is stored in metadata, so `private_dep`  can be correctly set during load. A `Some`
691    /// value for `private_dep` indicates that the crate is known to be private or public (note
692    /// that any `None` or `Some(false)` use of the same crate will make it public).
693    ///
694    /// Sometimes the directly dependent crate is not specified by `--extern`, in this case,
695    /// `private-dep` is none during loading. This is equivalent to the scenario where the
696    /// command parameter is set to `public-dependency`
697    fn is_private_dep(&self, externs: &Externs, name: Symbol, private_dep: Option<bool>) -> bool {
698        let extern_private = externs.get(name.as_str()).map(|e| e.is_private_dep);
699        match (extern_private, private_dep) {
700            // Explicit non-private via `--extern`, explicit non-private from metadata, or
701            // unspecified with default to public.
702            (Some(false), _) | (_, Some(false)) | (None, None) => false,
703            // Marked private via `--extern priv:mycrate` or in metadata.
704            (Some(true) | None, Some(true) | None) => true,
705        }
706    }
707
708    fn register_crate<'tcx>(
709        &mut self,
710        tcx: TyCtxt<'tcx>,
711        host_lib: Option<Library>,
712        origin: CrateOrigin<'_>,
713        lib: Library,
714        dep_kind: CrateDepKind,
715        name: Symbol,
716        private_dep: Option<bool>,
717    ) -> Result<CrateNum, CrateError> {
718        let _prof_timer =
719            tcx.sess.prof.generic_activity_with_arg("metadata_register_crate", name.as_str());
720
721        let Library { source, metadata } = lib;
722        let crate_root = metadata.get_root();
723        let unhashed = metadata.get_root_unhashed();
724        let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_crate_hash());
725        let private_dep = self.is_private_dep(&tcx.sess.opts.externs, name, private_dep);
726
727        // Claim this crate number and cache it
728        let feed = self.intern_stable_crate_id(tcx, &crate_root)?;
729        let cnum = feed.key();
730
731        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:731",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(731u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("register crate `{0}` (cnum = {1}. private_dep = {2})",
                                                    crate_root.name(), cnum, private_dep) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!(
732            "register crate `{}` (cnum = {}. private_dep = {})",
733            crate_root.name(),
734            cnum,
735            private_dep
736        );
737
738        // Maintain a reference to the top most crate.
739        // Stash paths for top-most crate locally if necessary.
740        let crate_paths;
741        let dep_root_for_errors = if let Some(dep_root_for_errors) = origin.dep_root_for_errors() {
742            dep_root_for_errors
743        } else {
744            crate_paths = CratePaths::new(crate_root.name(), source.clone());
745            &crate_paths
746        };
747
748        let cnum_map = self.resolve_crate_deps(
749            tcx,
750            dep_root_for_errors,
751            &crate_root,
752            &metadata,
753            cnum,
754            dep_kind,
755            private_dep,
756        )?;
757
758        let raw_proc_macros = if crate_root.is_proc_macro_crate() {
759            let temp_root;
760            let (dlsym_source, dlsym_root) = match &host_lib {
761                Some(host_lib) => (&host_lib.source, {
762                    temp_root = host_lib.metadata.get_root();
763                    &temp_root
764                }),
765                None => (&source, &crate_root),
766            };
767            let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
768            Some(self.dlsym_proc_macros(dlsym_dylib, dlsym_root.stable_crate_id())?)
769        } else {
770            None
771        };
772
773        let crate_metadata = CrateMetadata::new(
774            tcx,
775            metadata,
776            crate_root,
777            unhashed,
778            raw_proc_macros,
779            cnum,
780            cnum_map,
781            dep_kind,
782            source,
783            private_dep,
784            host_hash,
785        );
786
787        self.set_crate_data(cnum, crate_metadata);
788
789        Ok(cnum)
790    }
791
792    fn load_proc_macro<'a, 'b>(
793        &self,
794        sess: &'a Session,
795        locator: &mut CrateLocator<'b>,
796        crate_rejections: &mut CrateRejections,
797        path_kind: PathKind,
798        host_hash: Option<Svh>,
799    ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
800    where
801        'a: 'b,
802    {
803        if sess.opts.unstable_opts.dual_proc_macros {
804            // Use a new crate locator and crate rejections so trying to load a proc macro doesn't
805            // affect the error message we emit
806            let mut proc_macro_locator = locator.clone();
807
808            // Try to load a proc macro
809            proc_macro_locator.for_target_proc_macro(sess, path_kind);
810
811            // Load the proc macro crate for the target
812            let target_result =
813                match self.load(&mut proc_macro_locator, &mut CrateRejections::default())? {
814                    Some(LoadResult::Previous(cnum)) => {
815                        return Ok(Some((LoadResult::Previous(cnum), None)));
816                    }
817                    Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
818                    None => return Ok(None),
819                };
820
821            // Use the existing crate_rejections as we want the error message to be affected by
822            // loading the host proc macro.
823            *crate_rejections = CrateRejections::default();
824
825            // Load the proc macro crate for the host
826            locator.for_proc_macro(sess, path_kind);
827
828            locator.hash = host_hash;
829
830            let Some(host_result) = self.load(locator, crate_rejections)? else {
831                return Ok(None);
832            };
833
834            let host_result = match host_result {
835                LoadResult::Previous(..) => {
836                    {
    ::core::panicking::panic_fmt(format_args!("host and target proc macros must be loaded in lock-step"));
}panic!("host and target proc macros must be loaded in lock-step")
837                }
838                LoadResult::Loaded(library) => library,
839            };
840            Ok(Some((target_result.unwrap(), Some(host_result))))
841        } else {
842            // Use a new crate locator and crate rejections so trying to load a proc macro doesn't
843            // affect the error message we emit
844            let mut proc_macro_locator = locator.clone();
845
846            // Load the proc macro crate for the host
847            proc_macro_locator.for_proc_macro(sess, path_kind);
848
849            if let Some(host_result) =
850                self.load(&mut proc_macro_locator, &mut CrateRejections::default())?
851            {
852                Ok(Some((host_result, None)))
853            } else if sess.opts.unstable_opts.wasm_proc_macros {
854                // Load the proc macro crate for wasm
855                proc_macro_locator.for_wasm_proc_macro(sess, path_kind);
856
857                match self.load(&mut proc_macro_locator, &mut CrateRejections::default())? {
858                    Some(host_result) => Ok(Some((host_result, None))),
859                    None => Ok(None),
860                }
861            } else {
862                Ok(None)
863            }
864        }
865    }
866
867    fn resolve_crate<'tcx>(
868        &mut self,
869        tcx: TyCtxt<'tcx>,
870        name: Symbol,
871        span: Span,
872        dep_kind: CrateDepKind,
873        origin: CrateOrigin<'_>,
874    ) -> Option<CrateNum> {
875        self.used_extern_options.insert(name);
876        match self.maybe_resolve_crate(tcx, name, dep_kind, origin) {
877            Ok(cnum) => {
878                self.set_used_recursively(cnum);
879                Some(cnum)
880            }
881            Err(err) => {
882                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:882",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(882u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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 resolve crate {0} {1:?}",
                                                    name, dep_kind) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("failed to resolve crate {} {:?}", name, dep_kind);
883                // Crate maybe injected with `standard_library_imports::inject`, its span is
884                // dummy. We ignore compiler-injected prelude/sysroot loads here so they don't
885                // suppress unrelated diagnostics, such as "unsupported targets for std library"
886                // etc., these may be helpful for users to resolve crate loading failure.
887                self.has_crate_resolve_with_fail = true;
888                let missing_core = self
889                    .maybe_resolve_crate(
890                        tcx,
891                        sym::core,
892                        CrateDepKind::Unconditional,
893                        CrateOrigin::Extern,
894                    )
895                    .is_err();
896                err.report(tcx.sess, span, missing_core);
897                None
898            }
899        }
900    }
901
902    fn maybe_resolve_crate<'b, 'tcx>(
903        &'b mut self,
904        tcx: TyCtxt<'tcx>,
905        name: Symbol,
906        mut dep_kind: CrateDepKind,
907        origin: CrateOrigin<'b>,
908    ) -> Result<CrateNum, CrateError> {
909        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:909",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(909u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("resolving crate `{0}`",
                                                    name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("resolving crate `{}`", name);
910        if !name.as_str().is_ascii() {
911            return Err(CrateError::NonAsciiName(name));
912        }
913
914        let dep_root_for_errors = origin.dep_root_for_errors();
915        let dep = origin.dep();
916        let hash = dep.map(|d| d.hash);
917        let host_hash = dep.map(|d| d.host_hash).flatten();
918        let extra_filename = origin.dep_extra_filename();
919        let path_kind = if dep.is_some() { PathKind::Dependency } else { PathKind::Crate };
920        let private_dep = origin.private_dep();
921
922        let result = if let Some(cnum) = self.existing_match(name, hash) {
923            (LoadResult::Previous(cnum), None)
924        } else {
925            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:925",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(925u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("falling back to a load")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("falling back to a load");
926            let mut locator = CrateLocator::new(
927                tcx.sess,
928                &*self.metadata_loader,
929                name,
930                // The all loop is because `--crate-type=rlib --crate-type=rlib` is
931                // legal and produces both inside this type.
932                tcx.crate_types().iter().all(|c| *c == CrateType::Rlib),
933                hash,
934                extra_filename,
935                path_kind,
936            );
937            let mut crate_rejections = CrateRejections::default();
938
939            match self.load(&mut locator, &mut crate_rejections)? {
940                Some(res) => (res, None),
941                None => {
942                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:942",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(942u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("falling back to loading proc_macro")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("falling back to loading proc_macro");
943                    dep_kind = CrateDepKind::MacrosOnly;
944                    match self.load_proc_macro(
945                        tcx.sess,
946                        &mut locator,
947                        &mut crate_rejections,
948                        path_kind,
949                        host_hash,
950                    )? {
951                        Some(res) => res,
952                        None => {
953                            return Err(
954                                locator.into_error(crate_rejections, dep_root_for_errors.cloned())
955                            );
956                        }
957                    }
958                }
959            }
960        };
961
962        match result {
963            (LoadResult::Previous(cnum), None) => {
964                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:964",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(964u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("library for `{0}` was loaded previously, cnum {1}",
                                                    name, cnum) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("library for `{}` was loaded previously, cnum {cnum}", name);
965                // When `private_dep` is none, it indicates the directly dependent crate. If it is
966                // not specified by `--extern` on command line parameters, it may be
967                // `private-dependency` when `register_crate` is called for the first time. Then it must be updated to
968                // `public-dependency` here.
969                let private_dep = self.is_private_dep(&tcx.sess.opts.externs, name, private_dep);
970                let cdata = self.get_crate_data_mut(cnum);
971                if cdata.is_proc_macro_crate() {
972                    dep_kind = CrateDepKind::MacrosOnly;
973                }
974                cdata.set_dep_kind(cmp::max(cdata.dep_kind(), dep_kind));
975                cdata.update_and_private_dep(private_dep);
976                Ok(cnum)
977            }
978            (LoadResult::Loaded(library), host_library) => {
979                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:979",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(979u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("register newly loaded library for `{0}`",
                                                    name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("register newly loaded library for `{}`", name);
980                self.register_crate(tcx, host_library, origin, library, dep_kind, name, private_dep)
981            }
982            _ => ::core::panicking::panic_default_msg()panic!(),
983        }
984    }
985
986    fn load(
987        &self,
988        locator: &CrateLocator<'_>,
989        crate_rejections: &mut CrateRejections,
990    ) -> Result<Option<LoadResult>, CrateError> {
991        let Some(library) = locator.maybe_load_library_crate(crate_rejections)? else {
992            return Ok(None);
993        };
994
995        // In the case that we're loading a crate, but not matching
996        // against a hash, we could load a crate which has the same hash
997        // as an already loaded crate. If this is the case prevent
998        // duplicates by just using the first crate.
999        let root_name = library.metadata.get_root().name();
1000        let root_hash = library.metadata.get_crate_hash();
1001        let mut result = LoadResult::Loaded(library);
1002        for (cnum, data) in self.iter_crate_data() {
1003            if data.name() == root_name && data.hash() == root_hash {
1004                if !locator.hash.is_none() {
    ::core::panicking::panic("assertion failed: locator.hash.is_none()")
};assert!(locator.hash.is_none());
1005                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1005",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1005u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("load success, going to previous cnum: {0}",
                                                    cnum) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("load success, going to previous cnum: {}", cnum);
1006                result = LoadResult::Previous(cnum);
1007                break;
1008            }
1009        }
1010        Ok(Some(result))
1011    }
1012
1013    /// Go through the crate metadata and load any crates that it references.
1014    fn resolve_crate_deps(
1015        &mut self,
1016        tcx: TyCtxt<'_>,
1017        dep_root_for_errors: &CratePaths,
1018        crate_root: &CrateRoot,
1019        metadata: &MetadataBlob,
1020        krate: CrateNum,
1021        dep_kind: CrateDepKind,
1022        parent_is_private: bool,
1023    ) -> Result<CrateNumMap, CrateError> {
1024        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1024",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1024u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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!("resolving deps of external crate `{0}` with dep root `{1}`",
                                                    crate_root.name(), dep_root_for_errors.name) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1025            "resolving deps of external crate `{}` with dep root `{}`",
1026            crate_root.name(),
1027            dep_root_for_errors.name
1028        );
1029        if crate_root.is_proc_macro_crate() {
1030            return Ok(CrateNumMap::new());
1031        }
1032
1033        // The map from crate numbers in the crate we're resolving to local crate numbers.
1034        // We map 0 and all other holes in the map to our parent crate. The "additional"
1035        // self-dependencies should be harmless.
1036        let deps = crate_root.decode_crate_deps(metadata);
1037        // Encoded outside the hashed crate root; see `CrateRootUnhashed::dep_extra_filenames`.
1038        // Holds one entry per dep after the unused `LOCAL_CRATE` slot, so it lines up with `deps`
1039        // once that slot is skipped.
1040        let dep_extra_filenames = metadata.get_dep_extra_filenames();
1041        {
    match (&dep_extra_filenames.len(), &(deps.len() + 1)) {
        (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::Some(format_args!("expected one dep_extra_filename per crate dep, plus the unused LOCAL_CRATE slot")));
            }
        }
    }
};assert_eq!(
1042            dep_extra_filenames.len(),
1043            deps.len() + 1,
1044            "expected one dep_extra_filename per crate dep, plus the unused LOCAL_CRATE slot",
1045        );
1046        let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
1047        crate_num_map.push(krate);
1048        for (dep, dep_extra_filename) in
1049            deps.zip(dep_extra_filenames.iter().skip(1).map(String::as_str))
1050        {
1051            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1051",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1051u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("resolving dep `{0}`->`{1}` hash: `{2}` extra filename: `{3}` private {4}",
                                                    crate_root.name(), dep.name, dep.hash, dep_extra_filename,
                                                    dep.is_private) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!(
1052                "resolving dep `{}`->`{}` hash: `{}` extra filename: `{}` private {}",
1053                crate_root.name(),
1054                dep.name,
1055                dep.hash,
1056                dep_extra_filename,
1057                dep.is_private,
1058            );
1059            let dep_kind = match dep_kind {
1060                CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
1061                _ => dep.kind,
1062            };
1063            let cnum = self.maybe_resolve_crate(
1064                tcx,
1065                dep.name,
1066                dep_kind,
1067                CrateOrigin::IndirectDependency {
1068                    dep_root_for_errors,
1069                    parent_private: parent_is_private,
1070                    dep: &dep,
1071                    dep_extra_filename,
1072                },
1073            )?;
1074            crate_num_map.push(cnum);
1075        }
1076
1077        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1077",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1077u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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!("resolve_crate_deps: cnum_map for {0:?} is {1:?}",
                                                    krate, crate_num_map) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
1078        Ok(crate_num_map)
1079    }
1080
1081    fn dlsym_proc_macros(
1082        &self,
1083        path: &Path,
1084        stable_crate_id: StableCrateId,
1085    ) -> Result<&'static [ProcMacroClient], CrateError> {
1086        Ok(crate::host_dylib::dlsym_proc_macros(path, stable_crate_id)?)
1087    }
1088
1089    fn inject_panic_runtime(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1090        let is_std = attr::contains_name(&krate.attrs, sym::needs_panic_runtime);
1091        // If we're only compiling an rlib, then there's no need to select a
1092        // panic runtime, so we just skip this section entirely.
1093        let only_rlib = tcx.crate_types().iter().all(|ct| *ct == CrateType::Rlib);
1094        if only_rlib && !is_std {
1095            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1095",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1095u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("panic runtime injection skipped, only generating rlib")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("panic runtime injection skipped, only generating rlib");
1096            return;
1097        }
1098
1099        let desired_strategy = tcx.sess.panic_strategy();
1100        let name = match desired_strategy {
1101            PanicStrategy::Unwind => sym::panic_unwind,
1102            PanicStrategy::Abort => sym::panic_abort,
1103            PanicStrategy::ImmediateAbort => {
1104                // Immediate-aborting panics don't use a runtime.
1105                return;
1106            }
1107        };
1108
1109        // If we need a panic runtime, we try to find an existing one here. At
1110        // the same time we perform some general validation of the DAG we've got
1111        // going such as ensuring everything has a compatible panic strategy.
1112        let mut found_panic_runtime = None;
1113        let mut needs_panic_runtime = is_std;
1114        for (cnum, data) in self.iter_crate_data() {
1115            needs_panic_runtime |= data.needs_panic_runtime();
1116
1117            if data.is_panic_runtime() && data.name() == name {
1118                found_panic_runtime = Some(cnum)
1119            }
1120        }
1121
1122        // If we just don't need a panic runtime at all, then we're done here
1123        // and there's nothing else to do.
1124        if !needs_panic_runtime {
1125            return;
1126        }
1127
1128        // The panic runtime may already be resolved as a `std` dependency via `resolve_crate_deps`.
1129        //
1130        // For `build-std=always`, we avoid injecting it again as a direct dependency, because
1131        // Cargo relies on loading panic runtimes via the `-Ldependency` search paths.
1132        // We know that the panic runtime injected during the `std` build is the correct one
1133        // since Cargo passes the same `-Cpanic=` option to all crates.
1134        //
1135        // For prebuilt `std` it doesn't matter whether the runtime is injected directly or indirectly.
1136        if let Some(found_panic_runtime) = found_panic_runtime {
1137            self.injected_panic_runtime = Some(found_panic_runtime);
1138            return;
1139        }
1140
1141        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1141",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1141u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("panic runtime not found -- loading {0}",
                                                    name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("panic runtime not found -- loading {}", name);
1142
1143        // By this point we know that we need a panic runtime. Here we just load
1144        // an appropriate default runtime for our panic strategy.
1145        //
1146        // We may resolve to an already loaded crate (as the crate may not have
1147        // been explicitly linked prior to this), but this is fine.
1148        //
1149        // Also note that we have yet to perform validation of the crate graph
1150        // in terms of everyone has a compatible panic runtime format, that's
1151        // performed later as part of the `dependency_format` module.
1152        //
1153        // This has to be conditional as both panic_unwind and panic_abort may be present in the
1154        // crate graph at the same time. One of them will later be activated in dependency_formats.
1155        let Some(cnum) = self.resolve_crate(
1156            tcx,
1157            name,
1158            DUMMY_SP,
1159            CrateDepKind::Conditional,
1160            CrateOrigin::Injected,
1161        ) else {
1162            return;
1163        };
1164        let cdata = self.get_crate_data(cnum);
1165
1166        // Sanity check the loaded crate to ensure it is indeed a panic runtime.
1167        if !cdata.is_panic_runtime() {
1168            tcx.dcx().emit_err(diagnostics::CrateNotPanicRuntime { crate_name: name });
1169        }
1170        // Check the `panic_abort` was compiled with `-Cpanic=abort`.
1171        if desired_strategy == PanicStrategy::Abort
1172            && cdata.required_panic_strategy() != Some(PanicStrategy::Abort)
1173        {
1174            tcx.dcx().emit_err(diagnostics::NoPanicStrategy {
1175                crate_name: name,
1176                strategy: desired_strategy,
1177            });
1178        }
1179
1180        self.injected_panic_runtime = Some(cnum);
1181    }
1182
1183    fn inject_profiler_runtime(&mut self, tcx: TyCtxt<'_>) {
1184        let needs_profiler_runtime =
1185            tcx.sess.instrument_coverage() || tcx.sess.opts.cg.profile_generate.enabled();
1186        if !needs_profiler_runtime || tcx.sess.opts.unstable_opts.no_profiler_runtime {
1187            return;
1188        }
1189
1190        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1190",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1190u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("loading profiler")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("loading profiler");
1191
1192        // HACK: This uses conditional despite actually being unconditional to ensure that
1193        // there is no error emitted when two dylibs independently depend on profiler_builtins.
1194        // This is fine as profiler_builtins is always statically linked into the dylib just
1195        // like compiler_builtins. Unlike compiler_builtins however there is no guaranteed
1196        // common dylib that the duplicate crate check believes the crate to be included in.
1197        // add_upstream_rust_crates has a corresponding check that forces profiler_builtins
1198        // to be statically linked in even when marked as NotLinked.
1199        let name = Symbol::intern(&tcx.sess.opts.unstable_opts.profiler_runtime);
1200        let Some(cnum) = self.resolve_crate(
1201            tcx,
1202            name,
1203            DUMMY_SP,
1204            CrateDepKind::Conditional,
1205            CrateOrigin::Injected,
1206        ) else {
1207            return;
1208        };
1209        let cdata = self.get_crate_data(cnum);
1210
1211        // Sanity check the loaded crate to ensure it is indeed a profiler runtime
1212        if !cdata.is_profiler_runtime() {
1213            tcx.dcx().emit_err(diagnostics::NotProfilerRuntime { crate_name: name });
1214        }
1215    }
1216
1217    fn inject_allocator_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1218        self.has_global_allocator =
1219            match &*fn_spans(krate, Symbol::intern(&global_fn_name(sym::alloc))) {
1220                [span1, span2, ..] => {
1221                    tcx.dcx().emit_err(diagnostics::NoMultipleGlobalAlloc {
1222                        span2: *span2,
1223                        span1: *span1,
1224                    });
1225                    true
1226                }
1227                spans => !spans.is_empty(),
1228            };
1229        let alloc_error_handler = Symbol::intern(&global_fn_name(ALLOC_ERROR_HANDLER));
1230        self.has_alloc_error_handler = match &*fn_spans(krate, alloc_error_handler) {
1231            [span1, span2, ..] => {
1232                tcx.dcx().emit_err(diagnostics::NoMultipleAllocErrorHandler {
1233                    span2: *span2,
1234                    span1: *span1,
1235                });
1236                true
1237            }
1238            spans => !spans.is_empty(),
1239        };
1240
1241        // Check to see if we actually need an allocator. This desire comes
1242        // about through the `#![needs_allocator]` attribute and is typically
1243        // written down in liballoc.
1244        if !attr::contains_name(&krate.attrs, sym::needs_allocator)
1245            && !self.iter_crate_data().any(|(_, data)| data.needs_allocator())
1246        {
1247            return;
1248        }
1249
1250        // At this point we've determined that we need an allocator. Let's see
1251        // if our compilation session actually needs an allocator based on what
1252        // we're emitting.
1253        let all_rlib = tcx.crate_types().iter().all(|ct| #[allow(non_exhaustive_omitted_patterns)] match *ct {
    CrateType::Rlib => true,
    _ => false,
}matches!(*ct, CrateType::Rlib));
1254        if all_rlib {
1255            return;
1256        }
1257
1258        // Ok, we need an allocator. Not only that but we're actually going to
1259        // create an artifact that needs one linked in. Let's go find the one
1260        // that we're going to link in.
1261        //
1262        // First up we check for global allocators. Look at the crate graph here
1263        // and see what's a global allocator, including if we ourselves are a
1264        // global allocator.
1265        #[allow(rustc::symbol_intern_string_literal)]
1266        let this_crate = Symbol::intern("this crate");
1267
1268        let mut global_allocator = self.has_global_allocator.then_some(this_crate);
1269        for (_, data) in self.iter_crate_data() {
1270            if data.has_global_allocator() {
1271                match global_allocator {
1272                    Some(other_crate) => {
1273                        tcx.dcx().emit_err(diagnostics::ConflictingGlobalAlloc {
1274                            crate_name: data.name(),
1275                            other_crate_name: other_crate,
1276                            this_crate: other_crate == this_crate,
1277                        });
1278                    }
1279                    None => global_allocator = Some(data.name()),
1280                }
1281            }
1282        }
1283        let mut alloc_error_handler = self.has_alloc_error_handler.then_some(this_crate);
1284        for (_, data) in self.iter_crate_data() {
1285            if data.has_alloc_error_handler() {
1286                match alloc_error_handler {
1287                    Some(other_crate) => {
1288                        tcx.dcx().emit_err(diagnostics::ConflictingAllocErrorHandler {
1289                            crate_name: data.name(),
1290                            other_crate_name: other_crate,
1291                        });
1292                    }
1293                    None => alloc_error_handler = Some(data.name()),
1294                }
1295            }
1296        }
1297
1298        if global_allocator.is_some() {
1299            self.allocator_kind = Some(AllocatorKind::Global);
1300        } else {
1301            // Ok we haven't found a global allocator but we still need an
1302            // allocator. At this point our allocator request is typically fulfilled
1303            // by the standard library, denoted by the `#![default_lib_allocator]`
1304            // attribute.
1305            if !attr::contains_name(&krate.attrs, sym::default_lib_allocator)
1306                && !self.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
1307            {
1308                tcx.dcx().emit_err(diagnostics::GlobalAllocRequired);
1309            }
1310            self.allocator_kind = Some(AllocatorKind::Default);
1311        }
1312
1313        if alloc_error_handler.is_some() {
1314            self.alloc_error_handler_kind = Some(AllocatorKind::Global);
1315        } else {
1316            // The alloc crate provides a default allocation error handler if
1317            // one isn't specified.
1318            self.alloc_error_handler_kind = Some(AllocatorKind::Default);
1319        }
1320    }
1321
1322    fn inject_forced_externs(&mut self, tcx: TyCtxt<'_>) {
1323        for (name, entry) in tcx.sess.opts.externs.iter() {
1324            if entry.force {
1325                let name_interned = Symbol::intern(name);
1326                if !self.used_extern_options.contains(&name_interned) {
1327                    self.resolve_crate(
1328                        tcx,
1329                        name_interned,
1330                        DUMMY_SP,
1331                        CrateDepKind::Unconditional,
1332                        CrateOrigin::Extern,
1333                    );
1334                }
1335            }
1336        }
1337    }
1338
1339    /// Inject the `compiler_builtins` crate if it is not already in the graph.
1340    fn inject_compiler_builtins(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1341        // `compiler_builtins` does not get extern builtins, nor do `#![no_core]` crates
1342        if attr::contains_name(&krate.attrs, sym::compiler_builtins)
1343            || attr::contains_name(&krate.attrs, sym::no_core)
1344        {
1345            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1345",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1345u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("`compiler_builtins` unneeded")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("`compiler_builtins` unneeded");
1346            return;
1347        }
1348
1349        // If a `#![compiler_builtins]` crate already exists, avoid injecting it twice. This is
1350        // the common case since usually it appears as a dependency of `std` or `alloc`.
1351        for (cnum, cmeta) in self.iter_crate_data() {
1352            if cmeta.is_compiler_builtins() {
1353                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1353",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1353u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("`compiler_builtins` already exists (cnum = {0}); skipping injection",
                                                    cnum) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("`compiler_builtins` already exists (cnum = {cnum}); skipping injection");
1354                return;
1355            }
1356        }
1357
1358        // `compiler_builtins` is not yet in the graph; inject it. Error on resolution failure.
1359        let Some(cnum) = self.resolve_crate(
1360            tcx,
1361            sym::compiler_builtins,
1362            krate.spans.inner_span.shrink_to_lo(),
1363            CrateDepKind::Unconditional,
1364            CrateOrigin::Injected,
1365        ) else {
1366            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1366",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1366u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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!("`compiler_builtins` not resolved")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("`compiler_builtins` not resolved");
1367            return;
1368        };
1369
1370        // Sanity check that the loaded crate is `#![compiler_builtins]`
1371        let cdata = self.get_crate_data(cnum);
1372        if !cdata.is_compiler_builtins() {
1373            tcx.dcx().emit_err(diagnostics::CrateNotCompilerBuiltins { crate_name: cdata.name() });
1374        }
1375    }
1376
1377    fn report_unused_deps_in_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1378        // Make a point span rather than covering the whole file
1379        let span = krate.spans.inner_span.shrink_to_lo();
1380        // Complain about anything left over
1381        for (name, entry) in tcx.sess.opts.externs.iter() {
1382            if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
1383                // Don't worry about pathless `--extern foo` sysroot references
1384                continue;
1385            }
1386            if entry.nounused_dep || entry.force {
1387                // We're not worried about this one
1388                continue;
1389            }
1390            let name_interned = Symbol::intern(name);
1391            if self.used_extern_options.contains(&name_interned) {
1392                continue;
1393            }
1394
1395            // Got a real unused --extern
1396            if tcx.sess.opts.json_unused_externs.is_enabled() {
1397                self.unused_externs.push(name_interned);
1398                continue;
1399            }
1400
1401            tcx.sess.psess.buffer_lint(
1402                UNUSED_CRATE_DEPENDENCIES,
1403                span,
1404                ast::CRATE_NODE_ID,
1405                diagnostics::UnusedCrateDependency {
1406                    extern_crate: name_interned,
1407                    local_crate: tcx.crate_name(LOCAL_CRATE),
1408                },
1409            );
1410        }
1411    }
1412
1413    fn report_future_incompatible_deps(&self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1414        let name = tcx.crate_name(LOCAL_CRATE);
1415
1416        if name.as_str() == "wasm_bindgen" {
1417            let major = env::var("CARGO_PKG_VERSION_MAJOR")
1418                .ok()
1419                .and_then(|major| u64::from_str(&major).ok());
1420            let minor = env::var("CARGO_PKG_VERSION_MINOR")
1421                .ok()
1422                .and_then(|minor| u64::from_str(&minor).ok());
1423            let patch = env::var("CARGO_PKG_VERSION_PATCH")
1424                .ok()
1425                .and_then(|patch| u64::from_str(&patch).ok());
1426
1427            match (major, minor, patch) {
1428                // v1 or bigger is valid.
1429                (Some(1..), _, _) => return,
1430                // v0.3 or bigger is valid.
1431                (Some(0), Some(3..), _) => return,
1432                // v0.2.88 or bigger is valid.
1433                (Some(0), Some(2), Some(88..)) => return,
1434                // Not using Cargo.
1435                (None, None, None) => return,
1436                _ => (),
1437            }
1438
1439            // Make a point span rather than covering the whole file
1440            let span = krate.spans.inner_span.shrink_to_lo();
1441
1442            tcx.sess.dcx().emit_err(diagnostics::WasmCAbi { span });
1443        }
1444    }
1445
1446    pub fn postprocess(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1447        self.inject_compiler_builtins(tcx, krate);
1448        self.inject_forced_externs(tcx);
1449        self.inject_profiler_runtime(tcx);
1450        self.inject_allocator_crate(tcx, krate);
1451        self.inject_panic_runtime(tcx, krate);
1452
1453        self.report_unused_deps_in_crate(tcx, krate);
1454        self.report_future_incompatible_deps(tcx, krate);
1455
1456        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1456",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1456u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::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:?}",
                                                    self) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("{:?}", self);
1457    }
1458
1459    /// Process an `extern crate foo` AST node.
1460    pub fn process_extern_crate(
1461        &mut self,
1462        tcx: TyCtxt<'_>,
1463        item: &ast::Item,
1464        def_id: LocalDefId,
1465        definitions: &Definitions,
1466    ) -> Option<CrateNum> {
1467        match item.kind {
1468            ast::ItemKind::ExternCrate(orig_name, ident) => {
1469                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs:1469",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1469u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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!("resolving extern crate stmt. ident: {0} orig_name: {1:?}",
                                                    ident, orig_name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolving extern crate stmt. ident: {} orig_name: {:?}", ident, orig_name);
1470                let name = match orig_name {
1471                    Some(orig_name) => {
1472                        validate_crate_name(tcx.sess, orig_name, Some(item.span));
1473                        orig_name
1474                    }
1475                    None => ident.name,
1476                };
1477                let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
1478                    CrateDepKind::MacrosOnly
1479                } else {
1480                    CrateDepKind::Unconditional
1481                };
1482
1483                let cnum =
1484                    self.resolve_crate(tcx, name, item.span, dep_kind, CrateOrigin::Extern)?;
1485
1486                let def_path = definitions.def_path(def_id);
1487                // An extern crate is only globally nameable if every segment in its path
1488                // is in the type namespace (i.e., it is purely nested inside modules).
1489                // If any segment is in the value namespace (e.g. inside a fn or const),
1490                // it is unnameable from outside that block.
1491                let is_unnameable =
1492                    def_path.data.iter().any(|d| !#[allow(non_exhaustive_omitted_patterns)] match d.data {
    DefPathData::TypeNs(_) => true,
    _ => false,
}matches!(d.data, DefPathData::TypeNs(_)));
1493                self.update_extern_crate(
1494                    cnum,
1495                    name,
1496                    ExternCrate {
1497                        src: if is_unnameable {
1498                            ExternCrateSource::Path
1499                        } else {
1500                            ExternCrateSource::Extern(def_id.to_def_id())
1501                        },
1502                        span: item.span,
1503                        path_len: if is_unnameable { usize::MAX } else { def_path.data.len() },
1504                        dependency_of: LOCAL_CRATE,
1505                    },
1506                );
1507                Some(cnum)
1508            }
1509            _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
1510        }
1511    }
1512
1513    pub fn process_path_extern(
1514        &mut self,
1515        tcx: TyCtxt<'_>,
1516        name: Symbol,
1517        span: Span,
1518    ) -> Option<CrateNum> {
1519        let cnum =
1520            self.resolve_crate(tcx, name, span, CrateDepKind::Unconditional, CrateOrigin::Extern)?;
1521
1522        self.update_extern_crate(
1523            cnum,
1524            name,
1525            ExternCrate {
1526                src: ExternCrateSource::Path,
1527                span,
1528                // to have the least priority in `update_extern_crate`
1529                path_len: usize::MAX,
1530                dependency_of: LOCAL_CRATE,
1531            },
1532        );
1533
1534        Some(cnum)
1535    }
1536
1537    pub fn maybe_process_path_extern(&mut self, tcx: TyCtxt<'_>, name: Symbol) -> Option<CrateNum> {
1538        match self.maybe_resolve_crate(tcx, name, CrateDepKind::Unconditional, CrateOrigin::Extern)
1539        {
1540            Ok(cnum) => Some(cnum),
1541            Err(_) => {
1542                self.has_crate_resolve_with_fail = true;
1543                None
1544            }
1545        }
1546    }
1547}
1548
1549fn fn_spans(krate: &ast::Crate, name: Symbol) -> Vec<Span> {
1550    struct Finder {
1551        name: Symbol,
1552        spans: Vec<Span>,
1553    }
1554    impl<'ast> visit::Visitor<'ast> for Finder {
1555        fn visit_item(&mut self, item: &'ast ast::Item) {
1556            if let Some(ident) = item.kind.ident()
1557                && ident.name == self.name
1558                && attr::contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1559            {
1560                self.spans.push(item.span);
1561            }
1562            visit::walk_item(self, item)
1563        }
1564    }
1565
1566    let mut f = Finder { name, spans: Vec::new() };
1567    visit::walk_crate(&mut f, krate);
1568    f.spans
1569}