proc_macro/bridge/selfless_reify.rs
1//! Abstraction for creating `fn` pointers from any callable that *effectively*
2//! has the equivalent of implementing `Default`, even if the compiler neither
3//! provides `Default` nor allows reifying closures (i.e. creating `fn` pointers)
4//! other than those with absolutely no captures.
5//!
6//! More specifically, for a closure-like type to be "effectively `Default`":
7//! * it must be a ZST (zero-sized type): no information contained within, so
8//! that `Default`'s return value (if it were implemented) is unambiguous
9//! * it must be `Copy`: no captured "unique ZST tokens" or any other similar
10//! types that would make duplicating values at will unsound
11//! * combined with the ZST requirement, this confers a kind of "telecopy"
12//! ability: similar to `Copy`, but without keeping the value around, and
13//! instead "reconstructing" it (a noop given it's a ZST) when needed
14//! * it must be *provably* inhabited: no captured uninhabited types or any
15//! other types that cannot be constructed by the user of this abstraction
16//! * the proof is a value of the closure-like type itself, in a sense the
17//! "seed" for the "telecopy" process made possible by ZST + `Copy`
18//! * this requirement is the only reason an abstraction limited to a specific
19//! usecase is required: ZST + `Copy` can be checked with *at worst* a panic
20//! at the "attempted `::default()` call" time, but that doesn't guarantee
21//! that the value can be soundly created, and attempting to use the typical
22//! "proof ZST token" approach leads yet again to having a ZST + `Copy` type
23//! that is not proof of anything without a value (i.e. isomorphic to a
24//! newtype of the type it's trying to prove the inhabitation of)
25//!
26//! A more flexible (and safer) solution to the general problem could exist once
27//! `const`-generic parameters can have type parameters in their types:
28//!
29//! ```rust,ignore (needs future const-generics)
30//! extern "C" fn ffi_wrapper<
31//! A, R,
32//! F: Fn(A) -> R,
33//! const f: F, // <-- this `const`-generic is not yet allowed
34//! >(arg: A) -> R {
35//! f(arg)
36//! }
37//! ```
38
39use std::mem;
40
41pub(super) const fn reify_to_extern_c_fn_hrt_bridge<
42 R,
43 F: Fn(super::BridgeConfig<'_>) -> R + Copy,
44>(
45 f: F,
46) -> extern "C" fn(super::BridgeConfig<'_>) -> R {
47 // FIXME(eddyb) describe the `F` type (e.g. via `type_name::<F>`) once panic
48 // formatting becomes possible in `const fn`.
49 const {
50 assert!(size_of::<F>() == 0, "selfless_reify: closure must be zero-sized");
51 }
52 extern "C" fn wrapper<R, F: Fn(super::BridgeConfig<'_>) -> R + Copy>(
53 bridge: super::BridgeConfig<'_>,
54 ) -> R {
55 let f = unsafe {
56 // SAFETY: `F` satisfies all criteria for "out of thin air"
57 // reconstructability (see module-level doc comment).
58 mem::conjure_zst::<F>()
59 };
60 f(bridge)
61 }
62 let _f_proof = f;
63 wrapper::<R, F>
64}