diff --git a/Zend/Optimizer/zend_inference.c b/Zend/Optimizer/zend_inference.c index 37bdaf383e8b..63fee535e052 100644 --- a/Zend/Optimizer/zend_inference.c +++ b/Zend/Optimizer/zend_inference.c @@ -2275,8 +2275,21 @@ static uint32_t binary_op_result_type( /* Handle potentially overloaded operators. * This could be made more precise by checking the class type, if known. */ if ((t1_type & MAY_BE_OBJECT) || (t2_type & MAY_BE_OBJECT)) { - /* This is somewhat GMP specific. */ - tmp |= MAY_BE_OBJECT | MAY_BE_FALSE | MAY_BE_RC1; + switch (opcode) { + case ZEND_ADD: + case ZEND_SUB: + case ZEND_MUL: + case ZEND_DIV: + case ZEND_MOD: + case ZEND_POW: + /* Operable methods may return any non-void/never type. */ + tmp |= MAY_BE_ANY | MAY_BE_ARRAY_KEY_ANY | MAY_BE_ARRAY_OF_ANY | MAY_BE_ARRAY_OF_REF | MAY_BE_RC1 | MAY_BE_RCN; + break; + default: + /* This is somewhat GMP specific. */ + tmp |= MAY_BE_OBJECT | MAY_BE_FALSE | MAY_BE_RC1; + break; + } } } diff --git a/Zend/tests/operable/anon_class_alias.phpt b/Zend/tests/operable/anon_class_alias.phpt new file mode 100644 index 000000000000..9e4c2027d9fd --- /dev/null +++ b/Zend/tests/operable/anon_class_alias.phpt @@ -0,0 +1,34 @@ +--TEST-- +Anonymous Operable class with explicit final operator method works and can be safely aliased +--FILE-- +v + $x); + } +}; + +var_dump(($a + 5)->v); + +class_alias(get_class($a), 'AliasedAnon'); +eval('readonly class SubAnon extends AliasedAnon {}'); + +$sub = new SubAnon(20); +var_dump(($sub + 7)->v); + +$rmAnon = new ReflectionMethod($a, '__add'); +$rmSub = new ReflectionMethod(SubAnon::class, '__add'); +var_dump($rmAnon->isOperatorMethod(), $rmAnon->isFinal()); +var_dump($rmSub->isOperatorMethod(), $rmSub->isFinal()); + +?> +--EXPECT-- +int(15) +int(27) +bool(true) +bool(true) +bool(true) +bool(true) diff --git a/Zend/tests/operable/error_abstract_non_readonly.phpt b/Zend/tests/operable/error_abstract_non_readonly.phpt new file mode 100644 index 000000000000..05d12430021c --- /dev/null +++ b/Zend/tests/operable/error_abstract_non_readonly.phpt @@ -0,0 +1,12 @@ +--TEST-- +Non-readonly abstract class cannot implement Operable +--FILE-- + +--EXPECTF-- +Fatal error: Class BadAbstract implements Operable and must be declared readonly in %s on line %d diff --git a/Zend/tests/operable/error_anon_non_final.phpt b/Zend/tests/operable/error_anon_non_final.phpt new file mode 100644 index 000000000000..a749c545be9d --- /dev/null +++ b/Zend/tests/operable/error_anon_non_final.phpt @@ -0,0 +1,22 @@ +--TEST-- +Anonymous Operable class must declare concrete operator methods final (blocks class_alias override) +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Operable@anonymous::__add() on non-final class must be declared final in %s on line 3 diff --git a/Zend/tests/operable/error_backed_enum.phpt b/Zend/tests/operable/error_backed_enum.phpt new file mode 100644 index 000000000000..5bb1bc2a2570 --- /dev/null +++ b/Zend/tests/operable/error_backed_enum.phpt @@ -0,0 +1,12 @@ +--TEST-- +Backed enum cannot implement Operable +--FILE-- + +--EXPECTF-- +Fatal error: Enum BadBackedEnum cannot implement Operable in %s on line %d diff --git a/Zend/tests/operable/error_default_param.phpt b/Zend/tests/operable/error_default_param.phpt new file mode 100644 index 000000000000..3931ec834b88 --- /dev/null +++ b/Zend/tests/operable/error_default_param.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method parameters cannot have default values +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__mod() parameters cannot have default values in %s on line %d diff --git a/Zend/tests/operable/error_early_bind_subclass.phpt b/Zend/tests/operable/error_early_bind_subclass.phpt new file mode 100644 index 000000000000..3556da32008b --- /dev/null +++ b/Zend/tests/operable/error_early_bind_subclass.phpt @@ -0,0 +1,22 @@ +--TEST-- +Early-bound subclass of Operable parent is validated for operator methods +--FILE-- + +--EXPECTF-- +Fatal error: Operator method BadChildOp::__mul() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_enum.phpt b/Zend/tests/operable/error_enum.phpt new file mode 100644 index 000000000000..68d223d65145 --- /dev/null +++ b/Zend/tests/operable/error_enum.phpt @@ -0,0 +1,12 @@ +--TEST-- +Unit enum cannot implement Operable +--FILE-- + +--EXPECTF-- +Fatal error: Enum BadEnum cannot implement Operable in %s on line %d diff --git a/Zend/tests/operable/error_interface_invalid.phpt b/Zend/tests/operable/error_interface_invalid.phpt new file mode 100644 index 000000000000..bd2773308ecc --- /dev/null +++ b/Zend/tests/operable/error_interface_invalid.phpt @@ -0,0 +1,12 @@ +--TEST-- +Invalid operator method declared on interface extending Operable is rejected +--FILE-- + +--EXPECTF-- +Fatal error: Operator method BadInterface::__mul() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_non_operable_parent_grand_override.phpt b/Zend/tests/operable/error_non_operable_parent_grand_override.phpt new file mode 100644 index 000000000000..a2f58b5e80f8 --- /dev/null +++ b/Zend/tests/operable/error_non_operable_parent_grand_override.phpt @@ -0,0 +1,23 @@ +--TEST-- +Grandchild cannot override final operator method inherited through Operable child from non-Operable base +--FILE-- + +--EXPECTF-- +Fatal error: Cannot override final method Base::__add() in %s on line %d diff --git a/Zend/tests/operable/error_non_operable_parent_invalid.phpt b/Zend/tests/operable/error_non_operable_parent_invalid.phpt new file mode 100644 index 000000000000..3aaea3f435c7 --- /dev/null +++ b/Zend/tests/operable/error_non_operable_parent_invalid.phpt @@ -0,0 +1,17 @@ +--TEST-- +Non-Operable parent cannot smuggle invalid operator method into Operable child +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Child::__add() cannot return by reference in %s on line %d diff --git a/Zend/tests/operable/error_non_operable_parent_non_final.phpt b/Zend/tests/operable/error_non_operable_parent_non_final.phpt new file mode 100644 index 000000000000..5b7d92a5cc08 --- /dev/null +++ b/Zend/tests/operable/error_non_operable_parent_non_final.phpt @@ -0,0 +1,20 @@ +--TEST-- +Operable class cannot inherit non-final concrete operator method from non-Operable ancestor +--FILE-- + +--EXPECTF-- +Fatal error: Operable class Child cannot inherit non-final operator method Base1::__add() in %s on line %d diff --git a/Zend/tests/operable/error_non_readonly.phpt b/Zend/tests/operable/error_non_readonly.phpt new file mode 100644 index 000000000000..be9b646e7992 --- /dev/null +++ b/Zend/tests/operable/error_non_readonly.phpt @@ -0,0 +1,14 @@ +--TEST-- +Non-readonly class cannot implement Operable +--FILE-- + +--EXPECTF-- +Fatal error: Class Bad implements Operable and must be declared readonly in %s on line %d diff --git a/Zend/tests/operable/error_override_final.phpt b/Zend/tests/operable/error_override_final.phpt new file mode 100644 index 000000000000..aea22f4ca8b8 --- /dev/null +++ b/Zend/tests/operable/error_override_final.phpt @@ -0,0 +1,14 @@ +--TEST-- +Concrete operator method on non-final Operable class must be declared final +--FILE-- + +--EXPECTF-- +Fatal error: Operator method ParentOp::__add() on non-final class must be declared final in %s on line %d diff --git a/Zend/tests/operable/error_param_by_ref.phpt b/Zend/tests/operable/error_param_by_ref.phpt new file mode 100644 index 000000000000..519cee14d2a4 --- /dev/null +++ b/Zend/tests/operable/error_param_by_ref.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method first parameter cannot be passed by reference +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() parameters cannot be passed by reference in %s on line %d diff --git a/Zend/tests/operable/error_param_iterable.phpt b/Zend/tests/operable/error_param_iterable.phpt new file mode 100644 index 000000000000..24f9bf70602a --- /dev/null +++ b/Zend/tests/operable/error_param_iterable.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method rejects iterable operand parameter type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_param_mixed.phpt b/Zend/tests/operable/error_param_mixed.phpt new file mode 100644 index 000000000000..a4084ed975b1 --- /dev/null +++ b/Zend/tests/operable/error_param_mixed.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method rejects mixed operand parameter type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_param_nullable.phpt b/Zend/tests/operable/error_param_nullable.phpt new file mode 100644 index 000000000000..22e867e60e60 --- /dev/null +++ b/Zend/tests/operable/error_param_nullable.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method rejects nullable operand parameter type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_param_object.phpt b/Zend/tests/operable/error_param_object.phpt new file mode 100644 index 000000000000..6a57da40f9a1 --- /dev/null +++ b/Zend/tests/operable/error_param_object.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method rejects object operand parameter type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_param_string.phpt b/Zend/tests/operable/error_param_string.phpt new file mode 100644 index 000000000000..8ca0e6a5fe9f --- /dev/null +++ b/Zend/tests/operable/error_param_string.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method rejects string operand parameter type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__mul() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_param_union_bool.phpt b/Zend/tests/operable/error_param_union_bool.phpt new file mode 100644 index 000000000000..3c4e98001ddf --- /dev/null +++ b/Zend/tests/operable/error_param_union_bool.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method rejects disallowed primitive inside union type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_return_by_ref.phpt b/Zend/tests/operable/error_return_by_ref.phpt new file mode 100644 index 000000000000..dacedd1153c1 --- /dev/null +++ b/Zend/tests/operable/error_return_by_ref.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator methods cannot return by reference +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() cannot return by reference in %s on line %d diff --git a/Zend/tests/operable/error_return_missing.phpt b/Zend/tests/operable/error_return_missing.phpt new file mode 100644 index 000000000000..adf73d10edf2 --- /dev/null +++ b/Zend/tests/operable/error_return_missing.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method must declare a return type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() must declare a return type in %s on line %d diff --git a/Zend/tests/operable/error_return_mixed.phpt b/Zend/tests/operable/error_return_mixed.phpt new file mode 100644 index 000000000000..ad481e5a250f --- /dev/null +++ b/Zend/tests/operable/error_return_mixed.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method cannot return mixed +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() cannot return void, never, or mixed in %s on line %d diff --git a/Zend/tests/operable/error_return_never.phpt b/Zend/tests/operable/error_return_never.phpt new file mode 100644 index 000000000000..cc894f9b3a4b --- /dev/null +++ b/Zend/tests/operable/error_return_never.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method cannot return never +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() cannot return void, never, or mixed in %s on line %d diff --git a/Zend/tests/operable/error_return_void.phpt b/Zend/tests/operable/error_return_void.phpt new file mode 100644 index 000000000000..d409564d3937 --- /dev/null +++ b/Zend/tests/operable/error_return_void.phpt @@ -0,0 +1,12 @@ +--TEST-- +Operator method cannot return void +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() cannot return void, never, or mixed in %s on line %d diff --git a/Zend/tests/operable/error_second_param_bool.phpt b/Zend/tests/operable/error_second_param_bool.phpt new file mode 100644 index 000000000000..95df8b30291e --- /dev/null +++ b/Zend/tests/operable/error_second_param_bool.phpt @@ -0,0 +1,14 @@ +--TEST-- +Second parameter of operator method must be OperandSide (rejects bool) +--FILE-- + +--EXPECTF-- +Fatal error: The second parameter of operator method Bad::__sub() must be OperandSide in %s on line %d diff --git a/Zend/tests/operable/error_second_param_by_ref.phpt b/Zend/tests/operable/error_second_param_by_ref.phpt new file mode 100644 index 000000000000..6083909b57fe --- /dev/null +++ b/Zend/tests/operable/error_second_param_by_ref.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method second parameter (OperandSide) cannot be passed by reference +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__sub() parameters cannot be passed by reference in %s on line %d diff --git a/Zend/tests/operable/error_second_param_namespaced_side.phpt b/Zend/tests/operable/error_second_param_namespaced_side.phpt new file mode 100644 index 000000000000..5b601b65b8ec --- /dev/null +++ b/Zend/tests/operable/error_second_param_namespaced_side.phpt @@ -0,0 +1,21 @@ +--TEST-- +Second parameter of operator method must be global OperandSide, not namespaced OperandSide +--FILE-- + +--EXPECTF-- +Fatal error: The second parameter of operator method App\Bad::__sub() must be OperandSide in %s on line %d diff --git a/Zend/tests/operable/error_second_param_nullable_side.phpt b/Zend/tests/operable/error_second_param_nullable_side.phpt new file mode 100644 index 000000000000..8636d3d10a2e --- /dev/null +++ b/Zend/tests/operable/error_second_param_nullable_side.phpt @@ -0,0 +1,14 @@ +--TEST-- +Second parameter of operator method cannot be nullable OperandSide +--FILE-- + +--EXPECTF-- +Fatal error: The second parameter of operator method Bad::__sub() must be OperandSide in %s on line %d diff --git a/Zend/tests/operable/error_static.phpt b/Zend/tests/operable/error_static.phpt new file mode 100644 index 000000000000..663b31e54c40 --- /dev/null +++ b/Zend/tests/operable/error_static.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method cannot be static +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__mul() must be public and non-static in %s on line %d diff --git a/Zend/tests/operable/error_three_params.phpt b/Zend/tests/operable/error_three_params.phpt new file mode 100644 index 000000000000..00c68fe81378 --- /dev/null +++ b/Zend/tests/operable/error_three_params.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method cannot take more than 2 parameters +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__div() must take 1 or 2 parameters in %s on line %d diff --git a/Zend/tests/operable/error_trait_invalid.phpt b/Zend/tests/operable/error_trait_invalid.phpt new file mode 100644 index 000000000000..77389d42bc30 --- /dev/null +++ b/Zend/tests/operable/error_trait_invalid.phpt @@ -0,0 +1,18 @@ +--TEST-- +Invalid operator method imported from trait is rejected on Operable class +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() has an unsupported operand parameter type in %s on line %d diff --git a/Zend/tests/operable/error_trait_override_final.phpt b/Zend/tests/operable/error_trait_override_final.phpt new file mode 100644 index 000000000000..796db306a2bb --- /dev/null +++ b/Zend/tests/operable/error_trait_override_final.phpt @@ -0,0 +1,18 @@ +--TEST-- +Trait-imported concrete operator method on non-final Operable class must be final +--FILE-- + +--EXPECTF-- +Fatal error: Operator method ParentOp::__add() on non-final class must be declared final in %s on line %d diff --git a/Zend/tests/operable/error_untyped_param.phpt b/Zend/tests/operable/error_untyped_param.phpt new file mode 100644 index 000000000000..58a87659b911 --- /dev/null +++ b/Zend/tests/operable/error_untyped_param.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method must declare a parameter type +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__pow() must declare a parameter type in %s on line %d diff --git a/Zend/tests/operable/error_variadic.phpt b/Zend/tests/operable/error_variadic.phpt new file mode 100644 index 000000000000..509cb741cb24 --- /dev/null +++ b/Zend/tests/operable/error_variadic.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method cannot be variadic +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() cannot be variadic in %s on line %d diff --git a/Zend/tests/operable/error_visibility_private.phpt b/Zend/tests/operable/error_visibility_private.phpt new file mode 100644 index 000000000000..b36ba0a68f76 --- /dev/null +++ b/Zend/tests/operable/error_visibility_private.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method cannot be private +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__sub() must be public and non-static in %s on line %d diff --git a/Zend/tests/operable/error_visibility_protected.phpt b/Zend/tests/operable/error_visibility_protected.phpt new file mode 100644 index 000000000000..10f10f2f91a9 --- /dev/null +++ b/Zend/tests/operable/error_visibility_protected.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method cannot be protected +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() must be public and non-static in %s on line %d diff --git a/Zend/tests/operable/error_zero_params.phpt b/Zend/tests/operable/error_zero_params.phpt new file mode 100644 index 000000000000..2528f6524cdb --- /dev/null +++ b/Zend/tests/operable/error_zero_params.phpt @@ -0,0 +1,14 @@ +--TEST-- +Operator method must take at least 1 parameter +--FILE-- + +--EXPECTF-- +Fatal error: Operator method Bad::__add() must take 1 or 2 parameters in %s on line %d diff --git a/Zend/tests/operable/non_operable_parent_inheritance.phpt b/Zend/tests/operable/non_operable_parent_inheritance.phpt new file mode 100644 index 000000000000..7b91bc9e70dc --- /dev/null +++ b/Zend/tests/operable/non_operable_parent_inheritance.phpt @@ -0,0 +1,153 @@ +--TEST-- +Non-Operable parent inheritance, final class exemption, reflection context sensitivity, and abstract/interface chains +--FILE-- +v + $x); + } +} + +readonly class Child extends Base implements Operable { +} + +$anonFromFinalBase = new readonly class(10) extends Base implements Operable { +}; + +var_dump((new Child(10) + 5)->v); +var_dump(($anonFromFinalBase + 5)->v); + +// Reflection depends on reflected class (Child vs Base) +$rmChild = new ReflectionMethod(Child::class, '__add'); +$rmBase = new ReflectionMethod(Base::class, '__add'); +var_dump($rmChild->isOperatorMethod()); +var_dump($rmChild->isFinal()); +var_dump($rmBase->isOperatorMethod()); +var_dump($rmBase->isFinal()); + +var_dump((new ReflectionClass(Base::class))->getOperatorMethods()); +$childOps = (new ReflectionClass(Child::class))->getOperatorMethods(); +var_dump(array_keys($childOps)); +var_dump($childOps['+']->isOperatorMethod()); +var_dump($childOps['+']->isFinal()); +var_dump($childOps['+']->getDeclaringClass()->getName()); + +// 2. Non-final Base stays non-final for non-Operable siblings; +// final Child can inherit directly, and non-final Child can delegate with explicit final +readonly class NonFinalBase { + public function __construct(public int $v = 0) {} + + public function __add(int $x): static { + return new static($this->v + $x); + } +} + +final readonly class FinalChild extends NonFinalBase implements Operable { +} + +readonly class DelegatingChild extends NonFinalBase implements Operable { + final public function __add(int $x): static { + return parent::__add($x); + } +} + +readonly class Other extends NonFinalBase { + public function __add(int $x): static { + return new static($this->v + $x * 2); + } +} + +var_dump((new ReflectionMethod(NonFinalBase::class, '__add'))->isFinal()); +var_dump((new ReflectionMethod(FinalChild::class, '__add'))->isFinal()); +var_dump((new ReflectionMethod(FinalChild::class, '__add'))->isOperatorMethod()); +var_dump((new ReflectionMethod(DelegatingChild::class, '__add'))->isFinal()); +var_dump((new FinalChild(10) + 5)->v); +var_dump((new DelegatingChild(10) + 5)->v); +var_dump((new Other(10))->__add(5)->v); + +// 3. Abstract non-Operable parent and non-Operable interface chains +interface PlainAdd { + public function __add(int $x): self; +} + +interface OperableAdd extends PlainAdd, Operable { +} + +abstract readonly class AbstractBase { + abstract public function __sub(int $x, OperandSide $side): self; +} + +abstract readonly class AbstractChild extends AbstractBase implements OperableAdd { +} + +final readonly class ConcreteGrand extends AbstractChild { + public function __add(int $x): self { + return $this; + } + + public function __sub(int $x, OperandSide $side): self { + return $this; + } +} + +$rcAbsChild = new ReflectionClass(AbstractChild::class); +$absOps = $rcAbsChild->getOperatorMethods(); +var_dump(array_keys($absOps)); +var_dump($absOps['+']->isOperatorMethod(), $absOps['+']->isAbstract(), $absOps['+']->isFinal()); +var_dump($absOps['-']->isOperatorMethod(), $absOps['-']->isAbstract(), $absOps['-']->isFinal()); +var_dump((new ReflectionMethod(PlainAdd::class, '__add'))->isOperatorMethod()); +var_dump((new ReflectionMethod(AbstractBase::class, '__sub'))->isOperatorMethod()); + +$rcGrand = new ReflectionClass(ConcreteGrand::class); +$grandOps = $rcGrand->getOperatorMethods(); +var_dump($rcGrand->isFinal()); +var_dump($grandOps['+']->isOperatorMethod(), $grandOps['+']->isFinal()); +var_dump($grandOps['-']->isOperatorMethod(), $grandOps['-']->isFinal()); + +?> +--EXPECT-- +int(15) +int(15) +bool(true) +bool(true) +bool(false) +bool(true) +array(0) { +} +array(1) { + [0]=> + string(1) "+" +} +bool(true) +bool(true) +string(4) "Base" +bool(false) +bool(false) +bool(true) +bool(true) +int(15) +int(15) +int(20) +array(2) { + [0]=> + string(1) "+" + [1]=> + string(1) "-" +} +bool(true) +bool(true) +bool(false) +bool(true) +bool(true) +bool(false) +bool(false) +bool(false) +bool(true) +bool(true) +bool(false) +bool(true) +bool(false) diff --git a/Zend/tests/operable/reflection.phpt b/Zend/tests/operable/reflection.phpt new file mode 100644 index 000000000000..27d948bd03f7 --- /dev/null +++ b/Zend/tests/operable/reflection.phpt @@ -0,0 +1,192 @@ +--TEST-- +ReflectionClass::getOperatorMethods() and ReflectionMethod::isOperatorMethod() +--FILE-- +v; + } +} + +final readonly class SubNum extends ConcreteNum { + public function __div(int $d): self { + return $this; + } +} + +class Plain { + public function __add($other) {} +} + +// 1. Concrete class with subset of operators + inherited + trait + mixed-case +$rcConcrete = new ReflectionClass(ConcreteNum::class); +$ops = $rcConcrete->getOperatorMethods(); +var_dump(array_keys($ops)); +foreach ($ops as $sym => $method) { + echo "$sym => " . $method->getDeclaringClass()->getName() . "::" . $method->getName() + . " op=" . ($method->isOperatorMethod() ? "true" : "false") + . " final=" . ($method->isFinal() ? "true" : "false") . "\n"; +} + +// Non-operator methods on Operable class +var_dump($rcConcrete->getMethod('__construct')->isOperatorMethod()); +var_dump($rcConcrete->getMethod('helper')->isOperatorMethod()); +var_dump($rcConcrete->getMethod('__toString')->isOperatorMethod()); + +// 2. Subclass inheriting all 5 + adding '/' => all 6 in deterministic order +$rcSub = new ReflectionClass(SubNum::class); +$subOps = $rcSub->getOperatorMethods(); +var_dump(array_keys($subOps)); +var_dump($subOps['+']->isOperatorMethod()); +var_dump($subOps['/']->isOperatorMethod()); + +// 3. ReflectionObject works identically +$ro = new ReflectionObject(new SubNum(10)); +var_dump(array_keys($ro->getOperatorMethods())); + +// 4. Interface extending Operable & Operable itself +$rcIface = new ReflectionClass(Addable::class); +var_dump(array_keys($rcIface->getOperatorMethods())); +var_dump($rcIface->getMethod('__add')->isOperatorMethod()); +var_dump($rcIface->getMethod('__add')->isFinal()); + +$rcOperable = new ReflectionClass(Operable::class); +var_dump($rcOperable->getOperatorMethods()); + +// 5. Abstract readonly class (both abstract and concrete operator methods) +$rcAbs = new ReflectionClass(AbstractNum::class); +$absOps = $rcAbs->getOperatorMethods(); +var_dump(array_keys($absOps)); +var_dump($absOps['-']->isOperatorMethod(), $absOps['-']->isAbstract(), $absOps['-']->isFinal()); +var_dump($absOps['**']->isOperatorMethod(), $absOps['**']->isAbstract(), $absOps['**']->isFinal()); + +// 6. Trait itself is not Operable +$rcTrait = new ReflectionClass(MulTrait::class); +var_dump($rcTrait->getOperatorMethods()); +var_dump($rcTrait->getMethod('__Mul')->isOperatorMethod()); + +// 7. Non-Operable class defining __add +$rcPlain = new ReflectionClass(Plain::class); +var_dump($rcPlain->getOperatorMethods()); +var_dump($rcPlain->getMethod('__add')->isOperatorMethod()); + +?> +--EXPECT-- +array(5) { + [0]=> + string(1) "+" + [1]=> + string(1) "-" + [2]=> + string(1) "*" + [3]=> + string(1) "%" + [4]=> + string(2) "**" +} ++ => ConcreteNum::__ADD op=true final=true +- => ConcreteNum::__sub op=true final=true +* => ConcreteNum::__Mul op=true final=true +% => ConcreteNum::__mod op=true final=true +** => AbstractNum::__pow op=true final=true +bool(false) +bool(false) +bool(false) +array(6) { + [0]=> + string(1) "+" + [1]=> + string(1) "-" + [2]=> + string(1) "*" + [3]=> + string(1) "/" + [4]=> + string(1) "%" + [5]=> + string(2) "**" +} +bool(true) +bool(true) +array(6) { + [0]=> + string(1) "+" + [1]=> + string(1) "-" + [2]=> + string(1) "*" + [3]=> + string(1) "/" + [4]=> + string(1) "%" + [5]=> + string(2) "**" +} +array(1) { + [0]=> + string(1) "+" +} +bool(true) +bool(false) +array(0) { +} +array(3) { + [0]=> + string(1) "+" + [1]=> + string(1) "-" + [2]=> + string(2) "**" +} +bool(true) +bool(true) +bool(false) +bool(true) +bool(false) +bool(true) +array(0) { +} +bool(false) +array(0) { +} +bool(false) diff --git a/Zend/tests/operable/runtime_all_operators.phpt b/Zend/tests/operable/runtime_all_operators.phpt new file mode 100644 index 000000000000..9e6d0bbe2012 --- /dev/null +++ b/Zend/tests/operable/runtime_all_operators.phpt @@ -0,0 +1,87 @@ +--TEST-- +Runtime dispatch for all 6 arithmetic operators on Operable classes +--FILE-- +v + ($rhs instanceof self ? $rhs->v : $rhs)); + } + + public function __sub(self|int|float $rhs, OperandSide $side): self { + $other = $rhs instanceof self ? $rhs->v : $rhs; + return new self($side === OperandSide::Left ? $this->v - $other : $other - $this->v); + } + + public function __mul(self|int|float $rhs): self { + return new self($this->v * ($rhs instanceof self ? $rhs->v : $rhs)); + } + + public function __div(self|int|float $rhs, OperandSide $side): self { + $other = $rhs instanceof self ? $rhs->v : $rhs; + return new self($side === OperandSide::Left ? $this->v / $other : $other / $this->v); + } + + public function __mod(self|int|float $rhs, OperandSide $side): self { + $other = $rhs instanceof self ? $rhs->v : $rhs; + $res = $side === OperandSide::Left ? fmod($this->v, $other) : fmod($other, $this->v); + return new self($res); + } + + public function __pow(self|int|float $rhs, OperandSide $side): self { + $other = $rhs instanceof self ? $rhs->v : $rhs; + return new self($side === OperandSide::Left ? $this->v ** $other : $other ** $this->v); + } +} + +$a = new Num(10); +$b = new Num(4); + +// + (left, object+object, commutative right swap) +var_dump(($a + $b)->v); +var_dump(($a + 5)->v); +var_dump((5 + $a)->v); + +// - (left with OperandSide::Left, right with OperandSide::Right) +var_dump(($a - $b)->v); +var_dump(($a - 3)->v); +var_dump((3 - $a)->v); + +// * (left, commutative right swap, chained expression) +var_dump(($a * 3)->v); +var_dump((3 * $a)->v); +var_dump(($a * 3 + new Num(5))->v); + +// / (left and right with OperandSide) +var_dump(($a / $b)->v); +var_dump((20 / $a)->v); + +// % (left and right with OperandSide, including float % Operable without truncation) +var_dump(($a % 3)->v); +var_dump((25 % $a)->v); +var_dump((12.5 % $a)->v); + +// ** (left and right with OperandSide) +var_dump(($b ** 3)->v); +var_dump((2 ** $b)->v); + +?> +--EXPECT-- +int(14) +int(15) +int(15) +int(6) +int(7) +int(-7) +int(30) +int(30) +int(35) +float(2.5) +int(2) +float(1) +float(5) +float(2.5) +int(64) +int(16) diff --git a/Zend/tests/operable/runtime_compound_assignment.phpt b/Zend/tests/operable/runtime_compound_assignment.phpt new file mode 100644 index 000000000000..c8f6fed22ac6 --- /dev/null +++ b/Zend/tests/operable/runtime_compound_assignment.phpt @@ -0,0 +1,115 @@ +--TEST-- +Compound assignments, aliasing, references, properties, arrays, and exception safety for Operable +--FILE-- +amount : $other; + if ($val < 0) { + throw new DomainException("negative add"); + } + if ($val === 0) { + return $this; // returns same object instance + } + return new self($this->amount + $val); + } + + public function __sub(self|int $other, OperandSide $side): self { + $val = $other instanceof self ? $other->amount : $other; + return new self($side === OperandSide::Left ? $this->amount - $val : $val - $this->amount); + } + + public function __mul(int $factor): self { + return new self($this->amount * $factor); + } + + public function __div(int $d): self { + return new self(intdiv($this->amount, $d)); + } + + public function __mod(int $m): self { + return new self($this->amount % $m); + } + + public function __pow(int $e): self { + return new self($this->amount ** $e); + } +} + +// Basic compound assignment for all 6 ops +$m = new Money(10); +$m += new Money(5); // 15 +var_dump($m->amount); +$m -= 3; // 12 +var_dump($m->amount); +$m *= 2; // 24 +var_dump($m->amount); +$m /= 4; // 6 +var_dump($m->amount); +$m **= 2; // 36 +var_dump($m->amount); +$m %= 10; // 6 +var_dump($m->amount); + +// Self-aliasing: $m += $m (result == op1 == op2) +$m += $m; // 12 +var_dump($m->amount); + +// Returning $this in compound assignment (refcount stability) +$m += 0; // 12 +var_dump($m->amount); + +// Scalar LHS with Operable RHS compound assignment +$s = 100; +$s += new Money(25); +var_dump($s->amount); + +$s2 = 500; +$s2 -= new Money(75); +var_dump($s2->amount); + +// References +$orig = new Money(10); +$ref = &$orig; +$ref += new Money(20); +var_dump($orig->amount, $ref->amount); + +// Property and array element compound assignment +$box = (object)['v' => new Money(7)]; +$box->v *= 3; +var_dump($box->v->amount); + +$arr = [new Money(8)]; +$arr[0] += new Money(4); +var_dump($arr[0]->amount); + +// Exception during compound assignment leaves LHS intact +$safe = new Money(42); +try { + $safe += -1; +} catch (DomainException $e) { + echo "Caught: " . $e->getMessage() . "\n"; +} +var_dump($safe->amount); + +?> +--EXPECT-- +int(15) +int(12) +int(24) +int(6) +int(36) +int(6) +int(12) +int(12) +int(125) +int(425) +int(30) +int(30) +int(21) +int(12) +Caught: negative add +int(42) diff --git a/Zend/tests/operable/runtime_dispatch_precedence.phpt b/Zend/tests/operable/runtime_dispatch_precedence.phpt new file mode 100644 index 000000000000..b5e7eea36de9 --- /dev/null +++ b/Zend/tests/operable/runtime_dispatch_precedence.phpt @@ -0,0 +1,94 @@ +--TEST-- +Runtime dispatch priority between left and right Operable operands +--FILE-- +name . ")"; + } + public function __sub(LeftWins $other, OperandSide $side): string { + return "RightWithSide::__sub(" . $side->name . ")"; + } +} + +final readonly class RightCommutative implements Operable { + public function __add(LeftWins $other): string { + return "RightCommutative::__add"; + } + public function __mul(LeftWins $other): string { + return "RightCommutative::__mul"; + } + public function __sub(LeftWins $other): string { + return "RightCommutative::__sub"; + } + public function __div(LeftWins $other): string { + return "RightCommutative::__div"; + } + public function __mod(LeftWins $other): string { + return "RightCommutative::__mod"; + } + public function __pow(LeftWins $other): string { + return "RightCommutative::__pow"; + } +} + +$l = new LeftWins(); +$rs = new RightWithSide(); +$rc = new RightCommutative(); + +// Step 2: Left wins when left accepts right +var_dump($l + $rs); +var_dump($l + $rc); + +// Step 3: Left rejects RightWithSide for '-', falls back to RightWithSide with OperandSide::Right +var_dump($l - $rs); + +// Step 4: Left rejects RightCommutative for '*', falls back to commutative swap +var_dump($l * $rc); + +// Non-commutative operators do NOT swap to 1-param right operand +foreach (['-', '/', '%', '**'] as $op) { + try { + match ($op) { + '-' => $l - $rc, + '/' => $l / $rc, + '%' => $l % $rc, + '**' => $l ** $rc, + }; + } catch (InvalidOperatorError $e) { + echo "Caught $op: " . $e->getMessage() . "\n"; + } +} + +?> +--EXPECT-- +string(15) "LeftWins::__add" +string(15) "LeftWins::__add" +string(27) "RightWithSide::__sub(Right)" +string(23) "RightCommutative::__mul" +Caught -: Unsupported operand types: LeftWins - RightCommutative +Caught /: Unsupported operand types: LeftWins / RightCommutative +Caught %: Unsupported operand types: LeftWins % RightCommutative +Caught **: Unsupported operand types: LeftWins ** RightCommutative diff --git a/Zend/tests/operable/runtime_errors.phpt b/Zend/tests/operable/runtime_errors.phpt new file mode 100644 index 000000000000..f64f6944febd --- /dev/null +++ b/Zend/tests/operable/runtime_errors.phpt @@ -0,0 +1,74 @@ +--TEST-- +InvalidOperatorError thrown for unsupported arithmetic operands on Operable while non-Operable and bitwise ops keep plain TypeError +--FILE-- + $m + "100", + fn() => "100" + $m, + fn() => $m - 1, + fn() => $m * 2, + fn() => $m / 2, + fn() => $m % 2, + fn() => $m ** 2, +]; + +foreach ($operableCases as $fn) { + try { + $fn(); + } catch (TypeError $e) { + echo get_class($e) . " (is InvalidOperatorError=" . ($e instanceof InvalidOperatorError ? "yes" : "no") . "): " . $e->getMessage() . "\n"; + } +} + +// Non-Operable arithmetic ops and bitwise/shift ops still throw plain TypeError (not InvalidOperatorError) +$plainTypeErrorCases = [ + fn() => $n + 1, + fn() => [] + 1, + fn() => $m | 1, + fn() => $m & 1, + fn() => $m ^ 1, + fn() => $m << 1, + fn() => $m >> 1, +]; + +foreach ($plainTypeErrorCases as $fn) { + try { + $fn(); + } catch (TypeError $e) { + echo get_class($e) . " (is InvalidOperatorError=" . ($e instanceof InvalidOperatorError ? "yes" : "no") . "): " . $e->getMessage() . "\n"; + } +} + +?> +--EXPECT-- +InvalidOperatorError (is InvalidOperatorError=yes): Unsupported operand types: Money + string +InvalidOperatorError (is InvalidOperatorError=yes): Unsupported operand types: string + Money +InvalidOperatorError (is InvalidOperatorError=yes): Unsupported operand types: Money - int +InvalidOperatorError (is InvalidOperatorError=yes): Unsupported operand types: Money * int +InvalidOperatorError (is InvalidOperatorError=yes): Unsupported operand types: Money / int +InvalidOperatorError (is InvalidOperatorError=yes): Unsupported operand types: Money % int +InvalidOperatorError (is InvalidOperatorError=yes): Unsupported operand types: Money ** int +TypeError (is InvalidOperatorError=no): Unsupported operand types: NonOperable + int +TypeError (is InvalidOperatorError=no): Unsupported operand types: array + int +TypeError (is InvalidOperatorError=no): Unsupported operand types: Money | int +TypeError (is InvalidOperatorError=no): Unsupported operand types: Money & int +TypeError (is InvalidOperatorError=no): Unsupported operand types: Money ^ int +TypeError (is InvalidOperatorError=no): Unsupported operand types: Money << int +TypeError (is InvalidOperatorError=no): Unsupported operand types: Money >> int diff --git a/Zend/tests/operable/runtime_internal_interop_bcmath.phpt b/Zend/tests/operable/runtime_internal_interop_bcmath.phpt new file mode 100644 index 000000000000..cacef2a02731 --- /dev/null +++ b/Zend/tests/operable/runtime_internal_interop_bcmath.phpt @@ -0,0 +1,68 @@ +--TEST-- +Operable interop with BcMath\Number internal operator overloading +--EXTENSIONS-- +bcmath +--FILE-- +amount))->add($other)->value); + } + + public function __sub(Number $other, OperandSide $side): self { + $selfNum = new Number($this->amount); + $res = $side === OperandSide::Left ? $selfNum->sub($other) : $other->sub($selfNum); + return new self($res->value); + } +} + +final readonly class NonMatching implements Operable { + public function __add(int $x): self { + return $this; + } +} + +$m = new Money("100"); +$n = new Number("25"); + +// Operable takes precedence on left and right +var_dump(($m + $n)->amount); +var_dump(($n + $m)->amount); +var_dump(($m - $n)->amount); +var_dump(($n - $m)->amount); + +// Compound assignments +$m2 = $m; +$m2 += $n; +var_dump($m2->amount); + +$n2 = $n; +$n2 += $m; +var_dump($n2 instanceof Money, $n2->amount); + +// Non-matching Operable falls through to BcMath\Number (which rejects it -> InvalidOperatorError) +$nm = new NonMatching(); +foreach ([fn() => $nm + $n, fn() => $n + $nm] as $fn) { + try { + $fn(); + } catch (InvalidOperatorError $e) { + echo get_class($e) . ": " . $e->getMessage() . "\n"; + } +} + +?> +--EXPECT-- +string(3) "125" +string(3) "125" +string(2) "75" +string(3) "-75" +string(3) "125" +bool(true) +string(3) "125" +InvalidOperatorError: Unsupported operand types: NonMatching + BcMath\Number +InvalidOperatorError: Unsupported operand types: BcMath\Number + NonMatching diff --git a/Zend/tests/operable/runtime_internal_interop_gmp.phpt b/Zend/tests/operable/runtime_internal_interop_gmp.phpt new file mode 100644 index 000000000000..d20e6ddd46b1 --- /dev/null +++ b/Zend/tests/operable/runtime_internal_interop_gmp.phpt @@ -0,0 +1,53 @@ +--TEST-- +Operable interop with GMP internal operator overloading +--EXTENSIONS-- +gmp +--FILE-- +amount + gmp_intval($other)); + } + + public function __sub(GMP $other, OperandSide $side): self { + $val = gmp_intval($other); + return new self($side === OperandSide::Left ? $this->amount - $val : $val - $this->amount); + } +} + +final readonly class NonMatching implements Operable { + public function __add(int $x): self { + return $this; + } +} + +$m = new Money(100); +$g = gmp_init(25); + +// Operable takes precedence on left and right +var_dump(($m + $g)->amount); +var_dump(($g + $m)->amount); +var_dump(($m - $g)->amount); +var_dump(($g - $m)->amount); + +// Non-matching Operable falls through to GMP's TypeError +$nm = new NonMatching(); +foreach ([fn() => $nm + $g, fn() => $g + $nm] as $fn) { + try { + $fn(); + } catch (TypeError $e) { + echo get_class($e) . ": " . $e->getMessage() . "\n"; + } +} + +?> +--EXPECT-- +int(125) +int(125) +int(75) +int(-75) +TypeError: Number must be of type GMP|string|int, NonMatching given +TypeError: Number must be of type GMP|string|int, NonMatching given diff --git a/Zend/tests/operable/runtime_jit_hot_loop.phpt b/Zend/tests/operable/runtime_jit_hot_loop.phpt new file mode 100644 index 000000000000..0b859d9d6b67 --- /dev/null +++ b/Zend/tests/operable/runtime_jit_hot_loop.phpt @@ -0,0 +1,56 @@ +--TEST-- +Operable dispatch under hot loops (OPcache and JIT safety) +--INI-- +opcache.enable=1 +opcache.enable_cli=1 +opcache.jit=tracing +opcache.jit_buffer_size=64M +--EXTENSIONS-- +opcache +--FILE-- +x + ($rhs instanceof self ? $rhs->x : $rhs)); + } + + public function __sub(int $rhs, OperandSide $side): self { + return new self($side === OperandSide::Left ? $this->x - $rhs : $rhs - $this->x); + } + + public function __mul(int $factor): self { + return new self($this->x * $factor); + } + + public function __div(int $divisor): string { + return (string) intdiv($this->x, $divisor); + } +} + +function runHotLoop(): array { + $acc = new Vec(0); + $lastLabel = ''; + for ($i = 1; $i <= 500; $i++) { + $v = new Vec($i); + $scaled = 2 * $v; + $diff = 1000 - $v; + $acc += $scaled + $diff; + $lastLabel = $acc / 10; + } + return [$acc->x, $lastLabel]; +} + +// Sum_{i=1..500} (2*i + (1000 - i)) = Sum_{i=1..500} (1000 + i) = 500000 + 125250 = 625250 +var_dump(runHotLoop()); + +?> +--EXPECT-- +array(2) { + [0]=> + int(625250) + [1]=> + string(5) "62525" +} diff --git a/Zend/tests/operable/runtime_long_class_name.phpt b/Zend/tests/operable/runtime_long_class_name.phpt new file mode 100644 index 000000000000..d1151d6242b9 --- /dev/null +++ b/Zend/tests/operable/runtime_long_class_name.phpt @@ -0,0 +1,69 @@ +--TEST-- +Operable type resolution with 255-, 256-, and 257-character class names (stack buffer boundary) +--FILE-- +getMessage() . "\n"; +} + +// Matching primitive in the same union +var_dump($m + 42); + +// Subclasses of loaded 255-, 256-, and 257-char classes +var_dump($m * new Sub255()); +var_dump($m * new Sub256()); +var_dump($m * new Sub257()); + +?> +--EXPECT-- +int(255) +int(256) +int(257) +InvalidOperatorError: Unsupported operand types: Money + stdClass +string(7) "add:int" +string(10) "mul:Sub255" +string(10) "mul:Sub256" +string(10) "mul:Sub257" diff --git a/Zend/tests/operable/runtime_type_matching.phpt b/Zend/tests/operable/runtime_type_matching.phpt new file mode 100644 index 000000000000..e332e0ce255a --- /dev/null +++ b/Zend/tests/operable/runtime_type_matching.phpt @@ -0,0 +1,163 @@ +--TEST-- +Runtime type matching for Operable methods (strict primitives, unions, intersections, DNF, self/parent, no autoload) +--FILE-- + +--EXPECT-- +string(9) "int:int:7" +Rejected + float +Rejected + string +Rejected + bool +Rejected + null +Rejected + array +string(15) "float:float:2.5" +string(13) "float:float:2" +Rejected - string +string(19) "self|int:TypeTester" +string(12) "self|int:int" +Rejected * float +string(11) "union:OnlyA" +string(11) "union:OnlyB" +string(9) "union:int" +Rejected / BothAB +string(10) "dnf:BothAB" +string(9) "dnf:float" +string(9) "dnf:float" +Rejected % OnlyA +string(20) "BaseOp::__add(SubOp)" +string(21) "BaseOp::__add(BaseOp)" +string(20) "SubOp::__sub(BaseOp)" +string(19) "SubOp::__sub(SubOp)" +string(14) "noautoload:int" +Rejected ** stdClass +array(0) { +} +string(11) "alias:OnlyA" +string(8) "ci:OnlyB" diff --git a/Zend/tests/operable/runtime_unary_pm.phpt b/Zend/tests/operable/runtime_unary_pm.phpt new file mode 100644 index 000000000000..2081c3ee20af --- /dev/null +++ b/Zend/tests/operable/runtime_unary_pm.phpt @@ -0,0 +1,84 @@ +--TEST-- +Unary minus and unary plus dispatch through __mul(-1) and __mul(1) on Operable classes +--FILE-- +v + $rhs->v); + } + + public function __mul(self|int $rhs): self { + return new self($this->v * ($rhs instanceof self ? $rhs->v : $rhs)); + } +} + +final readonly class SideAwareNum implements Operable { + public function __construct(public int $v) {} + + public function __mul(int $rhs, OperandSide $side): string { + return ($side === OperandSide::Left ? 'L' : 'R') . ':' . ($this->v * $rhs); + } +} + +final readonly class FloatOnlyMul implements Operable { + public function __construct(public float $v) {} + + public function __mul(float $rhs): self { + return new self($this->v * $rhs); + } +} + +final readonly class SelfOnlyMul implements Operable { + public function __mul(self $rhs): self { + return $this; + } +} + +final readonly class NoMul implements Operable { + public function __add(int $rhs): self { + return $this; + } +} + +$a = new Num(7); +var_dump((-$a)->v); +var_dump((+$a)->v); +var_dump((-(-$a))->v); +var_dump((-$a + new Num(10))->v); + +$s = new SideAwareNum(5); +var_dump(-$s); +var_dump(+$s); + +$f = new FloatOnlyMul(2.5); +var_dump((-$f)->v); +var_dump((+$f)->v); + +foreach ([new SelfOnlyMul(), new NoMul()] as $obj) { + foreach (['-' => fn() => -$obj, '+' => fn() => +$obj] as $op => $fn) { + try { + $fn(); + echo "UNEXPECTED\n"; + } catch (InvalidOperatorError $e) { + echo $op . ' ' . get_class($obj) . ': ' . $e->getMessage() . "\n"; + } + } +} + +?> +--EXPECT-- +int(-7) +int(7) +int(7) +int(3) +string(4) "L:-5" +string(3) "L:5" +float(-2.5) +float(2.5) +- SelfOnlyMul: Unsupported operand types: SelfOnlyMul * int ++ SelfOnlyMul: Unsupported operand types: SelfOnlyMul * int +- NoMul: Unsupported operand types: NoMul * int ++ NoMul: Unsupported operand types: NoMul * int diff --git a/Zend/tests/operable/symbols.phpt b/Zend/tests/operable/symbols.phpt new file mode 100644 index 000000000000..9b3ac7671931 --- /dev/null +++ b/Zend/tests/operable/symbols.phpt @@ -0,0 +1,41 @@ +--TEST-- +Operable, OperandSide, and InvalidOperatorError built-in symbols +--FILE-- +getMessage() . "\n"; +} + +?> +--EXPECT-- +bool(true) +bool(true) +enum(OperandSide::Left) +enum(OperandSide::Right) +array(2) { + [0]=> + enum(OperandSide::Left) + [1]=> + enum(OperandSide::Right) +} +bool(true) +bool(false) +bool(true) +bool(true) +bool(true) +bool(true) +InvalidOperatorError: unsupported operand diff --git a/Zend/tests/operable/valid_definitions.phpt b/Zend/tests/operable/valid_definitions.phpt new file mode 100644 index 000000000000..8b0b8ff484fc --- /dev/null +++ b/Zend/tests/operable/valid_definitions.phpt @@ -0,0 +1,98 @@ +--TEST-- +Valid Operable class, interface, trait, and inheritance definitions +--FILE-- + +--EXPECT-- +bool(true) +bool(true) +bool(true) +bool(true) +bool(false) +bool(true) +OK diff --git a/Zend/zend_default_classes.c b/Zend/zend_default_classes.c index cc534e04549d..38a2b6994f6e 100644 --- a/Zend/zend_default_classes.c +++ b/Zend/zend_default_classes.c @@ -39,4 +39,5 @@ ZEND_API void zend_register_default_classes(void) zend_register_attribute_ce(); zend_register_enum_ce(); zend_register_fiber_ce(); + zend_register_operand_side_ce(); } diff --git a/Zend/zend_exceptions.c b/Zend/zend_exceptions.c index b5ccb74d7df7..65369cfaf279 100644 --- a/Zend/zend_exceptions.c +++ b/Zend/zend_exceptions.c @@ -43,6 +43,7 @@ ZEND_API zend_class_entry *zend_ce_error; ZEND_API zend_class_entry *zend_ce_compile_error; ZEND_API zend_class_entry *zend_ce_parse_error; ZEND_API zend_class_entry *zend_ce_type_error; +ZEND_API zend_class_entry *zend_ce_invalid_operator_error; ZEND_API zend_class_entry *zend_ce_argument_count_error; ZEND_API zend_class_entry *zend_ce_value_error; ZEND_API zend_class_entry *zend_ce_arithmetic_error; @@ -863,6 +864,9 @@ void zend_register_default_exception(void) /* {{{ */ zend_ce_type_error = register_class_TypeError(zend_ce_error); zend_init_exception_class_entry(zend_ce_type_error); + zend_ce_invalid_operator_error = register_class_InvalidOperatorError(zend_ce_type_error); + zend_init_exception_class_entry(zend_ce_invalid_operator_error); + zend_ce_argument_count_error = register_class_ArgumentCountError(zend_ce_type_error); zend_init_exception_class_entry(zend_ce_argument_count_error); diff --git a/Zend/zend_exceptions.h b/Zend/zend_exceptions.h index 7ef9ef016393..4bd6970fd0cc 100644 --- a/Zend/zend_exceptions.h +++ b/Zend/zend_exceptions.h @@ -32,6 +32,7 @@ extern ZEND_API zend_class_entry *zend_ce_error; extern ZEND_API zend_class_entry *zend_ce_compile_error; extern ZEND_API zend_class_entry *zend_ce_parse_error; extern ZEND_API zend_class_entry *zend_ce_type_error; +extern ZEND_API zend_class_entry *zend_ce_invalid_operator_error; extern ZEND_API zend_class_entry *zend_ce_argument_count_error; extern ZEND_API zend_class_entry *zend_ce_value_error; extern ZEND_API zend_class_entry *zend_ce_arithmetic_error; diff --git a/Zend/zend_exceptions.stub.php b/Zend/zend_exceptions.stub.php index 86f2838ee912..5eafe293e537 100644 --- a/Zend/zend_exceptions.stub.php +++ b/Zend/zend_exceptions.stub.php @@ -151,6 +151,10 @@ class TypeError extends Error { } +class InvalidOperatorError extends TypeError +{ +} + class ArgumentCountError extends TypeError { } diff --git a/Zend/zend_exceptions_arginfo.h b/Zend/zend_exceptions_arginfo.h index 4706161a09af..522a9d2fbe33 100644 --- a/Zend/zend_exceptions_arginfo.h +++ b/Zend/zend_exceptions_arginfo.h @@ -1,5 +1,5 @@ /* This is a generated file, edit zend_exceptions.stub.php instead. - * Stub hash: ba1562ca8fe2fe48c40bc52d10545aa989afd86c */ + * Stub hash: 01021fe977b76c5e766597d16f28220824b1bc97 */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Throwable_getMessage, 0, 0, IS_STRING, 0) ZEND_END_ARG_INFO() @@ -277,6 +277,16 @@ static zend_class_entry *register_class_TypeError(zend_class_entry *class_entry_ return class_entry; } +static zend_class_entry *register_class_InvalidOperatorError(zend_class_entry *class_entry_TypeError) +{ + zend_class_entry ce, *class_entry; + + INIT_CLASS_ENTRY(ce, "InvalidOperatorError", NULL); + class_entry = zend_register_internal_class_with_flags(&ce, class_entry_TypeError, 0); + + return class_entry; +} + static zend_class_entry *register_class_ArgumentCountError(zend_class_entry *class_entry_TypeError) { zend_class_entry ce, *class_entry; diff --git a/Zend/zend_inheritance.c b/Zend/zend_inheritance.c index 9e9e247faefd..a3d02a8b0868 100644 --- a/Zend/zend_inheritance.c +++ b/Zend/zend_inheritance.c @@ -3542,6 +3542,198 @@ static zend_class_entry *zend_lazy_class_load(const zend_class_entry *pce) } while (0) #endif +static bool zend_is_operator_method_name(const zend_string *lcname) +{ + return zend_string_equals_literal(lcname, "__add") + || zend_string_equals_literal(lcname, "__sub") + || zend_string_equals_literal(lcname, "__mul") + || zend_string_equals_literal(lcname, "__div") + || zend_string_equals_literal(lcname, "__mod") + || zend_string_equals_literal(lcname, "__pow"); +} + +static bool zend_validate_operator_param_type(zend_type type) +{ + if (!ZEND_TYPE_IS_SET(type)) { + return false; + } + + if (ZEND_TYPE_IS_ITERABLE_FALLBACK(type)) { + return false; + } + + /* Reject nullability (?T or T|null) and any disallowed primitive mask. + * Only int (MAY_BE_LONG) and float (MAY_BE_DOUBLE) are allowed as primitives. */ + uint32_t mask = ZEND_TYPE_PURE_MASK(type); + if (mask & ~(MAY_BE_LONG | MAY_BE_DOUBLE)) { + return false; + } + + /* Handle union and intersection (DNF) types recursively */ + if (ZEND_TYPE_HAS_LIST(type)) { + const zend_type *list_type; + ZEND_TYPE_LIST_FOREACH(ZEND_TYPE_LIST(type), list_type) { + if (!zend_validate_operator_param_type(*list_type)) { + return false; + } + } ZEND_TYPE_LIST_FOREACH_END(); + return true; + } + + /* If it has a class/interface name (including self/parent), it's valid + * as long as it isn't "iterable" (which is a mask) or disallowed. */ + if (ZEND_TYPE_HAS_NAME(type)) { + return true; + } + + /* Otherwise it must be a non-empty allowed primitive mask (int / float). */ + return mask != 0; +} + +static bool zend_is_exact_operand_side_type(zend_type type) +{ + if (!ZEND_TYPE_IS_SET(type) + || ZEND_TYPE_ALLOW_NULL(type) + || ZEND_TYPE_HAS_LIST(type) + || ZEND_TYPE_PURE_MASK(type) != 0 + || !ZEND_TYPE_HAS_NAME(type)) { + return false; + } + + return zend_string_equals_literal_ci(ZEND_TYPE_NAME(type), "OperandSide"); +} + +static void zend_validate_operable_class(zend_class_entry *ce) +{ + if (!instanceof_function(ce, zend_ce_operable)) { + return; + } + + /* Enums cannot implement Operable */ + if (ce->ce_flags & ZEND_ACC_ENUM) { + zend_error_noreturn(E_COMPILE_ERROR, + "Enum %s cannot implement Operable", + ZSTR_VAL(ce->name)); + } + + /* Non-interface classes must be declared readonly */ + if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && !(ce->ce_flags & ZEND_ACC_READONLY_CLASS)) { + zend_error_noreturn(E_COMPILE_ERROR, + "Class %s implements Operable and must be declared readonly", + ZSTR_VAL(ce->name)); + } + + zend_string *lcname; + zend_function *fn; + ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&ce->function_table, lcname, fn) { + if (!zend_is_operator_method_name(lcname)) { + continue; + } + + /* Skip methods already validated on an Operable ancestor */ + if (fn->common.scope != ce && instanceof_function(fn->common.scope, zend_ce_operable)) { + continue; + } + + /* Must be public and non-static */ + if (!(fn->common.fn_flags & ZEND_ACC_PUBLIC) || (fn->common.fn_flags & ZEND_ACC_STATIC)) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() must be public and non-static", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + /* Cannot return by reference */ + if (fn->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() cannot return by reference", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + /* Parameter count: 1 or 2, no variadics, no default values, no pass-by-reference */ + if (fn->common.fn_flags & ZEND_ACC_VARIADIC) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() cannot be variadic", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + if (fn->common.num_args < 1 || fn->common.num_args > 2) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() must take 1 or 2 parameters", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + if (fn->common.required_num_args != fn->common.num_args) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() parameters cannot have default values", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + for (uint32_t i = 0; i < fn->common.num_args; i++) { + if (ZEND_ARG_SEND_MODE(&fn->common.arg_info[i]) != ZEND_SEND_BY_VAL) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() parameters cannot be passed by reference", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + } + + /* Validate first parameter type */ + zend_arg_info *arg1 = &fn->common.arg_info[0]; + if (!ZEND_TYPE_IS_SET(arg1->type)) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() must declare a parameter type", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + if (!zend_validate_operator_param_type(arg1->type)) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() has an unsupported operand parameter type", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + /* Validate optional second parameter (must be exactly OperandSide) */ + if (fn->common.num_args == 2) { + zend_arg_info *arg2 = &fn->common.arg_info[1]; + if (!zend_is_exact_operand_side_type(arg2->type)) { + zend_error_noreturn(E_COMPILE_ERROR, + "The second parameter of operator method %s::%s() must be OperandSide", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + } + + /* Validate return type (required; void, never, and mixed are rejected) */ + if (!(fn->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() must declare a return type", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + zend_type ret_type = fn->common.arg_info[-1].type; + uint32_t ret_mask = ZEND_TYPE_PURE_MASK(ret_type); + if (ret_mask == MAY_BE_ANY || (ret_mask & (MAY_BE_VOID | MAY_BE_NEVER))) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() cannot return void, never, or mixed", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } + + /* Concrete operator methods must be declared final unless the class + * itself is final. */ + if (!(ce->ce_flags & ZEND_ACC_FINAL) + && !(fn->common.fn_flags & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL))) { + if (fn->common.scope == ce) { + zend_error_noreturn(E_COMPILE_ERROR, + "Operator method %s::%s() on non-final class must be declared final", + ZSTR_VAL(ce->name), ZSTR_VAL(fn->common.function_name)); + } else { + zend_error_noreturn(E_COMPILE_ERROR, + "Operable class %s cannot inherit non-final operator method %s::%s()", + ZSTR_VAL(ce->name), + ZSTR_VAL(fn->common.scope->name), + ZSTR_VAL(fn->common.function_name)); + } + } + } ZEND_HASH_FOREACH_END(); +} + ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, const zend_string *key) /* {{{ */ { /* Load parent/interface dependencies first, so we can still gracefully abort linking @@ -3760,6 +3952,7 @@ ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string if (ce->ce_flags & ZEND_ACC_ENUM) { zend_verify_enum(ce); } + zend_validate_operable_class(ce); if (ce->num_hooked_prop_variance_checks) { const zend_property_info *prop_info; ZEND_HASH_MAP_FOREACH_PTR(&ce->properties_info, prop_info) { @@ -4042,6 +4235,7 @@ ZEND_API zend_class_entry *zend_try_early_bind(zend_class_entry *ce, zend_class_ if ((ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_INTERFACE|ZEND_ACC_TRAIT|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) == ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { zend_verify_abstract_class(ce); } + zend_validate_operable_class(ce); zend_inheritance_check_override(ce); ZEND_ASSERT(!(ce->ce_flags & ZEND_ACC_UNRESOLVED_VARIANCE)); ce->ce_flags |= ZEND_ACC_LINKED; diff --git a/Zend/zend_interfaces.c b/Zend/zend_interfaces.c index b93b8f223b55..5bbc1cc79fca 100644 --- a/Zend/zend_interfaces.c +++ b/Zend/zend_interfaces.c @@ -19,6 +19,7 @@ #include "zend_API.h" #include "zend_interfaces.h" #include "zend_exceptions.h" +#include "zend_enum.h" #include "zend_interfaces_arginfo.h" #include "zend_property_hooks.h" @@ -30,6 +31,8 @@ ZEND_API zend_class_entry *zend_ce_serializable; ZEND_API zend_class_entry *zend_ce_countable; ZEND_API zend_class_entry *zend_ce_stringable; ZEND_API zend_class_entry *zend_ce_internal_iterator; +ZEND_API zend_class_entry *zend_ce_operable; +ZEND_API zend_class_entry *zend_ce_operand_side; static zend_object_handlers zend_internal_iterator_handlers; @@ -669,5 +672,14 @@ ZEND_API void zend_register_interfaces(void) sizeof(zend_object_handlers)); zend_internal_iterator_handlers.clone_obj = NULL; zend_internal_iterator_handlers.free_obj = zend_internal_iterator_free; + + zend_ce_operable = register_class_Operable(); +} +/* }}} */ + +/* {{{ zend_register_operand_side_ce */ +ZEND_API void zend_register_operand_side_ce(void) +{ + zend_ce_operand_side = register_class_OperandSide(); } /* }}} */ diff --git a/Zend/zend_interfaces.h b/Zend/zend_interfaces.h index 3aeac4fc8146..9839b3debd8e 100644 --- a/Zend/zend_interfaces.h +++ b/Zend/zend_interfaces.h @@ -30,6 +30,13 @@ extern ZEND_API zend_class_entry *zend_ce_arrayaccess; extern ZEND_API zend_class_entry *zend_ce_serializable; extern ZEND_API zend_class_entry *zend_ce_countable; extern ZEND_API zend_class_entry *zend_ce_stringable; +extern ZEND_API zend_class_entry *zend_ce_operable; +extern ZEND_API zend_class_entry *zend_ce_operand_side; + +typedef enum _zend_enum_OperandSide { + ZEND_ENUM_OperandSide_Left = 1, + ZEND_ENUM_OperandSide_Right = 2, +} zend_enum_OperandSide; typedef struct _zend_user_iterator { zend_object_iterator it; @@ -69,6 +76,7 @@ ZEND_API void zend_user_it_new_iterator(zend_class_entry *ce, zval *object, zval ZEND_API zend_object_iterator *zend_user_it_get_new_iterator(zend_class_entry *ce, zval *object, int by_ref); ZEND_API void zend_register_interfaces(void); +ZEND_API void zend_register_operand_side_ce(void); ZEND_API int zend_user_serialize(zval *object, unsigned char **buffer, size_t *buf_len, zend_serialize_data *data); ZEND_API int zend_user_unserialize(zval *object, zend_class_entry *ce, const unsigned char *buf, size_t buf_len, zend_unserialize_data *data); diff --git a/Zend/zend_interfaces.stub.php b/Zend/zend_interfaces.stub.php index 2247205e4697..92bdecca1583 100644 --- a/Zend/zend_interfaces.stub.php +++ b/Zend/zend_interfaces.stub.php @@ -83,3 +83,13 @@ public function valid(): bool {} public function rewind(): void {} } + +interface Operable +{ +} + +enum OperandSide +{ + case Left; + case Right; +} diff --git a/Zend/zend_interfaces_arginfo.h b/Zend/zend_interfaces_arginfo.h index 836313e4f41b..13a9ec3de0ea 100644 --- a/Zend/zend_interfaces_arginfo.h +++ b/Zend/zend_interfaces_arginfo.h @@ -1,5 +1,7 @@ /* This is a generated file, edit zend_interfaces.stub.php instead. - * Stub hash: a9c915c11e5989d8c7cf2d704ada09ca765670c3 */ + * Stub hash: 4dcee781316829a529450db6f7e2c3028d03d816 */ + +#include "zend_enum.h" ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_OBJ_INFO_EX(arginfo_class_IteratorAggregate_getIterator, 0, 0, Traversable, 0) ZEND_END_ARG_INFO() @@ -199,3 +201,24 @@ static zend_class_entry *register_class_InternalIterator(zend_class_entry *class return class_entry; } + +static zend_class_entry *register_class_Operable(void) +{ + zend_class_entry ce, *class_entry; + + INIT_CLASS_ENTRY(ce, "Operable", NULL); + class_entry = zend_register_internal_interface(&ce); + + return class_entry; +} + +static zend_class_entry *register_class_OperandSide(void) +{ + zend_class_entry *class_entry = zend_register_internal_enum("OperandSide", IS_UNDEF, NULL); + + zend_enum_add_case_cstr(class_entry, "Left", NULL); + + zend_enum_add_case_cstr(class_entry, "Right", NULL); + + return class_entry; +} diff --git a/Zend/zend_operators.c b/Zend/zend_operators.c index 00fb66ced5fa..800d84797ddd 100644 --- a/Zend/zend_operators.c +++ b/Zend/zend_operators.c @@ -28,6 +28,8 @@ #include "zend_strtod.h" #include "zend_exceptions.h" #include "zend_closures.h" +#include "zend_interfaces.h" +#include "zend_enum.h" #include #ifdef HAVE_LANGINFO_H @@ -1182,16 +1184,267 @@ ZEND_API zend_string* ZEND_FASTCALL zval_try_get_string_func(const zval *op) /* } /* }}} */ +static bool zend_is_arithmetic_operator_str(const char *operator) +{ + switch (operator[0]) { + case '+': + case '-': + case '/': + case '%': + return operator[1] == '\0'; + case '*': + return operator[1] == '\0' || (operator[1] == '*' && operator[2] == '\0'); + default: + return false; + } +} + +static bool zend_is_operable_zval(const zval *zv) +{ + if (Z_ISREF_P(zv)) { + zv = Z_REFVAL_P(zv); + } + return Z_TYPE_P(zv) == IS_OBJECT && instanceof_function(Z_OBJCE_P(zv), zend_ce_operable); +} + static ZEND_COLD zend_never_inline void ZEND_FASTCALL zend_binop_error(const char *operator, const zval *op1, const zval *op2) /* {{{ */ { if (EG(exception)) { return; } - zend_type_error("Unsupported operand types: %s %s %s", - zend_zval_type_name(op1), operator, zend_zval_type_name(op2)); + if (zend_is_arithmetic_operator_str(operator) + && (zend_is_operable_zval(op1) || zend_is_operable_zval(op2))) { + zend_throw_error(zend_ce_invalid_operator_error, + "Unsupported operand types: %s %s %s", + zend_zval_type_name(op1), operator, zend_zval_type_name(op2)); + } else { + zend_type_error("Unsupported operand types: %s %s %s", + zend_zval_type_name(op1), operator, zend_zval_type_name(op2)); + } } /* }}} */ +static const char *zend_operable_method_name(uint8_t opcode, size_t *len) +{ + switch (opcode) { + case ZEND_ADD: *len = sizeof("__add") - 1; return "__add"; + case ZEND_SUB: *len = sizeof("__sub") - 1; return "__sub"; + case ZEND_MUL: *len = sizeof("__mul") - 1; return "__mul"; + case ZEND_DIV: *len = sizeof("__div") - 1; return "__div"; + case ZEND_MOD: *len = sizeof("__mod") - 1; return "__mod"; + case ZEND_POW: *len = sizeof("__pow") - 1; return "__pow"; + default: return NULL; + } +} + +static zend_always_inline zend_class_entry *zend_operable_resolve_ce( + zend_string *name, zend_class_entry *scope) +{ + if (EXPECTED(ZSTR_HAS_CE_CACHE(name))) { + zend_class_entry *ce = ZSTR_GET_CE_CACHE(name); + if (EXPECTED(ce != NULL)) { + return ce; + } + } + + if (zend_string_equals_ci(name, ZSTR_KNOWN(ZEND_STR_SELF))) { + return scope; + } + if (zend_string_equals_ci(name, ZSTR_KNOWN(ZEND_STR_PARENT))) { + return scope->parent; + } + + /* Stack-allocated lowercase lookup avoids emalloc/efree on hot paths + * (e.g. permanent interned names without a CE cache slot, or unloaded + * classes in a union type). */ + size_t len = ZSTR_LEN(name); + if (UNEXPECTED(len == 0)) { + return NULL; + } + const char *str = ZSTR_VAL(name); + if (UNEXPECTED(str[0] == '\\')) { + if (len == 1) { + return NULL; + } + str++; + len--; + } + + char lc_buf[256]; + if (EXPECTED(len < sizeof(lc_buf))) { + zend_str_tolower_copy(lc_buf, str, len); + zend_class_entry *ce = zend_hash_str_find_ptr(EG(class_table), lc_buf, len); + if (ce) { + if (UNEXPECTED(!(ce->ce_flags & ZEND_ACC_LINKED))) { + return NULL; + } + if (ZSTR_HAS_CE_CACHE(name) && ZSTR_VALID_CE_CACHE(name) + && (!CG(in_compilation) || (ce->ce_flags & ZEND_ACC_IMMUTABLE))) { + ZSTR_SET_CE_CACHE(name, ce); + } + } + return ce; + } + + return zend_lookup_class_ex(name, NULL, ZEND_FETCH_CLASS_NO_AUTOLOAD); +} + +static bool zend_operable_type_accepts(zend_type type, zend_class_entry *scope, const zval *arg) +{ + if (ZEND_TYPE_IS_INTERSECTION(type)) { + const zend_type *list_type; + ZEND_TYPE_LIST_FOREACH(ZEND_TYPE_LIST(type), list_type) { + if (!zend_operable_type_accepts(*list_type, scope, arg)) { + return false; + } + } ZEND_TYPE_LIST_FOREACH_END(); + return true; + } + + uint32_t mask = ZEND_TYPE_PURE_MASK(type); + if (Z_TYPE_P(arg) == IS_LONG) { + /* Under strict_types=1, int satisfies both int and float */ + if ((mask & (MAY_BE_LONG | MAY_BE_DOUBLE)) != 0) { + return true; + } + } else if (Z_TYPE_P(arg) == IS_DOUBLE) { + if ((mask & MAY_BE_DOUBLE) != 0) { + return true; + } + } + + if (Z_TYPE_P(arg) != IS_OBJECT) { + return false; + } + + if (ZEND_TYPE_HAS_LIST(type)) { + const zend_type *list_type; + ZEND_TYPE_LIST_FOREACH(ZEND_TYPE_LIST(type), list_type) { + if (zend_operable_type_accepts(*list_type, scope, arg)) { + return true; + } + } ZEND_TYPE_LIST_FOREACH_END(); + return false; + } + + if (ZEND_TYPE_HAS_NAME(type)) { + zend_string *name = ZEND_TYPE_NAME(type); + zend_class_entry *arg_ce = Z_OBJCE_P(arg); + if (EXPECTED(arg_ce->name == name)) { + return true; + } + zend_class_entry *target_ce = zend_operable_resolve_ce(name, scope); + return target_ce != NULL && instanceof_function(arg_ce, target_ce); + } + + return false; +} + +static zend_function *zend_operable_find_method( + zend_object *obj, const char *method_name, size_t method_len, + const zval *other, bool require_side, bool allow_commutative_swap) +{ + if (!instanceof_function(obj->ce, zend_ce_operable)) { + return NULL; + } + + zend_function *fn = zend_hash_str_find_ptr(&obj->ce->function_table, method_name, method_len); + if (!fn) { + return NULL; + } + + if (require_side && fn->common.num_args != 2) { + if (!allow_commutative_swap || fn->common.num_args != 1) { + return NULL; + } + } + + if (!zend_operable_type_accepts(fn->common.arg_info[0].type, fn->common.scope, other)) { + return NULL; + } + + return fn; +} + +/* + * Returns: + * 1 if an Operable method was dispatched (result is populated, or EG(exception) is set) + * 0 if no Operable method matched (caller should fall through to internal handlers / error) + */ +static int zend_try_operable_binary_op(uint8_t opcode, zval *result, zval *op1, zval *op2) +{ + if (Z_TYPE_P(op1) != IS_OBJECT && Z_TYPE_P(op2) != IS_OBJECT) { + return 0; + } + + size_t method_len = 0; + const char *method_name = zend_operable_method_name(opcode, &method_len); + if (!method_name) { + return 0; + } + + zend_object *target = NULL; + zend_function *fn = NULL; + zval *other = NULL; + bool is_right = false; + + /* Step 2: Left operand (Operable) */ + if (Z_TYPE_P(op1) == IS_OBJECT) { + fn = zend_operable_find_method(Z_OBJ_P(op1), method_name, method_len, op2, false, false); + if (fn) { + target = Z_OBJ_P(op1); + other = op2; + is_right = false; + } + } + + /* Step 3 & 4: Right operand (Operable with OperandSide, or commutative swap for + and * only) */ + if (!fn && Z_TYPE_P(op2) == IS_OBJECT) { + bool allow_commutative = (opcode == ZEND_ADD || opcode == ZEND_MUL); + fn = zend_operable_find_method(Z_OBJ_P(op2), method_name, method_len, op1, true, allow_commutative); + if (fn) { + target = Z_OBJ_P(op2); + other = op1; + is_right = true; + } + } + + if (!fn) { + return 0; + } + + zval params[2]; + uint32_t param_count = 1; + ZVAL_COPY_VALUE(¶ms[0], other); + + if (fn->common.num_args == 2) { + zend_object *side_obj = zend_enum_get_case_by_id( + zend_ce_operand_side, is_right ? ZEND_ENUM_OperandSide_Right : ZEND_ENUM_OperandSide_Left); + ZVAL_OBJ(¶ms[1], side_obj); + param_count = 2; + } + + zval retval; + ZVAL_UNDEF(&retval); + zend_call_known_instance_method(fn, target, &retval, param_count, params); + + if (EG(exception)) { + zval_ptr_dtor(&retval); + if (result != op1 && result != op2) { + ZVAL_UNDEF(result); + } + return 1; + } + + ZEND_ASSERT(!Z_ISREF(retval)); + + if (result == op1 || result == op2) { + zval_ptr_dtor(result); + } + ZVAL_COPY_VALUE(result, &retval); + return 1; +} + static zend_never_inline void ZEND_FASTCALL add_function_array(zval *result, const zval *op1, const zval *op2) /* {{{ */ { if (result == op1 && Z_ARR_P(op1) == Z_ARR_P(op2)) { @@ -1239,6 +1492,10 @@ static zend_never_inline zend_result ZEND_FASTCALL add_function_slow(zval *resul return SUCCESS; } + if (zend_try_operable_binary_op(ZEND_ADD, result, op1, op2)) { + return EG(exception) ? FAILURE : SUCCESS; + } + ZEND_TRY_BINARY_OBJECT_OPERATION(ZEND_ADD); zval op1_copy, op2_copy; @@ -1303,6 +1560,10 @@ static zend_never_inline zend_result ZEND_FASTCALL sub_function_slow(zval *resul return SUCCESS; } + if (zend_try_operable_binary_op(ZEND_SUB, result, op1, op2)) { + return EG(exception) ? FAILURE : SUCCESS; + } + ZEND_TRY_BINARY_OBJECT_OPERATION(ZEND_SUB); zval op1_copy, op2_copy; @@ -1372,6 +1633,10 @@ static zend_never_inline zend_result ZEND_FASTCALL mul_function_slow(zval *resul return SUCCESS; } + if (zend_try_operable_binary_op(ZEND_MUL, result, op1, op2)) { + return EG(exception) ? FAILURE : SUCCESS; + } + ZEND_TRY_BINARY_OBJECT_OPERATION(ZEND_MUL); zval op1_copy, op2_copy; @@ -1486,6 +1751,10 @@ ZEND_API zend_result ZEND_FASTCALL pow_function(zval *result, zval *op1, zval *o return SUCCESS; } + if (zend_try_operable_binary_op(ZEND_POW, result, op1, op2)) { + return EG(exception) ? FAILURE : SUCCESS; + } + ZEND_TRY_BINARY_OBJECT_OPERATION(ZEND_POW); zval op1_copy, op2_copy; @@ -1573,6 +1842,10 @@ ZEND_API zend_result ZEND_FASTCALL div_function(zval *result, zval *op1, zval *o goto div_by_zero; } + if (zend_try_operable_binary_op(ZEND_DIV, result, op1, op2)) { + return EG(exception) ? FAILURE : SUCCESS; + } + ZEND_TRY_BINARY_OBJECT_OPERATION(ZEND_DIV); zval result_copy, op1_copy, op2_copy; @@ -1608,6 +1881,14 @@ ZEND_API zend_result ZEND_FASTCALL mod_function(zval *result, zval *op1, zval *o { zend_long op1_lval, op2_lval; + if (UNEXPECTED(Z_TYPE_P(op1) != IS_LONG || Z_TYPE_P(op2) != IS_LONG)) { + ZVAL_DEREF(op1); + ZVAL_DEREF(op2); + if (zend_try_operable_binary_op(ZEND_MOD, result, op1, op2)) { + return EG(exception) ? FAILURE : SUCCESS; + } + } + convert_op1_op2_long(op1, op1_lval, op2, op2_lval, result, ZEND_MOD, "%"); if (op2_lval == 0) { diff --git a/ext/reflection/php_reflection.c b/ext/reflection/php_reflection.c index de814d9cf66c..0751b94b366e 100644 --- a/ext/reflection/php_reflection.c +++ b/ext/reflection/php_reflection.c @@ -3698,6 +3698,48 @@ ZEND_METHOD(ReflectionMethod, isDestructor) } /* }}} */ +typedef struct _reflection_operator_entry { + const char *symbol; + size_t symbol_len; + const char *method; + size_t method_len; +} reflection_operator_entry; + +static const reflection_operator_entry reflection_operator_table[] = { + { "+", sizeof("+") - 1, "__add", sizeof("__add") - 1 }, + { "-", sizeof("-") - 1, "__sub", sizeof("__sub") - 1 }, + { "*", sizeof("*") - 1, "__mul", sizeof("__mul") - 1 }, + { "/", sizeof("/") - 1, "__div", sizeof("__div") - 1 }, + { "%", sizeof("%") - 1, "__mod", sizeof("__mod") - 1 }, + { "**", sizeof("**") - 1, "__pow", sizeof("__pow") - 1 }, +}; + +/* {{{ Returns whether this method is a typed operator method on an Operable class */ +ZEND_METHOD(ReflectionMethod, isOperatorMethod) +{ + const reflection_object *intern; + const zend_function *mptr; + + ZEND_PARSE_PARAMETERS_NONE(); + + GET_REFLECTION_OBJECT_PTR(mptr); + + if (!intern->ce || !instanceof_function(intern->ce, zend_ce_operable)) { + RETURN_FALSE; + } + + for (size_t i = 0; i < sizeof(reflection_operator_table) / sizeof(reflection_operator_table[0]); i++) { + if (zend_binary_strcasecmp( + ZSTR_VAL(mptr->common.function_name), ZSTR_LEN(mptr->common.function_name), + reflection_operator_table[i].method, reflection_operator_table[i].method_len) == 0) { + RETURN_TRUE; + } + } + + RETURN_FALSE; +} +/* }}} */ + /* {{{ Returns a bitfield of the modifiers for this method */ ZEND_METHOD(ReflectionMethod, getModifiers) { @@ -4543,6 +4585,42 @@ ZEND_METHOD(ReflectionClass, getMethods) } /* }}} */ +/* {{{ Returns an associative array of operator symbol => ReflectionMethod for Operable classes */ +ZEND_METHOD(ReflectionClass, getOperatorMethods) +{ + const reflection_object *intern; + zend_class_entry *ce; + + ZEND_PARSE_PARAMETERS_NONE(); + + GET_REFLECTION_OBJECT_PTR(ce); + + array_init(return_value); + + if (!instanceof_function(ce, zend_ce_operable)) { + return; + } + + for (size_t i = 0; i < sizeof(reflection_operator_table) / sizeof(reflection_operator_table[0]); i++) { + zend_function *mptr = zend_hash_str_find_ptr( + &ce->function_table, + reflection_operator_table[i].method, + reflection_operator_table[i].method_len + ); + if (mptr) { + zval method; + reflection_method_factory(ce, mptr, NULL, &method); + add_assoc_zval_ex( + return_value, + reflection_operator_table[i].symbol, + reflection_operator_table[i].symbol_len, + &method + ); + } + } +} +/* }}} */ + /* {{{ Returns whether a property exists or not */ ZEND_METHOD(ReflectionClass, hasProperty) { diff --git a/ext/reflection/php_reflection.stub.php b/ext/reflection/php_reflection.stub.php index b55978cd1df3..41d56838cb50 100644 --- a/ext/reflection/php_reflection.stub.php +++ b/ext/reflection/php_reflection.stub.php @@ -208,6 +208,8 @@ public function isConstructor(): bool {} /** @tentative-return-type */ public function isDestructor(): bool {} + public function isOperatorMethod(): bool {} + /** @tentative-return-type */ public function getClosure(?object $object = null): Closure {} @@ -304,6 +306,11 @@ public function getMethod(string $name): ReflectionMethod {} /** @tentative-return-type */ public function getMethods(?int $filter = null): array {} + /** + * @return array + */ + public function getOperatorMethods(): array {} + /** @tentative-return-type */ public function hasProperty(string $name): bool {} diff --git a/ext/reflection/php_reflection_arginfo.h b/ext/reflection/php_reflection_arginfo.h index eafbc9c0bd21..3291d2a2db95 100644 --- a/ext/reflection/php_reflection_arginfo.h +++ b/ext/reflection/php_reflection_arginfo.h @@ -1,5 +1,5 @@ /* This is a generated file, edit php_reflection.stub.php instead. - * Stub hash: 6191049a28b4c5fe134fc37cd8969a33d00c51de + * Stub hash: cbacf073a62000559d3828eb28951cd729d25b1e * Has decl header: yes */ #include "zend_attributes.h" @@ -161,6 +161,8 @@ ZEND_END_ARG_INFO() #define arginfo_class_ReflectionMethod_isDestructor arginfo_class_ReflectionFunctionAbstract_inNamespace +#define arginfo_class_ReflectionMethod_isOperatorMethod arginfo_class_ReflectionFunctionAbstract_hasTentativeReturnType + ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_OBJ_INFO_EX(arginfo_class_ReflectionMethod_getClosure, 0, 0, Closure, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, object, IS_OBJECT, 1, "null") ZEND_END_ARG_INFO() @@ -232,6 +234,8 @@ ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_TYPE_INFO_EX(arginfo_class_ReflectionClass_ ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, filter, IS_LONG, 1, "null") ZEND_END_ARG_INFO() +#define arginfo_class_ReflectionClass_getOperatorMethods arginfo_class_ReflectionFunctionAbstract_getClosureUsedVariables + #define arginfo_class_ReflectionClass_hasProperty arginfo_class_ReflectionClass_hasMethod ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_OBJ_INFO_EX(arginfo_class_ReflectionClass_getProperty, 0, 1, ReflectionProperty, 0) @@ -802,6 +806,7 @@ ZEND_METHOD(ReflectionMethod, isAbstract); ZEND_METHOD(ReflectionMethod, isFinal); ZEND_METHOD(ReflectionMethod, isConstructor); ZEND_METHOD(ReflectionMethod, isDestructor); +ZEND_METHOD(ReflectionMethod, isOperatorMethod); ZEND_METHOD(ReflectionMethod, getClosure); ZEND_METHOD(ReflectionMethod, getModifiers); ZEND_METHOD(ReflectionMethod, invoke); @@ -826,6 +831,7 @@ ZEND_METHOD(ReflectionClass, getConstructor); ZEND_METHOD(ReflectionClass, hasMethod); ZEND_METHOD(ReflectionClass, getMethod); ZEND_METHOD(ReflectionClass, getMethods); +ZEND_METHOD(ReflectionClass, getOperatorMethods); ZEND_METHOD(ReflectionClass, hasProperty); ZEND_METHOD(ReflectionClass, getProperty); ZEND_METHOD(ReflectionClass, getProperties); @@ -1097,6 +1103,7 @@ static const zend_function_entry class_ReflectionMethod_methods[] = { ZEND_ME(ReflectionMethod, isFinal, arginfo_class_ReflectionMethod_isFinal, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionMethod, isConstructor, arginfo_class_ReflectionMethod_isConstructor, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionMethod, isDestructor, arginfo_class_ReflectionMethod_isDestructor, ZEND_ACC_PUBLIC) + ZEND_ME(ReflectionMethod, isOperatorMethod, arginfo_class_ReflectionMethod_isOperatorMethod, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionMethod, getClosure, arginfo_class_ReflectionMethod_getClosure, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionMethod, getModifiers, arginfo_class_ReflectionMethod_getModifiers, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionMethod, invoke, arginfo_class_ReflectionMethod_invoke, ZEND_ACC_PUBLIC) @@ -1126,6 +1133,7 @@ static const zend_function_entry class_ReflectionClass_methods[] = { ZEND_ME(ReflectionClass, hasMethod, arginfo_class_ReflectionClass_hasMethod, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionClass, getMethod, arginfo_class_ReflectionClass_getMethod, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionClass, getMethods, arginfo_class_ReflectionClass_getMethods, ZEND_ACC_PUBLIC) + ZEND_ME(ReflectionClass, getOperatorMethods, arginfo_class_ReflectionClass_getOperatorMethods, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionClass, hasProperty, arginfo_class_ReflectionClass_hasProperty, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionClass, getProperty, arginfo_class_ReflectionClass_getProperty, ZEND_ACC_PUBLIC) ZEND_ME(ReflectionClass, getProperties, arginfo_class_ReflectionClass_getProperties, ZEND_ACC_PUBLIC) diff --git a/ext/reflection/php_reflection_decl.h b/ext/reflection/php_reflection_decl.h index e58dce51b39c..f772999a1082 100644 --- a/ext/reflection/php_reflection_decl.h +++ b/ext/reflection/php_reflection_decl.h @@ -1,12 +1,12 @@ /* This is a generated file, edit php_reflection.stub.php instead. - * Stub hash: 6191049a28b4c5fe134fc37cd8969a33d00c51de */ + * Stub hash: cbacf073a62000559d3828eb28951cd729d25b1e */ -#ifndef ZEND_PHP_REFLECTION_DECL_6191049a28b4c5fe134fc37cd8969a33d00c51de_H -#define ZEND_PHP_REFLECTION_DECL_6191049a28b4c5fe134fc37cd8969a33d00c51de_H +#ifndef ZEND_PHP_REFLECTION_DECL_cbacf073a62000559d3828eb28951cd729d25b1e_H +#define ZEND_PHP_REFLECTION_DECL_cbacf073a62000559d3828eb28951cd729d25b1e_H typedef enum zend_enum_PropertyHookType { ZEND_ENUM_PropertyHookType_Get = 1, ZEND_ENUM_PropertyHookType_Set = 2, } zend_enum_PropertyHookType; -#endif /* ZEND_PHP_REFLECTION_DECL_6191049a28b4c5fe134fc37cd8969a33d00c51de_H */ +#endif /* ZEND_PHP_REFLECTION_DECL_cbacf073a62000559d3828eb28951cd729d25b1e_H */ diff --git a/ext/reflection/tests/ReflectionClass_toString_001.phpt b/ext/reflection/tests/ReflectionClass_toString_001.phpt index 03495847857d..0b8a9ff177ff 100644 --- a/ext/reflection/tests/ReflectionClass_toString_001.phpt +++ b/ext/reflection/tests/ReflectionClass_toString_001.phpt @@ -30,7 +30,7 @@ Class [ class ReflectionClass implements Stringable, Refle Property [ public protected(set) readonly string $name ] } - - Methods [64] { + - Methods [65] { Method [ private method __clone ] { - Parameters [0] { @@ -153,6 +153,13 @@ Class [ class ReflectionClass implements Stringable, Refle - Tentative return [ array ] } + Method [ public method getOperatorMethods ] { + + - Parameters [0] { + } + - Return [ array ] + } + Method [ public method hasProperty ] { - Parameters [1] {