Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions crates/macros/src/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ClassEntryAttribute>,
#[darling(multiple)]
implements: Vec<ClassEntryAttribute>,
Expand Down Expand Up @@ -138,6 +141,7 @@ pub fn parser(mut input: ItemStruct) -> Result<TokenStream> {
&fields,
attr.flags.as_ref(),
attr.readonly.is_present(),
attr.no_constructor.is_present(),
&docs,
&gc_trace,
);
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<T: ::std::default::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<
Expand All @@ -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
];
Expand Down
57 changes: 33 additions & 24 deletions crates/macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Foo>` and `ClassRefMut<Foo>` are also parameter
/// types. A variadic parameter must use them, for example `&[ClassRef<Foo>]`.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
///
Expand Down Expand Up @@ -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))]
Expand Down Expand Up @@ -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 `<crate_name>_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.
///
Expand Down Expand Up @@ -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
/// &raquo;](./async_impl.md) for more info.
/// If you want to use async Rust, use `#[php_async_impl]`, instead: see [here &raquo;](./async_impl.md) for more info.
///
/// ## Options
///
Expand All @@ -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
///
Expand All @@ -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.
Expand All @@ -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<Self>`
/// 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:
///
Expand Down Expand Up @@ -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<Self, E>`, where `E: Into<PhpException>`.
/// When the error variant of `Result` is encountered, it is thrown as an
Expand Down
3 changes: 3 additions & 0 deletions guide/src/macros/classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
8 changes: 8 additions & 0 deletions guide/src/macros/impl.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self, E>`, where `E: Into<PhpException>`. When
the error variant of `Result` is encountered, it is thrown as an exception and
Expand Down
56 changes: 49 additions & 7 deletions src/builders/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -114,6 +114,10 @@ pub struct ClassBuilder {
/// Properties declared with their type, see
/// [`ClassBuilder::typed_property`].
pub(crate) typed_properties: Vec<ClassProperty>,
/// 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<FunctionBuilder<'static>>,
pub(crate) constants: Vec<ConstantEntry>,
register: Option<fn(&'static mut ClassEntry, ArgInfoTables)>,
pub(crate) docs: DocComments,
Expand All @@ -138,6 +142,7 @@ impl ClassBuilder {
object_override: None,
properties: vec![],
typed_properties: vec![],
unless_parent_constructs: None,
constants: vec![],
register: None,
docs: &[],
Expand Down Expand Up @@ -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::<T>::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::<T>::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() };
Expand Down Expand Up @@ -372,8 +379,11 @@ impl ClassBuilder {
self.object_override = Some(create_object::<T>);
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()
Expand All @@ -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::<T>));
self
} else {
// Add default constructor for classes
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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};
Expand Down
7 changes: 7 additions & 0 deletions src/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = &[];

Expand Down
6 changes: 6 additions & 0 deletions src/types/class_object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ impl<T: RegisteredClass> ZendClassObject<T> {
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> {
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"
Expand Down
Loading
Loading