Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
8c6e0b4
Refactor type checks for arrays and mixed types in ParamChecker, Retu…
rcalicdan Dec 4, 2026
fd5b7d5
Refactor ErrorFactory and ViolationCollector to utilize PathMatcher f…
rcalicdan Dec 4, 2026
161496f
Refactor evaluators to utilize StaticTypeEvaluator for class name res…
rcalicdan Dec 4, 2026
058ea6e
Enhance cloning functionality with exception-safe binding propagation…
rcalicdan Dec 4, 2026
68953ff
Add tests for return expression evaluation order with @param-out and …
rcalicdan Dec 4, 2026
58a16af
Implement contravariance soundness tests for TemplateManager::checkVa…
rcalicdan Dec 4, 2026
b7824ea
Refactor ArrayLiteralEvaluator for key soundness; add comprehensive t…
rcalicdan Dec 4, 2026
4fd9502
Enhance ConstantAndEnumEvaluator with non-autoloading checks for cons…
rcalicdan Dec 4, 2026
dbcfa05
Add by-reference return tests for single evaluation and aliasing soun…
rcalicdan Dec 4, 2026
538fc58
Implement coalesce assignment handling in ContractVisitor; add comput…
rcalicdan Dec 4, 2026
38adb7b
Add PropertyOpcodeParityTest to validate opcode and bitmask parity be…
rcalicdan Dec 4, 2026
449f9a8
Update cache version prefix to v0.15.0
rcalicdan Dec 4, 2026
7298f6e
Enhance multiline handling in ContractVisitor and TypePHPPrinter; add…
rcalicdan Dec 4, 2026
a805928
Add support for additional scalar types and refine type resolution in…
rcalicdan Dec 4, 2026
85ba2ed
Enhance EliminationSafetyPolicy with new type checks for object gener…
rcalicdan Dec 4, 2026
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
180 changes: 150 additions & 30 deletions src/Internal/Ast/ContractVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ final class ContractVisitor extends NodeVisitorAbstract
Node\Expr\AssignOp\BitwiseXor::class => Node\Expr\BinaryOp\BitwiseXor::class,
Node\Expr\AssignOp\ShiftLeft::class => Node\Expr\BinaryOp\ShiftLeft::class,
Node\Expr\AssignOp\ShiftRight::class => Node\Expr\BinaryOp\ShiftRight::class,
Node\Expr\AssignOp\Coalesce::class => Node\Expr\BinaryOp\Coalesce::class,
];

private const BY_REF_BUILTIN_FUNCTIONS = [
Expand Down Expand Up @@ -801,38 +800,90 @@ public function enterNode(Node $n): ?int

private function wrapCloneFunction(Node\Expr\FuncCall $node): ?Node\Expr
{
if ($node->getAttribute('typephp_wrapped') === true) {
if ($node->getAttribute('typephp_wrapped') === true || $node->isFirstClassCallable()) {
return null;
}

$firstArg = $node->args[0] ?? null;
if (! $firstArg instanceof Node\Arg) {
$originalExpr = null;
$propertiesExpr = null;
$positionalIndex = 0;

foreach ($node->args as $arg) {
if (! ($arg instanceof Node\Arg) || $arg->unpack) {
return null;
}

if ($arg->name !== null) {
$argName = $arg->name->toString();
if ($argName === 'object') {
$originalExpr = $arg->value;
} elseif ($argName === 'withProperties') {
$propertiesExpr = $arg->value;
} else {
return null;
}
} else {
if ($positionalIndex === 0) {
$originalExpr = $arg->value;
} elseif ($positionalIndex === 1) {
$propertiesExpr = $arg->value;
} else {
return null;
}
$positionalIndex++;
}
}

if ($originalExpr === null) {
return null;
}

$node->setAttribute('typephp_wrapped', true);

$originalExpr = $firstArg->value;
if ($propertiesExpr === null) {
$innerClone = new Node\Expr\Clone_(new Node\Expr\Variable('__typephpCloneSrc'));
$innerClone->setAttribute('typephp_wrapped', true);

$secondArg = $node->args[1] ?? null;
$propertiesExpr = $secondArg instanceof Node\Arg
? $secondArg->value
: new Node\Expr\ConstFetch(new Node\Name('null'));
$clonerArrow = new Node\Expr\ArrowFunction([
'static' => true,
'params' => [new Node\Param(new Node\Expr\Variable('__typephpCloneSrc'))],
'expr' => $innerClone,
]);

$node->args[0] = new Node\Arg(
new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::prepareClone'),
[new Node\Arg($originalExpr)],
),
return new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::executeClone'),
[
new Node\Arg($originalExpr),
new Node\Arg($clonerArrow),
]
);
}

$innerCloneCall = new Node\Expr\FuncCall(
new Node\Name('clone'),
[
new Node\Arg(new Node\Expr\Variable('__typephpCloneSrc')),
new Node\Arg(new Node\Expr\Variable('__typephpCloneProps')),
]
);
$innerCloneCall->setAttribute('typephp_wrapped', true);

$clonerArrow = new Node\Expr\ArrowFunction([
'static' => true,
'params' => [
new Node\Param(new Node\Expr\Variable('__typephpCloneSrc')),
new Node\Param(new Node\Expr\Variable('__typephpCloneProps')),
],
'expr' => $innerCloneCall,
]);

return new Node\Expr\StaticCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker'),
'cloneWith',
'executeCloneWith',
[
new Node\Arg($node),
new Node\Arg($originalExpr),
new Node\Arg($propertiesExpr),
new Node\Arg($clonerArrow),
new Node\Arg(new Node\Scalar\MagicConst\File()),
new Node\Arg(new Node\Scalar\LNumber($node->getStartLine())),
],
Expand Down Expand Up @@ -1984,6 +2035,14 @@ private function handleAssign(Node\Expr\Assign $node): ?Node
]
);

if ($expr->getEndLine() > $expr->getStartLine() && $expr->getStartLine() > 0) {
$wrappedNew->setAttribute('typephp_multiline_call', [
'startLine' => $expr->getStartLine(),
'endLine' => $expr->getEndLine(),
'forwardedStartIndex' => 3,
]);
}

$node->expr = $this->wrapVariableCheck($wrappedNew, $typeString, $varName, $node->var->getStartLine());

return null;
Expand Down Expand Up @@ -2341,6 +2400,10 @@ private function handleForeachTypePropagation(Node\Stmt\Foreach_ $node): void

private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr
{
if ($node instanceof Node\Expr\AssignOp\Coalesce) {
return $this->handleCoalesceAssign($node);
}

$binaryOpClass = self::ASSIGN_OP_MAP[$node::class] ?? null;
if ($binaryOpClass === null) {
return null;
Expand Down Expand Up @@ -2379,6 +2442,55 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr
return new Node\Expr\Assign($node->var, $wrapped);
}

private function handleCoalesceAssign(Node\Expr\AssignOp\Coalesce $node): ?Node\Expr
{
$isStandalone = $node->getAttribute('typephp_is_standalone') === true;
$line = $node->var->getStartLine();

if ($this->targetHasSideEffects($node->var)) {
$preAssignments = [];
$cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments);
$wrappedRhs = $this->wrapTargetMutation(clone $cleanTarget, $node->expr, $line);

if ($wrappedRhs === null) {
return null;
}

$this->markWriteContext($cleanTarget);
$assign = new Node\Expr\Assign(clone $cleanTarget, $wrappedRhs);
$assign->setAttribute('typephp_wrapped', true);
$assign->setAttribute('typephp_needs_parens', true);

$expr = $this->wrapWithPreEvaluations(
$preAssignments,
new Node\Expr\BinaryOp\Coalesce($cleanTarget, $assign)
);

if (! $isStandalone) {
$expr->setAttribute('typephp_needs_parens', true);
}

return $expr;
}

$wrappedRhs = $this->wrapTargetMutation(clone $node->var, $node->expr, $line);
if ($wrappedRhs === null) {
return null;
}

$assign = new Node\Expr\Assign(clone $node->var, $wrappedRhs);
$assign->setAttribute('typephp_wrapped', true);
$assign->setAttribute('typephp_needs_parens', true);

$expr = new Node\Expr\BinaryOp\Coalesce($node->var, $assign);

if (! $isStandalone) {
$expr->setAttribute('typephp_needs_parens', true);
}

return $expr;
}

private static function rhsNeedsParensInBinaryOp(Node\Expr $expr): bool
{
return $expr instanceof Node\Expr\BinaryOp
Expand Down Expand Up @@ -2406,7 +2518,7 @@ private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDe
$isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc;
$isPost = $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec;
$isStandalone = $node->getAttribute('typephp_is_standalone') === true;
$binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class;
$computeMethod = $isInc ? 'computeInc' : 'computeDec';

/** @var list<Node\Expr\Assign|Node\Expr\AssignRef> $preAssignments */
$preAssignments = [];
Expand All @@ -2421,8 +2533,11 @@ private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDe
}

$oldVar = new Node\Expr\Variable('__typephpOld' . $this->hoistTempCounter);
$binaryExpr = new $binaryClass(clone $oldVar, new Node\Scalar\LNumber(1));
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine());
$stepExpr = new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::' . $computeMethod),
[new Node\Arg(clone $oldVar)]
);
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $stepExpr, $node->var->getStartLine());

if ($wrapped === null) {
return null;
Expand All @@ -2439,8 +2554,11 @@ private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDe
return $expr;
}

$binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1));
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine());
$stepExpr = new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::' . $computeMethod),
[new Node\Arg(clone $cleanTarget)]
);
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $stepExpr, $node->var->getStartLine());

if ($wrapped === null) {
return null;
Expand Down Expand Up @@ -3002,18 +3120,20 @@ private function wrapClone(Node\Expr\Clone_ $node): ?Node\Expr\FuncCall

$node->setAttribute('typephp_wrapped', true);

$innerClone = new Node\Expr\Clone_(new Node\Expr\Variable('__typephpCloneSrc'));
$innerClone->setAttribute('typephp_wrapped', true);

$clonerArrow = new Node\Expr\ArrowFunction([
'static' => true,
'params' => [new Node\Param(new Node\Expr\Variable('__typephpCloneSrc'))],
'expr' => $innerClone,
]);

return new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::cloneInstance'),
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::executeClone'),
[
new Node\Arg(
new Node\Expr\Clone_(
new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::prepareClone'),
[new Node\Arg($node->expr)]
)
)
),
new Node\Arg($node->expr),
new Node\Arg($clonerArrow),
]
);
}
Expand Down
105 changes: 100 additions & 5 deletions src/Internal/Ast/Elimination/EliminationSafetyPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,19 @@
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;

/**
* Enforces LSP safety rules and runtime state invariants to determine
Expand Down Expand Up @@ -78,11 +87,8 @@ public static function isReturnEliminationSafe(
return false;
}

if ($returnTypeNode instanceof GenericTypeNode) {
$baseName = strtolower((string) $returnTypeNode->type);
if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) {
return false;
}
if (self::containsObjectGeneric($returnTypeNode)) {
return false;
}

if ($classContext === null || $functionNode instanceof Function_ || $functionNode instanceof Closure || $functionNode instanceof ArrowFunction) {
Expand Down Expand Up @@ -156,4 +162,93 @@ public static function isGeneratorEliminationSafe(

return false;
}

/**
* Recursively checks whether a TypeNode contains any object GenericTypeNode
* (e.g. Collection<Dog>, ?Collection<Dog>, Collection<Dog>|null, list<Collection<Dog>>,
* array{c: Collection<Dog>}) whose runtime WeakMap template bindings must be preserved.
*/
public static function containsObjectGeneric(TypeNode $typeNode): bool
{
while ($typeNode instanceof NullableTypeNode || $typeNode instanceof ArrayTypeNode) {
$typeNode = $typeNode->type;
}

if ($typeNode instanceof GenericTypeNode) {
$baseName = strtolower((string) $typeNode->type);
if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) {
return true;
}

foreach ($typeNode->genericTypes as $genericArg) {
if (self::containsObjectGeneric($genericArg)) {
return true;
}
}

return false;
}

if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) {
foreach ($typeNode->types as $member) {
if (self::containsObjectGeneric($member)) {
return true;
}
}

return false;
}

if ($typeNode instanceof ArrayShapeNode) {
foreach ($typeNode->items as $item) {
if (self::containsObjectGeneric($item->valueType)) {
return true;
}
}

if ($typeNode->unsealedType !== null) {
if (self::containsObjectGeneric($typeNode->unsealedType->valueType)) {
return true;
}

if ($typeNode->unsealedType->keyType !== null && self::containsObjectGeneric($typeNode->unsealedType->keyType)) {
return true;
}
}

return false;
}

if ($typeNode instanceof ObjectShapeNode) {
foreach ($typeNode->items as $item) {
if (self::containsObjectGeneric($item->valueType)) {
return true;
}
}

return false;
}

if ($typeNode instanceof CallableTypeNode) {
foreach ($typeNode->parameters as $param) {
if (self::containsObjectGeneric($param->type)) {
return true;
}
}

return self::containsObjectGeneric($typeNode->returnType);
}

if ($typeNode instanceof ConditionalTypeNode || $typeNode instanceof ConditionalTypeForParameterNode) {
return self::containsObjectGeneric($typeNode->if)
|| self::containsObjectGeneric($typeNode->else);
}

if ($typeNode instanceof OffsetAccessTypeNode) {
return self::containsObjectGeneric($typeNode->type)
|| self::containsObjectGeneric($typeNode->offset);
}

return false;
}
}
Loading
Loading