diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 6cdb809c..474fea39 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -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 = [ @@ -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())), ], @@ -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; @@ -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; @@ -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 @@ -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 $preAssignments */ $preAssignments = []; @@ -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; @@ -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; @@ -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), ] ); } diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php index c20eba60..385c1a49 100644 --- a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -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 @@ -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) { @@ -156,4 +162,93 @@ public static function isGeneratorEliminationSafe( return false; } + + /** + * Recursively checks whether a TypeNode contains any object GenericTypeNode + * (e.g. Collection, ?Collection, Collection|null, list>, + * array{c: Collection}) 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; + } } diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index 5a443c26..8fb63a10 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -4,9 +4,12 @@ namespace TypePHP\Internal\Ast\Elimination\Evaluator; +use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\BinaryOp\Concat; +use PhpParser\Node\Expr\UnaryMinus; use PhpParser\Node\Scalar\Encapsed; +use PhpParser\Node\Scalar\EncapsedStringPart; use PhpParser\Node\Scalar\LNumber; use PhpParser\Node\Scalar\String_; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; @@ -226,20 +229,54 @@ private static function satisfiesKeyValueArray( return false; } - $currentIdx = 0; + /** @var int|null $currentIdx */ + $currentIdx = null; + $nextIdxOverflowed = false; foreach ($arrayExpr->items as $item) { if ($item === null || $item->unpack) { return false; } + $mayCoerceToInt = false; + if ($item->key === null) { - $keyExpr = new LNumber($currentIdx); - $currentIdx++; - } elseif ($item->key instanceof LNumber) { + if ($nextIdxOverflowed) { + return false; + } + $assignedIdx = $currentIdx ?? 0; + $keyExpr = new LNumber($assignedIdx); + if ($assignedIdx === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $assignedIdx + 1; + } + } elseif (($intKey = self::extractStaticIntKey($item->key)) !== null) { $keyExpr = $item->key; - $currentIdx = max($currentIdx, $item->key->value + 1); - } elseif ($item->key instanceof String_ || $item->key instanceof Concat || $item->key instanceof Encapsed) { + if ($currentIdx === null || $intKey >= $currentIdx) { + if ($intKey === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $intKey + 1; + } + } + } elseif ($item->key instanceof String_) { + $rawKey = $item->key->value; + if ($rawKey !== '' && (string) (int) $rawKey === $rawKey) { + $coercedInt = (int) $rawKey; + $keyExpr = new LNumber($coercedInt); + if ($currentIdx === null || $coercedInt >= $currentIdx) { + if ($coercedInt === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $coercedInt + 1; + } + } + } else { + $keyExpr = $item->key; + } + } elseif ($item->key instanceof Concat || $item->key instanceof Encapsed) { $keyExpr = $item->key; + $mayCoerceToInt = ! self::isGuaranteedNonNumericStringExpr($item->key); } else { return false; } @@ -248,6 +285,16 @@ private static function satisfiesKeyValueArray( return false; } + if ($mayCoerceToInt) { + if ( + ! StaticTypeEvaluator::satisfies(new LNumber(0), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) + || ! StaticTypeEvaluator::satisfies(new LNumber(1), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) + || ! StaticTypeEvaluator::satisfies(new UnaryMinus(new LNumber(1)), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) + ) { + return false; + } + } + if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } @@ -289,20 +336,47 @@ private static function satisfiesArrayShape( } $actualItems = []; - $currentIdx = 0; + /** @var int|null $currentIdx */ + $currentIdx = null; + $nextIdxOverflowed = false; foreach ($arrayExpr->items as $item) { if ($item === null || $item->unpack) { return false; } if ($item->key === null) { - $key = $currentIdx; - $currentIdx++; - } elseif ($item->key instanceof LNumber) { - $key = $item->key->value; - $currentIdx = max($currentIdx, $key + 1); + if ($nextIdxOverflowed) { + return false; + } + $key = $currentIdx ?? 0; + if ($key === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $key + 1; + } + } elseif (($intKey = self::extractStaticIntKey($item->key)) !== null) { + $key = $intKey; + if ($currentIdx === null || $key >= $currentIdx) { + if ($key === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $key + 1; + } + } } elseif ($item->key instanceof String_) { - $key = $item->key->value; + $rawKey = $item->key->value; + if ($rawKey !== '' && (string) (int) $rawKey === $rawKey) { + $key = (int) $rawKey; + if ($currentIdx === null || $key >= $currentIdx) { + if ($key === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $key + 1; + } + } + } else { + $key = $rawKey; + } } else { return false; } @@ -350,6 +424,49 @@ private static function satisfiesArrayShape( return true; } + /** + * Evaluates a static integer array key expression (e.g. 5, -5, 1 + 2), returning null for floats or dynamic expressions. + */ + private static function extractStaticIntKey(Expr $expr): ?int + { + if ($expr instanceof LNumber) { + return $expr->value; + } + + $folded = ArithmeticEvaluator::evaluate($expr); + + return \is_int($folded) ? $folded : null; + } + + /** + * Checks whether a string concatenation or interpolation contains a static fragment that + * guarantees the resulting key can never coerce into a PHP canonical integer key. + */ + private static function isGuaranteedNonNumericStringExpr(Expr $expr): bool + { + if ($expr instanceof String_) { + return preg_match('/[^0-9\-]|[\s\S]-/', $expr->value) === 1; + } + + if ($expr instanceof Concat) { + return self::isGuaranteedNonNumericStringExpr($expr->left) + || self::isGuaranteedNonNumericStringExpr($expr->right); + } + + if ($expr instanceof Encapsed) { + foreach ($expr->parts as $part) { + if ($part instanceof EncapsedStringPart && preg_match('/[^0-9\-]|[\s\S]-/', $part->value) === 1) { + return true; + } + if ($part instanceof String_ && preg_match('/[^0-9\-]|[\s\S]-/', $part->value) === 1) { + return true; + } + } + } + + return false; + } + /** * Checks whether an array expression has sequential 0..n-1 integer keys. */ diff --git a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php index c0aa4b88..fa8d96cd 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php @@ -16,7 +16,9 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; -use TypePHP\Internal\Resolver\SpecialTypeResolver; +use ReflectionClass; +use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; +use TypePHP\Internal\Diagnostic\DebugLog; use UnitEnum; /** @@ -86,10 +88,10 @@ private static function satisfiesClassConst( return false; } - $targetClassName = $fetch->class->toString(); + $targetClassNode = $fetch->class; if ($typeNode instanceof ConstTypeNode && $typeNode->constExpr instanceof ConstFetchNode) { - if (! self::classesMatch($targetClassName, $typeNode->constExpr->className, $currentFile, $currentNamespace)) { + if (! self::classesMatch($targetClassNode, $typeNode->constExpr->className, $currentFile, $currentNamespace)) { return false; } @@ -103,11 +105,11 @@ private static function satisfiesClassConst( } if ($typeNode instanceof IdentifierTypeNode) { - if (! self::classesMatch($targetClassName, $typeNode->name, $currentFile, $currentNamespace)) { + if (! self::classesMatch($targetClassNode, $typeNode->name, $currentFile, $currentNamespace)) { return false; } - $resolvedEnum = self::resolveClassForReflection($targetClassName, $currentFile, $currentNamespace); + $resolvedEnum = self::resolveClassForReflection($targetClassNode, $currentFile, $currentNamespace); if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false)) { return false; } @@ -118,10 +120,22 @@ private static function satisfiesClassConst( if ($typeNode instanceof GenericTypeNode && strtolower((string) $typeNode->type) === 'int-mask-of') { $inner = $typeNode->genericTypes[0] ?? null; if ($inner instanceof ConstTypeNode && $inner->constExpr instanceof ConstFetchNode) { - if (! self::classesMatch($targetClassName, $inner->constExpr->className, $currentFile, $currentNamespace)) { + if (! self::classesMatch($targetClassNode, $inner->constExpr->className, $currentFile, $currentNamespace)) { return false; } + $isSyntheticSelf = $currentFile === '' + && ! $targetClassNode->isFullyQualified() + && ! $targetClassNode->isRelative() + && strtolower($targetClassNode->toString()) === 'self'; + + if (! $isSyntheticSelf) { + $resolvedClass = self::resolveClassForReflection($targetClassNode, $currentFile, $currentNamespace); + if (! self::isLoadedIntConstant($resolvedClass, $constName)) { + return false; + } + } + $pattern = $inner->constExpr->name; if (str_contains($pattern, '*')) { return self::matchesWildcard($constName, $pattern); @@ -177,18 +191,18 @@ private static function satisfiesEnumBackingValue( return false; } - $enumClassName = $fetch->var->class->toString(); + $enumClassNode = $fetch->var->class; $caseName = $fetch->var->name->toString(); if (strtolower($caseName) === 'class') { return false; } - if (! self::classesMatch($enumClassName, $enumTarget->name, $currentFile, $currentNamespace)) { + if (! self::classesMatch($enumClassNode, $enumTarget->name, $currentFile, $currentNamespace)) { return false; } - $resolvedEnum = self::resolveClassForReflection($enumClassName, $currentFile, $currentNamespace); + $resolvedEnum = self::resolveClassForReflection($enumClassNode, $currentFile, $currentNamespace); if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false) || ! is_subclass_of($resolvedEnum, BackedEnum::class)) { return false; } @@ -197,49 +211,91 @@ private static function satisfiesEnumBackingValue( } /** - * Verifies whether two class references deterministically denote the same class/enum. + * Verifies whether an AST class Name node and a PHPDoc class name deterministically denote the same class/enum. */ - private static function classesMatch(string $fetchClass, string $docClass, string $currentFile, ?string $currentNamespace = null): bool + private static function classesMatch(Name $fetchClassNode, string $docClass, string $currentFile, ?string $currentNamespace = null): bool { if ($docClass === '') { return false; } - $lowerFetch = strtolower($fetchClass); + $lowerFetch = strtolower($fetchClassNode->toString()); $lowerDoc = strtolower($docClass); - if ($lowerFetch === 'self' && $lowerDoc === 'self') { - return true; - } + if (! $fetchClassNode->isFullyQualified() && ! $fetchClassNode->isRelative()) { + if ($lowerFetch === 'self' && $lowerDoc === 'self') { + return true; + } - if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerFetch]) || isset(self::RELATIVE_CLASS_KEYWORDS[$lowerDoc])) { - return false; + if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerFetch])) { + return false; + } } - if ($fetchClass === $docClass) { - return true; + if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerDoc])) { + return false; } - if ($currentFile !== '') { - $resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($fetchClass, $currentFile, false, $currentNamespace); - $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($docClass, $currentFile, false, $currentNamespace); + return StaticTypeEvaluator::classNamesMatch($fetchClassNode, $docClass, $currentFile, $currentNamespace); + } - return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass; + /** + * Resolves an AST class Name node to its FQCN without invoking autoloading. + */ + private static function resolveClassForReflection(Name $classNode, string $currentFile, ?string $currentNamespace = null): string + { + $resolved = StaticTypeEvaluator::resolveAstClassName($classNode, $currentFile, $currentNamespace); + + if ( + ! $classNode->isFullyQualified() + && ! $classNode->isRelative() + && ! self::isLoadedSymbol($resolved) + ) { + $raw = $classNode->toString(); + if (str_contains($raw, '\\') && self::isLoadedSymbol($raw)) { + return $raw; + } } - return false; + return $resolved; + } + + /** + * Checks whether a class, interface, or enum is already loaded without triggering autoloading. + */ + private static function isLoadedSymbol(string $symbol): bool + { + return $symbol !== '' && ( + class_exists($symbol, false) + || interface_exists($symbol, false) + || enum_exists($symbol, false) + ); } /** - * Resolves a class name without invoking autoloading. + * Verifies via non-autoloading reflection that a constant exists, is not an enum case, + * and evaluates to a concrete integer. */ - private static function resolveClassForReflection(string $rawClass, string $currentFile, ?string $currentNamespace = null): string + private static function isLoadedIntConstant(string $resolvedClass, string $constName): bool { - if ($currentFile !== '') { - return SpecialTypeResolver::resolveFqcnForFile($rawClass, $currentFile, false, $currentNamespace); + if (! self::isLoadedSymbol($resolvedClass)) { + return false; } - return ltrim($rawClass, '\\'); + try { + /** @var class-string $resolvedClass */ + $refClass = new ReflectionClass($resolvedClass); + $refConst = $refClass->getReflectionConstant($constName); + if ($refConst === false || $refConst->isEnumCase()) { + return false; + } + + return \is_int($refConst->getValue()); + } catch (\Throwable $e) { + DebugLog::swallowed($e); // @codeCoverageIgnore + + return false; + } } /** @@ -261,12 +317,12 @@ private static function isEnumCase(string $enumClass, string $caseName): bool } /** - * Compares a constant name against a wildcard pattern prefix (e.g. 'STATUS_PAID' vs 'STATUS_*'). + * Compares a constant name against a wildcard pattern (e.g. 'STATUS_PAID' vs 'STATUS_*'). */ private static function matchesWildcard(string $actualName, string $pattern): bool { - $prefix = rtrim($pattern, '*'); + $regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i'; - return str_starts_with(strtoupper($actualName), strtoupper($prefix)); + return preg_match($regex, $actualName) === 1; } } diff --git a/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php index ef7fa80e..4d6e6ab0 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php @@ -12,7 +12,7 @@ use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; -use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; /** * Statically evaluates object instantiations and identity returns ($this, new static, new ClassName). @@ -103,33 +103,24 @@ private static function satisfiesNew(Name $classNameNode, TypeNode $typeNode, st $lowerNewClass = strtolower($rawNewClass); $lowerTargetType = strtolower($typeNode->name); - if ($lowerNewClass === 'static' && $lowerTargetType === 'static') { - return true; - } + if (! $classNameNode->isFullyQualified() && ! $classNameNode->isRelative()) { + if ($lowerNewClass === 'static' && $lowerTargetType === 'static') { + return true; + } - if ($lowerNewClass === 'self' && $lowerTargetType === 'self') { - return true; + if ($lowerNewClass === 'self' && $lowerTargetType === 'self') { + return true; + } } if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerTargetType])) { return false; } - if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerNewClass])) { + if (! $classNameNode->isFullyQualified() && ! $classNameNode->isRelative() && isset(self::RELATIVE_CLASS_KEYWORDS[$lowerNewClass])) { return false; } - if ($rawNewClass === $typeNode->name) { - return true; - } - - if ($currentFile !== '') { - $resolvedNewClass = SpecialTypeResolver::resolveFqcnForFile($rawNewClass, $currentFile, false, $currentNamespace); - $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false, $currentNamespace); - - return $resolvedNewClass !== '' && $resolvedNewClass === $resolvedTypeClass; - } - - return $rawNewClass === $typeNode->name; + return StaticTypeEvaluator::classNamesMatch($classNameNode, $typeNode->name, $currentFile, $currentNamespace); } } diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index 0e358d94..781fcb50 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -8,6 +8,7 @@ use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\Ternary; use PhpParser\Node\Expr\Variable; +use PhpParser\Node\Name; use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; @@ -75,7 +76,12 @@ public static function satisfies( } } - if ($expr instanceof Variable && \is_string($expr->name) && isset($trustedVariableTypes[$expr->name])) { + if ( + $expr instanceof Variable + && \is_string($expr->name) + && isset($trustedVariableTypes[$expr->name]) + && ! EliminationSafetyPolicy::containsObjectGeneric($typeNode) + ) { $resolvedTarget = $currentFile !== '' ? SpecialTypeResolver::resolveForFile($typeNode, $currentFile, $currentNamespace, false) : $typeNode; @@ -196,4 +202,117 @@ public static function isUnsetSafe(TypeNode $typeNode, array $chain): bool return false; } + + /** + * Resolves a PHP AST Name node to its exact FQCN using strict PHP syntactic name resolution + * rules (without autoloading or global fallback for unqualified names inside a namespace). + */ + public static function resolveAstClassName( + Name $nameNode, + string $currentFile = '', + ?string $currentNamespace = null + ): string { + $raw = $nameNode->toString(); + + if ($nameNode->isFullyQualified()) { + return $raw; + } + + $namespace = $currentNamespace ?? ($currentFile !== '' ? SpecialTypeResolver::getNamespaceFromFile($currentFile) : ''); + + if ($nameNode->isRelative()) { + return $namespace !== '' ? $namespace . '\\' . $raw : $raw; + } + + $imports = $currentFile !== '' + ? SpecialTypeResolver::getUseImportsFromFile($currentFile, $currentNamespace) + : []; + + if (isset($imports[$raw])) { + return $imports[$raw]; + } + + if (str_contains($raw, '\\')) { + [$first, $rest] = explode('\\', $raw, 2); + if (isset($imports[$first])) { + return $imports[$first] . '\\' . $rest; + } + } + + return $namespace !== '' ? $namespace . '\\' . $raw : $raw; + } + + /** + * Deterministically checks whether a PHP AST class Name node and a PHPDoc class name string + * refer to the exact same class or enum in the given file and namespace context. + */ + public static function classNamesMatch( + Name $astClassNode, + string $docClassName, + string $currentFile = '', + ?string $currentNamespace = null + ): bool { + if ($docClassName === '') { + return false; + } + + $docIsFqn = str_starts_with($docClassName, '\\'); + $docTrimmed = ltrim($docClassName, '\\'); + if ($docTrimmed === '') { + return false; + } + + if (! $docIsFqn && SpecialTypeResolver::isBuiltInTypeKeyword($docTrimmed)) { + return false; + } + + if ($currentFile === '') { + if ($astClassNode->isFullyQualified()) { + return $docIsFqn && $astClassNode->toString() === $docTrimmed; + } + + if ($astClassNode->isRelative()) { + if (! $docIsFqn || $currentNamespace === null) { + return false; + } + + $astFqcn = $currentNamespace !== '' + ? $currentNamespace . '\\' . $astClassNode->toString() + : $astClassNode->toString(); + + return $astFqcn === $docTrimmed; + } + + if ($docIsFqn) { + return false; + } + + return $astClassNode->toString() === $docTrimmed; + } + + $resolvedAstClass = self::resolveAstClassName($astClassNode, $currentFile, $currentNamespace); + if ($resolvedAstClass === '') { + return false; + } + + if ($docIsFqn) { + return $resolvedAstClass === $docTrimmed; + } + + $namespace = $currentNamespace ?? SpecialTypeResolver::getNamespaceFromFile($currentFile); + $imports = SpecialTypeResolver::getUseImportsFromFile($currentFile, $currentNamespace); + + if (isset($imports[$docTrimmed])) { + $resolvedDocClass = $imports[$docTrimmed]; + } elseif (str_contains($docTrimmed, '\\')) { + [$first, $rest] = explode('\\', $docTrimmed, 2); + $resolvedDocClass = isset($imports[$first]) + ? $imports[$first] . '\\' . $rest + : ($namespace !== '' ? $namespace . '\\' . $docTrimmed : $docTrimmed); + } else { + $resolvedDocClass = $namespace !== '' ? $namespace . '\\' . $docTrimmed : $docTrimmed; + } + + return $resolvedAstClass === $resolvedDocClass; + } } diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index cda0b6e9..6ce8c51a 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -325,6 +325,11 @@ private static function canEliminateSetupScope( } $paramTags = $phpDocNode !== null ? DocblockExtractor::getParamTags($phpDocNode) : []; + if (isset($paramTags[''])) { + return false; + } + + $strictNullability = ! Config::isRespectNativeNullabilityEnabled(); foreach ($node->params as $param) { if ($param->variadic || ! ($param->var instanceof Node\Expr\Variable) || ! \is_string($param->var->name)) { @@ -348,7 +353,13 @@ private static function canEliminateSetupScope( continue; } - if (! self::nativeParamSatisfiesDocType($param->type, $paramTag->type)) { + $docType = $pTypeNode ?? $paramTag->type; + + if ($strictNullability && self::hasNullDefault($param) && ! self::docTypeAllowsNull($docType)) { + return false; + } + + if (! self::nativeParamSatisfiesDocType($param->type, $docType)) { return false; } } @@ -356,6 +367,39 @@ private static function canEliminateSetupScope( return true; } + private static function hasNullDefault(Node\Param $param): bool + { + return $param->default instanceof Node\Expr\ConstFetch + && strtolower($param->default->name->toString()) === 'null'; + } + + private static function docTypeAllowsNull(TypeNode $type): bool + { + if ($type instanceof NullableTypeNode) { + return true; + } + + if ($type instanceof IdentifierTypeNode) { + $lower = strtolower($type->name); + + return $lower === 'null' || $lower === 'mixed'; + } + + if ($type instanceof \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode) { + return $type->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode; + } + + if ($type instanceof UnionTypeNode) { + foreach ($type->types as $member) { + if (self::docTypeAllowsNull($member)) { + return true; + } + } + } + + return false; + } + private static function nativeParamSatisfiesDocType( Node\Identifier|Node\Name|Node\ComplexType|null $nativeType, TypeNode $docType @@ -497,10 +541,8 @@ private static function collectTrustedParamTypes( continue; } - if ( - Config::isRespectNativeNullabilityEnabled() - && self::parameterAllowsNullNatively($p) - ) { + $allowsNullNatively = self::parameterAllowsNullNatively($p); + if ($allowsNullNatively && (Config::isRespectNativeNullabilityEnabled() || ! isset($paramTags[$pName]))) { continue; } @@ -1099,6 +1141,72 @@ public static function buildParamOutCheckStmts( return $stmts; } + /** + * Checks whether a return expression is guaranteed side-effect-free and cannot throw or mutate state. + */ + public static function isTrivialPureReturnExpr(Node\Expr $expr): bool + { + return ($expr instanceof Node\Expr\Variable && \is_string($expr->name)) + || $expr instanceof Node\Scalar\LNumber + || $expr instanceof Node\Scalar\DNumber + || $expr instanceof Node\Scalar\String_ + || ($expr instanceof Node\Expr\ConstFetch && \in_array(strtolower($expr->name->toString()), ['true', 'false', 'null'], true)); + } + + /** + * Checks whether an expression can legally appear on the right-hand side of a reference assignment (`=&`). + */ + private static function isReferenceableExpr(Node\Expr $expr): bool + { + if ($expr instanceof Node\Expr\Variable || $expr instanceof Node\Expr\StaticPropertyFetch) { + return true; + } + + if ($expr instanceof Node\Expr\PropertyFetch) { + return $expr->var instanceof Node\Expr\New_ || self::isReferenceableExpr($expr->var); + } + + if ($expr instanceof Node\Expr\ArrayDimFetch) { + return $expr->dim !== null && self::isReferenceableExpr($expr->var); + } + + if ( + $expr instanceof Node\Expr\FuncCall + || $expr instanceof Node\Expr\MethodCall + || $expr instanceof Node\Expr\StaticCall + ) { + return ! $expr->isFirstClassCallable(); + } + + return false; + } + + /** + * Hoists a non-trivial return expression into a temporary variable so that it executes + * once and before @self-out, @param-out, or by-reference return checks. + * + * @return list + */ + public static function hoistReturnExprForExitChecks(Node\Stmt\Return_ $returnNode, bool $byRef = false): array + { + $originalExpr = $returnNode->expr; + if ($originalExpr === null || self::isTrivialPureReturnExpr($originalExpr)) { + return []; + } + + $retVar = new Node\Expr\Variable('__typephpRetVal'); + $assign = ($byRef && self::isReferenceableExpr($originalExpr)) + ? new Node\Expr\AssignRef($retVar, $originalExpr) + : new Node\Expr\Assign($retVar, $originalExpr); + + $stmt = new Node\Stmt\Expression($assign); + $stmt->setAttribute('typephp_injected', true); + + $returnNode->expr = new Node\Expr\Variable('__typephpRetVal'); + + return [$stmt]; + } + /** * @param array $params * @param callable(Node\Param, ?TypeNode, array): bool $predicate @@ -1734,6 +1842,7 @@ public static function inlineVarSubsumesReturn( if ( ! $isEliminationSafe || $targetReturnType === null + || EliminationSafetyPolicy::containsObjectGeneric($targetReturnType) || ! Config::isInlineScalarsEnabled() || ! Config::isInlineArraysEnabled() || ! Config::isInlineObjectsEnabled() @@ -1979,6 +2088,11 @@ public function enterNode(Node $n): int|Node|array|null $exitStmts = [...$exitStmts, ...$paramOutStmts]; } + $originalExpr = $n->expr; + $preEvalStmts = $exitStmts !== [] + ? FunctionContractInjector::hoistReturnExprForExitChecks($n, false) + : []; + if (FunctionContractInjector::inlineVarSubsumesReturn( $n, $this->genContract['return'] ?? null, @@ -1987,12 +2101,12 @@ public function enterNode(Node $n): int|Node|array|null $this->currentFile, $this->currentNamespace )) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } - $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + $origExprOrNull = $originalExpr ?? new Node\Expr\ConstFetch(new Node\Name('null')); $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); - $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; + $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $origExprOrNull; if ( ($this->genContract !== null @@ -2005,9 +2119,11 @@ public function enterNode(Node $n): int|Node|array|null )) || ($this->explicitGenContract !== null && $this->explicitGenContract['return'] === null) ) { - return $exitStmts !== [] ? [...$exitStmts, $n] : $n; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : $n; } + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + $scopeArg = new Node\Expr\BinaryOp\Coalesce( new Node\Expr\Variable('__typephpScope'), new Node\Expr\ConstFetch(new Node\Name('null')) @@ -2025,7 +2141,7 @@ public function enterNode(Node $n): int|Node|array|null $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $n->getStartLine()); - return $exitStmts !== [] ? [...$exitStmts, $n] : $n; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : $n; } return null; @@ -2204,8 +2320,13 @@ public function enterNode(Node $n): int|array|null $exitStmts = [...$exitStmts, ...$paramOutStmts]; } + $originalExpr = $n->expr; + $preEvalStmts = ($exitStmts !== [] || ($this->isByRefReturn && $this->hasReturn)) + ? FunctionContractInjector::hoistReturnExprForExitChecks($n, $this->isByRefReturn) + : []; + if (! $this->hasReturn) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } $isReturnElimSafe = ! $this->isByRefReturn @@ -2222,33 +2343,34 @@ public function enterNode(Node $n): int|array|null $this->currentFile, $this->currentNamespace )) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } - $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); - + $origExprOrNull = $originalExpr ?? new Node\Expr\ConstFetch(new Node\Name('null')); $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); - $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; + $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $origExprOrNull; if ( $isReturnElimSafe && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes, $this->currentNamespace) ) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + if ($this->isNativeVoid) { $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); $voidGuardStmts = FunctionContractInjector::buildVoidReturnGuard($checkCall); - return [...$exitStmts, ...$voidGuardStmts]; + return [...$preEvalStmts, ...$exitStmts, ...$voidGuardStmts]; } if ($this->isByRefReturn) { $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); $byRefGuardStmts = FunctionContractInjector::buildByRefReturnGuard($checkCall, $n, $n->getStartLine()); - return [...$exitStmts, ...$byRefGuardStmts]; + return [...$preEvalStmts, ...$exitStmts, ...$byRefGuardStmts]; } if ($this->canGuardReturnCache) { @@ -2267,7 +2389,7 @@ public function enterNode(Node $n): int|array|null ); } - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } return null; @@ -2361,10 +2483,32 @@ public static function tagPrecedingAssignments(array $stmts): void && $curr->expr instanceof Node\Expr\Yield_ && $curr->expr->value instanceof Node\Expr\Variable && $curr->expr->value->name === $assignedVarName - && ($curr->expr->key === null || ! ($curr->expr->key instanceof Node\Expr\Assign)) + && ($curr->expr->key === null || ! self::exprMayMutateVar($curr->expr->key)) ) { $curr->expr->setAttribute('typephp_preceding_assign_expr', $prev->expr->expr); } } } + + /** + * Checks whether a yield key expression contains any assignment, increment/decrement, + * call, or other side-effecting node that could mutate local state before the yield value is evaluated. + */ + private static function exprMayMutateVar(Node\Expr $expr): bool + { + return (new \PhpParser\NodeFinder())->findFirst($expr, static function (Node $n): bool { + return $n instanceof Node\Expr\Assign + || $n instanceof Node\Expr\AssignOp + || $n instanceof Node\Expr\AssignRef + || $n instanceof Node\Expr\PreInc + || $n instanceof Node\Expr\PostInc + || $n instanceof Node\Expr\PreDec + || $n instanceof Node\Expr\PostDec + || $n instanceof Node\Expr\CallLike + || $n instanceof Node\Expr\Yield_ + || $n instanceof Node\Expr\YieldFrom + || $n instanceof Node\Expr\Eval_ + || $n instanceof Node\Expr\Include_; + }) !== null; + } } diff --git a/src/Internal/Ast/TypePHPPrinter.php b/src/Internal/Ast/TypePHPPrinter.php index f867ab38..0db755a7 100644 --- a/src/Internal/Ast/TypePHPPrinter.php +++ b/src/Internal/Ast/TypePHPPrinter.php @@ -40,6 +40,10 @@ protected function p( return '(' . parent::p($node, PrettyPrinterAbstract::MAX_PRECEDENCE, PrettyPrinterAbstract::MAX_PRECEDENCE, $parentFormatPreserved) . ')'; } + if ($node instanceof Node\Expr\StaticCall && $node->getAttribute('typephp_multiline_call') !== null) { + return $this->printMultilineStaticCall($node); + } + $output = parent::p($node, $precedence, $lhsPrecedence, $parentFormatPreserved); if ($node instanceof Node\Stmt && $node->getAttribute('typephp_injected') === true) { @@ -49,6 +53,46 @@ protected function p( return $output; } + /** + * Prints a wrapped constructor StaticCall while preserving the exact start/end lines + * of its forwarded multi-line constructor arguments. + */ + private function printMultilineStaticCall(Node\Expr\StaticCall $node): string + { + /** @var array{startLine: int, endLine: int, forwardedStartIndex: int} $info */ + $info = $node->getAttribute('typephp_multiline_call'); + $startLine = $info['startLine']; + $endLine = $info['endLine']; + $fwdStart = $info['forwardedStartIndex']; + + $prefixArgs = []; + for ($i = 0; $i < $fwdStart && isset($node->args[$i]); $i++) { + $prefixArgs[] = $this->p($node->args[$i]); + } + + $output = $this->p($node->class) . '::' . $this->p($node->name) . '(' . implode(', ', $prefixArgs); + $cursorLine = $startLine + substr_count($output, "\n"); + + $totalArgs = \count($node->args); + for ($i = $fwdStart; $i < $totalArgs; $i++) { + $arg = $node->args[$i]; + $comments = $arg->getComments(); + $argStartLine = $comments !== [] ? $comments[0]->getStartLine() : $arg->getStartLine(); + $leadingNewlines = ($argStartLine > $cursorLine) ? ($argStartLine - $cursorLine) : 0; + + $printedArg = $this->p($arg); + $argNewlines = substr_count($printedArg, "\n"); + + $output .= ($leadingNewlines > 0 ? ',' . str_repeat("\n", $leadingNewlines) : ', ') . $printedArg; + $cursorLine += $leadingNewlines + $argNewlines; + } + + $trailingNewlines = ($endLine > $cursorLine) ? ($endLine - $cursorLine) : 0; + $output .= str_repeat("\n", $trailingNewlines) . ')'; + + return $output; + } + /** * Converts single-line comments and squashes whitespace on injected statements * without altering string literals or attribute tokens. diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index fe234a7a..f0b159f6 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -147,6 +147,7 @@ public static function reset(): void 'false' => true, 'scalar' => true, 'numeric' => true, + 'number' => true, 'positive-int' => true, 'negative-int' => true, 'non-positive-int' => true, @@ -164,18 +165,43 @@ public static function reset(): void 'non-empty-lowercase-string' => true, 'uppercase-string' => true, 'non-empty-uppercase-string' => true, + 'literal-string' => true, + 'truthy-string' => true, + 'non-falsy-string' => true, + 'class-string' => true, + 'interface-string' => true, + 'trait-string' => true, + 'enum-string' => true, + 'callable-string' => true, 'truthy' => true, 'falsy' => true, + 'falsey' => true, 'array-key' => true, ]; /** - * Fast lookup set for iterable types. + * Fast lookup set for built-in generic types representing scalar refinements rather than generic objects. + */ + private const SCALAR_GENERIC_TYPES = [ + 'int' => true, + 'integer' => true, + 'int-mask' => true, + 'int-mask-of' => true, + 'class-string' => true, + 'key-of' => true, + 'value-of' => true, + ]; + + /** + * Fast lookup set for iterable and collection array types. */ private const ARRAY_TYPES = [ 'array' => true, 'list' => true, 'iterable' => true, + 'non-empty-array' => true, + 'non-empty-list' => true, + 'non-empty-array-list' => true, ]; /** @@ -221,13 +247,15 @@ public static function checkVariable( $context = ($varName === 'return') ? 'Return value' : "Variable \$$varName"; + $isObjectGeneric = false; if ($typeNode instanceof GenericTypeNode) { $baseName = strtolower((string) $typeNode->type); - $isCollection = isset(self::ARRAY_TYPES[$baseName]); + $isObjectGeneric = ! isset(self::ARRAY_TYPES[$baseName]) && ! isset(self::SCALAR_GENERIC_TYPES[$baseName]); - if (! $isCollection) { + if ($isObjectGeneric) { if (! Config::isInlineGenericsEnabled() && Config::isInlineObjectsEnabled()) { $typeNode = $typeNode->type; + $isObjectGeneric = false; } elseif (! Config::isInlineGenericsEnabled() && ! Config::isInlineObjectsEnabled()) { return $value; } @@ -235,11 +263,11 @@ public static function checkVariable( } $preExistingBindings = null; - if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { + if ($isObjectGeneric && ($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { $preExistingBindings = TemplateManager::getConcreteInstanceBindings($value); } - if ($typeNode instanceof GenericTypeNode && Config::isInlineGenericsEnabled() && \is_object($value)) { + if ($isObjectGeneric && Config::isInlineGenericsEnabled() && \is_object($value) && $typeNode instanceof GenericTypeNode) { $err = TemplateManager::bindInstanceFromNode($value, $typeNode, $context); if ($err !== null) { return $err; @@ -255,16 +283,18 @@ public static function checkVariable( TemplateManager::markFallbackReturnBindings($value, $typeNode, $fallbackMeta[1], $fallbackMeta[0], $preExistingBindings); } - if ($typeNode instanceof CallableTypeNode || ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'callable')) { - $cbPrefix = ($varName === 'return') ? 'Return value: Callback' : "Variable \$$varName: Callback"; + if (Config::isInlineCallablesEnabled()) { + if ($typeNode instanceof CallableTypeNode || ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'callable')) { + $cbPrefix = ($varName === 'return') ? 'Return value: Callback' : "Variable \$$varName: Callback"; - return CallableWrapper::wrapTypeNode($typeNode, $value, $cbPrefix, $registry); - } + return CallableWrapper::wrapTypeNode($typeNode, $value, $cbPrefix, $registry); + } - if ($typeNode instanceof ArrayShapeNode && \is_array($value)) { - $value = self::wrapShapeCallables($typeNode, $value, $context, $registry); - } elseif (\is_array($value)) { - $value = self::wrapCollectionCallables($typeNode, $value, $context, $registry); + if ($typeNode instanceof ArrayShapeNode && \is_array($value)) { + $value = self::wrapShapeCallables($typeNode, $value, $context, $registry); + } elseif (\is_array($value)) { + $value = self::wrapCollectionCallables($typeNode, $value, $context, $registry); + } } } catch (\Throwable $e) { DebugLog::swallowed($e); // @codeCoverageIgnore @@ -441,8 +471,12 @@ private static function wrapShapeCallables(ArrayShapeNode $shapeNode, array $val */ private static function wrapCollectionCallables(TypeNode $typeNode, array $value, string $context, TypeValidatorRegistry $registry): array { + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + $innerCallable = null; - if ($typeNode instanceof GenericTypeNode && \in_array(strtolower((string) $typeNode->type), ['list', 'array', 'iterable'], true)) { + if ($typeNode instanceof GenericTypeNode && isset(self::ARRAY_TYPES[strtolower((string) $typeNode->type)])) { $innerCallable = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null; } elseif ($typeNode instanceof ArrayTypeNode) { $innerCallable = $typeNode->type; @@ -1138,7 +1172,7 @@ private static function shouldValidateType(TypeNode $node): bool return false; } - if ($lower === 'callable') { + if ($lower === 'callable' || $lower === 'pure-callable' || $lower === 'static-closure' || $lower === 'static-pure-closure') { return Config::isInlineCallablesEnabled(); } @@ -1159,6 +1193,10 @@ private static function shouldValidateType(TypeNode $node): bool return $checkArrays; } + if (isset(self::SCALAR_GENERIC_TYPES[$lower])) { + return Config::isInlineScalarsEnabled(); + } + if (Config::isInlineGenericsEnabled()) { return true; } diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index a43c7415..96b3a692 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -243,16 +243,11 @@ public static function areAllParamsUnconstrained(string $effectiveFunction): boo } /** - * Checks if a TypeNode represents an unconstrained type (mixed or array). + * Checks if a TypeNode represents an unconstrained type (mixed). */ private static function isUnconstrained(TypeNode $typeNode): bool { - if (! ($typeNode instanceof IdentifierTypeNode)) { - return false; - } - $lower = strtolower($typeNode->name); - - return $lower === 'mixed' || $lower === 'array'; + return $typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'mixed'; } /** diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index 5ed0ffcd..eb7cfbb4 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -409,7 +409,10 @@ private static function evaluateReturn( if ($resolvedType instanceof IdentifierTypeNode) { $name = $resolvedType->name; - if ($name === 'mixed' || $name === 'array' || strtolower($name) === 'mixed' || strtolower($name) === 'array') { + if ($name === 'mixed' || strtolower($name) === 'mixed') { + return $value; + } + if (($name === 'array' || strtolower($name) === 'array') && \is_array($value)) { return $value; } } @@ -553,7 +556,7 @@ private static function evaluateReturn( if ($resolvedType instanceof IdentifierTypeNode) { $lower = strtolower($resolvedType->name); - if ($lower === 'mixed' || $lower === 'array') { + if ($lower === 'mixed' || ($lower === 'array' && \is_array($value))) { return $value; } } diff --git a/src/Internal/Diagnostic/ErrorFactory.php b/src/Internal/Diagnostic/ErrorFactory.php index dffded9f..be25d55c 100644 --- a/src/Internal/Diagnostic/ErrorFactory.php +++ b/src/Internal/Diagnostic/ErrorFactory.php @@ -6,17 +6,13 @@ use ReflectionClass; use TypeError; +use TypePHP\Internal\Util\PathMatcher; /** * @internal Factory creating ErrorMessage value objects and preparing TypeError instances with exact caller traces. */ final class ErrorFactory { - private const INTERNAL_DIR_PATTERNS = [ - 'src/Internal/', - 'bin/typephp', - ]; - private const CALL_SITE_KEYWORDS = [ 'argument $', 'argument #', @@ -136,13 +132,7 @@ private static function isInternalFile(string $normalizedFile): bool return false; } - foreach (self::INTERNAL_DIR_PATTERNS as $pattern) { - if (str_contains($normalizedFile, $pattern)) { - return true; - } - } - - return false; + return PathMatcher::isLibraryInternal($normalizedFile); } /** diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index d173972f..84c365e7 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -291,16 +291,26 @@ public static function typeReferencesTemplate(?TypeNode $node, array $templateNa } /** - * Checks if a TypeNode represents an unconstrained type (mixed or array). + * Checks if a native PHP reflection type is a non-nullable `array`. */ - private static function isUnconstrainedType(TypeNode $typeNode): bool + private static function isNativeNonNullArrayType(?\ReflectionType $type): bool + { + return $type instanceof \ReflectionNamedType + && strtolower($type->getName()) === 'array' + && ! $type->allowsNull(); + } + + /** + * Checks if a TypeNode represents an unconstrained type (mixed, or bare array when natively guaranteed). + */ + private static function isUnconstrainedType(TypeNode $typeNode, bool $isNativelyNonNullArray = false): bool { if (! ($typeNode instanceof IdentifierTypeNode)) { return false; } $lower = strtolower($typeNode->name); - return $lower === 'mixed' || $lower === 'array'; + return $lower === 'mixed' || ($isNativelyNonNullArray && $lower === 'array'); } /** @@ -308,6 +318,7 @@ private static function isUnconstrainedType(TypeNode $typeNode): bool * @param array $aliases * @param array $methodTemplates * @param array $allTemplates + * @param array $nativeArrayParams * * @return array{ * constrainedTypes: array, @@ -331,7 +342,9 @@ private static function computeContractFlags( array $methodTemplates, bool $paramsAreDynamic = false, array $allTemplates = [], - bool $returnIsThis = false + bool $returnIsThis = false, + array $nativeArrayParams = [], + bool $isNativeArrayReturn = false ): array { $constrainedTypes = []; $paramConditionals = []; @@ -341,7 +354,7 @@ private static function computeContractFlags( if (! ($tNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($tNode)) { $paramConditionals[$paramName] = true; $constrainedTypes[$paramName] = $tNode; - } elseif (! self::isUnconstrainedType($tNode)) { + } elseif (! self::isUnconstrainedType($tNode, isset($nativeArrayParams[$paramName]))) { $constrainedTypes[$paramName] = $tNode; } @@ -368,8 +381,7 @@ private static function computeContractFlags( $returnUnconstrained = false; $returnHasConditional = false; if ($returnType instanceof IdentifierTypeNode) { - $lower = strtolower($returnType->name); - $returnUnconstrained = ($lower === 'mixed' || $lower === 'array'); + $returnUnconstrained = self::isUnconstrainedType($returnType, $isNativeArrayReturn); } elseif ($returnType !== null) { $returnHasConditional = ConditionalChecker::containsConditional($returnType); } @@ -1128,6 +1140,15 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t $returnIsDynamic = $returnIsThis || str_contains($retStr, 'static') || str_contains($retStr, '$this'); } + /** @var array $nativeArrayParams */ + $nativeArrayParams = []; + foreach ($ref->getParameters() as $p) { + if (! $p->isVariadic() && self::isNativeNonNullArrayType($p->getType())) { + $nativeArrayParams[$p->getName()] = true; + } + } + $isNativeArrayReturn = self::isNativeNonNullArrayType($ref->getReturnType()); + $flags = self::computeContractFlags( $types, $returnType, @@ -1137,7 +1158,9 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t $methodTemplates, $paramsAreDynamic, $allTemplates, - $returnIsThis + $returnIsThis, + $nativeArrayParams, + $isNativeArrayReturn ); return [ @@ -1195,14 +1218,21 @@ private static function parseFunction(\ReflectionFunction $ref): array $baseParamNames = []; $baseParamVariadic = []; $baseParamObjects = []; + /** @var array $nativeArrayParams */ + $nativeArrayParams = []; foreach ($baseParams as $idx => $p) { - $baseParamNames[$idx] = $p->getName(); - $baseParamVariadic[$p->getName()] = $p->isVariadic(); - $baseParamObjects[$p->getName()] = $p; + $pName = $p->getName(); + $baseParamNames[$idx] = $pName; + $baseParamVariadic[$pName] = $p->isVariadic(); + $baseParamObjects[$pName] = $p; + if (! $p->isVariadic() && self::isNativeNonNullArrayType($p->getType())) { + $nativeArrayParams[$pName] = true; + } if (self::hasSensitiveAttribute($p)) { - $sensitiveParams[$p->getName()] = true; + $sensitiveParams[$pName] = true; } } + $isNativeArrayReturn = self::isNativeNonNullArrayType($ref->getReturnType()); if ($doc === false || self::shouldIgnoreDoc($doc)) { return [ @@ -1346,7 +1376,9 @@ private static function parseFunction(\ReflectionFunction $ref): array $templates, false, $templates, - $returnIsThis + $returnIsThis, + $nativeArrayParams, + $isNativeArrayReturn ); return [ diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 6a3dbb74..96431264 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -160,10 +160,17 @@ final class TemplateManager private static array $realTypeSymbolCache = []; /** - * Temporary storage for an original object instance being cloned. + * Temporary storage for the top-most original object instance being cloned. */ public static ?object $pendingCloneSource = null; + /** + * Stack of active clone source objects supporting nested clones inside __clone(). + * + * @var list + */ + private static array $pendingCloneStack = []; + /** * Fast boolean flag indicating whether any pending constructor generic instantiations are active. */ @@ -704,6 +711,7 @@ public static function reset(): void self::$subclassCache = []; self::$realTypeSymbolCache = []; self::$pendingCloneSource = null; + self::$pendingCloneStack = []; self::$hasPendingInstantiations = false; self::$methodTemplatesCache = []; self::$isMethodTemplateCache = []; @@ -728,6 +736,21 @@ public static function reset(): void self::$expandedKeyOrValueOfCache = null; } + public static function pushPendingCloneSource(object $original): void + { + self::$pendingCloneStack[] = $original; + self::$pendingCloneSource = $original; + } + + public static function popPendingCloneSource(): ?object + { + $popped = array_pop(self::$pendingCloneStack); + $count = \count(self::$pendingCloneStack); + self::$pendingCloneSource = $count > 0 ? self::$pendingCloneStack[$count - 1] : null; + + return $popped; + } + /** * Restores or clears instance template bindings in WeakMap. * @@ -3462,6 +3485,26 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return true; } + if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { + if ($lowerExisting === 'mixed' || $lowerExisting === '*') { + return true; + } + + if ($lowerExisting === 'object' && ClassNameValidator::isValid($expectedName) && self::isRealTypeSymbol($expectedName)) { + return true; + } + + if (isset(self::SCALAR_SUBTYPES[$lowerExisting][$lowerExpected]) || self::isScalarSubtype($lowerExpected, $lowerExisting)) { + return true; + } + + if (isset(self::COLLECTION_SUBTYPES[$lowerExisting])) { + return isset(self::COLLECTION_SUBTYPES[$lowerExisting][$lowerExpected]); + } + + return self::isSubclass($expectedName, $existingName); + } + if ($lowerExpected === 'object' && ClassNameValidator::isValid($existingName) && self::isRealTypeSymbol($existingName)) { return true; } @@ -3478,10 +3521,6 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::isSubclass($existingName, $expectedName); } - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - return self::isSubclass($expectedName, $existingName); - } - return false; } @@ -3527,6 +3566,13 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } } + if ($expected instanceof IdentifierTypeNode) { + $lowerExpected = strtolower($expected->name); + if ($lowerExpected === 'mixed' || $lowerExpected === '*') { + return true; + } + } + if ($existing instanceof ConstTypeNode && $expected instanceof ConstTypeNode) { $ok1 = false; $ok2 = false; @@ -3543,20 +3589,24 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } } + if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { + return self::checkVariance($expected, $existing, GenericTypeNode::VARIANCE_COVARIANT); + } + if ($expected instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExpectedUnionVariance($existing, $expected, $variance); + return self::checkExpectedUnionCovariant($existing, $expected); } if ($existing instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExistingUnionVariance($existing, $expected, $variance); + return self::checkExistingUnionCovariant($existing, $expected); } if ($expected instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExpectedIntersectionVariance($existing, $expected, $variance); + return self::checkExpectedIntersectionCovariant($existing, $expected); } if ($existing instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExistingIntersectionVariance($existing, $expected, $variance); + return self::checkExistingIntersectionCovariant($existing, $expected); } if ($existing instanceof ArrayTypeNode && $expected instanceof ArrayTypeNode) { @@ -3621,10 +3671,6 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str if ($expected instanceof IdentifierTypeNode) { $lowerExpected = strtolower($expected->name); - if ($lowerExpected === 'mixed' || $lowerExpected === '*') { - return true; - } - if ($existing instanceof ArrayTypeNode || $existing instanceof ArrayShapeNode) { if ($variance === GenericTypeNode::VARIANCE_COVARIANT && ($lowerExpected === 'array' || $lowerExpected === 'iterable')) { return true; @@ -3649,11 +3695,11 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { - return self::isSubclass((string) $existing->type, $expected->name); - } + if ($lowerExpected === 'object' && ClassNameValidator::isValid((string) $existing->type) && self::isRealTypeSymbol((string) $existing->type)) { + return true; + } - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - return self::isSubclass($expected->name, (string) $existing->type); + return self::isSubclass((string) $existing->type, $expected->name); } return false; @@ -3679,19 +3725,19 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($expected instanceof UnionTypeNode) { - return self::checkExpectedUnionVariance($existing, $expected, $variance); + return self::checkExpectedUnionCovariant($existing, $expected); } if ($existing instanceof UnionTypeNode) { - return self::checkExistingUnionVariance($existing, $expected, $variance); + return false; } if ($expected instanceof IntersectionTypeNode) { - return self::checkExpectedIntersectionVariance($existing, $expected, $variance); + return self::checkExpectedIntersectionCovariant($existing, $expected); } if ($existing instanceof IntersectionTypeNode) { - return self::checkExistingIntersectionVariance($existing, $expected, $variance); + return self::checkExistingIntersectionCovariant($existing, $expected); } $existingStr = (string) $existing; @@ -3716,10 +3762,6 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::isSubclass($existingStr, $expectedStr); } - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - return self::isSubclass($expectedStr, $existingStr); - } - return false; } @@ -3837,18 +3879,8 @@ private static function isScalarSubtype(string $sub, string $super): bool return false; } - private static function checkExpectedUnionVariance(TypeNode $existing, UnionTypeNode $expected, string $variance): bool + private static function checkExpectedUnionCovariant(TypeNode $existing, UnionTypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($expected->types as $unionVariant) { - if (! self::checkVariance($existing, $unionVariant, $variance)) { - return false; - } - } - - return true; - } - if ($existing instanceof IdentifierTypeNode) { self::$compiledUnionMembersCache ??= new WeakMap(); $compiled = self::$compiledUnionMembersCache[$expected] ?? null; @@ -3882,7 +3914,7 @@ private static function checkExpectedUnionVariance(TypeNode $existing, UnionType if ($existing instanceof UnionTypeNode) { foreach ($existing->types as $existingVariant) { - if (! self::checkExpectedUnionVariance($existingVariant, $expected, $variance)) { + if (! self::checkExpectedUnionCovariant($existingVariant, $expected)) { return false; } } @@ -3899,43 +3931,19 @@ private static function checkExpectedUnionVariance(TypeNode $existing, UnionType return false; } - private static function checkExistingUnionVariance(UnionTypeNode $existing, TypeNode $expected, string $variance): bool + private static function checkExistingUnionCovariant(UnionTypeNode $existing, TypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { - foreach ($existing->types as $existingVariant) { - if (! self::checkVariance($existingVariant, $expected, $variance)) { - return false; - } - } - - return true; - } - - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($existing->types as $existingVariant) { - if (self::checkVariance($existingVariant, $expected, $variance)) { - return true; - } + foreach ($existing->types as $existingVariant) { + if (! self::checkVariance($existingVariant, $expected, GenericTypeNode::VARIANCE_COVARIANT)) { + return false; } - - return false; } - return false; + return true; } - private static function checkExpectedIntersectionVariance(TypeNode $existing, IntersectionTypeNode $expected, string $variance): bool + private static function checkExpectedIntersectionCovariant(TypeNode $existing, IntersectionTypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($expected->types as $intersectionMember) { - if (! self::checkVariance($existing, $intersectionMember, $variance)) { - return false; - } - } - - return true; - } - foreach ($expected->types as $intersectionMember) { if (! self::checkVariance($existing, $intersectionMember, GenericTypeNode::VARIANCE_COVARIANT)) { return false; @@ -3945,18 +3953,8 @@ private static function checkExpectedIntersectionVariance(TypeNode $existing, In return true; } - private static function checkExistingIntersectionVariance(IntersectionTypeNode $existing, TypeNode $expected, string $variance): bool + private static function checkExistingIntersectionCovariant(IntersectionTypeNode $existing, TypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($existing->types as $existingMember) { - if (! self::checkVariance($existingMember, $expected, $variance)) { - return false; - } - } - - return true; - } - foreach ($existing->types as $existingMember) { if (self::checkVariance($existingMember, $expected, GenericTypeNode::VARIANCE_COVARIANT)) { return true; diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index e86556d5..7debc68f 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -17,7 +17,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.14.4_'; + public const VERSION_PREFIX = 'v0.15.0_'; /** * Config keys that only steer runtime behaviour and never change the transformed source. diff --git a/src/Internal/Io/StreamWrapper.php b/src/Internal/Io/StreamWrapper.php index 48442a9b..9483e4d9 100644 --- a/src/Internal/Io/StreamWrapper.php +++ b/src/Internal/Io/StreamWrapper.php @@ -307,19 +307,17 @@ public static function transformSource(string $source, string $filePath = ''): s $transformed = self::neutralizeTrailingLineComments($transformed); - $transformedLineCount = substr_count($transformed, "\n"); - $drift = $transformedLineCount - $originalLineCount; - - if ($drift > 0) { + if (str_contains($transformed, '/*__TYPEPHP_INJECTED_START__*/')) { $transformed = preg_replace( '/[ \t]*\r?\n[ \t]*\/\*__TYPEPHP_INJECTED_START__\*\//', ' /*__TYPEPHP_INJECTED_START__*/', - $transformed, - $drift + $transformed ) ?? $transformed; - $drift = substr_count($transformed, "\n") - $originalLineCount; } + $transformedLineCount = substr_count($transformed, "\n"); + $drift = $transformedLineCount - $originalLineCount; + if ($drift < 0) { $nl = str_contains($transformed, "\r\n") ? "\r\n" : "\n"; $transformed .= str_repeat($nl, abs($drift)); diff --git a/src/Internal/Reporting/ViolationCollector.php b/src/Internal/Reporting/ViolationCollector.php index 23998132..b4affef6 100644 --- a/src/Internal/Reporting/ViolationCollector.php +++ b/src/Internal/Reporting/ViolationCollector.php @@ -13,6 +13,7 @@ use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Resolver\HierarchyResolver; use TypePHP\Internal\Util\Config; +use TypePHP\Internal\Util\PathMatcher; /** * @internal Manages violation reporting, deduplication, warning dispatch, and parallel test sharding. @@ -825,8 +826,7 @@ private static function collectApplicationFrames(): array $normalizedFile = str_replace('\\', '/', $frame['file']); if ( - str_contains($normalizedFile, 'src/Internal/') - || str_contains($normalizedFile, 'bin/typephp') + PathMatcher::isLibraryInternal($normalizedFile) || str_contains($normalizedFile, 'vendor/phpunit/') || str_contains($normalizedFile, 'vendor/pestphp/') || str_contains($normalizedFile, 'vendor/composer/') diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 7f0f0941..5ab905d8 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -54,6 +54,7 @@ final class SpecialTypeResolver 'list' => true, 'object' => true, 'callable' => true, + 'pure-callable' => true, 'iterable' => true, 'resource' => true, 'null' => true, @@ -93,8 +94,14 @@ final class SpecialTypeResolver 'array-key' => true, 'literal-string' => true, 'truthy-string' => true, + 'non-falsy-string' => true, 'non-empty-array' => true, 'non-empty-list' => true, + 'non-empty-array-list' => true, + 'key-of' => true, + 'value-of' => true, + 'int-mask' => true, + 'int-mask-of' => true, 'number' => true, 'numeric' => true, 'truthy' => true, diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index b69a8f11..5aa10566 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -2370,9 +2370,9 @@ public static function checkReturn(string $function, mixed $value, object|string || ($tName === 'string' && \is_string($value)) || ($tName === 'bool' && \is_bool($value)) || ($tName === 'float' && (\is_float($value) || \is_int($value))) + || ($tName === 'array' && \is_array($value)) || (\is_object($value) && ($value instanceof $tName) && ! ($value instanceof Traversable)) || $tName === 'mixed' - || $tName === 'array' ) { return $value; } @@ -2478,7 +2478,7 @@ public static function checkReturn(string $function, mixed $value, object|string if ($resolvedType instanceof IdentifierTypeNode) { $lowerName = strtolower($resolvedType->name); - if ($lowerName === 'mixed' || $lowerName === 'array') { + if ($lowerName === 'mixed') { ReturnChecker::$noReturnContractCache[$effectiveFunction] = true; $unconstrainedPlan = [ 'class' => $declaringClass, @@ -2971,13 +2971,84 @@ public static function wrapIterable(string $function, string $paramName, mixed $ return IterableWrapper::wrap($function, $paramName, $iterable, self::$registry ??= new TypeValidatorRegistry(), $thisOrClass); } + /** + * Executes a clone expression with single operand evaluation and exception-safe generic binding propagation. + * + * @param \Closure(mixed): mixed $cloner + */ + public static function executeClone(mixed $original, \Closure $cloner): mixed + { + if (! \is_object($original)) { + return $cloner($original); + } + + TemplateManager::pushPendingCloneSource($original); + + try { + $cloned = $cloner($original); + } finally { + TemplateManager::popPendingCloneSource(); + } + + if (\is_object($cloned)) { + TemplateManager::copyInstanceBindings($original, $cloned); + } + + return $cloned; + } + + /** + * PHP 8.5: Executes clone($object, $withProperties) with single argument evaluation, + * exception-safe generic binding propagation, and overridden property validation. + * + * @param \Closure(mixed, mixed): mixed $cloner + */ + public static function executeCloneWith( + mixed $original, + mixed $overriddenProperties, + \Closure $cloner, + string $file = '', + ?int $line = null, + ): mixed { + if (! \is_object($original)) { + return $cloner($original, $overriddenProperties); + } + + TemplateManager::pushPendingCloneSource($original); + + try { + $cloned = $cloner($original, $overriddenProperties); + } finally { + TemplateManager::popPendingCloneSource(); + } + + if (! \is_object($cloned)) { + return $cloned; + } + + TemplateManager::copyInstanceBindings($original, $cloned); + + if (\is_array($overriddenProperties) && $overriddenProperties !== [] && self::$isEnabled && Config::isInlinePropertiesEnabled()) { + foreach ($overriddenProperties as $propName => $propValue) { + $res = self::checkProperty($propValue, $cloned, (string) $propName, $file); + if ($res instanceof ErrorMessage) { + $typeError = new \TypePHP\Exception\TypeError($res->getMessage()); + + throw ErrorFactory::prepareException($typeError, $line, $file !== '' ? $file : null); + } + } + } + + return $cloned; + } + /** * Registers a pending clone source object before clone execution. */ public static function prepareClone(mixed $original): mixed { if (\is_object($original)) { - TemplateManager::$pendingCloneSource = $original; + TemplateManager::pushPendingCloneSource($original); } return $original; @@ -2986,13 +3057,14 @@ public static function prepareClone(mixed $original): mixed /** * Copies generic template bindings from an original object to a cloned object instance. */ - public static function cloneInstance(mixed $cloned, mixed $original): mixed + public static function cloneInstance(mixed $cloned, mixed $original = null): mixed { - if (\is_object($cloned) && \is_object($original)) { - TemplateManager::copyInstanceBindings($original, $cloned); - } + $popped = TemplateManager::popPendingCloneSource(); + $source = \is_object($original) ? $original : $popped; - TemplateManager::$pendingCloneSource = null; + if (\is_object($cloned) && \is_object($source)) { + TemplateManager::copyInstanceBindings($source, $cloned); + } return $cloned; } @@ -3009,8 +3081,8 @@ public static function cloneWith( string $file = '', ?int $line = null, ): mixed { - $source = \is_object($original) ? $original : TemplateManager::$pendingCloneSource; - TemplateManager::$pendingCloneSource = null; + $popped = TemplateManager::popPendingCloneSource(); + $source = \is_object($original) ? $original : $popped; if (! \is_object($cloned) || ! \is_object($source)) { return $cloned; @@ -3018,7 +3090,7 @@ public static function cloneWith( TemplateManager::copyInstanceBindings($source, $cloned); - if ($overriddenProperties !== null && $overriddenProperties !== [] && Config::isInlinePropertiesEnabled()) { + if ($overriddenProperties !== null && $overriddenProperties !== [] && self::$isEnabled && Config::isInlinePropertiesEnabled()) { foreach ($overriddenProperties as $propName => $propValue) { $res = self::checkProperty($propValue, $cloned, (string) $propName, $file); if ($res instanceof ErrorMessage) { @@ -3032,6 +3104,38 @@ public static function cloneWith( return $cloned; } + /** + * Evaluates PHP's native increment (++) semantics without mutating the caller's slot. + */ + public static function computeInc(mixed $value): mixed + { + if (\is_int($value) || \is_float($value)) { + return $value + 1; + } + + $copy = $value; + /** @phpstan-ignore preInc.type */ + ++$copy; + + return $copy; + } + + /** + * Evaluates PHP's native decrement (--) semantics without mutating the caller's slot. + */ + public static function computeDec(mixed $value): mixed + { + if (\is_int($value) || \is_float($value)) { + return $value - 1; + } + + $copy = $value; + /** @phpstan-ignore preDec.type */ + --$copy; + + return $copy; + } + /** * Infers a TypeNode AST representation from a raw PHP value. */ diff --git a/src/Internal/Util/PathMatcher.php b/src/Internal/Util/PathMatcher.php index 101e4a1f..e2ff2e60 100644 --- a/src/Internal/Util/PathMatcher.php +++ b/src/Internal/Util/PathMatcher.php @@ -46,6 +46,11 @@ final class PathMatcher */ private static ?string $cachedLibSrcDir = null; + /** + * Cached lowercase TypePHP CLI binary path. + */ + private static ?string $cachedLibBinPath = null; + /** * Cache for canonicalized paths. * @@ -64,6 +69,7 @@ public static function reset(): void self::$canonicalPathCache = []; self::$cachedCacheDir = null; self::$cachedLibSrcDir = null; + self::$cachedLibBinPath = null; CacheManager::reset(); } @@ -204,6 +210,9 @@ public static function isLibraryInternal(string $normalizedPath): bool if (self::$cachedLibSrcDir === null) { $parentDir = realpath(\dirname(__DIR__, 2)); self::$cachedLibSrcDir = $parentDir !== false ? rtrim(self::normalizePath($parentDir), '/') . '/' : ''; + self::$cachedLibBinPath = $parentDir !== false + ? strtolower(rtrim(self::normalizePath(\dirname($parentDir)), '/') . '/bin/typephp') + : ''; } $libSrcDir = self::$cachedLibSrcDir; @@ -215,6 +224,14 @@ public static function isLibraryInternal(string $normalizedPath): bool $lowerCanon = strtolower($canon); $lowerLibSrcDir = strtolower($libSrcDir); + if ( + (self::$cachedLibBinPath !== null && self::$cachedLibBinPath !== '' && $lowerCanon === self::$cachedLibBinPath) + || str_ends_with($lowerCanon, '/vendor/bin/typephp') + || $lowerCanon === 'vendor/bin/typephp' + ) { + return true; + } + if (str_contains($lowerLibSrcDir, '/vendor/')) { return str_starts_with($lowerCanon, $lowerLibSrcDir); } diff --git a/tests/Fixtures/Domain/EliminationBox.php b/tests/Fixtures/Domain/EliminationBox.php new file mode 100644 index 00000000..cdef231d --- /dev/null +++ b/tests/Fixtures/Domain/EliminationBox.php @@ -0,0 +1,24 @@ +item = $item; + } +} diff --git a/tests/Internal/Ast/ContractVisitorTest.php b/tests/Internal/Ast/ContractVisitorTest.php index b0927ed9..2fbc9e8d 100644 --- a/tests/Internal/Ast/ContractVisitorTest.php +++ b/tests/Internal/Ast/ContractVisitorTest.php @@ -93,8 +93,8 @@ class HookedClass { $transformed = $this->printer->prettyPrint($newStmts); - expect($transformed)->toContain('RuntimeTypeChecker::checkVariable($val + 1, \'positive-int\', \'val\'') - ->and($transformed)->toContain('RuntimeTypeChecker::checkVariable($val - 1, \'positive-int\', \'val\'') + expect($transformed)->toContain('RuntimeTypeChecker::checkVariable(\TypePHP\Internal\RuntimeTypeChecker::computeInc($val), \'positive-int\', \'val\'') + ->and($transformed)->toContain('RuntimeTypeChecker::checkVariable(\TypePHP\Internal\RuntimeTypeChecker::computeDec($val), \'positive-int\', \'val\'') ; }); @@ -142,7 +142,7 @@ public function set() { ; }); - test('transforms clone expressions into prepareClone and cloneInstance wrappers', function () { + test('transforms clone expressions into executeClone wrappers', function () { $code = <<<'PHP' printer->prettyPrint($newStmts); - expect($transformed)->toContain('RuntimeTypeChecker::cloneInstance') - ->and($transformed)->toContain('RuntimeTypeChecker::prepareClone($original)') + expect($transformed)->toContain('RuntimeTypeChecker::executeClone($original,') + ->and($transformed)->toContain('clone $__typephpCloneSrc') ; }); @@ -398,8 +398,8 @@ public function enumMethod() { expect($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$className::\$staticCount + 5, \$className, 'staticCount'") ->and($transformed)->toContain('$__typephpTgt0 = $getObj()') - ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$__typephpTgt0::\$staticCount + 1, \$__typephpTgt0, 'staticCount'") - ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$className::\$staticCount2 - 1, \$className, 'staticCount2'") + ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\\TypePHP\\Internal\\RuntimeTypeChecker::computeInc(\$__typephpTgt0::\$staticCount), \$__typephpTgt0, 'staticCount'") + ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\\TypePHP\\Internal\\RuntimeTypeChecker::computeDec(\$className::\$staticCount2), \$className, 'staticCount2'") ; }); diff --git a/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorKeySoundnessTest.php b/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorKeySoundnessTest.php new file mode 100644 index 00000000..c05d3429 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorKeySoundnessTest.php @@ -0,0 +1,346 @@ + + */ +function elimNumericStringKeyToStringMap(): array +{ + return ['123' => 'hello']; +} + +/** + * @return array + */ +function elimZeroStringKeyToStringMap(): array +{ + return ['0' => 'zero']; +} + +/** + * @return array + */ +function elimDynamicNumericConcatKey(string $suffix): array +{ + return ['1' . $suffix => 'val']; +} + +/** + * @return array + */ +function elimDynamicNumericInterpolatedKey(string $suffix): array +{ + return ["1{$suffix}" => 'val']; +} + +/** + * @return array<0|5, string> + */ +function elimStringIntKeyShiftsAutoKey(): array +{ + return ['5' => 'five', 'six']; +} + +/** + * @return array{'5': string, 0: int} + */ +function elimShapeStringKeyAutoIndexMismatch(): array +{ + return ['5' => 'five', 99]; +} + +/** + * @return array{-5: string, 0: int} + */ +function elimShapeNegativeKeyAutoIndexMismatch(): array +{ + return [-5 => 'neg', 99]; +} + +/** + * @return array + */ +function elimValidNonCanonicalStringKeys(): array +{ + return [ + '01' => 'leading-zero', + '-0' => 'neg-zero', + '+1' => 'plus-one', + '1.0' => 'dot-zero', + ' 1' => 'leading-space', + '9223372036854775808' => 'overflow', + ]; +} + +/** + * @return array + */ +function elimValidNonNumericInterpolatedKey(int $id): array +{ + return ["user_{$id}" => 'ok']; +} + +describe('ArrayLiteralEvaluator Key Coercion & Auto-Index Soundness', function () { + beforeEach(function () { + Config::set(['eliminate_statically_proven_checks' => true]); + }); + + afterEach(function () { + Config::reset(); + }); + + describe('Numeric string key coercion in array', function () { + test('does not satisfy array for canonical numeric string keys', function () { + $stringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('string'), + ]); + $nonEmptyStringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('string'), + ]); + + foreach (['0', '1', '-1', '123', '-42', (string) PHP_INT_MAX, (string) PHP_INT_MIN] as $numStr) { + $arr = new Array_([new ArrayItem(new String_('val'), new String_($numStr))]); + + expect(StaticTypeEvaluator::satisfies($arr, $stringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arr, $nonEmptyStringMap))->toBeFalse(); + } + }); + + test('throws TypeError at runtime instead of eliminating numeric string keys in array', function () { + expect(fn () => elimNumericStringKeyToStringMap()) + ->toThrow(TypeError::class, 'key must be of type string') + ; + + expect(fn () => elimZeroStringKeyToStringMap()) + ->toThrow(TypeError::class, 'key must be of type string') + ; + }); + + test('evaluates canonical numeric string keys as int against constrained int key types', function () { + $posIntMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('positive-int'), + new IdentifierTypeNode('string'), + ]); + $intMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('int'), + new IdentifierTypeNode('string'), + ]); + + $negArr = new Array_([new ArrayItem(new String_('val'), new String_('-5'))]); + $posArr = new Array_([new ArrayItem(new String_('val'), new String_('5'))]); + + expect(StaticTypeEvaluator::satisfies($negArr, $posIntMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($negArr, $intMap))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($posArr, $posIntMap))->toBeTrue(); + }); + + test('still eliminates non-canonical numeric strings for array', function () { + expect(elimValidNonCanonicalStringKeys())->toBe([ + '01' => 'leading-zero', + '-0' => 'neg-zero', + '+1' => 'plus-one', + '1.0' => 'dot-zero', + ' 1' => 'leading-space', + '9223372036854775808' => 'overflow', + ]); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function elimValidNonCanonicalStringKeys\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkReturn'); + }); + }); + + describe('Dynamic Concat and Encapsed key coercion risk', function () { + test('does not eliminate Concat or Encapsed keys that may coerce to integer keys against string/non-empty-string', function () { + $stringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('string'), + ]); + $nonEmptyStringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('string'), + ]); + $arrayKeyMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('array-key'), + new IdentifierTypeNode('string'), + ]); + + $concatKey = new Concat(new String_('1'), new Variable('suffix')); + $encapsedKey = new Encapsed([new EncapsedStringPart('1'), new Variable('suffix')]); + + $arrConcat = new Array_([new ArrayItem(new String_('val'), $concatKey)]); + $arrEncapsed = new Array_([new ArrayItem(new String_('val'), $encapsedKey)]); + + expect(StaticTypeEvaluator::satisfies($arrConcat, $stringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arrConcat, $nonEmptyStringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arrEncapsed, $stringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arrEncapsed, $nonEmptyStringMap))->toBeFalse(); + + expect(StaticTypeEvaluator::satisfies($arrConcat, $arrayKeyMap))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($arrEncapsed, $arrayKeyMap))->toBeTrue(); + }); + + test('throws TypeError at runtime when dynamic Concat or Encapsed key coerces to int', function () { + expect(fn () => elimDynamicNumericConcatKey('23')) + ->toThrow(TypeError::class, 'key must be of type string') + ; + + expect(fn () => elimDynamicNumericInterpolatedKey('')) + ->toThrow(TypeError::class, 'key must be of type non-empty-string') + ; + }); + + test('still eliminates Concat and Encapsed keys guaranteed non-numeric by static chunks', function () { + expect(elimValidNonNumericInterpolatedKey(7))->toBe(['user_7' => 'ok']); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function elimValidNonNumericInterpolatedKey\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkReturn'); + }); + }); + + describe('Auto-increment index synchronization after numeric string and negative keys', function () { + test('advances auto-key index after numeric string keys in array and shapes', function () { + $union0Or5Map = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new UnionTypeNode([ + new ConstTypeNode(new ConstExprIntegerNode('0')), + new ConstTypeNode(new ConstExprIntegerNode('5')), + ]), + new IdentifierTypeNode('string'), + ]); + $union5Or6Map = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new UnionTypeNode([ + new ConstTypeNode(new ConstExprIntegerNode('5')), + new ConstTypeNode(new ConstExprIntegerNode('6')), + ]), + new IdentifierTypeNode('string'), + ]); + + $arr = new Array_([ + new ArrayItem(new String_('five'), new String_('5')), + new ArrayItem(new String_('six')), + ]); + + expect(StaticTypeEvaluator::satisfies($arr, $union0Or5Map))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arr, $union5Or6Map))->toBeTrue(); + + expect(fn () => elimStringIntKeyShiftsAutoKey()) + ->toThrow(TypeError::class, 'key') + ; + }); + + test('handles negative integer keys using PHP 8+ auto-index rules in shapes and maps', function () { + $shapeMinus5AndMinus4 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-4'), false, new IdentifierTypeNode('int')), + ]); + $shapeMinus5And0 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('0'), false, new IdentifierTypeNode('int')), + ]); + + $negLitArr = new Array_([ + new ArrayItem(new String_('neg'), new UnaryMinus(new LNumber(5))), + new ArrayItem(new LNumber(99)), + ]); + $negStrArr = new Array_([ + new ArrayItem(new String_('neg'), new String_('-5')), + new ArrayItem(new LNumber(99)), + ]); + $strThenNegArr = new Array_([ + new ArrayItem(new String_('x'), new String_('foo')), + new ArrayItem(new String_('neg'), new UnaryMinus(new LNumber(5))), + new ArrayItem(new LNumber(99)), + ]); + + $shapeFooMinus5Minus4 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('foo', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-4'), false, new IdentifierTypeNode('int')), + ]); + $shapeFooMinus5And0 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('foo', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('0'), false, new IdentifierTypeNode('int')), + ]); + + expect(StaticTypeEvaluator::satisfies($negLitArr, $shapeMinus5AndMinus4))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($negStrArr, $shapeMinus5AndMinus4))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($negLitArr, $shapeMinus5And0))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($negStrArr, $shapeMinus5And0))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($strThenNegArr, $shapeFooMinus5Minus4))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($strThenNegArr, $shapeFooMinus5And0))->toBeFalse(); + + expect(fn () => elimShapeStringKeyAutoIndexMismatch()) + ->toThrow(TypeError::class) + ; + + expect(fn () => elimShapeNegativeKeyAutoIndexMismatch()) + ->toThrow(TypeError::class) + ; + }); + + test('matches PHP auto-key after explicit positive then negative keys ([2 => a, -5 => b, c] => key 3)', function () { + $shapeValid = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('2'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('3'), false, new IdentifierTypeNode('string')), + ]); + $shapeWrong = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('2'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-4'), false, new IdentifierTypeNode('string')), + ]); + + $arr = new Array_([ + new ArrayItem(new String_('a'), new LNumber(2)), + new ArrayItem(new String_('b'), new UnaryMinus(new LNumber(5))), + new ArrayItem(new String_('c')), + ]); + + expect(StaticTypeEvaluator::satisfies($arr, $shapeValid))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($arr, $shapeWrong))->toBeFalse(); + + $shape5And6 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('6'), false, new IdentifierTypeNode('int')), + ]); + $shape5And0 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('5', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('0'), false, new IdentifierTypeNode('int')), + ]); + + $str5Arr = new Array_([ + new ArrayItem(new String_('five'), new String_('5')), + new ArrayItem(new LNumber(99)), + ]); + + expect(StaticTypeEvaluator::satisfies($str5Arr, $shape5And0))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($str5Arr, $shape5And6))->toBeTrue(); + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/FullyQualifiedNameEliminationTest.php b/tests/Internal/Ast/Elimination/FullyQualifiedNameEliminationTest.php new file mode 100644 index 00000000..72aca7d9 --- /dev/null +++ b/tests/Internal/Ast/Elimination/FullyQualifiedNameEliminationTest.php @@ -0,0 +1,352 @@ + + */ + public static function returnGlobalIntMask(): int + { + return \FqnElimConst::FLAG_A; + } + + /** + * @return FqnElimStatus + */ + public static function returnGlobalEnumCase(): mixed + { + return \FqnElimStatus::Active; + } + + /** + * @return value-of + */ + public static function returnGlobalEnumValue(): string + { + return \FqnElimStatus::Active->value; + } + + /** + * @return FqnElimUser + */ + public static function validFqnNew(): mixed + { + return new \FqnElimOther\FqnElimUser(); + } + + /** + * @return \FqnElimOther\FqnElimUser + */ + public static function validImportedNew(): mixed + { + return new FqnElimUser(); + } + + /** + * @return \FqnElimApp\FqnElimUser + */ + public static function validRelativeNew(): mixed + { + return new namespace\FqnElimUser(); + } + + /** + * @return FqnElimConst::STATUS_OK + */ + public static function validFqnConst(): mixed + { + return \FqnElimOther\FqnElimConst::STATUS_OK; + } + + /** + * @return FqnElimStatus + */ + public static function validFqnEnum(): mixed + { + return \FqnElimOther\FqnElimStatus::Active; + } + + /** + * @return value-of + */ + public static function validFqnEnumValue(): string + { + return \FqnElimOther\FqnElimStatus::Active->value; + } +} +PHP); + + file_put_contents($shadowFile, <<<'PHP' + $includes, + 'eliminate_statically_proven_checks' => true, + ]); + + require_once $globalFile; + require_once $otherFile; + require_once $localFile; + require_once $serviceFile; +}); + +afterEach(function () { + Config::reset(); +}); + +afterAll(function () use (&$fqnElimTmpDir, &$fqnElimFiles) { + Config::reset(); + + foreach ($fqnElimFiles as $file) { + if (file_exists($file)) { + @unlink($file); + } + } + + if ($fqnElimTmpDir !== null) { + @rmdir($fqnElimTmpDir); + } +}); + +describe('Compile-Time Elimination with FullyQualified and Relative Class Names', function () use (&$fqnElimAppServiceFile, &$fqnElimShadowFile) { + describe('ObjectEvaluator (new \Foo and new namespace\Foo)', function () use (&$fqnElimShadowFile) { + test('does not eliminate return check when new \FqnElimUser() mismatches imported @return FqnElimUser', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalNew()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimUser') + ; + }); + + test('does not eliminate return check when new namespace\FqnElimUser() mismatches imported @return FqnElimUser', function () { + expect(fn () => FqnElimApp\AppService::returnRelativeNew()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimUser') + ; + }); + + test('does not treat unimported namespaced new DateTime() as global \DateTime', function () use (&$fqnElimShadowFile) { + $satisfied = StaticTypeEvaluator::satisfies( + new New_(new Name('DateTime')), + new IdentifierTypeNode('\DateTime'), + (string) $fqnElimShadowFile, + [], + 'FqnElimShadow' + ); + + expect($satisfied)->toBeFalse(); + }); + + test('does not match FullyQualified \User against unqualified User without file context', function () { + $satisfied = StaticTypeEvaluator::satisfies( + new New_(new FullyQualified('User')), + new IdentifierTypeNode('User') + ); + + expect($satisfied)->toBeFalse(); + }); + }); + + describe('ConstantAndEnumEvaluator (\Foo::CONST, int-mask-of, enums, value-of)', function () { + test('does not eliminate return check for \FqnElimConst::STATUS_OK against imported FqnElimConst::STATUS_OK', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalConst()) + ->toThrow(TypeError::class) + ; + }); + + test('does not eliminate return check for \FqnElimConst::STATUS_OK against imported FqnElimConst::STATUS_*', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalConstWildcard()) + ->toThrow(TypeError::class) + ; + }); + + test('does not eliminate return check for \FqnElimConst::FLAG_A against imported int-mask-of', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalIntMask()) + ->toThrow(TypeError::class) + ; + }); + + test('does not eliminate return check for \FqnElimStatus::Active against imported FqnElimStatus', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalEnumCase()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimStatus') + ; + }); + + test('does not eliminate return check for \FqnElimStatus::Active->value against imported value-of', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalEnumValue()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimStatus') + ; + }); + }); + + describe('Legitimate FullyQualified and Relative matches still eliminate checks', function () use (&$fqnElimAppServiceFile) { + test('still eliminates checks when resolved FQCNs genuinely match', function () use (&$fqnElimAppServiceFile) { + expect(FqnElimApp\AppService::validFqnNew())->toBeInstanceOf(FqnElimOther\FqnElimUser::class); + expect(FqnElimApp\AppService::validImportedNew())->toBeInstanceOf(FqnElimOther\FqnElimUser::class); + expect(FqnElimApp\AppService::validRelativeNew())->toBeInstanceOf(FqnElimApp\FqnElimUser::class); + expect(FqnElimApp\AppService::validFqnConst())->toBe('other_ok'); + expect(FqnElimApp\AppService::validFqnEnum())->toBe(FqnElimOther\FqnElimStatus::Active); + expect(FqnElimApp\AppService::validFqnEnumValue())->toBe('other_active'); + + $source = file_get_contents((string) $fqnElimAppServiceFile); + expect($source)->toBeString(); + + $transformed = StreamWrapper::transformSource((string) $source, (string) $fqnElimAppServiceFile); + + foreach (['validFqnNew', 'validImportedNew', 'validRelativeNew', 'validFqnConst', 'validFqnEnum', 'validFqnEnumValue'] as $method) { + $pattern = '/function ' . $method . '\b.*?\{(.*?)\}/s'; + preg_match($pattern, $transformed, $matches); + expect($matches[1] ?? null)->not->toBeNull(); + expect($matches[1])->not->toContain('checkReturn'); + } + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/FunctionContractEliminationEdgeCasesTest.php b/tests/Internal/Ast/Elimination/FunctionContractEliminationEdgeCasesTest.php new file mode 100644 index 00000000..b9d68712 --- /dev/null +++ b/tests/Internal/Ast/Elimination/FunctionContractEliminationEdgeCasesTest.php @@ -0,0 +1,174 @@ + + */ +function genYieldWithKeyPostDec(): Generator +{ + $val = 1; + yield ($val--) => $val; +} + +/** + * @return Generator + */ +function genYieldWithKeyAssignOp(): Generator +{ + $val = 1; + yield ($val -= 5) => $val; +} + +/** + * @return Generator + */ +function genYieldWithNestedKeyAssign(): Generator +{ + $val = 1; + yield ($tmp = ($val = -3)) => $val; +} + +/** + * @return Generator + */ +function genYieldWithKeyByRefCall(): Generator +{ + $val = 1; + yield mutateRefToNegative($val) => $val; +} + +/** + * @return Generator + */ +function genYieldWithPureKey(): Generator +{ + $key = 0; + $val = 42; + yield $key => $val; +} + +describe('FunctionContractInjector Static Elimination Edge Cases', function () { + afterEach(function () { + Config::reset(); + }); + + describe('Implicitly nullable native parameter (int $x = null) under strict nullability', function () { + test('does not eliminate setupScope for int $x = null when respect_native_nullability is false', function () { + $baseTmp = sys_get_temp_dir() . '/typephp_implicit_null_' . uniqid('', true); + mkdir($baseTmp, 0777, true); + $realBase = realpath($baseTmp); + $tmpDir = str_replace('\\', '/', $realBase !== false ? $realBase : $baseTmp); + $scriptPath = $tmpDir . '/implicit_nullable.php'; + + $source = <<<'PHP' + $includes, + 'respect_native_nullability' => false, + 'eliminate_statically_proven_checks' => true, + ]); + + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $transformed = StreamWrapper::transformSource($source, $scriptPath); + + preg_match('/function strictImplicitNullReject\b.*?\{(.*?)\}/s', $transformed, $rejectMatch); + preg_match('/function strictImplicitNullExplicitDoc\b.*?\{(.*?)\}/s', $transformed, $allowMatch); + preg_match('/function strictImplicitNullReturnBypass\b.*?\{(.*?)\}/s', $transformed, $retMatch); + + expect($rejectMatch[1] ?? '')->toContain('setupScope'); + expect($allowMatch[1] ?? '')->not->toContain('setupScope'); + expect($retMatch[1] ?? '')->toContain('checkReturn'); + + require_once $scriptPath; + + expect(strictImplicitNullReject(5))->toBe(5); + expect(strictImplicitNullExplicitDoc(null))->toBeNull(); + expect(fn () => strictImplicitNullReject(null)) + ->toThrow(TypeError::class, 'Argument $x must be of type int') + ; + expect(strictImplicitNullReturnBypass(5))->toBe(5); + expect(fn () => strictImplicitNullReturnBypass(null)) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; + } finally { + restore_error_handler(); + @unlink($scriptPath); + @rmdir($tmpDir); + } + }); + }); + + describe('Generator yield $key => $val preceding assignment tagging', function () { + test('does not eliminate checkYield when yield key mutates the yielded variable', function () { + expect(fn () => iterator_to_array(genYieldWithKeyPostDec())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + expect(fn () => iterator_to_array(genYieldWithKeyAssignOp())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + expect(fn () => iterator_to_array(genYieldWithNestedKeyAssign())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + expect(fn () => iterator_to_array(genYieldWithKeyByRefCall())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + }); + + test('still eliminates checkYield when yield key is pure and preceding value is proven', function () { + expect(iterator_to_array(genYieldWithPureKey()))->toBe([0 => 42]); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function genYieldWithPureKey\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkYield'); + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/IntMaskOfConstantSoundnessTest.php b/tests/Internal/Ast/Elimination/IntMaskOfConstantSoundnessTest.php new file mode 100644 index 00000000..fde66673 --- /dev/null +++ b/tests/Internal/Ast/Elimination/IntMaskOfConstantSoundnessTest.php @@ -0,0 +1,236 @@ + + */ +function returnStringFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_LABEL; +} + +/** + * @return int-mask-of + */ +function returnFloatFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_FLOAT; +} + +/** + * @return int-mask-of + */ +function returnBoolFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_BOOL; +} + +/** + * @return int-mask-of + */ +function returnArrayFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_ARRAY; +} + +/** + * @return int-mask-of + */ +function returnBitwiseOrWithStringFlag(): mixed +{ + return IntMaskFlagsFixture::FLAG_STR_NUM_A | IntMaskFlagsFixture::FLAG_STR_NUM_B; +} + +/** + * @return int-mask-of + */ +function returnBitwiseOrWithFloatFlag(): int +{ + return IntMaskFlagsFixture::FLAG_FLOAT_OUT | IntMaskFlagsFixture::FLAG_READ; +} + +final class SelfMaskFlagsFixture +{ + public const FLAG_READ = 1; + public const FLAG_LABEL = 'read'; + + /** + * @return int-mask-of + */ + public function returnSelfNonIntFlag(): mixed + { + return self::FLAG_LABEL; + } +} + +/** + * @return int-mask-of + */ +function returnExactStringFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_LABEL; +} + +/** + * @return int-mask-of + */ +function returnBackedEnumCaseInIntMask(): mixed +{ + return IntMaskBackedEnumFixture::FLAG_CASE; +} + +/** + * @return int-mask-of + */ +function returnValidIntFlagsMask(): int +{ + return IntMaskFlagsFixture::FLAG_READ | IntMaskFlagsFixture::FLAG_WRITE; +} + +describe('ConstantAndEnumEvaluator int-mask-of Soundness', function () { + beforeEach(function () { + Config::set(['eliminate_statically_proven_checks' => true]); + }); + + afterEach(function () { + Config::reset(); + }); + + test('does not satisfy int-mask-of when matching constant is string, float, bool, array, or null', function () { + $maskWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_*')), + ]); + $maskExactNonInt = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_LABEL')), + ]); + + foreach (['FLAG_LABEL', 'FLAG_FLOAT', 'FLAG_BOOL', 'FLAG_ARRAY', 'FLAG_NULL'] as $constName) { + $fetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier($constName)); + expect(StaticTypeEvaluator::satisfies($fetch, $maskWildcard, __FILE__))->toBeFalse(); + } + + $labelFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_LABEL')); + expect(StaticTypeEvaluator::satisfies($labelFetch, $maskExactNonInt, __FILE__))->toBeFalse(); + }); + + test('does not satisfy int-mask-of when BitwiseOr includes a non-int constant', function () { + $maskWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_*')), + ]); + + $intFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_READ')); + $strFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_LABEL')); + $floatFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_FLOAT')); + + expect(StaticTypeEvaluator::satisfies(new BitwiseOr($intFetch, $strFetch), $maskWildcard, __FILE__))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies(new BitwiseOr($intFetch, $floatFetch), $maskWildcard, __FILE__))->toBeFalse(); + }); + + test('does not satisfy int-mask-of when matching symbol is an enum case object', function () { + $maskEnumWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskBackedEnumFixture::class, 'FLAG_*')), + ]); + + $enumFetch = new ClassConstFetch(new Name(IntMaskBackedEnumFixture::class), new Identifier('FLAG_CASE')); + + expect(StaticTypeEvaluator::satisfies($enumFetch, $maskEnumWildcard, __FILE__))->toBeFalse(); + }); + + test('does not satisfy int-mask-of for unloaded external classes', function () { + $unloadedClass = 'NonExistentUnloadedFlags_' . bin2hex(random_bytes(4)); + $mask = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode('\\' . $unloadedClass, 'FLAG_*')), + ]); + $fetch = new ClassConstFetch(new FullyQualified($unloadedClass), new Identifier('FLAG_A')); + + expect(StaticTypeEvaluator::satisfies($fetch, $mask, __FILE__))->toBeFalse(); + }); + + test('retains checkReturn and throws TypeError at runtime for non-int constants matching int-mask-of', function () { + expect(fn () => returnStringFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnFloatFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBoolFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnArrayFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBitwiseOrWithStringFlag()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBitwiseOrWithFloatFlag()) + ->toThrow(TypeError::class, 'must be a valid bitmask combination') + ; + + expect(fn () => (new SelfMaskFlagsFixture())->returnSelfNonIntFlag()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnExactStringFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBackedEnumCaseInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + }); + + test('still eliminates int-mask-of checks for genuine loaded integer constants and bitwise ORs', function () { + $maskWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_*')), + ]); + + $readFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_READ')); + $writeFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_WRITE')); + + expect(StaticTypeEvaluator::satisfies($readFetch, $maskWildcard, __FILE__))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies(new BitwiseOr($readFetch, $writeFetch), $maskWildcard, __FILE__))->toBeTrue(); + expect(returnValidIntFlagsMask())->toBe(3); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function returnValidIntFlagsMask\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkReturn'); + }); +}); diff --git a/tests/Internal/Checker/PropertyOpcodeParityTest.php b/tests/Internal/Checker/PropertyOpcodeParityTest.php new file mode 100644 index 00000000..9f252daa --- /dev/null +++ b/tests/Internal/Checker/PropertyOpcodeParityTest.php @@ -0,0 +1,63 @@ +getConstants() as $name => $value) { + if (str_starts_with($name, 'OP_') && $name !== 'OP_FALLBACK') { + $memberOps[$name] = $value; + } + } + + $runtimeOps = []; + foreach ($runtimeRef->getConstants() as $name => $value) { + if (str_starts_with($name, 'PROP_OP_')) { + $runtimeOps[substr($name, 5)] = $value; + } + } + + expect($memberOps)->not->toBeEmpty(); + expect($runtimeOps)->toBe($memberOps); + }); + + test('all RuntimeTypeChecker PROP_BIT_* constants match MemberAssignChecker BIT_* constants and are distinct powers of two', function () { + $memberRef = new ReflectionClass(MemberAssignChecker::class); + $runtimeRef = new ReflectionClass(RuntimeTypeChecker::class); + + $memberBits = []; + foreach ($memberRef->getConstants() as $name => $value) { + if (str_starts_with($name, 'BIT_')) { + $memberBits[$name] = $value; + } + } + + $runtimeBits = []; + foreach ($runtimeRef->getConstants() as $name => $value) { + if (str_starts_with($name, 'PROP_BIT_')) { + $runtimeBits[substr($name, 5)] = $value; + } + } + + expect($memberBits)->not->toBeEmpty(); + expect($runtimeBits)->toBe($memberBits); + + $combinedMask = 0; + foreach ($memberBits as $name => $bit) { + expect($bit)->toBeInt() + ->and($bit)->toBeGreaterThan(0) + ->and(($bit & ($bit - 1)))->toBe(0, "{$name} must be a power of two") + ->and(($combinedMask & $bit))->toBe(0, "{$name} collides with another bitmask") + ; + + $combinedMask |= $bit; + } + }); +}); diff --git a/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php b/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php new file mode 100644 index 00000000..c782dd98 --- /dev/null +++ b/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php @@ -0,0 +1,215 @@ + $includes, + ]); + + require_once $servicePath; + require_once $callerPath; +}); + +afterEach(function () { + Config::reset(); +}); + +afterAll(function () use (&$userInternalTmpDir, &$userInternalServiceFile, &$userInternalCallerFile) { + Config::reset(); + + if ($userInternalServiceFile !== null && file_exists($userInternalServiceFile)) { + @unlink($userInternalServiceFile); + } + if ($userInternalCallerFile !== null && file_exists($userInternalCallerFile)) { + @unlink($userInternalCallerFile); + } + if ($userInternalTmpDir !== null) { + @rmdir($userInternalTmpDir . '/src/Internal'); + @rmdir($userInternalTmpDir . '/src'); + @rmdir($userInternalTmpDir); + } +}); + +describe('User project src/Internal/ stack traces & violation attribution', function () use (&$userInternalServiceFile, &$userInternalCallerFile) { + test('ErrorFactory preserves user src/Internal/ call-site file, line, and trace on parameter TypeError', function () use (&$userInternalCallerFile) { + $caught = null; + + try { + UserAppInternalTest\Internal\UserCaller::triggerParamViolation(); + } catch (TypeError $e) { + $caught = $e; + } + + expect($caught)->toBeInstanceOf(TypeError::class); + expect(str_replace('\\', '/', $caught->getFile()))->toBe($userInternalCallerFile); + expect($caught->getLine())->toBe(11); + + $traceFiles = array_values(array_filter(array_map( + static fn (array $frame): ?string => isset($frame['file']) ? str_replace('\\', '/', $frame['file']) : null, + $caught->getTrace() + ))); + + expect($traceFiles)->toContain($userInternalCallerFile); + + foreach ($traceFiles as $traceFile) { + expect(PathMatcher::isLibraryInternal($traceFile))->toBeFalse(); + } + }); + + test('ErrorFactory preserves user src/Internal/ caller frame in trace on return TypeError', function () use (&$userInternalServiceFile, &$userInternalCallerFile) { + $caught = null; + + try { + UserAppInternalTest\Internal\UserCaller::triggerReturnViolation(); + } catch (TypeError $e) { + $caught = $e; + } + + expect($caught)->toBeInstanceOf(TypeError::class); + expect(str_replace('\\', '/', $caught->getFile()))->toBe($userInternalServiceFile); + expect($caught->getLine())->toBe(22); + + $traceFiles = array_values(array_filter(array_map( + static fn (array $frame): ?string => isset($frame['file']) ? str_replace('\\', '/', $frame['file']) : null, + $caught->getTrace() + ))); + + expect($traceFiles)->toContain($userInternalCallerFile); + + foreach ($traceFiles as $traceFile) { + expect(PathMatcher::isLibraryInternal($traceFile))->toBeFalse(); + } + }); + + test('ViolationCollector attributes report-mode parameter violations to user src/Internal/ caller', function () use (&$userInternalCallerFile) { + Config::set([ + 'on_violation' => 'report', + 'report_file' => null, + ]); + + UserAppInternalTest\Internal\UserCaller::triggerParamViolation(); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(1); + expect($violations[0]->file)->toBe($userInternalCallerFile); + expect($violations[0]->line)->toBe(11); + expect($violations[0]->caller)->toContain('src/Internal/UserCaller.php:11'); + }); + + test('ViolationCollector attributes report-mode return violations to user src/Internal/ service and caller', function () use (&$userInternalServiceFile) { + Config::set([ + 'on_violation' => 'report', + 'report_file' => null, + ]); + + UserAppInternalTest\Internal\UserCaller::triggerReturnViolation(); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(1); + expect($violations[0]->file)->toBe($userInternalServiceFile); + expect($violations[0]->line)->toBe(22); + expect($violations[0]->caller)->toContain('src/Internal/UserCaller.php:16'); + }); + + test('ViolationCollector emits warn-mode warnings pointing to user src/Internal/ call site', function () { + Config::set([ + 'on_violation' => 'warn', + ]); + + $warnings = []; + set_error_handler(static function (int $errno, string $errstr) use (&$warnings): bool { + if ($errno === E_USER_WARNING) { + $warnings[] = $errstr; + + return true; + } + + return false; + }, E_USER_WARNING); + + try { + UserAppInternalTest\Internal\UserCaller::triggerParamViolation(); + } finally { + restore_error_handler(); + } + + expect($warnings)->toHaveCount(1); + expect(str_replace('\\', '/', $warnings[0]))->toContain('src/Internal/UserCaller.php on line 11'); + }); +}); diff --git a/tests/TypeChecking/ArraysAndShapes/BareArrayEnforcementTest.php b/tests/TypeChecking/ArraysAndShapes/BareArrayEnforcementTest.php new file mode 100644 index 00000000..38347a3e --- /dev/null +++ b/tests/TypeChecking/ArraysAndShapes/BareArrayEnforcementTest.php @@ -0,0 +1,314 @@ +value : $override; + } +} + +/** + * @phpstan-type BareArrayAlias array + */ +final class BareArrayAliasHolder +{ + /** + * @param BareArrayAlias $payload + */ + public function accept(mixed $payload): void + { + } + + /** + * @return BareArrayAlias + */ + public function produce(mixed $val): mixed + { + return $val; + } +} + +/** + * @method mixed acceptPayload(array $data) + * @method array fetchPayload(mixed $val) + */ +final class BareArrayMagicCaller +{ + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + return $args[0] ?? null; + } +} + +describe('Bare array PHPDoc Contract Enforcement', function () { + describe('Parameter Contracts (@param array)', function () { + test('accepts valid arrays (empty, list, associative)', function () { + testBareArrayUntypedParam([]); + testBareArrayUntypedParam([1, 2, 3]); + testBareArrayUntypedParam(['a' => 1]); + testBareArrayMixedParam(['k' => 'v']); + testBareArrayWithConstrainedParam(1, ['ok' => true]); + testBareArrayUppercaseParam([1]); + + expect(true)->toBeTrue(); + }); + + test('throws TypeError when non-array is passed to untyped @param array', function () { + expect(fn () => testBareArrayUntypedParam(123)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + + expect(fn () => testBareArrayUntypedParam('not-an-array')) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + + expect(fn () => testBareArrayUntypedParam(null)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + }); + + test('throws TypeError when non-array is passed to native mixed @param array', function () { + expect(fn () => testBareArrayMixedParam(42)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + }); + + test('throws TypeError when bare array param is paired with another constrained param (cold and warm)', function () { + testBareArrayWithConstrainedParam(1, ['valid']); + + expect(fn () => testBareArrayWithConstrainedParam(2, 'not-an-array')) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + }); + + test('throws TypeError for case-insensitive @param ARRAY', function () { + expect(fn () => testBareArrayUppercaseParam(false)) + ->toThrow(TypeError::class, 'Argument $data must be of type ARRAY') + ; + }); + }); + + describe('Return Contracts (@return array)', function () { + test('accepts valid array returns', function () { + expect(testBareArrayUntypedReturn([]))->toBe([]); + expect(testBareArrayUntypedReturn(['a' => 1]))->toBe(['a' => 1]); + expect(testBareArrayMixedReturn([1, 2]))->toBe([1, 2]); + expect(testBareArrayUppercaseReturn([]))->toBe([]); + }); + + test('throws TypeError when untyped @return array returns a non-array (cold and warm)', function () { + expect(fn () => testBareArrayUntypedReturn('nope')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + + // Second call verifies noReturnContractCache / simpleReturnPlanCache did not bypass validation + expect(fn () => testBareArrayUntypedReturn(123)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError when native mixed @return array returns a non-array', function () { + expect(testBareArrayMixedReturn(['ok']))->toBe(['ok']); + + expect(fn () => testBareArrayMixedReturn(new stdClass())) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError for case-insensitive @return ARRAY', function () { + expect(fn () => testBareArrayUppercaseReturn('nope')) + ->toThrow(TypeError::class, 'Return value must be of type ARRAY') + ; + }); + }); + + describe('Generic Template Bound to array (T = array)', function () { + test('throws TypeError on generic class @return T when T is array (cold ReturnChecker path)', function () { + $box = new BareArrayBox(['key' => 'val']); + + expect(fn () => $box->getCold('not-an-array')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError on generic class @return T when T is array (warm genericReturnPlanCache path)', function () { + $box = new BareArrayBox(['key' => 'val']); + + // Populates RuntimeTypeChecker::$genericReturnPlanCache + expect($box->getWarm(true, null))->toBe(['key' => 'val']); + + // Hits cached `$tName === 'array'` fast path + expect(fn () => $box->getWarm(false, 123)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError on standalone generic function @return T when T is inferred as array', function () { + expect(testBareArrayGenericReturn(['k' => 'v'], ['other' => 1]))->toBe(['other' => 1]); + + expect(fn () => testBareArrayGenericReturn(['k' => 'v'], 'not-an-array')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + }); + + describe('Conditionals, Aliases, and Magic Methods Resolving to array', function () { + test('throws TypeError when conditional @param resolves to bare array', function () { + testBareArrayConditionalParam(true, ['ok']); + testBareArrayConditionalParam(false, 10); + + expect(fn () => testBareArrayConditionalParam(true, 'not-an-array')) + ->toThrow(TypeError::class, 'Argument $val must be of type array') + ; + }); + + test('throws TypeError when conditional @return resolves to bare array', function () { + expect(testBareArrayConditionalReturn(true, ['ok']))->toBe(['ok']); + expect(testBareArrayConditionalReturn(false, 'ok'))->toBe('ok'); + + expect(fn () => testBareArrayConditionalReturn(true, 999)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError when type alias resolving to bare array is violated', function () { + $holder = new BareArrayAliasHolder(); + $holder->accept(['ok' => 1]); + expect($holder->produce(['ok' => 1]))->toBe(['ok' => 1]); + + expect(fn () => $holder->accept('not-an-array')) + ->toThrow(TypeError::class, 'Argument $payload must be of type array') + ; + + expect(fn () => $holder->produce(42)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError when @method bare array param or return is violated', function () { + $caller = new BareArrayMagicCaller(); + expect($caller->acceptPayload(['ok']))->toBe(['ok']); + expect($caller->fetchPayload(['ok']))->toBe(['ok']); + + expect(fn () => $caller->acceptPayload(123)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + + expect(fn () => $caller->fetchPayload('not-an-array')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + }); +}); diff --git a/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php b/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php index fe0d18d1..18a9ab3e 100644 --- a/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php +++ b/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php @@ -177,6 +177,8 @@ public function init(): void $transformed = StreamWrapper::transformSource($source, 'precedence_button_test.php'); - expect($transformed)->toContain("\$this->tooltip ?? (\$this->direction === 'up' ? 'VALIDATE' : 'CANCEL')"); + expect($transformed)->toContain('$this->tooltip ?? ($this->tooltip =') + ->and($transformed)->toContain("checkProperty(\$this->direction === 'up' ? 'VALIDATE' : 'CANCEL'") + ; }); }); diff --git a/tests/TypeChecking/Boundaries/ByRefReturnSingleEvaluationTest.php b/tests/TypeChecking/Boundaries/ByRefReturnSingleEvaluationTest.php new file mode 100644 index 00000000..89a7b2ce --- /dev/null +++ b/tests/TypeChecking/Boundaries/ByRefReturnSingleEvaluationTest.php @@ -0,0 +1,167 @@ + + */ + public array $slots = [0 => 10, 1 => -999]; + + public int $cursor = 0; + + private int $singleSlot = 10; + + private mixed $badSlot = -5; + + public function &acquireSlot(): int + { + $this->slotAccessCount++; + + return $this->singleSlot; + } + + public function &acquireBadSlot(): mixed + { + $this->slotAccessCount++; + + return $this->badSlot; + } + + /** + * @return positive-int + */ + public function &getPositiveSlot(): int + { + return $this->acquireSlot(); + } + + /** + * @return positive-int + */ + public function &getBadPositiveSlot(): mixed + { + return $this->acquireBadSlot(); + } + + /** + * @return positive-int + */ + public function &nextArraySlot(): mixed + { + return $this->slots[$this->cursor++]; + } + + public function getSingleSlotValue(): int + { + return $this->singleSlot; + } +} + +/** + * @param mixed $out + * + * @param-out positive-int $out + * + * @return positive-int + */ +function &byRefReturnWithParamOut(array &$backing, int &$calls, mixed &$out): int +{ + $pick = static function &() use (&$backing, &$calls, &$out): int { + $calls++; + $out = 77; + + return $backing[0]; + }; + + return $pick(); +} + +describe('By-Reference Return Guard Single Evaluation & Aliasing Soundness', function () { + test('evaluates method call in by-reference return exactly once and preserves reference aliasing', function () { + $holder = new ByRefReturnSlotHolder(); + + $ref = &$holder->getPositiveSlot(); + + expect($holder->slotAccessCount)->toBe(1); + expect($ref)->toBe(10); + + $ref = 55; + expect($holder->getSingleSlotValue())->toBe(55); + }); + + test('evaluates failing by-reference return expression once before throwing TypeError', function () { + $holder = new ByRefReturnSlotHolder(); + + expect(fn () => $holder->getBadPositiveSlot()) + ->toThrow(TypeError::class, 'Return value must be of type positive-int') + ; + + expect($holder->slotAccessCount)->toBe(1); + }); + + test('evaluates ArrayDimFetch side-effect index in by-reference return exactly once', function () { + $holder = new ByRefReturnSlotHolder(); + + // Slot 0 is 10 (valid), Slot 1 is -999 (invalid). + // Double evaluation checks Slot 0 (10, passes) and returns Slot 1 (-999)! + $ref = &$holder->nextArraySlot(); + + expect($holder->cursor)->toBe(1); + expect($ref)->toBe(10); + + $ref = 42; + expect($holder->slots[0])->toBe(42); + }); + + test('evaluates by-reference return with @param-out once and preserves aliasing', function () { + $backing = [15]; + $calls = 0; + $out = null; + + $ref = &byRefReturnWithParamOut($backing, $calls, $out); + + expect($calls)->toBe(1); + expect($out)->toBe(77); + expect($ref)->toBe(15); + + $ref = 88; + expect($backing[0])->toBe(88); + }); + + test('AST transformation handles non-referenceable expressions inside by-ref functions without syntax errors', function () { + $source = <<<'PHP' +acquireSlot(); +} +PHP; + + $transformed = StreamWrapper::transformSource($source, __FILE__); + + expect(substr_count($transformed, '$holder->acquireSlot()'))->toBe(1); + + $tokens = StreamWrapper::getParser()->parse($transformed); + expect($tokens)->not->toBeNull(); + }); +}); diff --git a/tests/TypeChecking/Boundaries/IncDecAndCoalesceAssignSoundnessTest.php b/tests/TypeChecking/Boundaries/IncDecAndCoalesceAssignSoundnessTest.php new file mode 100644 index 00000000..c8df5ec4 --- /dev/null +++ b/tests/TypeChecking/Boundaries/IncDecAndCoalesceAssignSoundnessTest.php @@ -0,0 +1,328 @@ + $old, 'new' => $local]; +} + +/** + * @param ?positive-int $val + */ +function decNullablePositiveInt(?int $val): ?int +{ + /** @var ?positive-int $local */ + $local = $val; + $local--; + + return $local; +} + +/** + * @param ?positive-int $val + */ +function incNullablePositiveInt(?int $val): int +{ + /** @var ?positive-int $local */ + $local = $val; + $local++; + + return $local; +} + +function incBoolVar(bool $flag): bool +{ + /** @var bool $local */ + $local = $flag; + $local++; + + return $local; +} + +/** + * @param positive-int $n + */ +function decPositiveIntToZero(int $n): int +{ + /** @var positive-int $local */ + $local = $n; + $local--; + + return $local; +} + +final class CoalesceReadonlyPropertyFixture +{ + /** + * @var positive-int + */ + public readonly ?int $id; + + /** + * @var ?positive-int + */ + public ?int $count = null; + + public int $setCount = 0; + + public function __construct(?int $initialId = null, ?int $initialCount = null) + { + if ($initialId !== null) { + $this->id = $initialId; + } + $this->count = $initialCount; + } + + public function coalesceReadonlyId(int $fallback): int + { + return $this->id ??= $fallback; + } + + public function coalesceCount(callable $factory): ?int + { + return $this->count ??= $factory(); + } + + public function coalesceWithSideEffectTarget(callable $getSelf, int $fallback): ?int + { + return ($getSelf())->count ??= $fallback; + } +} + +describe('Increment/Decrement and Coalesce-Assign (??=) Semantic Preservation', function () { + describe('++ / -- preserves native PHP semantics for strings, null, and bools', function () { + test('increments alphanumeric strings instead of crashing with string + int TypeError', function () { + $a = null; + $z = null; + $item = null; + $post = null; + + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $a = incNonEmptyString('a'); + $z = incNonEmptyString('z'); + $item = incNonEmptyString('item09'); + $post = postIncStringWithReturn('a'); + } finally { + restore_error_handler(); + } + + expect($a)->toBe('b'); + expect($z)->toBe('aa'); + expect($item)->toBe('item10'); + expect($post)->toBe(['old' => 'a', 'new' => 'b']); + }); + + test('preserves null on decrement instead of converting null into -1', function () { + $result = null; + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $result = decNullablePositiveInt(null); + } finally { + restore_error_handler(); + } + + expect($result)->toBeNull(); + expect(incNullablePositiveInt(null))->toBe(1); + }); + + test('preserves bool on increment instead of coercing bool + 1 to int(2)', function () { + $result = null; + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $result = incBoolVar(true); + } finally { + restore_error_handler(); + } + + expect($result)->toBeTrue(); + }); + + test('still catches genuine contract violations on decremented integers', function () { + expect(fn () => decPositiveIntToZero(1)) + ->toThrow(TypeError::class, 'must be of type positive-int') + ; + }); + }); + + describe('??= (Coalesce-Assign) preserves short-circuiting and non-reassignment semantics', function () { + test('does not rewrite already-initialized readonly property on ??=', function () { + $obj = new CoalesceReadonlyPropertyFixture(initialId: 10); + + expect($obj->coalesceReadonlyId(20))->toBe(10); + expect($obj->id)->toBe(10); + }); + + test('initializes uninitialized readonly property on ??= and validates contract', function () { + $obj = new CoalesceReadonlyPropertyFixture(); + expect($obj->coalesceReadonlyId(25))->toBe(25); + expect($obj->id)->toBe(25); + + $obj2 = new CoalesceReadonlyPropertyFixture(); + expect(fn () => $obj2->coalesceReadonlyId(-5)) + ->toThrow(TypeError::class, 'must be of type positive-int') + ; + }); + + test('does not evaluate RHS factory when target is already non-null, and enforces contract when null', function () { + $obj = new CoalesceReadonlyPropertyFixture(initialCount: 7); + $calls = 0; + + $res = $obj->coalesceCount(function () use (&$calls): int { + $calls++; + + return 99; + }); + + expect($res)->toBe(7); + expect($calls)->toBe(0); + + $nullObj = new CoalesceReadonlyPropertyFixture(initialCount: null); + expect(function () use ($nullObj, &$calls): void { + $nullObj->coalesceCount(function () use (&$calls): int { + $calls++; + + return -3; + }); + })->toThrow(TypeError::class, 'must be of type positive-int'); + + expect($calls)->toBe(1); + }); + + test('does not trigger PHP 8.4 property set hook when hooked property is already non-null on ??=', function () { + if (\PHP_VERSION_ID < 80400) { + expect(true)->toBeTrue(); + + return; + } + + $baseTmp = sys_get_temp_dir() . '/typephp_coalesce_hook_' . uniqid('', true); + mkdir($baseTmp, 0777, true); + $realBase = realpath($baseTmp); + $tmpDir = str_replace('\\', '/', $realBase !== false ? $realBase : $baseTmp); + $scriptPath = $tmpDir . '/hook_coalesce.php'; + + file_put_contents($scriptPath, <<<'PHP' +setCalls++; + $this->score = $val; + } + } + + public function coalesceScore(int $fallback): ?int + { + return $this->score ??= $fallback; + } +} + +$obj = new HookedCoalesceFixture(); +$afterNonNull = $obj->coalesceScore(20); +$setsAfterNonNull = $obj->setCalls; + +$obj->score = null; +$setsAfterReset = $obj->setCalls; +$afterNull = $obj->coalesceScore(30); +$setsAfterAssign = $obj->setCalls; + +return [ + 'afterNonNull' => $afterNonNull, + 'setsAfterNonNull' => $setsAfterNonNull, + 'setsAfterReset' => $setsAfterReset, + 'afterNull' => $afterNull, + 'setsAfterAssign' => $setsAfterAssign, +]; +PHP); + + $currentIncludes = TypePHP\Internal\Util\Config::get()['include'] ?? []; + $includes = \is_array($currentIncludes) ? $currentIncludes : []; + $includes[] = $tmpDir . '/**'; + TypePHP\Internal\Util\Config::set(['include' => $includes]); + + try { + /** @var array{afterNonNull: ?int, setsAfterNonNull: int, setsAfterReset: int, afterNull: ?int, setsAfterAssign: int} $res */ + $res = require $scriptPath; + + expect($res['afterNonNull'])->toBe(10); + expect($res['setsAfterNonNull'])->toBe(0); + expect($res['setsAfterReset'])->toBe(1); + expect($res['afterNull'])->toBe(30); + expect($res['setsAfterAssign'])->toBe(2); + } finally { + TypePHP\Internal\Util\Config::reset(); + @unlink($scriptPath); + @rmdir($tmpDir); + } + }); + + test('evaluates impure target base once on ??= and preserves valid operator precedence in compound expressions', function () { + $obj = new CoalesceReadonlyPropertyFixture(initialCount: null); + $targetCalls = 0; + + $res = $obj->coalesceWithSideEffectTarget(function () use ($obj, &$targetCalls): CoalesceReadonlyPropertyFixture { + $targetCalls++; + + return $obj; + }, 15); + + expect($targetCalls)->toBe(1); + expect($res)->toBe(15); + expect($obj->count)->toBe(15); + + $source = <<<'PHP' +parse($transformed); + expect($tokens)->not->toBeNull(); + expect($transformed)->toContain('?? ($x ='); + }); + }); +}); diff --git a/tests/TypeChecking/Boundaries/Php85CloneWithTest.php b/tests/TypeChecking/Boundaries/Php85CloneWithTest.php index 62b4aab2..c46db42a 100644 --- a/tests/TypeChecking/Boundaries/Php85CloneWithTest.php +++ b/tests/TypeChecking/Boundaries/Php85CloneWithTest.php @@ -22,7 +22,7 @@ describe('PHP 8.5 "Clone With" Syntax Support (TDD)', function () { describe('1. AST Transformation (nikic/php-parser FuncCall interception)', function () { - test('transforms PHP 8.5 clone($obj, [...]) function call into RuntimeTypeChecker::cloneWith wrapper', function () { + test('transforms PHP 8.5 clone($obj, [...]) function call into RuntimeTypeChecker::executeCloneWith wrapper', function () { $source = <<<'PHP' 20]); @@ -30,12 +30,12 @@ $transformed = StreamWrapper::transformSource($source, 'test_clone_with.php'); - expect($transformed)->toContain('RuntimeTypeChecker::cloneWith') + expect($transformed)->toContain('RuntimeTypeChecker::executeCloneWith($order,') ->and($transformed)->toContain('[\'score\' => 20]') ; }); - test('transforms single-argument clone($obj) into RuntimeTypeChecker::cloneInstance wrapper', function () { + test('transforms single-argument clone($obj) into RuntimeTypeChecker::executeClone wrapper', function () { $source = <<<'PHP' toContain('RuntimeTypeChecker::cloneInstance'); + expect($transformed)->toContain('RuntimeTypeChecker::executeClone($order,'); }); }); diff --git a/tests/TypeChecking/Boundaries/ReturnExpressionPostConditionOrderTest.php b/tests/TypeChecking/Boundaries/ReturnExpressionPostConditionOrderTest.php new file mode 100644 index 00000000..b5360e28 --- /dev/null +++ b/tests/TypeChecking/Boundaries/ReturnExpressionPostConditionOrderTest.php @@ -0,0 +1,288 @@ + + */ +function testPostCondGenPopulateInReturn(mixed &$out): Generator +{ + $out = 10; + yield 1; + $out = null; + + return postCondSetOutAndReturnString($out, 77); +} + +/** + * @param mixed $out + * + * @param-out positive-int $out + * + * @return Generator + */ +function testPostCondGenCorruptInReturn(mixed &$out): Generator +{ + $out = 10; + yield 1; + + return postCondSetOutAndReturnString($out, -3); +} + +/** + * @param mixed $out + * + * @param-out positive-int $out + * + * @return Generator + */ +function testPostCondGenThrowInReturn(mixed &$out): Generator +{ + $out = 10; + yield 1; + $out = null; + + return postCondThrowString($out); +} +/** + * @template T + */ +final class PostCondSelfOutBox +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } + + /** + * @return T + */ + public function getValue(): mixed + { + return $this->value; + } + + private function readIntAndRewriteToString(): int + { + $old = $this->getValue(); + $this->value = 'migrated'; + + return \is_int($old) ? $old : 0; + } + + private function throwOnTransition(): string + { + throw new RuntimeException('transition failed'); + } + + /** + * @phpstan-self-out self + */ + public function readOldThenTransition(): int + { + return $this->readIntAndRewriteToString(); + } + + /** + * @phpstan-self-out self + */ + public function failDuringTransition(): string + { + return $this->throwOnTransition(); + } +} + +describe('Return Expression Evaluation Order vs @param-out / @self-out', function () { + describe('Non-generator @param-out post-conditions', function () { + test('evaluates return expression before checking @param-out when return expression populates &$out', function () { + $out = null; + $result = testPostCondPopulateOutInReturn($out); + + expect($result)->toBeTrue(); + expect($out)->toBe(42); + }); + + test('catches @param-out violation when return expression mutates &$out from valid to invalid', function () { + $out = null; + + expect(fn () => testPostCondCorruptOutInReturn($out)) + ->toThrow(TypeError::class, 'Argument &$out (param-out)') + ; + }); + + test('evaluates inline assignment inside return expression before checking @param-out', function () { + $out = null; + expect(testPostCondInlineAssignInReturn($out, 25))->toBe(25); + expect($out)->toBe(25); + + $out = 5; + expect(fn () => testPostCondInlineAssignInReturn($out, -1)) + ->toThrow(TypeError::class, 'Argument &$out (param-out)') + ; + }); + + test('enforces both @param-out and @return after evaluating return expression', function () { + $out = null; + expect(testPostCondBothParamOutAndReturn($out, 15, 99))->toBe(99); + expect($out)->toBe(15); + + $out = null; + expect(fn () => testPostCondBothParamOutAndReturn($out, 15, -1)) + ->toThrow(TypeError::class, 'Return value must be of type positive-int') + ; + }); + + test('does not run @param-out check when return expression throws an exception', function () { + $out = null; + + expect(fn () => testPostCondThrowInReturn($out)) + ->toThrow(RuntimeException::class, 'helper failed') + ; + }); + }); + + describe('@self-out post-conditions', function () { + test('evaluates return expression under pre-transition state before applying @self-out', function () { + $box = new PostCondSelfOutBox(42); + + $old = $box->readOldThenTransition(); + + expect($old)->toBe(42); + expect(TypePHP::getGenericType($box))->toBe('string'); + expect($box->getValue())->toBe('migrated'); + }); + + test('does not apply @self-out transition when return expression throws an exception', function () { + $box = new PostCondSelfOutBox(42); + + expect(fn () => $box->failDuringTransition()) + ->toThrow(RuntimeException::class, 'transition failed') + ; + + expect(TypePHP::getGenericType($box))->toBe('int'); + expect($box->getValue())->toBe(42); + }); + }); + + describe('Generator return expressions with @param-out', function () { + test('evaluates generator return expression before checking @param-out', function () { + $out = null; + $gen = testPostCondGenPopulateInReturn($out); + iterator_to_array($gen); + + expect($gen->getReturn())->toBe('done'); + expect($out)->toBe(77); + }); + + test('catches @param-out violation mutated inside generator return expression', function () { + $out = null; + $gen = testPostCondGenCorruptInReturn($out); + + expect(fn () => iterator_to_array($gen)) + ->toThrow(TypeError::class, 'Argument &$out (param-out)') + ; + }); + + test('does not run @param-out check when generator return expression throws an exception', function () { + $out = null; + $gen = testPostCondGenThrowInReturn($out); + + expect(fn () => iterator_to_array($gen)) + ->toThrow(RuntimeException::class, 'generator helper failed') + ; + }); + }); +}); diff --git a/tests/TypeChecking/Configuration/InlineVarConfigRoutingTest.php b/tests/TypeChecking/Configuration/InlineVarConfigRoutingTest.php new file mode 100644 index 00000000..065d9b81 --- /dev/null +++ b/tests/TypeChecking/Configuration/InlineVarConfigRoutingTest.php @@ -0,0 +1,512 @@ + + */ + public mixed $nonEmptyIntList = null; + + /** + * @var class-string + */ + public mixed $classString = null; +} + +/** + * @template T + */ +final class InlineConfigRoutingGenericBox +{ + /** + * @var T + */ + public mixed $value = null; + + /** + * @param T $value + */ + public function set(mixed $value): void + { + $this->value = $value; + } +} + +function testInlineRoutingNonEmptyArray(mixed $val): mixed +{ + /** @var non-empty-array $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingNonEmptyList(mixed $val): mixed +{ + /** @var non-empty-list $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingGenericNonEmptyList(mixed $val): mixed +{ + /** @var non-empty-list $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingGenericNonEmptyArray(mixed $val): mixed +{ + /** @var non-empty-array $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingNonEmptyCallableList(mixed $val): mixed +{ + /** @var non-empty-list $callbacks */ + $callbacks = $val; + + return $callbacks; +} + +function testInlineRoutingNumber(mixed $val): mixed +{ + /** @var number $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingLiteralString(mixed $val): mixed +{ + /** @var literal-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingTruthyString(mixed $val): mixed +{ + /** @var truthy-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingNonFalsyString(mixed $val): mixed +{ + /** @var non-falsy-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingFalsey(mixed $val): mixed +{ + /** @var falsey $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingClassString(mixed $val): mixed +{ + /** @var class-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingInterfaceString(mixed $val): mixed +{ + /** @var interface-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingTraitString(mixed $val): mixed +{ + /** @var trait-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingEnumString(mixed $val): mixed +{ + /** @var enum-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingCallableString(mixed $val): mixed +{ + /** @var callable-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingIntRange(mixed $val): mixed +{ + /** @var int<1, 10> $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingIntMask(mixed $val): mixed +{ + /** @var int-mask<1, 2, 4> $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingGenericClassString(mixed $val): mixed +{ + /** @var class-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingKeyOf(mixed $val): mixed +{ + /** @var key-of $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingStdClass(mixed $val): mixed +{ + /** @var stdClass $x */ + $x = $val; + + return $x; +} + +describe('InlineChecker Config Routing (inline_vars)', function () { + $originalInlineVars = null; + + beforeEach(function () use (&$originalInlineVars) { + $originalInlineVars = TypePHP::getConfig()['inline_vars']; + }); + + afterEach(function () use (&$originalInlineVars) { + TypePHP::setConfig(['inline_vars' => $originalInlineVars]); + }); + + describe('Array Refinements (non-empty-array, non-empty-list)', function () { + test('enforces non-empty-array and non-empty-list when only arrays (+ properties) are enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => true, + 'scalars' => false, + 'objects' => false, + 'generics' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingNonEmptyArray(['a' => 1]))->toBe(['a' => 1]); + expect(testInlineRoutingNonEmptyList([1, 2]))->toBe([1, 2]); + expect(testInlineRoutingGenericNonEmptyList([1, 2]))->toBe([1, 2]); + expect(testInlineRoutingGenericNonEmptyArray(['a' => 1]))->toBe(['a' => 1]); + + expect(fn () => testInlineRoutingNonEmptyArray([])) + ->toThrow(TypeError::class, 'Variable $x must be of type non-empty-array') + ; + + expect(fn () => testInlineRoutingNonEmptyList([])) + ->toThrow(TypeError::class, 'Variable $x must be of type non-empty-list') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyList([])) + ->toThrow(TypeError::class, 'Variable $x must be a non-empty list') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyList(['bad'])) + ->toThrow(TypeError::class, 'Variable $x[0] must be of type int') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyArray(['a' => 'bad'])) + ->toThrow(TypeError::class, "Variable \$x['a'] must be of type int") + ; + + $holder = new InlineConfigRoutingHolder(); + expect(fn () => $holder->nonEmptyIntList = ['bad']) + ->toThrow(TypeError::class, 'Property InlineConfigRoutingHolder::$nonEmptyIntList[0] must be of type int') + ; + }); + + test('does not downgrade generic non-empty-list/non-empty-array element types when generics is disabled and objects is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => true, + 'objects' => true, + 'generics' => false, + 'scalars' => false, + 'callables' => false, + ], + ]); + + expect(fn () => testInlineRoutingGenericNonEmptyList(['not-an-int'])) + ->toThrow(TypeError::class, 'Variable $x[0] must be of type int') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyArray(['a' => 'not-an-int'])) + ->toThrow(TypeError::class, "Variable \$x['a'] must be of type int") + ; + }); + + test('skips non-empty-array and non-empty-list when arrays is disabled even if objects and generics are enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => false, + 'objects' => true, + 'generics' => true, + 'scalars' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingNonEmptyArray([]))->toBe([]); + expect(testInlineRoutingNonEmptyList([]))->toBe([]); + expect(testInlineRoutingGenericNonEmptyList(['bad']))->toBe(['bad']); + expect(testInlineRoutingGenericNonEmptyArray(['a' => 'bad']))->toBe(['a' => 'bad']); + + // Sanity check: actual object types are still enforced + expect(fn () => testInlineRoutingStdClass('not-an-object')) + ->toThrow(TypeError::class, 'Variable $x must be of type stdClass') + ; + }); + + test('wraps callables inside non-empty-list', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => true, + 'callables' => true, + 'objects' => false, + 'generics' => false, + 'scalars' => false, + ], + ]); + + $callbacks = testInlineRoutingNonEmptyCallableList([ + static fn ($n) => (string) $n, + ]); + + expect($callbacks[0](42))->toBe('42'); + expect(fn () => $callbacks[0]('not-an-int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + }); + }); + + describe('Scalar Refinement Identifiers', function () { + test('enforces all scalar refinement identifiers when only scalars (+ properties) are enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => true, + 'arrays' => false, + 'objects' => false, + 'generics' => false, + 'callables' => false, + ], + ]); + + // Valid values pass + expect(testInlineRoutingNumber(3.14))->toBe(3.14); + expect(testInlineRoutingLiteralString('abc'))->toBe('abc'); + expect(testInlineRoutingTruthyString('yes'))->toBe('yes'); + expect(testInlineRoutingNonFalsyString('yes'))->toBe('yes'); + expect(testInlineRoutingFalsey(''))->toBe(''); + expect(testInlineRoutingClassString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingInterfaceString(Throwable::class))->toBe(Throwable::class); + expect(testInlineRoutingTraitString(InlineConfigRoutingTestTrait::class))->toBe(InlineConfigRoutingTestTrait::class); + expect(testInlineRoutingEnumString(InlineConfigRoutingTestEnum::class))->toBe(InlineConfigRoutingTestEnum::class); + expect(testInlineRoutingCallableString('strlen'))->toBe('strlen'); + + // Invalid values throw + expect(fn () => testInlineRoutingNumber('not-a-number')) + ->toThrow(TypeError::class, 'Variable $x must be of type number') + ; + expect(fn () => testInlineRoutingLiteralString(123)) + ->toThrow(TypeError::class, 'Variable $x must be of type literal-string') + ; + expect(fn () => testInlineRoutingTruthyString('0')) + ->toThrow(TypeError::class, 'Variable $x must be of type truthy-string') + ; + expect(fn () => testInlineRoutingNonFalsyString('0')) + ->toThrow(TypeError::class, 'Variable $x must be of type non-falsy-string') + ; + expect(fn () => testInlineRoutingFalsey('truthy')) + ->toThrow(TypeError::class, 'Variable $x must be of type falsey') + ; + expect(fn () => testInlineRoutingClassString('NotARealClass')) + ->toThrow(TypeError::class, 'Variable $x must be of type class-string') + ; + expect(fn () => testInlineRoutingInterfaceString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be of type interface-string') + ; + expect(fn () => testInlineRoutingTraitString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be of type trait-string') + ; + expect(fn () => testInlineRoutingEnumString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be of type enum-string') + ; + expect(fn () => testInlineRoutingCallableString('not_a_real_callable_fn')) + ->toThrow(TypeError::class, 'Variable $x must be of type callable-string') + ; + + $holder = new InlineConfigRoutingHolder(); + expect(fn () => $holder->classString = 'NotARealClass') + ->toThrow(TypeError::class, 'Property InlineConfigRoutingHolder::$classString must be of type class-string') + ; + }); + + test('skips all scalar refinement identifiers when scalars is disabled even if objects is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => false, + 'objects' => true, + 'arrays' => false, + 'generics' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingNumber('not-a-number'))->toBe('not-a-number'); + expect(testInlineRoutingLiteralString(123))->toBe(123); + expect(testInlineRoutingTruthyString('0'))->toBe('0'); + expect(testInlineRoutingNonFalsyString('0'))->toBe('0'); + expect(testInlineRoutingFalsey('truthy'))->toBe('truthy'); + expect(testInlineRoutingClassString('NotARealClass'))->toBe('NotARealClass'); + expect(testInlineRoutingInterfaceString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingTraitString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingEnumString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingCallableString('not_a_real_callable_fn'))->toBe('not_a_real_callable_fn'); + }); + }); + + describe('Scalar Generic Refinements (int, int-mask, class-string, key-of)', function () { + test('enforces scalar generics when only scalars is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => true, + 'objects' => false, + 'generics' => false, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingIntRange(5))->toBe(5); + expect(testInlineRoutingIntMask(3))->toBe(3); + expect(testInlineRoutingGenericClassString(RuntimeException::class))->toBe(RuntimeException::class); + expect(testInlineRoutingKeyOf('a'))->toBe('a'); + + expect(fn () => testInlineRoutingIntRange(99)) + ->toThrow(TypeError::class, 'Variable $x must be <= 10') + ; + expect(fn () => testInlineRoutingIntMask(8)) + ->toThrow(TypeError::class, 'Variable $x must be a valid bitmask combination') + ; + expect(fn () => testInlineRoutingGenericClassString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be a class-string of Throwable') + ; + expect(fn () => testInlineRoutingKeyOf('c')) + ->toThrow(TypeError::class, 'Variable $x must be a key of the specified array shape') + ; + }); + + test('does not strip scalar generic parameters when generics is disabled and objects is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => true, + 'objects' => true, + 'generics' => false, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(fn () => testInlineRoutingIntRange(99)) + ->toThrow(TypeError::class, 'Variable $x must be <= 10') + ; + expect(fn () => testInlineRoutingIntMask(8)) + ->toThrow(TypeError::class, 'Variable $x must be a valid bitmask combination') + ; + expect(fn () => testInlineRoutingGenericClassString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be a class-string of Throwable') + ; + expect(fn () => testInlineRoutingKeyOf('c')) + ->toThrow(TypeError::class, 'Variable $x must be a key of the specified array shape') + ; + }); + + test('skips scalar generics when scalars is disabled even if generics is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => false, + 'generics' => true, + 'objects' => false, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingIntRange(99))->toBe(99); + expect(testInlineRoutingIntMask(8))->toBe(8); + expect(testInlineRoutingGenericClassString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingKeyOf('c'))->toBe('c'); + }); + }); + + describe('SpecialTypeResolver Built-in Keyword Recognition', function () { + test('recognizes non-falsy-string and pure-callable as built-in keywords when binding generic instances', function () { + /** @var InlineConfigRoutingGenericBox $box */ + $box = new InlineConfigRoutingGenericBox(); + + $box->set('valid'); + expect($box->value)->toBe('valid'); + + expect(fn () => $box->set('0')) + ->toThrow(TypeError::class, 'must be of type non-falsy-string') + ; + + expect(\TypePHP\Internal\Resolver\SpecialTypeResolver::isBuiltInTypeKeyword('non-falsy-string'))->toBeTrue(); + expect(\TypePHP\Internal\Resolver\SpecialTypeResolver::isBuiltInTypeKeyword('pure-callable'))->toBeTrue(); + expect(\TypePHP\Internal\Resolver\SpecialTypeResolver::isBuiltInTypeKeyword('non-empty-array-list'))->toBeTrue(); + }); + }); +}); diff --git a/tests/TypeChecking/Generics/CloneGenericsSoundnessTest.php b/tests/TypeChecking/Generics/CloneGenericsSoundnessTest.php new file mode 100644 index 00000000..8534e9c6 --- /dev/null +++ b/tests/TypeChecking/Generics/CloneGenericsSoundnessTest.php @@ -0,0 +1,236 @@ +value = $value; + } +} + +/** + * @template T + */ +final class CloneOuterBox +{ + public ?string $capturedTypeAfterInnerClone = null; + + /** + * @param T $value + * @param CloneTestBox $inner + */ + public function __construct( + public mixed $value, + public CloneTestBox $inner, + public bool $triggerInvalidAfterInnerClone = false, + ) { + } + + /** + * @param T $value + */ + public function setValue(mixed $value): void + { + $this->value = $value; + } + + public function __clone(): void + { + $this->inner = clone $this->inner; + $this->capturedTypeAfterInnerClone = TypePHP::getGenericType($this); + + if ($this->triggerInvalidAfterInnerClone) { + $this->setValue('definitely-not-an-int'); + } + } +} + +/** + * @template T + */ +final class CloneThrowingBox +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } + + public function __clone(): void + { + throw new RuntimeException('Clone aborted'); + } +} + +describe('Clone AST Wrapping & Generic Binding Soundness', function () { + test('clone evaluates impure operand expression exactly once and copies bindings from that instance', function () { + $calls = 0; + + $makeBox = function () use (&$calls): CloneTestBox { + $calls++; + + return $calls === 1 + ? new CloneTestBox(42) + : new CloneTestBox('wrong-second-instance'); + }; + + $cloned = clone $makeBox(); + + expect($calls)->toBe(1); + expect(TypePHP::getGenericType($cloned))->toBe('int'); + + $cloned->set(99); + expect($cloned->value)->toBe(99); + + expect(fn () => $cloned->set('invalid-string')) + ->toThrow(TypeError::class) + ; + }); + + test('nested clone inside __clone() preserves outer object generic bindings after inner clone completes', function () { + $outer = new CloneOuterBox(10, new CloneTestBox('inner')); + $cloned = clone $outer; + + expect($cloned->capturedTypeAfterInnerClone)->toBe('int'); + expect(TypePHP::getGenericType($cloned))->toBe('int'); + expect(TypePHP::getGenericType($cloned->inner))->toBe('string'); + }); + + test('nested clone inside __clone() continues enforcing outer generic contracts during __clone()', function () { + $outer = new CloneOuterBox(10, new CloneTestBox('inner'), triggerInvalidAfterInnerClone: true); + + expect(fn () => clone $outer) + ->toThrow(TypeError::class, 'Argument $value') + ; + }); + + test('exception thrown inside __clone() does not leak pending clone source to subsequent instantiations', function () { + $intBox = new CloneThrowingBox(42); + + expect(fn () => clone $intBox) + ->toThrow(RuntimeException::class, 'Clone aborted') + ; + + expect(\TypePHP\Internal\Generics\TemplateManager::$pendingCloneSource)->toBeNull(); + + $strBox = new CloneThrowingBox('hello'); + + expect($strBox->value)->toBe('hello'); + expect(TypePHP::getGenericType($strBox))->toBe('string'); + }); + + test('PHP 8.5 clone($obj, $props) AST transformation evaluates object and properties expressions once', function () { + $source = <<<'PHP' +toBe(1); + expect(substr_count($transformed, 'makeCloneProps()'))->toBe(1); + }); + + test('PHP 8.5 clone($obj, $props) runtime evaluates arguments once, preserves generics, and validates overrides', function () { + $baseTmp = sys_get_temp_dir() . '/typephp_clone_with_' . uniqid('', true); + mkdir($baseTmp, 0777, true); + $realBase = realpath($baseTmp); + $tmpDir = str_replace('\\', '/', $realBase !== false ? $realBase : $baseTmp); + $scriptPath = $tmpDir . '/clone_with_runtime.php'; + + file_put_contents($scriptPath, <<<'PHP' + 7]; +}; + +$cloned = clone($makeObj(), $makeProps()); + +return [ + 'objCalls' => $objCalls, + 'propsCalls' => $propsCalls, + 'genericType' => TypePHP::getGenericType($cloned), + 'count' => $cloned->count, + 'triggerInvalid' => static fn (): mixed => clone($cloned, ['count' => -3]), +]; +PHP); + + $currentIncludes = Config::get()['include'] ?? []; + $includes = \is_array($currentIncludes) ? $currentIncludes : []; + $includes[] = $tmpDir . '/**'; + + Config::set(['include' => $includes]); + + try { + /** @var array{objCalls: int, propsCalls: int, genericType: ?string, count: int, triggerInvalid: Closure(): mixed} $result */ + $result = require $scriptPath; + + expect($result['objCalls'])->toBe(1); + expect($result['propsCalls'])->toBe(1); + expect($result['genericType'])->toBe('int'); + expect($result['count'])->toBe(7); + expect($result['triggerInvalid'])->toThrow(TypeError::class, 'positive-int'); + } finally { + Config::reset(); + @unlink($scriptPath); + @rmdir($tmpDir); + } + })->skip(\PHP_VERSION_ID < 80500, 'Requires PHP 8.5+ clone-with syntax'); +}); diff --git a/tests/TypeChecking/Generics/ContraVarianceSoundnessTest.php b/tests/TypeChecking/Generics/ContraVarianceSoundnessTest.php new file mode 100644 index 00000000..8fc1137f --- /dev/null +++ b/tests/TypeChecking/Generics/ContraVarianceSoundnessTest.php @@ -0,0 +1,171 @@ + $consumer + */ +function acceptContravariantPositiveIntConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantIntConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantDogConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantObjectConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantIntersectionConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantIfaceAConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +describe('Generic Contravariance Soundness', function () { + describe('Contravariant generic consumers enforce supertype direction', function () { + test('accepts Consumer for Consumer and rejects reversed Consumer for Consumer', function () { + /** @var VarianceContravariantConsumer $intConsumer */ + $intConsumer = new VarianceContravariantConsumer(); + acceptContravariantPositiveIntConsumer($intConsumer); + + /** @var VarianceContravariantConsumer $posConsumer */ + $posConsumer = new VarianceContravariantConsumer(); + + expect(fn () => acceptContravariantIntConsumer($posConsumer)) + ->toThrow(TypeError::class, 'expects VarianceContravariantConsumer') + ; + }); + + test('accepts Consumer for Consumer and rejects reversed Consumer for Consumer', function () { + /** @var VarianceContravariantConsumer $objConsumer */ + $objConsumer = new VarianceContravariantConsumer(); + acceptContravariantDogConsumer($objConsumer); + + /** @var VarianceContravariantConsumer $dogConsumer */ + $dogConsumer = new VarianceContravariantConsumer(); + + expect(fn () => acceptContravariantObjectConsumer($dogConsumer)) + ->toThrow(TypeError::class, 'expects VarianceContravariantConsumer') + ; + }); + + test('accepts Consumer for Consumer and rejects the reverse', function () { + /** @var VarianceContravariantConsumer $aConsumer */ + $aConsumer = new VarianceContravariantConsumer(); + acceptContravariantIntersectionConsumer($aConsumer); + + /** @var VarianceContravariantConsumer $abConsumer */ + $abConsumer = new VarianceContravariantConsumer(); + + expect(fn () => acceptContravariantIfaceAConsumer($abConsumer)) + ->toThrow(TypeError::class, 'expects VarianceContravariantConsumer') + ; + }); + }); + + describe('TemplateManager::checkVariance() contravariant invariants', function () { + test('handles scalars, ranges, literals, class-strings, object, collections, unions, intersections, and mixed', function () { + $int = new IdentifierTypeNode('int'); + $posInt = new IdentifierTypeNode('positive-int'); + $string = new IdentifierTypeNode('string'); + $object = new IdentifierTypeNode('object'); + $mixed = new IdentifierTypeNode('mixed'); + $array = new IdentifierTypeNode('array'); + $list = new IdentifierTypeNode('list'); + $dog = new IdentifierTypeNode(VarianceDog::class); + $intRange = new GenericTypeNode($int, [ + new ConstTypeNode(new ConstExprIntegerNode('1')), + new ConstTypeNode(new ConstExprIntegerNode('10')), + ]); + $classStringDog = new GenericTypeNode(new IdentifierTypeNode('class-string'), [$dog]); + $fooLit = new ConstTypeNode(new ConstExprStringNode('foo', ConstExprStringNode::SINGLE_QUOTED)); + $intOrString = new UnionTypeNode([$int, $string]); + $ifaceA = new IdentifierTypeNode(VarianceIfaceA::class); + $ifaceB = new IdentifierTypeNode(VarianceIfaceB::class); + $aAndB = new IntersectionTypeNode([$ifaceA, $ifaceB]); + + expect(TemplateManager::checkVariance($int, $posInt, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($posInt, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($int, $intRange, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($intRange, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($string, $fooLit, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($fooLit, $string, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($string, $classStringDog, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($classStringDog, $string, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($object, $dog, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($dog, $object, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($array, $list, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($list, $array, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($ifaceA, $aAndB, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($aAndB, $ifaceA, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($intOrString, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($int, $intOrString, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($mixed, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + }); + }); +}); diff --git a/tests/TypeChecking/Generics/ObjectGenericReturnEliminationTest.php b/tests/TypeChecking/Generics/ObjectGenericReturnEliminationTest.php new file mode 100644 index 00000000..f15a7827 --- /dev/null +++ b/tests/TypeChecking/Generics/ObjectGenericReturnEliminationTest.php @@ -0,0 +1,271 @@ + + */ +function testElimReturnNullableDogBox(EliminationBox $box): ?EliminationBox +{ + return $box; +} + +/** + * @param EliminationBox $box + * + * @return EliminationBox|null + */ +function testElimReturnUnionNullDogBox(EliminationBox $box): ?EliminationBox +{ + return $box; +} + +/** + * @param EliminationBox $box + * + * @return EliminationBox|string + */ +function testElimReturnUnionStringDogBox(EliminationBox $box): EliminationBox|string +{ + return $box; +} + +/** + * @param list $boxes + * + * @return list> + */ +function testElimReturnDogBoxList(array $boxes): array +{ + return $boxes; +} + +/** + * @param EliminationBox[] $boxes + * + * @return EliminationBox[] + */ +function testElimReturnDogBoxTypedArray(array $boxes): array +{ + return $boxes; +} + +/** + * @param EliminationBox $box + * + * @return array{box: ?EliminationBox} + */ +function testElimReturnShapeWithNullableDogBox(EliminationBox $box): array +{ + return ['box' => $box]; +} + +/** + * @param EliminationBox $box + * + * @return list> + */ +function testElimReturnListLiteralWithNullableDogBox(EliminationBox $box): array +{ + return [$box]; +} + +/** + * @return ?EliminationBox + */ +function testElimReturnInlineVarNullableDogBox(mixed $val): ?EliminationBox +{ + /** @var EliminationBox */ + return $val; +} + +/** + * @param EliminationBox $box + * + * @return Generator> + */ +function testElimGeneratorReturnNullableDogBox(EliminationBox $box): Generator +{ + yield 1; + + return $box; +} + +function parseElimTestType(string $typeString): TypeNode +{ + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + + return $typeParser->parse($tokens); +} + +describe('Object-Generic Return Check Elimination Safety', function () { + $boxFqcn = EliminationBox::class; + $dogFqcn = Dog::class; + $carBoxLabel = EliminationBox::class . '<' . Car::class . '>'; + + describe('EliminationSafetyPolicy::isReturnEliminationSafe()', function () use ($boxFqcn, $dogFqcn) { + test('rejects nullable, union, and container-wrapped object generics', function () use ($boxFqcn, $dogFqcn) { + $fn = new Function_('dummy'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("?{$boxFqcn}<{$dogFqcn}>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|null")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|string")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("list<{$boxFqcn}<{$dogFqcn}>>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("array>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>[]")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("array{box: {$boxFqcn}<{$dogFqcn}>}")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("array{box: ?{$boxFqcn}<{$dogFqcn}>}")))->toBeFalse(); + }); + + test('still permits non-generic objects, scalar generics, and non-object-generic collections', function () use ($dogFqcn) { + $fn = new Function_('dummy'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("?{$dogFqcn}")))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("list<{$dogFqcn}>")))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType('list')))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType('?int')))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType('int<1, 10>|null')))->toBeTrue(); + }); + }); + + describe('StaticTypeEvaluator::satisfies()', function () use ($boxFqcn, $dogFqcn) { + test('does not prove a trusted raw-class variable satisfies nullable, union, or nested object generics', function () use ($boxFqcn, $dogFqcn) { + $boxVar = new Variable('box'); + $boxesVar = new Variable('boxes'); + $rawBoxTrusted = ['box' => parseElimTestType($boxFqcn)]; + $rawBoxListTrusted = ['boxes' => parseElimTestType("list<{$boxFqcn}>")]; + $rawBoxArrayTrusted = ['boxes' => parseElimTestType("{$boxFqcn}[]")]; + + expect(StaticTypeEvaluator::satisfies($boxVar, parseElimTestType("?{$boxFqcn}<{$dogFqcn}>"), '', $rawBoxTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|null"), '', $rawBoxTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|string"), '', $rawBoxTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxesVar, parseElimTestType("list<{$boxFqcn}<{$dogFqcn}>>"), '', $rawBoxListTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxesVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>[]"), '', $rawBoxArrayTrusted))->toBeFalse(); + + $shapeLiteral = new Array_([ + new ArrayItem($boxVar, new String_('box')), + ]); + expect(StaticTypeEvaluator::satisfies($shapeLiteral, parseElimTestType("array{box: ?{$boxFqcn}<{$dogFqcn}>}"), '', $rawBoxTrusted))->toBeFalse(); + + $listLiteral = new Array_([ + new ArrayItem($boxVar), + ]); + expect(StaticTypeEvaluator::satisfies($listLiteral, parseElimTestType("list>"), '', $rawBoxTrusted))->toBeFalse(); + }); + + test('still proves sound non-generic trusted variable returns', function () use ($boxFqcn, $dogFqcn) { + $xVar = new Variable('x'); + + expect(StaticTypeEvaluator::satisfies($xVar, parseElimTestType('?int'), '', ['x' => parseElimTestType('?int')]))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($xVar, parseElimTestType('int|string'), '', ['x' => parseElimTestType('int|string')]))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($xVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|int"), '', ['x' => parseElimTestType('int')]))->toBeTrue(); + }); + }); + + describe('End-to-End Runtime Enforcement and WeakMap Binding Preservation', function () use ($carBoxLabel) { + test('rejects Box and preserves WeakMap binding on @return ?Box', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + $unboundBox = new EliminationBox(); + $boundBox = testElimReturnNullableDogBox($unboundBox); + + expect($boundBox)->toBe($unboundBox); + expect(TypePHP::getGenericType($boundBox))->toBe(Dog::class); + expect(fn () => $boundBox->set(new Car())) + ->toThrow(TypeError::class, Dog::class) + ; + }); + + test('rejects Box on union @return Box|null and Box|string', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnUnionNullDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + expect(fn () => testElimReturnUnionStringDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('rejects list> on @return list> and @return Box[]', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnDogBoxList([$carBox])) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + expect(fn () => testElimReturnDogBoxTypedArray([$carBox])) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('rejects Box in array shape and list literals targeting nullable object generics', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnShapeWithNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + expect(fn () => testElimReturnListLiteralWithNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('does not let inline @var Box subsume @return ?Box', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnInlineVarNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('does not eliminate generator TReturn check on Generator>', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(function () use ($carBox) { + $gen = testElimGeneratorReturnNullableDogBox($carBox); + iterator_to_array($gen); + $gen->getReturn(); + })->toThrow(TypeError::class, $carBoxLabel); + + $unboundBox = new EliminationBox(); + $gen = testElimGeneratorReturnNullableDogBox($unboundBox); + iterator_to_array($gen); + $boundBox = $gen->getReturn(); + + expect($boundBox)->toBe($unboundBox); + expect(TypePHP::getGenericType($boundBox))->toBe(Dog::class); + }); + }); +}); diff --git a/tests/Unit/LineNumberPreservationTest.php b/tests/Unit/LineNumberPreservationTest.php index 6f726dd3..1dde1ca3 100644 --- a/tests/Unit/LineNumberPreservationTest.php +++ b/tests/Unit/LineNumberPreservationTest.php @@ -1204,5 +1204,78 @@ function inlineCommentBeforeUnset(): void ->and($transAfterIdx)->toBe($origAfterIdx) ; }); + + test('preserves exact internal line numbers for multi-line generic constructor calls with multiple arguments', function () { + $source = <<<'PHP' + + */ +$pair = new Pair(1, 1); + +/** + * @var Pair + */ +$pair = new Pair( + 1, + 2, +); + +$afterMultiLinePair = true; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_multiline_generic_pair.php'); + + $origLines = explode("\n", str_replace("\r\n", "\n", $source)); + $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); + + expect(\count($transLines))->toBe(\count($origLines)); + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + expect($findLineIndex('public function __construct(', $transLines)) + ->toBe($findLineIndex('public function __construct(', $origLines)) + ; + expect($findLineIndex('@var Pair', $transLines)) + ->toBe($findLineIndex('@var Pair', $origLines)) + ; + expect($findLineIndex('$pair = new Pair(1, 1);', $origLines))->toBe(21); + expect($transLines[21])->toContain("withPendingGeneric('Pair'"); + expect($findLineIndex('@var Pair', $transLines)) + ->toBe($findLineIndex('@var Pair', $origLines)) + ; + expect($transLines[26])->toContain("withPendingGeneric('Pair'"); + expect(trim($transLines[27]))->toBe('1,'); + expect(trim($transLines[28]))->toBe('2'); + expect($transLines[29])->toStartWith('),'); + expect($findLineIndex('$afterMultiLinePair = true;', $transLines)) + ->toBe($findLineIndex('$afterMultiLinePair = true;', $origLines)) + ; + }); }); });