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