use std::{
marker::PhantomData,
sync::{
Mutex, PoisonError,
atomic::{AtomicPtr, Ordering},
},
};
use once_cell::sync::OnceCell;
use crate::{
args::ArgInfoTables as OwnedArgInfo,
builders::{ClassBuilder, FunctionBuilder},
convert::IntoZvalDyn,
describe::DocComments,
exception::PhpException,
flags::{ClassFlags, ConstantFlags, MethodFlags, PropertyFlags},
gc::GcRoots,
internal::property::PropertyDescriptor,
zend::{ClassEntry, ExecuteData, ZendObjectHandlers},
};
pub type ClassEntryInfo = (fn() -> &'static ClassEntry, &'static str);
pub trait RegisteredClass: Sized + 'static {
const CLASS_NAME: &'static str;
const BUILDER_MODIFIER: Option<fn(ClassBuilder) -> ClassBuilder>;
const EXTENDS: Option<ClassEntryInfo>;
const IMPLEMENTS: &'static [ClassEntryInfo];
const FLAGS: ClassFlags = ClassFlags::empty();
const NO_CONSTRUCTOR: bool = false;
const DOC_COMMENTS: DocComments = &[];
fn get_metadata() -> &'static ClassMetadata<Self>;
#[must_use]
fn method_properties() -> &'static [PropertyDescriptor<Self>] {
&[]
}
fn method_builders() -> Vec<(FunctionBuilder<'static>, MethodFlags)>;
fn constructor() -> Option<ConstructorMeta<Self>>;
fn constants() -> &'static [(
&'static str,
&'static dyn IntoZvalDyn,
DocComments,
ConstantFlags,
)];
#[must_use]
fn static_properties() -> &'static [(
&'static str,
PropertyFlags,
Option<&'static (dyn IntoZvalDyn + Sync)>,
DocComments,
)] {
&[]
}
#[must_use]
fn interface_implementations() -> Vec<ClassEntryInfo> {
Vec::new()
}
#[must_use]
fn interface_method_implementations() -> Vec<(FunctionBuilder<'static>, MethodFlags)> {
Vec::new()
}
#[must_use]
fn default_init() -> Option<Self> {
None
}
#[must_use]
fn clone_fn() -> Option<fn(&Self) -> Self> {
None
}
fn gc_trace(&self, _roots: &mut GcRoots) {}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a `#[php_class]`",
label = "the PHP objects of `{Self}` hold no Rust value",
note = "a `#[php_enum]` parameter takes the enum by value, for example `suit: Suit`"
)]
pub trait PhpClass: RegisteredClass {}
pub struct ConstructorMeta<T> {
pub constructor: fn(&mut ExecuteData) -> ConstructorResult<T>,
pub build_fn: fn(FunctionBuilder) -> FunctionBuilder,
pub flags: Option<MethodFlags>,
}
pub enum ConstructorResult<T> {
Ok(T),
Exception(PhpException),
ArgError,
}
impl<T, E> From<std::result::Result<T, E>> for ConstructorResult<T>
where
E: Into<PhpException>,
{
fn from(result: std::result::Result<T, E>) -> Self {
match result {
Ok(x) => Self::Ok(x),
Err(e) => Self::Exception(e.into()),
}
}
}
impl<T> From<T> for ConstructorResult<T> {
fn from(result: T) -> Self {
Self::Ok(result)
}
}
struct ArgInfoTables(
#[expect(dead_code, reason = "held for the engine, never read back")] OwnedArgInfo,
);
unsafe impl Send for ArgInfoTables {}
unsafe impl Sync for ArgInfoTables {}
pub struct ClassMetadata<T: 'static> {
handlers: OnceCell<ZendObjectHandlers>,
field_properties: &'static [PropertyDescriptor<T>],
method_properties: OnceCell<&'static [PropertyDescriptor<T>]>,
mangled_names: OnceCell<Box<[Box<str>]>>,
arg_info: Mutex<Option<ArgInfoTables>>,
ce: AtomicPtr<ClassEntry>,
phantom: PhantomData<AtomicPtr<T>>,
}
impl<T: 'static> ClassMetadata<T> {
#[must_use]
pub const fn new(field_properties: &'static [PropertyDescriptor<T>]) -> Self {
Self {
handlers: OnceCell::new(),
field_properties,
method_properties: OnceCell::new(),
mangled_names: OnceCell::new(),
arg_info: Mutex::new(None),
ce: AtomicPtr::new(std::ptr::null_mut()),
phantom: PhantomData,
}
}
}
impl<T: 'static> Default for ClassMetadata<T> {
fn default() -> Self {
Self::new(&[])
}
}
impl<T: RegisteredClass> ClassMetadata<T> {
pub fn handlers(&self) -> &ZendObjectHandlers {
self.handlers.get_or_init(ZendObjectHandlers::new::<T>)
}
pub fn has_ce(&self) -> bool {
!self.ce.load(Ordering::Acquire).is_null()
}
#[expect(
clippy::expect_used,
reason = "the class entry is written once during MINIT, before any Rust code can reach the metadata"
)]
pub fn ce(&self) -> &'static ClassEntry {
unsafe { self.ce.load(Ordering::Acquire).as_ref() }
.expect("Attempted to retrieve class entry before it has been stored.")
}
pub fn set_ce(&self, ce: &'static mut ClassEntry) {
self.ce.store(ce, Ordering::Release);
}
pub fn set_arg_info(&self, arg_info: OwnedArgInfo) {
*self.arg_info.lock().unwrap_or_else(PoisonError::into_inner) =
Some(ArgInfoTables(arg_info));
}
#[must_use]
#[inline]
pub fn find_property(&self, name: &str) -> Option<&PropertyDescriptor<T>> {
self.field_properties
.iter()
.find(|p| p.name == name)
.or_else(|| self.method_properties().iter().find(|p| p.name == name))
}
#[must_use]
#[inline]
pub fn field_properties(&self) -> &'static [PropertyDescriptor<T>] {
self.field_properties
}
#[must_use]
#[inline]
pub fn method_properties(&self) -> &'static [PropertyDescriptor<T>] {
self.method_properties.get_or_init(T::method_properties)
}
pub fn all_properties(&self) -> impl Iterator<Item = &PropertyDescriptor<T>> {
self.field_properties
.iter()
.chain(self.method_properties().iter())
}
#[must_use]
#[inline]
pub fn mangled_names(&self) -> &[Box<str>] {
self.mangled_names.get_or_init(|| {
self.all_properties()
.map(|desc| {
if desc.flags.contains(PropertyFlags::Private) {
format!("\0{}\0{}", T::CLASS_NAME, desc.name).into_boxed_str()
} else if desc.flags.contains(PropertyFlags::Protected) {
format!("\0*\0{}", desc.name).into_boxed_str()
} else {
desc.name.into()
}
})
.collect()
})
}
}
#[cfg(test)]
mod tests {
use std::panic::{RefUnwindSafe, UnwindSafe};
use super::ClassMetadata;
fn assert_unwind_safe<T: RefUnwindSafe + UnwindSafe>() {}
#[test]
fn class_metadata_is_unwind_safe() {
assert_unwind_safe::<ClassMetadata<()>>();
}
}