Skip to main content

rustc_middle/
hooks.rs

1//! "Hooks" let you write `tcx` methods in downstream crates and call them in this crate, reducing
2//! the amount of code that needs to be in this crate (which is already very big). This is somewhat
3//! similar to queries, but queries come with a lot of machinery for caching and incremental
4//! compilation, whereas hooks are just plain function pointers without any of the query magic.
5
6use std::io;
7
8use rustc_hir::def_id::{DefId, DefPathHash};
9use rustc_index::bit_set::DenseBitSet;
10use rustc_session::StableCrateId;
11use rustc_span::def_id::{CrateNum, LocalDefId};
12use rustc_span::{ExpnHash, ExpnId, bug};
13
14use crate::mir;
15use crate::query::on_disk_cache::CacheEncoder;
16use crate::ty::{self, Ty, TyCtxt};
17
18macro_rules! declare_hooks {
19    (
20        $(
21            $(#[$attr:meta])*
22            hook $name:ident(
23                $( $arg:ident: $K:ty ),* $(,)?
24            ) -> $V:ty;
25        )*
26    ) => {
27
28        impl<'tcx> TyCtxt<'tcx> {
29            $(
30            $(#[$attr])*
31            #[inline(always)]
32            pub fn $name(self, $($arg: $K,)*) -> $V
33            {
34                (self.hooks.$name)(self, $($arg,)*)
35            }
36            )*
37        }
38
39        pub struct Providers {
40            $(pub $name: for<'tcx> fn(
41                TyCtxt<'tcx>,
42                $($arg: $K,)*
43            ) -> $V,)*
44        }
45
46        impl Default for Providers {
47            fn default() -> Self {
48                #[allow(unused)]
49                Providers {
50                    $($name:
51                        |_, $($arg,)*| default_hook(stringify!($name))),*
52                }
53            }
54        }
55
56        impl Copy for Providers {}
57        impl Clone for Providers {
58            fn clone(&self) -> Self { *self }
59        }
60    };
61}
62
63impl<'tcx> TyCtxt<'tcx> {
    #[doc =
    r" Tries to destructure an `mir::Const` ADT or array into its variant index"]
    #[doc =
    r" and its field values. This should only be used for pretty printing."]
    #[inline(always)]
    pub fn try_destructure_mir_constant_for_user_output(self,
        val: mir::ConstValue, ty: Ty<'tcx>)
        -> Option<mir::DestructuredConstant<'tcx>> {
        (self.hooks.try_destructure_mir_constant_for_user_output)(self, val,
            ty)
    }
    #[doc = r" Getting a &core::panic::Location referring to a span."]
    #[inline(always)]
    pub fn const_caller_location(self, file: rustc_span::Symbol, line: u32,
        col: u32) -> mir::ConstValue {
        (self.hooks.const_caller_location)(self, file, line, col)
    }
    #[doc =
    r" Imports all `SourceFile`s from the given crate into the current session."]
    #[doc =
    r" This normally happens automatically when we decode a `Span` from"]
    #[doc = r" that crate's metadata - however, the incr comp cache needs"]
    #[doc = r" to trigger this manually when decoding a foreign `Span`"]
    #[inline(always)]
    pub fn import_source_files(self, key: CrateNum) -> () {
        (self.hooks.import_source_files)(self, key)
    }
    #[inline(always)]
    pub fn expn_hash_to_expn_id(self, cnum: CrateNum, index_guess: u32,
        hash: ExpnHash) -> ExpnId {
        (self.hooks.expn_hash_to_expn_id)(self, cnum, index_guess, hash)
    }
    #[doc =
    r" Converts a `DefPathHash` to its corresponding `DefId` in the current compilation"]
    #[doc =
    r" session, if it still exists. This is used during incremental compilation to"]
    #[doc = r" turn a deserialized `DefPathHash` into its current `DefId`."]
    #[doc = r" Will fetch a DefId from a DefPathHash for a foreign crate."]
    #[inline(always)]
    pub fn def_path_hash_to_def_id_extern(self, hash: DefPathHash,
        stable_crate_id: StableCrateId) -> Option<DefId> {
        (self.hooks.def_path_hash_to_def_id_extern)(self, hash,
            stable_crate_id)
    }
    #[doc =
    r" Returns `true` if we should codegen an instance in the local crate, or returns `false` if we"]
    #[doc =
    r" can just link to the upstream crate and therefore don't need a mono item."]
    #[doc = r""]
    #[doc =
    r" Note: this hook isn't called within `rustc_middle` but #127779 suggests it's a hook instead"]
    #[doc =
    r" of a normal function because external tools might want to override it."]
    #[inline(always)]
    pub fn should_codegen_locally(self, instance: crate::ty::Instance<'tcx>)
        -> bool {
        (self.hooks.should_codegen_locally)(self, instance)
    }
    #[inline(always)]
    pub fn alloc_self_profile_query_strings(self) -> () {
        (self.hooks.alloc_self_profile_query_strings)(self)
    }
    #[doc = r" Saves and writes the DepGraph to the file system."]
    #[doc = r""]
    #[doc =
    r" This function saves both the dep-graph and the query result cache,"]
    #[doc = r" and drops the result cache."]
    #[doc = r""]
    #[doc =
    r" This function should only run after all queries have completed."]
    #[doc =
    r" Trying to execute a query afterwards would attempt to read the result cache we just dropped."]
    #[inline(always)]
    pub fn save_dep_graph(self) -> () { (self.hooks.save_dep_graph)(self) }
    #[inline(always)]
    pub fn verify_query_key_hashes(self) -> () {
        (self.hooks.verify_query_key_hashes)(self)
    }
    #[doc = r" Ensure the given scalar is valid for the given type."]
    #[doc = r" This checks non-recursive runtime validity."]
    #[inline(always)]
    pub fn validate_scalar_in_layout(self, scalar: crate::ty::ScalarInt,
        ty: Ty<'tcx>) -> bool {
        (self.hooks.validate_scalar_in_layout)(self, scalar, ty)
    }
    #[doc =
    r" **Do not call this directly; call the `mir_built` query instead.**"]
    #[doc = r""]
    #[doc =
    r" Creates the MIR for a given `DefId`, including unreachable code."]
    #[inline(always)]
    pub fn build_mir_inner_impl(self, def: LocalDefId) -> mir::Body<'tcx> {
        (self.hooks.build_mir_inner_impl)(self, def)
    }
    #[doc =
    r" Serializes all eligible query return values into the on-disk cache."]
    #[inline(always)]
    pub fn encode_query_values(self, encoder: &mut CacheEncoder<'tcx>) -> () {
        (self.hooks.encode_query_values)(self, encoder)
    }
    #[doc =
    r" Identifies landing pads that don't do anything, allowing some post-monomorphization"]
    #[doc = r" simplifications during codegen."]
    #[inline(always)]
    pub fn find_noop_landing_pads_for_instance(self, body: &mir::Body<'tcx>,
        instance: ty::Instance<'tcx>, typing_env: ty::TypingEnv<'tcx>)
        -> DenseBitSet<mir::BasicBlock> {
        (self.hooks.find_noop_landing_pads_for_instance)(self, body, instance,
            typing_env)
    }
    #[doc = r" Configures extra data to be included when pretty printing MIR"]
    #[inline(always)]
    pub fn mir_pretty_extra_data(self, body: &mir::Body<'tcx>)
        ->
            Option<Box<dyn Fn(mir::PassWhere, &mut dyn io::Write)
            -> io::Result<()>>> {
        (self.hooks.mir_pretty_extra_data)(self, body)
    }
}
pub struct Providers {
    pub try_destructure_mir_constant_for_user_output: for<'tcx> fn(TyCtxt<'tcx>,
        val: mir::ConstValue, ty: Ty<'tcx>)
        -> Option<mir::DestructuredConstant<'tcx>>,
    pub const_caller_location: for<'tcx> fn(TyCtxt<'tcx>,
        file: rustc_span::Symbol, line: u32, col: u32) -> mir::ConstValue,
    pub import_source_files: for<'tcx> fn(TyCtxt<'tcx>, key: CrateNum) -> (),
    pub expn_hash_to_expn_id: for<'tcx> fn(TyCtxt<'tcx>, cnum: CrateNum,
        index_guess: u32, hash: ExpnHash) -> ExpnId,
    pub def_path_hash_to_def_id_extern: for<'tcx> fn(TyCtxt<'tcx>,
        hash: DefPathHash, stable_crate_id: StableCrateId) -> Option<DefId>,
    pub should_codegen_locally: for<'tcx> fn(TyCtxt<'tcx>,
        instance: crate::ty::Instance<'tcx>) -> bool,
    pub alloc_self_profile_query_strings: for<'tcx> fn(TyCtxt<'tcx>) -> (),
    pub save_dep_graph: for<'tcx> fn(TyCtxt<'tcx>) -> (),
    pub verify_query_key_hashes: for<'tcx> fn(TyCtxt<'tcx>) -> (),
    pub validate_scalar_in_layout: for<'tcx> fn(TyCtxt<'tcx>,
        scalar: crate::ty::ScalarInt, ty: Ty<'tcx>) -> bool,
    pub build_mir_inner_impl: for<'tcx> fn(TyCtxt<'tcx>, def: LocalDefId)
        -> mir::Body<'tcx>,
    pub encode_query_values: for<'tcx> fn(TyCtxt<'tcx>,
        encoder: &mut CacheEncoder<'tcx>) -> (),
    pub find_noop_landing_pads_for_instance: for<'tcx> fn(TyCtxt<'tcx>,
        body: &mir::Body<'tcx>, instance: ty::Instance<'tcx>,
        typing_env: ty::TypingEnv<'tcx>) -> DenseBitSet<mir::BasicBlock>,
    pub mir_pretty_extra_data: for<'tcx> fn(TyCtxt<'tcx>,
        body: &mir::Body<'tcx>)
        ->
            Option<Box<dyn Fn(mir::PassWhere, &mut dyn io::Write)
            -> io::Result<()>>>,
}
impl Default for Providers {
    fn default() -> Self {

        #[allow(unused)]
        Providers {
            try_destructure_mir_constant_for_user_output: |_, val, ty|
                default_hook("try_destructure_mir_constant_for_user_output"),
            const_caller_location: |_, file, line, col|
                default_hook("const_caller_location"),
            import_source_files: |_, key| default_hook("import_source_files"),
            expn_hash_to_expn_id: |_, cnum, index_guess, hash|
                default_hook("expn_hash_to_expn_id"),
            def_path_hash_to_def_id_extern: |_, hash, stable_crate_id|
                default_hook("def_path_hash_to_def_id_extern"),
            should_codegen_locally: |_, instance|
                default_hook("should_codegen_locally"),
            alloc_self_profile_query_strings: |_|
                default_hook("alloc_self_profile_query_strings"),
            save_dep_graph: |_| default_hook("save_dep_graph"),
            verify_query_key_hashes: |_|
                default_hook("verify_query_key_hashes"),
            validate_scalar_in_layout: |_, scalar, ty|
                default_hook("validate_scalar_in_layout"),
            build_mir_inner_impl: |_, def|
                default_hook("build_mir_inner_impl"),
            encode_query_values: |_, encoder|
                default_hook("encode_query_values"),
            find_noop_landing_pads_for_instance: |_, body, instance,
                typing_env|
                default_hook("find_noop_landing_pads_for_instance"),
            mir_pretty_extra_data: |_, body|
                default_hook("mir_pretty_extra_data"),
        }
    }
}
impl Copy for Providers {}
impl Clone for Providers {
    fn clone(&self) -> Self { *self }
}declare_hooks! {
64    /// Tries to destructure an `mir::Const` ADT or array into its variant index
65    /// and its field values. This should only be used for pretty printing.
66    hook try_destructure_mir_constant_for_user_output(val: mir::ConstValue, ty: Ty<'tcx>) -> Option<mir::DestructuredConstant<'tcx>>;
67
68    /// Getting a &core::panic::Location referring to a span.
69    hook const_caller_location(file: rustc_span::Symbol, line: u32, col: u32) -> mir::ConstValue;
70
71    /// Imports all `SourceFile`s from the given crate into the current session.
72    /// This normally happens automatically when we decode a `Span` from
73    /// that crate's metadata - however, the incr comp cache needs
74    /// to trigger this manually when decoding a foreign `Span`
75    hook import_source_files(key: CrateNum) -> ();
76
77    hook expn_hash_to_expn_id(
78        cnum: CrateNum,
79        index_guess: u32,
80        hash: ExpnHash
81    ) -> ExpnId;
82
83    /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
84    /// session, if it still exists. This is used during incremental compilation to
85    /// turn a deserialized `DefPathHash` into its current `DefId`.
86    /// Will fetch a DefId from a DefPathHash for a foreign crate.
87    hook def_path_hash_to_def_id_extern(hash: DefPathHash, stable_crate_id: StableCrateId) -> Option<DefId>;
88
89    /// Returns `true` if we should codegen an instance in the local crate, or returns `false` if we
90    /// can just link to the upstream crate and therefore don't need a mono item.
91    ///
92    /// Note: this hook isn't called within `rustc_middle` but #127779 suggests it's a hook instead
93    /// of a normal function because external tools might want to override it.
94    hook should_codegen_locally(instance: crate::ty::Instance<'tcx>) -> bool;
95
96    hook alloc_self_profile_query_strings() -> ();
97
98    /// Saves and writes the DepGraph to the file system.
99    ///
100    /// This function saves both the dep-graph and the query result cache,
101    /// and drops the result cache.
102    ///
103    /// This function should only run after all queries have completed.
104    /// Trying to execute a query afterwards would attempt to read the result cache we just dropped.
105    hook save_dep_graph() -> ();
106
107    hook verify_query_key_hashes() -> ();
108
109    /// Ensure the given scalar is valid for the given type.
110    /// This checks non-recursive runtime validity.
111    hook validate_scalar_in_layout(scalar: crate::ty::ScalarInt, ty: Ty<'tcx>) -> bool;
112
113    /// **Do not call this directly; call the `mir_built` query instead.**
114    ///
115    /// Creates the MIR for a given `DefId`, including unreachable code.
116    hook build_mir_inner_impl(def: LocalDefId) -> mir::Body<'tcx>;
117
118    /// Serializes all eligible query return values into the on-disk cache.
119    hook encode_query_values(encoder: &mut CacheEncoder<'tcx>) -> ();
120
121    /// Identifies landing pads that don't do anything, allowing some post-monomorphization
122    /// simplifications during codegen.
123    hook find_noop_landing_pads_for_instance(
124        body: &mir::Body<'tcx>,
125        instance: ty::Instance<'tcx>,
126        typing_env: ty::TypingEnv<'tcx>,
127    ) -> DenseBitSet<mir::BasicBlock>;
128
129    /// Configures extra data to be included when pretty printing MIR
130    hook mir_pretty_extra_data(
131        body: &mir::Body<'tcx>,
132    ) -> Option<Box<dyn Fn(mir::PassWhere, &mut dyn io::Write) -> io::Result<()>>>;
133
134}
135
136#[cold]
137fn default_hook(name: &str) -> ! {
138    ::rustc_span::macros::bug_impl(None,
    format_args!("`tcx.{0}` cannot be called as `{0}` was never assigned to a provider function",
        name), Location::caller())bug!("`tcx.{name}` cannot be called as `{name}` was never assigned to a provider function")
139}