diff --git a/crates/macros/src/class.rs b/crates/macros/src/class.rs index 31abfa4b5..a9e03f13d 100644 --- a/crates/macros/src/class.rs +++ b/crates/macros/src/class.rs @@ -24,6 +24,9 @@ pub struct StructAttributes { /// Readonly classes have all properties implicitly readonly. #[darling(rename = "readonly")] readonly: Flag, + /// Whether the class declares no constructor when it has none of its own + /// (`#[php(no_constructor)]`); the struct must implement `Default`. + no_constructor: Flag, extends: Option, #[darling(multiple)] implements: Vec, @@ -138,6 +141,7 @@ pub fn parser(mut input: ItemStruct) -> Result { &fields, attr.flags.as_ref(), attr.readonly.is_present(), + attr.no_constructor.is_present(), &docs, &gc_trace, ); @@ -228,6 +232,7 @@ fn generate_registered_class_impl( fields: &[Property], flags: Option<&syn::Expr>, readonly: bool, + no_constructor: bool, docs: &[String], gc_trace: &TokenStream, ) -> TokenStream { @@ -387,11 +392,29 @@ fn generate_registered_class_impl( quote! { None } }; + // `#[php(no_constructor)]` needs `Default`: objects are initialized from + // it. + let (no_constructor_const, no_constructor_check) = if no_constructor { + ( + quote! { const NO_CONSTRUCTOR: bool = true; }, + quote! { + const _: fn() = || { + fn requires_default() {} + requires_default::<#ident>(); + }; + }, + ) + } else { + (quote! {}, quote! {}) + }; + let implements = implements.iter().map(|imp| { quote! { #imp } }); quote! { + #no_constructor_check + impl ::ext_php_rs::class::RegisteredClass for #ident { const CLASS_NAME: &'static str = #class_name; const BUILDER_MODIFIER: ::std::option::Option< @@ -404,6 +427,7 @@ fn generate_registered_class_impl( #(#implements,)* ]; const FLAGS: ::ext_php_rs::flags::ClassFlags = #flags; + #no_constructor_const const DOC_COMMENTS: &'static [&'static str] = &[ #docs ]; diff --git a/crates/macros/src/lib.rs b/crates/macros/src/lib.rs index 0a99a71eb..f8647c8cb 100644 --- a/crates/macros/src/lib.rs +++ b/crates/macros/src/lib.rs @@ -44,6 +44,10 @@ extern crate proc_macro; /// readonly class are implicitly readonly. /// - `flags` - Sets class flags using `ClassFlags`, e.g. `#[php(flags = /// ClassFlags::Final)]` for a final class. +/// - `no_constructor` - A class without a constructor declares none, rather +/// than one that throws: `new` creates an object initialized with +/// `Default::default()`. The struct must implement `Default`. See +/// [Constructors](./impl.md#constructors). /// - `#[php(extends(...))]` - Sets the parent class of the class. Can only be /// used once. Two forms are supported: /// - Simple type form: `#[php(extends(MyBaseClass))]` - For Rust-defined @@ -182,10 +186,9 @@ extern crate proc_macro; /// - `Option<&Foo>` and `Option<&mut Foo>` also accept `null`. /// /// The borrow starts before the function body and stops when the function -/// returns. The rules of [Access to the Rust Value](#access-to-the-rust-value) -/// apply during the call. If two parameters, or the object of the method and a -/// parameter, get the same object and the borrows conflict, PHP throws an -/// `Error`. +/// returns. The rules of [Access to the Rust Value](#access-to-the-rust-value) apply during +/// the call. If two parameters, or the object of the method and a parameter, +/// get the same object and the borrows conflict, PHP throws an `Error`. /// /// The borrow guards `ClassRef` and `ClassRefMut` are also parameter /// types. A variadic parameter must use them, for example `&[ClassRef]`. @@ -1329,8 +1332,8 @@ fn php_enum_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 { /// - `#[php(change_constant_case = "snake_case")]` - Renames the constant to /// snake case. /// -/// See the [`name` and `change_case`](./php.md#name-and-change_case) section -/// for a list of all available cases. +/// See the [`name` and `change_case`](./php.md#name-and-change_case) section for a list of all +/// available cases. /// /// The macro itself takes no arguments: `#[php_interface(name = "Foo")]` is a /// compile error. Put the options in `#[php(...)]` on the trait. @@ -1581,8 +1584,8 @@ fn php_enum_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 { /// - Use `#[php(implements(ce = ...))]` on `#[php_class]` for built-in PHP /// interfaces like `Iterator`, `ArrayAccess`, `Countable`, etc. /// -/// See the [Classes documentation](./classes.md#implementing-an-interface) for -/// examples of implementing built-in interfaces. +/// See the [Classes documentation](./classes.md#implementing-an-interface) for examples +/// of implementing built-in interfaces. /// /// ## Cross-Crate Support /// @@ -1918,10 +1921,9 @@ fn php_interface_internal(args: TokenStream2, input: TokenStream2) -> TokenStrea /// values, `&[i64]` receives converted integers. If one of the values cannot be /// converted into `T`, the call throws a `TypeError`. If one of the values is a /// class object whose Rust value is borrowed or not initialized, the call -/// throws an `Error`, see [Class Arguments](./classes.md#class-arguments). A -/// variadic parameter that is not the last parameter is a compile error. The -/// slice must be spelled in the signature; a type alias that hides the slice is -/// not detected. +/// throws an `Error`, see [Class Arguments](./classes.md#class-arguments). A variadic parameter that is +/// not the last parameter is a compile error. The slice must be spelled in the +/// signature; a type alias that hides the slice is not detected. /// /// ```rust,no_run,ignore /// # #![cfg_attr(windows, feature(abi_vectorcall))] @@ -2098,10 +2100,9 @@ fn php_const_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 { /// /// The function is renamed to `get_module` if you have used another name. The /// macro also exports a crate-prefixed `_get_module` alias, used -/// when [statically linking the extension into -/// php-src](../advanced/static_linking.md). Building with -/// `EXT_PHP_RS_STATIC_EXT=1` removes the unmangled `get_module` export (the -/// function itself stays callable from Rust) so a statically linked +/// when [statically linking the extension into php-src](../advanced/static_linking.md). +/// Building with `EXT_PHP_RS_STATIC_EXT=1` removes the unmangled `get_module` +/// export (the function itself stays callable from Rust) so a statically linked /// extension cannot collide with another extension exporting `get_module`. /// Dynamic builds (`extension=` / `dl()`) must not set the variable. /// @@ -2214,8 +2215,7 @@ fn php_module_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 /// If you do not want a function exported to PHP, you should place it in a /// separate `impl` block. /// -/// If you want to use async Rust, use `#[php_async_impl]`, instead: see [here -/// »](./async_impl.md) for more info. +/// If you want to use async Rust, use `#[php_async_impl]`, instead: see [here »](./async_impl.md) for more info. /// /// ## Options /// @@ -2229,8 +2229,8 @@ fn php_module_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 /// - `#[php(change_constant_case = "snake_case")]` - Renames the constant to /// snake case. /// -/// See the [`name` and `change_case`](./php.md#name-and-change_case) section -/// for a list of all available cases. +/// See the [`name` and `change_case`](./php.md#name-and-change_case) section for a list of all +/// available cases. /// /// ## Methods /// @@ -2239,8 +2239,8 @@ fn php_module_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 /// methods is they are bounded by their class object. /// /// Instance methods, static methods and constructors benefit from the same -/// zero-allocation fast path as standalone functions. See the -/// [Performance](./function.md#performance) section for details. +/// zero-allocation fast path as standalone functions. See the [Performance](./function.md#performance) +/// section for details. /// /// Class methods can take a `&self` or `&mut self` parameter. They cannot take /// a consuming `self` parameter. Static methods can omit this `self` parameter. @@ -2249,8 +2249,8 @@ fn php_module_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 /// the self parameter. The parameter must have the name `self_`. Borrow the /// Rust value with `self_.try_borrow()` or `self_.try_borrow_mut()`. You can /// also return `self_` to return `$this`. A `&mut ZendClassObject` -/// parameter does not compile. Refer to [Access to the Rust -/// Value](./classes.md#access-to-the-rust-value) for the borrow rules. +/// parameter does not compile. Refer to [Access to the Rust Value](./classes.md#access-to-the-rust-value) +/// for the borrow rules. /// /// The rest of the options are passed as separate attributes: /// @@ -2383,6 +2383,15 @@ fn php_module_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 /// By default, if a class does not have a constructor, it is not constructable /// from PHP. It can only be returned from a Rust function to PHP. /// +/// With `#[php(no_constructor)]` on a struct that implements `Default`, the +/// class declares no constructor instead, as a PHP class without one: `new`, on +/// the class or on a PHP subclass, creates an object initialized with +/// `Default::default()`, and `ReflectionClass::getConstructor()` returns +/// `null`. An exception class extending `\Exception` inherits +/// `Exception::__construct`. Under a Rust class that declares a constructor, +/// the class keeps the one that throws, since the parent's would run on an +/// object of another type. +/// /// Constructors are Rust methods which can take any amount of parameters and /// returns either `Self` or `Result`, where `E: Into`. /// When the error variant of `Result` is encountered, it is thrown as an diff --git a/guide/src/macros/classes.md b/guide/src/macros/classes.md index 1e30b52f8..9e2257162 100644 --- a/guide/src/macros/classes.md +++ b/guide/src/macros/classes.md @@ -17,6 +17,9 @@ placed underneath the `#[php_class]` attribute. readonly class are implicitly readonly. - `flags` - Sets class flags using `ClassFlags`, e.g. `#[php(flags = ClassFlags::Final)]` for a final class. +- `no_constructor` - A class without a constructor declares none, rather than one + that throws: `new` creates an object initialized with `Default::default()`. The + struct must implement `Default`. See [Constructors](./impl.md#constructors). - `#[php(extends(...))]` - Sets the parent class of the class. Can only be used once. Two forms are supported: - Simple type form: `#[php(extends(MyBaseClass))]` - For Rust-defined classes that implement `RegisteredClass`. diff --git a/guide/src/macros/impl.md b/guide/src/macros/impl.md index efbb4d5ac..5db66204c 100644 --- a/guide/src/macros/impl.md +++ b/guide/src/macros/impl.md @@ -172,6 +172,14 @@ pattern in PHP. By default, if a class does not have a constructor, it is not constructable from PHP. It can only be returned from a Rust function to PHP. +With `#[php(no_constructor)]` on a struct that implements `Default`, the class +declares no constructor instead, as a PHP class without one: `new`, on the class +or on a PHP subclass, creates an object initialized with `Default::default()`, +and `ReflectionClass::getConstructor()` returns `null`. An exception class +extending `\Exception` inherits `Exception::__construct`. Under a Rust class that +declares a constructor, the class keeps the one that throws, since the parent's +would run on an object of another type. + Constructors are Rust methods which can take any amount of parameters and returns either `Self` or `Result`, where `E: Into`. When the error variant of `Result` is encountered, it is thrown as an exception and diff --git a/src/builders/class.rs b/src/builders/class.rs index c82117dad..3f3664912 100644 --- a/src/builders/class.rs +++ b/src/builders/class.rs @@ -15,9 +15,9 @@ use crate::{ exception::PhpException, ffi::{ _ZEND_TYPE_NAME_BIT, _ZEND_TYPE_NULLABLE_BIT, IS_DOUBLE, IS_LONG, IS_UNDEF, MAY_BE_ANY, - zend_declare_class_constant_ex, zend_declare_property, zend_declare_typed_property, - zend_do_implement_interface, zend_hash_str_find_ptr_lc, zend_register_internal_class_ex, - zend_register_internal_interface, + ZEND_INTERNAL_FUNCTION, zend_declare_class_constant_ex, zend_declare_property, + zend_declare_typed_property, zend_do_implement_interface, zend_hash_str_find_ptr_lc, + zend_register_internal_class_ex, zend_register_internal_interface, }, flags::{ClassFlags, ConstantFlags, DataType, MethodFlags, PropertyFlags}, types::{ZendClassObject, ZendObject, ZendStr, Zval}, @@ -114,6 +114,10 @@ pub struct ClassBuilder { /// Properties declared with their type, see /// [`ClassBuilder::typed_property`]. pub(crate) typed_properties: Vec, + /// The throwing constructor of a `#[php(no_constructor)]` class, added by + /// [`ClassBuilder::register`] when the parent is a Rust class declaring a + /// constructor: inherited, it would run on an object of another type. + unless_parent_constructs: Option>, pub(crate) constants: Vec, register: Option, pub(crate) docs: DocComments, @@ -138,6 +142,7 @@ impl ClassBuilder { object_override: None, properties: vec![], typed_properties: vec![], + unless_parent_constructs: None, constants: vec![], register: None, docs: &[], @@ -320,7 +325,9 @@ impl ClassBuilder { // Without default initialization, accessing properties on uninitialized // objects would panic. if let Some(instance) = T::default_init() { - let obj = ZendClassObject::::new(instance).into_raw(); + // `ce` is `T`'s class or a PHP subclass of it: the object is one + // of the class `new` names. + let obj = ZendClassObject::::new_in(instance, unsafe { ce.as_ref() }).into_raw(); // SAFETY: `into_raw` yields a valid, exclusively owned object that // the engine takes over. return unsafe { (*obj).get_mut_zend_obj() }; @@ -372,8 +379,11 @@ impl ClassBuilder { self.object_override = Some(create_object::); let is_interface = T::FLAGS.contains(ClassFlags::Interface); - // For interfaces: only add __construct if explicitly declared - // For classes: always add __construct (PHP needs it for object creation) + // For interfaces: only add __construct if explicitly declared. + // For classes: a declared constructor; else, with `NO_CONSTRUCTOR`, none + // (objects are created initialized from `Default`, see `create_object`), + // unless a Rust parent declares one (see `register`); else one that + // throws, since the object could not be initialized. if let Some(ConstructorMeta { build_fn, flags, .. }) = T::constructor() @@ -386,7 +396,10 @@ impl ClassBuilder { let visibility = flags.unwrap_or(MethodFlags::Public); self.method(build_fn(func), visibility) } else if is_interface { - // Don't add default constructor for interfaces + self + } else if T::NO_CONSTRUCTOR { + self.unless_parent_constructs = + Some(FunctionBuilder::new("__construct", constructor::)); self } else { // Add default constructor for classes @@ -471,6 +484,20 @@ impl ClassBuilder { Ok(()) } + /// A `#[php(no_constructor)]` class under a Rust class that declares a + /// constructor would inherit it, and the parent's constructor would run on + /// an object of another Rust type: the class keeps the one that throws. + fn keep_throwing_constructor(&mut self) { + if let Some(constructor) = self.unless_parent_constructs.take() + && self + .extends + .as_ref() + .is_some_and(|(parent, _)| constructs_in_this_module(parent())) + { + self.methods.push((constructor, MethodFlags::Public)); + } + } + /// Builds and registers the class. /// /// # Errors @@ -501,6 +528,8 @@ impl ClassBuilder { self.ce.name = ZendStr::new_interned(&self.name, true).into_raw(); + self.keep_throwing_constructor(); + let mut arg_info = Vec::with_capacity(self.methods.len()); let mut methods = Vec::with_capacity(self.methods.len() + 1); let mut sensitive = SensitiveParameters::new(); @@ -727,6 +756,19 @@ fn declare_typed_property( Ok(()) } +/// Whether `class` declares a constructor registered by the module being +/// started: a Rust class of this extension, whose constructor initializes an +/// object of its own Rust type. +fn constructs_in_this_module(class: &ClassEntry) -> bool { + // SAFETY: a registered class's constructor is a live function of the + // engine's function table, and `type_` tells which member of the union + // holds it. + unsafe { class.constructor.as_ref() }.is_some_and(|constructor| unsafe { + u32::from(constructor.type_) == ZEND_INTERNAL_FUNCTION + && constructor.internal_function.module == ExecutorGlobals::get().current_module + }) +} + #[cfg(test)] mod tests { use crate::ffi::{IS_ARRAY, IS_FALSE, IS_NULL, IS_OBJECT, IS_STRING, IS_TRUE, MAY_BE_BOOL}; diff --git a/src/class.rs b/src/class.rs index 04f39e4ba..fb4abee35 100644 --- a/src/class.rs +++ b/src/class.rs @@ -45,6 +45,13 @@ pub trait RegisteredClass: Sized + 'static { /// PHP flags applied to the class. const FLAGS: ClassFlags = ClassFlags::empty(); + /// Whether the class declares no constructor when it has none of its own, + /// set by `#[php(no_constructor)]`: `new` then creates an object + /// initialized with `Default::default()`, as for a PHP class without a + /// constructor. Otherwise a class without a constructor gets one that + /// throws. + const NO_CONSTRUCTOR: bool = false; + /// Doc comments for the class. const DOC_COMMENTS: DocComments = &[]; diff --git a/src/types/class_object.rs b/src/types/class_object.rs index 20a1bf5b8..43fed6fc3 100644 --- a/src/types/class_object.rs +++ b/src/types/class_object.rs @@ -69,6 +69,12 @@ impl ZendClassObject { Self::internal_new(None, ce) } + /// Creates a new [`ZendClassObject`] of type `T` holding `val`, as an + /// object of `ce`: `T`'s own class, or a PHP subclass of it. + pub(crate) fn new_in(val: T, ce: Option<&'static ClassEntry>) -> ZBox { + Self::internal_new(Some(val), ce) + } + #[expect( clippy::expect_used, reason = "the Zend allocator aborts the process on OOM, so the pointer is never null" diff --git a/tests/src/integration/class/mod.rs b/tests/src/integration/class/mod.rs index bc211d405..341ea115a 100644 --- a/tests/src/integration/class/mod.rs +++ b/tests/src/integration/class/mod.rs @@ -938,6 +938,77 @@ fn typed_properties( )) } +/// A `#[php(no_constructor)]` class: like a PHP class without a constructor, +/// it declares none, and `new` (of it or of a PHP subclass) creates an object +/// initialized from `Default`. +#[php_class] +#[php(no_constructor)] +#[derive(Default, Clone)] +pub struct TestNoConstructor { + count: i64, +} + +#[php_impl] +impl TestNoConstructor { + pub fn increment(&mut self) -> i64 { + self.count += 1; + self.count + } +} + +/// An abstract `#[php(no_constructor)]` class: PHP subclasses need no +/// constructor of their own. +#[php_class] +#[php(flags = ext_php_rs::flags::ClassFlags::Abstract)] +#[php(no_constructor)] +#[derive(Default)] +pub struct TestNoConstructorAbstract; + +#[php_impl] +impl TestNoConstructorAbstract { + #[php(abstract)] + pub fn name(&self) -> String { + unimplemented!() + } + + pub fn greet(&self) -> &'static str { + "hello from the abstract class" + } +} + +/// A class with no constructor and a default value, without the opt-in: it +/// keeps the constructor that throws. +#[php_class] +#[derive(Default)] +pub struct TestNoConstructorNotOptedIn; + +static CONSTRUCTING_BASE_RUNS: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0); + +/// A Rust class with a constructor, counting its runs. +#[php_class] +pub struct TestConstructingBase; + +#[php_impl] +impl TestConstructingBase { + pub fn __construct() -> Self { + CONSTRUCTING_BASE_RUNS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Self + } + + pub fn runs() -> i64 { + CONSTRUCTING_BASE_RUNS.load(std::sync::atomic::Ordering::SeqCst) + } +} + +/// A `#[php(no_constructor)]` class under a Rust class with a constructor: +/// inheriting it would run the parent's constructor on an object of another +/// Rust type, so it keeps the constructor that throws. +#[php_class] +#[php(extends(TestConstructingBase))] +#[php(no_constructor)] +#[derive(Default)] +pub struct TestNoConstructorChild; + pub fn build_module(builder: ModuleBuilder) -> ModuleBuilder { let builder = builder .class::() @@ -969,6 +1040,11 @@ pub fn build_module(builder: ModuleBuilder) -> ModuleBuilder { .class::() .class::() .class::() + .class::() + .class::() + .class::() + .class::() + .class::() .function(wrap_function!(test_class)) .function(wrap_function!(throw_exception)) .function(wrap_function!(throw_class_object_exception_with_prop)) @@ -1010,6 +1086,13 @@ mod tests { )); } + #[test] + fn class_without_constructor() { + assert!(crate::integration::test::run_php( + "class/no_constructor.php" + )); + } + #[test] fn class_works() { assert!(crate::integration::test::run_php("class/class.php")); diff --git a/tests/src/integration/class/no_constructor.php b/tests/src/integration/class/no_constructor.php new file mode 100644 index 000000000..5cadc3f23 --- /dev/null +++ b/tests/src/integration/class/no_constructor.php @@ -0,0 +1,91 @@ +getConstructor() === null, 'no constructor is declared'); +assert($reflection->isInstantiable()); + +$object = new TestNoConstructor(); +assert($object->increment() === 1); +assert($object->increment() === 2); + +// A PHP subclass is an object of the subclass, initialized from `Default`, +// with no constructor of its own either. +class NoConstructorChild extends TestNoConstructor +{ + public string $extra = 'child'; +} + +$child = new NoConstructorChild(); +assert($child::class === NoConstructorChild::class, $child::class); +assert($child instanceof TestNoConstructor); +assert($child->extra === 'child'); +assert($child->increment() === 1); +assert(( new ReflectionClass($child) )->getConstructor() === null); + +// A subclass constructor cannot call a parent constructor that does not exist, +// exactly as with a PHP parent class without one. +class NoConstructorChildCallingParent extends TestNoConstructor +{ + public function __construct() + { + parent::__construct(); + } +} + +try { + new NoConstructorChildCallingParent(); + assert(false, 'parent::__construct() must fail'); +} catch (Error $e) { + assert(str_contains($e->getMessage(), 'Cannot call constructor'), $e->getMessage()); +} + +// Clones keep the subclass. +$copy = clone $child; +assert($copy::class === NoConstructorChild::class); + +// An abstract class: a PHP subclass implementing the abstract methods needs no +// constructor. +class ConcreteNoConstructor extends TestNoConstructorAbstract +{ + public function name(): string + { + return 'concrete'; + } +} + +$concrete = new ConcreteNoConstructor(); +assert($concrete->name() === 'concrete'); +assert($concrete->greet() === 'hello from the abstract class'); +assert(( new ReflectionClass(TestNoConstructorAbstract::class) )->getConstructor() === null); + +try { + new TestNoConstructorAbstract(); + assert(false, 'an abstract class cannot be instantiated'); +} catch (Error $e) { + assert(str_contains($e->getMessage(), 'Cannot instantiate abstract class'), $e->getMessage()); +} + +// Without `#[php(no_constructor)]`, a class with a default value keeps the +// constructor that throws. +assert(( new ReflectionClass(TestNoConstructorNotOptedIn::class) )->getConstructor() !== null); +try { + new TestNoConstructorNotOptedIn(); + assert(false, 'a class that did not opt in cannot be instantiated'); +} catch (Exception $e) { + assert($e->getMessage() === 'You cannot instantiate this class from PHP.', $e->getMessage()); +} + +// Under a Rust class with a constructor, the class keeps the constructor that +// throws: inheriting the parent's would run it on an object of another type. +$runs = TestConstructingBase::runs(); +new TestConstructingBase(); +assert(TestConstructingBase::runs() === ( $runs + 1 )); +try { + new TestNoConstructorChild(); + assert(false, 'the Rust parent constructor must not be inherited'); +} catch (Exception $e) { + assert($e->getMessage() === 'You cannot instantiate this class from PHP.', $e->getMessage()); +} +assert(TestConstructingBase::runs() === ( $runs + 1 ), 'the parent constructor did not run');