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
15 changes: 13 additions & 2 deletions lib/VM.php
Original file line number Diff line number Diff line change
Expand Up @@ -1654,6 +1654,9 @@ private function runFramesInner(): int

return self::FIBER_SUSPEND;
}
$frame->call = null;
$frame->callArgs = [];
$frame->callArgEntries = [];
break;
}
$this->context->push($frame);
Expand Down Expand Up @@ -2893,7 +2896,7 @@ private function raiseUncaughtException(Variable $thrown): void
} catch (\LogicException) {
$message = 'Exception';
}
throw new \Exception($message);
throw VM\ExceptionSupport::nativeUncaughtThrowable($entry, $message);
}
throw new \Exception($thrown->toString());
}
Expand Down Expand Up @@ -3784,8 +3787,16 @@ protected function initStaticCallable(Frame $frame, string $callableName): void
if (!isset($this->context->classes[$lcClass])) {
throw new \LogicException("Call to undefined static method {$callableName}()");
}
$frame->staticCallClass = $this->context->classes[$lcClass]->name;
$class = $this->context->classes[$lcClass];
$frame->staticCallClass = $class->name;
$methodLc = strtolower($methodName);
if ($class->isEnum && null !== $class->backedType && ('from' === $methodLc || 'tryfrom' === $methodLc)) {
$frame->call = new VM\EnumFromHandler($class, 'tryfrom' === $methodLc);
$frame->callArgs = [];
$frame->callArgEntries = [];

return;
}
try {
[$class, $methodLc] = $this->resolveStaticMethod($lcClass, $methodLc);
} catch (\LogicException $e) {
Expand Down
181 changes: 181 additions & 0 deletions lib/VM/BackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php

declare(strict_types=1);

namespace PHPCompiler\VM;

/**
* BackedEnum::from / tryFrom lookup (Zend parity, #3114).
*
* @see Zend/zend_enum.c — zend_enum_from_case(), zend_try_enum_from_case()
*/
final class BackedEnum
{
public static function caseForValue(ClassEntry $enum, Variable $value): ?EnumCaseEntry
{
if (!$enum->isEnum || null === $enum->backedType) {
return null;
}
$normalized = self::normalizeBackingArgument($enum, $value->resolveIndirect());
foreach ($enum->enumCases as $case) {
$backing = $case['value'];
if (!self::backingValuesMatch($enum->backedType, $backing, $normalized)) {
continue;
}

return new EnumCaseEntry($enum, $case['name'], clone $backing);
}

return null;
}

public static function valueErrorMessage(ClassEntry $enum, Variable $value): string
{
$value = $value->resolveIndirect();
try {
$normalized = self::normalizeBackingArgument($enum, $value);
$repr = self::formatBackingRepr($enum->backedType ?? '', $normalized);
} catch (\TypeError) {
$repr = self::formatRawRepr($value);
}

return $repr.' is not a valid backing value for enum '.$enum->name;
}

private static function normalizeBackingArgument(ClassEntry $enum, Variable $arg): Variable
{
$backedType = $enum->backedType;
if ('int' === $backedType) {
return self::normalizeIntBackingArgument($enum->name, $arg);
}
if ('string' === $backedType) {
return self::normalizeStringBackingArgument($arg);
}

throw new \LogicException('Unsupported enum backing type: '.$backedType);
}

private static function normalizeIntBackingArgument(string $enumName, Variable $arg): Variable
{
$result = new Variable(Variable::TYPE_INTEGER);
switch ($arg->type) {
case Variable::TYPE_INTEGER:
$result->int($arg->toInt());

return $result;
case Variable::TYPE_FLOAT:
$float = $arg->toFloat();
if (!is_finite($float) || (float) (int) $float !== $float) {
break;
}
$result->int((int) $float);

return $result;
case Variable::TYPE_STRING:
$str = $arg->toString();
if ('' === $str || !is_numeric($str)) {
break;
}
$result->int((int) (float) $str);

return $result;
default:
break;
}

throw new \TypeError(
$enumName.'::from(): Argument #1 ($value) must be of type int, '
.self::typeLabel($arg).' given'
);
}

private static function normalizeStringBackingArgument(Variable $arg): Variable
{
$result = new Variable(Variable::TYPE_STRING);
switch ($arg->type) {
case Variable::TYPE_STRING:
$result->string($arg->toString());

return $result;
case Variable::TYPE_INTEGER:
$result->string((string) $arg->toInt());

return $result;
case Variable::TYPE_FLOAT:
$result->string((string) $arg->toFloat());

return $result;
case Variable::TYPE_BOOLEAN:
$result->string($arg->toBool() ? '1' : '0');

return $result;
case Variable::TYPE_NULL:
$result->string('');

return $result;
default:
break;
}

throw new \TypeError(
'Argument #1 ($value) must be of type string, '.self::typeLabel($arg).' given'
);
}

private static function backingValuesMatch(string $backedType, Variable $caseValue, Variable $arg): bool
{
$caseValue = $caseValue->resolveIndirect();
$arg = $arg->resolveIndirect();
if ('int' === $backedType) {
if (Variable::TYPE_INTEGER !== $caseValue->type || Variable::TYPE_INTEGER !== $arg->type) {
return false;
}

return $caseValue->toInt() === $arg->toInt();
}
if ('string' === $backedType) {
if (Variable::TYPE_STRING !== $caseValue->type || Variable::TYPE_STRING !== $arg->type) {
return false;
}

return $caseValue->toString() === $arg->toString();
}

return false;
}

private static function formatBackingRepr(string $backedType, Variable $value): string
{
if ('string' === $backedType) {
return '"'.$value->toString().'"';
}

return (string) $value->toInt();
}

private static function formatRawRepr(Variable $value): string
{
return match ($value->type) {
Variable::TYPE_STRING => '"'.$value->toString().'"',
Variable::TYPE_INTEGER => (string) $value->toInt(),
Variable::TYPE_FLOAT => (string) $value->toFloat(),
Variable::TYPE_BOOLEAN => $value->toBool() ? 'true' : 'false',
Variable::TYPE_NULL => 'null',
default => 'unknown',
};
}

private static function typeLabel(Variable $value): string
{
return match ($value->type) {
Variable::TYPE_STRING => 'string',
Variable::TYPE_INTEGER => 'int',
Variable::TYPE_FLOAT => 'float',
Variable::TYPE_BOOLEAN => 'bool',
Variable::TYPE_NULL => 'null',
Variable::TYPE_OBJECT => 'object',
Variable::TYPE_ARRAY => 'array',
default => 'mixed',
};
}
}
2 changes: 1 addition & 1 deletion lib/VM/EnumCaseEntry.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace PHPCompiler\VM;

/**
* Zend-style enum case object for E::Case fetches (#3420, #3554).
* Zend-style enum case object for E::Case fetches (#3420, #3554, #3114).
*/
final class EnumCaseEntry
{
Expand Down
53 changes: 53 additions & 0 deletions lib/VM/EnumFromHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace PHPCompiler\VM;

use PHPCompiler\Frame;
use PHPCompiler\Func\Internal;
use PHPCompiler\JIT\Context;
use PHPCompiler\JIT\Variable as JITVariable;
use PHPLLVM\Value;

/**
* VM handler for BackedEnum::from() and ::tryFrom() (#3114).
*/
final class EnumFromHandler extends Internal
{
public function __construct(
private ClassEntry $enum,
private bool $try,
) {
parent::__construct($enum->name.'::'.($try ? 'tryFrom' : 'from'));
}

public function execute(Frame $frame): void
{
if (\count($frame->calledArgs) < 1) {
throw new \LogicException(
$this->getName().'() requires exactly 1 argument in this compiler build'
);
}
$arg = $frame->calledArgs[0];
$match = BackedEnum::caseForValue($this->enum, $arg);
if (null === $match) {
if (!$this->try) {
throw new \ValueError(BackedEnum::valueErrorMessage($this->enum, $arg));
}
if (null !== $frame->returnVar) {
$frame->returnVar->null();
}

return;
}
if (null !== $frame->returnVar) {
$frame->returnVar->enumCase($match);
}
}

public function call(Context $context, JITVariable ...$args): Value
{
throw new \LogicException($this->getName().'() is not supported in JIT in this compiler build');
}
}
22 changes: 22 additions & 0 deletions lib/VM/ExceptionSupport.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,26 @@ public static function throwSiteLine(Frame $frame): int
{
return 0;
}

/**
* Map a materialized VM Throwable object to a native PHP exception for PHPUnit / uncaught exit (#3114, #195).
*/
public static function nativeUncaughtThrowable(ObjectEntry $entry, string $message): \Throwable
{
$lc = strtolower($entry->class->name);

return match ($lc) {
self::CLASS_VALUE_ERROR => new \ValueError($message),
self::CLASS_TYPE_ERROR => new \TypeError($message),
self::CLASS_DIVISION_BY_ZERO_ERROR => new \DivisionByZeroError($message),
self::CLASS_ARGUMENT_COUNT_ERROR => new \ArgumentCountError($message),
self::CLASS_PARSE_ERROR => new \ParseError($message),
self::CLASS_UNHANDLED_MATCH_ERROR => new \UnhandledMatchError($message),
self::CLASS_ASSERTION_ERROR => new \AssertionError($message),
self::CLASS_ERROR => new \Error($message),
self::CLASS_LOGIC_EXCEPTION => new \LogicException($message),
self::CLASS_EXCEPTION => new \Exception($message),
default => new \Exception($message),
};
}
}
11 changes: 11 additions & 0 deletions lib/VM/Variable.php
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,13 @@ public function copyFrom(self $var): void {
$this->streamResource = false;
$this->array = $var->array;
break;
case self::TYPE_ENUM_CASE:
$this->enumCase(new EnumCaseEntry(
$var->enumCase->enumClass,
$var->enumCase->caseName,
clone $var->enumCase->backingValue,
));
break;
default:
var_dump($var);
throw new \LogicException("Unsupported type copy: {$var->type}");
Expand Down Expand Up @@ -713,6 +720,9 @@ public function equals(Variable $other): bool {
return $self->float === $other->float;
case TYPE_PAIR_OBJECT_OBJECT:
return $self->object->looseEquals($other->object);
case TYPE_PAIR_ENUM_CASE_ENUM_CASE:
return $self->enumCase->enumClass === $other->enumCase->enumClass
&& $self->enumCase->caseName === $other->enumCase->caseName;
case TYPE_PAIR_BOOLEAN_BOOLEAN:
return $self->bool === $other->bool;
case TYPE_PAIR_NULL_NULL:
Expand Down Expand Up @@ -1423,6 +1433,7 @@ private static function byteFromAssignValue(self $value): string
const TYPE_PAIR_FLOAT_FLOAT = 514;
const TYPE_PAIR_STRING_STRING = 1028;
const TYPE_PAIR_OBJECT_OBJECT = 1285;
const TYPE_PAIR_ENUM_CASE_ENUM_CASE = 2313;
const TYPE_PAIR_BOOLEAN_BOOLEAN = 771;
const TYPE_PAIR_NULL_NULL = 0;
const TYPE_PAIR_ARRAY_ARRAY = 1542;
Expand Down
Loading