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