rustc_metadata/rmeta/decoder/
cstore_impl.rs

1use std::any::Any;
2use std::mem;
3use std::sync::Arc;
4
5use rustc_attr_data_structures::Deprecation;
6use rustc_hir::def::{CtorKind, DefKind, Res};
7use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE};
8use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
9use rustc_middle::arena::ArenaAllocatable;
10use rustc_middle::bug;
11use rustc_middle::metadata::ModChild;
12use rustc_middle::middle::exported_symbols::ExportedSymbol;
13use rustc_middle::middle::stability::DeprecationEntry;
14use rustc_middle::query::{ExternProviders, LocalCrate};
15use rustc_middle::ty::fast_reject::SimplifiedType;
16use rustc_middle::ty::{self, TyCtxt};
17use rustc_middle::util::Providers;
18use rustc_session::cstore::{CrateStore, ExternCrate};
19use rustc_session::{Session, StableCrateId};
20use rustc_span::hygiene::ExpnId;
21use rustc_span::{Span, Symbol, kw};
22
23use super::{Decodable, DecodeContext, DecodeIterator};
24use crate::creader::{CStore, LoadedMacro};
25use crate::rmeta::AttrFlags;
26use crate::rmeta::table::IsDefault;
27use crate::{foreign_modules, native_libs};
28
29trait ProcessQueryValue<'tcx, T> {
30    fn process_decoded(self, _tcx: TyCtxt<'tcx>, _err: impl Fn() -> !) -> T;
31}
32
33impl<T> ProcessQueryValue<'_, T> for T {
34    #[inline(always)]
35    fn process_decoded(self, _tcx: TyCtxt<'_>, _err: impl Fn() -> !) -> T {
36        self
37    }
38}
39
40impl<'tcx, T> ProcessQueryValue<'tcx, ty::EarlyBinder<'tcx, T>> for T {
41    #[inline(always)]
42    fn process_decoded(self, _tcx: TyCtxt<'_>, _err: impl Fn() -> !) -> ty::EarlyBinder<'tcx, T> {
43        ty::EarlyBinder::bind(self)
44    }
45}
46
47impl<T> ProcessQueryValue<'_, T> for Option<T> {
48    #[inline(always)]
49    fn process_decoded(self, _tcx: TyCtxt<'_>, err: impl Fn() -> !) -> T {
50        if let Some(value) = self { value } else { err() }
51    }
52}
53
54impl<'tcx, T: ArenaAllocatable<'tcx>> ProcessQueryValue<'tcx, &'tcx T> for Option<T> {
55    #[inline(always)]
56    fn process_decoded(self, tcx: TyCtxt<'tcx>, err: impl Fn() -> !) -> &'tcx T {
57        if let Some(value) = self { tcx.arena.alloc(value) } else { err() }
58    }
59}
60
61impl<T, E> ProcessQueryValue<'_, Result<Option<T>, E>> for Option<T> {
62    #[inline(always)]
63    fn process_decoded(self, _tcx: TyCtxt<'_>, _err: impl Fn() -> !) -> Result<Option<T>, E> {
64        Ok(self)
65    }
66}
67
68impl<'a, 'tcx, T: Copy + Decodable<DecodeContext<'a, 'tcx>>> ProcessQueryValue<'tcx, &'tcx [T]>
69    for Option<DecodeIterator<'a, 'tcx, T>>
70{
71    #[inline(always)]
72    fn process_decoded(self, tcx: TyCtxt<'tcx>, err: impl Fn() -> !) -> &'tcx [T] {
73        if let Some(iter) = self { tcx.arena.alloc_from_iter(iter) } else { err() }
74    }
75}
76
77impl<'a, 'tcx, T: Copy + Decodable<DecodeContext<'a, 'tcx>>>
78    ProcessQueryValue<'tcx, ty::EarlyBinder<'tcx, &'tcx [T]>>
79    for Option<DecodeIterator<'a, 'tcx, T>>
80{
81    #[inline(always)]
82    fn process_decoded(
83        self,
84        tcx: TyCtxt<'tcx>,
85        err: impl Fn() -> !,
86    ) -> ty::EarlyBinder<'tcx, &'tcx [T]> {
87        ty::EarlyBinder::bind(if let Some(iter) = self {
88            tcx.arena.alloc_from_iter(iter)
89        } else {
90            err()
91        })
92    }
93}
94
95impl<'a, 'tcx, T: Copy + Decodable<DecodeContext<'a, 'tcx>>>
96    ProcessQueryValue<'tcx, Option<&'tcx [T]>> for Option<DecodeIterator<'a, 'tcx, T>>
97{
98    #[inline(always)]
99    fn process_decoded(self, tcx: TyCtxt<'tcx>, _err: impl Fn() -> !) -> Option<&'tcx [T]> {
100        if let Some(iter) = self { Some(&*tcx.arena.alloc_from_iter(iter)) } else { None }
101    }
102}
103
104impl ProcessQueryValue<'_, Option<DeprecationEntry>> for Option<Deprecation> {
105    #[inline(always)]
106    fn process_decoded(self, _tcx: TyCtxt<'_>, _err: impl Fn() -> !) -> Option<DeprecationEntry> {
107        self.map(DeprecationEntry::external)
108    }
109}
110
111macro_rules! provide_one {
112    ($tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => { table }) => {
113        provide_one! {
114            $tcx, $def_id, $other, $cdata, $name => {
115                $cdata
116                    .root
117                    .tables
118                    .$name
119                    .get($cdata, $def_id.index)
120                    .map(|lazy| lazy.decode(($cdata, $tcx)))
121                    .process_decoded($tcx, || panic!("{:?} does not have a {:?}", $def_id, stringify!($name)))
122            }
123        }
124    };
125    ($tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => { table_defaulted_array }) => {
126        provide_one! {
127            $tcx, $def_id, $other, $cdata, $name => {
128                let lazy = $cdata.root.tables.$name.get($cdata, $def_id.index);
129                let value = if lazy.is_default() {
130                    &[] as &[_]
131                } else {
132                    $tcx.arena.alloc_from_iter(lazy.decode(($cdata, $tcx)))
133                };
134                value.process_decoded($tcx, || panic!("{:?} does not have a {:?}", $def_id, stringify!($name)))
135            }
136        }
137    };
138    ($tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => { table_direct }) => {
139        provide_one! {
140            $tcx, $def_id, $other, $cdata, $name => {
141                // We don't decode `table_direct`, since it's not a Lazy, but an actual value
142                $cdata
143                    .root
144                    .tables
145                    .$name
146                    .get($cdata, $def_id.index)
147                    .process_decoded($tcx, || panic!("{:?} does not have a {:?}", $def_id, stringify!($name)))
148            }
149        }
150    };
151    ($tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => $compute:block) => {
152        fn $name<'tcx>(
153            $tcx: TyCtxt<'tcx>,
154            def_id_arg: rustc_middle::query::queries::$name::Key<'tcx>,
155        ) -> rustc_middle::query::queries::$name::ProvidedValue<'tcx> {
156            let _prof_timer =
157                $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
158
159            #[allow(unused_variables)]
160            let ($def_id, $other) = def_id_arg.into_args();
161            assert!(!$def_id.is_local());
162
163            // External query providers call `crate_hash` in order to register a dependency
164            // on the crate metadata. The exception is `crate_hash` itself, which obviously
165            // doesn't need to do this (and can't, as it would cause a query cycle).
166            use rustc_middle::dep_graph::dep_kinds;
167            if dep_kinds::$name != dep_kinds::crate_hash && $tcx.dep_graph.is_fully_enabled() {
168                $tcx.ensure_ok().crate_hash($def_id.krate);
169            }
170
171            let cdata = rustc_data_structures::sync::FreezeReadGuard::map(CStore::from_tcx($tcx), |c| {
172                c.get_crate_data($def_id.krate).cdata
173            });
174            let $cdata = crate::creader::CrateMetadataRef {
175                cdata: &cdata,
176                cstore: &CStore::from_tcx($tcx),
177            };
178
179            $compute
180        }
181    };
182}
183
184macro_rules! provide {
185    ($tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
186      $($name:ident => { $($compute:tt)* })*) => {
187        fn provide_extern(providers: &mut ExternProviders) {
188            $(provide_one! {
189                $tcx, $def_id, $other, $cdata, $name => { $($compute)* }
190            })*
191
192            *providers = ExternProviders {
193                $($name,)*
194                ..*providers
195            };
196        }
197    }
198}
199
200// small trait to work around different signature queries all being defined via
201// the macro above.
202trait IntoArgs {
203    type Other;
204    fn into_args(self) -> (DefId, Self::Other);
205}
206
207impl IntoArgs for DefId {
208    type Other = ();
209    fn into_args(self) -> (DefId, ()) {
210        (self, ())
211    }
212}
213
214impl IntoArgs for CrateNum {
215    type Other = ();
216    fn into_args(self) -> (DefId, ()) {
217        (self.as_def_id(), ())
218    }
219}
220
221impl IntoArgs for (CrateNum, DefId) {
222    type Other = DefId;
223    fn into_args(self) -> (DefId, DefId) {
224        (self.0.as_def_id(), self.1)
225    }
226}
227
228impl<'tcx> IntoArgs for ty::InstanceKind<'tcx> {
229    type Other = ();
230    fn into_args(self) -> (DefId, ()) {
231        (self.def_id(), ())
232    }
233}
234
235impl IntoArgs for (CrateNum, SimplifiedType) {
236    type Other = SimplifiedType;
237    fn into_args(self) -> (DefId, SimplifiedType) {
238        (self.0.as_def_id(), self.1)
239    }
240}
241
242provide! { tcx, def_id, other, cdata,
243    explicit_item_bounds => { table_defaulted_array }
244    explicit_item_self_bounds => { table_defaulted_array }
245    explicit_predicates_of => { table }
246    generics_of => { table }
247    inferred_outlives_of => { table_defaulted_array }
248    explicit_super_predicates_of => { table_defaulted_array }
249    explicit_implied_predicates_of => { table_defaulted_array }
250    type_of => { table }
251    type_alias_is_lazy => { table_direct }
252    variances_of => { table }
253    fn_sig => { table }
254    codegen_fn_attrs => { table }
255    impl_trait_header => { table }
256    const_param_default => { table }
257    object_lifetime_default => { table }
258    thir_abstract_const => { table }
259    optimized_mir => { table }
260    mir_for_ctfe => { table }
261    closure_saved_names_of_captured_variables => { table }
262    mir_coroutine_witnesses => { table }
263    promoted_mir => { table }
264    def_span => { table }
265    def_ident_span => { table }
266    lookup_stability => { table }
267    lookup_const_stability => { table }
268    lookup_default_body_stability => { table }
269    lookup_deprecation_entry => { table }
270    params_in_repr => { table }
271    def_kind => { cdata.def_kind(def_id.index) }
272    impl_parent => { table }
273    defaultness => { table_direct }
274    constness => { table_direct }
275    const_conditions => { table }
276    explicit_implied_const_bounds => { table_defaulted_array }
277    coerce_unsized_info => {
278        Ok(cdata
279            .root
280            .tables
281            .coerce_unsized_info
282            .get(cdata, def_id.index)
283            .map(|lazy| lazy.decode((cdata, tcx)))
284            .process_decoded(tcx, || panic!("{def_id:?} does not have coerce_unsized_info"))) }
285    mir_const_qualif => { table }
286    rendered_const => { table }
287    rendered_precise_capturing_args => { table }
288    asyncness => { table_direct }
289    fn_arg_idents => { table }
290    coroutine_kind => { table_direct }
291    coroutine_for_closure => { table }
292    coroutine_by_move_body_def_id => { table }
293    eval_static_initializer => {
294        Ok(cdata
295            .root
296            .tables
297            .eval_static_initializer
298            .get(cdata, def_id.index)
299            .map(|lazy| lazy.decode((cdata, tcx)))
300            .unwrap_or_else(|| panic!("{def_id:?} does not have eval_static_initializer")))
301    }
302    trait_def => { table }
303    deduced_param_attrs => {
304        // FIXME: `deduced_param_attrs` has some sketchy encoding settings,
305        // where we don't encode unless we're optimizing, doing codegen,
306        // and not incremental (see `encoder.rs`). I don't think this is right!
307        cdata
308            .root
309            .tables
310            .deduced_param_attrs
311            .get(cdata, def_id.index)
312            .map(|lazy| {
313                &*tcx.arena.alloc_from_iter(lazy.decode((cdata, tcx)))
314            })
315            .unwrap_or_default()
316    }
317    opaque_ty_origin => { table }
318    assumed_wf_types_for_rpitit => { table }
319    collect_return_position_impl_trait_in_trait_tys => {
320        Ok(cdata
321            .root
322            .tables
323            .trait_impl_trait_tys
324            .get(cdata, def_id.index)
325            .map(|lazy| lazy.decode((cdata, tcx)))
326            .process_decoded(tcx, || panic!("{def_id:?} does not have trait_impl_trait_tys")))
327    }
328
329    associated_types_for_impl_traits_in_associated_fn => { table_defaulted_array }
330
331    visibility => { cdata.get_visibility(def_id.index) }
332    adt_def => { cdata.get_adt_def(def_id.index, tcx) }
333    adt_destructor => { table }
334    adt_async_destructor => { table }
335    associated_item_def_ids => {
336        tcx.arena.alloc_from_iter(cdata.get_associated_item_or_field_def_ids(def_id.index))
337    }
338    associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
339    inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
340    attrs_for_def => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) }
341    is_mir_available => { cdata.is_item_mir_available(def_id.index) }
342    is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
343    cross_crate_inlinable => { table_direct }
344
345    dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
346    is_private_dep => { cdata.private_dep }
347    is_panic_runtime => { cdata.root.panic_runtime }
348    is_compiler_builtins => { cdata.root.compiler_builtins }
349    has_global_allocator => { cdata.root.has_global_allocator }
350    has_alloc_error_handler => { cdata.root.has_alloc_error_handler }
351    has_panic_handler => { cdata.root.has_panic_handler }
352    is_profiler_runtime => { cdata.root.profiler_runtime }
353    required_panic_strategy => { cdata.root.required_panic_strategy }
354    panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
355    extern_crate => { cdata.extern_crate.map(|c| &*tcx.arena.alloc(c)) }
356    is_no_builtins => { cdata.root.no_builtins }
357    symbol_mangling_version => { cdata.root.symbol_mangling_version }
358    specialization_enabled_in => { cdata.root.specialization_enabled_in }
359    reachable_non_generics => {
360        let reachable_non_generics = tcx
361            .exported_symbols(cdata.cnum)
362            .iter()
363            .filter_map(|&(exported_symbol, export_info)| {
364                if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
365                    Some((def_id, export_info))
366                } else {
367                    None
368                }
369            })
370            .collect();
371
372        reachable_non_generics
373    }
374    native_libraries => { cdata.get_native_libraries(tcx.sess).collect() }
375    foreign_modules => { cdata.get_foreign_modules(tcx.sess).map(|m| (m.def_id, m)).collect() }
376    crate_hash => { cdata.root.header.hash }
377    crate_host_hash => { cdata.host_hash }
378    crate_name => { cdata.root.header.name }
379    num_extern_def_ids => { cdata.num_def_ids() }
380
381    extra_filename => { cdata.root.extra_filename.clone() }
382
383    traits => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
384    trait_impls_in_crate => { tcx.arena.alloc_from_iter(cdata.get_trait_impls()) }
385    implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
386    crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) }
387
388    dep_kind => { cdata.dep_kind }
389    module_children => {
390        tcx.arena.alloc_from_iter(cdata.get_module_children(def_id.index, tcx.sess))
391    }
392    lib_features => { cdata.get_lib_features() }
393    stability_implications => {
394        cdata.get_stability_implications(tcx).iter().copied().collect()
395    }
396    stripped_cfg_items => { cdata.get_stripped_cfg_items(cdata.cnum, tcx) }
397    intrinsic_raw => { cdata.get_intrinsic(def_id.index) }
398    defined_lang_items => { cdata.get_lang_items(tcx) }
399    diagnostic_items => { cdata.get_diagnostic_items() }
400    missing_lang_items => { cdata.get_missing_lang_items(tcx) }
401
402    missing_extern_crate_item => {
403        matches!(cdata.extern_crate, Some(extern_crate) if !extern_crate.is_direct())
404    }
405
406    used_crate_source => { Arc::clone(&cdata.source) }
407    debugger_visualizers => { cdata.get_debugger_visualizers() }
408
409    exportable_items => { tcx.arena.alloc_from_iter(cdata.get_exportable_items()) }
410    stable_order_of_exportable_impls => { tcx.arena.alloc(cdata.get_stable_order_of_exportable_impls().collect()) }
411    exported_symbols => {
412        let syms = cdata.exported_symbols(tcx);
413
414        // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
415        // to block export of generics from dylibs, but we must fix
416        // rust-lang/rust#65890 before we can do that robustly.
417
418        syms
419    }
420
421    crate_extern_paths => { cdata.source().paths().cloned().collect() }
422    expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
423    is_doc_hidden => { cdata.get_attr_flags(def_id.index).contains(AttrFlags::IS_DOC_HIDDEN) }
424    doc_link_resolutions => { tcx.arena.alloc(cdata.get_doc_link_resolutions(def_id.index)) }
425    doc_link_traits_in_scope => {
426        tcx.arena.alloc_from_iter(cdata.get_doc_link_traits_in_scope(def_id.index))
427    }
428    anon_const_kind => { table }
429}
430
431pub(in crate::rmeta) fn provide(providers: &mut Providers) {
432    provide_cstore_hooks(providers);
433    providers.queries = rustc_middle::query::Providers {
434        allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
435        alloc_error_handler_kind: |tcx, ()| CStore::from_tcx(tcx).alloc_error_handler_kind(),
436        is_private_dep: |_tcx, LocalCrate| false,
437        native_library: |tcx, id| {
438            tcx.native_libraries(id.krate)
439                .iter()
440                .filter(|lib| native_libs::relevant_lib(tcx.sess, lib))
441                .find(|lib| {
442                    let Some(fm_id) = lib.foreign_module else {
443                        return false;
444                    };
445                    let map = tcx.foreign_modules(id.krate);
446                    map.get(&fm_id)
447                        .expect("failed to find foreign module")
448                        .foreign_items
449                        .contains(&id)
450                })
451        },
452        native_libraries: native_libs::collect,
453        foreign_modules: foreign_modules::collect,
454
455        // Returns a map from a sufficiently visible external item (i.e., an
456        // external item that is visible from at least one local module) to a
457        // sufficiently visible parent (considering modules that re-export the
458        // external item to be parents).
459        visible_parent_map: |tcx, ()| {
460            use std::collections::hash_map::Entry;
461            use std::collections::vec_deque::VecDeque;
462
463            let mut visible_parent_map: DefIdMap<DefId> = Default::default();
464            // This is a secondary visible_parent_map, storing the DefId of
465            // parents that re-export the child as `_` or module parents
466            // which are `#[doc(hidden)]`. Since we prefer paths that don't
467            // do this, merge this map at the end, only if we're missing
468            // keys from the former.
469            // This is a rudimentary check that does not catch all cases,
470            // just the easiest.
471            let mut fallback_map: Vec<(DefId, DefId)> = Default::default();
472
473            // Issue 46112: We want the map to prefer the shortest
474            // paths when reporting the path to an item. Therefore we
475            // build up the map via a breadth-first search (BFS),
476            // which naturally yields minimal-length paths.
477            //
478            // Note that it needs to be a BFS over the whole forest of
479            // crates, not just each individual crate; otherwise you
480            // only get paths that are locally minimal with respect to
481            // whatever crate we happened to encounter first in this
482            // traversal, but not globally minimal across all crates.
483            let bfs_queue = &mut VecDeque::new();
484
485            for &cnum in tcx.crates(()) {
486                // Ignore crates without a corresponding local `extern crate` item.
487                if tcx.missing_extern_crate_item(cnum) {
488                    continue;
489                }
490
491                bfs_queue.push_back(cnum.as_def_id());
492            }
493
494            let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
495                if !child.vis.is_public() {
496                    return;
497                }
498
499                if let Some(def_id) = child.res.opt_def_id() {
500                    if child.ident.name == kw::Underscore {
501                        fallback_map.push((def_id, parent));
502                        return;
503                    }
504
505                    if tcx.is_doc_hidden(parent) {
506                        fallback_map.push((def_id, parent));
507                        return;
508                    }
509
510                    match visible_parent_map.entry(def_id) {
511                        Entry::Occupied(mut entry) => {
512                            // If `child` is defined in crate `cnum`, ensure
513                            // that it is mapped to a parent in `cnum`.
514                            if def_id.is_local() && entry.get().is_local() {
515                                entry.insert(parent);
516                            }
517                        }
518                        Entry::Vacant(entry) => {
519                            entry.insert(parent);
520                            if matches!(
521                                child.res,
522                                Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
523                            ) {
524                                bfs_queue.push_back(def_id);
525                            }
526                        }
527                    }
528                }
529            };
530
531            while let Some(def) = bfs_queue.pop_front() {
532                for child in tcx.module_children(def).iter() {
533                    add_child(bfs_queue, child, def);
534                }
535            }
536
537            // Fill in any missing entries with the less preferable path.
538            // If this path re-exports the child as `_`, we still use this
539            // path in a diagnostic that suggests importing `::*`.
540
541            for (child, parent) in fallback_map {
542                visible_parent_map.entry(child).or_insert(parent);
543            }
544
545            visible_parent_map
546        },
547
548        dependency_formats: |tcx, ()| Arc::new(crate::dependency_format::calculate(tcx)),
549        has_global_allocator: |tcx, LocalCrate| CStore::from_tcx(tcx).has_global_allocator(),
550        has_alloc_error_handler: |tcx, LocalCrate| CStore::from_tcx(tcx).has_alloc_error_handler(),
551        postorder_cnums: |tcx, ()| {
552            tcx.arena.alloc_from_iter(
553                CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE).into_iter(),
554            )
555        },
556        crates: |tcx, ()| {
557            // The list of loaded crates is now frozen in query cache,
558            // so make sure cstore is not mutably accessed from here on.
559            tcx.untracked().cstore.freeze();
560            tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).iter_crate_data().map(|(cnum, _)| cnum))
561        },
562        used_crates: |tcx, ()| {
563            // The list of loaded crates is now frozen in query cache,
564            // so make sure cstore is not mutably accessed from here on.
565            tcx.untracked().cstore.freeze();
566            tcx.arena.alloc_from_iter(
567                CStore::from_tcx(tcx)
568                    .iter_crate_data()
569                    .filter_map(|(cnum, data)| data.used().then_some(cnum)),
570            )
571        },
572        ..providers.queries
573    };
574    provide_extern(&mut providers.extern_queries);
575}
576
577impl CStore {
578    pub fn ctor_untracked(&self, def: DefId) -> Option<(CtorKind, DefId)> {
579        self.get_crate_data(def.krate).get_ctor(def.index)
580    }
581
582    pub fn load_macro_untracked(&self, id: DefId, tcx: TyCtxt<'_>) -> LoadedMacro {
583        let sess = tcx.sess;
584        let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
585
586        let data = self.get_crate_data(id.krate);
587        if data.root.is_proc_macro_crate() {
588            LoadedMacro::ProcMacro(data.load_proc_macro(id.index, tcx))
589        } else {
590            LoadedMacro::MacroDef {
591                def: data.get_macro(id.index, sess),
592                ident: data.item_ident(id.index, sess),
593                attrs: data.get_item_attrs(id.index, sess).collect(),
594                span: data.get_span(id.index, sess),
595                edition: data.root.edition,
596            }
597        }
598    }
599
600    pub fn def_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
601        self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
602    }
603
604    pub fn def_kind_untracked(&self, def: DefId) -> DefKind {
605        self.get_crate_data(def.krate).def_kind(def.index)
606    }
607
608    pub fn expn_that_defined_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
609        self.get_crate_data(def_id.krate).get_expn_that_defined(def_id.index, sess)
610    }
611
612    /// Only public-facing way to traverse all the definitions in a non-local crate.
613    /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
614    /// See <https://github.com/rust-lang/rust/pull/85889> for context.
615    pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
616        self.get_crate_data(cnum).num_def_ids()
617    }
618
619    pub fn get_proc_macro_quoted_span_untracked(
620        &self,
621        cnum: CrateNum,
622        id: usize,
623        sess: &Session,
624    ) -> Span {
625        self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
626    }
627
628    pub fn set_used_recursively(&mut self, cnum: CrateNum) {
629        let cmeta = self.get_crate_data_mut(cnum);
630        if !cmeta.used {
631            cmeta.used = true;
632            let dependencies = mem::take(&mut cmeta.dependencies);
633            for &dep_cnum in &dependencies {
634                self.set_used_recursively(dep_cnum);
635            }
636            self.get_crate_data_mut(cnum).dependencies = dependencies;
637        }
638    }
639
640    pub(crate) fn update_extern_crate(&mut self, cnum: CrateNum, extern_crate: ExternCrate) {
641        let cmeta = self.get_crate_data_mut(cnum);
642        if cmeta.update_extern_crate(extern_crate) {
643            // Propagate the extern crate info to dependencies if it was updated.
644            let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
645            let dependencies = mem::take(&mut cmeta.dependencies);
646            for &dep_cnum in &dependencies {
647                self.update_extern_crate(dep_cnum, extern_crate);
648            }
649            self.get_crate_data_mut(cnum).dependencies = dependencies;
650        }
651    }
652}
653
654impl CrateStore for CStore {
655    fn as_any(&self) -> &dyn Any {
656        self
657    }
658    fn untracked_as_any(&mut self) -> &mut dyn Any {
659        self
660    }
661
662    fn crate_name(&self, cnum: CrateNum) -> Symbol {
663        self.get_crate_data(cnum).root.header.name
664    }
665
666    fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
667        self.get_crate_data(cnum).root.stable_crate_id
668    }
669
670    /// Returns the `DefKey` for a given `DefId`. This indicates the
671    /// parent `DefId` as well as some idea of what kind of data the
672    /// `DefId` refers to.
673    fn def_key(&self, def: DefId) -> DefKey {
674        self.get_crate_data(def.krate).def_key(def.index)
675    }
676
677    fn def_path(&self, def: DefId) -> DefPath {
678        self.get_crate_data(def.krate).def_path(def.index)
679    }
680
681    fn def_path_hash(&self, def: DefId) -> DefPathHash {
682        self.get_crate_data(def.krate).def_path_hash(def.index)
683    }
684}
685
686fn provide_cstore_hooks(providers: &mut Providers) {
687    providers.hooks.def_path_hash_to_def_id_extern = |tcx, hash, stable_crate_id| {
688        // If this is a DefPathHash from an upstream crate, let the CrateStore map
689        // it to a DefId.
690        let cstore = CStore::from_tcx(tcx);
691        let cnum = *tcx
692            .untracked()
693            .stable_crate_ids
694            .read()
695            .get(&stable_crate_id)
696            .unwrap_or_else(|| bug!("uninterned StableCrateId: {stable_crate_id:?}"));
697        assert_ne!(cnum, LOCAL_CRATE);
698        let def_index = cstore.get_crate_data(cnum).def_path_hash_to_def_index(hash);
699        DefId { krate: cnum, index: def_index }
700    };
701
702    providers.hooks.expn_hash_to_expn_id = |tcx, cnum, index_guess, hash| {
703        let cstore = CStore::from_tcx(tcx);
704        cstore.get_crate_data(cnum).expn_hash_to_expn_id(tcx.sess, index_guess, hash)
705    };
706    providers.hooks.import_source_files = |tcx, cnum| {
707        let cstore = CStore::from_tcx(tcx);
708        let cdata = cstore.get_crate_data(cnum);
709        for file_index in 0..cdata.root.source_map.size() {
710            cdata.imported_source_file(file_index as u32, tcx.sess);
711        }
712    };
713}