Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass class object type to PHP when taking object parameter #64

Merged
merged 3 commits into from
Sep 8, 2021
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
1 change: 1 addition & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,5 @@ const ALLOWED_BINDINGS: &[&str] = &[
"_ZEND_SEND_MODE_SHIFT",
"_ZEND_TYPE_NULLABLE_BIT",
"ts_rsrc_id",
"_ZEND_TYPE_NAME_BIT",
];
1 change: 1 addition & 0 deletions docsrs_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

pub const ZEND_DEBUG: u32 = 1;
pub const ZEND_MM_ALIGNMENT: u32 = 8;
pub const _ZEND_TYPE_NAME_BIT: u32 = 8388608;
pub const _ZEND_TYPE_NULLABLE_BIT: u32 = 2;
pub const HT_MIN_SIZE: u32 = 8;
pub const IS_UNDEF: u32 = 0;
Expand Down
4 changes: 2 additions & 2 deletions example/skel/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ pub fn test_str(input: &str) -> &str {
// ))
// }

#[global_allocator]
static GLOBAL: PhpAllocator = PhpAllocator::new();
// #[global_allocator]
// static GLOBAL: PhpAllocator = PhpAllocator::new();

#[php_class]
#[property(test = 0)]
Expand Down
6 changes: 6 additions & 0 deletions example/skel/test.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
<?php

include 'vendor/autoload.php';

$ext = new ReflectionExtension('skel');

dd($ext);

$x = fn_once();
$x();
$x();
Expand Down
2 changes: 2 additions & 0 deletions ext-php-rs-derive/src/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ pub fn parser(args: AttributeArgs, mut input: ItemStruct) -> Result<TokenStream>
static #meta: ::ext_php_rs::php::types::object::ClassMetadata<#ident> = ::ext_php_rs::php::types::object::ClassMetadata::new();

impl ::ext_php_rs::php::types::object::RegisteredClass for #ident {
const CLASS_NAME: &'static str = #class_name;

fn get_metadata() -> &'static ::ext_php_rs::php::types::object::ClassMetadata<Self> {
&#meta
}
Expand Down
5 changes: 3 additions & 2 deletions src/php/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ impl<'a> Arg<'a> {
self.as_ref,
self.variadic,
self.allow_null,
),
)
.ok_or(Error::InvalidCString)?,
default_value: match &self.default_value {
Some(val) => CString::new(val.as_str())?.into_raw(),
None => ptr::null(),
Expand All @@ -135,7 +136,7 @@ impl From<Arg<'_>> for _zend_expected_type {
DataType::Double => _zend_expected_type_Z_EXPECTED_DOUBLE,
DataType::String => _zend_expected_type_Z_EXPECTED_STRING,
DataType::Array => _zend_expected_type_Z_EXPECTED_ARRAY,
DataType::Object => _zend_expected_type_Z_EXPECTED_OBJECT,
DataType::Object(_) => _zend_expected_type_Z_EXPECTED_OBJECT,
DataType::Resource => _zend_expected_type_Z_EXPECTED_RESOURCE,
_ => unreachable!(),
};
Expand Down
6 changes: 6 additions & 0 deletions src/php/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,11 @@ impl ClassBuilder {
///
/// * `T` - The type which will override the Zend object. Must implement [`RegisteredClass`]
/// which can be derived using the [`php_class`](crate::php_class) attribute macro.
///
/// # Panics
///
/// Panics if the class name associated with `T` is not the same as the class name specified
/// when creating the builder.
pub fn object_override<T: RegisteredClass>(mut self) -> Self {
unsafe extern "C" fn create_object<T: RegisteredClass>(
_: *mut ClassEntry,
Expand All @@ -272,6 +277,7 @@ impl ClassBuilder {
(*ptr).get_mut_zend_obj()
}

assert_eq!(self.name.as_str(), T::CLASS_NAME);
self.object_override = Some(create_object::<T>);
self
}
Expand Down
88 changes: 59 additions & 29 deletions src/php/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,54 @@ use crate::{
};

/// Valid data types for PHP.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DataType {
Undef = IS_UNDEF,

Null = IS_NULL,
False = IS_FALSE,
True = IS_TRUE,
Long = IS_LONG,
Double = IS_DOUBLE,
String = IS_STRING,
Array = IS_ARRAY,
Object = IS_OBJECT,
Resource = IS_RESOURCE,
Reference = IS_REFERENCE,
Callable = IS_CALLABLE,

ConstantExpression = IS_CONSTANT_AST,
Void = IS_VOID,
Mixed = IS_MIXED,

/// Only used when creating arguments.
Bool = _IS_BOOL,
Undef,
Null,
False,
True,
Long,
Double,
String,
Array,
Object(Option<&'static str>),
Resource,
Reference,
Callable,
ConstantExpression,
Void,
Mixed,
Bool,
}

impl Default for DataType {
fn default() -> Self {
Self::Void
}
}

impl DataType {
/// Returns the integer representation of the data type.
pub const fn as_u32(&self) -> u32 {
match self {
DataType::Undef => IS_UNDEF,
DataType::Null => IS_NULL,
DataType::False => IS_FALSE,
DataType::True => IS_TRUE,
DataType::Long => IS_LONG,
DataType::Double => IS_DOUBLE,
DataType::String => IS_STRING,
DataType::Array => IS_ARRAY,
DataType::Object(_) => IS_OBJECT,
DataType::Resource => IS_RESOURCE,
DataType::Reference => IS_RESOURCE,
DataType::Callable => IS_CALLABLE,
DataType::ConstantExpression => IS_CONSTANT_AST,
DataType::Void => IS_VOID,
DataType::Mixed => IS_MIXED,
DataType::Bool => _IS_BOOL,
}
}
}

// TODO: Ideally want something like this
Expand Down Expand Up @@ -69,12 +94,15 @@ impl TryFrom<ZvalTypeFlags> for DataType {
contains!(Double);
contains!(String);
contains!(Array);
contains!(Object);
contains!(Resource);
contains!(Callable);
contains!(ConstantExpression);
contains!(Void);

if value.contains(ZvalTypeFlags::Object) {
return Ok(DataType::Object(None));
}

Err(Error::UnknownDatatype(0))
}
}
Expand All @@ -95,18 +123,20 @@ impl TryFrom<u32> for DataType {
contains!(IS_VOID, Void);
contains!(IS_CALLABLE, Callable);
contains!(IS_CONSTANT_AST, ConstantExpression);
contains!(IS_CONSTANT_AST, ConstantExpression);
contains!(IS_CONSTANT_AST, ConstantExpression);
contains!(IS_REFERENCE, Reference);
contains!(IS_RESOURCE, Resource);
contains!(IS_OBJECT, Object);
contains!(IS_ARRAY, Array);
contains!(IS_STRING, String);
contains!(IS_DOUBLE, Double);
contains!(IS_LONG, Long);
contains!(IS_TRUE, True);
contains!(IS_FALSE, False);
contains!(IS_NULL, Null);

if (value & IS_OBJECT) == IS_OBJECT {
return Ok(DataType::Object(None));
}

contains!(IS_UNDEF, Undef);

Err(Error::UnknownDatatype(value))
Expand All @@ -124,7 +154,7 @@ impl Display for DataType {
DataType::Double => write!(f, "Double"),
DataType::String => write!(f, "String"),
DataType::Array => write!(f, "Array"),
DataType::Object => write!(f, "Object"),
DataType::Object(obj) => write!(f, "{}", obj.as_deref().unwrap_or("Object")),
DataType::Resource => write!(f, "Resource"),
DataType::Reference => write!(f, "Reference"),
DataType::Callable => write!(f, "Callable"),
Expand Down Expand Up @@ -163,7 +193,7 @@ mod tests {
test!(IS_DOUBLE, Double);
test!(IS_STRING, String);
test!(IS_ARRAY, Array);
test!(IS_OBJECT, Object);
assert_eq!(DataType::try_from(IS_OBJECT), Ok(DataType::Object(None)));
test!(IS_RESOURCE, Resource);
test!(IS_REFERENCE, Reference);
test!(IS_CONSTANT_AST, ConstantExpression);
Expand All @@ -173,7 +203,7 @@ mod tests {
test!(IS_INTERNED_STRING_EX, String);
test!(IS_STRING_EX, String);
test!(IS_ARRAY_EX, Array);
test!(IS_OBJECT_EX, Object);
assert_eq!(DataType::try_from(IS_OBJECT_EX), Ok(DataType::Object(None)));
test!(IS_RESOURCE_EX, Resource);
test!(IS_REFERENCE_EX, Reference);
test!(IS_CONSTANT_AST_EX, ConstantExpression);
Expand Down
3 changes: 2 additions & 1 deletion src/php/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

use std::{ffi::CString, mem, os::raw::c_char, ptr};

use crate::bindings::zend_function_entry;
use crate::errors::Result;
use crate::{bindings::zend_function_entry, errors::Error};

use super::{
args::{Arg, ArgInfo},
Expand Down Expand Up @@ -132,6 +132,7 @@ impl<'a> FunctionBuilder<'a> {
type_: match self.retval {
Some(retval) => {
ZendType::empty_from_type(retval, self.ret_as_ref, false, self.ret_as_null)
.ok_or(Error::InvalidCString)?
}
None => ZendType::empty(false, false),
},
Expand Down
2 changes: 2 additions & 0 deletions src/php/types/closure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ impl Default for Closure {
}

impl RegisteredClass for Closure {
const CLASS_NAME: &'static str = "RustClosure";

fn get_metadata() -> &'static super::object::ClassMetadata<Self> {
&CLOSURE_META
}
Expand Down
81 changes: 78 additions & 3 deletions src/php/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@ pub mod object;
pub mod string;
pub mod zval;

use std::{ffi::c_void, ptr};
use std::{
ffi::{c_void, CString},
ptr,
};

use crate::bindings::{
zend_type, IS_MIXED, MAY_BE_ANY, MAY_BE_BOOL, _IS_BOOL, _ZEND_IS_VARIADIC_BIT,
_ZEND_SEND_MODE_SHIFT, _ZEND_TYPE_NULLABLE_BIT,
_ZEND_SEND_MODE_SHIFT, _ZEND_TYPE_NAME_BIT, _ZEND_TYPE_NULLABLE_BIT,
};

use super::enums::DataType;
Expand All @@ -38,12 +41,84 @@ impl ZendType {
}
}

/// Attempts to create a zend type for a given datatype. Returns an option containing the type.
///
/// Returns [`None`] if the data type was a class object where the class name could not be converted
/// into a C string (i.e. contained NUL-bytes).
///
/// # Parameters
///
/// * `type_` - Data type to create zend type for.
/// * `pass_by_ref` - Whether the type should be passed by reference.
/// * `is_variadic` - Whether the type is for a variadic argument.
/// * `allow_null` - Whether the type should allow null to be passed in place.
pub fn empty_from_type(
type_: DataType,
pass_by_ref: bool,
is_variadic: bool,
allow_null: bool,
) -> Option<Self> {
match type_ {
DataType::Object(Some(class)) => {
Self::empty_from_class_type(class, pass_by_ref, is_variadic, allow_null)
}
type_ => Some(Self::empty_from_primitive_type(
type_,
pass_by_ref,
is_variadic,
allow_null,
)),
}
}

/// Attempts to create a zend type for a class object type. Returns an option containing the type if successful.
///
/// Returns [`None`] if the data type was a class object where the class name could not be converted
/// into a C string (i.e. contained NUL-bytes).
///
/// # Parameters
///
/// * `class_name` - Name of the class parameter.
/// * `pass_by_ref` - Whether the type should be passed by reference.
/// * `is_variadic` - Whether the type is for a variadic argument.
/// * `allow_null` - Whether the type should allow null to be passed in place.
fn empty_from_class_type(
class_name: &str,
pass_by_ref: bool,
is_variadic: bool,
allow_null: bool,
) -> Option<Self> {
Some(Self {
ptr: CString::new(class_name).ok()?.into_raw() as *mut c_void,
type_mask: _ZEND_TYPE_NAME_BIT
| (if allow_null {
_ZEND_TYPE_NULLABLE_BIT
} else {
0
})
| Self::arg_info_flags(pass_by_ref, is_variadic),
})
}

/// Attempts to create a zend type for a primitive PHP type.
///
/// # Parameters
///
/// * `type_` - Data type to create zend type for.
/// * `pass_by_ref` - Whether the type should be passed by reference.
/// * `is_variadic` - Whether the type is for a variadic argument.
/// * `allow_null` - Whether the type should allow null to be passed in place.
///
/// # Panics
///
/// Panics if the given `type_` is for a class object type.
fn empty_from_primitive_type(
type_: DataType,
pass_by_ref: bool,
is_variadic: bool,
allow_null: bool,
) -> Self {
assert!(!matches!(type_, DataType::Object(Some(_))));
Self {
ptr: ptr::null::<c_void>() as *mut c_void,
type_mask: Self::type_init_code(type_, pass_by_ref, is_variadic, allow_null),
Expand Down Expand Up @@ -81,7 +156,7 @@ impl ZendType {
is_variadic: bool,
allow_null: bool,
) -> u32 {
let type_ = type_ as u32;
let type_ = type_.as_u32();

(if type_ == _IS_BOOL {
MAY_BE_BOOL
Expand Down
Loading