Skip to main content

ext_php_rs/builders/
class.rs

1use std::{
2    ffi::CString,
3    mem::{ManuallyDrop, MaybeUninit},
4    ptr,
5    rc::Rc,
6};
7
8use crate::{
9    args::ArgInfoTables,
10    builders::{FunctionBuilder, function::free_registered_entries},
11    class::{ClassEntryInfo, ConstructorMeta, ConstructorResult, RegisteredClass},
12    convert::{IntoZval, IntoZvalDyn},
13    describe::DocComments,
14    error::{Error, Result},
15    exception::PhpException,
16    ffi::{
17        _ZEND_TYPE_NAME_BIT, _ZEND_TYPE_NULLABLE_BIT, IS_DOUBLE, IS_LONG, IS_UNDEF, MAY_BE_ANY,
18        ZEND_INTERNAL_FUNCTION, zend_declare_class_constant_ex, zend_declare_property,
19        zend_declare_typed_property, zend_do_implement_interface, zend_hash_str_find_ptr_lc,
20        zend_register_internal_class_ex, zend_register_internal_interface,
21    },
22    flags::{ClassFlags, ConstantFlags, DataType, MethodFlags, PropertyFlags},
23    types::{ZendClassObject, ZendObject, ZendStr, Zval},
24    zend::function::{SensitiveParameters, mark_sensitive},
25    zend::{ClassEntry, CompilerGlobals, ExecuteData, ExecutorGlobals, FunctionEntry, ZendType},
26    zend_fastcall,
27};
28
29/// A constant entry: (name, `value_closure`, docs, `stub_value`, flags)
30type ConstantEntry = (
31    String,
32    Box<dyn FnOnce() -> Result<Zval>>,
33    DocComments,
34    String,
35    ConstantFlags,
36);
37type PropertyDefault = Option<Box<dyn FnOnce() -> Result<Zval>>>;
38
39/// Metadata for a class property to be registered with PHP.
40pub struct ClassProperty {
41    /// Name of the property.
42    pub name: String,
43    /// Visibility and modifier flags.
44    pub flags: PropertyFlags,
45    /// Optional default value closure.
46    pub default: PropertyDefault,
47    /// Documentation comments.
48    pub docs: DocComments,
49    /// PHP type for stub generation.
50    pub ty: Option<DataType>,
51    /// Whether the property accepts null.
52    pub nullable: bool,
53    /// Whether the property is read-only (getter without setter).
54    pub readonly: bool,
55    /// PHP stub representation of the default value (e.g. `"null"`, `"42"`).
56    pub default_stub: Option<String>,
57}
58
59/// Returns the first name that repeats an earlier one. The engine keys
60/// method, function and class tables by ASCII-lowercased name, and constant and
61/// property tables by the exact name.
62pub(crate) fn first_duplicate<'a>(
63    names: impl IntoIterator<Item = &'a str>,
64    fold_ascii_case: bool,
65) -> Option<&'a str> {
66    let names: Vec<&str> = names.into_iter().collect();
67    names.iter().enumerate().find_map(|(i, name)| {
68        names[..i]
69            .iter()
70            .any(|earlier| {
71                if fold_ascii_case {
72                    earlier.eq_ignore_ascii_case(name)
73                } else {
74                    earlier == name
75                }
76            })
77            .then_some(*name)
78    })
79}
80
81/// Returns an error when the engine already holds a class, interface or enum
82/// named `name`, ignoring ASCII case. `do_register_internal_class` would
83/// silently replace it.
84///
85/// `EG(class_table)` is only set at request startup, so this reads
86/// `CG(class_table)`, which holds every class registered so far.
87pub(crate) fn ensure_class_name_free(name: &str) -> Result<()> {
88    let class_table = CompilerGlobals::get().class_table;
89    if class_table.is_null() {
90        return Ok(());
91    }
92    // SAFETY: `class_table` is the engine's live class table and `name` is
93    // valid for `name.len()` bytes; the lookup copies it before lowercasing.
94    let found = unsafe { zend_hash_str_find_ptr_lc(class_table, name.as_ptr().cast(), name.len()) };
95    if found.is_null() {
96        Ok(())
97    } else {
98        Err(Error::DuplicateClass {
99            class: name.to_owned(),
100        })
101    }
102}
103
104/// Builder for registering a class in PHP.
105#[must_use]
106pub struct ClassBuilder {
107    pub(crate) name: String,
108    ce: ClassEntry,
109    pub(crate) extends: Option<ClassEntryInfo>,
110    pub(crate) interfaces: Vec<ClassEntryInfo>,
111    pub(crate) methods: Vec<(FunctionBuilder<'static>, MethodFlags)>,
112    object_override: Option<unsafe extern "C" fn(class_type: *mut ClassEntry) -> *mut ZendObject>,
113    pub(crate) properties: Vec<ClassProperty>,
114    /// Properties declared with their type, see
115    /// [`ClassBuilder::typed_property`].
116    pub(crate) typed_properties: Vec<ClassProperty>,
117    /// The throwing constructor of a `#[php(no_constructor)]` class, added by
118    /// [`ClassBuilder::register`] when the parent is a Rust class declaring a
119    /// constructor: inherited, it would run on an object of another type.
120    unless_parent_constructs: Option<FunctionBuilder<'static>>,
121    pub(crate) constants: Vec<ConstantEntry>,
122    register: Option<fn(&'static mut ClassEntry, ArgInfoTables)>,
123    pub(crate) docs: DocComments,
124}
125
126impl ClassBuilder {
127    /// Creates a new class builder, used to build classes
128    /// to be exported to PHP.
129    ///
130    /// # Parameters
131    ///
132    /// * `name` - The name of the class.
133    pub fn new<T: Into<String>>(name: T) -> Self {
134        Self {
135            name: name.into(),
136            // SAFETY: A zeroed class entry is in an initialized state, as it is a raw C type
137            // whose fields do not have a drop implementation.
138            ce: unsafe { MaybeUninit::zeroed().assume_init() },
139            extends: None,
140            interfaces: vec![],
141            methods: vec![],
142            object_override: None,
143            properties: vec![],
144            typed_properties: vec![],
145            unless_parent_constructs: None,
146            constants: vec![],
147            register: None,
148            docs: &[],
149        }
150    }
151
152    /// Return PHP class flags
153    #[must_use]
154    pub fn get_flags(&self) -> u32 {
155        self.ce.ce_flags
156    }
157
158    /// Sets the class builder to extend another class.
159    ///
160    /// # Parameters
161    ///
162    /// * `parent` - The parent class to extend.
163    pub fn extends(mut self, parent: ClassEntryInfo) -> Self {
164        self.extends = Some(parent);
165        self
166    }
167
168    /// Implements an interface on the class.
169    ///
170    /// # Parameters
171    ///
172    /// * `interface` - Interface to implement on the class.
173    ///
174    /// # Panics
175    ///
176    /// Panics when the given class entry `interface` is not an interface.
177    pub fn implements(mut self, interface: ClassEntryInfo) -> Self {
178        self.interfaces.push(interface);
179        self
180    }
181
182    /// Adds a method to the class.
183    ///
184    /// # Parameters
185    ///
186    /// * `func` - The function builder to add to the class.
187    /// * `flags` - Flags relating to the function. See [`MethodFlags`].
188    pub fn method(mut self, func: FunctionBuilder<'static>, flags: MethodFlags) -> Self {
189        self.methods.push((func, flags));
190        self
191    }
192
193    /// Adds a property to the class.
194    ///
195    /// # Parameters
196    ///
197    /// * `prop` - The property metadata to add to the class.
198    pub fn property(mut self, prop: ClassProperty) -> Self {
199        self.properties.push(prop);
200        self
201    }
202
203    /// Adds a typed property to the class, declared as PHP declares
204    /// `protected int $count = 0;`: the engine enforces `prop.ty` (and
205    /// `prop.nullable`) on every write, and reflection reports the type.
206    ///
207    /// `prop.ty` is a scalar type, `mixed`, or a class (`DataType::Object`
208    /// with a class name). Without a default the property starts
209    /// uninitialized, as an untyped default never does: reading it before a
210    /// write throws PHP's `Error`, and `unset()` returns it to that state. A
211    /// default must be a value of the type.
212    ///
213    /// `prop.readonly` must be `false`, and the class must not be a readonly
214    /// class (PHP 8.2): the engine would declare the property writable, where
215    /// PHP declares it `readonly`.
216    ///
217    /// [`ClassBuilder::property`] declares a property without a type; its
218    /// `ty` only shapes the generated stubs.
219    ///
220    /// # Errors
221    ///
222    /// [`ClassBuilder::register`] fails with [`Error::InvalidPropertyType`]
223    /// when `prop.ty` is `None` or names a type a property cannot have
224    /// (`iterable`, `resource`, `callable`, ...), when the default is not a
225    /// value of the type, or when the property would have to be readonly.
226    pub fn typed_property(mut self, prop: ClassProperty) -> Self {
227        self.typed_properties.push(prop);
228        self
229    }
230
231    /// Adds a constant to the class. The type of the constant is defined by the
232    /// type of the given default.
233    ///
234    /// Returns a result containing the class builder if the constant was
235    /// successfully added.
236    ///
237    /// # Parameters
238    ///
239    /// * `name` - The name of the constant to add to the class.
240    /// * `value` - The value of the constant.
241    /// * `docs` - Documentation comments for the constant.
242    /// * `flags` - Visibility of the constant.
243    ///
244    /// # Errors
245    ///
246    /// Returns an error if `value` cannot be converted into a [`Zval`].
247    pub fn constant<T: Into<String>>(
248        mut self,
249        name: T,
250        value: impl IntoZval + 'static,
251        docs: DocComments,
252        flags: ConstantFlags,
253    ) -> Result<Self> {
254        let zval = value.into_zval(true)?;
255        let stub = crate::convert::zval_to_stub(&zval);
256        self.constants
257            .push((name.into(), Box::new(|| Ok(zval)), docs, stub, flags));
258        Ok(self)
259    }
260
261    /// Adds a constant to the class from a `dyn` object. The type of the
262    /// constant is defined by the type of the value.
263    ///
264    /// Returns a result containing the class builder if the constant was
265    /// successfully added.
266    ///
267    /// # Parameters
268    ///
269    /// * `name` - The name of the constant to add to the class.
270    /// * `value` - The value of the constant.
271    /// * `docs` - Documentation comments for the constant.
272    /// * `flags` - Visibility of the constant.
273    ///
274    /// # Errors
275    ///
276    /// Returns an error if `value` cannot be converted into a [`Zval`].
277    pub fn dyn_constant<T: Into<String>>(
278        mut self,
279        name: T,
280        value: &'static dyn IntoZvalDyn,
281        docs: DocComments,
282        flags: ConstantFlags,
283    ) -> Result<Self> {
284        let stub = value.stub_value();
285        let value = Rc::new(value);
286        self.constants.push((
287            name.into(),
288            Box::new(move || value.as_zval(true)),
289            docs,
290            stub,
291            flags,
292        ));
293        Ok(self)
294    }
295
296    /// Sets the flags for the class.
297    ///
298    /// # Parameters
299    ///
300    /// * `flags` - Flags relating to the class. See [`ClassFlags`].
301    pub fn flags(mut self, flags: ClassFlags) -> Self {
302        self.ce.ce_flags = flags.bits();
303        self
304    }
305
306    /// Overrides the creation of the Zend object which will represent an
307    /// instance of this class.
308    ///
309    /// # Parameters
310    ///
311    /// * `T` - The type which will override the Zend object. Must implement
312    ///   [`RegisteredClass`] which can be derived using the
313    ///   [`php_class`](crate::php_class) attribute macro.
314    ///
315    /// # Panics
316    ///
317    /// Panics if the class name associated with `T` is not the same as the
318    /// class name specified when creating the builder.
319    pub fn object_override<T: RegisteredClass>(mut self) -> Self {
320        extern "C" fn create_object<T: RegisteredClass>(ce: *mut ClassEntry) -> *mut ZendObject {
321            // Try to initialize with a default instance if available.
322            // This is critical for exception classes that extend \Exception, because
323            // PHP's zend_throw_exception_ex creates objects via create_object without
324            // calling the constructor, then immediately accesses properties.
325            // Without default initialization, accessing properties on uninitialized
326            // objects would panic.
327            if let Some(instance) = T::default_init() {
328                // `ce` is `T`'s class or a PHP subclass of it: the object is one
329                // of the class `new` names.
330                let obj = ZendClassObject::<T>::new_in(instance, unsafe { ce.as_ref() }).into_raw();
331                // SAFETY: `into_raw` yields a valid, exclusively owned object that
332                // the engine takes over.
333                return unsafe { (*obj).get_mut_zend_obj() };
334            }
335
336            // SAFETY: After calling this function, PHP will always call the constructor
337            // defined below, which assumes that the object is uninitialized.
338            let obj = ZendClassObject::<T>::new_uninit(unsafe { ce.as_ref() }).into_raw();
339            // SAFETY: same ownership transfer as above.
340            unsafe { (*obj).get_mut_zend_obj() }
341        }
342
343        zend_fastcall! {
344            extern fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
345                crate::zend::run_handler(std::panic::AssertUnwindSafe(|| {
346                    let Some(ConstructorMeta { constructor, .. }) = T::constructor() else {
347                        PhpException::from_message("You cannot instantiate this class from PHP.".into())
348                            .throw();
349                        return;
350                    };
351
352                    let this = match constructor(ex) {
353                        ConstructorResult::Ok(this) => this,
354                        ConstructorResult::Exception(e) => {
355                            e.throw();
356                            return;
357                        }
358                        ConstructorResult::ArgError => return,
359                    };
360
361                    let Some(this_obj) = ex.get_object::<T>() else {
362                        PhpException::from_message("Failed to retrieve reference to `this` object.".into())
363                            .throw();
364                        return;
365                    };
366
367                    if let Err(err) = this_obj.initialize(this) {
368                        PhpException::from(err).throw();
369                    }
370                }));
371            }
372        }
373
374        debug_assert_eq!(
375            self.name.as_str(),
376            T::CLASS_NAME,
377            "Class name in builder does not match class name in `impl RegisteredClass`."
378        );
379        self.object_override = Some(create_object::<T>);
380        let is_interface = T::FLAGS.contains(ClassFlags::Interface);
381
382        // For interfaces: only add __construct if explicitly declared.
383        // For classes: a declared constructor; else, with `NO_CONSTRUCTOR`, none
384        // (objects are created initialized from `Default`, see `create_object`),
385        // unless a Rust parent declares one (see `register`); else one that
386        // throws, since the object could not be initialized.
387        if let Some(ConstructorMeta {
388            build_fn, flags, ..
389        }) = T::constructor()
390        {
391            let func = if is_interface {
392                FunctionBuilder::new_abstract("__construct")
393            } else {
394                FunctionBuilder::new("__construct", constructor::<T>)
395            };
396            let visibility = flags.unwrap_or(MethodFlags::Public);
397            self.method(build_fn(func), visibility)
398        } else if is_interface {
399            self
400        } else if T::NO_CONSTRUCTOR {
401            self.unless_parent_constructs =
402                Some(FunctionBuilder::new("__construct", constructor::<T>));
403            self
404        } else {
405            // Add default constructor for classes
406            let func = FunctionBuilder::new("__construct", constructor::<T>);
407            self.method(func, MethodFlags::Public)
408        }
409    }
410
411    /// Function to register the class with PHP, called once the class is built.
412    ///
413    /// It receives the registered class entry and the argument info tables of
414    /// the class's methods. `zend_register_functions` borrows those tables for
415    /// the life of the process, so the function must park them somewhere that
416    /// lives that long — normally the class's own
417    /// [`ClassMetadata`](crate::class::ClassMetadata) static:
418    ///
419    /// ```rust,ignore
420    /// .registration(|ce, arg_info| {
421    ///     META.set_ce(ce);
422    ///     META.set_arg_info(arg_info);
423    /// })
424    /// ```
425    ///
426    /// # Parameters
427    ///
428    /// * `register` - The function to call to register the class.
429    pub fn registration(mut self, register: fn(&'static mut ClassEntry, ArgInfoTables)) -> Self {
430        self.register = Some(register);
431        self
432    }
433
434    /// Sets the documentation for the class.
435    ///
436    /// # Parameters
437    ///
438    /// * `docs` - The documentation comments for the class.
439    pub fn docs(mut self, docs: DocComments) -> Self {
440        self.docs = docs;
441        self
442    }
443
444    /// Checks that no two properties, methods or constants of the class share
445    /// a PHP name. Methods are compared ignoring ASCII case, like the engine.
446    fn validate(&self) -> Result<()> {
447        if let Some(name) = first_duplicate(
448            self.properties
449                .iter()
450                .chain(&self.typed_properties)
451                .map(|p| p.name.as_str()),
452            false,
453        ) {
454            return Err(Error::DuplicateProperty {
455                property: format!("{}::${name}", self.name),
456            });
457        }
458        if let Some(name) = first_duplicate(self.methods.iter().map(|(m, _)| m.name.as_str()), true)
459        {
460            return Err(Error::DuplicateMethod {
461                method: format!("{}::{name}", self.name),
462            });
463        }
464        if let Some(name) = first_duplicate(self.constants.iter().map(|c| c.0.as_str()), false) {
465            return Err(Error::DuplicateConstant {
466                constant: format!("{}::{name}", self.name),
467            });
468        }
469        #[cfg(php82)]
470        let readonly_class = self.ce.ce_flags & ClassFlags::ReadonlyClass.bits() != 0;
471        #[cfg(not(php82))]
472        let readonly_class = false;
473        for prop in &self.typed_properties {
474            let typed = prop
475                .ty
476                .and_then(|ty| property_type_mask(ty, prop.nullable))
477                .is_some();
478            if !typed || prop.readonly || readonly_class {
479                return Err(Error::InvalidPropertyType {
480                    property: format!("{}::${}", self.name, prop.name),
481                });
482            }
483        }
484        Ok(())
485    }
486
487    /// A `#[php(no_constructor)]` class under a Rust class that declares a
488    /// constructor would inherit it, and the parent's constructor would run on
489    /// an object of another Rust type: the class keeps the one that throws.
490    fn keep_throwing_constructor(&mut self) {
491        if let Some(constructor) = self.unless_parent_constructs.take()
492            && self
493                .extends
494                .as_ref()
495                .is_some_and(|(parent, _)| constructs_in_this_module(parent()))
496        {
497            self.methods.push((constructor, MethodFlags::Public));
498        }
499    }
500
501    /// Builds and registers the class.
502    ///
503    /// # Errors
504    ///
505    /// * [`Error::DuplicateProperty`], [`Error::DuplicateMethod`] or
506    ///   [`Error::DuplicateConstant`] - If two members share a PHP name.
507    /// * [`Error::DuplicateClass`] - If a class with this name, ignoring ASCII
508    ///   case, is already registered.
509    /// * [`Error::InvalidPropertyType`] - If a typed property has no type a
510    ///   property can have, or a default that is not a value of its type.
511    /// * [`Error::InvalidPointer`] - If the class could not be registered.
512    /// * [`Error::InvalidCString`] - If the class name is not a valid C string.
513    /// * [`Error::IntegerOverflow`] - If the property flags are not valid.
514    /// * If a method or property could not be built.
515    ///
516    /// # Panics
517    ///
518    /// * If called outside a module startup (MINIT) function.
519    /// * If no registration function was provided.
520    pub fn register(mut self) -> Result<()> {
521        assert!(
522            !ExecutorGlobals::get().current_module.is_null(),
523            "Classes can only be registered from a module startup (MINIT) function: \
524             `do_register_internal_class` dereferences `EG(current_module)`."
525        );
526        self.validate()?;
527        ensure_class_name_free(&self.name)?;
528
529        self.ce.name = ZendStr::new_interned(&self.name, true).into_raw();
530
531        self.keep_throwing_constructor();
532
533        let mut arg_info = Vec::with_capacity(self.methods.len());
534        let mut methods = Vec::with_capacity(self.methods.len() + 1);
535        let mut sensitive = SensitiveParameters::new();
536        for (method, flags) in self.methods {
537            sensitive.extend(method.sensitive());
538            let (mut entry, args) = method.build()?;
539            entry.add_flags(flags);
540            methods.push(entry);
541            arg_info.push(args);
542        }
543
544        // The engine keeps `zend_internal_function.arg_info` pointing into these
545        // for the life of the process, so `register` parks them. Holding them in
546        // a `ManuallyDrop` keeps them alive across registration, which reads
547        // them, without a second owner. Every fallible step below runs after the
548        // class entry is in `CG(class_table)`, so an error must leak the tables
549        // rather than dangle the functions the engine already holds.
550        let arg_info = ManuallyDrop::new(arg_info.into_boxed_slice());
551
552        methods.push(FunctionEntry::end());
553        let entries = Box::into_raw(methods.into_boxed_slice());
554        self.ce.info.internal.builtin_functions = entries.cast::<FunctionEntry>().cast_const();
555
556        let class = if self.ce.flags().contains(ClassFlags::Interface) {
557            unsafe { zend_register_internal_interface(&raw mut self.ce) }
558        } else {
559            // Resolved here and not before the branch: the getter is usually
560            // `T::get_metadata().ce()`, which panics when the parent has not been
561            // registered, and `zend_register_internal_interface` takes no parent.
562            let parent = match self.extends {
563                Some((ptr, _)) => ptr::from_ref(ptr()).cast_mut(),
564                None => std::ptr::null_mut(),
565            };
566            unsafe { zend_register_internal_class_ex(&raw mut self.ce, parent) }
567        };
568
569        // SAFETY: `do_register_internal_class` has interned every `fname` and read
570        // `builtin_functions` for the last time, so the table is dead.
571        unsafe { free_registered_entries(entries) };
572
573        let class = unsafe { class.as_mut() }.ok_or(Error::InvalidPointer)?;
574        class.info.internal.builtin_functions = ptr::null();
575        mark_sensitive(&raw const class.function_table, &sensitive);
576
577        // disable serialization if the class has an associated object
578        if self.object_override.is_some() {
579            cfg_if::cfg_if! {
580                if #[cfg(php81)] {
581                    class.ce_flags |= ClassFlags::NotSerializable.bits();
582                } else {
583                    class.serialize = Some(crate::ffi::zend_class_serialize_deny);
584                    class.unserialize = Some(crate::ffi::zend_class_unserialize_deny);
585                }
586            }
587        }
588
589        for (iface, _) in self.interfaces {
590            let interface = iface();
591            assert!(
592                interface.is_interface(),
593                "Given class entry was not an interface."
594            );
595
596            unsafe { zend_do_implement_interface(class, ptr::from_ref(interface).cast_mut()) };
597        }
598
599        for prop in self.properties {
600            let mut default_zval = match prop.default {
601                Some(f) => f()?,
602                None => Zval::new(),
603            };
604            unsafe {
605                zend_declare_property(
606                    class,
607                    CString::new(prop.name.as_str())?.as_ptr(),
608                    prop.name.len() as _,
609                    &raw mut default_zval,
610                    prop.flags.bits().try_into()?,
611                );
612            }
613        }
614
615        for prop in self.typed_properties {
616            declare_typed_property(class, &self.name, prop)?;
617        }
618
619        for (name, value, _, _, flags) in self.constants {
620            // The constants table keeps the interned key; releasing an interned
621            // string is a no-op, so dropping the `ZBox` afterwards is sound.
622            let name = ZendStr::new_interned(&name, true);
623            // `zend_declare_class_constant_ex` takes the payload with
624            // `ZVAL_COPY_VALUE` and no incref and, unlike
625            // `zend_declare_typed_property`, does not reject refcounted values, so
626            // the constants table owns it and the `Zval` must not run its destructor.
627            let mut value = ManuallyDrop::new(value()?);
628            unsafe {
629                zend_declare_class_constant_ex(
630                    class,
631                    name.as_ptr().cast_mut(),
632                    &raw mut *value,
633                    flags.bits().try_into()?,
634                    ptr::null_mut(),
635                );
636            };
637        }
638
639        if let Some(object_override) = self.object_override {
640            class.__bindgen_anon_2.create_object = Some(object_override);
641        }
642
643        if let Some(register) = self.register {
644            register(class, ManuallyDrop::into_inner(arg_info));
645        } else {
646            panic!("Class {} was not registered.", self.name);
647        }
648
649        Ok(())
650    }
651}
652
653/// The type mask of a property declared with `ty`, or `None` when a property
654/// cannot have that type.
655///
656/// An allowlist: the types of [`ZendType::scalar_type_mask`], `mixed`, and a
657/// class (`DataType::Object` with a name, whose mask holds
658/// `_ZEND_TYPE_NAME_BIT` and needs the name as the type's pointer).
659/// `nullable` adds `null`, except to `mixed`, which holds it already.
660/// `iterable` is refused: a property cannot use the `_ZEND_TYPE_ITERABLE_BIT`
661/// arginfo carries, which only `zend_register_functions` expands into
662/// `Traversable|array`.
663pub(crate) fn property_type_mask(ty: DataType, nullable: bool) -> Option<u32> {
664    let nullable = if nullable { _ZEND_TYPE_NULLABLE_BIT } else { 0 };
665    let mask = match ty {
666        DataType::Mixed => return Some(MAY_BE_ANY),
667        DataType::Object(_) if ty.class_name().is_some() => _ZEND_TYPE_NAME_BIT,
668        _ => ZendType::scalar_type_mask(ty)?,
669    };
670    Some(mask | nullable)
671}
672
673/// How a default value of type code `code` fits a property whose type is
674/// `mask`, as `zend_is_valid_default_value` decides.
675#[derive(Debug, PartialEq, Eq)]
676pub(crate) enum DefaultFit {
677    /// A value of the type, or no default (`IS_UNDEF`).
678    Fits,
679    /// An `int` where the type holds `float`: the default becomes a float.
680    ToDouble,
681    /// Refused.
682    Refused,
683}
684
685pub(crate) fn default_fit(mask: u32, code: u32) -> DefaultFit {
686    if code == IS_UNDEF || (code < 32 && mask & (1 << code) != 0) {
687        DefaultFit::Fits
688    } else if mask & (1 << IS_DOUBLE) != 0 && code == IS_LONG {
689        DefaultFit::ToDouble
690    } else {
691        DefaultFit::Refused
692    }
693}
694
695/// Declares `prop` on `class` (named `class_name`) with its type, see
696/// [`ClassBuilder::typed_property`].
697fn declare_typed_property(
698    class: &mut ClassEntry,
699    class_name: &str,
700    prop: ClassProperty,
701) -> Result<()> {
702    let invalid = || Error::InvalidPropertyType {
703        property: format!("{class_name}::${}", prop.name),
704    };
705    let ty = prop.ty.ok_or_else(invalid)?;
706    let mask = property_type_mask(ty, prop.nullable).ok_or_else(invalid)?;
707    // A property type names its class with an interned `zend_string`, where
708    // argument info takes a C string.
709    let type_ptr = match ty.class_name() {
710        Some(name) => ManuallyDrop::new(ZendStr::new_interned(name, true))
711            .as_ptr()
712            .cast_mut()
713            .cast(),
714        None => ptr::null_mut(),
715    };
716    let mut default = if let Some(f) = prop.default {
717        f()?
718    } else {
719        // `IS_UNDEF`: the property starts uninitialized.
720        let mut undef = Zval::new();
721        undef.u1.type_info = IS_UNDEF;
722        undef
723    };
724    // SAFETY: the low byte of `type_info` is the zval's type code, whichever
725    // member of the union was written.
726    let code = unsafe { default.u1.type_info } & 0xff;
727    match default_fit(mask, code) {
728        DefaultFit::Fits => {}
729        DefaultFit::ToDouble => {
730            let long = default.long().ok_or_else(invalid)?;
731            #[expect(
732                clippy::cast_precision_loss,
733                reason = "PHP converts an int default to float the same way"
734            )]
735            default.set_double(long as f64);
736        }
737        DefaultFit::Refused => return Err(invalid()),
738    }
739    let name = ZendStr::new_interned(&prop.name, true);
740    // The engine takes the default with `ZVAL_COPY_VALUE`, as for
741    // `zend_declare_property` above, and keeps the interned name and type.
742    unsafe {
743        zend_declare_typed_property(
744            class,
745            name.as_ptr().cast_mut(),
746            &raw mut default,
747            prop.flags.bits().try_into()?,
748            ptr::null_mut(),
749            ZendType {
750                ptr: type_ptr,
751                type_mask: mask,
752            },
753        );
754    }
755    std::mem::forget(default);
756    Ok(())
757}
758
759/// Whether `class` declares a constructor registered by the module being
760/// started: a Rust class of this extension, whose constructor initializes an
761/// object of its own Rust type.
762fn constructs_in_this_module(class: &ClassEntry) -> bool {
763    // SAFETY: a registered class's constructor is a live function of the
764    // engine's function table, and `type_` tells which member of the union
765    // holds it.
766    unsafe { class.constructor.as_ref() }.is_some_and(|constructor| unsafe {
767        u32::from(constructor.type_) == ZEND_INTERNAL_FUNCTION
768            && constructor.internal_function.module == ExecutorGlobals::get().current_module
769    })
770}
771
772#[cfg(test)]
773mod tests {
774    use crate::ffi::{IS_ARRAY, IS_FALSE, IS_NULL, IS_OBJECT, IS_STRING, IS_TRUE, MAY_BE_BOOL};
775    use crate::test::test_function;
776
777    use super::*;
778
779    fn typed(name: &str, ty: DataType, nullable: bool) -> ClassProperty {
780        ClassProperty {
781            name: name.into(),
782            flags: PropertyFlags::Public,
783            default: None,
784            docs: &[],
785            ty: Some(ty),
786            nullable,
787            readonly: false,
788            default_stub: None,
789        }
790    }
791
792    #[test]
793    fn property_type_mask_covers_every_data_type() {
794        let null = _ZEND_TYPE_NULLABLE_BIT;
795        let cases = [
796            (DataType::Undef, None),
797            (DataType::Null, None),
798            (DataType::False, None),
799            (DataType::True, None),
800            (DataType::Long, Some(1 << IS_LONG)),
801            (DataType::Double, Some(1 << IS_DOUBLE)),
802            (DataType::String, Some(1 << IS_STRING)),
803            (DataType::Array, Some(1 << IS_ARRAY)),
804            (DataType::Iterable, None),
805            (DataType::Object("".into()), Some(1 << IS_OBJECT)),
806            (DataType::Object("Foo".into()), Some(_ZEND_TYPE_NAME_BIT)),
807            (DataType::Resource, None),
808            (DataType::Reference, None),
809            (DataType::Callable, None),
810            (DataType::ConstantExpression, None),
811            (DataType::Indirect, None),
812            (DataType::Void, None),
813            (DataType::Mixed, Some(MAY_BE_ANY)),
814            (DataType::Bool, Some(MAY_BE_BOOL)),
815            (DataType::Ptr, None),
816        ];
817        for (ty, mask) in cases {
818            assert_eq!(property_type_mask(ty, false), mask, "{ty:?}");
819            let nullable = match ty {
820                DataType::Mixed => mask,
821                _ => mask.map(|m| m | null),
822            };
823            assert_eq!(property_type_mask(ty, true), nullable, "?{ty:?}");
824        }
825    }
826
827    #[test]
828    fn validate_refuses_a_typed_property_without_a_property_type() {
829        // `iterable` refused arrays and segfaulted on the TypeError, `resource`
830        // and a constant expression segfaulted `ReflectionType::__toString`,
831        // and `Indirect` became `callable`.
832        for ty in [
833            DataType::Iterable,
834            DataType::Resource,
835            DataType::ConstantExpression,
836            DataType::Indirect,
837            DataType::Callable,
838            DataType::Void,
839        ] {
840            let class = ClassBuilder::new("Foo").typed_property(typed("a", ty, false));
841            assert!(
842                matches!(
843                    class.validate(),
844                    Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
845                ),
846                "{ty:?}"
847            );
848        }
849        let mut missing = typed("a", DataType::Long, false);
850        missing.ty = None;
851        assert!(
852            ClassBuilder::new("Foo")
853                .typed_property(missing)
854                .validate()
855                .is_err()
856        );
857    }
858
859    #[test]
860    fn validate_accepts_property_types() {
861        let class = ClassBuilder::new("Foo")
862            .typed_property(typed("a", DataType::Long, false))
863            .typed_property(typed("b", DataType::String, true))
864            .typed_property(typed("c", DataType::Object("ArrayObject".into()), false))
865            .typed_property(typed("d", DataType::Mixed, true))
866            // An untyped property's `ty` only shapes stubs.
867            .property(typed("e", DataType::Iterable, false));
868        assert!(class.validate().is_ok());
869    }
870
871    #[test]
872    fn default_fit_as_zend_is_valid_default_value() {
873        let mask = |ty, nullable| property_type_mask(ty, nullable).expect("a property type");
874        let float = mask(DataType::Double, false);
875        assert_eq!(default_fit(float, IS_LONG), DefaultFit::ToDouble);
876        assert_eq!(default_fit(float, IS_DOUBLE), DefaultFit::Fits);
877        let string = mask(DataType::String, false);
878        assert_eq!(default_fit(string, IS_LONG), DefaultFit::Refused);
879        let int = mask(DataType::Long, false);
880        assert_eq!(default_fit(int, IS_DOUBLE), DefaultFit::Refused);
881        assert_eq!(default_fit(int, IS_NULL), DefaultFit::Refused);
882        assert_eq!(default_fit(int, IS_UNDEF), DefaultFit::Fits);
883        let nullable_int = mask(DataType::Long, true);
884        assert_eq!(default_fit(nullable_int, IS_NULL), DefaultFit::Fits);
885        let class = mask(DataType::Object("Foo".into()), false);
886        assert_eq!(default_fit(class, IS_LONG), DefaultFit::Refused);
887        assert_eq!(default_fit(class, IS_OBJECT), DefaultFit::Refused);
888        let boolean = mask(DataType::Bool, false);
889        assert_eq!(default_fit(boolean, IS_TRUE), DefaultFit::Fits);
890        assert_eq!(default_fit(boolean, IS_FALSE), DefaultFit::Fits);
891    }
892
893    #[test]
894    fn validate_refuses_readonly_typed_properties() {
895        let mut readonly = typed("a", DataType::Long, false);
896        readonly.readonly = true;
897        assert!(matches!(
898            ClassBuilder::new("Foo").typed_property(readonly).validate(),
899            Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
900        ));
901    }
902
903    #[test]
904    #[cfg(php82)]
905    fn validate_refuses_typed_properties_on_a_readonly_class() {
906        // The engine does not make a readonly class's typed properties
907        // readonly, as PHP's compiler does.
908        let class = ClassBuilder::new("Foo")
909            .flags(ClassFlags::ReadonlyClass)
910            .typed_property(typed("a", DataType::Long, false));
911        assert!(matches!(
912            class.validate(),
913            Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
914        ));
915    }
916
917    #[test]
918    fn validate_refuses_a_typed_property_repeating_an_untyped_one() {
919        let class = ClassBuilder::new("Foo")
920            .property(typed("a", DataType::Long, false))
921            .typed_property(typed("a", DataType::Long, false));
922        assert!(matches!(
923            class.validate(),
924            Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
925        ));
926    }
927
928    #[test]
929    #[allow(unpredictable_function_pointer_comparisons)]
930    fn test_new() {
931        let class = ClassBuilder::new("Foo");
932        assert_eq!(class.name, "Foo");
933        assert_eq!(class.extends, None);
934        assert_eq!(class.interfaces, vec![]);
935        assert_eq!(class.methods.len(), 0);
936        assert_eq!(class.object_override, None);
937        assert!(class.properties.is_empty());
938        assert_eq!(class.constants.len(), 0);
939        assert_eq!(class.register, None);
940        assert_eq!(class.docs, &[] as DocComments);
941    }
942
943    #[test]
944    fn test_extends() {
945        let extends: ClassEntryInfo = (|| todo!(), "Bar");
946        let class = ClassBuilder::new("Foo").extends(extends);
947        assert_eq!(class.extends, Some(extends));
948    }
949
950    #[test]
951    fn test_implements() {
952        let implements: ClassEntryInfo = (|| todo!(), "Bar");
953        let class = ClassBuilder::new("Foo").implements(implements);
954        assert_eq!(class.interfaces, vec![implements]);
955    }
956
957    #[test]
958    fn test_method() {
959        let method = FunctionBuilder::new("foo", test_function);
960        let class = ClassBuilder::new("Foo").method(method, MethodFlags::Public);
961        assert_eq!(class.methods.len(), 1);
962    }
963
964    #[test]
965    fn test_property() {
966        let class = ClassBuilder::new("Foo").property(ClassProperty {
967            name: "bar".into(),
968            flags: PropertyFlags::Public,
969            default: None,
970            docs: &["Doc 1"],
971            ty: Some(DataType::String),
972            nullable: false,
973            readonly: false,
974            default_stub: None,
975        });
976        assert_eq!(class.properties.len(), 1);
977        assert_eq!(class.properties[0].name, "bar");
978        assert_eq!(class.properties[0].flags, PropertyFlags::Public);
979        assert!(class.properties[0].default.is_none());
980        assert_eq!(class.properties[0].docs, &["Doc 1"] as DocComments);
981        assert_eq!(class.properties[0].ty, Some(DataType::String));
982    }
983
984    fn named_property(name: &str) -> ClassProperty {
985        ClassProperty {
986            name: name.into(),
987            flags: PropertyFlags::Public,
988            default: None,
989            docs: &[],
990            ty: None,
991            nullable: false,
992            readonly: false,
993            default_stub: None,
994        }
995    }
996
997    fn with_constant(mut class: ClassBuilder, name: &str) -> ClassBuilder {
998        class.constants.push((
999            name.into(),
1000            Box::new(|| Err(Error::InvalidPointer)),
1001            &[],
1002            String::new(),
1003            ConstantFlags::Public,
1004        ));
1005        class
1006    }
1007
1008    #[test]
1009    fn first_duplicate_folds_ascii_case_only_when_asked() {
1010        assert_eq!(first_duplicate(["a", "b", "a"], false), Some("a"));
1011        assert_eq!(first_duplicate(["a", "B", "b"], false), None);
1012        assert_eq!(first_duplicate(["a", "B", "b"], true), Some("b"));
1013        assert_eq!(first_duplicate(["ä", "Ä"], true), None);
1014        assert_eq!(first_duplicate([], true), None);
1015    }
1016
1017    #[test]
1018    fn validate_rejects_a_repeated_property() {
1019        let mut class = ClassBuilder::new("Foo");
1020        class.properties = vec![named_property("a"), named_property("a")];
1021        assert!(matches!(
1022            class.validate(),
1023            Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
1024        ));
1025    }
1026
1027    #[test]
1028    fn validate_rejects_methods_that_differ_only_by_case() {
1029        let class = ClassBuilder::new("Foo")
1030            .method(
1031                FunctionBuilder::new("run", test_function),
1032                MethodFlags::Public,
1033            )
1034            .method(
1035                FunctionBuilder::new("RUN", test_function),
1036                MethodFlags::Static,
1037            );
1038        assert!(matches!(
1039            class.validate(),
1040            Err(Error::DuplicateMethod { method }) if method == "Foo::RUN"
1041        ));
1042    }
1043
1044    #[test]
1045    fn validate_compares_constants_exactly() {
1046        let class = with_constant(with_constant(ClassBuilder::new("Foo"), "A"), "a");
1047        assert!(class.validate().is_ok());
1048        let class = with_constant(class, "A");
1049        assert!(matches!(
1050            class.validate(),
1051            Err(Error::DuplicateConstant { constant }) if constant == "Foo::A"
1052        ));
1053    }
1054
1055    #[test]
1056    #[cfg(feature = "embed")]
1057    fn class_names_already_in_the_class_table_are_taken() {
1058        let ran = crate::embed::Embed::run(|| {
1059            assert!(matches!(
1060                ensure_class_name_free("STDCLASS"),
1061                Err(Error::DuplicateClass { class }) if class == "STDCLASS"
1062            ));
1063            assert!(ensure_class_name_free("ExtPhpRsNoSuchClass").is_ok());
1064            true
1065        });
1066        assert!(ran);
1067    }
1068
1069    #[test]
1070    fn validate_accepts_distinct_members() {
1071        let mut class = ClassBuilder::new("Foo")
1072            .method(
1073                FunctionBuilder::new("run", test_function),
1074                MethodFlags::Public,
1075            )
1076            .method(
1077                FunctionBuilder::new("stop", test_function),
1078                MethodFlags::Public,
1079            );
1080        class.properties = vec![named_property("a"), named_property("b")];
1081        assert!(with_constant(class, "A").validate().is_ok());
1082    }
1083
1084    #[test]
1085    #[cfg(feature = "embed")]
1086    fn test_constant() {
1087        let class = ClassBuilder::new("Foo")
1088            .constant("bar", 42, &["Doc 1"], ConstantFlags::Public)
1089            .expect("Failed to create constant");
1090        assert_eq!(class.constants.len(), 1);
1091        assert_eq!(class.constants[0].0, "bar");
1092        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
1093    }
1094
1095    #[test]
1096    #[cfg(feature = "embed")]
1097    fn test_dyn_constant() {
1098        let class = ClassBuilder::new("Foo")
1099            .dyn_constant("bar", &42, &["Doc 1"], ConstantFlags::Public)
1100            .expect("Failed to create constant");
1101        assert_eq!(class.constants.len(), 1);
1102        assert_eq!(class.constants[0].0, "bar");
1103        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
1104    }
1105
1106    #[test]
1107    fn test_flags() {
1108        let class = ClassBuilder::new("Foo").flags(ClassFlags::Abstract);
1109        assert_eq!(class.ce.ce_flags, ClassFlags::Abstract.bits());
1110    }
1111
1112    #[test]
1113    fn test_registration() {
1114        let class = ClassBuilder::new("Foo").registration(|_, _| {});
1115        assert!(class.register.is_some());
1116    }
1117
1118    #[test]
1119    fn test_registration_interface() {
1120        let class = ClassBuilder::new("Foo")
1121            .flags(ClassFlags::Interface)
1122            .registration(|_, _| {});
1123        assert!(class.register.is_some());
1124    }
1125
1126    #[test]
1127    fn test_docs() {
1128        let class = ClassBuilder::new("Foo").docs(&["Doc 1"]);
1129        assert_eq!(class.docs, &["Doc 1"] as DocComments);
1130    }
1131
1132    // TODO: Test the register function
1133}