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    const_of_item => { table }
407}
408
409pub(in crate::rmeta) fn provide(providers: &mut Providers) {
410    provide_cstore_hooks(providers);
411    providers.queries = rustc_middle::query::Providers {
412        allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
413        alloc_error_handler_kind: |tcx, ()| CStore::from_tcx(tcx).alloc_error_handler_kind(),
414        is_private_dep: |_tcx, LocalCrate| false,
415        native_library: |tcx, id| {
416            tcx.native_libraries(id.krate)
417                .iter()
418                .filter(|lib| native_libs::relevant_lib(tcx.sess, lib))
419                .find(|lib| {
420                    let Some(fm_id) = lib.foreign_module else {
421                        return false;
422                    };
423                    let map = tcx.foreign_modules(id.krate);
424                    map.get(&fm_id)
425                        .expect("failed to find foreign module")
426                        .foreign_items
427                        .contains(&id)
428                })
429        },
430        native_libraries: native_libs::collect,
431        foreign_modules: foreign_modules::collect,
432
433        // Returns a map from a sufficiently visible external item (i.e., an
434        // external item that is visible from at least one local module) to a
435        // sufficiently visible parent (considering modules that re-export the
436        // external item to be parents).
437        visible_parent_map: |tcx, ()| {
438            use std::collections::hash_map::Entry;
439            use std::collections::vec_deque::VecDeque;
440
441            let mut visible_parent_map: DefIdMap<DefId> = Default::default();
442            // This is a secondary visible_parent_map, storing the DefId of
443            // parents that re-export the child as `_` or module parents
444            // which are `#[doc(hidden)]`. Since we prefer paths that don't
445            // do this, merge this map at the end, only if we're missing
446            // keys from the former.
447            // This is a rudimentary check that does not catch all cases,
448            // just the easiest.
449            let mut fallback_map: Vec<(DefId, DefId)> = Default::default();
450
451            // Issue 46112: We want the map to prefer the shortest
452            // paths when reporting the path to an item. Therefore we
453            // build up the map via a breadth-first search (BFS),
454            // which naturally yields minimal-length paths.
455            //
456            // Note that it needs to be a BFS over the whole forest of
457            // crates, not just each individual crate; otherwise you
458            // only get paths that are locally minimal with respect to
459            // whatever crate we happened to encounter first in this
460            // traversal, but not globally minimal across all crates.
461            let bfs_queue = &mut VecDeque::new();
462
463            for &cnum in tcx.crates(()) {
464                // Ignore crates without a corresponding local `extern crate` item.
465                if tcx.missing_extern_crate_item(cnum) {
466                    continue;
467                }
468
469                bfs_queue.push_back(cnum.as_def_id());
470            }
471
472            let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
473                if !child.vis.is_public() {
474                    return;
475                }
476
477                if let Some(def_id) = child.res.opt_def_id() {
478                    if child.ident.name == kw::Underscore {
479                        fallback_map.push((def_id, parent));
480                        return;
481                    }
482
483                    if tcx.is_doc_hidden(parent) {
484                        fallback_map.push((def_id, parent));
485                        return;
486                    }
487
488                    match visible_parent_map.entry(def_id) {
489                        Entry::Occupied(mut entry) => {
490                            // If `child` is defined in crate `cnum`, ensure
491                            // that it is mapped to a parent in `cnum`.
492                            if def_id.is_local() && entry.get().is_local() {
493                                entry.insert(parent);
494                            }
495                        }
496                        Entry::Vacant(entry) => {
497                            entry.insert(parent);
498                            if child.res.module_like_def_id().is_some() {
499                                bfs_queue.push_back(def_id);
500                            }
501                        }
502                    }
503                }
504            };
505
506            while let Some(def) = bfs_queue.pop_front() {
507                for child in tcx.module_children(def).iter() {
508                    add_child(bfs_queue, child, def);
509                }
510            }
511
512            // Fill in any missing entries with the less preferable path.
513            // If this path re-exports the child as `_`, we still use this
514            // path in a diagnostic that suggests importing `::*`.
515
516            for (child, parent) in fallback_map {
517                visible_parent_map.entry(child).or_insert(parent);
518            }
519
520            visible_parent_map
521        },
522
523        dependency_formats: |tcx, ()| Arc::new(crate::dependency_format::calculate(tcx)),
524        has_global_allocator: |tcx, LocalCrate| CStore::from_tcx(tcx).has_global_allocator(),
525        has_alloc_error_handler: |tcx, LocalCrate| CStore::from_tcx(tcx).has_alloc_error_handler(),
526        postorder_cnums: |tcx, ()| {
527            tcx.arena.alloc_from_iter(
528                CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE).into_iter(),
529            )
530        },
531        crates: |tcx, ()| {
532            // The list of loaded crates is now frozen in query cache,
533            // so make sure cstore is not mutably accessed from here on.
534            tcx.untracked().cstore.freeze();
535            tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).iter_crate_data().map(|(cnum, _)| cnum))
536        },
537        used_crates: |tcx, ()| {
538            // The list of loaded crates is now frozen in query cache,
539            // so make sure cstore is not mutably accessed from here on.
540            tcx.untracked().cstore.freeze();
541            tcx.arena.alloc_from_iter(
542                CStore::from_tcx(tcx)
543                    .iter_crate_data()
544                    .filter_map(|(cnum, data)| data.used().then_some(cnum)),
545            )
546        },
547        ..providers.queries
548    };
549    provide_extern(&mut providers.extern_queries);
550}
551
552impl CStore {
553    pub fn ctor_untracked(&self, def: DefId) -> Option<(CtorKind, DefId)> {
554        self.get_crate_data(def.krate).get_ctor(def.index)
555    }
556
557    pub fn load_macro_untracked(&self, id: DefId, tcx: TyCtxt<'_>) -> LoadedMacro {
558        let sess = tcx.sess;
559        let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
560
561        let data = self.get_crate_data(id.krate);
562        if data.root.is_proc_macro_crate() {
563            LoadedMacro::ProcMacro(data.load_proc_macro(id.index, tcx))
564        } else {
565            LoadedMacro::MacroDef {
566                def: data.get_macro(id.index, sess),
567                ident: data.item_ident(id.index, sess),
568                attrs: data.get_item_attrs(id.index, sess).collect(),
569                span: data.get_span(id.index, sess),
570                edition: data.root.edition,
571            }
572        }
573    }
574
575    pub fn def_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
576        self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
577    }
578
579    pub fn def_kind_untracked(&self, def: DefId) -> DefKind {
580        self.get_crate_data(def.krate).def_kind(def.index)
581    }
582
583    pub fn expn_that_defined_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
584        self.get_crate_data(def_id.krate).get_expn_that_defined(def_id.index, sess)
585    }
586
587    /// Only public-facing way to traverse all the definitions in a non-local crate.
588    /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
589    /// See <https://github.com/rust-lang/rust/pull/85889> for context.
590    pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
591        self.get_crate_data(cnum).num_def_ids()
592    }
593
594    pub fn get_proc_macro_quoted_span_untracked(
595        &self,
596        cnum: CrateNum,
597        id: usize,
598        sess: &Session,
599    ) -> Span {
600        self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
601    }
602
603    pub fn set_used_recursively(&mut self, cnum: CrateNum) {
604        let cmeta = self.get_crate_data_mut(cnum);
605        if !cmeta.used {
606            cmeta.used = true;
607            let dependencies = mem::take(&mut cmeta.dependencies);
608            for &dep_cnum in &dependencies {
609                self.set_used_recursively(dep_cnum);
610            }
611            self.get_crate_data_mut(cnum).dependencies = dependencies;
612        }
613    }
614
615    /// Track how an extern crate has been loaded. Called after resolving an import in the local crate.
616    ///
617    /// * the `name` is for [`Self::set_resolved_extern_crate_name`] saving `--extern name=`
618    /// * `extern_crate` is for diagnostics
619    pub(crate) fn update_extern_crate(
620        &mut self,
621        cnum: CrateNum,
622        name: Symbol,
623        extern_crate: ExternCrate,
624    ) {
625        debug_assert_eq!(
626            extern_crate.dependency_of, LOCAL_CRATE,
627            "this function should not be called on transitive dependencies"
628        );
629        self.set_resolved_extern_crate_name(name, cnum);
630        self.update_transitive_extern_crate_diagnostics(cnum, extern_crate);
631    }
632
633    /// `CrateMetadata` uses `ExternCrate` only for diagnostics
634    fn update_transitive_extern_crate_diagnostics(
635        &mut self,
636        cnum: CrateNum,
637        extern_crate: ExternCrate,
638    ) {
639        let cmeta = self.get_crate_data_mut(cnum);
640        if cmeta.update_extern_crate_diagnostics(extern_crate) {
641            // Propagate the extern crate info to dependencies if it was updated.
642            let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
643            let dependencies = mem::take(&mut cmeta.dependencies);
644            for &dep_cnum in &dependencies {
645                self.update_transitive_extern_crate_diagnostics(dep_cnum, extern_crate);
646            }
647            self.get_crate_data_mut(cnum).dependencies = dependencies;
648        }
649    }
650}
651
652impl CrateStore for CStore {
653    fn as_any(&self) -> &dyn Any {
654        self
655    }
656    fn untracked_as_any(&mut self) -> &mut dyn Any {
657        self
658    }
659
660    fn crate_name(&self, cnum: CrateNum) -> Symbol {
661        self.get_crate_data(cnum).root.header.name
662    }
663
664    fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
665        self.get_crate_data(cnum).root.stable_crate_id
666    }
667
668    /// Returns the `DefKey` for a given `DefId`. This indicates the
669    /// parent `DefId` as well as some idea of what kind of data the
670    /// `DefId` refers to.
671    fn def_key(&self, def: DefId) -> DefKey {
672        self.get_crate_data(def.krate).def_key(def.index)
673    }
674
675    fn def_path(&self, def: DefId) -> DefPath {
676        self.get_crate_data(def.krate).def_path(def.index)
677    }
678
679    fn def_path_hash(&self, def: DefId) -> DefPathHash {
680        self.get_crate_data(def.krate).def_path_hash(def.index)
681    }
682}
683
684fn provide_cstore_hooks(providers: &mut Providers) {
685    providers.hooks.def_path_hash_to_def_id_extern = |tcx, hash, stable_crate_id| {
686        // If this is a DefPathHash from an upstream crate, let the CrateStore map
687        // it to a DefId.
688        let cstore = CStore::from_tcx(tcx);
689        let cnum = *tcx
690            .untracked()
691            .stable_crate_ids
692            .read()
693            .get(&stable_crate_id)
694            .unwrap_or_else(|| bug!("uninterned StableCrateId: {stable_crate_id:?}"));
695        assert_ne!(cnum, LOCAL_CRATE);
696        let def_index = cstore.get_crate_data(cnum).def_path_hash_to_def_index(hash)?;
697        Some(DefId { krate: cnum, index: def_index })
698    };
699
700    providers.hooks.expn_hash_to_expn_id = |tcx, cnum, index_guess, hash| {
701        let cstore = CStore::from_tcx(tcx);
702        cstore.get_crate_data(cnum).expn_hash_to_expn_id(tcx.sess, index_guess, hash)
703    };
704    providers.hooks.import_source_files = |tcx, cnum| {
705        let cstore = CStore::from_tcx(tcx);
706        let cdata = cstore.get_crate_data(cnum);
707        for file_index in 0..cdata.root.source_map.size() {
708            cdata.imported_source_file(file_index as u32, tcx.sess);
709        }
710    };
711}