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