Skip to main content

rustc_metadata/
creader.rs

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