rustc_metadata/rmeta/decoder/
cstore_impl.rs

1use std::any::Any;
2use std::mem;
3use std::sync::Arc;
4
5use rustc_attr_parsing::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_names => { 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 => {
334        let _ = cdata;
335        tcx.calculate_dtor(def_id, |_,_| Ok(()))
336    }
337    adt_async_destructor => {
338        let _ = cdata;
339        tcx.calculate_async_dtor(def_id, |_,_| Ok(()))
340    }
341    associated_item_def_ids => {
342        tcx.arena.alloc_from_iter(cdata.get_associated_item_or_field_def_ids(def_id.index))
343    }
344    associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
345    inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
346    attrs_for_def => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) }
347    is_mir_available => { cdata.is_item_mir_available(def_id.index) }
348    is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
349    cross_crate_inlinable => { table_direct }
350
351    dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
352    is_private_dep => { cdata.private_dep }
353    is_panic_runtime => { cdata.root.panic_runtime }
354    is_compiler_builtins => { cdata.root.compiler_builtins }
355    has_global_allocator => { cdata.root.has_global_allocator }
356    has_alloc_error_handler => { cdata.root.has_alloc_error_handler }
357    has_panic_handler => { cdata.root.has_panic_handler }
358    is_profiler_runtime => { cdata.root.profiler_runtime }
359    required_panic_strategy => { cdata.root.required_panic_strategy }
360    panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
361    extern_crate => { cdata.extern_crate.map(|c| &*tcx.arena.alloc(c)) }
362    is_no_builtins => { cdata.root.no_builtins }
363    symbol_mangling_version => { cdata.root.symbol_mangling_version }
364    specialization_enabled_in => { cdata.root.specialization_enabled_in }
365    reachable_non_generics => {
366        let reachable_non_generics = tcx
367            .exported_symbols(cdata.cnum)
368            .iter()
369            .filter_map(|&(exported_symbol, export_info)| {
370                if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
371                    Some((def_id, export_info))
372                } else {
373                    None
374                }
375            })
376            .collect();
377
378        reachable_non_generics
379    }
380    native_libraries => { cdata.get_native_libraries(tcx.sess).collect() }
381    foreign_modules => { cdata.get_foreign_modules(tcx.sess).map(|m| (m.def_id, m)).collect() }
382    crate_hash => { cdata.root.header.hash }
383    crate_host_hash => { cdata.host_hash }
384    crate_name => { cdata.root.header.name }
385    num_extern_def_ids => { cdata.num_def_ids() }
386
387    extra_filename => { cdata.root.extra_filename.clone() }
388
389    traits => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
390    trait_impls_in_crate => { tcx.arena.alloc_from_iter(cdata.get_trait_impls()) }
391    implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
392    crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) }
393
394    dep_kind => { cdata.dep_kind }
395    module_children => {
396        tcx.arena.alloc_from_iter(cdata.get_module_children(def_id.index, tcx.sess))
397    }
398    lib_features => { cdata.get_lib_features() }
399    stability_implications => {
400        cdata.get_stability_implications(tcx).iter().copied().collect()
401    }
402    stripped_cfg_items => { cdata.get_stripped_cfg_items(cdata.cnum, tcx) }
403    intrinsic_raw => { cdata.get_intrinsic(def_id.index) }
404    defined_lang_items => { cdata.get_lang_items(tcx) }
405    diagnostic_items => { cdata.get_diagnostic_items() }
406    missing_lang_items => { cdata.get_missing_lang_items(tcx) }
407
408    missing_extern_crate_item => {
409        matches!(cdata.extern_crate, Some(extern_crate) if !extern_crate.is_direct())
410    }
411
412    used_crate_source => { Arc::clone(&cdata.source) }
413    debugger_visualizers => { cdata.get_debugger_visualizers() }
414
415    exported_symbols => {
416        let syms = cdata.exported_symbols(tcx);
417
418        // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
419        // to block export of generics from dylibs, but we must fix
420        // rust-lang/rust#65890 before we can do that robustly.
421
422        syms
423    }
424
425    crate_extern_paths => { cdata.source().paths().cloned().collect() }
426    expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
427    is_doc_hidden => { cdata.get_attr_flags(def_id.index).contains(AttrFlags::IS_DOC_HIDDEN) }
428    doc_link_resolutions => { tcx.arena.alloc(cdata.get_doc_link_resolutions(def_id.index)) }
429    doc_link_traits_in_scope => {
430        tcx.arena.alloc_from_iter(cdata.get_doc_link_traits_in_scope(def_id.index))
431    }
432}
433
434pub(in crate::rmeta) fn provide(providers: &mut Providers) {
435    provide_cstore_hooks(providers);
436    providers.queries = rustc_middle::query::Providers {
437        allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
438        alloc_error_handler_kind: |tcx, ()| CStore::from_tcx(tcx).alloc_error_handler_kind(),
439        is_private_dep: |_tcx, LocalCrate| false,
440        native_library: |tcx, id| {
441            tcx.native_libraries(id.krate)
442                .iter()
443                .filter(|lib| native_libs::relevant_lib(tcx.sess, lib))
444                .find(|lib| {
445                    let Some(fm_id) = lib.foreign_module else {
446                        return false;
447                    };
448                    let map = tcx.foreign_modules(id.krate);
449                    map.get(&fm_id)
450                        .expect("failed to find foreign module")
451                        .foreign_items
452                        .contains(&id)
453                })
454        },
455        native_libraries: native_libs::collect,
456        foreign_modules: foreign_modules::collect,
457
458        // Returns a map from a sufficiently visible external item (i.e., an
459        // external item that is visible from at least one local module) to a
460        // sufficiently visible parent (considering modules that re-export the
461        // external item to be parents).
462        visible_parent_map: |tcx, ()| {
463            use std::collections::hash_map::Entry;
464            use std::collections::vec_deque::VecDeque;
465
466            let mut visible_parent_map: DefIdMap<DefId> = Default::default();
467            // This is a secondary visible_parent_map, storing the DefId of
468            // parents that re-export the child as `_` or module parents
469            // which are `#[doc(hidden)]`. Since we prefer paths that don't
470            // do this, merge this map at the end, only if we're missing
471            // keys from the former.
472            // This is a rudimentary check that does not catch all cases,
473            // just the easiest.
474            let mut fallback_map: Vec<(DefId, DefId)> = Default::default();
475
476            // Issue 46112: We want the map to prefer the shortest
477            // paths when reporting the path to an item. Therefore we
478            // build up the map via a breadth-first search (BFS),
479            // which naturally yields minimal-length paths.
480            //
481            // Note that it needs to be a BFS over the whole forest of
482            // crates, not just each individual crate; otherwise you
483            // only get paths that are locally minimal with respect to
484            // whatever crate we happened to encounter first in this
485            // traversal, but not globally minimal across all crates.
486            let bfs_queue = &mut VecDeque::new();
487
488            for &cnum in tcx.crates(()) {
489                // Ignore crates without a corresponding local `extern crate` item.
490                if tcx.missing_extern_crate_item(cnum) {
491                    continue;
492                }
493
494                bfs_queue.push_back(cnum.as_def_id());
495            }
496
497            let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
498                if !child.vis.is_public() {
499                    return;
500                }
501
502                if let Some(def_id) = child.res.opt_def_id() {
503                    if child.ident.name == kw::Underscore {
504                        fallback_map.push((def_id, parent));
505                        return;
506                    }
507
508                    if tcx.is_doc_hidden(parent) {
509                        fallback_map.push((def_id, parent));
510                        return;
511                    }
512
513                    match visible_parent_map.entry(def_id) {
514                        Entry::Occupied(mut entry) => {
515                            // If `child` is defined in crate `cnum`, ensure
516                            // that it is mapped to a parent in `cnum`.
517                            if def_id.is_local() && entry.get().is_local() {
518                                entry.insert(parent);
519                            }
520                        }
521                        Entry::Vacant(entry) => {
522                            entry.insert(parent);
523                            if matches!(
524                                child.res,
525                                Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
526                            ) {
527                                bfs_queue.push_back(def_id);
528                            }
529                        }
530                    }
531                }
532            };
533
534            while let Some(def) = bfs_queue.pop_front() {
535                for child in tcx.module_children(def).iter() {
536                    add_child(bfs_queue, child, def);
537                }
538            }
539
540            // Fill in any missing entries with the less preferable path.
541            // If this path re-exports the child as `_`, we still use this
542            // path in a diagnostic that suggests importing `::*`.
543
544            for (child, parent) in fallback_map {
545                visible_parent_map.entry(child).or_insert(parent);
546            }
547
548            visible_parent_map
549        },
550
551        dependency_formats: |tcx, ()| Arc::new(crate::dependency_format::calculate(tcx)),
552        has_global_allocator: |tcx, LocalCrate| CStore::from_tcx(tcx).has_global_allocator(),
553        has_alloc_error_handler: |tcx, LocalCrate| CStore::from_tcx(tcx).has_alloc_error_handler(),
554        postorder_cnums: |tcx, ()| {
555            tcx.arena
556                .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
557        },
558        crates: |tcx, ()| {
559            // The list of loaded crates is now frozen in query cache,
560            // so make sure cstore is not mutably accessed from here on.
561            tcx.untracked().cstore.freeze();
562            tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).iter_crate_data().map(|(cnum, _)| cnum))
563        },
564        used_crates: |tcx, ()| {
565            // The list of loaded crates is now frozen in query cache,
566            // so make sure cstore is not mutably accessed from here on.
567            tcx.untracked().cstore.freeze();
568            tcx.arena.alloc_from_iter(
569                CStore::from_tcx(tcx)
570                    .iter_crate_data()
571                    .filter_map(|(cnum, data)| data.used().then_some(cnum)),
572            )
573        },
574        ..providers.queries
575    };
576    provide_extern(&mut providers.extern_queries);
577}
578
579impl CStore {
580    pub fn ctor_untracked(&self, def: DefId) -> Option<(CtorKind, DefId)> {
581        self.get_crate_data(def.krate).get_ctor(def.index)
582    }
583
584    pub fn load_macro_untracked(&self, id: DefId, tcx: TyCtxt<'_>) -> LoadedMacro {
585        let sess = tcx.sess;
586        let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
587
588        let data = self.get_crate_data(id.krate);
589        if data.root.is_proc_macro_crate() {
590            LoadedMacro::ProcMacro(data.load_proc_macro(id.index, tcx))
591        } else {
592            LoadedMacro::MacroDef {
593                def: data.get_macro(id.index, sess),
594                ident: data.item_ident(id.index, sess),
595                attrs: data.get_item_attrs(id.index, sess).collect(),
596                span: data.get_span(id.index, sess),
597                edition: data.root.edition,
598            }
599        }
600    }
601
602    pub fn def_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
603        self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
604    }
605
606    pub fn def_kind_untracked(&self, def: DefId) -> DefKind {
607        self.get_crate_data(def.krate).def_kind(def.index)
608    }
609
610    pub fn expn_that_defined_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
611        self.get_crate_data(def_id.krate).get_expn_that_defined(def_id.index, sess)
612    }
613
614    /// Only public-facing way to traverse all the definitions in a non-local crate.
615    /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
616    /// See <https://github.com/rust-lang/rust/pull/85889> for context.
617    pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
618        self.get_crate_data(cnum).num_def_ids()
619    }
620
621    pub fn get_proc_macro_quoted_span_untracked(
622        &self,
623        cnum: CrateNum,
624        id: usize,
625        sess: &Session,
626    ) -> Span {
627        self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
628    }
629
630    pub fn set_used_recursively(&mut self, cnum: CrateNum) {
631        let cmeta = self.get_crate_data_mut(cnum);
632        if !cmeta.used {
633            cmeta.used = true;
634            let dependencies = mem::take(&mut cmeta.dependencies);
635            for &dep_cnum in &dependencies {
636                self.set_used_recursively(dep_cnum);
637            }
638            self.get_crate_data_mut(cnum).dependencies = dependencies;
639        }
640    }
641
642    pub(crate) fn update_extern_crate(&mut self, cnum: CrateNum, extern_crate: ExternCrate) {
643        let cmeta = self.get_crate_data_mut(cnum);
644        if cmeta.update_extern_crate(extern_crate) {
645            // Propagate the extern crate info to dependencies if it was updated.
646            let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
647            let dependencies = mem::take(&mut cmeta.dependencies);
648            for &dep_cnum in &dependencies {
649                self.update_extern_crate(dep_cnum, extern_crate);
650            }
651            self.get_crate_data_mut(cnum).dependencies = dependencies;
652        }
653    }
654}
655
656impl CrateStore for CStore {
657    fn as_any(&self) -> &dyn Any {
658        self
659    }
660    fn untracked_as_any(&mut self) -> &mut dyn Any {
661        self
662    }
663
664    fn crate_name(&self, cnum: CrateNum) -> Symbol {
665        self.get_crate_data(cnum).root.header.name
666    }
667
668    fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
669        self.get_crate_data(cnum).root.stable_crate_id
670    }
671
672    /// Returns the `DefKey` for a given `DefId`. This indicates the
673    /// parent `DefId` as well as some idea of what kind of data the
674    /// `DefId` refers to.
675    fn def_key(&self, def: DefId) -> DefKey {
676        self.get_crate_data(def.krate).def_key(def.index)
677    }
678
679    fn def_path(&self, def: DefId) -> DefPath {
680        self.get_crate_data(def.krate).def_path(def.index)
681    }
682
683    fn def_path_hash(&self, def: DefId) -> DefPathHash {
684        self.get_crate_data(def.krate).def_path_hash(def.index)
685    }
686}
687
688fn provide_cstore_hooks(providers: &mut Providers) {
689    providers.hooks.def_path_hash_to_def_id_extern = |tcx, hash, stable_crate_id| {
690        // If this is a DefPathHash from an upstream crate, let the CrateStore map
691        // it to a DefId.
692        let cstore = CStore::from_tcx(tcx);
693        let cnum = *tcx
694            .untracked()
695            .stable_crate_ids
696            .read()
697            .get(&stable_crate_id)
698            .unwrap_or_else(|| bug!("uninterned StableCrateId: {stable_crate_id:?}"));
699        assert_ne!(cnum, LOCAL_CRATE);
700        let def_index = cstore.get_crate_data(cnum).def_path_hash_to_def_index(hash);
701        DefId { krate: cnum, index: def_index }
702    };
703
704    providers.hooks.expn_hash_to_expn_id = |tcx, cnum, index_guess, hash| {
705        let cstore = CStore::from_tcx(tcx);
706        cstore.get_crate_data(cnum).expn_hash_to_expn_id(tcx.sess, index_guess, hash)
707    };
708    providers.hooks.import_source_files = |tcx, cnum| {
709        let cstore = CStore::from_tcx(tcx);
710        let cdata = cstore.get_crate_data(cnum);
711        for file_index in 0..cdata.root.source_map.size() {
712            cdata.imported_source_file(file_index as u32, tcx.sess);
713        }
714    };
715}