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.
56use rustc_hir::def_id::{DefId, DefPathHash};
7use rustc_index::bit_set::DenseBitSet;
8use rustc_session::StableCrateId;
9use rustc_span::def_id::{CrateNum, LocalDefId};
10use rustc_span::{ExpnHash, ExpnId, bug};
1112use crate::mir;
13use crate::query::on_disk_cache::CacheEncoder;
14use crate::ty::{self, Ty, TyCtxt};
1516macro_rules!declare_hooks {
17 (
18 $(
19 $(#[$attr:meta])*
20 hook $name:ident(
21 $( $arg:ident: $K:ty ),* $(,)?
22) -> $V:ty;
23 )*
24 ) => {
2526impl<'tcx> TyCtxt<'tcx> {
27 $(
28 $(#[$attr])*
29#[inline(always)]
30pub fn $name(self, $($arg: $K,)*) -> $V
31{
32 (self.hooks.$name)(self, $($arg,)*)
33 }
34 )*
35 }
3637pub struct Providers {
38 $(pub $name: for<'tcx> fn(
39 TyCtxt<'tcx>,
40 $($arg: $K,)*
41 ) -> $V,)*
42 }
4344impl Default for Providers {
45fn default() -> Self {
46#[allow(unused)]
47Providers {
48 $($name:
49 |_, $($arg,)*| default_hook(stringify!($name))),*
50 }
51 }
52 }
5354impl Copy for Providers {}
55impl Clone for Providers {
56fn clone(&self) -> Self { *self }
57 }
58 };
59}
6061impl<'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)
}
}
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>,
}
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"),
}
}
}
impl Copy for Providers {}
impl Clone for Providers {
fn clone(&self) -> Self { *self }
}declare_hooks! {
62/// Tries to destructure an `mir::Const` ADT or array into its variant index
63 /// and its field values. This should only be used for pretty printing.
64hook try_destructure_mir_constant_for_user_output(val: mir::ConstValue, ty: Ty<'tcx>) -> Option<mir::DestructuredConstant<'tcx>>;
6566/// Getting a &core::panic::Location referring to a span.
67hook const_caller_location(file: rustc_span::Symbol, line: u32, col: u32) -> mir::ConstValue;
6869/// Imports all `SourceFile`s from the given crate into the current session.
70 /// This normally happens automatically when we decode a `Span` from
71 /// that crate's metadata - however, the incr comp cache needs
72 /// to trigger this manually when decoding a foreign `Span`
73hook import_source_files(key: CrateNum) -> ();
7475 hook expn_hash_to_expn_id(
76 cnum: CrateNum,
77 index_guess: u32,
78 hash: ExpnHash79 ) -> ExpnId;
8081/// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
82 /// session, if it still exists. This is used during incremental compilation to
83 /// turn a deserialized `DefPathHash` into its current `DefId`.
84 /// Will fetch a DefId from a DefPathHash for a foreign crate.
85hook def_path_hash_to_def_id_extern(hash: DefPathHash, stable_crate_id: StableCrateId) -> Option<DefId>;
8687/// Returns `true` if we should codegen an instance in the local crate, or returns `false` if we
88 /// can just link to the upstream crate and therefore don't need a mono item.
89 ///
90 /// Note: this hook isn't called within `rustc_middle` but #127779 suggests it's a hook instead
91 /// of a normal function because external tools might want to override it.
92hook should_codegen_locally(instance: crate::ty::Instance<'tcx>) -> bool;
9394 hook alloc_self_profile_query_strings() -> ();
9596/// Saves and writes the DepGraph to the file system.
97 ///
98 /// This function saves both the dep-graph and the query result cache,
99 /// and drops the result cache.
100 ///
101 /// This function should only run after all queries have completed.
102 /// Trying to execute a query afterwards would attempt to read the result cache we just dropped.
103hook save_dep_graph() -> ();
104105 hook verify_query_key_hashes() -> ();
106107/// Ensure the given scalar is valid for the given type.
108 /// This checks non-recursive runtime validity.
109hook validate_scalar_in_layout(scalar: crate::ty::ScalarInt, ty: Ty<'tcx>) -> bool;
110111/// **Do not call this directly; call the `mir_built` query instead.**
112 ///
113 /// Creates the MIR for a given `DefId`, including unreachable code.
114hook build_mir_inner_impl(def: LocalDefId) -> mir::Body<'tcx>;
115116/// Serializes all eligible query return values into the on-disk cache.
117hook encode_query_values(encoder: &mut CacheEncoder<'tcx>) -> ();
118119/// Identifies landing pads that don't do anything, allowing some post-monomorphization
120 /// simplifications during codegen.
121hook find_noop_landing_pads_for_instance(
122 body: &mir::Body<'tcx>,
123 instance: ty::Instance<'tcx>,
124 typing_env: ty::TypingEnv<'tcx>,
125 ) -> DenseBitSet<mir::BasicBlock>;
126}127128#[cold]
129fn default_hook(name: &str) -> ! {
130::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")131}