From 05e12ac995c59d170abb65cf206e4b6ed48d4298 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 09:55:46 +0800 Subject: [PATCH 1/9] Add comprehensive tests for unset mutation enforcement and line number preservation --- src/Internal/Ast/ContractVisitor.php | 281 ++++++++- .../Ast/Elimination/StaticTypeEvaluator.php | 80 +++ src/Internal/Ast/FunctionContractInjector.php | 55 +- src/Internal/Ast/NodeBuilder.php | 98 ++++ src/Internal/Checker/InlineChecker.php | 5 +- src/Internal/Checker/MemberAssignChecker.php | 104 ++++ src/Internal/RuntimeTypeChecker.php | 89 +++ src/Internal/Util/StructureMutator.php | 92 +++ .../Priority3/ArrayAccessSubclassFixtures.php | 27 + .../Priority3/CallableAliasFixtures.php | 35 ++ .../Priority3/MultiNamespaceFixtures.php | 33 ++ .../MemberUnsetValidationTest.php | 495 ++++++++++++++++ .../ArraysAndShapes/UnsetMutationTest.php | 533 ++++++++++++++++++ .../Boundaries/Priority1BugsTest.php | 191 +++++++ tests/Unit/LineNumberPreservationTest.php | 266 ++++++++- 15 files changed, 2362 insertions(+), 22 deletions(-) create mode 100644 tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php create mode 100644 tests/Fixtures/Priority3/CallableAliasFixtures.php create mode 100644 tests/Fixtures/Priority3/MultiNamespaceFixtures.php create mode 100644 tests/TypeChecking/ArraysAndShapes/MemberUnsetValidationTest.php create mode 100644 tests/TypeChecking/ArraysAndShapes/UnsetMutationTest.php create mode 100644 tests/TypeChecking/Boundaries/Priority1BugsTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index cfca40b6..2722f143 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -49,11 +49,48 @@ final class ContractVisitor extends NodeVisitorAbstract Node\Expr\AssignOp\Coalesce::class => Node\Expr\BinaryOp\Coalesce::class, ]; + private const BY_REF_BUILTIN_FUNCTIONS = [ + 'preg_match' => [2 => true], + 'preg_match_all' => [2 => true], + 'sort' => [0 => true], + 'rsort' => [0 => true], + 'asort' => [0 => true], + 'arsort' => [0 => true], + 'ksort' => [0 => true], + 'krsort' => [0 => true], + 'usort' => [0 => true], + 'uasort' => [0 => true], + 'uksort' => [0 => true], + 'natcasesort' => [0 => true], + 'natsort' => [0 => true], + 'shuffle' => [0 => true], + 'array_multisort' => [0 => true, 1 => true, 2 => true], + 'array_push' => [0 => true], + 'array_pop' => [0 => true], + 'array_shift' => [0 => true], + 'array_unshift' => [0 => true], + 'array_splice' => [0 => true], + 'array_walk' => [0 => true], + 'array_walk_recursive' => [0 => true], + 'reset' => [0 => true], + 'end' => [0 => true], + 'next' => [0 => true], + 'prev' => [0 => true], + 'each' => [0 => true], + 'parse_str' => [1 => true], + 'openssl_random_pseudo_bytes' => [1 => true], + ]; + /** * @var array> */ private static array $parsedShapeCache = []; + /** + * @var array + */ + private static array $parsedUnsetTypeCache = []; + /** * @var array> */ @@ -111,10 +148,43 @@ public function enterNode(Node $node): Node|array|null { $this->trackDeclarationEntry($node); - if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Expr\Closure) { + if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Expr\Closure || $node instanceof Node\Expr\ArrowFunction) { $this->byRefStack[] = $node->byRef; } + if ($node instanceof Node\Expr\ArrowFunction && $node->byRef) { + $this->markWriteContext($node->expr); + } + + if ($node instanceof Node\Expr\CallLike && ! $node->isFirstClassCallable()) { + foreach ($node->getArgs() as $arg) { + if ($arg->byRef) { + $this->markWriteContext($arg->value); + } + } + + // Built-in functions with by-reference parameters + if ($node instanceof Node\Expr\FuncCall && $node->name instanceof Node\Name) { + $funcLower = strtolower($node->name->getLast()); + if (isset(self::BY_REF_BUILTIN_FUNCTIONS[$funcLower])) { + $targetIndices = self::BY_REF_BUILTIN_FUNCTIONS[$funcLower]; + foreach ($node->getArgs() as $idx => $arg) { + if (isset($targetIndices[$idx])) { + $this->markWriteContext($arg->value); + } + } + } + } elseif ($node instanceof Node\Expr\MethodCall || $node instanceof Node\Expr\StaticCall) { + // If a static property is passed as an argument to any method call, mark write context + // so it cannot be broken by rewriting into a function call if the method takes by-ref. + foreach ($node->getArgs() as $arg) { + if ($arg->value instanceof Node\Expr\StaticPropertyFetch) { + $this->markWriteContext($arg->value); + } + } + } + } + if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) { $this->scopeManager->pushScope(isIsolated: true); $this->registerParamInferredTypes($node->params); @@ -145,9 +215,6 @@ public function enterNode(Node $node): Node|array|null } elseif ($node instanceof Node\Stmt\Unset_) { foreach ($node->vars as $v) { $this->markWriteContext($v); - if ($v instanceof Node\Expr\Variable && \is_string($v->name)) { - $this->scopeManager->unregisterVarType($v->name); - } } } elseif ($node instanceof Node\ArrayItem && $node->byRef) { $this->markWriteContext($node->value); @@ -234,6 +301,10 @@ public function leaveNode(Node $node): Node|array|null { $this->trackDeclarationExit($node); + if ($node instanceof Node\Stmt\Unset_) { + return $this->handleUnset($node); + } + if ($node instanceof Node\Stmt\Class_ && $node->name !== null) { $className = $this->resolveQualifiedName($node->name); if ($className !== null) { @@ -251,7 +322,7 @@ public function leaveNode(Node $node): Node|array|null } } - if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Expr\Closure) { + if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Expr\Closure || $node instanceof Node\Expr\ArrowFunction) { array_pop($this->byRefStack); } @@ -1816,11 +1887,11 @@ private function buildChainAst(array $chain): Node\Expr\Array_ foreach ($chain as $step) { $kind = new Node\Scalar\String_($step[0]); if ($step[0] === 'dim') { - $dimExpr = $step[1] instanceof Node\Expr ? $step[1] : new Node\Expr\ConstFetch(new Node\Name('null')); + $dimExpr = $step[1] instanceof Node\Expr ? clone $step[1] : new Node\Expr\ConstFetch(new Node\Name('null')); } elseif (\is_string($step[1])) { $dimExpr = new Node\Scalar\String_($step[1]); } elseif ($step[1] instanceof Node\Expr) { - $dimExpr = $step[1]; + $dimExpr = clone $step[1]; } else { $dimExpr = new Node\Scalar\String_(''); } @@ -2126,4 +2197,200 @@ private function extractDestructuringVariables(Node\Expr\List_|Node\Expr\Array_ return $vars; } + + /** + * Hoists impure targets, groups unset chains by root, injects pre-validation checks, + * and unregisters any whole variables destroyed by unset(). + * + * @return list|null + */ + private function handleUnset(Node\Stmt\Unset_ $node): ?array + { + /** @var list $preStmts */ + $preStmts = []; + /** @var list $varsToUnregister */ + $varsToUnregister = []; + /** @var array>}> $varUnsetGroups */ + $varUnsetGroups = []; + /** @var array>}> $propUnsetGroups */ + $propUnsetGroups = []; + + foreach ($node->vars as $idx => $v) { + if ($v instanceof Node\Expr\Variable) { + if (\is_string($v->name)) { + $varsToUnregister[] = $v->name; + } + + continue; + } + + if ($this->targetHasSideEffects($v)) { + $preAssignments = []; + $cleanTarget = $this->hoistImpureTarget($v, $preAssignments); + $this->markWriteContext($cleanTarget); + $node->vars[$idx] = $cleanTarget; + $v = $cleanTarget; + + foreach ($preAssignments as $assign) { + $preStmt = new Node\Stmt\Expression($assign); + $preStmt->setAttribute('typephp_injected', true); + $preStmts[] = $preStmt; + } + } + + $chainInfo = $this->extractMemberChain($v); + if ($chainInfo !== null) { + $root = $chainInfo['root']; + $chain = $chainInfo['chain']; + + if ($root instanceof Node\Expr\Variable && \is_string($root->name)) { + $varName = $root->name; + $typeString = $this->scopeManager->getVarTypeFromScope($varName); + + if ($typeString !== null && $this->shouldHandleMemberUnsetCheck($typeString, $chain)) { + if (! isset($varUnsetGroups[$varName])) { + $varUnsetGroups[$varName] = [ + 'rootExpr' => clone $root, + 'typeString' => $typeString, + 'varName' => $varName, + 'chains' => [], + ]; + } + $varUnsetGroups[$varName]['chains'][] = $chain; + + continue; + } + } + } + + $propDimInfo = $this->extractPropertyDimChain($v); + if ($propDimInfo !== null) { + $tExpr = $propDimInfo['targetExpr']; + $pName = $propDimInfo['propName']; + + if ($tExpr instanceof Node\Expr\Variable && \is_string($tExpr->name)) { + $groupKey = 'v:' . $tExpr->name . ':' . $pName; + } elseif ($tExpr instanceof Node\Expr\ClassConstFetch && $tExpr->class instanceof Node\Name) { + $groupKey = 'c:' . $tExpr->class->toString() . ':' . $pName; + } else { + $groupKey = 'u:' . $idx; + } + + if (! isset($propUnsetGroups[$groupKey])) { + $propUnsetGroups[$groupKey] = [ + 'targetExpr' => clone $tExpr, + 'propName' => $pName, + 'chains' => [], + ]; + } + $propUnsetGroups[$groupKey]['chains'][] = $propDimInfo['chain']; + } + } + + /** @var list $checkStmts */ + $checkStmts = []; + $line = $node->getStartLine(); + + foreach ($varUnsetGroups as $group) { + $checkCall = NodeBuilder::createMemberUnsetCheckCall( + $group['rootExpr'], + $this->buildChainsAst($group['chains']), + $group['typeString'], + $group['varName'], + $line, + $this->getCurrentCallerExpr(), + $this->getCurrentThisExpr() + ); + $checkStmts[] = NodeBuilder::createIfErrorThrowStmt($checkCall, $line); + } + + foreach ($propUnsetGroups as $group) { + $checkCall = NodeBuilder::createPropertyMemberUnsetCheckCall( + $group['targetExpr'], + $group['propName'], + $this->buildChainsAst($group['chains']), + $line + ); + $checkStmts[] = NodeBuilder::createIfErrorThrowStmt($checkCall, $line); + } + + foreach ($varsToUnregister as $varName) { + $this->scopeManager->unregisterVarType($varName); + } + + if ($preStmts === [] && $checkStmts === []) { + return null; + } + + return [...$preStmts, ...$checkStmts, $node]; + } + + /** + * Converts a list of member accessor chains into an AST Array_ of chains. + * + * @param list> $chains + */ + private function buildChainsAst(array $chains): Node\Expr\Array_ + { + $items = []; + foreach ($chains as $chain) { + $items[] = new Node\ArrayItem($this->buildChainAst($chain)); + } + + return new Node\Expr\Array_($items); + } + + /** + * @param list $chain + */ + private function shouldHandleMemberUnsetCheck(string $typeString, array $chain): bool + { + if (($chain[0][0] ?? null) === 'prop') { + return str_contains($typeString, '{'); + } + + $hasDim = false; + foreach ($chain as $step) { + if ($step[0] === 'dim') { + $hasDim = true; + + break; + } + } + + if (! $hasDim) { + return str_contains($typeString, '{'); + } + + if (Config::isEliminateStaticallyProvenChecksEnabled()) { + $typeNode = $this->parseUnsetTypeCached($typeString); + if ($typeNode !== null && StaticTypeEvaluator::isUnsetSafe($typeNode, $chain)) { + return false; + } + } + + return true; + } + + private function parseUnsetTypeCached(string $typeString): ?TypeNode + { + if (isset(self::$parsedUnsetTypeCache[$typeString])) { + $cached = self::$parsedUnsetTypeCache[$typeString]; + + return $cached !== false ? $cached : null; + } + + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + $parsed = $typeParser->parse($tokens); + self::$parsedUnsetTypeCache[$typeString] = $parsed; + + return $parsed; + } catch (\Throwable) { + self::$parsedUnsetTypeCache[$typeString] = false; + + return null; + } + } } diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index 9505e8a9..3dbe1102 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -8,7 +8,9 @@ use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\Ternary; use PhpParser\Node\Expr\Variable; +use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; 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\TypeNode; @@ -110,4 +112,82 @@ public static function satisfies( || ObjectEvaluator::satisfies($expr, $typeNode, $currentFile) || ScalarEvaluator::satisfies($expr, $typeNode); } + + /** + * Determines whether unsetting a member at the given accessor chain can never + * violate the target TypeNode contract (e.g., unset($map['k']) on array or T[]). + * + * @param list $chain + */ + public static function isUnsetSafe(TypeNode $typeNode, array $chain): bool + { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + if ($chain === []) { + return true; + } + + $firstKind = $chain[0][0]; + if ($firstKind !== 'dim') { + return false; + } + + if ($typeNode instanceof NullableTypeNode) { + return self::isUnsetSafe($typeNode->type, $chain); + } + + if ($typeNode instanceof UnionTypeNode) { + $hasArrayMember = false; + foreach ($typeNode->types as $member) { + if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { + continue; + } + + $hasArrayMember = true; + if (! self::isUnsetSafe($member, $chain)) { + return false; + } + } + + return $hasArrayMember; + } + + if ($typeNode instanceof IdentifierTypeNode) { + $lower = strtolower($typeNode->name); + + return $lower === 'array' || $lower === 'iterable' || $lower === 'mixed'; + } + + if ($typeNode instanceof ArrayTypeNode) { + if (\count($chain) === 1) { + return true; + } + + return self::isUnsetSafe($typeNode->type, \array_slice($chain, 1)); + } + + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower((string) $typeNode->type); + if ($base !== 'array' && $base !== 'iterable') { + return false; + } + + if (\count($chain) === 1) { + return true; + } + + $genericCount = \count($typeNode->genericTypes); + if ($genericCount === 0) { + return true; + } + + $valueType = $genericCount >= 2 ? $typeNode->genericTypes[1] : $typeNode->genericTypes[0]; + + return self::isUnsetSafe($valueType, \array_slice($chain, 1)); + } + + return false; + } } diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 550367a9..1325a0a3 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -389,6 +389,10 @@ private static function collectTrustedParamTypes( return []; } + if (Config::getOnViolation() !== 'throw' || ! Config::isParamsEnabled()) { + return []; + } + $candidateNames = []; foreach ($node->params as $p) { if (! $p->byRef && $p->var instanceof Node\Expr\Variable && \is_string($p->var->name)) { @@ -425,6 +429,13 @@ private static function collectTrustedParamTypes( continue; } + if ( + Config::isRespectNativeNullabilityEnabled() + && self::parameterAllowsNullNatively($p) + ) { + continue; + } + $typeNode = null; if (isset($paramTags[$pName])) { $typeNode = $paramTags[$pName]->type; @@ -458,6 +469,32 @@ private static function collectTrustedParamTypes( return $trustedTypes; } + private static function parameterAllowsNullNatively(Node\Param $param): bool + { + if ($param->default instanceof Node\Expr\ConstFetch && strtolower($param->default->name->toString()) === 'null') { + return true; + } + + $type = $param->type; + if ($type instanceof Node\NullableType) { + return true; + } + + if ($type instanceof Node\Identifier && strtolower($type->name) === 'null') { + return true; + } + + if ($type instanceof Node\UnionType) { + foreach ($type->types as $t) { + if ($t instanceof Node\Identifier && strtolower($t->name) === 'null') { + return true; + } + } + } + + return false; + } + /** * Traverses statements to identify parameters that are never mutated or passed by reference. * @@ -470,13 +507,11 @@ private static function findUnmutatedVariables(array $stmts, array $candidateNam { $unmutated = $candidateNames; - $visitor = new class ($unmutated) extends NodeVisitorAbstract { + $visitor = new class($unmutated) extends NodeVisitorAbstract { /** * @param array $unmutated */ - public function __construct(public array &$unmutated) - { - } + public function __construct(public array &$unmutated) {} public function enterNode(Node $node): ?int { @@ -836,7 +871,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class () extends NodeVisitorAbstract { + $visitor = new class() extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -1466,7 +1501,7 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $genContract, $explicitGenContract, @@ -1493,8 +1528,7 @@ public function __construct( private bool $hasSelfOut, private array $trustedParamTypes, private bool $useDynamicMethodKey - ) { - } + ) {} public function enterNode(Node $n): int|Node|array|null { @@ -1741,7 +1775,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1777,8 +1811,7 @@ public function __construct( private array $trustedParamTypes, private bool $useDynamicMethodKey, private bool $canGuardReturnCache - ) { - } + ) {} public function enterNode(Node $n): int|array|null { diff --git a/src/Internal/Ast/NodeBuilder.php b/src/Internal/Ast/NodeBuilder.php index fdd40402..7af450a9 100644 --- a/src/Internal/Ast/NodeBuilder.php +++ b/src/Internal/Ast/NodeBuilder.php @@ -232,4 +232,102 @@ public static function createConstantClosureReturnCheckCall( ] ); } + + public static function createMemberUnsetCheckCall( + Node\Expr $rootExpr, + Node\Expr $chainsExpr, + string $typeString, + string $varName, + int $line, + ?Node\Expr $callerExpr = null, + ?Node\Expr $thisArg = null + ): Node\Expr\FuncCall { + $args = [ + new Node\Arg($rootExpr), + new Node\Arg($chainsExpr), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\String_($varName)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ]; + + if ($callerExpr !== null) { + $args[] = new Node\Arg($callerExpr); + if ($thisArg !== null) { + $args[] = new Node\Arg($thisArg); + } + } + + return new Node\Expr\FuncCall( + new Node\Name('\TypePHP\Internal\RuntimeTypeChecker::checkMemberUnset'), + $args + ); + } + + public static function createPropertyMemberUnsetCheckCall( + Node\Expr $objectOrClassExpr, + string $propertyName, + Node\Expr $chainsExpr, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name('\TypePHP\Internal\RuntimeTypeChecker::checkPropertyMemberUnset'), + [ + new Node\Arg($objectOrClassExpr), + new Node\Arg(new Node\Scalar\String_($propertyName)), + new Node\Arg($chainsExpr), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } + + public static function createIfErrorThrowStmt(Node\Expr\FuncCall $checkCall, int $startLine = -1): Node\Stmt\If_ + { + $args = [ + new Node\Arg( + new Node\Expr\New_( + new Node\Name\FullyQualified('TypePHP\Exception\TypeError'), + [ + new Node\Arg( + new Node\Expr\MethodCall( + new Node\Expr\Variable('__typephpErr'), + 'getMessage' + ) + ), + ] + ) + ), + ]; + + if ($startLine !== -1) { + $args[] = new Node\Arg(new Node\Scalar\LNumber($startLine)); + } + + $ifStmt = new Node\Stmt\If_( + new Node\Expr\Instanceof_( + new Node\Expr\Assign( + new Node\Expr\Variable('__typephpErr'), + $checkCall + ), + new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage') + ), + [ + 'stmts' => [ + new Node\Stmt\Expression( + new Node\Expr\Throw_( + new Node\Expr\StaticCall( + new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorFactory'), + 'prepareException', + $args + ) + ) + ), + ], + ] + ); + $ifStmt->setAttribute('typephp_injected', true); + + return $ifStmt; + } } diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 742ebc07..1227b891 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -171,7 +171,8 @@ public static function checkVariable( string $file, TypeValidatorRegistry $registry, ?string $caller = null, - mixed $thisOrClass = null + mixed $thisOrClass = null, + bool $allowEmptyShape = true ): mixed { if (! Config::hasActiveInlineChecks()) { return $value; @@ -196,7 +197,7 @@ public static function checkVariable( return $value; } - if ($value === [] && $varName !== 'return' && self::isArrayShapeType($typeNode)) { + if ($allowEmptyShape && $value === [] && $varName !== 'return' && self::isArrayShapeType($typeNode)) { return $value; } diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 4d2e5ff5..a0d6a250 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -12,6 +12,7 @@ use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use ReflectionNamedType; use ReflectionProperty; +use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Docblock\DocblockParser; @@ -215,6 +216,109 @@ public static function check( return $value; } + /** + * Evaluates member unset mutations against the root variable's type contract before unsetting. + * + * @param list> $chains + */ + public static function checkUnset( + mixed $root, + array $chains, + string $typeString, + string $varName, + string $file, + TypeValidatorRegistry $registry, + ?string $caller = null, + mixed $thisOrClass = null + ): ?ErrorMessage { + if ($chains === []) { + return null; + } + + if (\is_object($root) && ($chains[0][0][0] ?? null) === 'dim') { + return null; + } + + $copy = StructureMutator::unsetCopy($root, $chains); + + $res = InlineChecker::checkVariable( + $copy, + $typeString, + $varName, + $file, + $registry, + $caller, + $thisOrClass, + allowEmptyShape: false + ); + + return $res instanceof ErrorMessage ? $res : null; + } + + /** + * Evaluates member unset mutations on an object or static property. + * + * @param list> $chains + */ + public static function checkPropertyUnset( + mixed $objectOrClass, + string $propName, + array $chains, + string $file, + ?TypeValidatorRegistry $registry = null + ): ?ErrorMessage { + if ($chains === [] || (! \is_object($objectOrClass) && ! \is_string($objectOrClass))) { + return null; + } + + $className = \is_string($objectOrClass) ? $objectOrClass : $objectOrClass::class; + + if (isset(InlineChecker::$nullPropertyCache[$className][$propName]) || ! RuntimeTypeChecker::$inlinePropertiesEnabled) { + return null; + } + + if (Config::isEliminateStaticallyProvenChecksEnabled()) { + $propPlan = (isset(self::$propertyMutationPlanCache[$className]) && \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) + ? self::$propertyMutationPlanCache[$className][$propName] + : self::buildPropertyMutationPlan($className, $propName); + + if ($propPlan === null) { + return null; + } + + $allSafe = true; + foreach ($chains as $chain) { + if (! StaticTypeEvaluator::isUnsetSafe($propPlan['rawType'], $chain)) { + $allSafe = false; + + break; + } + } + + if ($allSafe) { + return null; + } + } + + $currentVal = self::readPropertyValue($objectOrClass, $className, $propName); + + if (\is_object($currentVal) && ($chains[0][0][0] ?? null) === 'dim') { + return null; + } + + $copy = StructureMutator::unsetCopy($currentVal, $chains); + + $res = InlineChecker::checkProperty( + $copy, + $objectOrClass, + $propName, + $file, + $registry ?? RuntimeTypeChecker::getRegistry() + ); + + return $res instanceof ErrorMessage ? $res : null; + } + /** * Evaluates dimension/member mutation assignment on an object or static property. * diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 7db9d7ab..391c4b77 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -562,6 +562,95 @@ public static function checkMemberAssign( return $res; } + /** + * Evaluates member unset mutations (unset($arr[$key]) or unset($obj->prop)) + * against the root variable's type contract atomically before unsetting. + * + * @param list> $chains + */ + public static function checkMemberUnset( + mixed $root, + array $chains, + string $typeString, + string $varName, + string $file, + int $line = -1, + ?string $caller = null, + mixed $thisOrClass = null + ): ?ErrorMessage { + if (! self::$isEnabled) { + return null; + } + + $res = MemberAssignChecker::checkUnset( + $root, + $chains, + $typeString, + $varName, + $file, + self::getRegistry(), + $caller, + $thisOrClass + ); + + if ($res instanceof ErrorMessage) { + if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($caller ?? '')) { + return null; + } + + /** @var ErrorMessage|null $handled */ + $handled = ViolationCollector::handle($res, 'variable', null, $file, $line > 0 ? $line : null, $caller, '$' . $varName); + + return $handled; + } + + return null; + } + + /** + * Evaluates member unset mutations on an object or static property + * (unset($obj->prop[$key]) or unset(Class::$prop[$key])) atomically before unsetting. + * + * @param list> $chains + */ + public static function checkPropertyMemberUnset( + mixed $objectOrClass, + string $propName, + array $chains, + string $file, + int $line = -1 + ): ?ErrorMessage { + if (! self::$isEnabled || ! self::$inlinePropertiesEnabled) { + return null; + } + + $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); + if ($className !== '' && isset(InlineChecker::$nullPropertyCache[$className][$propName])) { + return null; + } + + $res = MemberAssignChecker::checkPropertyUnset( + $objectOrClass, + $propName, + $chains, + $file, + self::$registry + ); + + if ($res instanceof ErrorMessage) { + if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName)) { + return null; + } + + /** @var ErrorMessage|null $handled */ + $handled = ViolationCollector::handle($res, 'property', null, $file, $line > 0 ? $line : null, $className . '::$' . $propName, '$' . $propName); + + return $handled; + } + + return null; + } + /** * Fast-path for 1-level property dimension assignments ($obj->prop[$key] = $val or $obj->prop[] = $val), * avoiding per-write [['dim', $key]] array allocations. diff --git a/src/Internal/Util/StructureMutator.php b/src/Internal/Util/StructureMutator.php index 327b5ebc..4973de73 100644 --- a/src/Internal/Util/StructureMutator.php +++ b/src/Internal/Util/StructureMutator.php @@ -85,4 +85,96 @@ public static function mutateCopy(mixed $root, array $chain, mixed $value): mixe return $copy; } + + /** + * Applies one or more unset operations along accessor chains on an isolated copy of root. + * + * @param list> $chains + */ + public static function unsetCopy(mixed $root, array $chains): mixed + { + $copy = \is_object($root) ? clone $root : $root; + + foreach ($chains as $chain) { + if ($chain === []) { + continue; + } + + $current = &$copy; + $count = \count($chain); + + for ($i = 0; $i < $count; $i++) { + [$kind, $key] = $chain[$i]; + $isLast = ($i === $count - 1); + + if ($kind === 'dim') { + if (! \is_array($current) || $key === null) { + break; + } + + if (\is_int($key) || \is_string($key)) { + $arrayKey = $key; + } elseif (\is_bool($key) || \is_float($key)) { + $arrayKey = (int) $key; + } else { + break; + } + + if ($isLast) { + unset($current[$arrayKey]); + } else { + if (! \array_key_exists($arrayKey, $current)) { + break; + } + + $next = $current[$arrayKey]; + if (! \is_array($next) && ! \is_object($next)) { + break; + } + + if (\is_object($next)) { + $current[$arrayKey] = clone $next; + } + + $current = &$current[$arrayKey]; + } + } elseif ($kind === 'prop') { + $propName = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); + if (! \is_object($current) || $propName === '') { + break; + } + + if ($isLast) { + try { + // @phpstan-ignore property.dynamicName + unset($current->$propName); + } catch (\Throwable) { + break; + } + } else { + try { + // @phpstan-ignore property.dynamicName + $propVal = $current->$propName ?? null; + if (! \is_array($propVal) && ! \is_object($propVal)) { + break; + } + + if (\is_object($propVal)) { + // @phpstan-ignore property.dynamicName + $current->$propName = clone $propVal; + } + + // @phpstan-ignore property.dynamicName + $current = &$current->$propName; + } catch (\Throwable) { + break; + } + } + } + } + unset($current); + } + + return $copy; + } } diff --git a/tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php b/tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php new file mode 100644 index 00000000..a4ff88a8 --- /dev/null +++ b/tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php @@ -0,0 +1,27 @@ + + */ +class Priority3IntArrayMap extends ArrayObject +{ +} + +class Priority3ArrayAccessHolder +{ + /** + * @var Priority3IntArrayMap + */ + public Priority3IntArrayMap $map; + + public function __construct() + { + $this->map = new Priority3IntArrayMap(['a' => 10]); + } +} diff --git a/tests/Fixtures/Priority3/CallableAliasFixtures.php b/tests/Fixtures/Priority3/CallableAliasFixtures.php new file mode 100644 index 00000000..6608125d --- /dev/null +++ b/tests/Fixtures/Priority3/CallableAliasFixtures.php @@ -0,0 +1,35 @@ + + */ +class Priority3CallableAliasHolder +{ + /** + * @param NumberPredicate $predicate + */ + public function filterNumber(mixed $predicate, int $val): bool + { + return $predicate($val); + } + + /** + * @param StringIterable $items + * + * @return list + */ + public function consumeStrings(mixed $items): array + { + $out = []; + foreach ($items as $v) { + $out[] = $v; + } + + return $out; + } +} diff --git a/tests/Fixtures/Priority3/MultiNamespaceFixtures.php b/tests/Fixtures/Priority3/MultiNamespaceFixtures.php new file mode 100644 index 00000000..25cdb63f --- /dev/null +++ b/tests/Fixtures/Priority3/MultiNamespaceFixtures.php @@ -0,0 +1,33 @@ + 'paid', + 'amount' => 100, + 'note' => 'initial', + ]; + + /** + * @var list + */ + public array $numbers = [10, 20, 30]; + + /** + * @var non-empty-list + */ + public array $nonEmptyNumbers = [10]; + + /** + * @var array{items: list, meta?: array{tag: string}} + */ + public array $nested = [ + 'items' => [1, 2, 3], + 'meta' => ['tag' => 'v1'], + ]; +} + +class MemberUnsetStaticBox +{ + /** + * @var list + */ + public static array $numbers = [1, 2, 3]; + + /** + * @var array{status: 'paid', amount: positive-int} + */ + public static array $receipt = [ + 'status' => 'paid', + 'amount' => 100, + ]; + + public static function reset(): void + { + self::$numbers = [1, 2, 3]; + self::$receipt = ['status' => 'paid', 'amount' => 100]; + } +} + +class MemberUnsetBoxFactory +{ + public int $calls = 0; + + public MemberUnsetPropertyBox $box; + + public function __construct() + { + $this->box = new MemberUnsetPropertyBox(); + } + + public function next(): MemberUnsetPropertyBox + { + $this->calls++; + + return $this->box; + } +} + +describe('Member Unset Validation (Red Phase)', function () { + beforeEach(function () { + MemberUnsetStaticBox::reset(); + Config::reset(); + TypePHP::clearViolations(); + }); + + afterEach(function () { + MemberUnsetStaticBox::reset(); + TypePHP::clearViolations(); + Config::reset(); + }); + + describe('1. Array Shapes (Required, Optional, Unsealed, Nested, Tuples & Aliases)', function () { + test('reproduces playground bug: rejects unset on required key and prevents Undefined array key in subsequent compound op', function () { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + $warnings = []; + set_error_handler(static function (int $errno, string $errstr) use (&$warnings): bool { + $warnings[] = $errstr; + + return true; + }); + + try { + expect(function () use (&$receipt) { + unset($receipt['amount']); + })->toThrow(TypeError::class, "Variable \$receipt is missing required key 'amount'"); + + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + + expect(function () use (&$receipt) { + $receipt['amount'] += -200; + })->toThrow(TypeError::class, "Variable \$receipt['amount'] must be of type positive-int"); + } finally { + restore_error_handler(); + } + + expect($warnings)->toBeEmpty(); + }); + + test('rejects unsetting the sole required key of a 1-key array shape (must not hit empty-array init bypass)', function () { + /** @var array{amount: positive-int} $single */ + $single = ['amount' => 100]; + + expect(function () use (&$single) { + unset($single['amount']); + })->toThrow(TypeError::class, "Variable \$single is missing required key 'amount'"); + + expect($single)->toBe(['amount' => 100]); + }); + + test('allows unsetting optional keys (including already-absent optional keys) on an array shape', function () { + /** @var array{status: 'paid', amount: positive-int, note?: string} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100, 'note' => 'promo']; + + unset($receipt['note']); + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + + unset($receipt['note']); + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + }); + + test('allows unsetting extra keys on an unsealed shape while rejecting required keys', function () { + /** @var array{status: 'paid', ...} $receipt */ + $receipt = ['status' => 'paid', 'ref' => 'abc-123']; + + unset($receipt['ref']); + expect($receipt)->toBe(['status' => 'paid']); + + expect(function () use (&$receipt) { + unset($receipt['status']); + })->toThrow(TypeError::class, "Variable \$receipt is missing required key 'status'"); + + expect($receipt)->toBe(['status' => 'paid']); + }); + + test('validates nested array shape unset and preserves state atomically', function () { + /** @var array{user: array{id: positive-int, name?: non-empty-string}} $config */ + $config = [ + 'user' => [ + 'id' => 42, + 'name' => 'Alice', + ], + ]; + + unset($config['user']['name']); + expect($config)->toBe(['user' => ['id' => 42]]); + + expect(function () use (&$config) { + unset($config['user']['id']); + })->toThrow(TypeError::class, "Variable \$config['user'] is missing required key 'id'"); + + expect($config)->toBe(['user' => ['id' => 42]]); + }); + + test('follows by-reference alias when unsetting a required key', function () { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + $alias = &$receipt; + + expect(function () use (&$alias) { + unset($alias['amount']); + })->toThrow(TypeError::class, "Variable \$alias is missing required key 'amount'"); + + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + }); + + test('enforces required vs optional elements on positional tuple shapes', function () { + /** @var array{0: positive-int, 1?: non-empty-string} $tuple */ + $tuple = [10, 'hello']; + + unset($tuple[1]); + expect($tuple)->toBe([10]); + + expect(function () use (&$tuple) { + unset($tuple[0]); + })->toThrow(TypeError::class, "Variable \$tuple is missing required key '0'"); + + expect($tuple)->toBe([10]); + }); + }); + + describe('2. Lists & Non-Empty Containers (list, non-empty-list, non-empty-array)', function () { + test('rejects unsetting non-trailing indices in list because it breaks sequential keys', function () { + /** @var list $list */ + $list = [1, 2, 3]; + + expect(function () use (&$list) { + unset($list[0]); + })->toThrow(TypeError::class, 'Variable $list must be a list'); + + expect($list)->toBe([1, 2, 3]); + + expect(function () use (&$list) { + unset($list[1]); + })->toThrow(TypeError::class, 'Variable $list must be a list'); + + expect($list)->toBe([1, 2, 3]); + }); + + test('allows unsetting the trailing index of list', function () { + /** @var list $list */ + $list = [1, 2, 3]; + + unset($list[2]); + expect($list)->toBe([1, 2]); + }); + + test('rejects unsetting the last remaining element of non-empty-list', function () { + /** @var non-empty-list $list */ + $list = [10, 20]; + + unset($list[1]); + expect($list)->toBe([10]); + + expect(function () use (&$list) { + unset($list[0]); + })->toThrow(TypeError::class, 'Variable $list must be a non-empty list'); + + expect($list)->toBe([10]); + }); + + test('rejects unsetting the last remaining element of non-empty-array while allowing partial unset', function () { + /** @var non-empty-array $map */ + $map = ['a' => 1, 'b' => 2]; + + unset($map['a']); + expect($map)->toBe(['b' => 2]); + + expect(function () use (&$map) { + unset($map['b']); + })->toThrow(TypeError::class, 'Variable $map must be a non-empty array'); + + expect($map)->toBe(['b' => 2]); + }); + + test('evaluates multi-target unset on the same root variable atomically as a single state transition', function () { + /** @var list $list */ + $list = [10, 20]; + + // Final state [] IS a valid list even though unsetting index 0 alone would create a gap + unset($list[0], $list[1]); + expect($list)->toBe([]); + + /** @var non-empty-list $nonEmpty */ + $nonEmpty = [10, 20]; + + // Final state [] violates non-empty-list; neither element should be unset + expect(function () use (&$nonEmpty) { + unset($nonEmpty[0], $nonEmpty[1]); + })->toThrow(TypeError::class, 'Variable $nonEmpty must be a non-empty list'); + + expect($nonEmpty)->toBe([10, 20]); + }); + }); + + describe('3. Object Shapes (object{...})', function () { + test('rejects unsetting required property and allows unsetting optional property on stdClass shape', function () { + /** @var object{id: positive-int, name: non-empty-string, note?: string} $obj */ + $obj = (object) ['id' => 1, 'name' => 'Alice', 'note' => 'vip']; + + unset($obj->note); + expect(property_exists($obj, 'note'))->toBeFalse(); + + expect(function () use (&$obj) { + unset($obj->name); + })->toThrow(TypeError::class, "Variable \$obj is missing required property 'name'"); + + expect($obj->name)->toBe('Alice'); + }); + + test('rejects unsetting nested required object shape property', function () { + /** @var object{user: object{id: positive-int}} $data */ + $data = (object) ['user' => (object) ['id' => 10]]; + + expect(function () use (&$data) { + unset($data->user->id); + })->toThrow(TypeError::class, "Variable \$data->user is missing required property 'id'"); + + expect($data->user->id)->toBe(10); + }); + }); + + describe('4. Class & Static Property Member Unset', function () { + test('rejects unsetting required shape key and allows optional key on object property', function () { + $box = new MemberUnsetPropertyBox(); + + unset($box->receipt['note']); + expect($box->receipt)->toBe(['status' => 'paid', 'amount' => 100]); + + expect(function () use ($box) { + unset($box->receipt['amount']); + })->toThrow(TypeError::class, "is missing required key 'amount'"); + + expect($box->receipt)->toBe(['status' => 'paid', 'amount' => 100]); + }); + + test('rejects unsetting non-trailing list element and emptying non-empty-list on object property', function () { + $box = new MemberUnsetPropertyBox(); + + unset($box->numbers[2]); + expect($box->numbers)->toBe([10, 20]); + + expect(function () use ($box) { + unset($box->numbers[0]); + })->toThrow(TypeError::class, 'must be a list'); + + expect($box->numbers)->toBe([10, 20]); + + expect(function () use ($box) { + unset($box->nonEmptyNumbers[0]); + })->toThrow(TypeError::class, 'must be a non-empty list'); + + expect($box->nonEmptyNumbers)->toBe([10]); + }); + + test('validates nested property member unset ($box->nested["items"][0])', function () { + $box = new MemberUnsetPropertyBox(); + + unset($box->nested['meta']); + expect($box->nested)->toBe(['items' => [1, 2, 3]]); + + expect(function () use ($box) { + unset($box->nested['items'][0]); + })->toThrow(TypeError::class, "['items'] must be a list"); + + expect($box->nested['items'])->toBe([1, 2, 3]); + }); + + test('validates static property member unset (StaticBox::$numbers[0] & StaticBox::$receipt["amount"])', function () { + expect(function () { + unset(MemberUnsetStaticBox::$numbers[0]); + })->toThrow(TypeError::class, 'must be a list'); + + expect(MemberUnsetStaticBox::$numbers)->toBe([1, 2, 3]); + + expect(function () { + unset(MemberUnsetStaticBox::$receipt['amount']); + })->toThrow(TypeError::class, "is missing required key 'amount'"); + + expect(MemberUnsetStaticBox::$receipt)->toBe(['status' => 'paid', 'amount' => 100]); + }); + }); + + describe('5. Side-Effecting Target Single-Evaluation', function () { + test('evaluates impure property receiver and array index only once on unset', function () { + $factory = new MemberUnsetBoxFactory(); + + // Valid trailing unset on impure receiver + unset($factory->next()->numbers[2]); + expect($factory->calls)->toBe(1) + ->and($factory->box->numbers)->toBe([10, 20]) + ; + + // Failing unset on impure receiver still evaluates next() only once + expect(function () use ($factory) { + unset($factory->next()->numbers[0]); + })->toThrow(TypeError::class, 'must be a list'); + + expect($factory->calls)->toBe(2) + ->and($factory->box->numbers)->toBe([10, 20]) + ; + + // Impure array index expression on local list variable + /** @var list $list */ + $list = [1, 2, 3]; + $idx = 2; + unset($list[$idx++]); + + expect($idx)->toBe(3) + ->and($list)->toBe([1, 2]) + ; + }); + }); + + describe('6. Bare Variable Unset, Static Elimination, Zero Line-Drift & Violation Modes', function () { + test('allows bare unset($receipt) without throwing and unregisters its scope binding', function () { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + unset($receipt); + + expect(isset($receipt))->toBeFalse(); + + // After bare unset, reassigning without a new @var must not enforce the old contract + $receipt = 'completely_different'; + expect($receipt)->toBe('completely_different'); + }); + + test('allows and statically eliminates unset checks on plain associative maps (array, T[])', function () { + $source = <<<'PHP' + $map */ +$map = ['a' => 1, 'b' => 2]; +unset($map['a']); + +/** @var int[] $nums */ +$nums = [1, 2, 3]; +unset($nums[0]); +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_unset_map_elimination.php'); + + expect($transformed)->not()->toContain('checkMemberUnset'); + + /** @var array $map */ + $map = ['a' => 1, 'b' => 2]; + unset($map['a']); + expect($map)->toBe(['b' => 2]); + }); + + test('preserves exact line numbers (zero line-drift) when injecting unset guards', function () { + $source = <<<'PHP' + 'paid', 'amount' => 100]; + +unset($receipt['amount']); + +$landmark = 'exact_line_10'; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_unset_line_drift.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)); + + $origIdx = array_search("\$landmark = 'exact_line_10';", array_map('trim', $origLines), true); + $transIdx = array_search("\$landmark = 'exact_line_10';", array_map('trim', $transLines), true); + + expect($transIdx)->toBe($origIdx) + ->and($origIdx)->toBe(9) + ; + }); + + test('records violation without throwing in report mode and bypasses when enabled is false', function () { + Config::set(['on_violation' => 'report']); + + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + unset($receipt['amount']); + + expect($receipt)->toBe(['status' => 'paid']); + + $violations = TypePHP::getViolations(); + expect($violations)->toHaveCount(1) + ->and($violations[0]->kind)->toBe('variable') + ->and($violations[0]->target)->toBe('$receipt') + ->and($violations[0]->expected)->toBe("required 'amount'") + ; + + Config::set(['enabled' => false, 'on_violation' => 'throw']); + + /** @var array{status: 'paid', amount: positive-int} $disabledReceipt */ + $disabledReceipt = ['status' => 'paid', 'amount' => 100]; + unset($disabledReceipt['amount']); + + expect($disabledReceipt)->toBe(['status' => 'paid']); + }); + }); +}); diff --git a/tests/TypeChecking/ArraysAndShapes/UnsetMutationTest.php b/tests/TypeChecking/ArraysAndShapes/UnsetMutationTest.php new file mode 100644 index 00000000..147ba6c5 --- /dev/null +++ b/tests/TypeChecking/ArraysAndShapes/UnsetMutationTest.php @@ -0,0 +1,533 @@ + 1, + 'name' => 'Alice', + 'nickname' => 'Ali', + ]; + + /** + * @var list + */ + public array $numbers = [10, 20, 30]; + + /** + * @var non-empty-array + */ + public array $nonEmpty = ['only' => 100]; +} + +class UnsetPropStaticBox +{ + /** + * @var array{status: 'paid', amount: positive-int, note?: string} + */ + public static array $receipt = [ + 'status' => 'paid', + 'amount' => 100, + 'note' => 'ok', + ]; + + /** + * @var list + */ + public static array $numbers = [10, 20, 30]; + + public static function reset(): void + { + self::$receipt = [ + 'status' => 'paid', + 'amount' => 100, + 'note' => 'ok', + ]; + self::$numbers = [10, 20, 30]; + } +} + +/** + * @template T + */ +class UnsetGenericListBox +{ + /** + * @var non-empty-list + */ + public array $items; + + /** + * @param non-empty-list $items + */ + public function __construct(array $items) + { + $this->items = $items; + } +} + +class UnsetIgnoredCaller +{ + /** + * @typephp-ignore + */ + public static function unsetRequiredShapeKey(): array + { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + unset($receipt['amount']); + + return $receipt; + } + + /** + * @typephp-ignore + */ + public static function unsetPropertyKey(UnsetPropBox $box): void + { + unset($box->user['name']); + } +} + +describe('Unset Mutation Enforcement (unset($arr[$k]) & unset($obj->prop))', function () { + beforeEach(function () { + Config::reset(); + TypePHP::clearViolations(); + UnsetPropStaticBox::reset(); + }); + + afterEach(function () { + UnsetPropStaticBox::reset(); + TypePHP::clearViolations(); + Config::reset(); + }); + + describe('1. Direct Bug Reproduction & Cascading State Corruption', function () { + test('rejects unsetting a required array shape key and prevents cascading undefined key warning', function () { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + expect(function () use (&$receipt) { + unset($receipt['amount']); + })->toThrow(TypeError::class, "Variable \$receipt is missing required key 'amount'"); + + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + + $warnings = []; + set_error_handler(static function (int $errno, string $errstr) use (&$warnings): bool { + $warnings[] = $errstr; + + return true; + }); + + try { + expect(function () use (&$receipt) { + $receipt['amount'] += -200; + })->toThrow(TypeError::class, "Variable \$receipt['amount'] must be of type positive-int"); + } finally { + restore_error_handler(); + } + + expect($warnings)->toBeEmpty(); + }); + + test('rejects unsetting the only remaining required key on a 1-key shape (bypasses empty-array init exemption)', function () { + /** @var array{id: positive-int} $single */ + $single = ['id' => 1]; + + expect(function () use (&$single) { + unset($single['id']); + })->toThrow(TypeError::class, "Variable \$single is missing required key 'id'"); + + expect($single)->toBe(['id' => 1]); + }); + }); + + describe('2. Array Shapes (Required, Optional, Nested, Unsealed, Positional Tuples)', function () { + test('allows unsetting optional and non-existent keys on an array shape', function () { + /** @var array{status: 'paid', amount: positive-int, refunded_at?: non-empty-string} $receipt */ + $receipt = [ + 'status' => 'paid', + 'amount' => 100, + 'refunded_at' => '2026-01-01', + ]; + + unset($receipt['refunded_at']); + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + + unset($receipt['non_existent_key']); + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + }); + + test('enforces unsetting inside nested array shapes and preserves atomicity', function () { + /** @var array{user: array{id: positive-int, name: non-empty-string, nickname?: non-empty-string}} $payload */ + $payload = [ + 'user' => [ + 'id' => 1, + 'name' => 'Alice', + 'nickname' => 'Ali', + ], + ]; + + unset($payload['user']['nickname']); + expect($payload['user'])->toBe(['id' => 1, 'name' => 'Alice']); + + expect(function () use (&$payload) { + unset($payload['user']['name']); + })->toThrow(TypeError::class, "Variable \$payload['user'] is missing required key 'name'"); + + expect($payload['user']['name'])->toBe('Alice'); + }); + + test('enforces unsetting required key vs extra key on unsealed array shapes', function () { + /** @var array{id: positive-int, ...} $payload */ + $payload = ['id' => 42, 'extra' => 'meta']; + + unset($payload['extra']); + expect($payload)->toBe(['id' => 42]); + + expect(function () use (&$payload) { + unset($payload['id']); + })->toThrow(TypeError::class, "Variable \$payload is missing required key 'id'"); + + expect($payload)->toBe(['id' => 42]); + }); + + test('enforces required vs optional elements on positional tuple shapes', function () { + /** @var array{0: positive-int, 1?: non-empty-string} $tuple */ + $tuple = [10, 'label']; + + unset($tuple[1]); + expect($tuple)->toBe([10]); + + expect(function () use (&$tuple) { + unset($tuple[0]); + })->toThrow(TypeError::class, "Variable \$tuple is missing required key '0'"); + + expect($tuple)->toBe([10]); + }); + }); + + describe('3. Lists & Non-Empty Containers (list, non-empty-list, non-empty-array)', function () { + test('rejects interior unset on list that creates key gaps, while allowing trailing unset', function () { + /** @var list $items */ + $items = [10, 20, 30]; + + expect(function () use (&$items) { + unset($items[0]); + })->toThrow(TypeError::class, 'Variable $items must be a list'); + + expect($items)->toBe([10, 20, 30]); + + expect(function () use (&$items) { + unset($items[1]); + })->toThrow(TypeError::class, 'Variable $items must be a list'); + + expect($items)->toBe([10, 20, 30]); + + unset($items[2]); + expect($items)->toBe([10, 20]); + + unset($items[1], $items[0]); + expect($items)->toBe([]); + }); + + test('rejects unsetting the last element of non-empty-list', function () { + /** @var non-empty-list $items */ + $items = [10, 20]; + + unset($items[1]); + expect($items)->toBe([10]); + + expect(function () use (&$items) { + unset($items[0]); + })->toThrow(TypeError::class, 'Variable $items must be a non-empty list'); + + expect($items)->toBe([10]); + }); + + test('rejects unsetting the last entry of non-empty-array', function () { + /** @var non-empty-array $map */ + $map = ['a' => 1, 'b' => 2]; + + unset($map['a']); + expect($map)->toBe(['b' => 2]); + + expect(function () use (&$map) { + unset($map['b']); + })->toThrow(TypeError::class, 'Variable $map must be a non-empty array'); + + expect($map)->toBe(['b' => 2]); + }); + + test('rejects interior unset on large list even when array_validation is hybrid', function () { + Config::set(['array_validation' => 'hybrid']); + + /** @var list $largeList */ + $largeList = range(1, 200); + + expect(function () use (&$largeList) { + unset($largeList[50]); + })->toThrow(TypeError::class, 'Variable $largeList must be a list'); + + expect(\count($largeList))->toBe(200) + ->and(\array_key_exists(50, $largeList))->toBeTrue() + ; + }); + }); + + describe('4. Object Shapes (object{...}, stdClass{...}) & ArrayAccess Controls', function () { + test('rejects unsetting required property on object shape and allows optional property unset', function () { + /** @var object{id: positive-int, name: non-empty-string, nickname?: non-empty-string} $user */ + $user = (object) ['id' => 1, 'name' => 'Alice', 'nickname' => 'Ali']; + + unset($user->nickname); + expect(property_exists($user, 'nickname'))->toBeFalse(); + + expect(function () use ($user) { + unset($user->name); + })->toThrow(TypeError::class, "Variable \$user is missing required property 'name'"); + + expect($user->name)->toBe('Alice'); + }); + + test('rejects unsetting required property on strict stdClass shape and nested structures', function () { + /** @var \stdClass{profile: object{email: non-empty-string}, items: non-empty-list} $data */ + $data = (object) [ + 'profile' => (object) ['email' => 'alice@example.com'], + 'items' => [10], + ]; + + expect(function () use ($data) { + unset($data->profile->email); + })->toThrow(TypeError::class, "Variable \$data->profile is missing required property 'email'"); + + expect($data->profile->email)->toBe('alice@example.com'); + + expect(function () use ($data) { + unset($data->items[0]); + })->toThrow(TypeError::class, 'Variable $data->items must be a non-empty list'); + + expect($data->items)->toBe([10]); + }); + + test('allows unsetting keys on generic ArrayAccess object (ArrayObject)', function () { + /** @var ArrayObject $map */ + $map = new ArrayObject(['a' => 10, 'b' => 20]); + + unset($map['a']); + + expect(\count($map))->toBe(1) + ->and($map['b'])->toBe(20) + ; + }); + }); + + describe('5. Multi-Argument unset(), Impure Targets & By-Reference Aliases', function () { + test('validates multi-argument unset($a, $b) cumulatively and atomically when emptying non-empty-array', function () { + /** @var non-empty-array $map */ + $map = ['a' => 1, 'b' => 2]; + + expect(function () use (&$map) { + unset($map['a'], $map['b']); + })->toThrow(TypeError::class, 'Variable $map must be a non-empty array'); + + expect($map)->toBe(['a' => 1, 'b' => 2]); + }); + + test('evaluates side-effecting receiver and index expressions only once during unset', function () { + $box = new UnsetPropBox(); + $boxCalls = 0; + $getBox = static function () use ($box, &$boxCalls): UnsetPropBox { + $boxCalls++; + + return $box; + }; + + $idx = 2; + $getIdx = static function () use (&$idx): int { + return $idx--; + }; + + unset($getBox()->numbers[$getIdx()]); + expect($boxCalls)->toBe(1) + ->and($idx)->toBe(1) + ->and($box->numbers)->toBe([10, 20]) + ; + + expect(function () use ($getBox) { + unset($getBox()->user['name']); + })->toThrow(TypeError::class, "is missing required key 'name'"); + + expect($boxCalls)->toBe(2) + ->and($box->user['name'])->toBe('Alice') + ; + }); + + test('enforces unset on by-reference variable alias ($alias = &$receipt)', function () { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + $alias = &$receipt; + + expect(function () use (&$alias) { + unset($alias['amount']); + })->toThrow(TypeError::class, "Variable \$alias is missing required key 'amount'"); + + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]) + ->and($alias)->toBe(['status' => 'paid', 'amount' => 100]) + ; + }); + + test('allows unsetting an entire local variable and unregistering its @var contract', function () { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + unset($receipt); + + expect(isset($receipt))->toBeFalse(); + + $receipt = 'reassigned_after_unset'; + expect($receipt)->toBe('reassigned_after_unset'); + }); + }); + + describe('6. Class Instance, Static & Generic Properties', function () { + test('rejects invalid unset on instance property arrays/shapes and allows valid unsets', function () { + $box = new UnsetPropBox(); + + unset($box->user['nickname'], $box->numbers[2]); + expect($box->user)->toBe(['id' => 1, 'name' => 'Alice']) + ->and($box->numbers)->toBe([10, 20]) + ; + + expect(function () use ($box) { + unset($box->user['name']); + })->toThrow(TypeError::class, "is missing required key 'name'"); + + expect($box->user['name'])->toBe('Alice'); + + expect(function () use ($box) { + unset($box->numbers[0]); + })->toThrow(TypeError::class, 'must be a list'); + + expect($box->numbers)->toBe([10, 20]); + + expect(function () use ($box) { + unset($box->nonEmpty['only']); + })->toThrow(TypeError::class, 'must be a non-empty array'); + + expect($box->nonEmpty)->toBe(['only' => 100]); + }); + + test('rejects invalid unset on static property arrays/shapes', function () { + unset(UnsetPropStaticBox::$receipt['note'], UnsetPropStaticBox::$numbers[2]); + expect(UnsetPropStaticBox::$receipt)->toBe(['status' => 'paid', 'amount' => 100]) + ->and(UnsetPropStaticBox::$numbers)->toBe([10, 20]) + ; + + expect(function () { + unset(UnsetPropStaticBox::$receipt['amount']); + })->toThrow(TypeError::class, "is missing required key 'amount'"); + + expect(UnsetPropStaticBox::$receipt['amount'])->toBe(100); + + expect(function () { + unset(UnsetPropStaticBox::$numbers[0]); + })->toThrow(TypeError::class, 'must be a list'); + + expect(UnsetPropStaticBox::$numbers)->toBe([10, 20]); + }); + + test('rejects emptying non-empty-list generic property on pre-bound class instance', function () { + /** @var UnsetGenericListBox $box */ + $box = new UnsetGenericListBox([10]); + + expect(function () use ($box) { + unset($box->items[0]); + })->toThrow(TypeError::class, 'must be a non-empty list'); + + expect($box->items)->toBe([10]); + }); + }); + + describe('7. Closures, Config Toggles, Ignore Tags & Report Mode', function () { + test('enforces unset inside closures capturing @var variables', function () { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + $byValue = function () use ($receipt): void { + unset($receipt['amount']); + }; + + expect($byValue)->toThrow(TypeError::class, "is missing required key 'amount'"); + + $byRef = function () use (&$receipt): void { + unset($receipt['amount']); + }; + + expect($byRef)->toThrow(TypeError::class, "is missing required key 'amount'"); + expect($receipt)->toBe(['status' => 'paid', 'amount' => 100]); + }); + + test('respects global enabled => false and inline_vars config toggles', function () { + Config::set(['enabled' => false]); + + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + unset($receipt['amount']); + expect($receipt)->toBe(['status' => 'paid']); + + Config::reset(); + Config::set(['inline_vars' => ['arrays' => false, 'properties' => false]]); + + /** @var array{status: 'paid', amount: positive-int} $receipt2 */ + $receipt2 = ['status' => 'paid', 'amount' => 100]; + unset($receipt2['amount']); + expect($receipt2)->toBe(['status' => 'paid']); + + $box = new UnsetPropBox(); + unset($box->user['name']); + expect($box->user)->toBe(['id' => 1, 'nickname' => 'Ali']); + }); + + test('respects @typephp-ignore on calling method', function () { + $result = UnsetIgnoredCaller::unsetRequiredShapeKey(); + expect($result)->toBe(['status' => 'paid']); + + $box = new UnsetPropBox(); + UnsetIgnoredCaller::unsetPropertyKey($box); + expect($box->user)->toBe(['id' => 1, 'nickname' => 'Ali']); + }); + + test('records violation without throwing when on_violation is report', function () { + Config::set(['on_violation' => 'report']); + + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + unset($receipt['amount']); + + expect($receipt)->toBe(['status' => 'paid']); + + $violations = TypePHP::getViolations(); + expect($violations)->toHaveCount(1) + ->and($violations[0]->kind)->toBe('variable') + ->and($violations[0]->target)->toBe('$receipt') + ->and($violations[0]->expected)->toBe("required 'amount'") + ; + }); + }); +}); diff --git a/tests/TypeChecking/Boundaries/Priority1BugsTest.php b/tests/TypeChecking/Boundaries/Priority1BugsTest.php new file mode 100644 index 00000000..53fb20c4 --- /dev/null +++ b/tests/TypeChecking/Boundaries/Priority1BugsTest.php @@ -0,0 +1,191 @@ + self::$token; + } +} + +describe('Priority 1 Bugs: Type Safety & Call Boundary Soundness (Red Phase)', function () { + beforeEach(function () { + Config::reset(); + TypePHP::clearViolations(); + }); + + afterEach(function () { + TypePHP::clearViolations(); + Config::reset(); + }); + + describe('Bug 1: collectTrustedParamTypes vs respect_native_nullability & Report Mode', function () { + test('rejects null return when native parameter is ?int=null but DocBlock specifies positive-int', function () { + $fixture = new Priority1NullableParamFixture(); + + expect(fn () => $fixture->returnPositiveId(null)) + ->toThrow(TypeError::class, 'Return value') + ; + }); + + test('rejects null return when native parameter is int|null=null but DocBlock specifies positive-int', function () { + $fixture = new Priority1NullableParamFixture(); + + expect(fn () => $fixture->returnUnionPositiveId(null)) + ->toThrow(TypeError::class, 'Return value') + ; + }); + + test('records both parameter and return violations in report mode when unmutated parameter is returned', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p1_report_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/report_return.php'; + + $code = <<<'PHP' + 'report']); + StreamWrapper::register(); + + require_once $filePath; + + $fixture = new \App\Priority1\ReportReturnFixture(); + $result = $fixture->echoPositive(-10); + + expect($result)->toBe(-10); + + $violations = TypePHP::getViolations(); + $kinds = array_map(static fn ($v): string => $v->kind, $violations); + + expect($kinds)->toContain('parameter') + ->and($kinds)->toContain('return') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); + + describe('Bug 2: StaticPropertyFetch in By-Reference Arguments & By-Ref Arrow Functions', function () { + test('passes static property directly to preg_match without fatal error or StaticCall rewriting', function () { + Priority1StaticByRefHolder::$matches = []; + + $result = Priority1StaticByRefHolder::executePregMatch(); + + expect($result)->toBe(1) + ->and(Priority1StaticByRefHolder::$matches[0])->toBe('hello') + ; + }); + + test('passes static property directly to sort() by-reference without fatal error', function () { + Priority1StaticByRefHolder::$list = [3, 1, 2]; + + $result = Priority1StaticByRefHolder::executeSort(); + + expect($result)->toBeTrue() + ->and(Priority1StaticByRefHolder::$list)->toBe([1, 2, 3]) + ; + }); + + test('passes static property to user-defined by-reference method without fatal error', function () { + Priority1StaticByRefHolder::$token = 'initial'; + + Priority1StaticByRefHolder::executeCustomByRef(); + + expect(Priority1StaticByRefHolder::$token)->toBe('mutated'); + }); + + test('tracks by-reference returns in PHP 8.2+ arrow functions (fn &())', function () { + Priority1StaticByRefHolder::$token = 'valid'; + + $arrow = Priority1StaticByRefHolder::getArrowRef(); + $ref = &$arrow(); + $ref = 'updated'; + + expect(Priority1StaticByRefHolder::$token)->toBe('updated'); + }); + }); +}); \ No newline at end of file diff --git a/tests/Unit/LineNumberPreservationTest.php b/tests/Unit/LineNumberPreservationTest.php index 619caf0f..6f726dd3 100644 --- a/tests/Unit/LineNumberPreservationTest.php +++ b/tests/Unit/LineNumberPreservationTest.php @@ -28,10 +28,8 @@ function number(int $number): int $origLines = explode("\n", str_replace("\r\n", "\n", $source)); $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); - // Total number of lines in transformed source MUST match original source expect(\count($transLines))->toBe(\count($origLines)); - // The line containing 'number(-5);' must be on the exact same line index $origCallLine = array_search('number(-5);', array_map('trim', $origLines), true); $transCallLine = array_search('number(-5);', array_map('trim', $transLines), true); @@ -943,4 +941,268 @@ public function compute(int $multiplier): int ->and($transLines[$transReturnLine])->toContain('$intermediate') ; }); + + describe('Unset Statement Line Number Preservation', function () { + test('preserves exact line numbers when injecting unset guards across comments, closures, properties, and hoisted targets', function () { + $source = <<<'PHP' + 1, 'name' => 'Alice']; + + /** + * @var list + */ + public static array $scores = [10, 20, 30]; + + public function mutate(): void + { + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + // Trailing comment right before unset + unset($receipt['amount']); + + unset($this->user['name']); + unset(self::$scores[0]); + + $fn = function () use (&$receipt): void { + unset($receipt['status']); + }; + + $landmarkAfterClosure = true; + } +} + +$factory = new class () { + /** + * @var list + */ + public array $items = [1, 2, 3]; + + public function next(): self + { + return $this; + } +}; + +$idx = 0; +unset($factory->next()->items[$idx++]); + +$finalLandmark = 'exact_final_line'; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_unset_drift_comprehensive.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)) + ->and($transformed)->toContain('// Trailing comment right before unset') + ->and($transformed)->toContain('RuntimeTypeChecker::checkMemberUnset') + ->and($transformed)->toContain('RuntimeTypeChecker::checkPropertyMemberUnset') + ->and($transformed)->toContain('$__typephpTgt0 = $factory->next()') + ; + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + $landmarks = [ + "unset(\$receipt['amount']);", + "unset(\$this->user['name']);", + 'unset(self::$scores[0]);', + "unset(\$receipt['status']);", + '$landmarkAfterClosure = true;', + "\$finalLandmark = 'exact_final_line';", + ]; + + foreach ($landmarks as $landmark) { + $origIdx = $findLineIndex($landmark, $origLines); + $transIdx = $findLineIndex($landmark, $transLines); + + expect($origIdx)->toBeGreaterThan(-1, "Missing original landmark: {$landmark}") + ->and($transIdx)->toBe($origIdx, "Line drift detected on landmark: {$landmark}") + ; + } + + $origHoistedIdx = $findLineIndex('unset($factory->next()->items[$idx++]);', $origLines); + $transHoistedIdx = $findLineIndex('unset($__typephpTgt0->items[$__typephpTgt1]);', $transLines); + + expect($origHoistedIdx)->toBeGreaterThan(-1) + ->and($transHoistedIdx)->toBe($origHoistedIdx) + ; + }); + + test('preserves exact line numbers on CRLF (\r\n) files with unset injections', function () { + $source = " 'paid', 'amount' => 100];\r\n" + . "\r\n" + . "unset(\$receipt['amount']);\r\n" + . "\r\n" + . "\$crlfLandmark = true;\r\n"; + + $transformed = StreamWrapper::transformSource($source, 'test_unset_crlf_drift.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)); + + $origIdx = array_search('$crlfLandmark = true;', array_map('trim', $origLines), true); + $transIdx = array_search('$crlfLandmark = true;', array_map('trim', $transLines), true); + + expect($transIdx)->toBe($origIdx) + ->and($origIdx)->toBe(9) + ; + }); + + test('points TypeError::getLine() to the exact unset statement line at runtime', function () { + $sysTemp = realpath(sys_get_temp_dir()); + $baseTemp = str_replace('\\', '/', $sysTemp !== false ? $sysTemp : sys_get_temp_dir()); + $tempDir = $baseTemp . '/typephp_unset_line_' . uniqid(); + mkdir($tempDir, 0777, true); + + $canonicalDir = str_replace('\\', '/', realpath($tempDir) ?: $tempDir); + $scriptPath = $canonicalDir . '/unset_line_check.php'; + + $code = <<<'PHP' + 1, 'name' => 'Alice']; +} + +function triggerUnsetLocalLineError(): void +{ + /** @var array{status: 'paid', amount: positive-int} $receipt */ + $receipt = ['status' => 'paid', 'amount' => 100]; + + unset($receipt['amount']); +} + +function triggerUnsetPropLineError(): void +{ + $box = new UnsetLineCheckFixture(); + + unset($box->user['name']); +} +PHP; + + file_put_contents($scriptPath, $code); + + try { + Config::set([ + 'include' => [ + $canonicalDir . '/**', + ], + 'exclude' => [ + 'vendor/**', + ], + ]); + StreamWrapper::register(); + + require $scriptPath; + + $localLine = null; + + try { + triggerUnsetLocalLineError(); + } catch (TypePHP\Exception\TypeError $e) { + $localLine = $e->getLine(); + } + + $propLine = null; + + try { + triggerUnsetPropLineError(); + } catch (TypePHP\Exception\TypeError $e) { + $propLine = $e->getLine(); + } + + expect($localLine)->toBe(18) + ->and($propLine)->toBe(25) + ; + } finally { + Config::reset(); + if (file_exists($scriptPath)) { + @unlink($scriptPath); + } + if (is_dir($tempDir)) { + @rmdir($tempDir); + } + } + }); + + test('preserves valid PHP and exact line numbers when an inline // comment precedes an unset guard', function () { + $source = <<<'PHP' + 'paid', 'amount' => 100]; // Inline trailing comment + unset($receipt['amount']); + + $afterUnset = true; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_unset_inline_comment_drift.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)) + ->and($transformed)->toContain('RuntimeTypeChecker::checkMemberUnset') + ->and(PhpToken::tokenize($transformed))->toBeArray() + ; + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + $origUnsetIdx = $findLineIndex("unset(\$receipt['amount']);", $origLines); + $transUnsetIdx = $findLineIndex("unset(\$receipt['amount']);", $transLines); + + $origAfterIdx = $findLineIndex('$afterUnset = true;', $origLines); + $transAfterIdx = $findLineIndex('$afterUnset = true;', $transLines); + + expect($origUnsetIdx)->toBeGreaterThan(-1) + ->and($transUnsetIdx)->toBe($origUnsetIdx) + ->and($origAfterIdx)->toBeGreaterThan(-1) + ->and($transAfterIdx)->toBe($origAfterIdx) + ; + }); + }); }); From 3b6b2de6cb896f8b1b7f2c9ee051d7407a284441 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 11:53:39 +0800 Subject: [PATCH 2/9] Add tests for Priority 2 Bugs: Cache Isolation, AST Printer & Class Constants --- .../Boundaries/Priority2BugsTest.php | 629 ++++++++++++++++++ 1 file changed, 629 insertions(+) create mode 100644 tests/TypeChecking/Boundaries/Priority2BugsTest.php diff --git a/tests/TypeChecking/Boundaries/Priority2BugsTest.php b/tests/TypeChecking/Boundaries/Priority2BugsTest.php new file mode 100644 index 00000000..c2d2a02a --- /dev/null +++ b/tests/TypeChecking/Boundaries/Priority2BugsTest.php @@ -0,0 +1,629 @@ + + */ + public Priority2InnerBoxFixture $inner; + + /** + * @param T $value + */ + public function __construct(mixed $value) + { + $this->inner = new Priority2InnerBoxFixture($value); + } +} + +describe('Priority 2 Bugs: Cache Isolation, AST Printer & Class Constants (Red Phase)', function () { + beforeEach(function () { + Config::reset(); + }); + + afterEach(function () { + Config::reset(); + }); + + describe('Bug 3: TypePHPPrinter String Literal Preservation (#, //, and Spaces)', function () { + beforeEach(function () { + Config::set(['eliminate_statically_proven_checks' => false]); + }); + + test('preserves hex color string with # inside injected constant check without line drift', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkConstant') + ->and($transformed)->toContain("'\\'#ffffff\\''") + ->and($transformed)->not()->toContain('/*ffffff') + ->and(substr_count($transformed, "\n"))->toBe(substr_count($source, "\n")) + ; + }); + + test('preserves URL with double slashes // inside injected constant check without line drift', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkConstant') + ->and($transformed)->toContain("'\\'https://example.com/api\\''") + ->and($transformed)->not()->toContain('https:/*') + ->and(substr_count($transformed, "\n"))->toBe(substr_count($source, "\n")) + ; + }); + + test('preserves multiple consecutive spaces in string literals inside injected statements', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkConstant') + ->and($transformed)->toContain("'\\'a b\\''") + ->and($transformed)->not()->toContain("'\\'a b\\''") + ->and(substr_count($transformed, "\n"))->toBe(substr_count($source, "\n")) + ; + }); + + test('executes injected checks with #, //, escaped quotes, spaces, and attributes without ParseError', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p2_printer_' . uniqid(); + mkdir($tempDir, 0777, true); + $validFile = $tempDir . '/printer_valid.php'; + $invalidFile = $tempDir . '/printer_invalid.php'; + + $validCode = <<<'PHP' +toBe('#112233|https://a.test/x y') + ->and(fn() => require $invalidFile)->toThrow(TypeError::class) + ; + } finally { + @unlink($validFile); + @unlink($invalidFile); + @rmdir($tempDir); + } + }); + }); + + describe('Bug 4: TemplateManager::reset() Cache Clearing Omission', function () { + test('clears compiledBindPlanBySigCache and propagatedPropTypeCache on reset', function () { + $ref = new ReflectionClass(TemplateManager::class); + + $bindPlanProp = $ref->getProperty('compiledBindPlanBySigCache'); + $propTypeProp = $ref->getProperty('propagatedPropTypeCache'); + + $bindPlanProp->setValue(null, ['DummyClass' => ['DummySig' => ['skip' => true]]]); + $propTypeProp->setValue(null, ['DummyClass' => [0 => ['DummySig' => null]]]); + + expect($bindPlanProp->getValue())->not()->toBeEmpty() + ->and($propTypeProp->getValue())->not()->toBeEmpty() + ; + + TemplateManager::reset(); + + expect($bindPlanProp->getValue())->toBeEmpty() + ->and($propTypeProp->getValue())->toBeEmpty() + ; + }); + + test('clears naturally populated generic plan and propagation caches via Config::reset()', function () { + $outer = new Priority2OuterBoxFixture('hello'); + TemplateManager::bindInstance($outer, Priority2OuterBoxFixture::class . ''); + + $ref = new ReflectionClass(TemplateManager::class); + $bindPlanProp = $ref->getProperty('compiledBindPlanBySigCache'); + $propTypeProp = $ref->getProperty('propagatedPropTypeCache'); + + expect($bindPlanProp->getValue())->toHaveKey(Priority2OuterBoxFixture::class) + ->and($propTypeProp->getValue())->toHaveKey(Priority2OuterBoxFixture::class) + ; + + Config::reset(); + + expect($bindPlanProp->getValue())->toBeEmpty() + ->and($propTypeProp->getValue())->toBeEmpty() + ; + }); + }); + + describe('Bug 5: Class Constants with self::, parent::, static::, Visibility, and Class-Level Aliases', function () { + test('resolves self::CONSTANT in class constant check for valid and invalid values', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p2_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $validFile = $tempDir . '/self_const_valid.php'; + $invalidFile = $tempDir . '/self_const_invalid.php'; + + $validCode = <<<'PHP' + require $validFile)->not()->toThrow(TypeError::class) + ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'BASE_CODE') + ; + } finally { + @unlink($validFile); + @unlink($invalidFile); + @rmdir($tempDir); + } + }); + + test('resolves non-public self::PRIVATE_BASE and static::CONSTANT in class constant checks', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p2_self_vis_' . uniqid(); + mkdir($tempDir, 0777, true); + $validFile = $tempDir . '/self_vis_valid.php'; + $invalidFile = $tempDir . '/self_vis_invalid.php'; + + $validCode = <<<'PHP' + require $validFile)->not()->toThrow(TypeError::class) + ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'PRIVATE_BASE') + ; + } finally { + @unlink($validFile); + @unlink($invalidFile); + @rmdir($tempDir); + } + }); + + test('resolves parent::CONSTANT directly via RuntimeTypeChecker without swallowing Error', function () { + $valid = RuntimeTypeChecker::checkClassConstant( + Priority2ChildConstFixture::class, + 'CHILD_LIMIT', + 'parent::PARENT_LIMIT', + __FILE__, + 21 + ); + + expect($valid)->toBe(500); + + $res = RuntimeTypeChecker::checkConstant( + Priority2ChildConstFixture::class . '::CHILD_LIMIT', + 999, + 'parent::PARENT_LIMIT', + __FILE__, + 21 + ); + + expect($res)->toBeInstanceOf(ErrorMessage::class) + ->and($res->getMessage())->toContain('must be literal ' . Priority2ParentConstFixture::class . '::PARENT_LIMIT') + ; + }); + + test('resolves parent::CONSTANT and parent::PROTECTED_LIMIT end-to-end via StreamWrapper', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p2_parent_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $validFile = $tempDir . '/parent_const_valid.php'; + $invalidFile = $tempDir . '/parent_const_invalid.php'; + + $validCode = <<<'PHP' + require $validFile)->not()->toThrow(TypeError::class) + ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'PROTECTED_LIMIT') + ; + } finally { + @unlink($validFile); + @unlink($invalidFile); + @rmdir($tempDir); + } + }); + + test('resolves class-level @phpstan-type and @psalm-type aliases in class constant checks', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p2_alias_' . uniqid(); + mkdir($tempDir, 0777, true); + $validFile = $tempDir . '/alias_const_valid.php'; + $invalidFile = $tempDir . '/alias_const_invalid.php'; + + $validCode = <<<'PHP' + require $validFile)->not()->toThrow(TypeError::class) + ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($validFile); + @unlink($invalidFile); + @rmdir($tempDir); + } + }); + + test('resolves @phpstan-import-type and aliases referencing self:: constants in class constants', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p2_import_alias_' . uniqid(); + mkdir($tempDir, 0777, true); + $validFile = $tempDir . '/import_alias_valid.php'; + $invalidFile = $tempDir . '/import_alias_invalid.php'; + + $validCode = <<<'PHP' + + */ +class AliasSourceFixture +{ +} + +/** + * @phpstan-import-type SharedPort from AliasSourceFixture + * @phpstan-type FlagMask int-mask-of + */ +class ImportedAliasConstValidFixture +{ + public const FLAG_READ = 1; + public const FLAG_WRITE = 2; + + /** + * @var SharedPort + */ + public const DEFAULT_PORT = 8080; + + /** + * @var FlagMask + */ + public const DEFAULT_FLAGS = 3; +} +PHP; + + $invalidCode = <<<'PHP' + + */ +class AliasSourceInvalidFixture +{ +} + +/** + * @phpstan-import-type SharedPort from AliasSourceInvalidFixture + */ +class ImportedAliasConstInvalidFixture +{ + /** + * @var SharedPort + */ + public const BAD_PORT = 70000; +} +PHP; + + file_put_contents($validFile, $validCode); + file_put_contents($invalidFile, $invalidCode); + + try { + StreamWrapper::register(); + + expect(fn() => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn() => require $invalidFile)->toThrow(TypeError::class, '<= 65535') + ; + } finally { + @unlink($validFile); + @unlink($invalidFile); + @rmdir($tempDir); + } + }); + }); +}); From cddb81941d0323318382cf845350281b971ba944 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 12:52:17 +0800 Subject: [PATCH 3/9] Enhance type validation and error handling in ConstValidator and RuntimeTypeChecker; add new tests for alias constant resolution and inherited class-level aliases --- src/Internal/Ast/TypePHPPrinter.php | 49 ++++++- src/Internal/Generics/TemplateManager.php | 2 + src/Internal/RuntimeTypeChecker.php | 136 ++++++++++-------- src/Internal/Validator/ConstValidator.php | 91 ++++++++++-- .../Validator/TypeValidatorRegistry.php | 1 + .../Boundaries/Priority2BugsTest.php | 122 ++++++++++++++++ 6 files changed, 330 insertions(+), 71 deletions(-) diff --git a/src/Internal/Ast/TypePHPPrinter.php b/src/Internal/Ast/TypePHPPrinter.php index b2819da1..f867ab38 100644 --- a/src/Internal/Ast/TypePHPPrinter.php +++ b/src/Internal/Ast/TypePHPPrinter.php @@ -50,13 +50,54 @@ protected function p( } /** - * Converts single-line comments and squashes whitespace on injected statements. + * Converts single-line comments and squashes whitespace on injected statements + * without altering string literals or attribute tokens. */ private function formatInjectedStatement(string $output): string { - $output = preg_replace('/(?:\/\/(.*?)|#(.*?))(?=\r?\n|$)/', '/*$1$2 */', $output) ?? $output; - $output = preg_replace('/\s+/', ' ', trim($output)) ?? $output; + $trimmed = trim($output); + if ($trimmed === '') { + return '/*__TYPEPHP_INJECTED_START__*/' . '/*__TYPEPHP_INJECTED_END__*/'; + } + + $tokens = \PhpToken::tokenize(' $token) { + if ($index === 0 && $token->id === T_OPEN_TAG) { + continue; + } + + if ($token->id === T_WHITESPACE) { + $formatted .= ' '; + + continue; + } + + if ($token->id === T_COMMENT) { + if (str_starts_with($token->text, '//') || str_starts_with($token->text, '#')) { + $commentBody = rtrim($token->text, "\r\n"); + $cleaned = str_starts_with($commentBody, '//') + ? substr($commentBody, 2) + : substr($commentBody, 1); + $cleaned = str_replace('*/', '* /', $cleaned); + $formatted .= '/*' . $cleaned . ' */'; + } else { + $formatted .= preg_replace('/\s+/', ' ', $token->text) ?? $token->text; + } + + continue; + } + + if ($token->id === T_DOC_COMMENT) { + $formatted .= preg_replace('/\s+/', ' ', $token->text) ?? $token->text; + + continue; + } + + $formatted .= $token->text; + } - return '/*__TYPEPHP_INJECTED_START__*/' . $output . '/*__TYPEPHP_INJECTED_END__*/'; + return '/*__TYPEPHP_INJECTED_START__*/' . trim($formatted) . '/*__TYPEPHP_INJECTED_END__*/'; } } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 7c713d9a..4970d43f 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -669,6 +669,8 @@ public static function reset(): void self::$noInheritedBindingsClasses = []; self::$templatePropertyPlanCache = []; self::$verifiedShallowRefinements = null; + self::$compiledBindPlanBySigCache = []; + self::$propagatedPropTypeCache = []; } /** diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 391c4b77..5421cf40 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -281,32 +281,25 @@ public static function checkConstant( } try { - $normalized = DocblockNormalizer::normalize($typeString); - [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); - $tokens = new TokenIterator($lexer->tokenize($normalized)); - $typeNode = $typeParser->parse($tokens); - - if ($file !== '') { - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); - } + $typeNode = self::resolveConstantTypeNode($typeString, $constantName, $file); + } catch (\Throwable $e) { + return $value; + } - $context = "Constant {$constantName}"; + $context = "Constant {$constantName}"; - $err = self::getRegistry()->validate($value, $typeNode, $context); - if ($err !== null) { - if (IgnoreManager::isCallerIgnored()) { - return $value; - } + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } - $target = str_contains($constantName, '::') - ? explode('::', $constantName, 2)[1] - : $constantName; - $declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null; + $target = str_contains($constantName, '::') + ? explode('::', $constantName, 2)[1] + : $constantName; + $declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null; - return ViolationCollector::handle($err, 'constant', $value, $file, $line, $constantName, $target, $declaredIn); - } - } catch (\Throwable $e) { - // Silently ignore unexpected parsing errors + return ViolationCollector::handle($err, 'constant', $value, $file, $line, $constantName, $target, $declaredIn); } return $value; @@ -328,28 +321,22 @@ public static function checkConstantClosureParam( } try { - $normalized = DocblockNormalizer::normalize($typeString); - [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); - $tokens = new TokenIterator($lexer->tokenize($normalized)); - $typeNode = $typeParser->parse($tokens); - - if ($file !== '') { - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); - } + $typeNode = self::resolveConstantTypeNode($typeString, $caller, $file); + } catch (\Throwable $e) { + return $value; + } - $context = "{$caller}(): Argument \${$paramName}"; + $context = "{$caller}(): Argument \${$paramName}"; - $err = self::getRegistry()->validate($value, $typeNode, $context); - if ($err !== null) { - if (IgnoreManager::isCallerIgnored()) { - return $value; - } + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } - $declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null; + $declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null; - return ViolationCollector::handle($err, 'parameter', $value, null, null, $caller, '$' . $paramName, $declaredIn); - } - } catch (\Throwable $e) { + return ViolationCollector::handle($err, 'parameter', $value, null, null, $caller, '$' . $paramName, $declaredIn); } return $value; @@ -370,31 +357,68 @@ public static function checkConstantClosureReturn( } try { - $normalized = DocblockNormalizer::normalize($typeString); - [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); - $tokens = new TokenIterator($lexer->tokenize($normalized)); - $typeNode = $typeParser->parse($tokens); + $typeNode = self::resolveConstantTypeNode($typeString, $caller, $file); + } catch (\Throwable $e) { + return $value; + } + + $context = "{$caller}(): Return value"; - if ($file !== '') { - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; } - $context = "{$caller}(): Return value"; + $declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null; - $err = self::getRegistry()->validate($value, $typeNode, $context); - if ($err !== null) { - if (IgnoreManager::isCallerIgnored()) { - return $value; - } + return ViolationCollector::handle($err, 'return', $value, $file, $line, $caller, 'return', $declaredIn); + } - $declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null; + return $value; + } + + /** + * Parses a constant's type string, expanding class-level aliases and resolving self/static/parent + * when the target denotes a class constant, or falling back to file imports for global constants. + */ + private static function resolveConstantTypeNode(string $typeString, string $targetName, string $file): TypeNode + { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + $typeNode = $typeParser->parse($tokens); + + if (str_contains($targetName, '::')) { + $declaringClass = explode('::', $targetName, 2)[0]; + if ( + $declaringClass !== '' + && ClassNameValidator::isValid($declaringClass) + && ( + class_exists($declaringClass, false) + || interface_exists($declaringClass, false) + || trait_exists($declaringClass, false) + || enum_exists($declaringClass, false) + || class_exists($declaringClass) + || interface_exists($declaringClass) + || trait_exists($declaringClass) + || enum_exists($declaringClass) + ) + ) { + $aliases = DocblockParser::parseClassAliases($declaringClass); + if ($aliases !== []) { + $typeNode = DocblockParser::substituteAliases($typeNode, $aliases); + } - return ViolationCollector::handle($err, 'return', $value, $file, $line, $caller, 'return', $declaredIn); + return SpecialTypeResolver::resolve($typeNode, $declaringClass); } - } catch (\Throwable $e) { } - return $value; + if ($file !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + } + + return $typeNode; } /** diff --git a/src/Internal/Validator/ConstValidator.php b/src/Internal/Validator/ConstValidator.php index ffaa7561..f8e7e938 100644 --- a/src/Internal/Validator/ConstValidator.php +++ b/src/Internal/Validator/ConstValidator.php @@ -17,6 +17,7 @@ use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; +use TypePHP\Internal\Util\ClassNameValidator; /** * @internal Validates literal values, class constants, and wildcard constant patterns (Class::PREFIX_*) against ConstTypeNode ASTs. @@ -30,6 +31,19 @@ final class ConstValidator implements TypeValidatorInterface */ private static array $wildcardConstantCache = []; + /** + * 2D Cache for single resolved class constants: [$className][$constName] => array{0: bool, 1: mixed}. + * + * @var array> + */ + private static array $classConstantCache = []; + + public static function reset(): void + { + self::$wildcardConstantCache = []; + self::$classConstantCache = []; + } + public function validate(mixed $value, TypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { /** @var ConstTypeNode $constTypeNode */ @@ -68,15 +82,8 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return null; } - $fqcnConstant = $className !== '' - ? $className . '::' . $pattern - : $pattern; - - if (\defined($fqcnConstant)) { - $expected = \constant($fqcnConstant); - } else { - $expected = (string) $constExpr; - } + [$resolved, $constValue] = self::resolveSingleConstantValue($className, $pattern); + $expected = $resolved ? $constValue : (string) $constExpr; } else { $expected = (string) $constExpr; } @@ -96,6 +103,52 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return null; } + /** + * Resolves a single class or global constant value via ReflectionClass (supporting protected/private constants), + * guarding against unresolved relative class keywords (self, static, parent, $this). + * + * @return array{0: bool, 1: mixed} + */ + private static function resolveSingleConstantValue(string $className, string $constName): array + { + if ($className !== '') { + $lowerClass = strtolower($className); + if ($lowerClass === 'self' || $lowerClass === 'static' || $lowerClass === 'parent' || $lowerClass === '$this') { + return [false, null]; + } + + if (isset(self::$classConstantCache[$className]) && \array_key_exists($constName, self::$classConstantCache[$className])) { + return self::$classConstantCache[$className][$constName]; + } + + if ( + ClassNameValidator::isValid($className) + && ( + class_exists($className, false) + || class_exists($className) + || interface_exists($className, false) + || interface_exists($className) + || enum_exists($className, false) + || enum_exists($className) + ) + ) { + /** @var class-string $className */ + $refClass = new ReflectionClass($className); + if ($refClass->hasConstant($constName)) { + return self::$classConstantCache[$className][$constName] = [true, $refClass->getConstant($constName)]; + } + } + + return self::$classConstantCache[$className][$constName] = [false, null]; + } + + if (\defined($constName)) { + return [true, \constant($constName)]; + } + + return [false, null]; + } + /** * Resolves and caches all values of class constants matching a wildcard pattern (e.g. PREFIX_*). * @@ -109,8 +162,24 @@ private static function resolveWildcardConstantValues(string $className, string $list = []; $map = []; - - if ($className !== '' && (class_exists($className, false) || class_exists($className) || interface_exists($className, false) || interface_exists($className))) { + $lowerClass = strtolower($className); + + if ( + $className !== '' + && $lowerClass !== 'self' + && $lowerClass !== 'static' + && $lowerClass !== 'parent' + && $lowerClass !== '$this' + && ClassNameValidator::isValid($className) + && ( + class_exists($className, false) + || class_exists($className) + || interface_exists($className, false) + || interface_exists($className) + || enum_exists($className, false) + || enum_exists($className) + ) + ) { /** @var class-string $className */ $refClass = new ReflectionClass($className); $regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i'; diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index aff4a807..5a6503ec 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -47,6 +47,7 @@ public static function reset(): void { GenericValidator::reset(); ArrayShapeValidator::reset(); + ConstValidator::reset(); } public function __construct() diff --git a/tests/TypeChecking/Boundaries/Priority2BugsTest.php b/tests/TypeChecking/Boundaries/Priority2BugsTest.php index c2d2a02a..80bedb61 100644 --- a/tests/TypeChecking/Boundaries/Priority2BugsTest.php +++ b/tests/TypeChecking/Boundaries/Priority2BugsTest.php @@ -482,6 +482,7 @@ class ParentConstChildInvalidFixture extends ParentConstInvalidBaseFixture mkdir($tempDir, 0777, true); $validFile = $tempDir . '/alias_const_valid.php'; $invalidFile = $tempDir . '/alias_const_invalid.php'; + $invalidPrivateFile = $tempDir . '/alias_private_const_invalid.php'; $validCode = <<<'PHP' require $validFile)->not()->toThrow(TypeError::class) ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'positive-int') + ->and(fn() => require $invalidPrivateFile)->toThrow(TypeError::class, 'non-empty-string') ; } finally { @unlink($validFile); @unlink($invalidFile); + @unlink($invalidPrivateFile); @rmdir($tempDir); } }); @@ -548,6 +571,7 @@ class AliasConstInvalidFixture mkdir($tempDir, 0777, true); $validFile = $tempDir . '/import_alias_valid.php'; $invalidFile = $tempDir . '/import_alias_invalid.php'; + $invalidMaskFile = $tempDir . '/import_alias_mask_invalid.php'; $validCode = <<<'PHP' + */ +class ImportedAliasMaskInvalidFixture +{ + public const FLAG_READ = 1; + public const FLAG_WRITE = 2; + + /** + * @var FlagMask + */ + public const BAD_FLAGS = 8; +} PHP; file_put_contents($validFile, $validCode); file_put_contents($invalidFile, $invalidCode); + file_put_contents($invalidMaskFile, $invalidMaskCode); try { StreamWrapper::register(); expect(fn() => require $validFile)->not()->toThrow(TypeError::class) ->and(fn() => require $invalidFile)->toThrow(TypeError::class, '<= 65535') + ->and(fn() => require $invalidMaskFile)->toThrow(TypeError::class, 'bitmask') + ; + } finally { + @unlink($validFile); + @unlink($invalidFile); + @unlink($invalidMaskFile); + @rmdir($tempDir); + } + }); + + test('resolves inherited class-level aliases from parent classes in class constant checks', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p2_inherited_alias_' . uniqid(); + mkdir($tempDir, 0777, true); + $validFile = $tempDir . '/inherited_alias_valid.php'; + $invalidFile = $tempDir . '/inherited_alias_invalid.php'; + + $validCode = <<<'PHP' + + */ +class InheritedAliasParentValidFixture +{ +} + +class InheritedAliasChildValidFixture extends InheritedAliasParentValidFixture +{ + /** + * @var RetryCount + */ + public const MAX_RETRIES = 3; + + /** + * @var RetryCount + */ + protected const DEFAULT_RETRIES = 1; +} +PHP; + + $invalidCode = <<<'PHP' + + */ +class InheritedAliasParentInvalidFixture +{ +} + +class InheritedAliasChildInvalidFixture extends InheritedAliasParentInvalidFixture +{ + /** + * @var RetryCount + */ + public const MAX_RETRIES = 10; +} +PHP; + + file_put_contents($validFile, $validCode); + file_put_contents($invalidFile, $invalidCode); + + try { + StreamWrapper::register(); + + expect(fn() => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn() => require $invalidFile)->toThrow(TypeError::class, '<= 5') ; } finally { @unlink($validFile); From 0ed138413f927269a4f890f1be3b11eef5fac14d Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 13:18:32 +0800 Subject: [PATCH 4/9] Refactor code style and add new tests for Priority 3 Bugs: Cross-Namespace Static Elimination, Aliased Callables, and Opcode Fast-Paths --- src/Internal/Ast/FunctionContractInjector.php | 18 +- .../Priority3/ArrayAccessSubclassFixtures.php | 22 ++ .../Priority3/CallableAliasFixtures.php | 29 ++- .../Priority3/MultiNamespaceFixtures.php | 35 ++- .../Boundaries/Priority1BugsTest.php | 2 +- .../Boundaries/Priority2BugsTest.php | 34 +-- .../Boundaries/Priority3BugsTest.php | 203 ++++++++++++++++++ 7 files changed, 315 insertions(+), 28 deletions(-) create mode 100644 tests/TypeChecking/Boundaries/Priority3BugsTest.php diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 1325a0a3..a7dca979 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -507,11 +507,13 @@ private static function findUnmutatedVariables(array $stmts, array $candidateNam { $unmutated = $candidateNames; - $visitor = new class($unmutated) extends NodeVisitorAbstract { + $visitor = new class ($unmutated) extends NodeVisitorAbstract { /** * @param array $unmutated */ - public function __construct(public array &$unmutated) {} + public function __construct(public array &$unmutated) + { + } public function enterNode(Node $node): ?int { @@ -871,7 +873,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class() extends NodeVisitorAbstract { + $visitor = new class () extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -1501,7 +1503,7 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $genContract, $explicitGenContract, @@ -1528,7 +1530,8 @@ public function __construct( private bool $hasSelfOut, private array $trustedParamTypes, private bool $useDynamicMethodKey - ) {} + ) { + } public function enterNode(Node $n): int|Node|array|null { @@ -1775,7 +1778,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1811,7 +1814,8 @@ public function __construct( private array $trustedParamTypes, private bool $useDynamicMethodKey, private bool $canGuardReturnCache - ) {} + ) { + } public function enterNode(Node $n): int|array|null { diff --git a/tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php b/tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php index a4ff88a8..a754a300 100644 --- a/tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php +++ b/tests/Fixtures/Priority3/ArrayAccessSubclassFixtures.php @@ -13,6 +13,15 @@ class Priority3IntArrayMap extends ArrayObject { } +/** + * @template V + * + * @extends ArrayObject + */ +class Priority3StringKeyedMap extends ArrayObject +{ +} + class Priority3ArrayAccessHolder { /** @@ -20,8 +29,21 @@ class Priority3ArrayAccessHolder */ public Priority3IntArrayMap $map; + /** + * @var Priority3StringKeyedMap + */ + public Priority3StringKeyedMap $genericMap; + public function __construct() { $this->map = new Priority3IntArrayMap(['a' => 10]); + $this->genericMap = new Priority3StringKeyedMap(['a' => 10]); + } + + public function mutateLocalMap(int|string $key, mixed $value): void + { + /** @var Priority3IntArrayMap $localMap */ + $localMap = new Priority3IntArrayMap(['a' => 10]); + $localMap[$key] = $value; } } diff --git a/tests/Fixtures/Priority3/CallableAliasFixtures.php b/tests/Fixtures/Priority3/CallableAliasFixtures.php index 6608125d..f3124f3d 100644 --- a/tests/Fixtures/Priority3/CallableAliasFixtures.php +++ b/tests/Fixtures/Priority3/CallableAliasFixtures.php @@ -6,7 +6,7 @@ /** * @phpstan-type NumberPredicate callable(positive-int): bool - * @phpstan-type StringIterable iterable + * @phpstan-type StringSequence iterable */ class Priority3CallableAliasHolder { @@ -19,7 +19,19 @@ public function filterNumber(mixed $predicate, int $val): bool } /** - * @param StringIterable $items + * @param ?NumberPredicate $predicate + */ + public function filterOptionalNumber(mixed $predicate, int $val): bool + { + if ($predicate === null) { + return true; + } + + return $predicate($val); + } + + /** + * @param StringSequence $items * * @return list */ @@ -32,4 +44,17 @@ public function consumeStrings(mixed $items): array return $out; } + + /** + * @param StringSequence $items + */ + public function countStrings(mixed $items): int + { + $count = 0; + foreach ($items as $_) { + $count++; + } + + return $count; + } } diff --git a/tests/Fixtures/Priority3/MultiNamespaceFixtures.php b/tests/Fixtures/Priority3/MultiNamespaceFixtures.php index 25cdb63f..5d78622e 100644 --- a/tests/Fixtures/Priority3/MultiNamespaceFixtures.php +++ b/tests/Fixtures/Priority3/MultiNamespaceFixtures.php @@ -3,6 +3,8 @@ declare(strict_types=1); namespace TypePHP\Tests\Fixtures\Priority3\SubA { + use TypePHP\Tests\Fixtures\Domain\Cat; + use TypePHP\Tests\Fixtures\Domain\Dog; use TypePHP\Tests\Fixtures\Domain\Dog as TargetPet; class MultiNsCallerA @@ -12,12 +14,41 @@ class MultiNsCallerA */ public function getPet(): object { - return new TargetPet(); + return new Dog(); + } + + /** + * @return TargetPet + */ + public function getWrongPet(): object + { + return new Cat(); + } + + /** + * @param TargetPet $pet + * + * @return Dog + */ + public function passthroughDog(object $pet): object + { + return $pet; + } + + /** + * @param TargetPet $pet + * + * @return Cat + */ + public function unsoundPassthrough(object $pet): object + { + return $pet; } } } namespace TypePHP\Tests\Fixtures\Priority3\SubB { + use TypePHP\Tests\Fixtures\Domain\Cat; use TypePHP\Tests\Fixtures\Domain\Cat as TargetPet; class MultiNsCallerB @@ -27,7 +58,7 @@ class MultiNsCallerB */ public function getPet(): object { - return new TargetPet(); + return new Cat(); } } } diff --git a/tests/TypeChecking/Boundaries/Priority1BugsTest.php b/tests/TypeChecking/Boundaries/Priority1BugsTest.php index 53fb20c4..4242d806 100644 --- a/tests/TypeChecking/Boundaries/Priority1BugsTest.php +++ b/tests/TypeChecking/Boundaries/Priority1BugsTest.php @@ -188,4 +188,4 @@ public function echoPositive(int $id) expect(Priority1StaticByRefHolder::$token)->toBe('updated'); }); }); -}); \ No newline at end of file +}); diff --git a/tests/TypeChecking/Boundaries/Priority2BugsTest.php b/tests/TypeChecking/Boundaries/Priority2BugsTest.php index 80bedb61..1810536b 100644 --- a/tests/TypeChecking/Boundaries/Priority2BugsTest.php +++ b/tests/TypeChecking/Boundaries/Priority2BugsTest.php @@ -32,7 +32,9 @@ class Priority2InnerBoxFixture /** * @param T $value */ - public function __construct(public mixed $value) {} + public function __construct(public mixed $value) + { + } } /** @@ -209,7 +211,7 @@ class PrinterInvalidFixture require $validFile; expect(\App\Priority2\Printer\PrinterValidFixture::run())->toBe('#112233|https://a.test/x y') - ->and(fn() => require $invalidFile)->toThrow(TypeError::class) + ->and(fn () => require $invalidFile)->toThrow(TypeError::class) ; } finally { @unlink($validFile); @@ -309,8 +311,8 @@ class SelfConstInvalidFixture try { StreamWrapper::register(); - expect(fn() => require $validFile)->not()->toThrow(TypeError::class) - ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'BASE_CODE') + expect(fn () => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn () => require $invalidFile)->toThrow(TypeError::class, 'BASE_CODE') ; } finally { @unlink($validFile); @@ -372,8 +374,8 @@ class SelfPrivateInvalidFixture try { StreamWrapper::register(); - expect(fn() => require $validFile)->not()->toThrow(TypeError::class) - ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'PRIVATE_BASE') + expect(fn () => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn () => require $invalidFile)->toThrow(TypeError::class, 'PRIVATE_BASE') ; } finally { @unlink($validFile); @@ -467,8 +469,8 @@ class ParentConstChildInvalidFixture extends ParentConstInvalidBaseFixture try { StreamWrapper::register(); - expect(fn() => require $validFile)->not()->toThrow(TypeError::class) - ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'PROTECTED_LIMIT') + expect(fn () => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn () => require $invalidFile)->toThrow(TypeError::class, 'PROTECTED_LIMIT') ; } finally { @unlink($validFile); @@ -554,9 +556,9 @@ class AliasPrivateConstInvalidFixture try { StreamWrapper::register(); - expect(fn() => require $validFile)->not()->toThrow(TypeError::class) - ->and(fn() => require $invalidFile)->toThrow(TypeError::class, 'positive-int') - ->and(fn() => require $invalidPrivateFile)->toThrow(TypeError::class, 'non-empty-string') + expect(fn () => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn () => require $invalidFile)->toThrow(TypeError::class, 'positive-int') + ->and(fn () => require $invalidPrivateFile)->toThrow(TypeError::class, 'non-empty-string') ; } finally { @unlink($validFile); @@ -663,9 +665,9 @@ class ImportedAliasMaskInvalidFixture try { StreamWrapper::register(); - expect(fn() => require $validFile)->not()->toThrow(TypeError::class) - ->and(fn() => require $invalidFile)->toThrow(TypeError::class, '<= 65535') - ->and(fn() => require $invalidMaskFile)->toThrow(TypeError::class, 'bitmask') + expect(fn () => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn () => require $invalidFile)->toThrow(TypeError::class, '<= 65535') + ->and(fn () => require $invalidMaskFile)->toThrow(TypeError::class, 'bitmask') ; } finally { @unlink($validFile); @@ -738,8 +740,8 @@ class InheritedAliasChildInvalidFixture extends InheritedAliasParentInvalidFixtu try { StreamWrapper::register(); - expect(fn() => require $validFile)->not()->toThrow(TypeError::class) - ->and(fn() => require $invalidFile)->toThrow(TypeError::class, '<= 5') + expect(fn () => require $validFile)->not()->toThrow(TypeError::class) + ->and(fn () => require $invalidFile)->toThrow(TypeError::class, '<= 5') ; } finally { @unlink($validFile); diff --git a/tests/TypeChecking/Boundaries/Priority3BugsTest.php b/tests/TypeChecking/Boundaries/Priority3BugsTest.php new file mode 100644 index 00000000..04750b2b --- /dev/null +++ b/tests/TypeChecking/Boundaries/Priority3BugsTest.php @@ -0,0 +1,203 @@ +not()->toBeFalse(); + + $source = file_get_contents((string) $fixturePath); + expect($source)->not()->toBeFalse(); + + $transformed = StreamWrapper::transformSource((string) $source, (string) $fixturePath); + + [$subAPart, $subBPart] = explode('namespace TypePHP\Tests\Fixtures\Priority3\SubB', $transformed, 2); + [$subAGetPet, $subARest] = explode('function getWrongPet', $subAPart, 2); + [$subAGetWrongPet, $subAPassthroughRest] = explode('function passthroughDog', $subARest, 2); + [$subAPassthroughDog, $subAUnsoundPassthrough] = explode('function unsoundPassthrough', $subAPassthroughRest, 2); + + expect($subAGetPet)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($subAGetWrongPet)->toContain('RuntimeTypeChecker::checkReturn') + ->and($subAPassthroughDog)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($subAUnsoundPassthrough)->toContain('RuntimeTypeChecker::checkReturn') + ->and($subBPart)->not()->toContain('RuntimeTypeChecker::checkReturn') + ; + + $callerA = new MultiNsCallerA(); + $callerB = new MultiNsCallerB(); + + expect($callerA->getPet())->toBeInstanceOf(Dog::class) + ->and($callerA->passthroughDog(new Dog()))->toBeInstanceOf(Dog::class) + ->and($callerB->getPet())->toBeInstanceOf(Cat::class) + ->and(fn () => $callerA->getWrongPet())->toThrow(TypeError::class, 'Dog') + ->and(fn () => $callerA->unsoundPassthrough(new Dog()))->toThrow(TypeError::class, 'Cat') + ; + }); + }); + + describe('Bug 7: Aliased Callables/Iterables & Concrete ArrayAccess Subclasses', function () { + test('injects wrapCallable when parameter uses @phpstan-type alias for a callable', function () { + $fixturePath = realpath(__DIR__ . '/../../Fixtures/Priority3/CallableAliasFixtures.php'); + $source = file_get_contents((string) $fixturePath); + $transformed = StreamWrapper::transformSource((string) $source, (string) $fixturePath); + + expect($transformed)->toContain('RuntimeTypeChecker::wrapCallable'); + + $holder = new Priority3CallableAliasHolder(); + $badCb = fn (int $n): string => 'not_a_bool'; + + expect(fn () => $holder->filterNumber($badCb, 10)) + ->toThrow(TypeError::class, 'Callback $predicate return value must be of type bool') + ; + }); + + test('injects wrapCallable and validates argument constraint through @phpstan-type alias', function () { + $holder = new Priority3CallableAliasHolder(); + $cb = fn (int $n): bool => true; + + expect(fn () => $holder->filterNumber($cb, -5)) + ->toThrow(TypeError::class, 'positive-int') + ->and($holder->filterOptionalNumber(null, -5))->toBeTrue() + ->and(fn () => $holder->filterOptionalNumber($cb, -5)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('injects wrapIterable when parameter uses @phpstan-type alias for an iterable', function () { + $fixturePath = realpath(__DIR__ . '/../../Fixtures/Priority3/CallableAliasFixtures.php'); + $source = file_get_contents((string) $fixturePath); + $transformed = StreamWrapper::transformSource((string) $source, (string) $fixturePath); + + expect($transformed)->toContain('RuntimeTypeChecker::wrapIterable'); + + $holder = new Priority3CallableAliasHolder(); + $badIterator = new ArrayIterator([10, -50]); + + expect(fn () => $holder->countStrings($badIterator)) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + + test('validates member dimension assignment on concrete and partially-generic ArrayAccess subclasses', function () { + $holder = new Priority3ArrayAccessHolder(); + + $holder->map['b'] = 20; + expect($holder->map['b'])->toBe(20); + + expect(fn () => $holder->map['b'] = 'not_an_int') + ->toThrow(TypeError::class, 'must be of type int') + ->and(fn () => $holder->map[123] = 20) + ->toThrow(TypeError::class, 'must be of type string') + ; + + $holder->genericMap['b'] = 30; + expect($holder->genericMap['b'])->toBe(30); + + expect(fn () => $holder->genericMap['b'] = 'not_an_int') + ->toThrow(TypeError::class, 'must be of type int') + ->and(fn () => $holder->genericMap[123] = 30) + ->toThrow(TypeError::class, 'must be of type string') + ; + + $holder->mutateLocalMap('ok', 40); + + expect(fn () => $holder->mutateLocalMap('ok', 'bad')) + ->toThrow(TypeError::class, 'must be of type int') + ->and(fn () => $holder->mutateLocalMap(123, 40)) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + }); + + describe('Bug 8: Fast-Path Return Opcode Compilation for 2-Member Nullable Unions (T|null)', function () { + test('compiles fast opcode without falling back to full registry dispatch for 2-member nullable unions', function () { + $ref = new ReflectionMethod(RuntimeTypeChecker::class, 'compileSimpleReturnOp'); + + $cases = [ + new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('null')]), + new UnionTypeNode([new IdentifierTypeNode('null'), new IdentifierTypeNode('int')]), + new UnionTypeNode([new IdentifierTypeNode('string'), new IdentifierTypeNode('null')]), + new UnionTypeNode([new IdentifierTypeNode('null'), new IdentifierTypeNode('string')]), + new UnionTypeNode([new IdentifierTypeNode('bool'), new IdentifierTypeNode('null')]), + new UnionTypeNode([new IdentifierTypeNode('float'), new IdentifierTypeNode('null')]), + new UnionTypeNode([new IdentifierTypeNode('array'), new IdentifierTypeNode('null')]), + new UnionTypeNode([new IdentifierTypeNode('positive-int'), new IdentifierTypeNode('null')]), + new UnionTypeNode([new IdentifierTypeNode(stdClass::class), new IdentifierTypeNode('null')]), + ]; + + foreach ($cases as $unionNode) { + $res = $ref->invoke(null, $unionNode); + expect($res[0])->not()->toBe(0); + } + + $nonNullableUnion = new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('string')]); + $fallbackRes = $ref->invoke(null, $nonNullableUnion); + expect($fallbackRes[0])->toBe(0); + }); + + test('validates valid, null, and invalid return values cleanly via compiled T|null return plans', function () { + $fixture = new Priority3NullableReturnFixture(); + + expect($fixture->getNullableInt(42))->toBe(42) + ->and($fixture->getNullableInt(99))->toBe(99) + ->and($fixture->getNullableInt(null))->toBeNull() + ->and($fixture->getNullableString('hello'))->toBe('hello') + ->and($fixture->getNullableString('world'))->toBe('world') + ->and($fixture->getNullableString(null))->toBeNull() + ->and(fn () => $fixture->getNullableInt('bad'))->toThrow(TypeError::class, 'must be of type (int | null)') + ->and(fn () => $fixture->getNullableString(123))->toThrow(TypeError::class, 'must be of type (string | null)') + ; + }); + }); +}); From 51fc30c2301a2dea6feb3df7412e8bbb640dac87 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 13:30:10 +0800 Subject: [PATCH 5/9] Enhance type handling and validation for ArrayAccess and callable types --- src/Internal/Ast/ContractVisitor.php | 157 +++++++- .../Evaluator/ArrayLiteralEvaluator.php | 45 ++- .../Evaluator/ConstantAndEnumEvaluator.php | 64 ++-- .../Evaluator/GeneratorEvaluator.php | 19 +- .../Elimination/Evaluator/ObjectEvaluator.php | 16 +- .../Ast/Elimination/StaticTypeEvaluator.php | 24 +- src/Internal/Ast/FunctionContractInjector.php | 346 +++++++++++++++--- src/Internal/Checker/InlineChecker.php | 23 ++ src/Internal/Checker/MemberAssignChecker.php | 240 +++++++++++- src/Internal/RuntimeTypeChecker.php | 43 +++ src/Internal/Wrapper/CallableWrapper.php | 48 ++- src/Internal/Wrapper/IterableWrapper.php | 20 + 12 files changed, 919 insertions(+), 126 deletions(-) diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 2722f143..50851fee 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -10,6 +10,9 @@ use PhpParser\NodeVisitorAbstract; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; @@ -96,12 +99,17 @@ final class ContractVisitor extends NodeVisitorAbstract */ private array $localClassPropertyTypes = []; + /** + * @var array> + */ + private array $localClassAliases = []; + private ScopeManager $scopeManager; private string $currentNamespace = ''; /** - * @var list + * @var list, templates?: array}> */ private array $classStack = []; @@ -232,7 +240,7 @@ public function enterNode(Node $node): Node|array|null if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) { $classContext = $this->classStack !== [] ? end($this->classStack) : null; - FunctionContractInjector::inject($node, $classContext, $this->currentFile); + FunctionContractInjector::inject($node, $classContext, $this->currentFile, $this->currentNamespace); return null; } @@ -435,7 +443,7 @@ private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, stri continue; } - if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile, [], $this->currentNamespace)) { continue; } @@ -503,7 +511,7 @@ private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): ar continue; } - if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile, [], $this->currentNamespace)) { continue; } @@ -587,13 +595,15 @@ private function instrumentConstantClosure( $caller, $returnTypeNode, $returnTypeStr, - $this->currentFile + $this->currentFile, + $this->currentNamespace ) extends NodeVisitorAbstract { public function __construct( private string $caller, private TypeNode $returnTypeNode, private string $returnTypeStr, - private string $currentFile + private string $currentFile, + private string $currentNamespace ) { } @@ -614,7 +624,7 @@ public function enterNode(Node $n): int|Node|null if ( Config::isEliminateStaticallyProvenChecksEnabled() - && StaticTypeEvaluator::satisfies($exprToWrap, $this->returnTypeNode, $this->currentFile) + && StaticTypeEvaluator::satisfies($exprToWrap, $this->returnTypeNode, $this->currentFile, [], $this->currentNamespace) ) { return null; } @@ -823,7 +833,7 @@ private function processClassPropertyDefaults(Node\Stmt\Class_ $node): void foreach ($stmt->props as $p) { $isExplicitNull = $p->default instanceof Node\Expr\ConstFetch && strtolower($p->default->name->toString()) === 'null'; if ($p->default !== null && ! $isExplicitNull) { - if ($propTypeNode !== null && StaticTypeEvaluator::satisfies($p->default, $propTypeNode, $this->currentFile)) { + if ($propTypeNode !== null && StaticTypeEvaluator::satisfies($p->default, $propTypeNode, $this->currentFile, [], $this->currentNamespace)) { continue; } @@ -889,7 +899,7 @@ private function processClassPropertyDefaults(Node\Stmt\Class_ $node): void } /** - * @return array + * @return array */ private function resolveClassTemplatesForDefaults(Node\Stmt\Class_ $node): array { @@ -1107,6 +1117,8 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } + $classAliases = $this->extractClassLikeAliases($node, $doc, $typeName); + $this->classStack[] = [ 'name' => $typeName, 'isAnonymous' => ($node instanceof Node\Stmt\Class_ && $node->name === null), @@ -1117,9 +1129,134 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ 'isFinal' => $isFinal, 'hasTemplates' => $hasTemplates, 'isTrait' => $isTrait, + 'aliases' => $classAliases, + 'templates' => $templates, ]; } + /** + * Extracts class-level and inherited @phpstan-type / @psalm-type / @phpstan-import-type aliases at AST transform time. + * + * @return array + */ + private function extractClassLikeAliases( + Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\Trait_|Node\Stmt\Enum_ $node, + ?\PhpParser\Comment\Doc $doc, + ?string $typeName + ): array { + /** @var array $aliases */ + $aliases = []; + + if ($doc !== null && (str_contains($doc->getText(), '-type') || str_contains($doc->getText(), 'import-type'))) { + try { + $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); + + foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } + } + + foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } + } + + $importTags = [ + ...$phpDocNode->getTagsByName('@psalm-import-type'), + ...$phpDocNode->getTagsByName('@phpstan-import-type'), + ]; + + foreach ($importTags as $tag) { + if ($tag->value instanceof TypeAliasImportTagValueNode) { + $importTag = $tag->value; + $localName = $importTag->importedAs ?? $importTag->importedAlias; + if (isset($aliases[$localName])) { + continue; + } + + $sourceFqcn = $this->resolveClassNameFromNode(new Node\Name((string) $importTag->importedFrom)) + ?? (string) $importTag->importedFrom; + + $imported = $this->localClassAliases[$sourceFqcn][$importTag->importedAlias] ?? null; + if ( + $imported === null + && ClassNameValidator::isValid($sourceFqcn) + && (class_exists($sourceFqcn) || interface_exists($sourceFqcn) || trait_exists($sourceFqcn) || enum_exists($sourceFqcn)) + ) { + $imported = DocblockExtractor::resolveImportedTypeAlias($sourceFqcn, $importTag->importedAlias); + } + + if ($imported !== null) { + $aliases[$localName] = $imported; + } + } + } + } catch (\Throwable) { + } + } + + /** @var list $parentNodes */ + $parentNodes = []; + if ($node instanceof Node\Stmt\Class_) { + if ($node->extends !== null) { + $parentNodes[] = $node->extends; + } + foreach ($node->implements as $iface) { + $parentNodes[] = $iface; + } + } elseif ($node instanceof Node\Stmt\Interface_) { + foreach ($node->extends as $iface) { + $parentNodes[] = $iface; + } + } elseif ($node instanceof Node\Stmt\Enum_) { + foreach ($node->implements as $iface) { + $parentNodes[] = $iface; + } + } + + if ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_ || $node instanceof Node\Stmt\Enum_) { + foreach ($node->stmts as $stmt) { + if ($stmt instanceof Node\Stmt\TraitUse) { + foreach ($stmt->traits as $traitName) { + $parentNodes[] = $traitName; + } + } + } + } + + foreach ($parentNodes as $parentNode) { + $parentFqcn = $this->resolveClassNameFromNode($parentNode) ?? $parentNode->toString(); + $parentAliases = $this->localClassAliases[$parentFqcn] ?? null; + if ( + $parentAliases === null + && ClassNameValidator::isValid($parentFqcn) + && (class_exists($parentFqcn) || interface_exists($parentFqcn) || trait_exists($parentFqcn)) + ) { + $parentAliases = DocblockParser::parseClassAliases($parentFqcn); + } + + if ($parentAliases !== null) { + foreach ($parentAliases as $aName => $aType) { + if (! isset($aliases[$aName])) { + $aliases[$aName] = $aType; + } + } + } + } + + foreach ($aliases as $aName => $aType) { + $aliases[$aName] = DocblockParser::substituteAliases($aType, $aliases); + } + + if ($typeName !== null && $aliases !== []) { + $this->localClassAliases[$typeName] = $aliases; + } + + return $aliases; + } + private function handleReturn(Node\Stmt\Return_ $node): void { if ($node->expr === null) { @@ -1336,7 +1473,7 @@ private function handleAssign(Node\Expr\Assign $node): ?Node } } - if ($parsedType !== null && StaticTypeEvaluator::satisfies($expr, $parsedType, $this->currentFile)) { + if ($parsedType !== null && StaticTypeEvaluator::satisfies($expr, $parsedType, $this->currentFile, [], $this->currentNamespace)) { return null; } diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index 2fa76b92..5a443c26 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -58,7 +58,8 @@ public static function satisfies( Array_ $arrayExpr, TypeNode $typeNode, string $currentFile = '', - array $trustedVariableTypes = [] + array $trustedVariableTypes = [], + ?string $currentNamespace = null ): bool { $count = \count($arrayExpr->items); @@ -71,15 +72,15 @@ public static function satisfies( } if ($typeNode instanceof ArrayTypeNode) { - return self::satisfiesList($arrayExpr, $typeNode->type, false, $currentFile, $trustedVariableTypes); + return self::satisfiesList($arrayExpr, $typeNode->type, false, $currentFile, $trustedVariableTypes, $currentNamespace); } if ($typeNode instanceof GenericTypeNode) { - return self::satisfiesGenericArray($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes); + return self::satisfiesGenericArray($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes, $currentNamespace); } if ($typeNode instanceof ArrayShapeNode) { - return self::satisfiesArrayShape($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes); + return self::satisfiesArrayShape($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes, $currentNamespace); } return false; @@ -138,33 +139,34 @@ private static function satisfiesGenericArray( Array_ $arrayExpr, GenericTypeNode $node, string $currentFile, - array $trustedVariableTypes = [] + array $trustedVariableTypes = [], + ?string $currentNamespace = null ): bool { $base = strtolower((string) $node->type); $genericCount = \count($node->genericTypes); if ($base === 'list' && $genericCount >= 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes, $currentNamespace); } if ($base === 'non-empty-list' && $genericCount >= 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes, $currentNamespace); } if (($base === 'array' || $base === 'iterable') && $genericCount === 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes, $currentNamespace); } if (($base === 'array' || $base === 'iterable') && $genericCount >= 2) { - return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], false, $currentFile, $trustedVariableTypes); + return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], false, $currentFile, $trustedVariableTypes, $currentNamespace); } if ($base === 'non-empty-array' && $genericCount === 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes, $currentNamespace); } if ($base === 'non-empty-array' && $genericCount >= 2) { - return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], true, $currentFile, $trustedVariableTypes); + return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], true, $currentFile, $trustedVariableTypes, $currentNamespace); } return false; @@ -178,7 +180,8 @@ private static function satisfiesList( TypeNode $itemType, bool $requireNonEmpty, string $currentFile, - array $trustedVariableTypes = [] + array $trustedVariableTypes = [], + ?string $currentNamespace = null ): bool { $count = \count($arrayExpr->items); if ($requireNonEmpty && $count === 0) { @@ -198,7 +201,7 @@ private static function satisfiesList( } $expectedIdx++; - if (! StaticTypeEvaluator::satisfies($item->value, $itemType, $currentFile, $trustedVariableTypes)) { + if (! StaticTypeEvaluator::satisfies($item->value, $itemType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } } @@ -215,7 +218,8 @@ private static function satisfiesKeyValueArray( TypeNode $valueType, bool $requireNonEmpty, string $currentFile, - array $trustedVariableTypes = [] + array $trustedVariableTypes = [], + ?string $currentNamespace = null ): bool { $count = \count($arrayExpr->items); if ($requireNonEmpty && $count === 0) { @@ -240,11 +244,11 @@ private static function satisfiesKeyValueArray( return false; } - if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile, $trustedVariableTypes)) { + if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } - if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile, $trustedVariableTypes)) { + if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } } @@ -259,7 +263,8 @@ private static function satisfiesArrayShape( Array_ $arrayExpr, ArrayShapeNode $shapeNode, string $currentFile, - array $trustedVariableTypes = [] + array $trustedVariableTypes = [], + ?string $currentNamespace = null ): bool { if ($shapeNode->kind === ArrayShapeNode::KIND_LIST && ! self::isSequentialList($arrayExpr)) { return false; @@ -314,7 +319,7 @@ private static function satisfiesArrayShape( continue; } - if (! StaticTypeEvaluator::satisfies($actualItems[$expectedKey], $shapeItem->valueType, $currentFile, $trustedVariableTypes)) { + if (! StaticTypeEvaluator::satisfies($actualItems[$expectedKey], $shapeItem->valueType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } } @@ -331,12 +336,12 @@ private static function satisfiesArrayShape( if ($shapeNode->unsealedType !== null) { if ($shapeNode->unsealedType->keyType !== null) { $keyExpr = \is_int($actualKey) ? new LNumber($actualKey) : new String_($actualKey); - if (! StaticTypeEvaluator::satisfies($keyExpr, $shapeNode->unsealedType->keyType, $currentFile, $trustedVariableTypes)) { + if (! StaticTypeEvaluator::satisfies($keyExpr, $shapeNode->unsealedType->keyType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } } - if (! StaticTypeEvaluator::satisfies($actualValueExpr, $shapeNode->unsealedType->valueType, $currentFile, $trustedVariableTypes)) { + if (! StaticTypeEvaluator::satisfies($actualValueExpr, $shapeNode->unsealedType->valueType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } } diff --git a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php index aec70c52..c0aa4b88 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php @@ -47,18 +47,22 @@ final class ConstantAndEnumEvaluator * 2. Evaluates bitwise OR expressions (A | B) against `int-mask-of` wildcards. * 3. Evaluates backed enum property reads (Enum::Case->value) against `value-of`. */ - public static function satisfies(Expr $expr, TypeNode $typeNode, string $currentFile = ''): bool - { + public static function satisfies( + Expr $expr, + TypeNode $typeNode, + string $currentFile = '', + ?string $currentNamespace = null + ): bool { if ($expr instanceof ClassConstFetch) { - return self::satisfiesClassConst($expr, $typeNode, $currentFile); + return self::satisfiesClassConst($expr, $typeNode, $currentFile, $currentNamespace); } if ($expr instanceof BitwiseOr) { - return self::satisfiesBitwiseOr($expr, $typeNode, $currentFile); + return self::satisfiesBitwiseOr($expr, $typeNode, $currentFile, $currentNamespace); } if ($expr instanceof PropertyFetch) { - return self::satisfiesEnumBackingValue($expr, $typeNode, $currentFile); + return self::satisfiesEnumBackingValue($expr, $typeNode, $currentFile, $currentNamespace); } return false; @@ -67,8 +71,12 @@ public static function satisfies(Expr $expr, TypeNode $typeNode, string $current /** * Evaluates a class constant fetch against ConstTypeNode, IdentifierTypeNode, or int-mask-of. */ - private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $typeNode, string $currentFile): bool - { + private static function satisfiesClassConst( + ClassConstFetch $fetch, + TypeNode $typeNode, + string $currentFile, + ?string $currentNamespace = null + ): bool { if (! ($fetch->class instanceof Name) || ! ($fetch->name instanceof Identifier)) { return false; } @@ -81,7 +89,7 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty $targetClassName = $fetch->class->toString(); if ($typeNode instanceof ConstTypeNode && $typeNode->constExpr instanceof ConstFetchNode) { - if (! self::classesMatch($targetClassName, $typeNode->constExpr->className, $currentFile)) { + if (! self::classesMatch($targetClassName, $typeNode->constExpr->className, $currentFile, $currentNamespace)) { return false; } @@ -95,11 +103,11 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty } if ($typeNode instanceof IdentifierTypeNode) { - if (! self::classesMatch($targetClassName, $typeNode->name, $currentFile)) { + if (! self::classesMatch($targetClassName, $typeNode->name, $currentFile, $currentNamespace)) { return false; } - $resolvedEnum = self::resolveClassForReflection($targetClassName, $currentFile); + $resolvedEnum = self::resolveClassForReflection($targetClassName, $currentFile, $currentNamespace); if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false)) { return false; } @@ -110,7 +118,7 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty 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)) { + if (! self::classesMatch($targetClassName, $inner->constExpr->className, $currentFile, $currentNamespace)) { return false; } @@ -129,21 +137,29 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty /** * Recursively verifies that both operands of a bitwise OR expression satisfy an `int-mask-of` wildcard. */ - private static function satisfiesBitwiseOr(BitwiseOr $expr, TypeNode $typeNode, string $currentFile): bool - { + private static function satisfiesBitwiseOr( + BitwiseOr $expr, + TypeNode $typeNode, + string $currentFile, + ?string $currentNamespace = null + ): bool { if (! ($typeNode instanceof GenericTypeNode) || strtolower((string) $typeNode->type) !== 'int-mask-of') { return false; } - return self::satisfies($expr->left, $typeNode, $currentFile) - && self::satisfies($expr->right, $typeNode, $currentFile); + return self::satisfies($expr->left, $typeNode, $currentFile, $currentNamespace) + && self::satisfies($expr->right, $typeNode, $currentFile, $currentNamespace); } /** * Verifies whether a BackedEnum::Case->value property access satisfies `value-of`. */ - private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode $typeNode, string $currentFile): bool - { + private static function satisfiesEnumBackingValue( + PropertyFetch $fetch, + TypeNode $typeNode, + string $currentFile, + ?string $currentNamespace = null + ): bool { if (! ($fetch->name instanceof Identifier) || $fetch->name->name !== 'value') { return false; } @@ -168,11 +184,11 @@ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode return false; } - if (! self::classesMatch($enumClassName, $enumTarget->name, $currentFile)) { + if (! self::classesMatch($enumClassName, $enumTarget->name, $currentFile, $currentNamespace)) { return false; } - $resolvedEnum = self::resolveClassForReflection($enumClassName, $currentFile); + $resolvedEnum = self::resolveClassForReflection($enumClassName, $currentFile, $currentNamespace); if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false) || ! is_subclass_of($resolvedEnum, BackedEnum::class)) { return false; } @@ -183,7 +199,7 @@ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode /** * Verifies whether two class references deterministically denote the same class/enum. */ - private static function classesMatch(string $fetchClass, string $docClass, string $currentFile): bool + private static function classesMatch(string $fetchClass, string $docClass, string $currentFile, ?string $currentNamespace = null): bool { if ($docClass === '') { return false; @@ -205,8 +221,8 @@ private static function classesMatch(string $fetchClass, string $docClass, strin } if ($currentFile !== '') { - $resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($fetchClass, $currentFile, false); - $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($docClass, $currentFile, false); + $resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($fetchClass, $currentFile, false, $currentNamespace); + $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($docClass, $currentFile, false, $currentNamespace); return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass; } @@ -217,10 +233,10 @@ private static function classesMatch(string $fetchClass, string $docClass, strin /** * Resolves a class name without invoking autoloading. */ - private static function resolveClassForReflection(string $rawClass, string $currentFile): string + private static function resolveClassForReflection(string $rawClass, string $currentFile, ?string $currentNamespace = null): string { if ($currentFile !== '') { - return SpecialTypeResolver::resolveFqcnForFile($rawClass, $currentFile, false); + return SpecialTypeResolver::resolveFqcnForFile($rawClass, $currentFile, false, $currentNamespace); } return ltrim($rawClass, '\\'); diff --git a/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php index 097e0bc9..9f023612 100644 --- a/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php @@ -125,7 +125,8 @@ public static function canEliminateYield( ?TypeNode $keyType, ?TypeNode $valueType, string $currentFile = '', - ?Expr $precedingValueExpr = null + ?Expr $precedingValueExpr = null, + ?string $currentNamespace = null ): bool { if (! Config::isEliminateStaticallyProvenChecksEnabled()) { return false; @@ -133,14 +134,14 @@ public static function canEliminateYield( if ($keyType !== null && ! self::isMixedType($keyType)) { $keyExpr = $yieldNode->key ?? new LNumber(0); - if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile, [], $currentNamespace)) { return false; } } if ($valueType !== null && ! self::isMixedType($valueType)) { $valExpr = $precedingValueExpr ?? $yieldNode->value ?? new ConstFetch(new Name('null')); - if (! StaticTypeEvaluator::satisfies($valExpr, $valueType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($valExpr, $valueType, $currentFile, [], $currentNamespace)) { return false; } } @@ -168,7 +169,8 @@ public static function canEliminateYieldFrom( YieldFrom $yieldFromNode, ?TypeNode $keyType, ?TypeNode $valueType, - string $currentFile = '' + string $currentFile = '', + ?string $currentNamespace = null ): bool { if (! Config::isEliminateStaticallyProvenChecksEnabled()) { return false; @@ -186,13 +188,13 @@ public static function canEliminateYieldFrom( /** @var TypeNode $valueType */ $targetType = new GenericTypeNode(new IdentifierTypeNode('iterable'), [$valueType]); - return ArrayLiteralEvaluator::satisfies($yieldFromNode->expr, $targetType, $currentFile); + return ArrayLiteralEvaluator::satisfies($yieldFromNode->expr, $targetType, $currentFile, [], $currentNamespace); } $effectiveValueType = $valueType ?? new IdentifierTypeNode('mixed'); $targetType = new GenericTypeNode(new IdentifierTypeNode('iterable'), [$keyType, $effectiveValueType]); - return ArrayLiteralEvaluator::satisfies($yieldFromNode->expr, $targetType, $currentFile); + return ArrayLiteralEvaluator::satisfies($yieldFromNode->expr, $targetType, $currentFile, [], $currentNamespace); } /** @@ -204,7 +206,8 @@ public static function canEliminateGeneratorReturn( ?Expr $returnExpr, ?TypeNode $returnType, string $currentFile = '', - array $trustedVariableTypes = [] + array $trustedVariableTypes = [], + ?string $currentNamespace = null ): bool { if (! Config::isEliminateStaticallyProvenChecksEnabled()) { return false; @@ -216,7 +219,7 @@ public static function canEliminateGeneratorReturn( $effectiveExpr = $returnExpr ?? new ConstFetch(new Name('null')); - return StaticTypeEvaluator::satisfies($effectiveExpr, $returnType, $currentFile, $trustedVariableTypes); + return StaticTypeEvaluator::satisfies($effectiveExpr, $returnType, $currentFile, $trustedVariableTypes, $currentNamespace); } /** diff --git a/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php index f04e3ff6..ef7fa80e 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php @@ -53,8 +53,12 @@ final class ObjectEvaluator * 4. Evaluates `new self()` against `self`. * 5. Evaluates `new ClassName()` against `ClassName` using static FQCN equality (zero reflection, zero autoloading). */ - public static function satisfies(Expr $expr, TypeNode $typeNode, string $currentFile = ''): bool - { + public static function satisfies( + Expr $expr, + TypeNode $typeNode, + string $currentFile = '', + ?string $currentNamespace = null + ): bool { if ($typeNode instanceof GenericTypeNode) { return false; } @@ -64,7 +68,7 @@ public static function satisfies(Expr $expr, TypeNode $typeNode, string $current } if ($expr instanceof New_ && $expr->class instanceof Name) { - return self::satisfiesNew($expr->class, $typeNode, $currentFile); + return self::satisfiesNew($expr->class, $typeNode, $currentFile, $currentNamespace); } return false; @@ -89,7 +93,7 @@ private static function satisfiesThis(TypeNode $typeNode): bool /** * Evaluates `new ClassName(...)` against expected object type contracts. */ - private static function satisfiesNew(Name $classNameNode, TypeNode $typeNode, string $currentFile): bool + private static function satisfiesNew(Name $classNameNode, TypeNode $typeNode, string $currentFile, ?string $currentNamespace = null): bool { if (! ($typeNode instanceof IdentifierTypeNode)) { return false; @@ -120,8 +124,8 @@ private static function satisfiesNew(Name $classNameNode, TypeNode $typeNode, st } if ($currentFile !== '') { - $resolvedNewClass = SpecialTypeResolver::resolveFqcnForFile($rawNewClass, $currentFile, false); - $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false); + $resolvedNewClass = SpecialTypeResolver::resolveFqcnForFile($rawNewClass, $currentFile, false, $currentNamespace); + $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false, $currentNamespace); return $resolvedNewClass !== '' && $resolvedNewClass === $resolvedTypeClass; } diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index 3dbe1102..0e358d94 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -20,6 +20,7 @@ use TypePHP\Internal\Ast\Elimination\Evaluator\ObjectEvaluator; use TypePHP\Internal\Ast\Elimination\Evaluator\ScalarEvaluator; use TypePHP\Internal\Generics\TemplateManager; +use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\Config; /** @@ -56,7 +57,8 @@ public static function satisfies( Expr $expr, TypeNode $typeNode, string $currentFile = '', - array $trustedVariableTypes = [] + array $trustedVariableTypes = [], + ?string $currentNamespace = null ): bool { if (! Config::isEliminateStaticallyProvenChecksEnabled()) { return false; @@ -74,16 +76,20 @@ public static function satisfies( } if ($expr instanceof Variable && \is_string($expr->name) && isset($trustedVariableTypes[$expr->name])) { + $resolvedTarget = $currentFile !== '' + ? SpecialTypeResolver::resolveForFile($typeNode, $currentFile, $currentNamespace, false) + : $typeNode; + return TemplateManager::checkVariance( $trustedVariableTypes[$expr->name], - $typeNode, + $resolvedTarget, GenericTypeNode::VARIANCE_COVARIANT ); } if ($expr instanceof Ternary && $expr->if !== null) { - return self::satisfies($expr->if, $typeNode, $currentFile, $trustedVariableTypes) - && self::satisfies($expr->else, $typeNode, $currentFile, $trustedVariableTypes); + return self::satisfies($expr->if, $typeNode, $currentFile, $trustedVariableTypes, $currentNamespace) + && self::satisfies($expr->else, $typeNode, $currentFile, $trustedVariableTypes, $currentNamespace); } if ($typeNode instanceof NullableTypeNode) { @@ -91,12 +97,12 @@ public static function satisfies( return true; } - return self::satisfies($expr, $typeNode->type, $currentFile, $trustedVariableTypes); + return self::satisfies($expr, $typeNode->type, $currentFile, $trustedVariableTypes, $currentNamespace); } if ($typeNode instanceof UnionTypeNode) { foreach ($typeNode->types as $member) { - if (self::satisfies($expr, $member, $currentFile, $trustedVariableTypes)) { + if (self::satisfies($expr, $member, $currentFile, $trustedVariableTypes, $currentNamespace)) { return true; } } @@ -105,11 +111,11 @@ public static function satisfies( } if ($expr instanceof Array_) { - return ArrayLiteralEvaluator::satisfies($expr, $typeNode, $currentFile, $trustedVariableTypes); + return ArrayLiteralEvaluator::satisfies($expr, $typeNode, $currentFile, $trustedVariableTypes, $currentNamespace); } - return ConstantAndEnumEvaluator::satisfies($expr, $typeNode, $currentFile) - || ObjectEvaluator::satisfies($expr, $typeNode, $currentFile) + return ConstantAndEnumEvaluator::satisfies($expr, $typeNode, $currentFile, $currentNamespace) + || ObjectEvaluator::satisfies($expr, $typeNode, $currentFile, $currentNamespace) || ScalarEvaluator::satisfies($expr, $typeNode); } diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index a7dca979..0db3d99e 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -9,7 +9,16 @@ use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode; +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\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -20,6 +29,7 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StubManager; @@ -42,12 +52,13 @@ final class FunctionContractInjector ]; /** - * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool, aliases?: array, templates?: array}|null $classContext */ public static function inject( Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?array $classContext = null, - string $currentFile = '' + string $currentFile = '', + ?string $currentNamespace = null ): void { if ($node->stmts === null) { return; @@ -159,6 +170,26 @@ public static function inject( } } + $effectiveAliases = $classContext['aliases'] ?? []; + if ($phpDocNode !== null && (str_contains($docText, '-type') || str_contains($docText, 'import-type'))) { + $effectiveAliases = self::mergeDocblockAliases($phpDocNode, $effectiveAliases, $currentFile, $currentNamespace); + } + + /** @var array $effectiveTemplates */ + $effectiveTemplates = [...($classContext['templates'] ?? []), ...$declaredTemplates]; + + /** @var array $resolvedParamTypes */ + $resolvedParamTypes = []; + if ($phpDocNode !== null) { + foreach (DocblockExtractor::getParamTags($phpDocNode) as $pName => $pTag) { + $pType = $pTag->type; + if ($effectiveAliases !== []) { + $pType = DocblockParser::substituteAliases($pType, $effectiveAliases); + } + $resolvedParamTypes[$pName] = $pType; + } + } + $isTrait = $classContext['isTrait'] ?? false; if ( @@ -179,7 +210,9 @@ public static function inject( $isPrivate, $hasRealInheritance, $returnTypeNode, - $hasReturn + $hasReturn, + $resolvedParamTypes, + $effectiveTemplates ) ) { $hasParam = false; @@ -192,10 +225,19 @@ public static function inject( $injectedStmts = []; if ($hasParam) { - $injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass, $needsReturnVars, $useDynamicMethodKey); + $injectedStmts = self::buildParamInjections( + $node->params, + $docText, + $thisArg, + $isReadonlyClass, + $needsReturnVars, + $useDynamicMethodKey, + $resolvedParamTypes, + $effectiveTemplates + ); } - $trustedParamTypes = self::collectTrustedParamTypes($node, $doc, $declaredTemplates, $currentFile); + $trustedParamTypes = self::collectTrustedParamTypes($node, $doc, $declaredTemplates, $currentFile, $currentNamespace); if ($hasReturn || $hasParamOut || $hasSelfOut) { $node->stmts = self::isGenerator($node) @@ -212,7 +254,8 @@ public static function inject( $hasSelfOut, $hasParam, $trustedParamTypes, - $useDynamicMethodKey + $useDynamicMethodKey, + $currentNamespace ) : self::wrapNonGeneratorReturns( $node->stmts, @@ -229,13 +272,18 @@ public static function inject( $currentFile, $trustedParamTypes, $useDynamicMethodKey, - ! $isMagicGet && ! $isMagicCall + ! $isMagicGet && ! $isMagicCall, + $currentNamespace ); } $node->stmts = [...$injectedStmts, ...$node->stmts]; } + /** + * @param array $resolvedParamTypes + * @param array $effectiveTemplates + */ private static function canEliminateSetupScope( Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?PhpDocNode $phpDocNode, @@ -244,7 +292,9 @@ private static function canEliminateSetupScope( bool $isPrivate, bool $hasRealInheritance, ?TypeNode $returnTypeNode, - bool $hasReturn + bool $hasReturn, + array $resolvedParamTypes = [], + array $effectiveTemplates = [] ): bool { if (! Config::isEliminateStaticallyProvenChecksEnabled()) { return false; @@ -269,13 +319,17 @@ private static function canEliminateSetupScope( return false; } + $pName = $param->var->name; + $resolvedType = $resolvedParamTypes[$pName] ?? null; $paramDoc = $param->getDocComment() !== null ? $param->getDocComment()->getText() : ''; $effectiveDoc = $docText . ' ' . $paramDoc; - if (self::isCallableCandidate($param, $effectiveDoc) || self::isIterableCandidate($param, $effectiveDoc)) { + if ( + self::isCallableCandidate($param, $effectiveDoc, $resolvedType, $effectiveTemplates) + || self::isIterableCandidate($param, $effectiveDoc, $resolvedType, $effectiveTemplates) + ) { return false; } - $pName = $param->var->name; $paramTag = $paramTags[$pName] ?? null; if ($paramTag === null) { @@ -286,7 +340,7 @@ private static function canEliminateSetupScope( continue; } - if (! self::nativeParamSatisfiesDocType($param->type, $paramTag->type)) { + if (! self::nativeParamSatisfiesDocType($param->type, $resolvedType ?? $paramTag->type)) { return false; } } @@ -375,7 +429,7 @@ private static function nativeParamSatisfiesDocType( /** * Extracts concrete parameter contracts and verifies they are never mutated in the body. * - * @param array $declaredTemplates + * @param array $declaredTemplates * * @return array */ @@ -383,7 +437,8 @@ private static function collectTrustedParamTypes( Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?Doc $doc, array $declaredTemplates, - string $currentFile + string $currentFile, + ?string $currentNamespace = null ): array { if ($node->stmts === null || $node->stmts === [] || $node->params === []) { return []; @@ -452,7 +507,7 @@ private static function collectTrustedParamTypes( } if ($currentFile !== '') { - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile, null, false); + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile, $currentNamespace, false); } if ($declaredTemplates !== [] && DocblockParser::typeReferencesTemplate($typeNode, $declaredTemplates)) { @@ -903,6 +958,8 @@ public function enterNode(Node $n): ?int /** * @param array $params + * @param array $resolvedParamTypes + * @param array $effectiveTemplates * * @return array */ @@ -912,11 +969,13 @@ private static function buildParamInjections( Node\Expr $thisArg, bool $isReadonlyClass = false, bool $needsReturnVars = false, - bool $useDynamicMethodKey = false + bool $useDynamicMethodKey = false, + array $resolvedParamTypes = [], + array $effectiveTemplates = [] ): array { $setupScopeStmts = self::buildSetupScopeStmt($params, $thisArg, $needsReturnVars, $useDynamicMethodKey); - $callableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isCallableCandidate'], 'wrapCallable', $isReadonlyClass); - $iterableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isIterableCandidate'], 'wrapIterable', $isReadonlyClass); + $callableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isCallableCandidate'], 'wrapCallable', $isReadonlyClass, $resolvedParamTypes, $effectiveTemplates); + $iterableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isIterableCandidate'], 'wrapIterable', $isReadonlyClass, $resolvedParamTypes, $effectiveTemplates); return [...$setupScopeStmts, ...$callableWrappers, ...$iterableWrappers]; } @@ -1070,7 +1129,9 @@ public static function buildParamOutCheckStmts( /** * @param array $params - * @param callable(Node\Param, string): bool $predicate + * @param callable(Node\Param, string, ?TypeNode, array): bool $predicate + * @param array $resolvedParamTypes + * @param array $effectiveTemplates * * @return array */ @@ -1080,16 +1141,19 @@ private static function buildParamWrappers( Node\Expr $thisArg, callable $predicate, string $wrapperMethod, - bool $isReadonlyClass = false + bool $isReadonlyClass = false, + array $resolvedParamTypes = [], + array $effectiveTemplates = [] ): array { $wrappers = []; foreach ($params as $param) { + $paramName = $param->var instanceof Node\Expr\Variable && \is_string($param->var->name) ? $param->var->name : ''; + $resolvedType = $paramName !== '' ? ($resolvedParamTypes[$paramName] ?? null) : null; $paramDoc = $param->getDocComment() !== null ? $param->getDocComment()->getText() : ''; $effectiveDoc = $docText . ' ' . $paramDoc; - if ($predicate($param, $effectiveDoc) && $param->var instanceof Node\Expr\Variable && \is_string($param->var->name)) { - $paramName = $param->var->name; + if ($paramName !== '' && $predicate($param, $effectiveDoc, $resolvedType, $effectiveTemplates)) { $assignExpr = new Node\Expr\Assign( new Node\Expr\Variable($paramName), new Node\Expr\FuncCall( @@ -1202,34 +1266,219 @@ private static function paramMayBeArray(Node\Param $param): bool return false; } - private static function isCallableCandidate(Node\Param $param, string $docText): bool - { - if ( - str_contains($docText, 'callable') - || str_contains($docText, 'Closure') - || str_contains($docText, 'pure-callable') - || str_contains($docText, 'static-closure') - ) { + /** + * @param array $effectiveTemplates + */ + private static function isCallableCandidate( + Node\Param $param, + string $docText, + ?TypeNode $resolvedParamType = null, + array $effectiveTemplates = [] + ): bool { + if (self::typeMatchesName($param->type, self::CALLABLE_TYPES)) { return true; } - return self::typeMatchesName($param->type, self::CALLABLE_TYPES); + if ($resolvedParamType !== null) { + return self::typeNodeContainsCallable($resolvedParamType, $effectiveTemplates); + } + + return str_contains($docText, 'callable') + || str_contains($docText, 'Closure') + || str_contains($docText, 'pure-callable') + || str_contains($docText, 'static-closure'); } - private static function isIterableCandidate(Node\Param $param, string $docText): bool - { + /** + * @param array $effectiveTemplates + */ + private static function isIterableCandidate( + Node\Param $param, + string $docText, + ?TypeNode $resolvedParamType = null, + array $effectiveTemplates = [] + ): bool { if (self::typeMatchesName($param->type, self::ITERABLE_TYPES)) { return true; } + if ($resolvedParamType !== null) { + return self::typeNodeContainsIterable($resolvedParamType, $effectiveTemplates); + } + $paramName = $param->var instanceof Node\Expr\Variable && \is_string($param->var->name) ? $param->var->name : ''; - if ($paramName !== '' && preg_match('/@(?:param|phpstan-param|psalm-param)\s+[^\$]*?(?:iterable|Traversable|Generator|Iterator)\b[^\$]*?\$' . preg_quote($paramName, '/') . '\b/i', $docText) === 1) { + if ($paramName !== '' && preg_match('/@(?:param|phpstan-param|psalm-param)\s+[^\$]*?\b(?:iterable|Traversable|Generator|Iterator|IteratorAggregate)\b[^\$]*?\$' . preg_quote($paramName, '/') . '\b/i', $docText) === 1) { + return true; + } + + return false; + } + + /** + * @param array $templates + * @param array $visited + */ + private static function typeNodeContainsCallable(TypeNode $node, array $templates, array $visited = []): bool + { + while ($node instanceof NullableTypeNode || $node instanceof ArrayTypeNode) { + $node = $node->type; + } + + if ($node instanceof CallableTypeNode) { return true; } + if ($node instanceof IdentifierTypeNode) { + $lower = strtolower(ltrim($node->name, '\\')); + if (\in_array($lower, ['callable', 'closure', 'pure-callable', 'static-closure', 'static-pure-closure'], true)) { + return true; + } + + if (isset($templates[$node->name]) && ! isset($visited[$node->name]) && $templates[$node->name]->bound !== null) { + $visited[$node->name] = true; + + return self::typeNodeContainsCallable($templates[$node->name]->bound, $templates, $visited); + } + + return false; + } + + if ($node instanceof GenericTypeNode) { + if (self::typeNodeContainsCallable($node->type, $templates, $visited)) { + return true; + } + foreach ($node->genericTypes as $gt) { + if (self::typeNodeContainsCallable($gt, $templates, $visited)) { + return true; + } + } + + return false; + } + + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + foreach ($node->types as $member) { + if (self::typeNodeContainsCallable($member, $templates, $visited)) { + return true; + } + } + + return false; + } + + if ($node instanceof ConditionalTypeNode || $node instanceof ConditionalTypeForParameterNode) { + return self::typeNodeContainsCallable($node->if, $templates, $visited) + || self::typeNodeContainsCallable($node->else, $templates, $visited); + } + return false; } + /** + * @param array $templates + * @param array $visited + */ + private static function typeNodeContainsIterable(TypeNode $node, array $templates, array $visited = []): bool + { + while ($node instanceof NullableTypeNode) { + $node = $node->type; + } + + if ($node instanceof IdentifierTypeNode) { + $lower = strtolower(ltrim($node->name, '\\')); + if (isset(self::ITERABLE_TYPES[$lower])) { + return true; + } + + if (isset($templates[$node->name]) && ! isset($visited[$node->name]) && $templates[$node->name]->bound !== null) { + $visited[$node->name] = true; + + return self::typeNodeContainsIterable($templates[$node->name]->bound, $templates, $visited); + } + + return false; + } + + if ($node instanceof GenericTypeNode) { + return self::typeNodeContainsIterable($node->type, $templates, $visited); + } + + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + foreach ($node->types as $member) { + if (self::typeNodeContainsIterable($member, $templates, $visited)) { + return true; + } + } + + return false; + } + + if ($node instanceof ConditionalTypeNode || $node instanceof ConditionalTypeForParameterNode) { + return self::typeNodeContainsIterable($node->if, $templates, $visited) + || self::typeNodeContainsIterable($node->else, $templates, $visited); + } + + return false; + } + + /** + * @param array $baseAliases + * + * @return array + */ + private static function mergeDocblockAliases( + PhpDocNode $phpDocNode, + array $baseAliases, + string $currentFile, + ?string $currentNamespace + ): array { + $aliases = $baseAliases; + + foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } + } + + foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } + } + + $importTags = [ + ...$phpDocNode->getTagsByName('@psalm-import-type'), + ...$phpDocNode->getTagsByName('@phpstan-import-type'), + ]; + + foreach ($importTags as $tag) { + if ($tag->value instanceof TypeAliasImportTagValueNode) { + $importTag = $tag->value; + $localName = $importTag->importedAs ?? $importTag->importedAlias; + $sourceName = (string) $importTag->importedFrom; + $sourceFqcn = $currentFile !== '' + ? SpecialTypeResolver::resolveFqcnForFile($sourceName, $currentFile, true, $currentNamespace) + : $sourceName; + + if ( + ClassNameValidator::isValid($sourceFqcn) + && (class_exists($sourceFqcn) || interface_exists($sourceFqcn) || trait_exists($sourceFqcn) || enum_exists($sourceFqcn)) + ) { + $imported = DocblockExtractor::resolveImportedTypeAlias($sourceFqcn, $importTag->importedAlias); + if ($imported !== null) { + $aliases[$localName] = $imported; + } + } + } + } + + foreach ($aliases as $name => $type) { + $aliases[$name] = DocblockParser::substituteAliases($type, $aliases); + } + + return $aliases; + } + /** * @param array $targetNames */ @@ -1483,7 +1732,8 @@ private static function wrapGeneratorReturns( bool $hasSelfOut = false, bool $hasScope = false, array $trustedParamTypes = [], - bool $useDynamicMethodKey = false + bool $useDynamicMethodKey = false, + ?string $currentNamespace = null ): array { $canEliminate = $functionNode !== null && ! $hasMethodTemplates @@ -1512,7 +1762,8 @@ private static function wrapGeneratorReturns( $byRefParams, $hasSelfOut, $trustedParamTypes, - $useDynamicMethodKey + $useDynamicMethodKey, + $currentNamespace ) extends NodeVisitorAbstract { /** * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract @@ -1529,7 +1780,8 @@ public function __construct( private array $byRefParams, private bool $hasSelfOut, private array $trustedParamTypes, - private bool $useDynamicMethodKey + private bool $useDynamicMethodKey, + private ?string $currentNamespace ) { } @@ -1575,7 +1827,8 @@ public function enterNode(Node $n): int|Node|array|null $this->genContract['key'], $this->genContract['value'], $this->currentFile, - $precedingValueExpr + $precedingValueExpr, + $this->currentNamespace ); $sendContract = $this->genContract ?? $this->explicitGenContract; @@ -1607,7 +1860,8 @@ public function enterNode(Node $n): int|Node|array|null $n, $this->genContract['key'], $this->genContract['value'], - $this->currentFile + $this->currentFile, + $this->currentNamespace ); if (! $canEliminateYieldFrom) { @@ -1664,7 +1918,8 @@ public function enterNode(Node $n): int|Node|array|null $candidateExpr, $this->genContract['return'], $this->currentFile, - $this->trustedParamTypes + $this->trustedParamTypes, + $this->currentNamespace )) || ($this->explicitGenContract !== null && $this->explicitGenContract['return'] === null) ) { @@ -1718,7 +1973,7 @@ public function enterNode(Node $n): int|Node|array|null } $canSkipImplicitGenReturn = ($genContract !== null - && GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile, $trustedParamTypes)) + && GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile, $trustedParamTypes, $currentNamespace)) || ($explicitGenContract !== null && $explicitGenContract['return'] === null); if (! $canSkipImplicitGenReturn) { @@ -1773,7 +2028,8 @@ private static function wrapNonGeneratorReturns( string $currentFile = '', array $trustedParamTypes = [], bool $useDynamicMethodKey = false, - bool $canGuardReturnCache = true + bool $canGuardReturnCache = true, + ?string $currentNamespace = null ): array { self::tagPrecedingAssignments($stmts); @@ -1792,7 +2048,8 @@ private static function wrapNonGeneratorReturns( $currentFile, $trustedParamTypes, $useDynamicMethodKey, - $canGuardReturnCache + $canGuardReturnCache, + $currentNamespace ) extends NodeVisitorAbstract { /** * @param array $byRefParams @@ -1813,7 +2070,8 @@ public function __construct( private string $currentFile, private array $trustedParamTypes, private bool $useDynamicMethodKey, - private bool $canGuardReturnCache + private bool $canGuardReturnCache, + private ?string $currentNamespace ) { } @@ -1875,7 +2133,7 @@ public function enterNode(Node $n): int|array|null && $this->functionNode !== null && $this->returnTypeNode !== null && EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode) - && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes) + && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes, $this->currentNamespace) ) { return $exitStmts !== [] ? [...$exitStmts, $n] : null; } diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 1227b891..5d5904e2 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -283,6 +283,29 @@ public static function validateCollectionElementMutation( $key = $path[0][1]; $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); + $aaContract = null; + if ( + ($typeNode instanceof IdentifierTypeNode && ! SpecialTypeResolver::isBuiltInTypeKeyword($typeNode->name) && is_a($typeNode->name, \ArrayAccess::class, true)) + || ($typeNode instanceof GenericTypeNode && ! \in_array(strtolower((string) $typeNode->type), ['list', 'non-empty-list', 'array', 'non-empty-array', 'iterable'], true) && is_a((string) $typeNode->type, \ArrayAccess::class, true)) + ) { + $aaContract = MemberAssignChecker::resolveArrayAccessElementContract($typeNode); + } + + if ($aaContract !== null) { + if ($key !== null && $aaContract['keyType'] !== null) { + $keyErr = $registry->validate($key, $aaContract['keyType'], "Variable \${$varName} key"); + if ($keyErr !== null) { + return $keyErr; + } + } + + if ($aaContract['valueType'] !== null) { + $context = "Variable \${$varName}" . ($key !== null ? "['{$keyStr}']" : '[]'); + + return $registry->validate($value, $aaContract['valueType'], $context); + } + } + if ($typeNode instanceof GenericTypeNode) { $base = strtolower((string) $typeNode->type); diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index a0d6a250..103cec2d 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -8,20 +8,26 @@ use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use ReflectionClass; use ReflectionNamedType; use ReflectionProperty; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; +use TypePHP\Internal\Resolver\HierarchyResolver; +use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StructureMutator; +use TypePHP\Internal\Util\StubManager; use TypePHP\Internal\Validator\TypeValidatorRegistry; use WeakMap; @@ -138,12 +144,21 @@ final class MemberAssignChecker */ private static ?WeakMap $innerElementContractCache = null; + /** + * Memoized ArrayAccess resolution plan per concrete/generic ArrayAccess subclass: + * [$className] => ?array{classTemplates: array, keyType: ?TypeNode, valueType: ?TypeNode} + * + * @var array, keyType: ?TypeNode, valueType: ?TypeNode}> + */ + private static array $arrayAccessPlanCache = []; + /** * Resets the cached reflection property and element contract registries. */ public static function reset(): void { self::$innerElementContractCache = null; + self::$arrayAccessPlanCache = []; self::$refPropertyCache = []; self::$propertyMutationPlanCache = []; self::$substitutedElementContractCache = []; @@ -866,6 +881,37 @@ private static function resolveElementContractFromPlan( return $contract; } + /** + * @return ?array{ + * isList: bool, + * quoteKey: bool, + * keyType: ?TypeNode, + * valueType: ?TypeNode, + * keyOp: int, + * keyExtra: string|int|null, + * valOp: int, + * valExtra: string|int|null + * } + */ + /** + * Resolves an element contract for any collection, ArrayObject, or ArrayAccess subclass TypeNode. + * + * @return ?array{ + * isList: bool, + * quoteKey: bool, + * keyType: ?TypeNode, + * valueType: ?TypeNode, + * keyOp: int, + * keyExtra: string|int|null, + * valOp: int, + * valExtra: string|int|null + * } + */ + public static function resolveArrayAccessElementContract(TypeNode $typeNode): ?array + { + return self::buildElementContract($typeNode); + } + /** * @return ?array{ * isList: bool, @@ -880,8 +926,13 @@ private static function resolveElementContractFromPlan( */ private static function buildElementContract(TypeNode $typeNode): ?array { + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + if ($typeNode instanceof GenericTypeNode) { - $base = strtolower((string) $typeNode->type); + $rawType = (string) $typeNode->type; + $base = strtolower($rawType); if ($base === 'list' || $base === 'non-empty-list') { $valueType = $typeNode->genericTypes[0] ?? null; @@ -899,6 +950,53 @@ private static function buildElementContract(TypeNode $typeNode): ?array ]; } + if ( + ! \in_array($base, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator', 'arrayaccess', 'arrayobject', 'arrayiterator', 'weakmap', 'splobjectstorage'], true) + && ClassNameValidator::isValid($rawType) + && (class_exists($rawType, false) || class_exists($rawType) || interface_exists($rawType, false) || interface_exists($rawType)) + && is_a($rawType, \ArrayAccess::class, true) + ) { + $aaPlan = self::resolveArrayAccessPlan($rawType); + if ($aaPlan !== null) { + $keyType = $aaPlan['keyType']; + $valueType = $aaPlan['valueType']; + + if ($aaPlan['classTemplates'] !== []) { + $templateList = array_values($aaPlan['classTemplates']); + $normalizedArgs = TemplateManager::normalizeGenericArguments($typeNode->genericTypes, $templateList); + $bindings = []; + foreach ($templateList as $idx => $tTag) { + if (isset($normalizedArgs[$idx])) { + $bindings[$tTag->name] = $normalizedArgs[$idx]; + } + } + + if ($bindings !== []) { + if ($keyType !== null) { + $keyType = TemplateSubstitutor::substitute($keyType, $bindings, $aaPlan['classTemplates']); + } + if ($valueType !== null) { + $valueType = TemplateSubstitutor::substitute($valueType, $bindings, $aaPlan['classTemplates']); + } + } + } + + [$keyOp, $keyExtra] = self::compileCheckOp($keyType); + [$valOp, $valExtra] = self::compileCheckOp($valueType); + + return [ + 'isList' => false, + 'quoteKey' => true, + 'keyType' => $keyType, + 'valueType' => $valueType, + 'keyOp' => $keyOp, + 'keyExtra' => $keyExtra, + 'valOp' => $valOp, + 'valExtra' => $valExtra, + ]; + } + } + $genericCount = \count($typeNode->genericTypes); $keyType = $genericCount >= 2 ? $typeNode->genericTypes[0] : null; $valueType = $genericCount >= 2 @@ -936,9 +1034,149 @@ private static function buildElementContract(TypeNode $typeNode): ?array ]; } + if ( + $typeNode instanceof IdentifierTypeNode + && ClassNameValidator::isValid($typeNode->name) + && (class_exists($typeNode->name, false) || class_exists($typeNode->name) || interface_exists($typeNode->name, false) || interface_exists($typeNode->name)) + && is_a($typeNode->name, \ArrayAccess::class, true) + ) { + $aaPlan = self::resolveArrayAccessPlan($typeNode->name); + if ($aaPlan !== null) { + $keyType = $aaPlan['keyType']; + $valueType = $aaPlan['valueType']; + + if ($aaPlan['classTemplates'] !== []) { + $fallbackBindings = []; + foreach ($aaPlan['classTemplates'] as $tName => $tTag) { + $fallbackBindings[$tName] = $tTag->default ?? $tTag->bound ?? new IdentifierTypeNode('mixed'); + } + if ($keyType !== null) { + $keyType = TemplateSubstitutor::substitute($keyType, $fallbackBindings, $aaPlan['classTemplates']); + } + if ($valueType !== null) { + $valueType = TemplateSubstitutor::substitute($valueType, $fallbackBindings, $aaPlan['classTemplates']); + } + } + + [$keyOp, $keyExtra] = self::compileCheckOp($keyType); + [$valOp, $valExtra] = self::compileCheckOp($valueType); + + return [ + 'isList' => false, + 'quoteKey' => true, + 'keyType' => $keyType, + 'valueType' => $valueType, + 'keyOp' => $keyOp, + 'keyExtra' => $keyExtra, + 'valOp' => $valOp, + 'valExtra' => $valExtra, + ]; + } + } + return null; } + /** + * Walks @extends/@implements/@use hierarchy to extract ArrayAccess contracts, + * including SPL targets (ArrayObject, ArrayIterator, SplFixedArray, ArrayAccess, etc.). + * + * @return ?array{classTemplates: array, keyType: ?TypeNode, valueType: ?TypeNode} + */ + private static function resolveArrayAccessPlan(string $className): ?array + { + if (\array_key_exists($className, self::$arrayAccessPlanCache)) { + return self::$arrayAccessPlanCache[$className]; + } + + try { + /** @var class-string $className */ + $refClass = new ReflectionClass($className); + $hierarchy = HierarchyResolver::getClassHierarchy($refClass); + $rootTemplates = DocblockParser::parseClassTemplates($className); + + /** @var array> $pendingBindings */ + $pendingBindings = []; + + foreach ($hierarchy as $hierClass) { + $hierName = $hierClass->getName(); + $activeBindings = $pendingBindings[$hierName] ?? []; + $aliases = DocblockParser::parseClassAliases($hierName); + + $docs = []; + $classDoc = StubManager::getClassDoc($hierName) ?? $hierClass->getDocComment(); + if ($classDoc !== false && $classDoc !== null) { + $docs[] = $classDoc; + } + foreach (SpecialTypeResolver::getClassTraitUseDocs($hierName) as $tDoc) { + $docs[] = $tDoc; + } + + foreach ($docs as $rawDoc) { + $phpDocNode = DocblockExtractor::parseDocString($rawDoc); + foreach (DocblockExtractor::getInheritedTags($phpDocNode) as $inheritedTag) { + if (! ($inheritedTag->type instanceof GenericTypeNode)) { + continue; + } + + $genericNode = $inheritedTag->type; + $targetFqcn = SpecialTypeResolver::resolveFqcn((string) $genericNode->type, $hierClass); + $lowerTarget = strtolower(ltrim($targetFqcn, '\\')); + + $resolvedArgs = []; + foreach ($genericNode->genericTypes as $gt) { + $arg = $aliases !== [] ? DocblockParser::substituteAliases($gt, $aliases) : $gt; + if ($activeBindings !== []) { + $arg = TemplateSubstitutor::substitute($arg, $activeBindings); + } + $resolvedArgs[] = SpecialTypeResolver::resolve($arg, $hierClass); + } + + if (\in_array($lowerTarget, ['arrayaccess', 'arrayobject', 'arrayiterator', 'splfixedarray', 'splobjectstorage', 'weakmap'], true)) { + $count = \count($resolvedArgs); + if ($lowerTarget === 'splfixedarray') { + $keyType = new IdentifierTypeNode('int'); + $valueType = $resolvedArgs[0] ?? null; + } elseif ($count === 1) { + $keyType = null; + $valueType = $resolvedArgs[0]; + } elseif ($count >= 2) { + $keyType = $resolvedArgs[0]; + $valueType = $resolvedArgs[1]; + } else { + continue; + } + + return self::$arrayAccessPlanCache[$className] = [ + 'classTemplates' => $rootTemplates, + 'keyType' => $keyType, + 'valueType' => $valueType, + ]; + } + + if ( + ClassNameValidator::isValid($targetFqcn) + && (class_exists($targetFqcn, false) || class_exists($targetFqcn) || interface_exists($targetFqcn, false) || interface_exists($targetFqcn) || trait_exists($targetFqcn, false) || trait_exists($targetFqcn)) + && is_a($targetFqcn, \ArrayAccess::class, true) + ) { + $targetTemplates = DocblockParser::parseClassTemplates($targetFqcn); + $templateList = array_values($targetTemplates); + $normalizedArgs = TemplateManager::normalizeGenericArguments($resolvedArgs, $templateList); + foreach ($templateList as $idx => $tTag) { + if (isset($normalizedArgs[$idx])) { + $pendingBindings[$targetFqcn][$tTag->name] = $normalizedArgs[$idx]; + } + } + } + } + } + } + } catch (\Throwable) { + } + + return self::$arrayAccessPlanCache[$className] = null; + } + /** * @return array{0: int, 1: string|int|null} */ diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 5421cf40..3ac9fc35 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -2553,6 +2553,9 @@ private static function executeSimpleReturnPlan( self::PARAM_CHECK_TRUE => $value === true, self::PARAM_CHECK_FALSE => $value === false, self::PARAM_CHECK_SCALAR => \is_scalar($value), + self::PARAM_CHECK_NULL_OR_INT => $value === null || \is_int($value), + self::PARAM_CHECK_NULL_OR_STRING => $value === null || \is_string($value), + self::PARAM_CHECK_NULL_OR_BOOL => $value === null || \is_bool($value), default => false, }; @@ -2580,17 +2583,51 @@ private static function executeSimpleReturnPlan( */ private static function compileSimpleReturnOp(TypeNode $resolvedType): array { + $isNullable = false; $inner = $resolvedType; + while ($inner instanceof NullableTypeNode) { + $isNullable = true; $inner = $inner->type; } + if ($inner instanceof UnionTypeNode && \count($inner->types) === 2) { + $t0 = $inner->types[0]; + $t1 = $inner->types[1]; + + if (self::isNullTypeNode($t0)) { + $isNullable = true; + $inner = $t1; + } elseif (self::isNullTypeNode($t1)) { + $isNullable = true; + $inner = $t0; + } + + while ($inner instanceof NullableTypeNode) { + $isNullable = true; + $inner = $inner->type; + } + } + if (! ($inner instanceof IdentifierTypeNode)) { return [self::PARAM_CHECK_FALLBACK, null]; } $name = $inner->name; + if ($isNullable) { + $nullableOp = match ($name) { + 'int', 'integer' => self::PARAM_CHECK_NULL_OR_INT, + 'string' => self::PARAM_CHECK_NULL_OR_STRING, + 'bool', 'boolean' => self::PARAM_CHECK_NULL_OR_BOOL, + default => null, + }; + + if ($nullableOp !== null) { + return [$nullableOp, null]; + } + } + $op = match ($name) { 'int', 'integer' => self::PARAM_CHECK_INT, 'string' => self::PARAM_CHECK_STRING, @@ -2629,6 +2666,12 @@ private static function compileSimpleReturnOp(TypeNode $resolvedType): array return [self::PARAM_CHECK_FALLBACK, null]; } + private static function isNullTypeNode(TypeNode $node): bool + { + return ($node instanceof IdentifierTypeNode && strtolower($node->name) === 'null') + || ($node instanceof ConstTypeNode && $node->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode); + } + /** * Validates a value sent into a generator via $gen->send() against TSend. */ diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index ab747f5b..d34bca03 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -139,12 +139,31 @@ public static function wrap(string $function, string $paramName, mixed $callable } if (\is_array($callable)) { + $unwrappedNode = $typeNode; + while ($unwrappedNode instanceof NullableTypeNode) { + $unwrappedNode = $unwrappedNode->type; + } + if ($unwrappedNode instanceof UnionTypeNode) { + $nonNullNode = null; + $nonNullCount = 0; + foreach ($unwrappedNode->types as $member) { + if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { + continue; + } + $nonNullCount++; + $nonNullNode = $member; + } + if ($nonNullCount === 1 && $nonNullNode !== null) { + $unwrappedNode = $nonNullNode; + } + } + $innerCallableTypeNode = null; - if ($typeNode instanceof GenericTypeNode && \in_array(strtolower((string) $typeNode->type), ['list', 'array', 'iterable'], strict: true)) { - $innerCallableTypeNode = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null; - } elseif ($typeNode instanceof ArrayTypeNode) { - $innerCallableTypeNode = $typeNode->type; + if ($unwrappedNode instanceof GenericTypeNode && \in_array(strtolower((string) $unwrappedNode->type), ['list', 'array', 'iterable'], strict: true)) { + $innerCallableTypeNode = $unwrappedNode->genericTypes[1] ?? $unwrappedNode->genericTypes[0] ?? null; + } elseif ($unwrappedNode instanceof ArrayTypeNode) { + $innerCallableTypeNode = $unwrappedNode->type; } if ($innerCallableTypeNode instanceof CallableTypeNode) { @@ -265,6 +284,27 @@ public static function wrapTypeNode( string $function = '', string $paramName = 'callback' ): mixed { + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof UnionTypeNode) { + $nonNullCallable = null; + $nonNullCount = 0; + foreach ($typeNode->types as $member) { + if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { + continue; + } + $nonNullCount++; + if ($member instanceof CallableTypeNode) { + $nonNullCallable = $member; + } + } + if ($nonNullCount === 1 && $nonNullCallable !== null) { + $typeNode = $nonNullCallable; + } + } + if (! ($typeNode instanceof CallableTypeNode) || ! self::isCallable($callable)) { return $callable; } diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index 0ee9baae..ab7b26ef 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -8,6 +8,7 @@ use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Exception\TypeError as TypePHPTypeError; @@ -182,6 +183,25 @@ private static function resolveKeyAndItemTypes( } } + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof UnionTypeNode) { + $nonNullNode = null; + $nonNullCount = 0; + foreach ($typeNode->types as $member) { + if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { + continue; + } + $nonNullCount++; + $nonNullNode = $member; + } + if ($nonNullCount === 1 && $nonNullNode !== null) { + $typeNode = $nonNullNode; + } + } + $baseName = ''; if ($typeNode instanceof IdentifierTypeNode) { $baseName = strtolower(ltrim($typeNode->name, '\\')); From edde153b4728085b9f4cbc99c29690f234219f37 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 14:06:48 +0800 Subject: [PATCH 6/9] Refactor ContractVisitor and FunctionContractInjector for improved alias resolution and make sure autoloading is disabled during ast transformation time; enhance Config reset logic to include ContractVisitor reset; streamline StructureMutator's unset logic --- src/Internal/Ast/ContractVisitor.php | 542 ++++++++++++++++-- src/Internal/Ast/FunctionContractInjector.php | 34 +- src/Internal/Util/Config.php | 4 + src/Internal/Util/StructureMutator.php | 8 +- 4 files changed, 509 insertions(+), 79 deletions(-) diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 50851fee..3eaf767c 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -4,12 +4,14 @@ namespace TypePHP\Internal\Ast; +use Composer\Autoload\ClassLoader; use PhpParser\Node; use PhpParser\NodeFinder; use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode; @@ -26,6 +28,7 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; @@ -94,6 +97,18 @@ final class ContractVisitor extends NodeVisitorAbstract */ private static array $parsedUnsetTypeCache = []; + /** + * In-memory cache of class-level aliases resolved from AST without invoking PHP autoloading. + * + * @var array> + */ + private static array $astClassAliasesCache = []; + + public static function reset(): void + { + self::$astClassAliasesCache = []; + } + /** * @var array> */ @@ -927,10 +942,30 @@ private function resolveClassTemplatesForDefaults(Node\Stmt\Class_ $node): array if ($node->extends !== null) { $parentClass = $this->resolveClassNameFromNode($node->extends) ?? $node->extends->toString(); - try { - $parentTemplates = DocblockParser::parseClassTemplates($parentClass); - $classTemplates = [...$classTemplates, ...$parentTemplates]; - } catch (\Throwable) { + if (class_exists($parentClass, false) || StubManager::hasClassStub($parentClass)) { + try { + $parentTemplates = DocblockParser::parseClassTemplates($parentClass); + $classTemplates = [...$classTemplates, ...$parentTemplates]; + } catch (\Throwable) { + } + } else { + $parentFile = self::findClassFileWithoutAutoload($parentClass); + if ($parentFile !== null) { + $parentSource = @file_get_contents($parentFile); + if ($parentSource !== false && str_contains($parentSource, 'template')) { + try { + $parentStmts = StreamWrapper::getParser()->parse($parentSource); + if ($parentStmts !== null) { + $parentDoc = self::findClassDocInStmts($parentStmts, $parentClass); + if ($parentDoc !== null) { + $phpDocNode = DocblockExtractor::parseDocString($parentDoc); + $classTemplates = [...$classTemplates, ...DocblockExtractor::extractTemplates($phpDocNode)]; + } + } + } catch (\Throwable) { + } + } + } } } @@ -1135,7 +1170,8 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } /** - * Extracts class-level and inherited @phpstan-type / @psalm-type / @phpstan-import-type aliases at AST transform time. + * Extracts class-level and inherited @phpstan-type / @psalm-type / @phpstan-import-type aliases at AST transform time + * without invoking PHP's autoloader/compiler. * * @return array */ @@ -1146,53 +1182,12 @@ private function extractClassLikeAliases( ): array { /** @var array $aliases */ $aliases = []; + $visited = $typeName !== null ? [$typeName => true] : []; if ($doc !== null && (str_contains($doc->getText(), '-type') || str_contains($doc->getText(), 'import-type'))) { try { $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); - - foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; - } - } - - foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; - } - } - - $importTags = [ - ...$phpDocNode->getTagsByName('@psalm-import-type'), - ...$phpDocNode->getTagsByName('@phpstan-import-type'), - ]; - - foreach ($importTags as $tag) { - if ($tag->value instanceof TypeAliasImportTagValueNode) { - $importTag = $tag->value; - $localName = $importTag->importedAs ?? $importTag->importedAlias; - if (isset($aliases[$localName])) { - continue; - } - - $sourceFqcn = $this->resolveClassNameFromNode(new Node\Name((string) $importTag->importedFrom)) - ?? (string) $importTag->importedFrom; - - $imported = $this->localClassAliases[$sourceFqcn][$importTag->importedAlias] ?? null; - if ( - $imported === null - && ClassNameValidator::isValid($sourceFqcn) - && (class_exists($sourceFqcn) || interface_exists($sourceFqcn) || trait_exists($sourceFqcn) || enum_exists($sourceFqcn)) - ) { - $imported = DocblockExtractor::resolveImportedTypeAlias($sourceFqcn, $importTag->importedAlias); - } - - if ($imported !== null) { - $aliases[$localName] = $imported; - } - } - } + $this->collectAliasesFromPhpDocInFile($phpDocNode, $aliases, $this->currentFile, $this->currentNamespace, $visited); } catch (\Throwable) { } } @@ -1228,33 +1223,452 @@ private function extractClassLikeAliases( foreach ($parentNodes as $parentNode) { $parentFqcn = $this->resolveClassNameFromNode($parentNode) ?? $parentNode->toString(); - $parentAliases = $this->localClassAliases[$parentFqcn] ?? null; + $parentAliases = self::resolveClassAliasesNoAutoload($parentFqcn, $this->localClassAliases, $visited); + + foreach ($parentAliases as $aName => $aType) { + if (! isset($aliases[$aName])) { + $aliases[$aName] = $aType; + } + } + } + + foreach ($aliases as $aName => $aType) { + $aliases[$aName] = DocblockParser::substituteAliases($aType, $aliases); + } + + if ($typeName !== null && $aliases !== []) { + $this->localClassAliases[$typeName] = $aliases; + } + + return $aliases; + } + + /** + * @param array $aliases + * @param array $visited + */ + private function collectAliasesFromPhpDocInFile( + PhpDocNode $phpDocNode, + array &$aliases, + string $filePath, + string $namespace, + array $visited + ): void { + foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } + } + + foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } + } + + $importTags = [ + ...$phpDocNode->getTagsByName('@psalm-import-type'), + ...$phpDocNode->getTagsByName('@phpstan-import-type'), + ]; + + foreach ($importTags as $tag) { + if ($tag->value instanceof TypeAliasImportTagValueNode) { + $importTag = $tag->value; + $localName = $importTag->importedAs ?? $importTag->importedAlias; + if (isset($aliases[$localName])) { + continue; + } + + $sourceFqcn = $this->resolveClassNameFromNode(new Node\Name((string) $importTag->importedFrom)) + ?? (string) $importTag->importedFrom; + + $sourceAliases = self::resolveClassAliasesNoAutoload($sourceFqcn, $this->localClassAliases, $visited); + if (isset($sourceAliases[$importTag->importedAlias])) { + $aliases[$localName] = $sourceAliases[$importTag->importedAlias]; + } + } + } + } + + /** + * Resolves class-level aliases for an FQCN without invoking PHP autoloading/compilation. + * + * @param array> $localClassAliases + * @param array $visited + * + * @return array + */ + public static function resolveClassAliasesNoAutoload( + string $fqcn, + array $localClassAliases = [], + array $visited = [] + ): array { + $fqcn = ltrim($fqcn, '\\'); + if ($fqcn === '' || isset($visited[$fqcn])) { + return []; + } + + if (isset($localClassAliases[$fqcn])) { + return $localClassAliases[$fqcn]; + } + + if (isset(self::$astClassAliasesCache[$fqcn])) { + return self::$astClassAliasesCache[$fqcn]; + } + + if ( + class_exists($fqcn, false) + || interface_exists($fqcn, false) + || trait_exists($fqcn, false) + || enum_exists($fqcn, false) + ) { + return self::$astClassAliasesCache[$fqcn] = DocblockParser::parseClassAliases($fqcn); + } + + $visited[$fqcn] = true; + + $stubDoc = StubManager::getClassDoc($fqcn); + if ($stubDoc !== null) { + if (! str_contains($stubDoc, '-type') && ! str_contains($stubDoc, 'import-type')) { + return self::$astClassAliasesCache[$fqcn] = []; + } + + try { + $phpDocNode = DocblockExtractor::parseDocString($stubDoc); + $aliases = []; + self::collectRawAliasesFromAstDoc($phpDocNode, $aliases, '', '', [], $localClassAliases, $visited); + + return self::$astClassAliasesCache[$fqcn] = $aliases; + } catch (\Throwable) { + return self::$astClassAliasesCache[$fqcn] = []; + } + } + + $filePath = self::findClassFileWithoutAutoload($fqcn); + if ($filePath === null) { + return self::$astClassAliasesCache[$fqcn] = []; + } + + $source = @file_get_contents($filePath); + if ( + $source === false + || ( + ! str_contains($source, '-type') + && ! str_contains($source, 'import-type') + && ! str_contains($source, 'extends') + && ! str_contains($source, 'implements') + && ! str_contains($source, 'use ') + ) + ) { + return self::$astClassAliasesCache[$fqcn] = []; + } + + try { + $stmts = StreamWrapper::getParser()->parse($source); + if ($stmts === null) { + return self::$astClassAliasesCache[$fqcn] = []; + } + + $aliases = self::extractTargetClassAliasesFromStmts($stmts, $fqcn, $filePath, $localClassAliases, $visited); + } catch (\Throwable) { + $aliases = []; + } + + return self::$astClassAliasesCache[$fqcn] = $aliases; + } + + /** + * Locates a class, interface, trait, or enum source file via Composer's ClassLoader without executing it. + */ + public static function findClassFileWithoutAutoload(string $fqcn): ?string + { + $fqcn = ltrim($fqcn, '\\'); + if (! ClassNameValidator::isValid($fqcn)) { + return null; + } + + $autoloaders = spl_autoload_functions(); + foreach ($autoloaders as $autoloader) { + if (\is_array($autoloader) && $autoloader[0] instanceof ClassLoader) { + $file = $autoloader[0]->findFile($fqcn); + if (\is_string($file) && $file !== '' && is_file($file)) { + return $file; + } + } + } + + return null; + } + + /** + * @param array $stmts + * @param array> $localClassAliases + * @param array $visited + * + * @return array + */ + private static function extractTargetClassAliasesFromStmts( + array $stmts, + string $targetFqcn, + string $filePath, + array $localClassAliases, + array $visited + ): array { + foreach ($stmts as $stmt) { + if ($stmt instanceof Node\Stmt\Namespace_) { + $ns = $stmt->name !== null ? $stmt->name->toString() : ''; + $imports = self::collectNamespaceImports($stmt->stmts); + $found = self::scanClassLikesForAliases($stmt->stmts, $ns, $imports, $targetFqcn, $filePath, $localClassAliases, $visited); + if ($found !== null) { + return $found; + } + } + } + + $topImports = self::collectNamespaceImports($stmts); + + return self::scanClassLikesForAliases($stmts, '', $topImports, $targetFqcn, $filePath, $localClassAliases, $visited) ?? []; + } + + /** + * @param array $stmts + * @param array $imports + * @param array> $localClassAliases + * @param array $visited + * + * @return array|null + */ + private static function scanClassLikesForAliases( + array $stmts, + string $namespace, + array $imports, + string $targetFqcn, + string $filePath, + array $localClassAliases, + array $visited + ): ?array { + foreach ($stmts as $stmt) { if ( - $parentAliases === null - && ClassNameValidator::isValid($parentFqcn) - && (class_exists($parentFqcn) || interface_exists($parentFqcn) || trait_exists($parentFqcn)) + ! ( + $stmt instanceof Node\Stmt\Class_ + || $stmt instanceof Node\Stmt\Interface_ + || $stmt instanceof Node\Stmt\Trait_ + || $stmt instanceof Node\Stmt\Enum_ + ) + || $stmt->name === null ) { - $parentAliases = DocblockParser::parseClassAliases($parentFqcn); + continue; } - if ($parentAliases !== null) { - foreach ($parentAliases as $aName => $aType) { + $fqcn = $namespace !== '' ? $namespace . '\\' . $stmt->name->toString() : $stmt->name->toString(); + if ($fqcn !== $targetFqcn) { + continue; + } + + /** @var array $aliases */ + $aliases = []; + $doc = $stmt->getDocComment(); + if ($doc !== null && (str_contains($doc->getText(), '-type') || str_contains($doc->getText(), 'import-type'))) { + try { + $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); + self::collectRawAliasesFromAstDoc($phpDocNode, $aliases, $filePath, $namespace, $imports, $localClassAliases, $visited); + } catch (\Throwable) { + } + } + + /** @var list $parentNodes */ + $parentNodes = []; + if ($stmt instanceof Node\Stmt\Class_) { + if ($stmt->extends !== null) { + $parentNodes[] = $stmt->extends; + } + foreach ($stmt->implements as $iface) { + $parentNodes[] = $iface; + } + } elseif ($stmt instanceof Node\Stmt\Interface_) { + foreach ($stmt->extends as $iface) { + $parentNodes[] = $iface; + } + } elseif ($stmt instanceof Node\Stmt\Enum_) { + foreach ($stmt->implements as $iface) { + $parentNodes[] = $iface; + } + } + + if ($stmt instanceof Node\Stmt\Class_ || $stmt instanceof Node\Stmt\Trait_ || $stmt instanceof Node\Stmt\Enum_) { + foreach ($stmt->stmts as $member) { + if ($member instanceof Node\Stmt\TraitUse) { + foreach ($member->traits as $traitName) { + $parentNodes[] = $traitName; + } + } + } + } + + foreach ($parentNodes as $parentNode) { + $parentFqcn = self::resolveAstName($parentNode, $namespace, $imports); + foreach (self::resolveClassAliasesNoAutoload($parentFqcn, $localClassAliases, $visited) as $aName => $aType) { if (! isset($aliases[$aName])) { $aliases[$aName] = $aType; } } } + + foreach ($aliases as $aName => $aType) { + $substituted = DocblockParser::substituteAliases($aType, $aliases); + $aliases[$aName] = $filePath !== '' + ? SpecialTypeResolver::resolveForFile($substituted, $filePath, $namespace, false) + : $substituted; + } + + return $aliases; } - foreach ($aliases as $aName => $aType) { - $aliases[$aName] = DocblockParser::substituteAliases($aType, $aliases); + return null; + } + + /** + * @param array $aliases + * @param array $imports + * @param array> $localClassAliases + * @param array $visited + */ + private static function collectRawAliasesFromAstDoc( + PhpDocNode $phpDocNode, + array &$aliases, + string $filePath, + string $namespace, + array $imports, + array $localClassAliases, + array $visited + ): void { + foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } } - if ($typeName !== null && $aliases !== []) { - $this->localClassAliases[$typeName] = $aliases; + foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { + if ($tag->value instanceof TypeAliasTagValueNode) { + $aliases[$tag->value->alias] = $tag->value->type; + } } - return $aliases; + $importTags = [ + ...$phpDocNode->getTagsByName('@psalm-import-type'), + ...$phpDocNode->getTagsByName('@phpstan-import-type'), + ]; + + foreach ($importTags as $tag) { + if ($tag->value instanceof TypeAliasImportTagValueNode) { + $importTag = $tag->value; + $localName = $importTag->importedAs ?? $importTag->importedAlias; + if (isset($aliases[$localName])) { + continue; + } + + $rawSource = ltrim((string) $importTag->importedFrom, '\\'); + $sourceFqcn = str_starts_with((string) $importTag->importedFrom, '\\') + ? $rawSource + : ($imports[$rawSource] ?? ($namespace !== '' && ! str_contains($rawSource, '\\') ? $namespace . '\\' . $rawSource : $rawSource)); + + $sourceAliases = self::resolveClassAliasesNoAutoload($sourceFqcn, $localClassAliases, $visited); + if (isset($sourceAliases[$importTag->importedAlias])) { + $aliases[$localName] = $sourceAliases[$importTag->importedAlias]; + } + } + } + + if ($filePath !== '') { + foreach ($aliases as $aName => $aType) { + $aliases[$aName] = SpecialTypeResolver::resolveForFile($aType, $filePath, $namespace, false); + } + } + } + + /** + * @param array $stmts + * + * @return array + */ + private static function collectNamespaceImports(array $stmts): array + { + $imports = []; + + foreach ($stmts as $stmt) { + if ($stmt instanceof Node\Stmt\Use_) { + if ($stmt->type !== Node\Stmt\Use_::TYPE_NORMAL) { + continue; + } + foreach ($stmt->uses as $use) { + $imports[$use->getAlias()->toString()] = $use->name->toString(); + } + } elseif ($stmt instanceof Node\Stmt\GroupUse) { + $prefix = $stmt->prefix->toString(); + foreach ($stmt->uses as $use) { + if ( + $use->type !== Node\Stmt\Use_::TYPE_NORMAL + && $use->type !== Node\Stmt\Use_::TYPE_UNKNOWN + && $stmt->type !== Node\Stmt\Use_::TYPE_NORMAL + ) { + continue; + } + $imports[$use->getAlias()->toString()] = $prefix . '\\' . $use->name->toString(); + } + } + } + + return $imports; + } + + /** + * @param array $imports + */ + private static function resolveAstName(Node\Name $nameNode, string $namespace, array $imports): string + { + $raw = $nameNode->toString(); + if ($nameNode->isFullyQualified()) { + return $raw; + } + + 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; + } + + /** + * @param array $stmts + */ + private static function findClassDocInStmts(array $stmts, string $targetFqcn): ?string + { + foreach ($stmts as $stmt) { + if ($stmt instanceof Node\Stmt\Namespace_) { + $ns = $stmt->name !== null ? $stmt->name->toString() : ''; + foreach ($stmt->stmts as $inner) { + if ($inner instanceof Node\Stmt\Class_ && $inner->name !== null) { + $fqcn = $ns !== '' ? $ns . '\\' . $inner->name->toString() : $inner->name->toString(); + if ($fqcn === $targetFqcn) { + return $inner->getDocComment()?->getText(); + } + } + } + } elseif ($stmt instanceof Node\Stmt\Class_ && $stmt->name !== null) { + if ($stmt->name->toString() === $targetFqcn) { + return $stmt->getDocComment()?->getText(); + } + } + } + + return null; } private function handleReturn(Node\Stmt\Return_ $node): void @@ -1976,6 +2390,10 @@ private function resolveStaticClassArg(Node\Name|Node\Expr $class): Node\Expr */ private function resolveClassNameFromNode(Node\Name $classNode): ?string { + if ($classNode->isFullyQualified()) { + return $classNode->toString(); + } + $rawClass = $classNode->toString(); $lowerClass = strtolower($rawClass); @@ -1986,10 +2404,10 @@ private function resolveClassNameFromNode(Node\Name $classNode): ?string } $resolved = $this->currentFile !== '' - ? SpecialTypeResolver::resolveFqcnForFile($rawClass, $this->currentFile, false) + ? SpecialTypeResolver::resolveFqcnForFile($rawClass, $this->currentFile, false, $this->currentNamespace) : $rawClass; - if ($resolved === $rawClass && $this->currentNamespace !== '' && ! str_contains($rawClass, '\\')) { + if ($resolved === $rawClass && $this->currentNamespace !== '') { return $this->currentNamespace . '\\' . $rawClass; } diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 0db3d99e..5c7adfe6 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -29,7 +29,6 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Resolver\SpecialTypeResolver; -use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StubManager; @@ -1456,19 +1455,32 @@ private static function mergeDocblockAliases( $importTag = $tag->value; $localName = $importTag->importedAs ?? $importTag->importedAlias; $sourceName = (string) $importTag->importedFrom; - $sourceFqcn = $currentFile !== '' - ? SpecialTypeResolver::resolveFqcnForFile($sourceName, $currentFile, true, $currentNamespace) - : $sourceName; - if ( - ClassNameValidator::isValid($sourceFqcn) - && (class_exists($sourceFqcn) || interface_exists($sourceFqcn) || trait_exists($sourceFqcn) || enum_exists($sourceFqcn)) - ) { - $imported = DocblockExtractor::resolveImportedTypeAlias($sourceFqcn, $importTag->importedAlias); - if ($imported !== null) { - $aliases[$localName] = $imported; + if (str_starts_with($sourceName, '\\')) { + $sourceFqcn = ltrim($sourceName, '\\'); + } else { + $sourceFqcn = $currentFile !== '' + ? SpecialTypeResolver::resolveFqcnForFile($sourceName, $currentFile, false, $currentNamespace) + : $sourceName; + + if ( + $sourceFqcn === $sourceName + && $currentNamespace !== null + && $currentNamespace !== '' + && ! str_contains($sourceName, '\\') + && ! class_exists($sourceName, false) + && ! interface_exists($sourceName, false) + && ! trait_exists($sourceName, false) + && ! enum_exists($sourceName, false) + ) { + $sourceFqcn = $currentNamespace . '\\' . $sourceName; } } + + $sourceAliases = ContractVisitor::resolveClassAliasesNoAutoload($sourceFqcn); + if (isset($sourceAliases[$importTag->importedAlias])) { + $aliases[$localName] = $sourceAliases[$importTag->importedAlias]; + } } } diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index ef67a76a..0fe1558e 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -5,6 +5,7 @@ namespace TypePHP\Internal\Util; use TypePHP\Extension\ExtensionInterface; +use TypePHP\Internal\Ast\ContractVisitor; use TypePHP\Internal\Checker\MemberAssignChecker; use TypePHP\Internal\Checker\ParamChecker; use TypePHP\Internal\Checker\ReturnChecker; @@ -778,6 +779,7 @@ public static function set(array $config): void self::syncFlags($mergedConfig); DocblockParser::reset(); + ContractVisitor::reset(); ParamChecker::reset(); MemberAssignChecker::reset(); ReturnChecker::reset(); @@ -837,6 +839,7 @@ private static function mergeConfig(array $base, array $overrides): array public static function reset(): void { self::$cachedConfig = null; + ContractVisitor::reset(); self::$projectRoot = null; self::$resolvedConfigFile = null; self::$enabled = true; @@ -882,6 +885,7 @@ public static function reset(): void RuntimeTypeChecker::$arrayValidationHybrid = false; DocblockParser::reset(); + ContractVisitor::reset(); ParamChecker::reset(); MemberAssignChecker::reset(); ReturnChecker::reset(); diff --git a/src/Internal/Util/StructureMutator.php b/src/Internal/Util/StructureMutator.php index 4973de73..1e759174 100644 --- a/src/Internal/Util/StructureMutator.php +++ b/src/Internal/Util/StructureMutator.php @@ -145,12 +145,8 @@ public static function unsetCopy(mixed $root, array $chains): mixed } if ($isLast) { - try { - // @phpstan-ignore property.dynamicName - unset($current->$propName); - } catch (\Throwable) { - break; - } + // @phpstan-ignore property.dynamicName + unset($current->$propName); } else { try { // @phpstan-ignore property.dynamicName From cbc4cd20d3cfb2c7ee48879fccabdd20852b2966 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 14:09:30 +0800 Subject: [PATCH 7/9] Add PHP 8.6 to the testing matrix in CI configuration --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aeeca167..bbfbc17d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,7 +82,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] - php: ['8.1', '8.2', '8.3', '8.4', '8.5'] + php: ['8.1', '8.2', '8.3', '8.4', '8.5', '8.6'] steps: - name: Checkout Code From 49ff3fda37ac31471b871405663e29227a41b382 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 14:13:17 +0800 Subject: [PATCH 8/9] Update vimeo/psalm dependency to version 7.0.0 in composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d9b472dd..47ab3767 100644 --- a/composer.json +++ b/composer.json @@ -35,7 +35,7 @@ "phpstan/phpstan": "^2.1", "phpstan/phpstan-strict-rules": "^2.0", "phpstan/extension-installer": "^1.4", - "vimeo/psalm": "^6.16", + "vimeo/psalm": "^7.0.0", "carthage-software/mago": "^1.47", "rector/rector": "^2.6", "friendsofphp/php-cs-fixer": "^3.95" From d4bb4b92658a94ee1c3d0139d1b289a66e50c123 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 24 Nov 2026 14:50:02 +0800 Subject: [PATCH 9/9] Enhance ContractVisitor and FunctionContractInjector for improved scope management; add tests for Priority 4 Bugs related to scope isolation and docblock heuristics --- src/Internal/Ast/ContractVisitor.php | 56 ++- src/Internal/Ast/FunctionContractInjector.php | 291 ++++++-------- src/Internal/Docblock/DocblockNormalizer.php | 8 + src/Internal/Io/CacheManager.php | 2 +- .../Ast/FunctionContractInjectorTest.php | 33 +- .../Boundaries/Priority4BugsTest.php | 369 ++++++++++++++++++ 6 files changed, 579 insertions(+), 180 deletions(-) create mode 100644 tests/TypeChecking/Boundaries/Priority4BugsTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 3eaf767c..5e9a41da 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -150,6 +150,20 @@ public static function reset(): void */ private array $byRefStack = []; + /** + * Tracks whether the try-body scope of an active TryCatch node is currently open. + * + * @var list + */ + private array $tryCatchScopeStack = []; + + /** + * Tracks whether the if-body scope of an active If_ node is currently open. + * + * @var list + */ + private array $ifScopeStack = []; + /** * @var array> */ @@ -226,6 +240,26 @@ public function enterNode(Node $node): Node|array|null $this->registerParamInferredTypes($node->params); } elseif ($this->isSoftScopeBoundary($node)) { $this->scopeManager->pushScope(isIsolated: false); + } elseif ($node instanceof Node\Stmt\If_) { + $this->scopeManager->pushScope(isIsolated: false); + $this->ifScopeStack[] = true; + } elseif ($node instanceof Node\Stmt\ElseIf_ || $node instanceof Node\Stmt\Else_) { + if ($this->ifScopeStack !== [] && end($this->ifScopeStack)) { + $this->scopeManager->popScope(); + array_pop($this->ifScopeStack); + $this->ifScopeStack[] = false; + } + $this->scopeManager->pushScope(isIsolated: false); + } elseif ($node instanceof Node\Stmt\TryCatch) { + $this->scopeManager->pushScope(isIsolated: false); + $this->tryCatchScopeStack[] = true; + } elseif ($node instanceof Node\Stmt\Catch_ || $node instanceof Node\Stmt\Finally_) { + if ($this->tryCatchScopeStack !== [] && end($this->tryCatchScopeStack)) { + $this->scopeManager->popScope(); + array_pop($this->tryCatchScopeStack); + $this->tryCatchScopeStack[] = false; + } + $this->scopeManager->pushScope(isIsolated: false); } if ($node instanceof Node\Expr\Assign || $node instanceof Node\Expr\AssignOp) { @@ -408,6 +442,22 @@ public function leaveNode(Node $node): Node|array|null return $boundaryCheck !== null ? [$node, $boundaryCheck] : null; } + if ($node instanceof Node\Stmt\ElseIf_ || $node instanceof Node\Stmt\Else_) { + $this->scopeManager->popScope(); + } elseif ($node instanceof Node\Stmt\If_) { + $wasActive = $this->ifScopeStack !== [] ? array_pop($this->ifScopeStack) : false; + if ($wasActive) { + $this->scopeManager->popScope(); + } + } elseif ($node instanceof Node\Stmt\Catch_ || $node instanceof Node\Stmt\Finally_) { + $this->scopeManager->popScope(); + } elseif ($node instanceof Node\Stmt\TryCatch) { + $wasActive = $this->tryCatchScopeStack !== [] ? array_pop($this->tryCatchScopeStack) : false; + if ($wasActive) { + $this->scopeManager->popScope(); + } + } + if ($this->isScopeBoundary($node)) { $this->scopeManager->popScope(); } @@ -2658,14 +2708,12 @@ private function isSoftScopeBoundary(Node $node): bool { return $node instanceof Node\Expr\ArrowFunction || $node instanceof Node\Stmt\Block - || $node instanceof Node\Stmt\If_ - || $node instanceof Node\Stmt\Else_ - || $node instanceof Node\Stmt\ElseIf_ || $node instanceof Node\Stmt\Foreach_ || $node instanceof Node\Stmt\While_ || $node instanceof Node\Stmt\For_ || $node instanceof Node\Stmt\Do_ - || $node instanceof Node\Stmt\TryCatch; + || $node instanceof Node\Stmt\Case_ + || $node instanceof Node\MatchArm; } private function isScopeBoundary(Node $node): bool diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 5c7adfe6..46cdc7dd 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -68,7 +68,7 @@ public static function inject( $docText = $doc !== null ? $doc->getText() : ''; $hasInheritance = $classContext['hasInheritance'] ?? true; - $hasRealInheritance = $classContext['hasRealInheritance'] ?? $hasInheritance; + $hasRealInheritance = $isClassMethod ? ($classContext['hasRealInheritance'] ?? $hasInheritance) : false; $hasPropertyWithDoc = $classContext['hasPropertyWithDoc'] ?? true; $isReadonlyClass = $classContext['isReadonly'] ?? false; $isFinalClass = $classContext['isFinal'] ?? false; @@ -96,66 +96,14 @@ public static function inject( $paramCount = \count($node->params); - $hasReturnDoc = str_contains($docText, '@return') - || str_contains($docText, '@phpstan-return') - || str_contains($docText, '@psalm-return'); - - $hasReturn = ! $isMagicLifecycle - && ! $isNativeNever - && ! ($isNativeVoid && ! $hasReturnDoc) - && ($isMagicGet || $isMagicCall || self::hasReturnContracts( - $docText, - $isClassMethod, - $hasInheritance, - $isPrivate, - $classContext === null, - )); - - $byRefParams = []; - foreach ($node->params as $p) { - if ($p->byRef && $p->var instanceof Node\Expr\Variable && \is_string($p->var->name)) { - $byRefParams[] = $p->var->name; - } - } - - $hasParamOutDoc = str_contains($docText, '@param-out') - || str_contains($docText, '@phpstan-param-out') - || str_contains($docText, '@psalm-param-out'); - - $hasParamOut = $byRefParams !== [] && ($hasParamOutDoc || $hasInheritance); - - $hasSelfOutDoc = str_contains($docText, 'self-out') || str_contains($docText, 'this-out'); - $hasSelfOut = $isClassMethod && ! $node->isStatic() && ($hasSelfOutDoc || ($hasClassTemplates && $hasRealInheritance)); - - $hasParam = ($isMagicGet || $isMagicCall) || ($paramCount > 0 && ( - str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc || $hasParamOutDoc) && str_contains($docText, '$')) - )) || self::hasParamContracts( - $docText, - $isClassMethod, - $hasInheritance, - $paramCount, - $isPrivate, - $isConstructor, - $hasPropertyWithDoc, - $classContext === null, - $node->attrGroups !== [], - ); - - if (! $hasParam && ! $hasReturn && ! $hasParamOut && ! $hasSelfOut) { - return; - } - - $thisArg = self::resolveThisArg($isClassMethod, $node); - $needsReturnVars = ($hasParam && ($paramCount > 0) && ( - $hasInheritance || str_contains($docText, ' is ') || ($hasReturnDoc && str_contains($docText, '$')) - )) || ($isClassMethod && $paramCount > 0 && ($isMagicGet || $isMagicCall)); - - $useDynamicMethodKey = $isClassMethod && ! $isPrivate && ! $isFinalClass; - $phpDocNode = null; $returnTypeNode = null; $hasMethodTemplates = false; $declaredTemplates = []; + $paramTags = []; + $paramOutTags = []; + $selfOutType = null; + if ($doc !== null) { try { $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); @@ -165,6 +113,9 @@ public static function inject( } $declaredTemplates = DocblockExtractor::extractTemplates($phpDocNode); $hasMethodTemplates = $declaredTemplates !== []; + $paramTags = DocblockExtractor::getParamTags($phpDocNode); + $paramOutTags = DocblockExtractor::getParamOutTags($phpDocNode); + $selfOutType = DocblockExtractor::getSelfOutTag($phpDocNode); } catch (\Throwable) { } } @@ -179,16 +130,73 @@ public static function inject( /** @var array $resolvedParamTypes */ $resolvedParamTypes = []; - if ($phpDocNode !== null) { - foreach (DocblockExtractor::getParamTags($phpDocNode) as $pName => $pTag) { - $pType = $pTag->type; - if ($effectiveAliases !== []) { - $pType = DocblockParser::substituteAliases($pType, $effectiveAliases); - } - $resolvedParamTypes[$pName] = $pType; + foreach ($paramTags as $pName => $pTag) { + $pType = $pTag->type; + if ($effectiveAliases !== []) { + $pType = DocblockParser::substituteAliases($pType, $effectiveAliases); + } + $resolvedParamTypes[$pName] = $pType; + } + + if ($returnTypeNode !== null && $effectiveAliases !== []) { + $returnTypeNode = DocblockParser::substituteAliases($returnTypeNode, $effectiveAliases); + } + + $hasReturnDoc = $returnTypeNode !== null; + + $hasReturn = ! $isMagicLifecycle + && ! $isNativeNever + && ! ($isNativeVoid && ! $hasReturnDoc) + && ($isMagicGet || $isMagicCall || self::hasReturnContracts( + $returnTypeNode, + $isClassMethod, + $hasInheritance, + $isPrivate, + $classContext === null, + )); + + $byRefParams = []; + foreach ($node->params as $p) { + if ($p->byRef && $p->var instanceof Node\Expr\Variable && \is_string($p->var->name)) { + $byRefParams[] = $p->var->name; } } + $hasParamOutDoc = $paramOutTags !== []; + $hasParamOut = $byRefParams !== [] && ($hasParamOutDoc || $hasInheritance); + + $hasSelfOutDoc = $selfOutType !== null; + $hasSelfOut = $isClassMethod && ! $node->isStatic() && ($hasSelfOutDoc || ($hasClassTemplates && $hasRealInheritance)); + + $isDirectUnitTest = ($classContext === null); + $hasParam = ($isMagicGet || $isMagicCall) + || ($isDirectUnitTest && $isClassMethod) + || ($paramCount > 0 && ( + $hasParamOutDoc + || ($returnTypeNode !== null && ConditionalChecker::containsConditional($returnTypeNode)) + || ($selfOutType !== null && ConditionalChecker::containsConditional($selfOutType)) + || ($isClassMethod && $hasInheritance && ! $isPrivate) + || $hasMethodTemplates + || $node->attrGroups !== [] + || self::hasParamDocContracts($resolvedParamTypes) + || ($isConstructor && $hasPropertyWithDoc) + )); + + if (! $hasParam && ! $hasReturn && ! $hasParamOut && ! $hasSelfOut) { + return; + } + + $thisArg = self::resolveThisArg($isClassMethod, $node); + + $needsReturnVars = ($hasParam && $paramCount > 0 && ( + ($isClassMethod && $hasInheritance) + || ($returnTypeNode !== null && ConditionalChecker::containsConditional($returnTypeNode)) + || ($selfOutType !== null && ConditionalChecker::containsConditional($selfOutType)) + || $hasParamOut + || ($isClassMethod && ($isMagicGet || $isMagicCall)) + )); + + $useDynamicMethodKey = $isClassMethod && ! $isPrivate && ! $isFinalClass; $isTrait = $classContext['isTrait'] ?? false; if ( @@ -204,7 +212,6 @@ public static function inject( && self::canEliminateSetupScope( $node, $phpDocNode, - $docText, $isClassMethod, $isPrivate, $hasRealInheritance, @@ -226,7 +233,6 @@ public static function inject( if ($hasParam) { $injectedStmts = self::buildParamInjections( $node->params, - $docText, $thisArg, $isReadonlyClass, $needsReturnVars, @@ -286,7 +292,6 @@ public static function inject( private static function canEliminateSetupScope( Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?PhpDocNode $phpDocNode, - string $docText, bool $isClassMethod, bool $isPrivate, bool $hasRealInheritance, @@ -299,7 +304,7 @@ private static function canEliminateSetupScope( return false; } - if ($node->attrGroups !== [] || str_contains($docText, ' is ')) { + if ($node->attrGroups !== []) { return false; } @@ -319,13 +324,9 @@ private static function canEliminateSetupScope( } $pName = $param->var->name; - $resolvedType = $resolvedParamTypes[$pName] ?? null; - $paramDoc = $param->getDocComment() !== null ? $param->getDocComment()->getText() : ''; - $effectiveDoc = $docText . ' ' . $paramDoc; - if ( - self::isCallableCandidate($param, $effectiveDoc, $resolvedType, $effectiveTemplates) - || self::isIterableCandidate($param, $effectiveDoc, $resolvedType, $effectiveTemplates) - ) { + $pTypeNode = $resolvedParamTypes[$pName] ?? null; + + if (self::isCallableCandidate($param, $pTypeNode, $effectiveTemplates) || self::isIterableCandidate($param, $pTypeNode, $effectiveTemplates)) { return false; } @@ -339,7 +340,7 @@ private static function canEliminateSetupScope( continue; } - if (! self::nativeParamSatisfiesDocType($param->type, $resolvedType ?? $paramTag->type)) { + if (! self::nativeParamSatisfiesDocType($param->type, $paramTag->type)) { return false; } } @@ -800,65 +801,39 @@ private static function resolveDocComment( return null; } - private static function hasParamContracts( - string $docText, + private static function hasReturnContracts( + ?TypeNode $returnTypeNode, bool $isClassMethod, bool $hasInheritance, - int $paramCount, bool $isPrivate, - bool $isConstructor, - bool $hasPropertyWithDoc, - bool $isDirectUnitTest, - bool $hasAttributes = false + bool $isDirectUnitTest = false, ): bool { - if ($paramCount === 0 && ! str_contains($docText, '@template')) { - return $isDirectUnitTest && $isClassMethod; - } - if ($isDirectUnitTest && $isClassMethod) { return true; } - if ($isConstructor && $docText === '' && ! $hasPropertyWithDoc) { - return false; + if ($returnTypeNode !== null) { + return ! self::isUnconstrainedDocType($returnTypeNode); } - if ($isPrivate && $docText === '' && ! ($isConstructor && $hasPropertyWithDoc)) { + if (! $isClassMethod) { return false; } - if (! $hasInheritance && $docText === '' && ! ($isConstructor && $hasPropertyWithDoc) && ! $hasAttributes) { + if (! $hasInheritance) { return false; } - if (str_contains($docText, '@template') || str_contains($docText, '@phpstan-param') || str_contains($docText, '@psalm-param')) { - return true; - } - - if (str_contains($docText, '@param')) { - return self::hasNonMixedParam($docText); - } - - return $isClassMethod && (! $isPrivate || ($isConstructor && $hasPropertyWithDoc)); + return ! $isPrivate; } - private static function hasNonMixedParam(string $docText): bool + /** + * @param array $resolvedParamTypes + */ + private static function hasParamDocContracts(array $resolvedParamTypes): bool { - if ((int) preg_match_all('/@param\s+([^\s$]+)/', $docText, $matches) === 0) { - return false; - } - - foreach ($matches[1] as $typeStr) { - $unionParts = explode('|', $typeStr); - $hasMixed = false; - foreach ($unionParts as $part) { - if (strtolower(trim($part)) === 'mixed') { - $hasMixed = true; - - break; - } - } - if (! $hasMixed) { + foreach ($resolvedParamTypes as $typeNode) { + if (! self::isUnconstrainedDocType($typeNode)) { return true; } } @@ -866,51 +841,21 @@ private static function hasNonMixedParam(string $docText): bool return false; } - private static function hasReturnContracts( - string $docText, - bool $isClassMethod, - bool $hasInheritance, - bool $isPrivate, - bool $isDirectUnitTest = false, - ): bool { - if ($isDirectUnitTest && $isClassMethod) { - return true; - } - - if ($isPrivate && $docText === '') { - return false; - } - - if ( - str_contains($docText, '@template') - || str_contains($docText, '@phpstan-return') - || str_contains($docText, '@psalm-return') - || str_contains($docText, '$this') - ) { - return true; + private static function isUnconstrainedDocType(TypeNode $typeNode): bool + { + if ($typeNode instanceof IdentifierTypeNode) { + return strtolower($typeNode->name) === 'mixed'; } - if (preg_match('/@return\s+([^\s]+)/', $docText, $matches) === 1) { - $returnTypeStr = $matches[1]; - $unionParts = explode('|', $returnTypeStr); - foreach ($unionParts as $part) { - if (strtolower(trim($part)) === 'mixed') { - return false; + if ($typeNode instanceof UnionTypeNode) { + foreach ($typeNode->types as $member) { + if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'mixed') { + return true; } } - - return true; } - if (! $isClassMethod) { - return false; - } - - if (! $hasInheritance) { - return false; - } - - return ! $isPrivate; + return false; } private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_|Node\Stmt\ClassMethod $node): Node\Expr @@ -964,7 +909,6 @@ public function enterNode(Node $n): ?int */ private static function buildParamInjections( array $params, - string $docText, Node\Expr $thisArg, bool $isReadonlyClass = false, bool $needsReturnVars = false, @@ -973,8 +917,8 @@ private static function buildParamInjections( array $effectiveTemplates = [] ): array { $setupScopeStmts = self::buildSetupScopeStmt($params, $thisArg, $needsReturnVars, $useDynamicMethodKey); - $callableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isCallableCandidate'], 'wrapCallable', $isReadonlyClass, $resolvedParamTypes, $effectiveTemplates); - $iterableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isIterableCandidate'], 'wrapIterable', $isReadonlyClass, $resolvedParamTypes, $effectiveTemplates); + $callableWrappers = self::buildParamWrappers($params, $thisArg, [self::class, 'isCallableCandidate'], 'wrapCallable', $isReadonlyClass, $resolvedParamTypes, $effectiveTemplates); + $iterableWrappers = self::buildParamWrappers($params, $thisArg, [self::class, 'isIterableCandidate'], 'wrapIterable', $isReadonlyClass, $resolvedParamTypes, $effectiveTemplates); return [...$setupScopeStmts, ...$callableWrappers, ...$iterableWrappers]; } @@ -1128,7 +1072,7 @@ public static function buildParamOutCheckStmts( /** * @param array $params - * @param callable(Node\Param, string, ?TypeNode, array): bool $predicate + * @param callable(Node\Param, ?TypeNode, array): bool $predicate * @param array $resolvedParamTypes * @param array $effectiveTemplates * @@ -1136,7 +1080,6 @@ public static function buildParamOutCheckStmts( */ private static function buildParamWrappers( array $params, - string $docText, Node\Expr $thisArg, callable $predicate, string $wrapperMethod, @@ -1148,11 +1091,13 @@ private static function buildParamWrappers( foreach ($params as $param) { $paramName = $param->var instanceof Node\Expr\Variable && \is_string($param->var->name) ? $param->var->name : ''; - $resolvedType = $paramName !== '' ? ($resolvedParamTypes[$paramName] ?? null) : null; - $paramDoc = $param->getDocComment() !== null ? $param->getDocComment()->getText() : ''; - $effectiveDoc = $docText . ' ' . $paramDoc; + if ($paramName === '') { + continue; + } + + $paramTypeNode = $resolvedParamTypes[$paramName] ?? null; - if ($paramName !== '' && $predicate($param, $effectiveDoc, $resolvedType, $effectiveTemplates)) { + if ($predicate($param, $paramTypeNode, $effectiveTemplates)) { $assignExpr = new Node\Expr\Assign( new Node\Expr\Variable($paramName), new Node\Expr\FuncCall( @@ -1270,7 +1215,6 @@ private static function paramMayBeArray(Node\Param $param): bool */ private static function isCallableCandidate( Node\Param $param, - string $docText, ?TypeNode $resolvedParamType = null, array $effectiveTemplates = [] ): bool { @@ -1282,10 +1226,12 @@ private static function isCallableCandidate( return self::typeNodeContainsCallable($resolvedParamType, $effectiveTemplates); } - return str_contains($docText, 'callable') - || str_contains($docText, 'Closure') - || str_contains($docText, 'pure-callable') - || str_contains($docText, 'static-closure'); + $paramDoc = $param->getDocComment()?->getText() ?? ''; + if ($paramDoc !== '') { + return str_contains($paramDoc, 'callable') || str_contains($paramDoc, 'Closure'); + } + + return false; } /** @@ -1293,7 +1239,6 @@ private static function isCallableCandidate( */ private static function isIterableCandidate( Node\Param $param, - string $docText, ?TypeNode $resolvedParamType = null, array $effectiveTemplates = [] ): bool { @@ -1305,9 +1250,9 @@ private static function isIterableCandidate( return self::typeNodeContainsIterable($resolvedParamType, $effectiveTemplates); } - $paramName = $param->var instanceof Node\Expr\Variable && \is_string($param->var->name) ? $param->var->name : ''; - if ($paramName !== '' && preg_match('/@(?:param|phpstan-param|psalm-param)\s+[^\$]*?\b(?:iterable|Traversable|Generator|Iterator|IteratorAggregate)\b[^\$]*?\$' . preg_quote($paramName, '/') . '\b/i', $docText) === 1) { - return true; + $paramDoc = $param->getDocComment()?->getText() ?? ''; + if ($paramDoc !== '') { + return (bool) preg_match('/\b(?:iterable|Traversable|Generator|Iterator|IteratorAggregate)\b/i', $paramDoc); } return false; diff --git a/src/Internal/Docblock/DocblockNormalizer.php b/src/Internal/Docblock/DocblockNormalizer.php index 328afa0b..232639c4 100644 --- a/src/Internal/Docblock/DocblockNormalizer.php +++ b/src/Internal/Docblock/DocblockNormalizer.php @@ -36,6 +36,14 @@ public static function normalize(string $doc): string return $doc; } + if (str_contains($doc, "\n")) { + $doc = preg_replace( + '/(@(?:phpstan-|psalm-)?(?:param-out|param|return|var|self-out|this-out|throws))[ \t]*\r?\n[ \t]*\*[ \t]+(?![@*\/])/m', + '$1 ', + $doc + ) ?? $doc; + } + if (substr_count($doc, '@') > 1) { $doc = preg_replace_callback( '/(?:\/\*\*|^\s*\*)\s*@[a-zA-Z0-9_-]+[^\r\n]*/m', diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index da2b5f96..41ca63a4 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -16,7 +16,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.14.1_'; + public const VERSION_PREFIX = 'v0.14.2_'; /** * Config keys that only steer runtime behaviour and never change the transformed source. diff --git a/tests/Internal/Ast/FunctionContractInjectorTest.php b/tests/Internal/Ast/FunctionContractInjectorTest.php index dd79d974..a737b3b5 100644 --- a/tests/Internal/Ast/FunctionContractInjectorTest.php +++ b/tests/Internal/Ast/FunctionContractInjectorTest.php @@ -88,13 +88,39 @@ public function dd(): never expect($fn->stmts)->not()->toBeEmpty(); + $setupIf = $fn->stmts[0]; + expect($setupIf)->toBeInstanceOf(Node\Stmt\If_::class) + ->and($setupIf->getAttribute('typephp_injected'))->toBeTrue() + ->and($setupIf->stmts[0])->toBeInstanceOf(Node\Stmt\Expression::class) + ->and($setupIf->stmts[0]->expr)->toBeInstanceOf(Node\Expr\Assign::class) + ->and($setupIf->stmts[0]->expr->var->name)->toBe('_typephpArgs') + ->and($fn->stmts[1])->toBeInstanceOf(Node\Stmt\Return_::class) + ; + }); + + test('hoists _typephpArgs to root when return type contains parameter-dependent conditional type', function () { + $doc = new Doc('/** @param int $id @return ($id is positive-int ? non-empty-string : string) */'); + + $fn = new Node\Stmt\Function_('testConditionalUser', [ + 'params' => [ + new Node\Param(new Node\Expr\Variable('id'), null, new Node\Identifier('int')), + ], + 'stmts' => [ + new Node\Stmt\Return_(new Node\Scalar\String_('alice')), + ], + ], [ + 'comments' => [$doc], + ]); + + FunctionContractInjector::inject($fn); + $firstStmt = $fn->stmts[0]; expect($firstStmt)->toBeInstanceOf(Node\Stmt\Expression::class) ->and($firstStmt->getAttribute('typephp_injected'))->toBeTrue() ->and($firstStmt->expr)->toBeInstanceOf(Node\Expr\Assign::class) ->and($firstStmt->expr->var->name)->toBe('_typephpArgs') ->and($fn->stmts[1])->toBeInstanceOf(Node\Stmt\If_::class) - ->and($fn->stmts[1]->getAttribute('typephp_injected'))->toBeTrue() + ->and($fn->stmts[2])->toBeInstanceOf(Node\Stmt\Return_::class) ; }); @@ -130,7 +156,10 @@ public function dd(): never FunctionContractInjector::inject($fn); - expect(\count($fn->stmts))->toBe(2); + expect(\count($fn->stmts))->toBe(1) + ->and($fn->stmts[0])->toBeInstanceOf(Node\Stmt\If_::class) + ->and($fn->stmts[0]->getAttribute('typephp_injected'))->toBeTrue() + ; }); }); diff --git a/tests/TypeChecking/Boundaries/Priority4BugsTest.php b/tests/TypeChecking/Boundaries/Priority4BugsTest.php new file mode 100644 index 00000000..ac90a071 --- /dev/null +++ b/tests/TypeChecking/Boundaries/Priority4BugsTest.php @@ -0,0 +1,369 @@ +toBe(-1) + ->and(\App\Priority4\TryCatchScopeFixture::tryAndCatchToFinally())->toBe('-10:') + ->and(fn () => \App\Priority4\TryCatchScopeFixture::ownCatchBlockStillEnforced()) + ->toThrow(TypeError::class, 'positive-int') + ->and(fn () => \App\Priority4\TryCatchScopeFixture::outerScopeStillEnforcedInCatch()) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('does not bleed @var between switch cases or after switch statement', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p4_switch_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/switch_scopes.php'; + + $code = <<<'PHP' +toBe(-99) + ->and(\App\Priority4\SwitchScopeFixture::siblingCases(3))->toBe(0) + ->and(\App\Priority4\SwitchScopeFixture::afterSwitch(1))->toBe(-1) + ->and(fn () => \App\Priority4\SwitchScopeFixture::ownCaseStillEnforced()) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('does not bleed @var from if branch into elseif or else branches', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p4_if_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/if_scopes.php'; + + $code = <<<'PHP' +toBe(10) + ->and(\App\Priority4\IfElseScopeFixture::pick(2))->toBe(-2) + ->and(\App\Priority4\IfElseScopeFixture::pick(3))->toBe(-3) + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); + + describe('Bug 10: Docblock Prose Heuristics & Multi-Line Tags in FunctionContractInjector', function () { + test('does not inject wrapCallable or setupScope when prose mentions callable, Closure, or $this', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::wrapCallable') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::setupScope') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ; + }); + + test('enforces real @return tag even when prose contains @return mixed earlier in the docblock', function () { + $tempDir = sys_get_temp_dir() . '/typephp_p4_prose_ret_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/prose_return.php'; + + $code = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + + file_put_contents($filePath, $code); + + try { + StreamWrapper::register(); + require $filePath; + + expect(fn () => \App\Priority4\getTightenedPositive()) + ->toThrow(TypeError::class, 'positive-int') + ->and(fn () => \App\Priority4\getMultilinePositive()) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('does not inject unnecessary setupScope, wrapIterable, or checkSelfOut from prose keywords', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::wrapIterable') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::setupScope') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkSelfOut') + ; + }); + }); +});