1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use core::mem::MaybeUninit;
use core::ops::Deref;
use core::ptr::{self, NonNull};
use std::os::raw::c_ulong;
use crate::abi::{BlockDescriptor, BlockDescriptorPtr, BlockFlags, BlockHeader};
use crate::debug::debug_block_header;
use crate::{Block, BlockFn};
// TODO: Should this be a static to help the compiler deduplicating them?
const GLOBAL_DESCRIPTOR: BlockDescriptor = BlockDescriptor {
reserved: 0,
size: mem::size_of::<BlockHeader>() as c_ulong,
};
/// A global Objective-C block that does not capture an environment.
///
/// This is a smart pointer that [`Deref`]s to [`Block`].
///
/// It can created and stored in static memory using the [`global_block!`]
/// macro.
///
/// [`global_block!`]: crate::global_block
#[repr(C)]
pub struct GlobalBlock<F: ?Sized> {
header: BlockHeader,
// We don't store a function pointer, instead it is placed inside the
// invoke function.
f: PhantomData<F>,
}
// TODO: Add `Send + Sync` bounds once the block itself supports that.
unsafe impl<F: ?Sized + BlockFn> Sync for GlobalBlock<F> {}
unsafe impl<F: ?Sized + BlockFn> Send for GlobalBlock<F> {}
// Note: We can't put correct bounds on A and R because we have a const fn,
// and that's not allowed yet in our MSRV.
//
// Fortunately, we don't need them, since they're present on `Sync`, so
// constructing the static in `global_block!` with an invalid `GlobalBlock`
// triggers an error.
impl<F: ?Sized> GlobalBlock<F> {
// TODO: Use new ABI with BLOCK_HAS_SIGNATURE
const FLAGS: BlockFlags =
BlockFlags(BlockFlags::BLOCK_IS_GLOBAL.0 | BlockFlags::BLOCK_USE_STRET.0);
#[doc(hidden)]
pub const __DEFAULT_HEADER: BlockHeader = BlockHeader {
// Populated in `global_block!`
isa: ptr::null_mut(),
flags: Self::FLAGS,
reserved: MaybeUninit::new(0),
// Populated in `global_block!`
invoke: None,
descriptor: BlockDescriptorPtr {
basic: &GLOBAL_DESCRIPTOR,
},
};
/// Use the [`global_block`] macro instead.
#[doc(hidden)]
#[inline]
pub const unsafe fn from_header(header: BlockHeader) -> Self {
Self {
header,
f: PhantomData,
}
}
// TODO: Add some constructor for when `F: Copy`.
}
impl<F: ?Sized + BlockFn> Deref for GlobalBlock<F> {
type Target = Block<F>;
#[inline]
fn deref(&self) -> &Self::Target {
let ptr: NonNull<Self> = NonNull::from(self);
let ptr: NonNull<Block<F>> = ptr.cast();
// SAFETY: This has the same layout as `Block`
//
// A global block does not hold any data, so it is safe to call
// immutably.
unsafe { ptr.as_ref() }
}
}
impl<F: ?Sized> fmt::Debug for GlobalBlock<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut f = f.debug_struct("GlobalBlock");
debug_block_header(&self.header, &mut f);
f.finish_non_exhaustive()
}
}
/// Construct a static [`GlobalBlock`].
///
/// The syntax is similar to a static closure (except that all types have to
/// be specified). Note that the block cannot capture its environment, its
/// parameter types must be [`EncodeArgument`] and the return type must be
/// [`EncodeReturn`].
///
/// [`EncodeArgument`]: objc2::encode::EncodeArgument
/// [`EncodeReturn`]: objc2::encode::EncodeReturn
///
/// # Examples
///
/// ```
/// use block2::global_block;
/// global_block! {
/// static MY_BLOCK = || -> i32 {
/// 42
/// };
/// }
/// assert_eq!(MY_BLOCK.call(()), 42);
/// ```
///
/// ```
/// use block2::global_block;
/// global_block! {
/// static ADDER_BLOCK = |x: i32, y: i32| -> i32 {
/// x + y
/// };
/// }
/// assert_eq!(ADDER_BLOCK.call((5, 7)), 12);
/// ```
///
/// The following does not compile because [`Box`] is not [`EncodeReturn`]:
///
/// ```compile_fail
/// use block2::global_block;
/// global_block! {
/// pub static BLOCK = |b: Box<i32>| {};
/// }
/// ```
///
/// This also doesn't work (yet), as blocks are overly restrictive about the
/// lifetimes involved.
///
/// ```compile_fail
/// use block2::global_block;
/// global_block! {
/// pub static BLOCK_WITH_LIFETIME = |x: &i32| -> i32 {
/// *x + 42
/// };
/// }
/// let x = 5;
/// let res = BLOCK_WITH_LIFETIME.call((&x,));
/// assert_eq!(res, 47);
/// ```
///
/// There is also no way to get a block function that's generic over its
/// parameters. One could imagine the following syntax would work, but it
/// can't due to implementation limitations:
///
/// ```compile_fail
/// use block2::global_block;
/// global_block! {
/// pub static BLOCK<T: Encode> = |b: T| {};
/// }
/// ```
///
/// [`Box`]: std::boxed::Box
#[macro_export]
macro_rules! global_block {
// `||` is parsed as one token
(
$(#[$m:meta])*
$vis:vis static $name:ident = || $(-> $r:ty)? $body:block $(;)?
) => {
$crate::global_block!(
$(#[$m])*
$vis static $name = |,| $(-> $r)? $body
);
};
(
$(#[$m:meta])*
$vis:vis static $name:ident = |$($a:ident: $t:ty),* $(,)?| $(-> $r:ty)? $body:block $(;)?
) => {
$(#[$m])*
#[allow(unused_unsafe)]
$vis static $name: $crate::GlobalBlock<dyn Fn($($t),*) $(-> $r)? + 'static> = unsafe {
let mut header = $crate::GlobalBlock::<dyn Fn($($t),*) $(-> $r)? + 'static>::__DEFAULT_HEADER;
header.isa = ::core::ptr::addr_of!($crate::ffi::_NSConcreteGlobalBlock);
header.invoke = ::core::option::Option::Some({
unsafe extern "C" fn inner(_: *mut $crate::GlobalBlock<dyn Fn($($t),*) $(-> $r)? + 'static>, $($a: $t),*) $(-> $r)? {
$body
}
// TODO: SAFETY
::core::mem::transmute::<
unsafe extern "C" fn(*mut $crate::GlobalBlock<dyn Fn($($t),*) $(-> $r)? + 'static>, $($a: $t),*) $(-> $r)?,
unsafe extern "C" fn(),
>(inner)
});
$crate::GlobalBlock::from_header(header)
};
};
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::format;
global_block! {
/// Test comments and visibility
pub(super) static NOOP_BLOCK = || {};
}
global_block! {
/// Multiple parameters + trailing comma
#[allow(unused)]
static BLOCK = |x: i32, y: i32, z: i32, w: i32,| -> i32 {
x + y + z + w
};
}
#[test]
fn test_noop_block() {
NOOP_BLOCK.call(());
}
#[test]
fn test_defined_in_function() {
global_block!(static MY_BLOCK = || -> i32 {
42
});
assert_eq!(MY_BLOCK.call(()), 42);
}
#[cfg(target_vendor = "apple")]
const DEBUG_BLOCKFLAGS: &str = r#"BlockFlags {
value: "00110000000000000000000000000000",
deallocating: false,
inline_layout_string: false,
small_descriptor: false,
is_noescape: false,
needs_free: false,
has_copy_dispose: false,
has_ctor: false,
is_gc: false,
is_global: true,
use_stret: true,
has_signature: false,
has_extended_layout: false,
over_referenced: false,
reference_count: 0,
..
}"#;
#[cfg(not(target_vendor = "apple"))]
const DEBUG_BLOCKFLAGS: &str = r#"BlockFlags {
value: "00110000000000000000000000000000",
has_copy_dispose: false,
has_ctor: false,
is_global: true,
use_stret: true,
has_signature: false,
over_referenced: false,
reference_count: 0,
..
}"#;
#[test]
fn test_debug() {
let invoke = NOOP_BLOCK.header.invoke.unwrap();
let size = mem::size_of::<BlockHeader>();
let expected = format!(
"GlobalBlock {{
isa: _NSConcreteGlobalBlock,
flags: {DEBUG_BLOCKFLAGS},
reserved: core::mem::maybe_uninit::MaybeUninit<i32>,
invoke: Some(
{invoke:#?},
),
descriptor: BlockDescriptor {{
reserved: 0,
size: {size},
}},
..
}}"
);
assert_eq!(format!("{NOOP_BLOCK:#?}"), expected);
}
#[allow(dead_code)]
fn covariant<'f>(b: GlobalBlock<dyn Fn() + 'static>) -> GlobalBlock<dyn Fn() + 'f> {
b
}
}