ext_php_rs/class.rs
1//! Types and traits used for registering classes with PHP.
2
3use std::{
4 marker::PhantomData,
5 sync::{
6 Mutex, PoisonError,
7 atomic::{AtomicPtr, Ordering},
8 },
9};
10
11use once_cell::sync::OnceCell;
12
13use crate::{
14 args::ArgInfoTables as OwnedArgInfo,
15 builders::{ClassBuilder, FunctionBuilder},
16 convert::IntoZvalDyn,
17 describe::DocComments,
18 exception::PhpException,
19 flags::{ClassFlags, ConstantFlags, MethodFlags, PropertyFlags},
20 gc::GcRoots,
21 internal::property::PropertyDescriptor,
22 zend::{ClassEntry, ExecuteData, ZendObjectHandlers},
23};
24
25/// A type alias for a tuple containing a function pointer to a class entry
26/// and a string representing the class name used in stubs.
27pub type ClassEntryInfo = (fn() -> &'static ClassEntry, &'static str);
28
29/// Implemented on Rust types which are exported to PHP. Allows users to get and
30/// set PHP properties on the object.
31pub trait RegisteredClass: Sized + 'static {
32 /// PHP class name of the registered class.
33 const CLASS_NAME: &'static str;
34
35 /// Function to be called when building the class. Allows user to modify the
36 /// class at runtime (add runtime constants etc).
37 const BUILDER_MODIFIER: Option<fn(ClassBuilder) -> ClassBuilder>;
38
39 /// Parent class entry. Optional.
40 const EXTENDS: Option<ClassEntryInfo>;
41
42 /// Interfaces implemented by the class.
43 const IMPLEMENTS: &'static [ClassEntryInfo];
44
45 /// PHP flags applied to the class.
46 const FLAGS: ClassFlags = ClassFlags::empty();
47
48 /// Whether the class declares no constructor when it has none of its own,
49 /// set by `#[php(no_constructor)]`: `new` then creates an object
50 /// initialized with `Default::default()`, as for a PHP class without a
51 /// constructor. Otherwise a class without a constructor gets one that
52 /// throws.
53 const NO_CONSTRUCTOR: bool = false;
54
55 /// Doc comments for the class.
56 const DOC_COMMENTS: DocComments = &[];
57
58 /// Returns a reference to the class metadata, which stores the class entry,
59 /// handlers, and property descriptors.
60 ///
61 /// This must be statically allocated, and is usually done through the
62 /// [`macro@php_class`] macro.
63 ///
64 /// [`macro@php_class`]: crate::php_class
65 fn get_metadata() -> &'static ClassMetadata<Self>;
66
67 /// Returns method properties (from `#[php(getter)]`/`#[php(setter)]`).
68 /// Resolved via autoref specialization in the macro-generated code.
69 #[must_use]
70 fn method_properties() -> &'static [PropertyDescriptor<Self>] {
71 &[]
72 }
73
74 /// Returns the method builders required to build the class.
75 fn method_builders() -> Vec<(FunctionBuilder<'static>, MethodFlags)>;
76
77 /// Returns the class constructor (if any).
78 fn constructor() -> Option<ConstructorMeta<Self>>;
79
80 /// Returns the constants provided by the class.
81 fn constants() -> &'static [(
82 &'static str,
83 &'static dyn IntoZvalDyn,
84 DocComments,
85 ConstantFlags,
86 )];
87
88 /// Returns the static properties provided by the class.
89 ///
90 /// Static properties are declared at the class level and managed by PHP,
91 /// not by Rust handlers. Each tuple contains (name, flags, default, docs).
92 /// The default value is optional - `None` means null default.
93 #[must_use]
94 fn static_properties() -> &'static [(
95 &'static str,
96 PropertyFlags,
97 Option<&'static (dyn IntoZvalDyn + Sync)>,
98 DocComments,
99 )] {
100 &[]
101 }
102
103 /// Returns interfaces from `#[php_impl_interface]` trait implementations.
104 ///
105 /// This method is generated by the `#[php_class]` macro and uses the
106 /// `inventory` crate to collect interface registrations across crate
107 /// boundaries at link time.
108 ///
109 /// The default implementation returns an empty vector. The macro overrides
110 /// this to iterate over `InterfaceRegistration` entries matching this type.
111 #[must_use]
112 fn interface_implementations() -> Vec<ClassEntryInfo> {
113 Vec::new()
114 }
115
116 /// Returns methods from `#[php_impl_interface]` trait implementations.
117 ///
118 /// This method is generated by the `#[php_class]` macro and uses the
119 /// `inventory` crate to collect method registrations across crate
120 /// boundaries at link time.
121 ///
122 /// The default implementation returns an empty vector. The macro overrides
123 /// this to iterate over `MethodRegistration` entries matching this type.
124 #[must_use]
125 fn interface_method_implementations() -> Vec<(FunctionBuilder<'static>, MethodFlags)> {
126 Vec::new()
127 }
128
129 /// Returns a default instance of the class for immediate initialization.
130 ///
131 /// This is used when PHP creates an object without calling the constructor,
132 /// such as when throwing exceptions via `zend_throw_exception_ex`. For types
133 /// that derive `Default`, this will return `Some(Self::default())`, allowing
134 /// the object to be properly initialized even without a constructor call.
135 #[must_use]
136 fn default_init() -> Option<Self> {
137 None
138 }
139
140 /// The function that copies the Rust value for PHP's `clone` operator.
141 ///
142 /// The `#[php_class]` macro returns `Some(<Self as Clone>::clone)` for
143 /// types that implement `Clone`. When it is [`None`], the class has no
144 /// clone handler, like the uncloneable classes of PHP: `clone` throws an
145 /// `Error` and `ReflectionClass::isCloneable()` returns `false`.
146 #[must_use]
147 fn clone_fn() -> Option<fn(&Self) -> Self> {
148 None
149 }
150
151 /// Reports the PHP values held in the Rust fields of this object to the
152 /// cycle collector.
153 ///
154 /// The [`macro@crate::php_class`] macro generates it: it calls
155 /// [`GcTrace::gc_trace`] one time for each field whose type implements
156 /// [`GcTrace`]. The default reports nothing.
157 ///
158 /// [`GcTrace`]: crate::gc::GcTrace
159 /// [`GcTrace::gc_trace`]: crate::gc::GcTrace::gc_trace
160 fn gc_trace(&self, _roots: &mut GcRoots) {}
161}
162
163/// A [`RegisteredClass`] whose PHP objects hold a Rust value of this type.
164///
165/// The [`macro@crate::php_class`] macro implements it. The PHP objects of a
166/// `#[php_enum]` or `#[php_interface]` type hold no Rust value, so these types
167/// do not implement it. Only a `PhpClass` type can be a `&T`, `&mut T`,
168/// `ClassRef<T>` or `ClassRefMut<T>` parameter.
169#[diagnostic::on_unimplemented(
170 message = "`{Self}` is not a `#[php_class]`",
171 label = "the PHP objects of `{Self}` hold no Rust value",
172 note = "a `#[php_enum]` parameter takes the enum by value, for example `suit: Suit`"
173)]
174pub trait PhpClass: RegisteredClass {}
175
176/// Stores metadata about a classes Rust constructor, including the function
177/// pointer and the arguments of the function.
178pub struct ConstructorMeta<T> {
179 /// Constructor function.
180 pub constructor: fn(&mut ExecuteData) -> ConstructorResult<T>,
181 /// Function called to build the constructor function. Usually adds
182 /// arguments.
183 pub build_fn: fn(FunctionBuilder) -> FunctionBuilder,
184 /// Add constructor modification
185 pub flags: Option<MethodFlags>,
186}
187
188/// Result returned from a constructor of a class.
189pub enum ConstructorResult<T> {
190 /// Successfully constructed the class, contains the new class object.
191 Ok(T),
192 /// An exception occurred while constructing the class.
193 Exception(PhpException),
194 /// Invalid arguments were given to the constructor.
195 ArgError,
196}
197
198impl<T, E> From<std::result::Result<T, E>> for ConstructorResult<T>
199where
200 E: Into<PhpException>,
201{
202 fn from(result: std::result::Result<T, E>) -> Self {
203 match result {
204 Ok(x) => Self::Ok(x),
205 Err(e) => Self::Exception(e.into()),
206 }
207 }
208}
209
210impl<T> From<T> for ConstructorResult<T> {
211 fn from(result: T) -> Self {
212 Self::Ok(result)
213 }
214}
215
216/// Owns the `zend_internal_arg_info` tables of a class's methods.
217struct ArgInfoTables(
218 #[expect(dead_code, reason = "held for the engine, never read back")] OwnedArgInfo,
219);
220
221// SAFETY: the tables are filled once during MINIT, before PHP spawns any request
222// thread, and are never read back through this handle. The engine only ever
223// `memcpy`s out of them (`zend_register_functions`, Zend/zend_API.c on 8.1
224// through 8.5) and never writes through the pointers they contain.
225unsafe impl Send for ArgInfoTables {}
226// SAFETY: see above.
227unsafe impl Sync for ArgInfoTables {}
228
229/// Stores the class entry, handlers, and property descriptors for a Rust type
230/// which has been exported to PHP. Usually allocated statically.
231pub struct ClassMetadata<T: 'static> {
232 handlers: OnceCell<ZendObjectHandlers>,
233 field_properties: &'static [PropertyDescriptor<T>],
234 method_properties: OnceCell<&'static [PropertyDescriptor<T>]>,
235 mangled_names: OnceCell<Box<[Box<str>]>>,
236 /// Argument info tables of this class's methods. `zend_register_functions`
237 /// borrows them until the module shuts down, so they are owned here rather
238 /// than orphaned: this static is the class's equivalent of a C extension's
239 /// `static zend_internal_arg_info[]`. A SAPI that starts the module again in
240 /// the same process registers the class again, with new tables.
241 arg_info: Mutex<Option<ArgInfoTables>>,
242 ce: AtomicPtr<ClassEntry>,
243
244 // `AtomicPtr` is used here because it is `Send + Sync`.
245 // fn() -> T could have been used but that is incompatible with const fns at
246 // the moment.
247 phantom: PhantomData<AtomicPtr<T>>,
248}
249
250impl<T: 'static> ClassMetadata<T> {
251 /// Creates a new class metadata instance with the given field properties.
252 #[must_use]
253 pub const fn new(field_properties: &'static [PropertyDescriptor<T>]) -> Self {
254 Self {
255 handlers: OnceCell::new(),
256 field_properties,
257 method_properties: OnceCell::new(),
258 mangled_names: OnceCell::new(),
259 arg_info: Mutex::new(None),
260 ce: AtomicPtr::new(std::ptr::null_mut()),
261 phantom: PhantomData,
262 }
263 }
264}
265
266impl<T: 'static> Default for ClassMetadata<T> {
267 fn default() -> Self {
268 Self::new(&[])
269 }
270}
271
272impl<T: RegisteredClass> ClassMetadata<T> {
273 /// Returns an immutable reference to the object handlers contained inside
274 /// the class metadata.
275 pub fn handlers(&self) -> &ZendObjectHandlers {
276 self.handlers.get_or_init(ZendObjectHandlers::new::<T>)
277 }
278
279 /// Checks if the class entry has been stored, returning a boolean.
280 pub fn has_ce(&self) -> bool {
281 !self.ce.load(Ordering::Acquire).is_null()
282 }
283
284 /// Retrieves a reference to the stored class entry.
285 ///
286 /// The class entry lives until the module shuts down. A SAPI that starts
287 /// the module again in the same process (`FrankenPHP` worker restarts)
288 /// registers a new one, so do not keep the reference across a restart:
289 /// call this again instead.
290 ///
291 /// # Panics
292 ///
293 /// Panics if there is no class entry stored inside the class metadata.
294 #[expect(
295 clippy::expect_used,
296 reason = "the class entry is written once during MINIT, before any Rust code can reach the metadata"
297 )]
298 pub fn ce(&self) -> &'static ClassEntry {
299 // SAFETY: There are only two values that can be stored in the atomic
300 // ptr: null or a static reference to a class entry. On the null case,
301 // `as_ref()` will return `None` and the function will panic.
302 unsafe { self.ce.load(Ordering::Acquire).as_ref() }
303 .expect("Attempted to retrieve class entry before it has been stored.")
304 }
305
306 /// Stores a reference to a class entry inside the class metadata.
307 ///
308 /// Called during MINIT, before any concurrent access. A SAPI can shut the
309 /// module down and start it again in the same process (`FrankenPHP` does on
310 /// a worker restart or `opcache_reset()`): MINIT then registers the class
311 /// again, and the new entry replaces the one freed with the old module.
312 pub fn set_ce(&self, ce: &'static mut ClassEntry) {
313 self.ce.store(ce, Ordering::Release);
314 }
315
316 /// Takes ownership of the argument info tables of this class's methods.
317 ///
318 /// `zend_register_functions` keeps `zend_internal_function.arg_info`
319 /// pointing into these until the module shuts down, so they must outlive
320 /// registration. Called from `ClassBuilder::register`, once per MINIT: when
321 /// the SAPI starts the module again in the same process, the new tables
322 /// replace those of the class freed with the old module.
323 pub fn set_arg_info(&self, arg_info: OwnedArgInfo) {
324 *self.arg_info.lock().unwrap_or_else(PoisonError::into_inner) =
325 Some(ArgInfoTables(arg_info));
326 }
327
328 /// Finds a property descriptor by name.
329 ///
330 /// Checks field properties first, then method properties. Linear scan is
331 /// used since typical PHP classes have few properties and cache locality
332 /// beats hashing at small N.
333 #[must_use]
334 #[inline]
335 pub fn find_property(&self, name: &str) -> Option<&PropertyDescriptor<T>> {
336 self.field_properties
337 .iter()
338 .find(|p| p.name == name)
339 .or_else(|| self.method_properties().iter().find(|p| p.name == name))
340 }
341
342 /// Returns the field properties (from `#[php(prop)]` struct fields).
343 #[must_use]
344 #[inline]
345 pub fn field_properties(&self) -> &'static [PropertyDescriptor<T>] {
346 self.field_properties
347 }
348
349 /// Returns the method properties (from `#[php(getter)]`/`#[php(setter)]`).
350 /// Lazily initialized on first access from `RegisteredClass::method_properties()`.
351 #[must_use]
352 #[inline]
353 pub fn method_properties(&self) -> &'static [PropertyDescriptor<T>] {
354 self.method_properties.get_or_init(T::method_properties)
355 }
356
357 /// Iterates over all properties (field + method).
358 pub fn all_properties(&self) -> impl Iterator<Item = &PropertyDescriptor<T>> {
359 self.field_properties
360 .iter()
361 .chain(self.method_properties().iter())
362 }
363
364 /// Returns the PHP-convention mangled names of every property, in
365 /// [`all_properties`](Self::all_properties) order.
366 ///
367 /// Private properties mangle to `"\0Class\0name"`, protected ones to
368 /// `"\0*\0name"`, public ones keep their name. Computed once per class on
369 /// first access, one allocation for the process lifetime.
370 #[must_use]
371 #[inline]
372 pub fn mangled_names(&self) -> &[Box<str>] {
373 self.mangled_names.get_or_init(|| {
374 self.all_properties()
375 .map(|desc| {
376 if desc.flags.contains(PropertyFlags::Private) {
377 format!("\0{}\0{}", T::CLASS_NAME, desc.name).into_boxed_str()
378 } else if desc.flags.contains(PropertyFlags::Protected) {
379 format!("\0*\0{}", desc.name).into_boxed_str()
380 } else {
381 desc.name.into()
382 }
383 })
384 .collect()
385 })
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use std::panic::{RefUnwindSafe, UnwindSafe};
392
393 use super::ClassMetadata;
394
395 fn assert_unwind_safe<T: RefUnwindSafe + UnwindSafe>() {}
396
397 #[test]
398 fn class_metadata_is_unwind_safe() {
399 assert_unwind_safe::<ClassMetadata<()>>();
400 }
401}