rustc_metadata/rmeta/decoder/
cstore_impl.rs

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