diff --git a/.gitignore b/.gitignore index 5b39fba8..4f6aca70 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,5 @@ index.php benchmark.php .php-cs-fixer.cache /app -/coverage-report \ No newline at end of file +/coverage-report +/coverage \ No newline at end of file diff --git a/composer.json b/composer.json index 42aed6a8..4c3f6e19 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,6 @@ "nikic/php-parser": "^5.3" }, "require-dev": { - "roave/security-advisories": "dev-latest", "laravel/pint": "^1.10", "pestphp/pest": "^2.0 || ^3.0 || ^4.0", "phpstan/phpstan": "^2.1", diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 1e8cfbb1..90579437 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -5,15 +5,18 @@ namespace TypePHP\Internal\Ast; use PhpParser\Node; +use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Parser\TokenIterator; +use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StubManager; @@ -43,12 +46,17 @@ final class ContractVisitor extends NodeVisitorAbstract */ private static array $parsedShapeCache = []; + /** + * @var array> + */ + private array $localClassPropertyTypes = []; + private ScopeManager $scopeManager; private string $currentNamespace = ''; /** - * @var list + * @var list */ private array $classStack = []; @@ -74,7 +82,7 @@ final class ContractVisitor extends NodeVisitorAbstract */ private array $byRefStack = []; - public function __construct() + public function __construct(private string $currentFile = '') { $this->scopeManager = new ScopeManager(); } @@ -94,6 +102,7 @@ public function enterNode(Node $node): ?array if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) { $this->scopeManager->pushScope(isIsolated: true); + $this->registerParamInferredTypes($node->params); } elseif ($node instanceof Node\Expr\Closure) { $capturedVars = []; foreach ($node->uses as $u) { @@ -106,6 +115,7 @@ public function enterNode(Node $node): ?array } } $this->scopeManager->pushScope(isIsolated: true, initialBindings: $capturedVars); + $this->registerParamInferredTypes($node->params); } elseif ($this->isSoftScopeBoundary($node)) { $this->scopeManager->pushScope(isIsolated: false); } @@ -120,6 +130,9 @@ public function enterNode(Node $node): ?array } 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\Expr\Isset_) { foreach ($node->vars as $v) { @@ -135,7 +148,7 @@ public function enterNode(Node $node): ?array if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) { $classContext = $this->classStack !== [] ? end($this->classStack) : null; - FunctionContractInjector::inject($node, $classContext); + FunctionContractInjector::inject($node, $classContext, $this->currentFile); return null; } @@ -172,11 +185,15 @@ public function enterNode(Node $node): ?array $this->scopeManager->extractVarDocblock($doc->getText(), $node->valueVar); } + $this->handleForeachTypePropagation($node); + return null; } if ($node instanceof Node\Expr\Assign) { $this->handleAssign($node); + } elseif ($node instanceof Node\Expr\AssignRef) { + $this->handleAssignRef($node); } return null; @@ -184,8 +201,10 @@ public function enterNode(Node $node): ?array /** * Pops the current lexical scope stack frame or replaces transformed expressions upon leaving a node. + * + * @return Node|array|null */ - public function leaveNode(Node $node): ?Node + public function leaveNode(Node $node): Node|array|null { $this->trackDeclarationExit($node); @@ -227,9 +246,7 @@ public function leaveNode(Node $node): ?Node if ($node->getAttribute('typephp_checked') !== true && $node->getAttribute('typephp_write_context') !== true) { $node->setAttribute('typephp_checked', true); - $classArg = $node->class instanceof Node\Name - ? new Node\Expr\ClassConstFetch($node->class, 'class') - : $node->class; + $classArg = $this->resolveStaticClassArg($node->class); return new Node\Expr\StaticCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker'), @@ -245,6 +262,15 @@ public function leaveNode(Node $node): ?Node } } + if ($node instanceof Node\Stmt\Foreach_ && $node->byRef) { + $boundaryCheck = $this->createForeachBoundaryCheck($node); + if ($this->isScopeBoundary($node)) { + $this->scopeManager->popScope(); + } + + return $boundaryCheck !== null ? [$node, $boundaryCheck] : null; + } + if ($this->isScopeBoundary($node)) { $this->scopeManager->popScope(); } @@ -252,6 +278,75 @@ public function leaveNode(Node $node): ?Node return null; } + private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stmt\Expression + { + $targetVarExpr = null; + $varName = null; + $typeString = null; + + if ($node->expr instanceof Node\Expr\Variable && \is_string($node->expr->name)) { + $varName = $node->expr->name; + $typeString = $this->scopeManager->getVarTypeFromScope($varName); + $targetVarExpr = $node->expr; + } elseif (($chainInfo = $this->extractMemberChain($node->expr)) !== null) { + $root = $chainInfo['root']; + if ($root instanceof Node\Expr\Variable && \is_string($root->name)) { + $varName = $root->name; + $typeString = $this->scopeManager->getVarTypeFromScope($varName); + $targetVarExpr = $root; + } + } + + if ($targetVarExpr === null || $varName === null || $typeString === null) { + return null; + } + + if (Config::isEliminateStaticallyProvenChecksEnabled() && self::isLoopBodyFreeOfOpaqueMutations($node)) { + return null; + } + + $line = $node->getEndLine() > 0 ? $node->getEndLine() : $node->getStartLine(); + $checkStmt = new Node\Stmt\Expression( + new Node\Expr\Assign( + $targetVarExpr, + $this->wrapVariableCheck($targetVarExpr, $typeString, $varName, $line) + ) + ); + $checkStmt->setAttribute('typephp_injected', true); + + return $checkStmt; + } + + private static function isLoopBodyFreeOfOpaqueMutations(Node\Stmt\Foreach_ $node): bool + { + $visitor = new class () extends NodeVisitorAbstract { + public bool $hasOpaqueCalls = false; + + public function enterNode(Node $n): ?int + { + if ($n instanceof Node\Expr\Closure || $n instanceof Node\Expr\ArrowFunction) { + $this->hasOpaqueCalls = true; + + return NodeTraverser::DONT_TRAVERSE_CHILDREN; + } + + if ($n instanceof Node\Expr\CallLike || $n instanceof Node\Expr\AssignRef) { + $this->hasOpaqueCalls = true; + + return NodeTraverser::STOP_TRAVERSAL; + } + + return null; + } + }; + + $traverser = new NodeTraverser(); + $traverser->addVisitor($visitor); + $traverser->traverse($node->stmts); + + return ! $visitor->hasOpaqueCalls; + } + private function wrapCloneFunction(Node\Expr\FuncCall $node): ?Node\Expr { if ($node->getAttribute('typephp_wrapped') === true) { @@ -318,35 +413,7 @@ private function processClassPropertyDefaults(Node\Stmt\Class_ $node): void $defaultProps = []; $hasConstructor = false; - - $classTemplates = []; - $nodeDoc = $node->getDocComment(); - if ($nodeDoc !== null && (str_contains($nodeDoc->getText(), '@template') || str_contains($nodeDoc->getText(), '@phpstan-template') || str_contains($nodeDoc->getText(), '@psalm-template'))) { - try { - $phpDocNode = DocblockExtractor::parseDocString($nodeDoc->getText()); - $classTemplates = DocblockExtractor::extractTemplates($phpDocNode); - } catch (\Throwable) { - } - } - - if ($node->name !== null) { - $className = $this->resolveQualifiedName($node->name); - if ($className !== null) { - try { - $loadedTemplates = DocblockParser::parseClassTemplates($className); - $classTemplates = [...$classTemplates, ...$loadedTemplates]; - } catch (\Throwable) { - } - } - } - - if ($node->extends !== null) { - try { - $parentTemplates = DocblockParser::parseClassTemplates($node->extends->toString()); - $classTemplates = [...$classTemplates, ...$parentTemplates]; - } catch (\Throwable) { - } - } + $classTemplates = null; foreach ($node->stmts as $stmt) { if ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') { @@ -358,25 +425,44 @@ private function processClassPropertyDefaults(Node\Stmt\Class_ $node): void $doc = $stmt->getDocComment(); if ($doc !== null && str_contains($doc->getText(), '@var') && ! str_contains($doc->getText(), '@typephp-ignore')) { - if ($classTemplates !== []) { - $varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText()); - if ($varTag !== null) { - try { - [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); - $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($varTag[0]))); - $propTypeNode = $typeParser->parse($tokens); + $hasNonNullDefault = false; + foreach ($stmt->props as $p) { + $isExplicitNull = $p->default instanceof Node\Expr\ConstFetch && strtolower($p->default->name->toString()) === 'null'; + if ($p->default !== null && ! $isExplicitNull) { + $hasNonNullDefault = true; - if (DocblockParser::typeReferencesTemplate($propTypeNode, $classTemplates)) { - continue; - } - } catch (\Throwable) { + break; + } + } + + if (! $hasNonNullDefault) { + continue; + } + + $classTemplates ??= $this->resolveClassTemplatesForDefaults($node); + + $propTypeNode = null; + $varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText()); + if ($varTag !== null) { + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($varTag[0]))); + $propTypeNode = $typeParser->parse($tokens); + + if ($classTemplates !== [] && DocblockParser::typeReferencesTemplate($propTypeNode, $classTemplates)) { + continue; } + } catch (\Throwable) { } } 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)) { + continue; + } + $defaultProps[] = [ 'name' => $p->name->toString(), 'line' => $p->getStartLine(), @@ -438,6 +524,45 @@ private function processClassPropertyDefaults(Node\Stmt\Class_ $node): void } } + /** + * @return array + */ + private function resolveClassTemplatesForDefaults(Node\Stmt\Class_ $node): array + { + $classTemplates = []; + $nodeDoc = $node->getDocComment(); + if ($nodeDoc !== null && (str_contains($nodeDoc->getText(), '@template') || str_contains($nodeDoc->getText(), '@phpstan-template') || str_contains($nodeDoc->getText(), '@psalm-template'))) { + try { + $phpDocNode = DocblockExtractor::parseDocString($nodeDoc->getText()); + $classTemplates = DocblockExtractor::extractTemplates($phpDocNode); + } catch (\Throwable) { + } + } + + if ($node->name !== null) { + $className = $this->resolveQualifiedName($node->name); + if ($className !== null && class_exists($className, false)) { + try { + $loadedTemplates = DocblockParser::parseClassTemplates($className); + $classTemplates = [...$classTemplates, ...$loadedTemplates]; + } catch (\Throwable) { + } + } + } + + if ($node->extends !== null) { + $parentClass = $this->resolveClassNameFromNode($node->extends) ?? $node->extends->toString(); + + try { + $parentTemplates = DocblockParser::parseClassTemplates($parentClass); + $classTemplates = [...$classTemplates, ...$parentTemplates]; + } catch (\Throwable) { + } + } + + return $classTemplates; + } + private function trackDeclarationEntry(Node $node): void { if ($node instanceof Node\Stmt\Namespace_) { @@ -485,6 +610,7 @@ private function trackDeclarationExit(Node $node): void private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\Trait_|Node\Stmt\Enum_ $node): void { $typeName = $this->resolveQualifiedName($node->name); + $shortName = $node->name !== null ? $node->name->toString() : null; $hasInheritance = true; $hasRealInheritance = false; $hasPropertyWithDoc = false; @@ -549,6 +675,41 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ ); } + if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) { + foreach ($node->stmts as $stmt) { + if ($stmt instanceof Node\Stmt\Property) { + $pDoc = $stmt->getDocComment(); + if ($pDoc !== null && str_contains($pDoc->getText(), '@var')) { + $varTag = DocblockExtractor::extractVarTagFromDoc($pDoc->getText()); + if ($varTag !== null) { + foreach ($stmt->props as $p) { + $propName = $p->name->toString(); + $this->localClassPropertyTypes[$typeName][$propName] = $varTag[0]; + if ($shortName !== null) { + $this->localClassPropertyTypes[$shortName][$propName] = $varTag[0]; + } + } + } + } + } elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') { + foreach ($stmt->params as $p) { + if ($p->isPromoted() && $p->var instanceof Node\Expr\Variable && \is_string($p->var->name)) { + $doc = $p->getDocComment(); + if ($doc !== null) { + $pType = DocblockExtractor::extractTypeFromPropertyDoc($doc->getText(), $p->var->name); + if ($pType !== null) { + $this->localClassPropertyTypes[$typeName][$p->var->name] = (string) $pType; + if ($shortName !== null) { + $this->localClassPropertyTypes[$shortName][$p->var->name] = (string) $pType; + } + } + } + } + } + } + } + } + $this->classStack[] = [ 'name' => $typeName, 'isAnonymous' => ($node instanceof Node\Stmt\Class_ && $node->name === null), @@ -609,7 +770,6 @@ private function handleExpression(Node\Stmt\Expression $node): ?array /** @var Node\Expr\List_|Node\Expr\Array_ $destructuringVar */ $destructuringVar = $node->expr->var; - // Auto-propagate types from RHS if it's a known ArrayShape in scope $rhs = $node->expr->expr; if ($rhs instanceof Node\Expr\Variable && \is_string($rhs->name)) { $sourceType = $this->scopeManager->getVarTypeFromScope($rhs->name); @@ -705,13 +865,11 @@ private function propagateShapeTypesToDestructuring(Node\Expr\List_|Node\Expr\Ar if ($targetVar instanceof Node\Expr\Variable && \is_string($targetVar->name)) { $this->scopeManager->registerVarType($targetVar->name, $fieldType); } elseif ($targetVar instanceof Node\Expr\List_ || $targetVar instanceof Node\Expr\Array_) { - // Recursively propagate nested shape fields $this->propagateShapeTypesToDestructuring($targetVar, $fieldType); } } } } catch (\Throwable $e) { - // Silently ignore parsing errors } } @@ -719,6 +877,16 @@ private function handleAssign(Node\Expr\Assign $node): void { if ($node->var instanceof Node\Expr\Variable && \is_string($node->var->name)) { $varName = $node->var->name; + + if ($node->expr instanceof Node\Expr\New_ && $node->expr->class instanceof Node\Name) { + $resolvedClass = $this->resolveClassNameFromNode($node->expr->class); + if ($resolvedClass !== null) { + $this->scopeManager->registerInferredVarType($varName, $resolvedClass); + } + } elseif (! ($node->expr instanceof Node\Expr\AssignRef)) { + $this->scopeManager->unregisterInferredVarType($varName); + } + $typeString = $this->scopeManager->getVarTypeFromScope($varName); if ($typeString !== null) { @@ -743,43 +911,124 @@ private function handleAssign(Node\Expr\Assign $node): void ...$constructorArgs, ] ); + + $node->expr = $this->wrapVariableCheck($expr, $typeString, $varName, $node->var->getStartLine()); + + return; + } + + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + $parsedType = $typeParser->parse($tokens); + + if (StaticTypeEvaluator::satisfies($expr, $parsedType, $this->currentFile)) { + return; + } + } catch (\Throwable) { } $node->expr = $this->wrapVariableCheck($expr, $typeString, $varName, $node->var->getStartLine()); + + return; } - } elseif (($chainInfo = $this->extractMemberChain($node->var)) !== null) { + } + + $wrapped = $this->wrapTargetMutation($node->var, $node->expr, $node->var->getStartLine()); + if ($wrapped !== null) { + $node->expr = $wrapped; + } + } + + private function handleAssignRef(Node\Expr\AssignRef $node): void + { + if (! ($node->var instanceof Node\Expr\Variable) || ! \is_string($node->var->name)) { + return; + } + + $aliasName = $node->var->name; + $deducedType = null; + + if ($node->expr instanceof Node\Expr\Variable && \is_string($node->expr->name)) { + $deducedType = $this->scopeManager->getVarTypeFromScope($node->expr->name) + ?? $this->scopeManager->getInferredVarType($node->expr->name); + } elseif (($chainInfo = $this->extractMemberChain($node->expr)) !== null) { $root = $chainInfo['root']; $chain = $chainInfo['chain']; + $currType = null; if ($root instanceof Node\Expr\Variable && \is_string($root->name)) { - $varName = $root->name; - $typeString = $this->scopeManager->getVarTypeFromScope($varName); + if ($root->name === 'this' && $this->classStack !== []) { + $classInfo = end($this->classStack); + $currType = $classInfo['name'] ?? null; + } else { + $currType = $this->scopeManager->getVarTypeFromScope($root->name) + ?? $this->scopeManager->getInferredVarType($root->name); + } + } elseif ($root instanceof Node\Name) { + $currType = $this->resolveClassNameFromNode($root); + } - if ($typeString !== null && $this->shouldHandleMemberAssignCheck($typeString, $chain)) { - $node->expr = $this->wrapMemberAssignCheck($node->expr, $root, $chain, $typeString, $varName, $node->var->getStartLine()); + if (\is_string($currType) && $currType !== '') { + $deducedType = $this->deduceMemberChainType($currType, $chain); + } + } - return; + if (\is_string($deducedType) && $deducedType !== '') { + $this->scopeManager->registerVarType($aliasName, $deducedType, overwrite: true); + } else { + $this->scopeManager->unregisterVarType($aliasName); + } + } + + private function handleForeachTypePropagation(Node\Stmt\Foreach_ $node): void + { + $containerType = null; + + if ($node->expr instanceof Node\Expr\Variable && \is_string($node->expr->name)) { + $containerType = $this->scopeManager->getVarTypeFromScope($node->expr->name) + ?? $this->scopeManager->getInferredVarType($node->expr->name); + } elseif (($chainInfo = $this->extractMemberChain($node->expr)) !== null) { + $root = $chainInfo['root']; + $chain = $chainInfo['chain']; + $currType = null; + + if ($root instanceof Node\Expr\Variable && \is_string($root->name)) { + if ($root->name === 'this' && $this->classStack !== []) { + $classInfo = end($this->classStack); + $currType = $classInfo['name'] ?? null; + } else { + $currType = $this->scopeManager->getVarTypeFromScope($root->name) + ?? $this->scopeManager->getInferredVarType($root->name); } + } elseif ($root instanceof Node\Name) { + $currType = $this->resolveClassNameFromNode($root); } - // Fallback for direct single property access - if ($node->var instanceof Node\Expr\PropertyFetch && $node->var->name instanceof Node\Identifier) { - $node->expr = $this->wrapPropertyCheck($node->expr, $node->var->var, $node->var->name->toString(), $node->var->getStartLine()); - } elseif ($node->var instanceof Node\Expr\StaticPropertyFetch && $node->var->name instanceof Node\VarLikeIdentifier) { - $classArg = $node->var->class instanceof Node\Name - ? new Node\Expr\ClassConstFetch($node->var->class, 'class') - : $node->var->class; + if (\is_string($currType) && $currType !== '') { + $containerType = $this->deduceMemberChainType($currType, $chain); + } + } + + if ($containerType === null) { + return; + } + + $elementType = TypeDeducer::deduceElementType($containerType); - $node->expr = $this->wrapPropertyCheck($node->expr, $classArg, $node->var->name->toString(), $node->var->getStartLine()); + if ($elementType !== null) { + if ($node->valueVar instanceof Node\Expr\Variable && \is_string($node->valueVar->name)) { + $this->scopeManager->registerVarType($node->valueVar->name, $elementType, overwrite: false); + } elseif ($this->isDestructuring($node->valueVar) && str_contains($elementType, '{')) { + /** @var Node\Expr\List_|Node\Expr\Array_ $destructuringVar */ + $destructuringVar = $node->valueVar; + $this->propagateShapeTypesToDestructuring($destructuringVar, $elementType); } - } elseif ($node->var instanceof Node\Expr\PropertyFetch && $node->var->name instanceof Node\Identifier) { - $node->expr = $this->wrapPropertyCheck($node->expr, $node->var->var, $node->var->name->toString(), $node->var->getStartLine()); - } elseif ($node->var instanceof Node\Expr\StaticPropertyFetch && $node->var->name instanceof Node\VarLikeIdentifier) { - $classArg = $node->var->class instanceof Node\Name - ? new Node\Expr\ClassConstFetch($node->var->class, 'class') - : $node->var->class; + } - $node->expr = $this->wrapPropertyCheck($node->expr, $classArg, $node->var->name->toString(), $node->var->getStartLine()); + if ($node->keyVar instanceof Node\Expr\Variable && \is_string($node->keyVar->name)) { + $keyType = TypeDeducer::deduceKeyType($containerType); + $this->scopeManager->registerVarType($node->keyVar->name, $keyType, overwrite: false); } } @@ -791,18 +1040,35 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr\Assign } $binaryExpr = new $binaryOpClass($node->var, $node->expr); + $wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine()); - if ($node->var instanceof Node\Expr\Variable && \is_string($node->var->name)) { - $varName = $node->var->name; + return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null; + } + + private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr\Assign + { + $isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc; + $binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class; + $binaryExpr = new $binaryClass($node->var, new Node\Scalar\LNumber(1)); + + $wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine()); + + return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null; + } + + /** + * Unifies wrapping of mutations across assignments, compound assignments, and increments/decrements. + */ + private function wrapTargetMutation(Node\Expr $target, Node\Expr $valueExpr, int $line): ?Node\Expr + { + if ($target instanceof Node\Expr\Variable && \is_string($target->name)) { + $varName = $target->name; $typeString = $this->scopeManager->getVarTypeFromScope($varName); if ($typeString !== null) { - return new Node\Expr\Assign( - $node->var, - $this->wrapVariableCheck($binaryExpr, $typeString, $varName, $node->var->getStartLine()) - ); + return $this->wrapVariableCheck($valueExpr, $typeString, $varName, $line); } - } elseif (($chainInfo = $this->extractMemberChain($node->var)) !== null) { + } elseif (($chainInfo = $this->extractMemberChain($target)) !== null) { $root = $chainInfo['root']; $chain = $chainInfo['chain']; @@ -811,117 +1077,165 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr\Assign $typeString = $this->scopeManager->getVarTypeFromScope($varName); if ($typeString !== null && $this->shouldHandleMemberAssignCheck($typeString, $chain)) { - return new Node\Expr\Assign( - $node->var, - $this->wrapMemberAssignCheck($binaryExpr, $root, $chain, $typeString, $varName, $node->var->getStartLine()) - ); + return $this->wrapMemberAssignCheck($valueExpr, $root, $chain, $typeString, $varName, $line); } } - if ($node->var instanceof Node\Expr\PropertyFetch && $node->var->name instanceof Node\Identifier) { - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $node->var->var, $node->var->name->toString(), $node->var->getStartLine()) - ); - } elseif ($node->var instanceof Node\Expr\StaticPropertyFetch && $node->var->name instanceof Node\VarLikeIdentifier) { - $classArg = $node->var->class instanceof Node\Name - ? new Node\Expr\ClassConstFetch($node->var->class, 'class') - : $node->var->class; - - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $classArg, $node->var->name->toString(), $node->var->getStartLine()) + if (($propDimInfo = $this->extractPropertyDimChain($target)) !== null) { + return $this->wrapPropertyMemberAssignCheck( + $valueExpr, + $propDimInfo['targetExpr'], + $propDimInfo['propName'], + $propDimInfo['chain'], + $line ); } - } elseif ($node->var instanceof Node\Expr\PropertyFetch && $node->var->name instanceof Node\Identifier) { - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $node->var->var, $node->var->name->toString(), $node->var->getStartLine()) - ); - } elseif ($node->var instanceof Node\Expr\StaticPropertyFetch && $node->var->name instanceof Node\VarLikeIdentifier) { - $classArg = $node->var->class instanceof Node\Name - ? new Node\Expr\ClassConstFetch($node->var->class, 'class') - : $node->var->class; - - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $classArg, $node->var->name->toString(), $node->var->getStartLine()) - ); + + if ($target instanceof Node\Expr\PropertyFetch && $target->name instanceof Node\Identifier) { + return $this->wrapPropertyCheck($valueExpr, $target->var, $target->name->toString(), $line); + } + + if ($target instanceof Node\Expr\StaticPropertyFetch && $target->name instanceof Node\VarLikeIdentifier) { + $classArg = $this->resolveStaticClassArg($target->class); + + return $this->wrapPropertyCheck($valueExpr, $classArg, $target->name->toString(), $line); + } + } elseif ($target instanceof Node\Expr\PropertyFetch && $target->name instanceof Node\Identifier) { + return $this->wrapPropertyCheck($valueExpr, $target->var, $target->name->toString(), $line); + } elseif ($target instanceof Node\Expr\StaticPropertyFetch && $target->name instanceof Node\VarLikeIdentifier) { + $classArg = $this->resolveStaticClassArg($target->class); + + return $this->wrapPropertyCheck($valueExpr, $classArg, $target->name->toString(), $line); } return null; } - private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr\Assign + /** + * Deduces the type resulting from traversing an accessor chain. + * + * @param list $chain + */ + private function deduceMemberChainType(string $rootType, array $chain): ?string { - $isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc; - $binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class; - $binaryExpr = new $binaryClass($node->var, new Node\Scalar\LNumber(1)); + $deducedType = $rootType; - if ($node->var instanceof Node\Expr\Variable && \is_string($node->var->name)) { - $varName = $node->var->name; - $typeString = $this->scopeManager->getVarTypeFromScope($varName); + foreach ($chain as $step) { + if ($deducedType === '') { + return null; + } - if ($typeString !== null) { - return new Node\Expr\Assign( - $node->var, - $this->wrapVariableCheck($binaryExpr, $typeString, $varName, $node->var->getStartLine()) - ); + if ($step[0] === 'dim') { + $dimExpr = $step[1] instanceof Node\Expr ? $step[1] : null; + $deducedType = TypeDeducer::deduceDimType($deducedType, $dimExpr); + if ($deducedType === null) { + return null; + } + } elseif ($step[0] === 'prop' && \is_string($step[1])) { + $propName = $step[1]; + if (isset($this->localClassPropertyTypes[$deducedType][$propName])) { + $deducedType = $this->localClassPropertyTypes[$deducedType][$propName]; + } else { + $deducedType = TypeDeducer::deducePropertyType($deducedType, $propName); + } + if ($deducedType === null) { + return null; + } + } else { + return null; } - } elseif (($chainInfo = $this->extractMemberChain($node->var)) !== 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); + return $deducedType; + } - if ($typeString !== null && $this->shouldHandleMemberAssignCheck($typeString, $chain)) { - return new Node\Expr\Assign( - $node->var, - $this->wrapMemberAssignCheck($binaryExpr, $root, $chain, $typeString, $varName, $node->var->getStartLine()) - ); + /** + * Resolves a static class target into an expression for runtime inspection. + */ + private function resolveStaticClassArg(Node\Name|Node\Expr $class): Node\Expr + { + return $class instanceof Node\Name + ? new Node\Expr\ClassConstFetch($class, 'class') + : $class; + } + + /** + * Resolves a ClassName AST node into an FQCN string using file imports and namespace fallbacks. + */ + private function resolveClassNameFromNode(Node\Name $classNode): ?string + { + $rawClass = $classNode->toString(); + $lowerClass = strtolower($rawClass); + + if (($lowerClass === 'self' || $lowerClass === 'static') && $this->classStack !== []) { + $classInfo = end($this->classStack); + + return $classInfo['name'] ?? null; + } + + $resolved = $this->currentFile !== '' + ? SpecialTypeResolver::resolveFqcnForFile($rawClass, $this->currentFile, false) + : $rawClass; + + if ($resolved === $rawClass && $this->currentNamespace !== '' && ! str_contains($rawClass, '\\')) { + return $this->currentNamespace . '\\' . $rawClass; + } + + return $resolved !== '' ? $resolved : null; + } + + /** + * Registers typed function or method parameters in the inferred type stack. + * + * @param array $params + */ + private function registerParamInferredTypes(array $params): void + { + foreach ($params as $param) { + if ($param->var instanceof Node\Expr\Variable && \is_string($param->var->name) && $param->type instanceof Node\Name) { + $pClass = $this->resolveClassNameFromNode($param->type); + if ($pClass !== null) { + $this->scopeManager->registerInferredVarType($param->var->name, $pClass); } } + } + } - if ($node->var instanceof Node\Expr\PropertyFetch && $node->var->name instanceof Node\Identifier) { - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $node->var->var, $node->var->name->toString(), $node->var->getStartLine()) - ); - } elseif ($node->var instanceof Node\Expr\StaticPropertyFetch && $node->var->name instanceof Node\VarLikeIdentifier) { - $classArg = $node->var->class instanceof Node\Name - ? new Node\Expr\ClassConstFetch($node->var->class, 'class') - : $node->var->class; - - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $classArg, $node->var->name->toString(), $node->var->getStartLine()) - ); + /** + * Converts a member accessor chain into an AST Array_ of tuples (kind, dimExpr). + * + * @param list $chain + */ + private function buildChainAst(array $chain): Node\Expr\Array_ + { + $chainItems = []; + 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')); + } elseif (\is_string($step[1])) { + $dimExpr = new Node\Scalar\String_($step[1]); + } elseif ($step[1] instanceof Node\Expr) { + $dimExpr = $step[1]; + } else { + $dimExpr = new Node\Scalar\String_(''); } - } elseif ($node->var instanceof Node\Expr\PropertyFetch && $node->var->name instanceof Node\Identifier) { - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $node->var->var, $node->var->name->toString(), $node->var->getStartLine()) - ); - } elseif ($node->var instanceof Node\Expr\StaticPropertyFetch && $node->var->name instanceof Node\VarLikeIdentifier) { - $classArg = $node->var->class instanceof Node\Name - ? new Node\Expr\ClassConstFetch($node->var->class, 'class') - : $node->var->class; - - return new Node\Expr\Assign( - $node->var, - $this->wrapPropertyCheck($binaryExpr, $classArg, $node->var->name->toString(), $node->var->getStartLine()) + + $chainItems[] = new Node\ArrayItem( + new Node\Expr\Array_([ + new Node\ArrayItem($kind), + new Node\ArrayItem($dimExpr), + ]) ); } - return null; + return new Node\Expr\Array_($chainItems); } /** * Unpacks any nested chain of ArrayDimFetch and PropertyFetch down to its root expression. * - * @return array{root: Node\Expr, chain: list}|null + * @return array{root: Node\Expr|Node\Name, chain: list}|null */ private function extractMemberChain(Node\Expr $target): ?array { @@ -942,6 +1256,11 @@ private function extractMemberChain(Node\Expr $target): ?array } } + if ($curr instanceof Node\Expr\StaticPropertyFetch && $curr->name instanceof Node\VarLikeIdentifier) { + array_unshift($chain, ['prop', $curr->name->toString()]); + $curr = $curr->class; + } + if ($chain === []) { return null; } @@ -957,6 +1276,10 @@ private function extractMemberChain(Node\Expr $target): ?array */ private function shouldHandleMemberAssignCheck(string $typeString, array $chain): bool { + if (($chain[0][0] ?? null) === 'prop') { + return str_contains($typeString, '{'); + } + foreach ($chain as $step) { if ($step[0] === 'dim') { return true; @@ -966,6 +1289,62 @@ private function shouldHandleMemberAssignCheck(string $typeString, array $chain) return str_contains($typeString, '{'); } + /** + * Unpacks array dimension fetches rooted at an instance or static property. + * + * @return array{targetExpr: Node\Expr, propName: string, chain: list}|null + */ + private function extractPropertyDimChain(Node\Expr $target): ?array + { + if (! ($target instanceof Node\Expr\ArrayDimFetch)) { + return null; + } + + $curr = $target; + $chain = []; + + while ($curr instanceof Node\Expr\ArrayDimFetch) { + array_unshift($chain, ['dim', $curr->dim]); + $curr = $curr->var; + } + + if ($curr instanceof Node\Expr\PropertyFetch && $curr->name instanceof Node\Identifier) { + return [ + 'targetExpr' => $curr->var, + 'propName' => $curr->name->toString(), + 'chain' => $chain, + ]; + } + + if ($curr instanceof Node\Expr\StaticPropertyFetch && $curr->name instanceof Node\VarLikeIdentifier) { + $classArg = $this->resolveStaticClassArg($curr->class); + + return [ + 'targetExpr' => $classArg, + 'propName' => $curr->name->toString(), + 'chain' => $chain, + ]; + } + + return null; + } + + /** + * @param list $chain + */ + private function wrapPropertyMemberAssignCheck( + Node\Expr $valueExpr, + Node\Expr $targetExpr, + string $propName, + array $chain, + int $line + ): Node\Expr\Ternary { + $chainAst = $this->buildChainAst($chain); + $checkCall = NodeBuilder::createPropertyMemberAssignCheckCall($targetExpr, $propName, $chainAst, $valueExpr); + + return NodeBuilder::createTernaryThrowExpr($checkCall, $line); + } + /** * @param list $chain */ @@ -977,28 +1356,7 @@ private function wrapMemberAssignCheck( string $varName, int $line ): Node\Expr\Ternary { - $chainItems = []; - 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')); - } elseif (\is_string($step[1])) { - $dimExpr = new Node\Scalar\String_($step[1]); - } elseif ($step[1] instanceof Node\Expr) { - $dimExpr = $step[1]; - } else { - $dimExpr = new Node\Scalar\String_(''); - } - - $chainItems[] = new Node\ArrayItem( - new Node\Expr\Array_([ - new Node\ArrayItem($kind), - new Node\ArrayItem($dimExpr), - ]) - ); - } - - $chainAst = new Node\Expr\Array_($chainItems); + $chainAst = $this->buildChainAst($chain); $checkCall = NodeBuilder::createMemberAssignCheckCall( $rootExpr, diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php new file mode 100644 index 00000000..d0e20799 --- /dev/null +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -0,0 +1,149 @@ + + */ + private const PERMISSIBLE_NON_OBJECT_GENERICS = [ + 'int' => true, + 'integer' => true, + 'int-mask' => true, + 'int-mask-of' => true, + 'value-of' => true, + 'list' => true, + 'non-empty-list' => true, + 'array' => true, + 'non-empty-array' => true, + 'iterable' => true, + ]; + + /** + * O(1) hash map of permissible generator return type containers. + * + * @var array + */ + private const PERMISSIBLE_GENERATOR_GENERICS = [ + 'generator' => true, + 'iterable' => true, + 'traversable' => true, + 'iterator' => true, + ]; + + /** + * Determines whether a return check can be safely eliminated under LSP rules. + * + * Flow of logic: + * 1. Returns false if no return type is declared. + * 2. Rejects generic object classes (e.g. Collection) to ensure runtime + * WeakMap template bindings are preserved. Permits array containers (list, array) + * and scalar generics (int, int-mask) which carry no object state. + * 3. Authorizes standalone functions, closures, and arrow functions (zero inheritance risk). + * 4. For class methods: + * - Authorizes private methods (cannot override or be overridden). + * - Authorizes classes with no inheritance (`hasRealInheritance === false`). + * 5. Defers all other methods to runtime to prevent bypassing unanalyzed parent contracts. + * + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext + */ + public static function isReturnEliminationSafe( + ClassMethod|Function_|Closure|ArrowFunction $functionNode, + ?array $classContext, + ?TypeNode $returnTypeNode + ): bool { + if ($returnTypeNode === null) { + return false; + } + + if ($returnTypeNode instanceof GenericTypeNode) { + $baseName = strtolower($returnTypeNode->type->name); + if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) { + return false; + } + } + + if ($classContext === null || $functionNode instanceof Function_ || $functionNode instanceof Closure || $functionNode instanceof ArrowFunction) { + return true; + } + + if ($functionNode->isPrivate()) { + return true; + } + + $hasRealInheritance = $classContext['hasRealInheritance'] ?? true; + if (! $hasRealInheritance) { + return true; + } + + return false; + } + + /** + * Determines whether generator yield, send, and return checks can be safely eliminated under LSP rules. + * + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext + */ + public static function isGeneratorEliminationSafe( + ClassMethod|Function_|Closure|ArrowFunction $functionNode, + ?array $classContext, + ?TypeNode $returnTypeNode + ): bool { + if ($returnTypeNode === null) { + return false; + } + + if ($returnTypeNode instanceof GenericTypeNode) { + $baseName = strtolower(ltrim($returnTypeNode->type->name, '\\')); + if (! isset(self::PERMISSIBLE_GENERATOR_GENERICS[$baseName])) { + return false; + } + } elseif ($returnTypeNode instanceof IdentifierTypeNode) { + $baseName = strtolower(ltrim($returnTypeNode->name, '\\')); + if (! isset(self::PERMISSIBLE_GENERATOR_GENERICS[$baseName])) { + return false; + } + } elseif (! ($returnTypeNode instanceof ArrayTypeNode)) { + return false; + } + + if ($classContext === null || $functionNode instanceof Function_ || $functionNode instanceof Closure || $functionNode instanceof ArrowFunction) { + return true; + } + + if ($classContext['hasTemplates'] ?? false) { + return false; + } + + if ($functionNode->isPrivate()) { + return true; + } + + $hasRealInheritance = $classContext['hasRealInheritance'] ?? true; + if (! $hasRealInheritance) { + return true; + } + + return false; + } +} diff --git a/src/Internal/Ast/Elimination/Evaluator/ArithmeticEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArithmeticEvaluator.php new file mode 100644 index 00000000..9d49d7f7 --- /dev/null +++ b/src/Internal/Ast/Elimination/Evaluator/ArithmeticEvaluator.php @@ -0,0 +1,118 @@ +value; + } + + if ($expr instanceof DNumber) { + return $expr->value; + } + + if ($expr instanceof UnaryMinus) { + $inner = self::evaluate($expr->expr); + + return $inner !== null ? -$inner : null; + } + + if ($expr instanceof UnaryPlus) { + return self::evaluate($expr->expr); + } + + if ($expr instanceof BinaryOp) { + return self::evaluateBinaryOp($expr); + } + + return null; + } + + /** + * Computes the result of a binary arithmetic operation on folded operands. + */ + private static function evaluateBinaryOp(BinaryOp $expr): int|float|null + { + $left = self::evaluate($expr->left); + $right = self::evaluate($expr->right); + + if ($left === null || $right === null) { + return null; + } + + $result = match ($expr::class) { + BinaryOp\Plus::class => $left + $right, + BinaryOp\Minus::class => $left - $right, + BinaryOp\Mul::class => $left * $right, + BinaryOp\Div::class => self::divide($left, $right), + BinaryOp\Mod::class => self::modulo($left, $right), + BinaryOp\Pow::class => $left ** $right, + default => null, + }; + + if ($result === null || ! is_finite((float) $result)) { + return null; + } + + return $result; + } + + /** + * Safely executes division, guarding against division by zero. + */ + private static function divide(int|float $left, int|float $right): int|float|null + { + if (abs((float) $right) < self::FLOAT_EPSILON) { + return null; + } + + return $left / $right; + } + + /** + * Safely executes integer modulo arithmetic, guarding against modulo by zero. + */ + private static function modulo(int|float $left, int|float $right): int|null + { + $intRight = (int) $right; + if ($intRight === 0) { + return null; + } + + return (int) $left % $intRight; + } +} diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php new file mode 100644 index 00000000..f4aed5b7 --- /dev/null +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -0,0 +1,359 @@ + + */ + private const EMPTY_ARRAY_ALLOWED_IDENTIFIERS = [ + 'array' => true, + 'list' => true, + 'iterable' => true, + 'mixed' => true, + ]; + + /** + * O(1) hash map of generic container base names satisfied by an empty array ([]). + * + * @var array + */ + private const EMPTY_ARRAY_ALLOWED_GENERICS = [ + 'array' => true, + 'list' => true, + 'iterable' => true, + ]; + + /** + * Determines whether an AST array expression satisfies a target type contract. + * + * Flow of logic: + * 1. Empty arrays ([]) are checked against types that permit empty collections. + * 2. Bare array/iterable identifiers (array, iterable, list) are evaluated. + * 3. Sequential lists (list, non-empty-list, T[]) verify keys are 0..n-1 and all values satisfy T. + * 4. Typed key-value maps (array) verify all keys satisfy K and all values satisfy V. + * 5. Array shapes (array{id: int, ...}) verify required keys, unexpected keys, and field types. + */ + public static function satisfies(Array_ $arrayExpr, TypeNode $typeNode, string $currentFile = ''): bool + { + $count = \count($arrayExpr->items); + + if ($count === 0) { + return self::satisfiesEmptyArray($typeNode); + } + + if ($typeNode instanceof IdentifierTypeNode) { + return self::satisfiesIdentifierArray($arrayExpr, $typeNode); + } + + if ($typeNode instanceof ArrayTypeNode) { + return self::satisfiesList($arrayExpr, $typeNode->type, false, $currentFile); + } + + if ($typeNode instanceof GenericTypeNode) { + return self::satisfiesGenericArray($arrayExpr, $typeNode, $currentFile); + } + + if ($typeNode instanceof ArrayShapeNode) { + return self::satisfiesArrayShape($arrayExpr, $typeNode, $currentFile); + } + + return false; + } + + /** + * Checks if a type contract permits an empty array ([]). + * Returns true for unbounded array/list/iterable, T[], and shapes with only optional keys. + * Returns false for non-empty-array, non-empty-list, and shapes with required keys. + */ + public static function satisfiesEmptyArray(TypeNode $typeNode): bool + { + if ($typeNode instanceof IdentifierTypeNode) { + return isset(self::EMPTY_ARRAY_ALLOWED_IDENTIFIERS[strtolower($typeNode->name)]); + } + + if ($typeNode instanceof ArrayTypeNode) { + return true; + } + + if ($typeNode instanceof GenericTypeNode) { + return isset(self::EMPTY_ARRAY_ALLOWED_GENERICS[strtolower($typeNode->type->name)]); + } + + if ($typeNode instanceof ArrayShapeNode) { + foreach ($typeNode->items as $item) { + if (! $item->optional) { + return false; + } + } + + return true; + } + + return false; + } + + /** + * Evaluates an array expression against bare identifier types (array, list, non-empty-list). + */ + private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTypeNode $node): bool + { + $name = strtolower($node->name); + + return match ($name) { + 'array', 'iterable', 'mixed' => true, + 'list' => self::isSequentialList($arrayExpr), + 'non-empty-array' => \count($arrayExpr->items) > 0, + 'non-empty-list' => \count($arrayExpr->items) > 0 && self::isSequentialList($arrayExpr), + default => false, + }; + } + + /** + * Evaluates an array expression against generic array containers: + * - Single template argument: list, non-empty-list, array + * - Double template argument: array, non-empty-array + */ + private static function satisfiesGenericArray(Array_ $arrayExpr, GenericTypeNode $node, string $currentFile): bool + { + $base = strtolower($node->type->name); + $genericCount = \count($node->genericTypes); + + if ($base === 'list' && $genericCount >= 1) { + return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile); + } + + if ($base === 'non-empty-list' && $genericCount >= 1) { + return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile); + } + + if (($base === 'array' || $base === 'iterable') && $genericCount === 1) { + return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile); + } + + if (($base === 'array' || $base === 'iterable') && $genericCount >= 2) { + return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], false, $currentFile); + } + + if ($base === 'non-empty-array' && $genericCount === 1) { + return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile); + } + + if ($base === 'non-empty-array' && $genericCount >= 2) { + return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], true, $currentFile); + } + + return false; + } + + /** + * Verifies that all array items have sequential integer keys (0..n-1) + * and every item value statically satisfies the element contract T. + */ + private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, bool $requireNonEmpty, string $currentFile): bool + { + $count = \count($arrayExpr->items); + if ($requireNonEmpty && $count === 0) { + return false; + } + + $expectedIdx = 0; + foreach ($arrayExpr->items as $item) { + if ($item === null) { + return false; + } + + if ($item->key !== null) { + if (! ($item->key instanceof LNumber) || $item->key->value !== $expectedIdx) { + return false; + } + } + $expectedIdx++; + + if (! StaticTypeEvaluator::satisfies($item->value, $itemType, $currentFile)) { + return false; + } + } + + return true; + } + + /** + * Verifies that every key in the array expression satisfies key contract K + * and every corresponding value satisfies value contract V. + */ + private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyType, TypeNode $valueType, bool $requireNonEmpty, string $currentFile): bool + { + $count = \count($arrayExpr->items); + if ($requireNonEmpty && $count === 0) { + return false; + } + + $currentIdx = 0; + foreach ($arrayExpr->items as $item) { + if ($item === null) { + return false; + } + + if ($item->key === null) { + $keyExpr = new LNumber($currentIdx); + $currentIdx++; + } elseif ($item->key instanceof LNumber) { + $keyExpr = $item->key; + $currentIdx = max($currentIdx, $item->key->value + 1); + } elseif ($item->key instanceof String_ || $item->key instanceof Concat || $item->key instanceof Encapsed) { + $keyExpr = $item->key; + } else { + return false; + } + + if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile)) { + return false; + } + + if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile)) { + return false; + } + } + + return true; + } + + /** + * Evaluates an array expression against a sealed or unsealed ArrayShapeNode. + * Guarantees all required keys exist, no unsealed keys intrude in sealed shapes, + * and all value expressions satisfy their corresponding shape property contracts. + */ + private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $shapeNode, string $currentFile): bool + { + if ($shapeNode->kind === ArrayShapeNode::KIND_LIST && ! self::isSequentialList($arrayExpr)) { + return false; + } + + $shapeMap = []; + $autoIdx = 0; + foreach ($shapeNode->items as $shapeItem) { + $key = match (true) { + $shapeItem->keyName instanceof ConstExprStringNode => $shapeItem->keyName->value, + $shapeItem->keyName instanceof ConstExprIntegerNode => (int) $shapeItem->keyName->value, + $shapeItem->keyName instanceof IdentifierTypeNode => $shapeItem->keyName->name, + $shapeItem->keyName !== null => (string) $shapeItem->keyName, + default => $autoIdx, + }; + + if (\is_int($key)) { + $autoIdx = max($autoIdx, $key + 1); + } + + $shapeMap[$key] = $shapeItem; + } + + $actualItems = []; + $currentIdx = 0; + foreach ($arrayExpr->items as $item) { + if ($item === null) { + return false; + } + + if ($item->key === null) { + $key = $currentIdx; + $currentIdx++; + } elseif ($item->key instanceof LNumber) { + $key = $item->key->value; + $currentIdx = max($currentIdx, $key + 1); + } elseif ($item->key instanceof String_) { + $key = $item->key->value; + } else { + return false; + } + + $actualItems[$key] = $item->value; + } + + foreach ($shapeMap as $expectedKey => $shapeItem) { + if (! \array_key_exists($expectedKey, $actualItems)) { + if (! $shapeItem->optional) { + return false; + } + + continue; + } + + if (! StaticTypeEvaluator::satisfies($actualItems[$expectedKey], $shapeItem->valueType, $currentFile)) { + return false; + } + } + + foreach ($actualItems as $actualKey => $actualValueExpr) { + if (\array_key_exists($actualKey, $shapeMap)) { + continue; + } + + if ($shapeNode->sealed) { + return false; + } + + 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)) { + return false; + } + } + + if (! StaticTypeEvaluator::satisfies($actualValueExpr, $shapeNode->unsealedType->valueType, $currentFile)) { + return false; + } + } + } + + return true; + } + + /** + * Checks whether an array expression has sequential 0..n-1 integer keys. + */ + private static function isSequentialList(Array_ $arrayExpr): bool + { + $expectedIdx = 0; + foreach ($arrayExpr->items as $item) { + if ($item === null) { + return false; + } + + if ($item->key !== null) { + if (! ($item->key instanceof LNumber) || $item->key->value !== $expectedIdx) { + return false; + } + } + $expectedIdx++; + } + + return true; + } +} diff --git a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php new file mode 100644 index 00000000..72cd8972 --- /dev/null +++ b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php @@ -0,0 +1,152 @@ +value) against `value-of`. + */ + public static function satisfies(Expr $expr, TypeNode $typeNode, string $currentFile = ''): bool + { + if ($expr instanceof ClassConstFetch) { + return self::satisfiesClassConst($expr, $typeNode, $currentFile); + } + + if ($expr instanceof BitwiseOr) { + return self::satisfiesBitwiseOr($expr, $typeNode, $currentFile); + } + + if ($expr instanceof PropertyFetch) { + return self::satisfiesEnumBackingValue($expr, $typeNode, $currentFile); + } + + return false; + } + + /** + * Evaluates a class constant fetch against ConstTypeNode, IdentifierTypeNode, or int-mask-of. + */ + private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $typeNode, string $currentFile): bool + { + if (! ($fetch->class instanceof Name) || ! ($fetch->name instanceof Identifier)) { + return false; + } + + $constName = $fetch->name->toString(); + $targetClassName = $fetch->class->toString(); + + if ($typeNode instanceof ConstTypeNode && $typeNode->constExpr instanceof ConstFetchNode) { + $docConstName = $typeNode->constExpr->name; + + if (str_contains($docConstName, '*')) { + return self::matchesWildcard($constName, $docConstName); + } + + return $constName === $docConstName; + } + + if ($typeNode instanceof IdentifierTypeNode) { + if ($currentFile !== '') { + $resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($targetClassName, $currentFile, false); + $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false); + + return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass; + } + + return $targetClassName === $typeNode->name; + } + + if ($typeNode instanceof GenericTypeNode && strtolower($typeNode->type->name) === 'int-mask-of') { + $inner = $typeNode->genericTypes[0] ?? null; + if ($inner instanceof ConstTypeNode && $inner->constExpr instanceof ConstFetchNode) { + return self::matchesWildcard($constName, $inner->constExpr->name); + } + } + + return false; + } + + /** + * 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 + { + if (! ($typeNode instanceof GenericTypeNode) || strtolower($typeNode->type->name) !== 'int-mask-of') { + return false; + } + + return self::satisfies($expr->left, $typeNode, $currentFile) + && self::satisfies($expr->right, $typeNode, $currentFile); + } + + /** + * Verifies whether an Enum::Case->value property access satisfies `value-of`. + */ + private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode $typeNode, string $currentFile): bool + { + if (! ($fetch->name instanceof Identifier) || $fetch->name->name !== 'value') { + return false; + } + + if (! ($fetch->var instanceof ClassConstFetch) || ! ($fetch->var->class instanceof Name)) { + return false; + } + + if (! ($typeNode instanceof GenericTypeNode) || strtolower($typeNode->type->name) !== 'value-of') { + return false; + } + + $enumTarget = $typeNode->genericTypes[0] ?? null; + if (! ($enumTarget instanceof IdentifierTypeNode)) { + return false; + } + + $enumClassName = $fetch->var->class->toString(); + + if ($currentFile !== '') { + $resolvedEnumClass = SpecialTypeResolver::resolveFqcnForFile($enumClassName, $currentFile, false); + $resolvedTargetClass = SpecialTypeResolver::resolveFqcnForFile($enumTarget->name, $currentFile, false); + + return $resolvedEnumClass !== '' && $resolvedEnumClass === $resolvedTargetClass; + } + + return $enumClassName === $enumTarget->name; + } + + /** + * Compares a constant name against a wildcard pattern prefix (e.g. 'STATUS_PAID' vs 'STATUS_*'). + */ + private static function matchesWildcard(string $actualName, string $pattern): bool + { + $prefix = rtrim($pattern, '*'); + + return str_starts_with(strtoupper($actualName), strtoupper($prefix)); + } +} diff --git a/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php new file mode 100644 index 00000000..205abb9b --- /dev/null +++ b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php @@ -0,0 +1,226 @@ + + */ + private const GENERATOR_ROOT_TYPES = [ + 'generator' => true, + 'iterable' => true, + 'traversable' => true, + 'iterator' => true, + ]; + + /** + * Extracts the [key, value, send, return] TypeNode contract from a generator's return TypeNode. + * Returns null if the return type is an unexpanded type alias or non-generator type. + * + * @return array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null + */ + public static function extractContract(TypeNode $returnTypeNode): ?array + { + if ($returnTypeNode instanceof IdentifierTypeNode) { + $base = strtolower(ltrim($returnTypeNode->name, '\\')); + if (! isset(self::GENERATOR_ROOT_TYPES[$base])) { + return null; + } + + return [ + 'key' => null, + 'value' => null, + 'send' => null, + 'return' => null, + ]; + } + + if ($returnTypeNode instanceof ArrayTypeNode) { + return [ + 'key' => null, + 'value' => $returnTypeNode->type, + 'send' => null, + 'return' => null, + ]; + } + + if ($returnTypeNode instanceof GenericTypeNode) { + $base = strtolower(ltrim($returnTypeNode->type->name, '\\')); + if (! isset(self::GENERATOR_ROOT_TYPES[$base])) { + return null; + } + + $count = \count($returnTypeNode->genericTypes); + + if ($count === 1) { + return [ + 'key' => null, + 'value' => $returnTypeNode->genericTypes[0], + 'send' => null, + 'return' => null, + ]; + } + + if ($count === 2) { + return [ + 'key' => $returnTypeNode->genericTypes[0], + 'value' => $returnTypeNode->genericTypes[1], + 'send' => null, + 'return' => null, + ]; + } + + if ($count === 3) { + return [ + 'key' => $returnTypeNode->genericTypes[0], + 'value' => $returnTypeNode->genericTypes[1], + 'send' => $returnTypeNode->genericTypes[2], + 'return' => null, + ]; + } + + if ($count >= 4) { + return [ + 'key' => $returnTypeNode->genericTypes[0], + 'value' => $returnTypeNode->genericTypes[1], + 'send' => $returnTypeNode->genericTypes[2], + 'return' => $returnTypeNode->genericTypes[3], + ]; + } + } + + return null; + } + + /** + * Determines whether `RuntimeTypeChecker::checkYield()` can be statically eliminated for a `yield` expression. + */ + public static function canEliminateYield( + Yield_ $yieldNode, + ?TypeNode $keyType, + ?TypeNode $valueType, + string $currentFile = '', + ?Expr $precedingValueExpr = null + ): bool { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + if ($keyType !== null && ! self::isMixedType($keyType)) { + $keyExpr = $yieldNode->key ?? new LNumber(0); + if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile)) { + return false; + } + } + + if ($valueType !== null && ! self::isMixedType($valueType)) { + $valExpr = $precedingValueExpr ?? $yieldNode->value ?? new ConstFetch(new Name('null')); + if (! StaticTypeEvaluator::satisfies($valExpr, $valueType, $currentFile)) { + return false; + } + } + + return true; + } + + /** + * Determines whether `RuntimeTypeChecker::checkSend()` can be statically eliminated. + * True when `TSend` is omitted (< 3 template arguments) or explicitly `mixed`. + */ + public static function canEliminateSend(?TypeNode $sendType): bool + { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + return $sendType === null || self::isMixedType($sendType); + } + + /** + * Determines whether `RuntimeTypeChecker::wrapIterable()` can be statically eliminated on `yield from`. + */ + public static function canEliminateYieldFrom( + YieldFrom $yieldFromNode, + ?TypeNode $keyType, + ?TypeNode $valueType, + string $currentFile = '' + ): bool { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + if (! ($yieldFromNode->expr instanceof Array_)) { + return false; + } + + if (($keyType === null || self::isMixedType($keyType)) && ($valueType === null || self::isMixedType($valueType))) { + return true; + } + + if ($keyType === null || self::isMixedType($keyType)) { + /** @var TypeNode $valueType */ + $targetType = new GenericTypeNode(new IdentifierTypeNode('iterable'), [$valueType]); + + return ArrayLiteralEvaluator::satisfies($yieldFromNode->expr, $targetType, $currentFile); + } + + $effectiveValueType = $valueType ?? new IdentifierTypeNode('mixed'); + $targetType = new GenericTypeNode(new IdentifierTypeNode('iterable'), [$keyType, $effectiveValueType]); + + return ArrayLiteralEvaluator::satisfies($yieldFromNode->expr, $targetType, $currentFile); + } + + /** + * Determines whether `RuntimeTypeChecker::checkGeneratorReturn()` can be statically eliminated. + */ + public static function canEliminateGeneratorReturn( + ?Expr $returnExpr, + ?TypeNode $returnType, + string $currentFile = '' + ): bool { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + if ($returnType === null || self::isMixedType($returnType)) { + return true; + } + + $effectiveExpr = $returnExpr ?? new ConstFetch(new Name('null')); + + return StaticTypeEvaluator::satisfies($effectiveExpr, $returnType, $currentFile); + } + + /** + * Checks if a TypeNode is an unconstrained `mixed` identifier. + */ + private static function isMixedType(TypeNode $typeNode): bool + { + return $typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'mixed'; + } +} diff --git a/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php new file mode 100644 index 00000000..f04e3ff6 --- /dev/null +++ b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php @@ -0,0 +1,131 @@ + + */ + private const RELATIVE_CLASS_KEYWORDS = [ + 'self' => true, + 'static' => true, + 'parent' => true, + '$this' => true, + ]; + + /** + * O(1) hash map of identifier types satisfied by `$this`. + * + * @var array + */ + private const THIS_COMPATIBLE_IDENTIFIERS = [ + '$this' => true, + 'self' => true, + ]; + + /** + * Determines whether an AST object expression deterministically satisfies an object contract. + * + * Flow of logic: + * 1. Rejects GenericTypeNode targets (e.g. Collection) to ensure WeakMap template bindings are preserved. + * 2. Evaluates `$this` against `$this` or `self`. + * 3. Evaluates `new static()` against `static`. + * 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 + { + if ($typeNode instanceof GenericTypeNode) { + return false; + } + + if ($expr instanceof Variable && $expr->name === 'this') { + return self::satisfiesThis($typeNode); + } + + if ($expr instanceof New_ && $expr->class instanceof Name) { + return self::satisfiesNew($expr->class, $typeNode, $currentFile); + } + + return false; + } + + /** + * Verifies that `$this` satisfies `@return $this` or `@return self`. + */ + private static function satisfiesThis(TypeNode $typeNode): bool + { + if ($typeNode instanceof ThisTypeNode) { + return true; + } + + if ($typeNode instanceof IdentifierTypeNode) { + return isset(self::THIS_COMPATIBLE_IDENTIFIERS[strtolower($typeNode->name)]); + } + + return false; + } + + /** + * Evaluates `new ClassName(...)` against expected object type contracts. + */ + private static function satisfiesNew(Name $classNameNode, TypeNode $typeNode, string $currentFile): bool + { + if (! ($typeNode instanceof IdentifierTypeNode)) { + return false; + } + + $rawNewClass = $classNameNode->toString(); + $lowerNewClass = strtolower($rawNewClass); + $lowerTargetType = strtolower($typeNode->name); + + if ($lowerNewClass === 'static' && $lowerTargetType === 'static') { + return true; + } + + if ($lowerNewClass === 'self' && $lowerTargetType === 'self') { + return true; + } + + if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerTargetType])) { + return false; + } + + if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerNewClass])) { + return false; + } + + if ($rawNewClass === $typeNode->name) { + return true; + } + + if ($currentFile !== '') { + $resolvedNewClass = SpecialTypeResolver::resolveFqcnForFile($rawNewClass, $currentFile, false); + $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false); + + return $resolvedNewClass !== '' && $resolvedNewClass === $resolvedTypeClass; + } + + return $rawNewClass === $typeNode->name; + } +} diff --git a/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php new file mode 100644 index 00000000..11c91d97 --- /dev/null +++ b/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php @@ -0,0 +1,369 @@ + + */ + private const TRUE_COMPATIBLE_TYPES = [ + 'bool' => true, + 'boolean' => true, + 'true' => true, + 'truthy' => true, + 'scalar' => true, + 'mixed' => true, + ]; + + /** + * O(1) hash map of type identifiers satisfied by boolean literal `false`. + * + * @var array + */ + private const FALSE_COMPATIBLE_TYPES = [ + 'bool' => true, + 'boolean' => true, + 'false' => true, + 'falsy' => true, + 'falsey' => true, + 'scalar' => true, + 'mixed' => true, + ]; + + /** + * O(1) hash map of type identifiers satisfied by literal `null`. + * + * @var array + */ + private const NULL_COMPATIBLE_TYPES = [ + 'null' => true, + 'void' => true, + 'mixed' => true, + ]; + + /** + * O(1) hash map of type identifiers satisfied by any non-empty string. + * + * @var array + */ + private const NON_EMPTY_STRING_COMPATIBLE_TYPES = [ + 'string' => true, + 'non-empty-string' => true, + 'array-key' => true, + 'scalar' => true, + 'mixed' => true, + ]; + + /** + * Determines whether an AST scalar expression satisfies the target type contract. + * + * Flow of logic: + * 1. Evaluates arithmetic numbers and constant folding (30 + 15, 60 * 60, 0.1 + 0.2). + * 2. Evaluates literal strings. + * 3. Evaluates string concatenations and interpolations ("user_{$id}") with non-empty prefixes. + * 4. Evaluates language constants (true, false, null). + */ + public static function satisfies(Expr $expr, TypeNode $typeNode): bool + { + $number = ArithmeticEvaluator::evaluate($expr); + if ($number !== null) { + return \is_int($number) + ? self::satisfiesInteger($number, $typeNode) + : self::satisfiesFloat($number, $typeNode); + } + + if ($expr instanceof String_) { + return self::satisfiesString($expr->value, $typeNode); + } + + if (($expr instanceof Concat || $expr instanceof Encapsed) && self::isGuaranteedNonEmptyString($expr)) { + return self::isNonEmptyStringType($typeNode); + } + + if ($expr instanceof ConstFetch) { + return self::satisfiesConst(strtolower($expr->name->getLast()), $typeNode); + } + + return false; + } + + /** + * Checks if an expression represents a literal `null` constant. + */ + public static function isNullLiteral(Expr $expr): bool + { + return $expr instanceof ConstFetch && strtolower($expr->name->getLast()) === 'null'; + } + + /** + * Recursively verifies whether a string, concatenation, or interpolation is guaranteed + * to produce a non-empty string. If at least one static chunk has length >= 1, the result + * can never be empty regardless of dynamic sub-expressions. + */ + public static function isGuaranteedNonEmptyString(Expr $expr): bool + { + if ($expr instanceof String_ && $expr->value !== '') { + return true; + } + + if ($expr instanceof Concat) { + return self::isGuaranteedNonEmptyString($expr->left) || self::isGuaranteedNonEmptyString($expr->right); + } + + if ($expr instanceof Encapsed) { + foreach ($expr->parts as $part) { + if ($part instanceof EncapsedStringPart && $part->value !== '') { + return true; + } + if ($part instanceof String_ && $part->value !== '') { + return true; + } + } + } + + return false; + } + + /** + * Evaluates an integer against ConstTypeNode, GenericTypeNode ranges/bitmasks, + * and scalar identifier refinements (including integer coercion to float types). + */ + private static function satisfiesInteger(int $value, TypeNode $typeNode): bool + { + if ($typeNode instanceof ConstTypeNode) { + if ($typeNode->constExpr instanceof ConstExprIntegerNode) { + return (int) $typeNode->constExpr->value === $value; + } + + if ($typeNode->constExpr instanceof ConstExprFloatNode) { + return abs($value - (float) $typeNode->constExpr->value) < ArithmeticEvaluator::FLOAT_EPSILON; + } + + return false; + } + + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower($typeNode->type->name); + + if ($base === 'int' || $base === 'integer') { + return self::satisfiesIntRange($value, $typeNode); + } + + if ($base === 'int-mask' || $base === 'int-mask-of') { + return self::satisfiesIntMask($value, $typeNode); + } + } + + if ($typeNode instanceof IdentifierTypeNode) { + return match (strtolower($typeNode->name)) { + 'int', 'integer', 'scalar', 'numeric', 'number', 'mixed' => true, + 'float', 'double' => true, + 'positive-int', 'positive-float' => $value > 0, + 'negative-int', 'negative-float' => $value < 0, + 'non-positive-int', 'non-positive-float' => $value <= 0, + 'non-negative-int', 'non-negative-float', 'unsigned-int' => $value >= 0, + 'non-zero-int', 'non-zero-float' => $value !== 0, + 'truthy' => $value !== 0, + 'falsy', 'falsey' => $value === 0, + 'array-key' => true, + default => false, + }; + } + + return false; + } + + /** + * Verifies if an integer falls within static `int` bounds. + */ + private static function satisfiesIntRange(int $value, GenericTypeNode $node): bool + { + $min = self::resolveRangeBound($node->genericTypes[0] ?? null); + $max = self::resolveRangeBound($node->genericTypes[1] ?? null); + + if ($min !== null && $value < $min) { + return false; + } + + if ($max !== null && $value > $max) { + return false; + } + + return true; + } + + /** + * Verifies if an integer bitmask matches allowed bit flags in `int-mask` + * or `int-mask-of`. Zero is always valid as it represents an empty bitmask. + */ + private static function satisfiesIntMask(int $value, GenericTypeNode $node): bool + { + if ($value === 0) { + return true; + } + + $allowedMask = 0; + foreach ($node->genericTypes as $gt) { + if ($gt instanceof ConstTypeNode && $gt->constExpr instanceof ConstExprIntegerNode) { + $allowedMask |= (int) $gt->constExpr->value; + } else { + return false; + } + } + + return ($value & ~$allowedMask) === 0; + } + + /** + * Resolves integer bounds from range AST nodes, ignoring 'min', 'max', and '*'. + */ + private static function resolveRangeBound(?TypeNode $boundNode): ?int + { + if ($boundNode === null) { + return null; + } + + if ($boundNode instanceof ConstTypeNode && $boundNode->constExpr instanceof ConstExprIntegerNode) { + return (int) $boundNode->constExpr->value; + } + + if ($boundNode instanceof IdentifierTypeNode) { + $name = strtolower($boundNode->name); + if ($name === 'min' || $name === 'max' || $name === '*') { + return null; + } + + if (is_numeric($boundNode->name)) { + return (int) $boundNode->name; + } + } + + return null; + } + + /** + * Evaluates a float against float literal constants with epsilon tolerance and float refinements. + */ + private static function satisfiesFloat(float $value, TypeNode $typeNode): bool + { + if ($typeNode instanceof ConstTypeNode) { + return $typeNode->constExpr instanceof ConstExprFloatNode + && abs($value - (float) $typeNode->constExpr->value) < ArithmeticEvaluator::FLOAT_EPSILON; + } + + if ($typeNode instanceof IdentifierTypeNode) { + return match (strtolower($typeNode->name)) { + 'float', 'double', 'scalar', 'numeric', 'number', 'mixed' => true, + 'positive-float' => $value > 0.0, + 'negative-float' => $value < 0.0, + 'non-positive-float' => $value <= 0.0, + 'non-negative-float' => $value >= 0.0, + 'non-zero-float' => $value !== 0.0 && $value !== -0.0, + 'truthy' => $value !== 0.0, + 'falsy', 'falsey' => $value === 0.0, + default => false, + }; + } + + return false; + } + + /** + * Evaluates a string against string literals and string refinements (e.g. non-empty, casing). + */ + private static function satisfiesString(string $value, TypeNode $typeNode): bool + { + if ($typeNode instanceof ConstTypeNode) { + return $typeNode->constExpr instanceof ConstExprStringNode + && $typeNode->constExpr->value === $value; + } + + if ($typeNode instanceof IdentifierTypeNode) { + return match (strtolower($typeNode->name)) { + 'string', 'literal-string', 'scalar', 'mixed' => true, + 'non-empty-string' => $value !== '', + 'lowercase-string' => strtolower($value) === $value, + 'non-empty-lowercase-string' => $value !== '' && strtolower($value) === $value, + 'uppercase-string' => strtoupper($value) === $value, + 'non-empty-uppercase-string' => $value !== '' && strtoupper($value) === $value, + 'numeric-string' => is_numeric($value), + 'truthy', 'truthy-string', 'non-falsy-string' => (bool) $value === true, + 'falsy', 'falsey' => (bool) $value === false, + 'array-key' => true, + default => false, + }; + } + + return false; + } + + /** + * Checks if the type node accepts any non-empty string. + */ + private static function isNonEmptyStringType(TypeNode $typeNode): bool + { + if ($typeNode instanceof IdentifierTypeNode) { + return isset(self::NON_EMPTY_STRING_COMPATIBLE_TYPES[strtolower($typeNode->name)]); + } + + return false; + } + + /** + * Evaluates literal language constants (`true`, `false`, `null`) against expected contracts. + */ + private static function satisfiesConst(string $constName, TypeNode $typeNode): bool + { + if ($typeNode instanceof ConstTypeNode) { + return ($constName === 'true' && $typeNode->constExpr instanceof ConstExprTrueNode) + || ($constName === 'false' && $typeNode->constExpr instanceof ConstExprFalseNode) + || ($constName === 'null' && $typeNode->constExpr instanceof ConstExprNullNode); + } + + if ($typeNode instanceof IdentifierTypeNode) { + $typeName = strtolower($typeNode->name); + + if ($constName === 'true') { + return isset(self::TRUE_COMPATIBLE_TYPES[$typeName]); + } + + if ($constName === 'false') { + return isset(self::FALSE_COMPATIBLE_TYPES[$typeName]); + } + + if ($constName === 'null') { + return isset(self::NULL_COMPATIBLE_TYPES[$typeName]); + } + } + + return false; + } +} diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php new file mode 100644 index 00000000..dfab34b9 --- /dev/null +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -0,0 +1,106 @@ + + */ + private const PERMISSIBLE_GENERIC_CONTAINERS = [ + 'int' => true, + 'integer' => true, + 'int-mask' => true, + 'int-mask-of' => true, + 'value-of' => true, + 'list' => true, + 'non-empty-list' => true, + 'array' => true, + 'non-empty-array' => true, + 'iterable' => true, + ]; + + /** + * Determines whether an AST expression deterministically satisfies a TypeNode contract. + * + * Flow of logic: + * 1. Returns false if `eliminate_statically_proven_checks` is disabled in configuration. + * 2. Rejects IntersectionTypeNode unconditionally (deferred to runtime to avoid autoloader deadlocks). + * 3. Rejects generic object templates to ensure runtime WeakMap registrations occur. + * 4. Evaluates Ternary expressions: if both `if` and `else` branches satisfy the contract, + * the expression is satisfied regardless of runtime condition. + * 5. Handles NullableTypeNode and UnionTypeNode disjunctions. + * 6. Delegates array expressions, constants/enums, object instantiations, and arithmetic/scalars. + */ + public static function satisfies(Expr $expr, TypeNode $typeNode, string $currentFile = ''): bool + { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + if ($typeNode instanceof IntersectionTypeNode) { + return false; + } + + if ($typeNode instanceof GenericTypeNode) { + $baseName = strtolower($typeNode->type->name); + if (! isset(self::PERMISSIBLE_GENERIC_CONTAINERS[$baseName])) { + return false; + } + } + + if ($expr instanceof Ternary && $expr->if !== null) { + return self::satisfies($expr->if, $typeNode, $currentFile) + && self::satisfies($expr->else, $typeNode, $currentFile); + } + + if ($typeNode instanceof NullableTypeNode) { + if (ScalarEvaluator::isNullLiteral($expr)) { + return true; + } + + return self::satisfies($expr, $typeNode->type, $currentFile); + } + + if ($typeNode instanceof UnionTypeNode) { + foreach ($typeNode->types as $member) { + if (self::satisfies($expr, $member, $currentFile)) { + return true; + } + } + + return false; + } + + if ($expr instanceof Array_) { + return ArrayLiteralEvaluator::satisfies($expr, $typeNode, $currentFile); + } + + return ConstantAndEnumEvaluator::satisfies($expr, $typeNode, $currentFile) + || ObjectEvaluator::satisfies($expr, $typeNode, $currentFile) + || ScalarEvaluator::satisfies($expr, $typeNode); + } +} diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index d8fafd14..e5019f13 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -8,6 +8,11 @@ use PhpParser\Node; use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use TypePHP\Internal\Ast\Elimination\EliminationSafetyPolicy; +use TypePHP\Internal\Ast\Elimination\Evaluator\GeneratorEvaluator; +use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; +use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Util\StubManager; /** @@ -31,8 +36,11 @@ final class FunctionContractInjector /** * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext */ - public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?array $classContext = null): void - { + public static function inject( + Node\Stmt\Function_|Node\Stmt\ClassMethod $node, + ?array $classContext = null, + string $currentFile = '' + ): void { if ($node->stmts === null) { return; } @@ -134,9 +142,31 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ? $injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass, $needsReturnVars); } + $returnTypeNode = null; + $hasMethodTemplates = false; + if ($doc !== null) { + try { + $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); + $returnTag = DocblockExtractor::getReturnTag($phpDocNode); + if ($returnTag !== null) { + $returnTypeNode = $returnTag->type; + } + $hasMethodTemplates = DocblockExtractor::extractTemplates($phpDocNode) !== []; + } catch (\Throwable) { + } + } + if ($hasReturn || $hasParamOut || $hasSelfOut) { $node->stmts = self::isGenerator($node) - ? self::wrapGeneratorReturns($node->stmts, $thisArg) + ? self::wrapGeneratorReturns( + $node->stmts, + $thisArg, + $node, + $classContext, + $returnTypeNode, + $currentFile, + $hasMethodTemplates + ) : self::wrapNonGeneratorReturns( $node->stmts, $thisArg, @@ -146,6 +176,10 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ? $hasParamOut ? $byRefParams : [], $hasSelfOut, $node->byRef, + $node, + $classContext, + $returnTypeNode, + $currentFile ); } @@ -333,7 +367,7 @@ private static function hasReturnContracts( return false; } - if (! $hasNativeReturnType && ! $hasReturnStatements) { + if (! $hasNativeReturnType) { return false; } @@ -754,26 +788,36 @@ public static function buildTernaryReturnExpr(Node\Expr\FuncCall $checkCall, ?in ); } - public static function buildWrappedYieldNode(Node\Expr\Yield_ $n, Node\Expr $thisArg): Node\Expr\Ternary - { - $checkYieldCall = new Node\Expr\FuncCall( - new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkYield'), - [ - new Node\Arg(new Node\Scalar\MagicConst\Method()), - new Node\Arg($n->key ?? new Node\Expr\ConstFetch(new Node\Name('null'))), - new Node\Arg($n->value ?? new Node\Expr\ConstFetch(new Node\Name('null'))), - new Node\Arg($thisArg), - ] - ); + public static function buildWrappedYieldNode( + Node\Expr\Yield_ $n, + Node\Expr $thisArg, + bool $wrapYield = true, + bool $wrapSend = true + ): Node\Expr { + if ($wrapYield) { + $checkYieldCall = new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkYield'), + [ + new Node\Arg(new Node\Scalar\MagicConst\Method()), + new Node\Arg($n->key ?? new Node\Expr\ConstFetch(new Node\Name('null'))), + new Node\Arg($n->value ?? new Node\Expr\ConstFetch(new Node\Name('null'))), + new Node\Arg($thisArg), + ] + ); - $n->value = new Node\Expr\Ternary( - new Node\Expr\Instanceof_( - new Node\Expr\Assign(new Node\Expr\Variable('__typephpYld'), $checkYieldCall), - new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage') - ), - self::buildTypeErrorThrowExpr(new Node\Expr\Variable('__typephpYld'), $n->getStartLine()), - new Node\Expr\Variable('__typephpYld') - ); + $n->value = new Node\Expr\Ternary( + new Node\Expr\Instanceof_( + new Node\Expr\Assign(new Node\Expr\Variable('__typephpYld'), $checkYieldCall), + new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage') + ), + self::buildTypeErrorThrowExpr(new Node\Expr\Variable('__typephpYld'), $n->getStartLine()), + new Node\Expr\Variable('__typephpYld') + ); + } + + if (! $wrapSend) { + return $n; + } $checkSendCall = new Node\Expr\FuncCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkSend'), @@ -796,15 +840,42 @@ public static function buildWrappedYieldNode(Node\Expr\Yield_ $n, Node\Expr $thi /** * @param array $stmts + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * * @return array */ - private static function wrapGeneratorReturns(array $stmts, Node\Expr $thisArg): array - { + private static function wrapGeneratorReturns( + array $stmts, + Node\Expr $thisArg, + Node\Stmt\Function_|Node\Stmt\ClassMethod|null $functionNode = null, + ?array $classContext = null, + ?TypeNode $returnTypeNode = null, + string $currentFile = '', + bool $hasMethodTemplates = false + ): array { + $canEliminate = $functionNode !== null + && ! $hasMethodTemplates + && ! ($classContext['hasTemplates'] ?? false) + && EliminationSafetyPolicy::isGeneratorEliminationSafe($functionNode, $classContext, $returnTypeNode); + + $genContract = ($canEliminate && $returnTypeNode !== null) + ? GeneratorEvaluator::extractContract($returnTypeNode) + : null; + + if ($genContract !== null) { + self::tagPrecedingAssignments($stmts); + } + $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ($thisArg) extends NodeVisitorAbstract { - public function __construct(private Node\Expr $thisArg) - { + $traverser->addVisitor(new class ($thisArg, $genContract, $currentFile) extends NodeVisitorAbstract { + /** + * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract + */ + public function __construct( + private Node\Expr $thisArg, + private ?array $genContract, + private string $currentFile + ) { } public function enterNode(Node $n): int|Node|null @@ -813,13 +884,53 @@ public function enterNode(Node $n): int|Node|null return NodeTraverser::DONT_TRAVERSE_CHILDREN; } + if ($this->genContract !== null) { + if ( + $n instanceof Node\Stmt\If_ + || $n instanceof Node\Stmt\Else_ + || $n instanceof Node\Stmt\ElseIf_ + || $n instanceof Node\Stmt\While_ + || $n instanceof Node\Stmt\Do_ + || $n instanceof Node\Stmt\For_ + || $n instanceof Node\Stmt\Foreach_ + || $n instanceof Node\Stmt\TryCatch + || $n instanceof Node\Stmt\Catch_ + || $n instanceof Node\Stmt\Finally_ + || $n instanceof Node\Stmt\Case_ + || $n instanceof Node\Stmt\Block + ) { + FunctionContractInjector::tagPrecedingAssignments($n->stmts); + } elseif ($n instanceof Node\Stmt\Declare_ && $n->stmts !== null) { + FunctionContractInjector::tagPrecedingAssignments($n->stmts); + } + } + if ($n instanceof Node\Expr\Yield_) { if ($n->getAttribute('typephp_wrapped') === true) { return null; } $n->setAttribute('typephp_wrapped', true); - return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg); + $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); + $precedingValueExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : null; + + $wrapYield = $this->genContract === null + || ! GeneratorEvaluator::canEliminateYield( + $n, + $this->genContract['key'], + $this->genContract['value'], + $this->currentFile, + $precedingValueExpr + ); + + $wrapSend = $this->genContract === null + || ! GeneratorEvaluator::canEliminateSend($this->genContract['send']); + + if (! $wrapYield && ! $wrapSend) { + return null; + } + + return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend); } if ($n instanceof Node\Expr\YieldFrom) { @@ -827,6 +938,19 @@ public function enterNode(Node $n): int|Node|null return null; } $n->setAttribute('typephp_wrapped', true); + + if ( + $this->genContract !== null + && GeneratorEvaluator::canEliminateYieldFrom( + $n, + $this->genContract['key'], + $this->genContract['value'], + $this->currentFile + ) + ) { + return null; + } + $n->expr = new Node\Expr\FuncCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::wrapIterable'), [ @@ -845,6 +969,20 @@ public function enterNode(Node $n): int|Node|null $n->setAttribute('typephp_generator_return_wrapped', true); $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); + $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; + + if ( + $this->genContract !== null + && GeneratorEvaluator::canEliminateGeneratorReturn( + $candidateExpr, + $this->genContract['return'], + $this->currentFile + ) + ) { + return $n; + } + $checkCall = new Node\Expr\FuncCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkGeneratorReturn'), [ @@ -868,22 +1006,27 @@ public function enterNode(Node $n): int|Node|null $lastStmt = end($newStmts); if (! $lastStmt instanceof Node\Stmt\Return_ && ! ($lastStmt instanceof Node\Stmt\Expression && $lastStmt->expr instanceof Node\Expr\Throw_)) { - $checkCall = new Node\Expr\FuncCall( - new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkGeneratorReturn'), - [ - new Node\Arg(new Node\Scalar\MagicConst\Method()), - new Node\Arg(new Node\Expr\ConstFetch(new Node\Name('null'))), - new Node\Arg($thisArg), - ] - ); + if ( + $genContract === null + || ! GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile) + ) { + $checkCall = new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkGeneratorReturn'), + [ + new Node\Arg(new Node\Scalar\MagicConst\Method()), + new Node\Arg(new Node\Expr\ConstFetch(new Node\Name('null'))), + new Node\Arg($thisArg), + ] + ); - $fallbackLine = $lastStmt instanceof Node\Stmt ? $lastStmt->getStartLine() : null; - $ternaryExpr = self::buildTernaryReturnExpr($checkCall, $fallbackLine); + $fallbackLine = $lastStmt instanceof Node\Stmt ? $lastStmt->getStartLine() : null; + $ternaryExpr = self::buildTernaryReturnExpr($checkCall, $fallbackLine); - $retStmt = new Node\Stmt\Return_($ternaryExpr); - $retStmt->setAttribute('typephp_injected', true); - $retStmt->setAttribute('typephp_generator_return_wrapped', true); - $newStmts[] = $retStmt; + $retStmt = new Node\Stmt\Return_($ternaryExpr); + $retStmt->setAttribute('typephp_injected', true); + $retStmt->setAttribute('typephp_generator_return_wrapped', true); + $newStmts[] = $retStmt; + } } return $newStmts; @@ -892,6 +1035,7 @@ public function enterNode(Node $n): int|Node|null /** * @param array $stmts * @param array $byRefParams + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * * @return array */ @@ -903,12 +1047,31 @@ private static function wrapNonGeneratorReturns( bool $hasReturn = true, array $byRefParams = [], bool $hasSelfOut = false, - bool $isByRefReturn = false + bool $isByRefReturn = false, + Node\Stmt\Function_|Node\Stmt\ClassMethod|null $functionNode = null, + ?array $classContext = null, + ?TypeNode $returnTypeNode = null, + string $currentFile = '' ): array { + self::tagPrecedingAssignments($stmts); + $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ($thisArg, $isNativeVoid, $needsReturnVars, $hasReturn, $byRefParams, $hasSelfOut, $isByRefReturn) extends NodeVisitorAbstract { + $traverser->addVisitor(new class ( + $thisArg, + $isNativeVoid, + $needsReturnVars, + $hasReturn, + $byRefParams, + $hasSelfOut, + $isByRefReturn, + $functionNode, + $classContext, + $returnTypeNode, + $currentFile + ) extends NodeVisitorAbstract { /** * @param array $byRefParams + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext */ public function __construct( private Node\Expr $thisArg, @@ -917,7 +1080,11 @@ public function __construct( private bool $hasReturn, private array $byRefParams, private bool $hasSelfOut, - private bool $isByRefReturn + private bool $isByRefReturn, + private Node\Stmt\Function_|Node\Stmt\ClassMethod|null $functionNode, + private ?array $classContext, + private ?TypeNode $returnTypeNode, + private string $currentFile ) { } @@ -927,6 +1094,25 @@ public function enterNode(Node $n): int|array|null return NodeTraverser::DONT_TRAVERSE_CHILDREN; } + if ( + $n instanceof Node\Stmt\If_ + || $n instanceof Node\Stmt\Else_ + || $n instanceof Node\Stmt\ElseIf_ + || $n instanceof Node\Stmt\While_ + || $n instanceof Node\Stmt\Do_ + || $n instanceof Node\Stmt\For_ + || $n instanceof Node\Stmt\Foreach_ + || $n instanceof Node\Stmt\TryCatch + || $n instanceof Node\Stmt\Catch_ + || $n instanceof Node\Stmt\Finally_ + || $n instanceof Node\Stmt\Case_ + || $n instanceof Node\Stmt\Block + ) { + FunctionContractInjector::tagPrecedingAssignments($n->stmts); + } elseif ($n instanceof Node\Stmt\Declare_ && $n->stmts !== null) { + FunctionContractInjector::tagPrecedingAssignments($n->stmts); + } + if ($n instanceof Node\Stmt\Return_) { if ($n->getAttribute('typephp_var_wrapped') === true) { return null; @@ -951,6 +1137,20 @@ public function enterNode(Node $n): int|array|null $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); + $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; + + if ( + ! $this->isByRefReturn + && ! $this->isNativeVoid + && $this->functionNode !== null + && $this->returnTypeNode !== null + && EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode) + && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile) + ) { + return $exitStmts !== [] ? [...$exitStmts, $n] : null; + } + if ($this->isNativeVoid) { $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); $voidGuardStmts = FunctionContractInjector::buildVoidReturnGuard($checkCall); @@ -1021,4 +1221,43 @@ public function enterNode(Node $n): int|array|null return $newStmts; } + + /** + * @param array $stmts + */ + public static function tagPrecedingAssignments(array $stmts): void + { + $count = \count($stmts); + for ($i = 1; $i < $count; $i++) { + $curr = $stmts[$i]; + $prev = $stmts[$i - 1]; + + if ( + ! ($prev instanceof Node\Stmt\Expression) + || ! ($prev->expr instanceof Node\Expr\Assign) + || ! ($prev->expr->var instanceof Node\Expr\Variable) + || ! \is_string($prev->expr->var->name) + ) { + continue; + } + + $assignedVarName = $prev->expr->var->name; + + if ( + $curr instanceof Node\Stmt\Return_ + && $curr->expr instanceof Node\Expr\Variable + && $curr->expr->name === $assignedVarName + ) { + $curr->setAttribute('typephp_preceding_assign_expr', $prev->expr->expr); + } elseif ( + $curr instanceof Node\Stmt\Expression + && $curr->expr instanceof Node\Expr\Yield_ + && $curr->expr->value instanceof Node\Expr\Variable + && $curr->expr->value->name === $assignedVarName + && ($curr->expr->key === null || ! ($curr->expr->key instanceof Node\Expr\Assign)) + ) { + $curr->expr->setAttribute('typephp_preceding_assign_expr', $prev->expr->expr); + } + } + } } diff --git a/src/Internal/Ast/NodeBuilder.php b/src/Internal/Ast/NodeBuilder.php index bb467198..07a97974 100644 --- a/src/Internal/Ast/NodeBuilder.php +++ b/src/Internal/Ast/NodeBuilder.php @@ -122,4 +122,22 @@ public static function createTernaryThrowExpr(Node\Expr\FuncCall $checkCall, int new Node\Expr\Variable('__typephpVal') ); } + + public static function createPropertyMemberAssignCheckCall( + Node\Expr $objectOrClassExpr, + string $propertyName, + Node\Expr $chainExpr, + Node\Expr $valueExpr + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name('\TypePHP\Internal\RuntimeTypeChecker::checkPropertyMemberAssign'), + [ + new Node\Arg($objectOrClassExpr), + new Node\Arg(new Node\Scalar\String_($propertyName)), + new Node\Arg($chainExpr), + new Node\Arg($valueExpr), + new Node\Arg(new Node\Scalar\MagicConst\File()), + ] + ); + } } diff --git a/src/Internal/Ast/ScopeManager.php b/src/Internal/Ast/ScopeManager.php index 2fb0087f..170dda7a 100644 --- a/src/Internal/Ast/ScopeManager.php +++ b/src/Internal/Ast/ScopeManager.php @@ -13,10 +13,20 @@ final class ScopeManager { /** + * In-memory stack of explicit @var type annotations. + * * @var list> */ private array $scopeStack = [[]]; + /** + * In-memory stack of inferred variable types (e.g. from $var = new ClassName() or typed parameters). + * Kept separate from explicit @var contracts to avoid injecting unwanted assignment checks on standard variables. + * + * @var list> + */ + private array $inferredStack = [[]]; + /** * Tracks which scope frames are isolated boundaries (functions, methods, closures). * @@ -29,6 +39,15 @@ final class ScopeManager */ private int $depth = 0; + /** + * Unregisters a variable from the current lexical scope frame (e.g. on unset). + */ + public function unregisterVarType(string $varName): void + { + unset($this->scopeStack[$this->depth][$varName]); + unset($this->inferredStack[$this->depth][$varName]); + } + /** * Programmatically registers a variable's type into the current scope frame. * Preserves explicit inline @var declarations in the current frame unless overwrite is true. @@ -42,6 +61,22 @@ public function registerVarType(string $varName, string $typeString, bool $overw $this->scopeStack[$this->depth][$varName] = $typeString; } + /** + * Registers an inferred variable type in the current lexical scope frame. + */ + public function registerInferredVarType(string $varName, string $typeString): void + { + $this->inferredStack[$this->depth][$varName] = $typeString; + } + + /** + * Unregisters an inferred variable type from the current lexical scope frame (e.g. on reassignment). + */ + public function unregisterInferredVarType(string $varName): void + { + unset($this->inferredStack[$this->depth][$varName]); + } + /** * Pushes a new lexical scope frame (O(1)). * @@ -52,6 +87,7 @@ public function pushScope(bool $isIsolated = false, array $initialBindings = []) { $this->depth++; $this->scopeStack[] = $initialBindings; + $this->inferredStack[] = []; $this->isolatedStack[] = $isIsolated; } @@ -62,6 +98,7 @@ public function popScope(): void { if ($this->depth > 0) { array_pop($this->scopeStack); + array_pop($this->inferredStack); array_pop($this->isolatedStack); $this->depth--; } @@ -101,7 +138,7 @@ public function extractVarDocblock(string $docText, ?Node\Expr $expr = null): vo } /** - * Resolves a variable type by walking upward through the lexical scope chain, + * Resolves an explicit variable type by walking upward through the lexical scope chain, * stopping at isolated scope boundaries (functions, methods, closures). */ public function getVarTypeFromScope(string $varName): ?string @@ -118,4 +155,23 @@ public function getVarTypeFromScope(string $varName): ?string return null; } + + /** + * Resolves an inferred variable type by walking upward through the lexical scope chain, + * stopping at isolated scope boundaries. + */ + public function getInferredVarType(string $varName): ?string + { + for ($i = $this->depth; $i >= 0; $i--) { + if (isset($this->inferredStack[$i][$varName])) { + return $this->inferredStack[$i][$varName]; + } + + if ($this->isolatedStack[$i]) { + break; + } + } + + return null; + } } diff --git a/src/Internal/Ast/TypeDeducer.php b/src/Internal/Ast/TypeDeducer.php new file mode 100644 index 00000000..9c8c2fb8 --- /dev/null +++ b/src/Internal/Ast/TypeDeducer.php @@ -0,0 +1,233 @@ + TypeNode + * + * @var array + */ + private static array $parsedTypeCache = []; + + /** + * Deduces the element/value type of a collection (list, T[], array, array{...}). + */ + public static function deduceElementType(string $typeString): ?string + { + $typeNode = self::parseTypeString($typeString); + if ($typeNode === null) { + return null; + } + + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof ArrayTypeNode) { + return (string) $typeNode->type; + } + + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower($typeNode->type->name); + $count = \count($typeNode->genericTypes); + + if (\in_array($base, ['list', 'non-empty-list'], true) && $count >= 1) { + return (string) $typeNode->genericTypes[0]; + } + + if (\in_array($base, ['array', 'non-empty-array', 'iterable'], true)) { + return $count >= 2 + ? (string) $typeNode->genericTypes[1] + : (string) ($typeNode->genericTypes[0] ?? 'mixed'); + } + } + + if ($typeNode instanceof ArrayShapeNode) { + $valueTypes = []; + foreach ($typeNode->items as $item) { + $valueTypes[] = (string) $item->valueType; + } + + $unique = array_values(array_unique($valueTypes)); + + if ($unique === []) { + return null; + } + + return \count($unique) === 1 ? $unique[0] : '(' . implode('|', $unique) . ')'; + } + + return null; + } + + /** + * Deduces the key type of a collection. + */ + public static function deduceKeyType(string $typeString): string + { + $typeNode = self::parseTypeString($typeString); + if ($typeNode === null) { + return 'array-key'; + } + + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower($typeNode->type->name); + $count = \count($typeNode->genericTypes); + + if (\in_array($base, ['list', 'non-empty-list'], true)) { + return 'int'; + } + + if (\in_array($base, ['array', 'non-empty-array', 'iterable'], true) && $count >= 2) { + return (string) $typeNode->genericTypes[0]; + } + } + + if ($typeNode instanceof ArrayTypeNode) { + return 'int'; + } + + return 'array-key'; + } + + /** + * Deduces the specific member type of an array dimension access ($arr[$dimExpr]). + */ + public static function deduceDimType(string $containerTypeString, ?Expr $dimExpr): ?string + { + $typeNode = self::parseTypeString($containerTypeString); + if ($typeNode === null) { + return null; + } + + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof ArrayShapeNode && $dimExpr !== null) { + $key = null; + if ($dimExpr instanceof String_) { + $key = $dimExpr->value; + } elseif ($dimExpr instanceof LNumber) { + $key = $dimExpr->value; + } + + if ($key !== null) { + $autoIdx = 0; + foreach ($typeNode->items as $item) { + $itemKey = match (true) { + $item->keyName instanceof ConstExprStringNode => $item->keyName->value, + $item->keyName instanceof ConstExprIntegerNode => (int) $item->keyName->value, + $item->keyName instanceof IdentifierTypeNode => $item->keyName->name, + $item->keyName !== null => (string) $item->keyName, + default => $autoIdx, + }; + + if (\is_int($itemKey)) { + $autoIdx = max($autoIdx, $itemKey + 1); + } + + if ($itemKey === $key) { + return (string) $item->valueType; + } + } + } + + if ($typeNode->unsealedType !== null) { + return (string) $typeNode->unsealedType->valueType; + } + } + + return self::deduceElementType($containerTypeString); + } + + /** + * Deduces the property type of an object shape or class property access ($obj->prop). + */ + public static function deducePropertyType(string $containerTypeString, string $propName): ?string + { + $typeNode = self::parseTypeString($containerTypeString); + if ($typeNode === null) { + return null; + } + + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof ObjectShapeNode) { + foreach ($typeNode->items as $item) { + $name = $item->keyName instanceof IdentifierTypeNode + ? $item->keyName->name + : (string) $item->keyName; + + if ($name === $propName) { + return (string) $item->valueType; + } + } + } + + if ($typeNode instanceof IdentifierTypeNode) { + $className = $typeNode->name; + if ( + class_exists($className, false) || class_exists($className) + || interface_exists($className, false) || interface_exists($className) + || trait_exists($className, false) || trait_exists($className) + ) { + $propType = DocblockParser::parseProperty($className, $propName); + if ($propType !== null) { + return (string) $propType; + } + } + } + + return null; + } + + private static function parseTypeString(string $typeString): ?TypeNode + { + if (isset(self::$parsedTypeCache[$typeString])) { + return self::$parsedTypeCache[$typeString]; + } + + try { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + + return self::$parsedTypeCache[$typeString] = $typeParser->parse($tokens); + } catch (\Throwable) { + return null; + } + } +} diff --git a/src/Internal/Ast/TypePHPPrinter.php b/src/Internal/Ast/TypePHPPrinter.php index 61d49321..45df3ac9 100644 --- a/src/Internal/Ast/TypePHPPrinter.php +++ b/src/Internal/Ast/TypePHPPrinter.php @@ -16,6 +16,17 @@ */ final class TypePHPPrinter extends Standard { + /** + * Enables native format-preserving insertion into empty method and function statement lists. + */ + protected function initializeEmptyListInsertionMap(): void + { + parent::initializeEmptyListInsertionMap(); + + $this->emptyListInsertionMap[Node\Stmt\ClassMethod::class . '->stmts'] = ['{', ' ', ' ']; + $this->emptyListInsertionMap[Node\Stmt\Function_::class . '->stmts'] = ['{', ' ', ' ']; + } + /** * Overrides base node printing to intercept injected statements and squash their formatting. */ diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 85a74163..85b416d9 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -4,6 +4,7 @@ namespace TypePHP\Internal\Checker; +use ReflectionProperty; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StructureMutator; @@ -14,6 +15,22 @@ */ final class MemberAssignChecker { + /** + * In-memory 2D cache for ReflectionProperty instances: + * [$className][$propName] => ?ReflectionProperty (null = non-declared/dynamic property) + * + * @var array> + */ + private static array $refPropertyCache = []; + + /** + * Resets the cached reflection property registry. + */ + public static function reset(): void + { + self::$refPropertyCache = []; + } + /** * Evaluates member mutation assignment against the declared type contract. * @@ -65,4 +82,82 @@ public static function check( return $value; } + + /** + * Evaluates dimension/member mutation assignment on an object or static property. + * + * @param list $chain + */ + public static function checkProperty( + mixed $objectOrClass, + string $propName, + array $chain, + mixed $value, + string $file, + TypeValidatorRegistry $registry + ): mixed { + if (! \is_object($objectOrClass) && ! \is_string($objectOrClass)) { + return $value; + } + + $className = \is_string($objectOrClass) ? $objectOrClass : $objectOrClass::class; + + if (isset(InlineChecker::$nullPropertyCache[$className][$propName]) || ! Config::isInlinePropertiesEnabled()) { + return $value; + } + + $currentVal = self::readPropertyValue($objectOrClass, $className, $propName); + $copy = StructureMutator::mutateCopy($currentVal, $chain, $value); + + $res = InlineChecker::checkProperty($copy, $objectOrClass, $propName, $file, $registry); + + if ($res instanceof ErrorMessage) { + return $res; + } + + return $value; + } + + /** + * Safely reads the current value of an instance or static property across all visibilities. + */ + private static function readPropertyValue(mixed $objectOrClass, string $className, string $propName): mixed + { + try { + $refProp = self::getReflectionProperty($className, $propName); + + if ($refProp !== null) { + if ($refProp->isStatic()) { + return $refProp->isInitialized() ? $refProp->getValue() : []; + } + + if (\is_object($objectOrClass)) { + return $refProp->isInitialized($objectOrClass) ? $refProp->getValue($objectOrClass) : []; + } + } elseif (\is_object($objectOrClass)) { + // @phpstan-ignore property.dynamicName + return $objectOrClass->$propName ?? []; + } + } catch (\Throwable) { + } + + return []; + } + + /** + * Resolves and memoizes ReflectionProperty descriptors, caching both declared properties and dynamic misses. + */ + private static function getReflectionProperty(string $className, string $propName): ?ReflectionProperty + { + if (isset(self::$refPropertyCache[$className]) && \array_key_exists($propName, self::$refPropertyCache[$className])) { + return self::$refPropertyCache[$className][$propName]; + } + + if (property_exists($className, $propName)) { + /** @var class-string $className */ + return self::$refPropertyCache[$className][$propName] = new ReflectionProperty($className, $propName); + } + + return self::$refPropertyCache[$className][$propName] = null; + } } diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 754d01e2..e75f1e79 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1040,7 +1040,7 @@ private static function inferGenericObjectNode( try { $targetRef = new \ReflectionClass($targetClassFqcn); $targetDoc = StubManager::getClassDoc($targetClassFqcn) ?? $targetRef->getDocComment(); - if ($targetDoc !== false && $targetDoc !== null) { + if ($targetDoc !== false) { $targetPhpDocNode = DocblockExtractor::parseDocString($targetDoc); $targetTemplateNames = array_keys(DocblockExtractor::extractTemplates($targetPhpDocNode)); } diff --git a/src/Internal/Cli/CacheClearCommand.php b/src/Internal/Cli/CacheClearCommand.php index 556dd83a..bbef24b3 100644 --- a/src/Internal/Cli/CacheClearCommand.php +++ b/src/Internal/Cli/CacheClearCommand.php @@ -7,7 +7,7 @@ use TypePHP\Internal\Io\CacheManager; /** - * @Command Clears the TypePHP cache. + * @internal Clears the TypePHP cache. */ final class CacheClearCommand implements CommandInterface { diff --git a/src/Internal/Cli/CommandRunner.php b/src/Internal/Cli/CommandRunner.php index eeb195b1..985e854a 100644 --- a/src/Internal/Cli/CommandRunner.php +++ b/src/Internal/Cli/CommandRunner.php @@ -4,6 +4,9 @@ namespace TypePHP\Internal\Cli; +/** + * @internal + */ final class CommandRunner { private const KNOWN_COMMANDS = [ diff --git a/src/Internal/Cli/ConfigInitCommand.php b/src/Internal/Cli/ConfigInitCommand.php index 9d00adc1..2e3cfb74 100644 --- a/src/Internal/Cli/ConfigInitCommand.php +++ b/src/Internal/Cli/ConfigInitCommand.php @@ -4,6 +4,9 @@ namespace TypePHP\Internal\Cli; +/** + * @internal + */ final class ConfigInitCommand implements CommandInterface { public function execute(array $args, $outputStream = STDOUT, $errorStream = STDERR): int @@ -53,6 +56,29 @@ private static function getTemplate(): string */ 'enabled' => true, + /* + |-------------------------------------------------------------------------- + | Eliminate Statically Proven Checks (Compile-Time Optimization) + |-------------------------------------------------------------------------- + | When true (default), TypePHP analyzes AST expressions during file + | transformation and omits runtime assertions for code that is + | mathematically or logically proven to satisfy the DocBlock contract at + | compile time (e.g. literal returns, property defaults, empty arrays, + | constant wildcards, and exact non-generic object instantiations). + | + | Dynamic expressions, variables, and generic objects continue to be + | deferred to strict runtime checks. + | + | Set to false for deep debugging, tracing every single check in stack traces, + | or benchmarking unoptimized AST instrumentation. + | + | Can also be set via environment variable: + | TYPEPHP_ELIMINATE_STATICALLY_PROVEN_CHECKS=false + | Can also be configured in root composer.json: + | "extra": { "typephp": { "eliminate-statically-proven-checks": false } } + */ + 'eliminate_statically_proven_checks' => true, + /* |-------------------------------------------------------------------------- | Auto-Boot on Composer Autoload diff --git a/src/Internal/Cli/HelpCommand.php b/src/Internal/Cli/HelpCommand.php index 8d4e8d4c..13db9b2a 100644 --- a/src/Internal/Cli/HelpCommand.php +++ b/src/Internal/Cli/HelpCommand.php @@ -4,6 +4,9 @@ namespace TypePHP\Internal\Cli; +/** + * @internal + */ final class HelpCommand implements CommandInterface { public function execute(array $args, $outputStream = STDOUT, $errorStream = STDERR): int diff --git a/src/Internal/Docblock/DocblockExtractor.php b/src/Internal/Docblock/DocblockExtractor.php index cc780f64..6560fadd 100644 --- a/src/Internal/Docblock/DocblockExtractor.php +++ b/src/Internal/Docblock/DocblockExtractor.php @@ -44,6 +44,18 @@ final class DocblockExtractor private static ?Lexer $lexer = null; + private const TEMPLATE_TAG_PRIORITIES = [ + '@template' => 1, + '@template-covariant' => 1, + '@template-contravariant' => 1, + '@psalm-template' => 2, + '@psalm-template-covariant' => 2, + '@psalm-template-contravariant' => 2, + '@phpstan-template' => 3, + '@phpstan-template-covariant' => 3, + '@phpstan-template-contravariant' => 3, + ]; + /** * Resets the parsed docblock cache. Useful for test isolation. */ @@ -357,27 +369,50 @@ public static function getVarTags(PhpDocNode $node): array } /** - * Extracts all @template tags with priority: @phpstan-template-* > @psalm-template-* > @template-*. + * Extracts all @template tags in declaration order with priority: @phpstan-template-* > @psalm-template-* > @template-*. + * Merges bounds and defaults when variance and bounds are split across multiple tags for the same template. * * @return array */ public static function extractTemplates(PhpDocNode $node): array { $templates = []; + $priorities = []; - $priorityGroups = [ - ['@template', '@template-covariant', '@template-contravariant'], - ['@psalm-template', '@psalm-template-covariant', '@psalm-template-contravariant'], - ['@phpstan-template', '@phpstan-template-covariant', '@phpstan-template-contravariant'], - ]; + foreach ($node->getTags() as $tagNode) { + $priority = self::TEMPLATE_TAG_PRIORITIES[$tagNode->name] ?? null; + if ($priority === null || ! ($tagNode->value instanceof TemplateTagValueNode)) { + continue; + } - foreach ($priorityGroups as $tagNames) { - foreach ($tagNames as $tagName) { - foreach ($node->getTagsByName($tagName) as $tagNode) { - if ($tagNode->value instanceof TemplateTagValueNode) { - $templates[$tagNode->value->name] = $tagNode->value; - } - } + $newTag = $tagNode->value; + $tName = $newTag->name; + + if (! isset($templates[$tName])) { + $templates[$tName] = $newTag; + $priorities[$tName] = $priority; + + continue; + } + + $existingTag = $templates[$tName]; + $existingPriority = $priorities[$tName]; + + if ($priority >= $existingPriority) { + $templates[$tName] = new TemplateTagValueNode( + $tName, + $newTag->bound ?? $existingTag->bound, + $newTag->description !== '' ? $newTag->description : $existingTag->description, + $newTag->default ?? $existingTag->default + ); + $priorities[$tName] = $priority; + } else { + $templates[$tName] = new TemplateTagValueNode( + $tName, + $existingTag->bound ?? $newTag->bound, + $existingTag->description !== '' ? $existingTag->description : $newTag->description, + $existingTag->default ?? $newTag->default + ); } } @@ -385,36 +420,38 @@ public static function extractTemplates(PhpDocNode $node): array } /** - * Extracts declared template variances ('covariant', 'contravariant', or 'invariant') per template name. + * Extracts declared template variances ('covariant', 'contravariant', or 'invariant') per template name in declaration order. * * @return array */ public static function extractTemplateVariances(PhpDocNode $node): array { $variances = []; + $priorities = []; - $priorityGroups = [ - ['@template', '@template-covariant', '@template-contravariant'], - ['@psalm-template', '@psalm-template-covariant', '@psalm-template-contravariant'], - ['@phpstan-template', '@phpstan-template-covariant', '@phpstan-template-contravariant'], - ]; + foreach ($node->getTags() as $tagNode) { + $priority = self::TEMPLATE_TAG_PRIORITIES[$tagNode->name] ?? null; + if ($priority === null || ! ($tagNode->value instanceof TemplateTagValueNode)) { + continue; + } - foreach ($priorityGroups as $tagNames) { - foreach ($tagNames as $tagName) { - foreach ($node->getTagsByName($tagName) as $tagNode) { - if ($tagNode->value instanceof TemplateTagValueNode) { - $tName = $tagNode->value->name; - $lowerTag = strtolower($tagNode->name); - - if (str_contains($lowerTag, 'covariant')) { - $variances[$tName] = 'covariant'; - } elseif (str_contains($lowerTag, 'contravariant')) { - $variances[$tName] = 'contravariant'; - } else { - $variances[$tName] = 'invariant'; - } - } + $tName = $tagNode->value->name; + $lowerTag = strtolower($tagNode->name); + + $variance = match (true) { + str_contains($lowerTag, 'covariant') => 'covariant', + str_contains($lowerTag, 'contravariant') => 'contravariant', + default => 'invariant', + }; + + if (! isset($priorities[$tName])) { + $variances[$tName] = $variance; + $priorities[$tName] = $priority; + } elseif ($priority >= $priorities[$tName]) { + if ($variance !== 'invariant' || $variances[$tName] === 'invariant') { + $variances[$tName] = $variance; } + $priorities[$tName] = $priority; } } @@ -590,7 +627,7 @@ public static function resolveImportedTypeAlias(string $fqcn, string $importedAl $ref = new \ReflectionClass($fqcn); $doc = $stubDoc ?? $ref->getDocComment(); - if ($doc === false || $doc === null) { + if ($doc === false) { return null; } diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index 92a30c98..a7eb5506 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -1106,7 +1106,7 @@ private static function parseFunction(\ReflectionFunction $ref): array } } - if ($doc === false || $doc === null || self::shouldIgnoreDoc($doc)) { + if ($doc === false || self::shouldIgnoreDoc($doc)) { return [ 'types' => [], 'paramOuts' => [], @@ -1576,7 +1576,7 @@ private static function applyConstructorPromotionFallback( $stubDoc = StubManager::getPropertyDoc($className, $paramName); $propDoc = $stubDoc ?? $propertyRef->getDocComment(); - if ($propDoc !== false && $propDoc !== null) { + if ($propDoc !== false) { $propType = DocblockExtractor::extractTypeFromPropertyDoc($propDoc, $paramName); if ($propType !== null) { $substitutedProp = self::substituteAliases($propType, $aliases); diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index f40f8085..2ec53725 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -502,7 +502,7 @@ public static function getDeclaredClassTemplateNames(string $className): array /** @var class-string $className */ $ref = new \ReflectionClass($className); $doc = StubManager::getClassDoc($className) ?? $ref->getDocComment(); - if ($doc !== false && $doc !== null) { + if ($doc !== false) { $phpDocNode = DocblockExtractor::parseDocString($doc); $templates = DocblockExtractor::extractTemplates($phpDocNode); @@ -682,6 +682,8 @@ public static function getBoundTemplates(string $function, object|string|null $t public static function hasInstanceBindings(object $instance): bool { + self::ensureInstanceInherited($instance); + return self::$instanceTemplateBindings !== null && isset(self::$instanceTemplateBindings[$instance]); } @@ -715,7 +717,7 @@ public static function getTemplateVariances(object $instance): array $ref = new \ReflectionClass($instance); $classDoc = $stubDoc ?? $ref->getDocComment(); - if ($classDoc !== false && $classDoc !== null) { + if ($classDoc !== false) { $classPhpDocNode = DocblockExtractor::parseDocString($classDoc); return DocblockExtractor::extractTemplateVariances($classPhpDocNode); @@ -1187,7 +1189,7 @@ private static function collectInheritedGenericTagBindings( $parentRef = new \ReflectionClass($parentName); $parentDoc = $stubDoc ?? $parentRef->getDocComment(); - if ($parentDoc === false || $parentDoc === null) { + if ($parentDoc === false) { return; } @@ -1251,7 +1253,7 @@ private static function collectDocsForClassHierarchyMember(\ReflectionClass $hie $stubDoc = StubManager::getClassDoc($hierClass->getName()); $classDoc = $stubDoc ?? $hierClass->getDocComment(); - if ($classDoc !== false && $classDoc !== null) { + if ($classDoc !== false) { $docs[] = $classDoc; } @@ -1730,7 +1732,11 @@ private static function getTopCallFrame(string $function): ?array private static function ensureInstanceInherited(object $instance): void { if (self::$instanceTemplateBindings === null || ! isset(self::$instanceTemplateBindings[$instance])) { - self::resolveInheritedTemplates($instance, $instance::class); + if (self::$pendingCloneSource !== null && is_a($instance, self::$pendingCloneSource::class)) { + self::copyInstanceBindings(self::$pendingCloneSource, $instance); + } else { + self::resolveInheritedTemplates($instance, $instance::class); + } } } diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index ae7717be..54b4bfd1 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -15,7 +15,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.11.4_'; + public const VERSION_PREFIX = 'v0.12.0_'; /** * Cached absolute cache directory path. diff --git a/src/Internal/Io/StreamWrapper.php b/src/Internal/Io/StreamWrapper.php index d1603f54..54a24f38 100644 --- a/src/Internal/Io/StreamWrapper.php +++ b/src/Internal/Io/StreamWrapper.php @@ -288,7 +288,7 @@ public static function transformSource(string $source, string $filePath = ''): s $newStmts = $traverser1->traverse($nodesToTraverse); $traverser2 = new NodeTraverser(); - $traverser2->addVisitor(new ContractVisitor()); + $traverser2->addVisitor(new ContractVisitor($filePath)); $newStmts = $traverser2->traverse($newStmts); $printer = self::getPrinter(); @@ -298,29 +298,15 @@ public static function transformSource(string $source, string $filePath = ''): s $transformedLineCount = substr_count($transformed, "\n"); $drift = $transformedLineCount - $originalLineCount; - $count0 = 0; - $count1 = 0; - $count2 = 0; - $count3 = 0; if ($drift > 0) { - $transformed = preg_replace('/[ \t]*\r?\n[ \t]*\/\*__TYPEPHP_INJECTED_START__\*\//', ' /*__TYPEPHP_INJECTED_START__*/', $transformed, $drift, $count0) ?? $transformed; - $drift -= $count0; - } - - if ($drift > 0) { - $transformed = preg_replace('/[ \t]*\r?\n[ \t]*\{[ \t]*\/\*__TYPEPHP_INJECTED_START__\*\//', ' { /*__TYPEPHP_INJECTED_START__*/', $transformed, $drift, $count1) ?? $transformed; - $drift -= $count1; - } - - if ($drift > 0) { - $transformed = preg_replace('/\/\*__TYPEPHP_INJECTED_END__\*\/[ \t]*\r?\n[ \t]*\}/', '/*__TYPEPHP_INJECTED_END__*/ }', $transformed, $drift, $count2) ?? $transformed; - $drift -= $count2; - } - - if ($drift > 0) { - $transformed = preg_replace('/\/\*__TYPEPHP_INJECTED_END__\*\/[ \t]*\r?\n[ \t]*/', '/*__TYPEPHP_INJECTED_END__*/ ', $transformed, $drift, $count3) ?? $transformed; - $drift -= $count3; + $transformed = preg_replace( + '/[ \t]*\r?\n[ \t]*\/\*__TYPEPHP_INJECTED_START__\*\//', + ' /*__TYPEPHP_INJECTED_START__*/', + $transformed, + $drift + ) ?? $transformed; + $drift = substr_count($transformed, "\n") - $originalLineCount; } if ($drift < 0) { @@ -918,7 +904,13 @@ private function openMemoryStream(string $resolvedPath): bool return false; } - $transformed = self::transformSource($source, $resolvedPath); + self::register(); + + try { + $transformed = self::transformSource($source, $resolvedPath); + } finally { + self::unregister(); + } $memHandle = fopen('php://memory', 'r+'); if ($memHandle !== false) { @@ -947,7 +939,15 @@ private function openCachedStream(string $resolvedPath, string $mode): bool if ($source === false) { return false; } - $transformed = self::transformSource($source, $resolvedPath); + + self::register(); + + try { + $transformed = self::transformSource($source, $resolvedPath); + } finally { + self::unregister(); + } + if (! CacheManager::writeCachedFileSafely($cachedFile, $transformed)) { return $this->openMemoryStream($resolvedPath); } diff --git a/src/Internal/Resolver/CallerBoundaryResolver.php b/src/Internal/Resolver/CallerBoundaryResolver.php index d5c537fd..a5caa999 100644 --- a/src/Internal/Resolver/CallerBoundaryResolver.php +++ b/src/Internal/Resolver/CallerBoundaryResolver.php @@ -62,7 +62,7 @@ public static function shouldBypassCallback(mixed $callable, string $prefix = '' try { $ref = new ReflectionFunction($callable); $file = $ref->getFileName(); - if ($file !== false && $file !== null) { + if ($file !== false) { $normalized = PathMatcher::normalizePath($file); return PathMatcher::isVendorPath($normalized); diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 78ab8279..ba0212a5 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -1224,7 +1224,7 @@ public static function resolveFqcn(string $name, \ReflectionClass|\ReflectionFun $ref instanceof \ReflectionFunction => $ref->getNamespaceName(), }; - $resolved = self::resolveNameFromImportsAndNamespace($name, [], $namespace); + $resolved = self::resolveNameFromImportsAndNamespace($name, [], $namespace, true); if (isset(self::OVERRIDABLE_SCALAR_ALIASES[$lower]) && $resolved === $name && ! self::symbolExists($name)) { return self::$fqcnCache[$contextKey][$name] = $name; @@ -1236,7 +1236,7 @@ public static function resolveFqcn(string $name, \ReflectionClass|\ReflectionFun /** * Resolves a short class name to its FQCN purely based on file context with 2D caching. */ - public static function resolveFqcnForFile(string $name, string $file): string + public static function resolveFqcnForFile(string $name, string $file, bool $autoload = true): string { $file = str_replace('\\', '/', $file); $lower = strtolower($name); @@ -1255,20 +1255,21 @@ public static function resolveFqcnForFile(string $name, string $file): string return $name; } - if (isset(self::$fileFqcnCache[$file][$name])) { - return self::$fileFqcnCache[$file][$name]; + $cacheKey = $autoload ? $name : ($name . ':no_auto'); + if (isset(self::$fileFqcnCache[$file][$cacheKey])) { + return self::$fileFqcnCache[$file][$cacheKey]; } $imports = self::getUseImportsFromFile($file); $namespace = self::getNamespaceFromFile($file); - $resolved = self::resolveNameFromImportsAndNamespace($name, $imports, $namespace); + $resolved = self::resolveNameFromImportsAndNamespace($name, $imports, $namespace, $autoload); - if (isset(self::OVERRIDABLE_SCALAR_ALIASES[$lower]) && $resolved === $name && ! self::symbolExists($name)) { - return self::$fileFqcnCache[$file][$name] = $name; + if (isset(self::OVERRIDABLE_SCALAR_ALIASES[$lower]) && $resolved === $name && ! self::symbolExists($name, $autoload)) { + return self::$fileFqcnCache[$file][$cacheKey] = $name; } - return self::$fileFqcnCache[$file][$name] = $resolved; + return self::$fileFqcnCache[$file][$cacheKey] = $resolved; } /** @@ -1276,8 +1277,12 @@ public static function resolveFqcnForFile(string $name, string $file): string * * @param array $imports */ - private static function resolveNameFromImportsAndNamespace(string $name, array $imports, string $namespace): string - { + private static function resolveNameFromImportsAndNamespace( + string $name, + array $imports, + string $namespace, + bool $autoload = true + ): string { if (isset($imports[$name])) { return $imports[$name]; } @@ -1285,33 +1290,33 @@ private static function resolveNameFromImportsAndNamespace(string $name, array $ if (! str_contains($name, '\\')) { if ($namespace !== '') { $namespacedClass = $namespace . '\\' . $name; - if (self::symbolExists($namespacedClass)) { + if (self::symbolExists($namespacedClass, $autoload)) { return $namespacedClass; } } - if (self::symbolExists($name)) { + if (self::symbolExists($name, $autoload)) { return $name; } return $name; } - if (self::symbolExists($name)) { + if (self::symbolExists($name, $autoload)) { return $name; } [$firstPart, $subPart] = explode('\\', $name, 2); if (isset($imports[$firstPart])) { $candidate = $imports[$firstPart] . '\\' . $subPart; - if (self::symbolExists($candidate)) { + if (self::symbolExists($candidate, $autoload)) { return $candidate; } } if ($namespace !== '') { $namespacedClass = $namespace . '\\' . $name; - if (self::symbolExists($namespacedClass)) { + if (self::symbolExists($namespacedClass, $autoload)) { return $namespacedClass; } } @@ -1320,15 +1325,24 @@ private static function resolveNameFromImportsAndNamespace(string $name, array $ } /** - * Fast-checks in-memory symbol tables before invoking autoloader. + * Checks in-memory symbol tables before optionally invoking autoloader. */ - private static function symbolExists(string $symbol): bool + private static function symbolExists(string $symbol, bool $autoload = true): bool { - return class_exists($symbol, false) + if ( + class_exists($symbol, false) || interface_exists($symbol, false) || enum_exists($symbol, false) || trait_exists($symbol, false) - || class_exists($symbol) + ) { + return true; + } + + if (! $autoload) { + return false; + } + + return class_exists($symbol) || interface_exists($symbol) || enum_exists($symbol) || trait_exists($symbol); @@ -1455,7 +1469,7 @@ public static function parseFileMetadata(string $fileName, string $source): void continue; } - if ($token->id === T_USE && $classStack !== []) { + if ($token->id === T_USE) { $isClosureUse = false; for ($j = $i + 1; $j < $count; $j++) { if ($tokens[$j]->id === T_WHITESPACE || $tokens[$j]->id === T_COMMENT) { @@ -1468,7 +1482,11 @@ public static function parseFileMetadata(string $fileName, string $source): void break; } - if (! $isClosureUse) { + if ($isClosureUse) { + continue; + } + + if ($classStack !== []) { for ($k = $i - 1; $k >= 0; $k--) { if ($tokens[$k]->id === T_DOC_COMMENT) { $top = end($classStack); @@ -1484,12 +1502,10 @@ public static function parseFileMetadata(string $fileName, string $source): void break; } } - } - continue; - } + continue; + } - if ($token->id === T_USE && $classStack === []) { $useStatement = ''; for ($j = $i + 1; $j < $count; $j++) { if ($tokens[$j]->text === ';') { diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 4ac48c47..28e4c2ad 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -67,6 +67,48 @@ public static function isEnabled(): bool return Config::isEnabled(); } + /** + * Evaluates member/dimension mutation assignments on an object or static property + * ($obj->prop[$key] = $val or Class::$prop[$key] = $val) atomically before writing. + * + * @param list $chain + */ + public static function checkPropertyMemberAssign( + mixed $objectOrClass, + string $propName, + array $chain, + mixed $value, + string $file + ): mixed { + $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); + if ($className !== '' && isset(InlineChecker::$nullPropertyCache[$className][$propName])) { + return $value; + } + + if (! Config::isEnabled() || ! Config::isInlinePropertiesEnabled()) { + return $value; + } + + $res = MemberAssignChecker::checkProperty( + $objectOrClass, + $propName, + $chain, + $value, + $file, + self::getRegistry() + ); + + if ($res instanceof ErrorMessage) { + if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName)) { + return $value; + } + + return ViolationCollector::handle($res, 'property', $value, $file, null, $className . '::$' . $propName, '$' . $propName); + } + + return $res; + } + /** * Evaluates member mutation assignments ($arr[$key] = $val or $obj->prop = $val) * against the root variable's type contract atomically before writing. diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index d92bfd1b..3b7d55e9 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\Checker\MemberAssignChecker; use TypePHP\Internal\Checker\ParamChecker; use TypePHP\Internal\Checker\ReturnChecker; use TypePHP\Internal\Docblock\DocblockParser; @@ -98,6 +99,8 @@ final class Config private static bool $inlineObjects = true; + private static bool $eliminateStaticallyProvenChecks = true; + private static int $ignoreTraceDepth = 25; private static function getEnvValue(string $key): ?string @@ -153,6 +156,20 @@ public static function isEnabled(): bool return self::$enabled; } + public static function isEliminateStaticallyProvenChecksEnabled(): bool + { + $env = self::getEnvValue('TYPEPHP_ELIMINATE_STATICALLY_PROVEN_CHECKS'); + if ($env !== null && trim($env) !== '') { + return filter_var($env, FILTER_VALIDATE_BOOLEAN); + } + + if (self::$cachedConfig === null) { + self::get(); + } + + return self::$eliminateStaticallyProvenChecks; + } + public static function isAutoBootEnabled(): bool { $envAutoBoot = self::getEnvValue('TYPEPHP_AUTO_BOOT'); @@ -586,6 +603,7 @@ public static function get(): array $defaultConfig = [ 'enabled' => true, + 'eliminate_statically_proven_checks' => true, 'auto_boot' => true, 'on_violation' => 'throw', 'report_file' => null, @@ -670,6 +688,9 @@ public static function get(): array if (! isset($userConfig['auto_boot']) && isset($data['extra']['typephp']['auto-boot'])) { $userConfig['auto_boot'] = filter_var($data['extra']['typephp']['auto-boot'], FILTER_VALIDATE_BOOLEAN); } + if (! isset($userConfig['eliminate_statically_proven_checks']) && isset($data['extra']['typephp']['eliminate-statically-proven-checks'])) { + $userConfig['eliminate_statically_proven_checks'] = filter_var($data['extra']['typephp']['eliminate-statically-proven-checks'], FILTER_VALIDATE_BOOLEAN); + } if (! isset($userConfig['on_violation']) && isset($data['extra']['typephp']['on-violation']) && \is_string($data['extra']['typephp']['on-violation'])) { $userConfig['on_violation'] = $data['extra']['typephp']['on-violation']; } @@ -742,6 +763,7 @@ public static function set(array $config): void DocblockParser::reset(); ParamChecker::reset(); + MemberAssignChecker::reset(); ReturnChecker::reset(); FileFilter::reset(); PathMatcher::reset(); @@ -803,6 +825,7 @@ public static function reset(): void self::$resolvedConfigFile = null; self::$enabled = true; self::$autoBoot = true; + self::$eliminateStaticallyProvenChecks = true; self::$onViolation = 'throw'; self::$reportFile = null; self::$failOnReport = false; @@ -856,6 +879,7 @@ private static function syncFlags(array $config): void { self::$enabled = (bool) ($config['enabled'] ?? true); self::$autoBoot = (bool) ($config['auto_boot'] ?? true); + self::$eliminateStaticallyProvenChecks = (bool) ($config['eliminate_statically_proven_checks'] ?? true); self::$onViolation = \is_string($config['on_violation'] ?? null) && trim($config['on_violation']) !== '' ? strtolower(trim($config['on_violation'])) : 'throw'; diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 62015d81..756c4342 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -67,6 +67,14 @@ final class GenericValidator implements TypeValidatorInterface */ private static array $maskOfCache = []; + public static function reset(): void + { + self::$constantCache = []; + self::$enumKeyCache = []; + self::$enumValueCache = []; + self::$maskOfCache = []; + } + /** * Validates a value against a GenericTypeNode AST. */ @@ -89,6 +97,22 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali }; } + /** + * Extracts an integer flag from an int literal or an int BackedEnum case. + */ + private static function extractIntFlag(mixed $val): ?int + { + if (\is_int($val)) { + return $val; + } + + if ($val instanceof \BackedEnum && \is_int($val->value)) { + return $val->value; + } + + return null; + } + private function validateKeyOf(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { $targetType = $node->genericTypes[0] ?? null; @@ -311,16 +335,18 @@ private function computeAllowedMask(array $genericTypes): int $allowedMask |= (int) $expr->value; } elseif ($expr instanceof ConstFetchNode) { $constVal = $this->resolveConstantValue($expr->className, $expr->name); - if (\is_int($constVal)) { - $allowedMask |= $constVal; + $intVal = self::extractIntFlag($constVal); + if ($intVal !== null) { + $allowedMask |= $intVal; } } } elseif ($typeNode instanceof IdentifierTypeNode) { $target = $this->extractConstantTarget($typeNode); if ($target !== null) { $constVal = $this->resolveConstantValue($target[0], $target[1]); - if (\is_int($constVal)) { - $allowedMask |= $constVal; + $intVal = self::extractIntFlag($constVal); + if ($intVal !== null) { + $allowedMask |= $intVal; } } } @@ -346,7 +372,13 @@ private function validateIntMaskOf(mixed $value, GenericTypeNode $node, string $ if ($targetType instanceof UnionTypeNode) { [$allowedMask, $foundFlags] = $this->computeMaskOfUnion($targetType); } else { - $target = $this->extractConstantTarget($targetType); + $target = null; + if ($targetType instanceof IdentifierTypeNode && ClassNameValidator::isValid($targetType->name) && enum_exists($targetType->name)) { + $target = [$targetType->name, '*']; + } else { + $target = $this->extractConstantTarget($targetType); + } + if ($target !== null && $target[1] !== '') { [$allowedMask, $foundFlags] = $this->resolveMaskOfPattern($target[0], $target[1]); } @@ -375,8 +407,9 @@ private function computeMaskOfUnion(UnionTypeNode $targetType): array $foundFlags = true; } elseif ($expr instanceof ConstFetchNode) { $val = $this->resolveConstantValue($expr->className, $expr->name); - if (\is_int($val)) { - $allowedMask |= $val; + $intVal = self::extractIntFlag($val); + if ($intVal !== null) { + $allowedMask |= $intVal; $foundFlags = true; } } @@ -384,8 +417,9 @@ private function computeMaskOfUnion(UnionTypeNode $targetType): array $target = $this->extractConstantTarget($unionMember); if ($target !== null) { $val = $this->resolveConstantValue($target[0], $target[1]); - if (\is_int($val)) { - $allowedMask |= $val; + $intVal = self::extractIntFlag($val); + if ($intVal !== null) { + $allowedMask |= $intVal; $foundFlags = true; } } @@ -410,26 +444,30 @@ private function resolveMaskOfPattern(string $className, string $pattern): array $foundFlags = false; if ($className !== '') { - if (class_exists($className) || interface_exists($className)) { + if (class_exists($className) || interface_exists($className) || enum_exists($className)) { + /** @var class-string $className */ $refClass = new \ReflectionClass($className); if (str_contains($pattern, '*')) { $regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i'; foreach ($refClass->getConstants() as $cName => $cValue) { - if (\is_int($cValue) && preg_match($regex, $cName) === 1) { - $allowedMask |= $cValue; + $intVal = self::extractIntFlag($cValue); + if ($intVal !== null && preg_match($regex, $cName) === 1) { + $allowedMask |= $intVal; $foundFlags = true; } } } else { $cValue = $this->resolveConstantValue($className, $pattern); - if (\is_int($cValue)) { - $allowedMask |= $cValue; + $intVal = self::extractIntFlag($cValue); + if ($intVal !== null) { + $allowedMask |= $intVal; $foundFlags = true; } elseif (\is_array($cValue)) { foreach ($cValue as $item) { - if (\is_int($item)) { - $allowedMask |= $item; + $itemVal = self::extractIntFlag($item); + if ($itemVal !== null) { + $allowedMask |= $itemVal; $foundFlags = true; } } @@ -447,8 +485,9 @@ private function resolveMaskOfPattern(string $className, string $pattern): array } } else { $cValue = $this->resolveConstantValue('', $pattern); - if (\is_int($cValue)) { - $allowedMask |= $cValue; + $intVal = self::extractIntFlag($cValue); + if ($intVal !== null) { + $allowedMask |= $intVal; $foundFlags = true; } } @@ -781,10 +820,6 @@ private function validateObjectGeneric(mixed $value, GenericTypeNode $node, stri return RuntimeTypeChecker::bindInstanceFromNode($value, $node, $context); } - // ========================================================================= - // SHARED UTILITIES - // ========================================================================= - /** * Extracts constant class name and constant name from ConstTypeNode or IdentifierTypeNode. * @@ -840,7 +875,8 @@ private function resolveConstantValue(string $fqcn, string $constName): mixed if (! \array_key_exists($cacheKey, self::$constantCache)) { $constValue = false; if ($fqcn !== '') { - if (class_exists($fqcn) || interface_exists($fqcn)) { + if (class_exists($fqcn) || interface_exists($fqcn) || enum_exists($fqcn)) { + /** @var class-string $fqcn */ $refClass = new \ReflectionClass($fqcn); if ($refClass->hasConstant($constName)) { $constValue = $refClass->getConstant($constName); diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index f3abfc2d..fbf1bc92 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -51,6 +51,7 @@ final class TypeValidatorRegistry public static function reset(): void { + GenericValidator::reset(); } public function __construct() diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index 7ccba227..9d9176d2 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -193,9 +193,7 @@ private static function createDispatcherClosure( if (! $hasAnyRef) { return function (...$args) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { - $effectiveTypeNode = $typeNode->templateTypes !== [] - ? self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName) - : $typeNode; + $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); self::validateCallbackArguments($effectiveTypeNode, $args, $prefix, $registry, $callable); @@ -211,9 +209,7 @@ private static function createDispatcherClosure( if ($isVariadicRef) { return function (&...$args) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { - $effectiveTypeNode = $typeNode->templateTypes !== [] - ? self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName) - : $typeNode; + $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); self::validateCallbackArguments($effectiveTypeNode, $args, $prefix, $registry, $callable); @@ -232,9 +228,7 @@ private static function createDispatcherClosure( if ($refPattern === [true]) { return function (mixed &$a = null) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { $args = [&$a]; - $effectiveTypeNode = $typeNode->templateTypes !== [] - ? self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName) - : $typeNode; + $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); self::validateCallbackArguments($effectiveTypeNode, $args, $prefix, $registry, $callable); @@ -253,9 +247,7 @@ private static function createDispatcherClosure( if ($refPattern === [true, false]) { return function (mixed &$a = null, mixed $b = null) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { $args = [&$a, $b]; - $effectiveTypeNode = $typeNode->templateTypes !== [] - ? self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName) - : $typeNode; + $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); self::validateCallbackArguments($effectiveTypeNode, $args, $prefix, $registry, $callable); @@ -274,9 +266,7 @@ private static function createDispatcherClosure( if ($refPattern === [false, true]) { return function (mixed $a = null, mixed &$b = null) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { $args = [$a, &$b]; - $effectiveTypeNode = $typeNode->templateTypes !== [] - ? self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName) - : $typeNode; + $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); self::validateCallbackArguments($effectiveTypeNode, $args, $prefix, $registry, $callable); @@ -295,9 +285,7 @@ private static function createDispatcherClosure( if ($refPattern === [true, true]) { return function (mixed &$a = null, mixed &$b = null) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { $args = [&$a, &$b]; - $effectiveTypeNode = $typeNode->templateTypes !== [] - ? self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName) - : $typeNode; + $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); self::validateCallbackArguments($effectiveTypeNode, $args, $prefix, $registry, $callable); @@ -314,9 +302,7 @@ private static function createDispatcherClosure( } return function (&...$args) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { - $effectiveTypeNode = $typeNode->templateTypes !== [] - ? self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName) - : $typeNode; + $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); self::validateCallbackArguments($effectiveTypeNode, $args, $prefix, $registry, $callable); @@ -421,21 +407,18 @@ private static function resolveEffectiveCallableTypeNode( } if ($callable instanceof Closure) { - try { - $ref = new ReflectionFunction($callable); - if ($ref->hasReturnType()) { - $retType = $ref->getReturnType(); - if ($retType instanceof \ReflectionNamedType && $retType->getName() !== 'mixed') { - $retName = $retType->getName(); - if ($typeNode->returnType instanceof IdentifierTypeNode && isset($localTemplates[$typeNode->returnType->name])) { - $rName = $typeNode->returnType->name; - if (! isset($boundLocal[$rName])) { - $boundLocal[$rName] = new IdentifierTypeNode($retName); - } + $ref = new ReflectionFunction($callable); + if ($ref->hasReturnType()) { + $retType = $ref->getReturnType(); + if ($retType instanceof \ReflectionNamedType && $retType->getName() !== 'mixed') { + $retName = $retType->getName(); + if ($typeNode->returnType instanceof IdentifierTypeNode && isset($localTemplates[$typeNode->returnType->name])) { + $rName = $typeNode->returnType->name; + if (! isset($boundLocal[$rName])) { + $boundLocal[$rName] = new IdentifierTypeNode($retName); } } } - } catch (\Throwable) { } } @@ -491,12 +474,9 @@ private static function inferLocalTemplateFromParam( if ($function !== '') { $boundToValidate = SpecialTypeResolver::resolve($tTag->bound, $function); } elseif ($callable instanceof Closure) { - try { - $cFile = (new ReflectionFunction($callable))->getFileName(); - if ($cFile !== false && $cFile !== '') { - $boundToValidate = SpecialTypeResolver::resolveForFile($tTag->bound, $cFile); - } - } catch (\Throwable) { + $cFile = (new ReflectionFunction($callable))->getFileName(); + if ($cFile !== false && $cFile !== '') { + $boundToValidate = SpecialTypeResolver::resolveForFile($tTag->bound, $cFile); } } diff --git a/tests/Contract/ViewTemplateAndConstructorExclusionTest.php b/tests/Contract/ViewTemplateAndConstructorExclusionTest.php index d964c0c4..048f5076 100644 --- a/tests/Contract/ViewTemplateAndConstructorExclusionTest.php +++ b/tests/Contract/ViewTemplateAndConstructorExclusionTest.php @@ -118,6 +118,14 @@ }); describe('3. Constructor Synthesis Safety (ContractVisitor)', function () { + beforeEach(function () { + Config::set(['eliminate_statically_proven_checks' => false]); + }); + + afterEach(function () { + Config::reset(); + }); + test('does NOT inject __construct when class extends a parent class', function () { $code = <<<'PHP' count())->toBe(1); $violations = TypePHP::getViolations(); - expect($violations)->toHaveCount(1) + expect($violations)->toHaveCount(2) ->and($violations[0]->kind)->toBe('parameter') ->and($violations[0]->expected)->toContain(Dog::class) ->and($violations[0]->count)->toBe(1) diff --git a/tests/Fixtures/Properties/PropertyRefTargetFixture.php b/tests/Fixtures/Properties/PropertyRefTargetFixture.php new file mode 100644 index 00000000..0a0db181 --- /dev/null +++ b/tests/Fixtures/Properties/PropertyRefTargetFixture.php @@ -0,0 +1,54 @@ + + */ + public array $numbers = [1, 2, 3]; + + /** + * @var array{id: positive-int, name: non-empty-string} + */ + public array $user = [ + 'id' => 1, + 'name' => 'Alice', + ]; + + /** + * @var positive-int + */ + public static int $staticScore = 100; + + public static function reset(): void + { + self::$staticScore = 100; + } + + public function mutateInternalScoreByRef(mixed $val): void + { + $ref = &$this->score; + $ref = $val; + } + + public function mutateInternalNumberByRef(mixed $val): void + { + $ref = &$this->numbers[0]; + $ref = $val; + } + + public function mutateInternalUserByRef(mixed $val): void + { + $ref = &$this->user['name']; + $ref = $val; + } +} diff --git a/tests/Internal/Ast/ContractVisitorTest.php b/tests/Internal/Ast/ContractVisitorTest.php index 05ac7520..13ad5d61 100644 --- a/tests/Internal/Ast/ContractVisitorTest.php +++ b/tests/Internal/Ast/ContractVisitorTest.php @@ -14,6 +14,11 @@ beforeEach(function () { $this->parser = (new ParserFactory())->createForNewestSupportedVersion(); $this->printer = new TypePHPPrinter(); + Config::set(['eliminate_statically_proven_checks' => false]); + }); + + afterEach(function () { + Config::reset(); }); test('skips constructor default check for properties with a get hook', function () { diff --git a/tests/Internal/Ast/Elimination/ArithmeticAndTernaryEvaluatorTest.php b/tests/Internal/Ast/Elimination/ArithmeticAndTernaryEvaluatorTest.php new file mode 100644 index 00000000..3a34f586 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ArithmeticAndTernaryEvaluatorTest.php @@ -0,0 +1,160 @@ +toBe(45); + expect(StaticTypeEvaluator::satisfies($expr, new IdentifierTypeNode('positive-int')))->toBeTrue(); + + $range = new GenericTypeNode(new IdentifierTypeNode('int'), [ + new IdentifierTypeNode('1'), + new IdentifierTypeNode('50'), + ]); + expect(StaticTypeEvaluator::satisfies($expr, $range))->toBeTrue(); + }); + + test('evaluates nested multiplication (60 * 60 * 24 = 86400)', function () { + $nested = new Mul(new Mul(new LNumber(60), new LNumber(60)), new LNumber(24)); + + expect(ArithmeticEvaluator::evaluate($nested))->toBe(86400); + expect(StaticTypeEvaluator::satisfies($nested, new IdentifierTypeNode('positive-int')))->toBeTrue(); + }); + + test('evaluates subtraction producing negative integer', function () { + $expr = new Minus(new LNumber(10), new LNumber(25)); // -15 + + expect(ArithmeticEvaluator::evaluate($expr))->toBe(-15); + expect(StaticTypeEvaluator::satisfies($expr, new IdentifierTypeNode('negative-int')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($expr, new IdentifierTypeNode('positive-int')))->toBeFalse() + ; + }); + + test('evaluates division and integer modulo', function () { + $div = new Div(new LNumber(100), new LNumber(4)); // 25 + expect(ArithmeticEvaluator::evaluate($div))->toBe(25); + expect(StaticTypeEvaluator::satisfies($div, new IdentifierTypeNode('positive-int')))->toBeTrue(); + + $mod = new Mod(new LNumber(17), new LNumber(5)); // 2 + expect(ArithmeticEvaluator::evaluate($mod))->toBe(2); + expect(StaticTypeEvaluator::satisfies($mod, new IdentifierTypeNode('positive-int')))->toBeTrue(); + }); + + test('evaluates exponentiation (2 ** 8 = 256)', function () { + $pow = new Pow(new LNumber(2), new LNumber(8)); + + expect(ArithmeticEvaluator::evaluate($pow))->toBe(256); + expect(StaticTypeEvaluator::satisfies($pow, new IdentifierTypeNode('positive-int')))->toBeTrue(); + }); + + test('handles IEEE 754 float arithmetic with epsilon tolerance (0.1 + 0.2 vs 0.3)', function () { + $floatAdd = new Plus(new DNumber(0.1), new DNumber(0.2)); + + $floatType = new ConstTypeNode(new ConstExprFloatNode('0.3')); + expect(StaticTypeEvaluator::satisfies($floatAdd, $floatType))->toBeTrue(); + }); + + test('aborts constant folding and defers to runtime on division and modulo by zero', function () { + $divZero = new Div(new LNumber(100), new LNumber(0)); + expect(ArithmeticEvaluator::evaluate($divZero))->toBeNull(); + expect(StaticTypeEvaluator::satisfies($divZero, new IdentifierTypeNode('int')))->toBeFalse(); + + $modZero = new Mod(new LNumber(100), new LNumber(0)); + expect(ArithmeticEvaluator::evaluate($modZero))->toBeNull(); + expect(StaticTypeEvaluator::satisfies($modZero, new IdentifierTypeNode('int')))->toBeFalse(); + }); + }); + + describe('Ternary Branch Confluence ($cond ? A : B)', function () { + test('satisfies contract when both ternary branches are proven valid', function () { + $ternary = new Ternary( + new Variable('isAdmin'), + new String_('admin'), + new String_('user') + ); + + $union = new UnionTypeNode([ + new ConstTypeNode(new ConstExprStringNode('admin', ConstExprStringNode::SINGLE_QUOTED)), + new ConstTypeNode(new ConstExprStringNode('user', ConstExprStringNode::SINGLE_QUOTED)), + ]); + + expect(StaticTypeEvaluator::satisfies($ternary, $union))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($ternary, new IdentifierTypeNode('non-empty-string')))->toBeTrue() + ; + }); + + test('rejects ternary when one branch violates the contract', function () { + $ternary = new Ternary( + new Variable('isAdmin'), + new String_('admin'), + new String_('guest') // Not in union! + ); + + $union = new UnionTypeNode([ + new ConstTypeNode(new ConstExprStringNode('admin', ConstExprStringNode::SINGLE_QUOTED)), + new ConstTypeNode(new ConstExprStringNode('user', ConstExprStringNode::SINGLE_QUOTED)), + ]); + + expect(StaticTypeEvaluator::satisfies($ternary, $union))->toBeFalse(); + }); + + test('defers shorthand elvis operator ($a ?: $b) to runtime', function () { + $elvis = new Ternary( + new Variable('a'), + null, + new String_('fallback') + ); + + expect(StaticTypeEvaluator::satisfies($elvis, new IdentifierTypeNode('string')))->toBeFalse(); + }); + }); + + describe('String Interpolation (Encapsed)', function () { + test('guarantees non-empty-string when template contains a non-empty string part', function () { + $interpolated = new Encapsed([ + new EncapsedStringPart('user_'), + new Variable('id'), + ]); + + expect(StaticTypeEvaluator::satisfies($interpolated, new IdentifierTypeNode('non-empty-string')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($interpolated, new IdentifierTypeNode('string')))->toBeTrue() + ; + }); + + test('does not guarantee non-empty-string when all parts are variables or empty', function () { + $bareVarInterpolation = new Encapsed([ + new Variable('prefix'), + new Variable('suffix'), + ]); + + expect(StaticTypeEvaluator::satisfies($bareVarInterpolation, new IdentifierTypeNode('non-empty-string')))->toBeFalse(); + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorTest.php b/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorTest.php new file mode 100644 index 00000000..a10529d2 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorTest.php @@ -0,0 +1,292 @@ +', function () { + $empty = new Array_([]); + + expect(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('array')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('list')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('iterable')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($empty, new ArrayTypeNode(new IdentifierTypeNode('int'))))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($empty, new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('positive-int')])))->toBeTrue() + ; + }); + + test('rejects non-empty-list and non-empty-array on empty array', function () { + $empty = new Array_([]); + + expect(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('non-empty-list')))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('non-empty-array')))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($empty, new GenericTypeNode(new IdentifierTypeNode('non-empty-list'), [new IdentifierTypeNode('int')])))->toBeFalse() + ; + }); + + test('satisfies shape with all optional keys, but rejects shape with required keys', function () { + $empty = new Array_([]); + + $allOptionalShape = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), true, new IdentifierTypeNode('int')), + ]); + + $requiredShape = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('int')), + ]); + + expect(ArrayLiteralEvaluator::satisfiesEmptyArray($allOptionalShape))->toBeTrue() + ->and(ArrayLiteralEvaluator::satisfiesEmptyArray($requiredShape))->toBeFalse() + ; + }); + }); + + describe('Sequential Lists ([1, 2, 3])', function () { + test('evaluates valid sequential list of positive-int', function () { + $list = new Array_([ + new ArrayItem(new LNumber(10)), + new ArrayItem(new LNumber(20)), + new ArrayItem(new LNumber(30)), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('positive-int')]); + + expect(StaticTypeEvaluator::satisfies($list, $type))->toBeTrue(); + }); + + test('rejects list containing item violating element contract', function () { + $list = new Array_([ + new ArrayItem(new LNumber(10)), + new ArrayItem(new LNumber(-5)), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('positive-int')]); + + expect(StaticTypeEvaluator::satisfies($list, $type))->toBeFalse(); + }); + + test('rejects list with associative or non-sequential integer keys', function () { + $assoc = new Array_([ + new ArrayItem(new LNumber(10), new String_('key')), + ]); + + $nonSequential = new Array_([ + new ArrayItem(new LNumber(10), new LNumber(1)), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('int')]); + + expect(StaticTypeEvaluator::satisfies($assoc, $type))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($nonSequential, $type))->toBeFalse() + ; + }); + + test('rejects list with unpack or dynamic elements', function () { + $list = new Array_([ + new ArrayItem(new LNumber(10)), + new ArrayItem(new Variable('dynamicVar')), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('int')]); + + expect(StaticTypeEvaluator::satisfies($list, $type))->toBeFalse(); + }); + }); + + describe('Sealed and Unsealed Array Shapes', function () { + test('evaluates valid sealed array shape with literal values', function () { + $array = new Array_([ + new ArrayItem(new LNumber(1), new String_('id')), + new ArrayItem(new String_('Alice'), new String_('name')), + ]); + + $shape = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('positive-int')), + new ArrayShapeItemNode(new ConstExprStringNode('name', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('non-empty-string')), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $shape))->toBeTrue(); + }); + + test('rejects sealed array shape when required key is missing', function () { + $array = new Array_([ + new ArrayItem(new LNumber(1), new String_('id')), + ]); + + $shape = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('positive-int')), + new ArrayShapeItemNode(new ConstExprStringNode('name', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('non-empty-string')), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $shape))->toBeFalse(); + }); + + test('rejects sealed array shape when extra key is present', function () { + $array = new Array_([ + new ArrayItem(new LNumber(1), new String_('id')), + new ArrayItem(new String_('forbidden'), new String_('extra')), + ]); + + $shape = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('positive-int')), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $shape))->toBeFalse(); + }); + + test('evaluates unsealed array shape with valid extra string values', function () { + $array = new Array_([ + new ArrayItem(new LNumber(1), new String_('id')), + new ArrayItem(new String_('extra_info'), new String_('tag')), + ]); + + $unsealed = new ArrayShapeUnsealedTypeNode(new IdentifierTypeNode('string'), new IdentifierTypeNode('string')); + + $shape = ArrayShapeNode::createUnsealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('positive-int')), + ], $unsealed); + + expect(StaticTypeEvaluator::satisfies($array, $shape))->toBeTrue(); + }); + }); + + describe('Arrays and Lists Containing Object Instantiations', function () { + test('evaluates valid sequential list of object instantiations (list)', function () { + $array = new Array_([ + new ArrayItem(new New_(new Name('User'))), + new ArrayItem(new New_(new Name('User'))), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('User')]); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeTrue(); + }); + + test('evaluates valid T[] array of object instantiations (User[])', function () { + $array = new Array_([ + new ArrayItem(new New_(new Name('User'))), + ]); + + $type = new ArrayTypeNode(new IdentifierTypeNode('User')); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeTrue(); + }); + + test('rejects list of objects when an item is the wrong class', function () { + $array = new Array_([ + new ArrayItem(new New_(new Name('User'))), + new ArrayItem(new New_(new Name('Product'))), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('User')]); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeFalse(); + }); + + test('evaluates array shape containing object instantiations', function () { + $array = new Array_([ + new ArrayItem(new New_(new Name('User')), new String_('author')), + new ArrayItem(new LNumber(1), new String_('id')), + ]); + + $shape = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('author', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('User')), + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('positive-int')), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $shape))->toBeTrue(); + }); + }); + + describe('Homogeneous and Heterogeneous Unions in Arrays (list)', function () { + test('evaluates heterogeneous scalar list (mix of ints and strings)', function () { + $array = new Array_([ + new ArrayItem(new LNumber(1)), + new ArrayItem(new String_('two')), + new ArrayItem(new LNumber(3)), + new ArrayItem(new String_('four')), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [ + new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('string')]), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeTrue(); + }); + + test('evaluates homogeneous scalar list against a union contract', function () { + $array = new Array_([ + new ArrayItem(new LNumber(10)), + new ArrayItem(new LNumber(20)), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [ + new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('string')]), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeTrue(); + }); + + test('rejects heterogeneous list when an element violates all union members', function () { + $array = new Array_([ + new ArrayItem(new LNumber(1)), + new ArrayItem(new String_('two')), + new ArrayItem(new ConstFetch(new Name('false'))), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [ + new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('string')]), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeFalse(); + }); + + test('evaluates heterogeneous list of constructed objects (list)', function () { + $array = new Array_([ + new ArrayItem(new New_(new Name('User'))), + new ArrayItem(new New_(new Name('Product'))), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('list'), [ + new UnionTypeNode([new IdentifierTypeNode('User'), new IdentifierTypeNode('Product')]), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeTrue(); + }); + + test('evaluates key-value array with union values (array)', function () { + $array = new Array_([ + new ArrayItem(new LNumber(100), new String_('port')), + new ArrayItem(new ConstFetch(new Name('true')), new String_('enabled')), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('string'), + new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('bool')]), + ]); + + expect(StaticTypeEvaluator::satisfies($array, $type))->toBeTrue(); + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/AstCheckEliminationIntegrationTest.php b/tests/Internal/Ast/Elimination/AstCheckEliminationIntegrationTest.php new file mode 100644 index 00000000..42e3cd4e --- /dev/null +++ b/tests/Internal/Ast/Elimination/AstCheckEliminationIntegrationTest.php @@ -0,0 +1,421 @@ +not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain("return 'active_label';") + ; + }); + + test('retains checkReturn on standalone function returning an unproven/violating integer', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('eliminates checkReturn on private method returning sequential list literal', function () { + $source = <<<'PHP' + */ + private function getIds(): array + { + return [1, 2, 3]; + } +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_list_return.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return [1, 2, 3];') + ; + }); + + test('retains checkReturn on method returning list when element violates contract', function () { + $source = <<<'PHP' + */ + private function getBadIds(): array + { + return [1, -2, 3]; + } +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_bad_list.php'); + + expect($transformed)->toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('eliminates checkReturn when returning empty array for list', function () { + $source = <<<'PHP' + */ +function getEmpty(): array +{ + return []; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_empty_list.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return [];') + ; + }); + + test('retains checkReturn when returning empty array for non-empty-list', function () { + $source = <<<'PHP' + */ +function getEmptyFails(): array +{ + return []; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_empty_non_empty.php'); + + expect($transformed)->toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('eliminates property default assertion in constructor when default is statically proven', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkProperty') + ->and($transformed)->not()->toContain('__construct') + ; + }); + + test('retains property default assertion when default violates contract', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkProperty') + ->and($transformed)->toContain('__construct') + ; + }); + + test('eliminates checkVariable on inline @var assignment when expression is statically proven', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkVariable') + ->and($transformed)->toContain('$x = 42;') + ; + }); + + test('retains checkVariable on inline @var assignment when expression violates contract', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkVariable'); + }); + + test('eliminates checkReturn on return $this in standalone class', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return $this;') + ; + }); +}); + +describe('Immediate Predecessor Local Data-Flow Elimination ($x = ; return $x;)', function () { + test('eliminates checkReturn when returned variable was immediately assigned a proven string literal', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return $name;') + ; + }); + + test('eliminates checkReturn when returned variable was immediately assigned a proven list literal', function () { + $source = <<<'PHP' + */ + private function getIds(): array + { + $ids = [1, 2, 3]; + return $ids; + } +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_flow_list.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return $ids;') + ; + }); + + test('eliminates checkReturn inside an if-block when variable is immediately assigned and returned', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return $msg;') + ->and($transformed)->toContain("return 'fallback';") + ; + }); + + test('retains checkReturn when immediately assigned variable violates the return contract', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('retains checkReturn when intervening statements exist between assignment and return', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); +}); + +describe('Generator & Iterable Compile-Time Check Elimination', function () { + test('completely eliminates checkYield, checkSend, and checkGeneratorReturn on proven 2-arg Generator', function () { + $source = <<<'PHP' + */ +function streamProvenConstants(): Generator +{ + yield 'first' => 10; + yield 'second' => 20; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_gen_proven.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkYield') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkSend') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn') + ; + }); + + test('eliminates checkYield on string concatenation and interpolation for non-empty-string', function () { + $source = <<<'PHP' + */ +function streamUserLabels(int $id, string $suffix): Generator +{ + yield 'user_' . $id => "label_{$suffix}"; + $computed = 'prefix_' . $suffix; + yield 'final' => $computed; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_gen_concat.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkYield') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkSend') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn') + ; + }); + + test('eliminates checkSend and checkGeneratorReturn while retaining checkYield when yielded value is dynamic', function () { + $source = <<<'PHP' + */ +function streamDynamicValue(int $dynamicVal): Generator +{ + yield 'item' => $dynamicVal; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_gen_partial.php'); + + expect($transformed)->toContain('RuntimeTypeChecker::checkYield') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkSend') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn') + ; + }); + + test('eliminates checkYield while retaining checkSend when TSend is constrained and yielded literal is proven', function () { + $source = <<<'PHP' + */ +function streamInteractiveProven(): Generator +{ + $input = yield 'prompt' => 1; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_gen_send_only.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkYield') + ->and($transformed)->toContain('RuntimeTypeChecker::checkSend') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn') + ; + }); + + test('eliminates wrapIterable on yield from proven array literal and retains on unproven array', function () { + $provenSource = <<<'PHP' + */ +function streamYieldFromProven(int $id): Generator +{ + yield from ['user_' . $id => 'role_' . $id]; +} +PHP; + + $transformedProven = StreamWrapper::transformSource($provenSource, 'test_yield_from_proven.php'); + expect($transformedProven)->not()->toContain('RuntimeTypeChecker::wrapIterable'); + + $unprovenSource = <<<'PHP' + */ +function streamYieldFromInvalid(): Generator +{ + yield from ['a' => 10, 'b' => -5]; +} +PHP; + + $transformedUnproven = StreamWrapper::transformSource($unprovenSource, 'test_yield_from_unproven.php'); + expect($transformedUnproven)->toContain('RuntimeTypeChecker::wrapIterable'); + }); + + test('eliminates checkGeneratorReturn on proven TReturn and retains when TReturn is violated', function () { + $provenReturn = <<<'PHP' + */ +function genProvenReturn(string $tag): Generator +{ + yield 0 => 'step'; + return 'done_' . $tag; +} +PHP; + + $transformedProven = StreamWrapper::transformSource($provenReturn, 'test_gen_ret_proven.php'); + expect($transformedProven)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn'); + + $invalidReturn = <<<'PHP' + */ +function genInvalidReturn(): Generator +{ + yield 0 => 'step'; + return -5; +} +PHP; + + $transformedInvalid = StreamWrapper::transformSource($invalidReturn, 'test_gen_ret_invalid.php'); + expect($transformedInvalid)->toContain('RuntimeTypeChecker::checkGeneratorReturn'); + }); +}); diff --git a/tests/Internal/Ast/Elimination/ConstantAndEnumEvaluatorTest.php b/tests/Internal/Ast/Elimination/ConstantAndEnumEvaluatorTest.php new file mode 100644 index 00000000..9891c308 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ConstantAndEnumEvaluatorTest.php @@ -0,0 +1,91 @@ +toBeTrue(); + }); + + test('evaluates wildcard constant prefix (self::STATUS_*)', function () { + $fetch = new ClassConstFetch(new Name('self'), new Identifier('STATUS_PAID')); + $wildcard = new ConstTypeNode(new ConstFetchNode('self', 'STATUS_*')); + + expect(StaticTypeEvaluator::satisfies($fetch, $wildcard))->toBeTrue(); + + $unmatched = new ClassConstFetch(new Name('self'), new Identifier('ROLE_ADMIN')); + expect(StaticTypeEvaluator::satisfies($unmatched, $wildcard))->toBeFalse(); + }); + + test('evaluates int-mask-of wildcard constants and bitwise OR combinations', function () { + $flagA = new ClassConstFetch(new Name('self'), new Identifier('FLAG_READ')); + $flagB = new ClassConstFetch(new Name('self'), new Identifier('FLAG_WRITE')); + $orExpr = new BitwiseOr($flagA, $flagB); + + $maskOf = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode('self', 'FLAG_*')), + ]); + + expect(StaticTypeEvaluator::satisfies($flagA, $maskOf))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($orExpr, $maskOf))->toBeTrue() + ; + + $badFlag = new ClassConstFetch(new Name('self'), new Identifier('OTHER_FLAG')); + $badOrExpr = new BitwiseOr($flagA, $badFlag); + expect(StaticTypeEvaluator::satisfies($badOrExpr, $maskOf))->toBeFalse(); + }); + }); + + describe('Enums and Backing Values', function () { + test('evaluates enum case fetch against enum base type', function () { + $fetch = new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')); + $type = new IdentifierTypeNode('StatusEnum'); + + expect(StaticTypeEvaluator::satisfies($fetch, $type))->toBeTrue(); + }); + + test('evaluates enum case fetch against enum wildcard (StatusEnum::*)', function () { + $fetch = new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')); + $wildcard = new ConstTypeNode(new ConstFetchNode('StatusEnum', '*')); + + expect(StaticTypeEvaluator::satisfies($fetch, $wildcard))->toBeTrue(); + }); + + test('evaluates enum case fetch against prefix wildcard (StatusEnum::ACT*)', function () { + $fetch = new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')); + $prefix = new ConstTypeNode(new ConstFetchNode('StatusEnum', 'ACT*')); + + expect(StaticTypeEvaluator::satisfies($fetch, $prefix))->toBeTrue(); + }); + + test('evaluates enum backing property access against value-of', function () { + $propFetch = new PropertyFetch( + new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')), + new Identifier('value') + ); + + $valueOf = new GenericTypeNode(new IdentifierTypeNode('value-of'), [ + new IdentifierTypeNode('StatusEnum'), + ]); + + expect(StaticTypeEvaluator::satisfies($propFetch, $valueOf))->toBeTrue(); + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/EliminationSafetyPolicyTest.php b/tests/Internal/Ast/Elimination/EliminationSafetyPolicyTest.php new file mode 100644 index 00000000..d5f62526 --- /dev/null +++ b/tests/Internal/Ast/Elimination/EliminationSafetyPolicyTest.php @@ -0,0 +1,76 @@ +toBeFalse(); + }); + + test('returns false when return type is a GenericTypeNode (WeakMap side effect)', function () { + $fn = new Function_('test'); + $generic = new GenericTypeNode(new IdentifierTypeNode('Collection'), [new IdentifierTypeNode('Dog')]); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, $generic))->toBeFalse(); + }); + + test('returns true for standalone functions (zero inheritance risk)', function () { + $fn = new Function_('test'); + $type = new IdentifierTypeNode('positive-int'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, $type))->toBeTrue(); + }); + + test('returns true for closures and arrow functions (zero inheritance risk)', function () { + $closure = new Closure(); + $arrow = new ArrowFunction(['expr' => new String_('ok')]); + $type = new IdentifierTypeNode('string'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($closure, null, $type))->toBeTrue() + ->and(EliminationSafetyPolicy::isReturnEliminationSafe($arrow, null, $type))->toBeTrue() + ; + }); + + test('returns true for private class methods regardless of inheritance', function () { + $method = new ClassMethod('secret', [ + 'flags' => Class_::MODIFIER_PRIVATE, + ]); + $context = ['hasRealInheritance' => true]; + $type = new IdentifierTypeNode('int'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($method, $context, $type))->toBeTrue(); + }); + + test('returns true for public methods in classes without inheritance (hasRealInheritance === false)', function () { + $method = new ClassMethod('render', [ + 'flags' => Class_::MODIFIER_PUBLIC, + ]); + $context = ['hasRealInheritance' => false]; + $type = new IdentifierTypeNode('string'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($method, $context, $type))->toBeTrue(); + }); + + test('returns false for public methods in classes with inheritance (preserves LSP)', function () { + $method = new ClassMethod('render', [ + 'flags' => Class_::MODIFIER_PUBLIC, + ]); + $context = ['hasRealInheritance' => true]; + $type = new IdentifierTypeNode('string'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($method, $context, $type))->toBeFalse(); + }); +}); diff --git a/tests/Internal/Ast/Elimination/GeneratorEvaluatorTest.php b/tests/Internal/Ast/Elimination/GeneratorEvaluatorTest.php new file mode 100644 index 00000000..b31bf95c --- /dev/null +++ b/tests/Internal/Ast/Elimination/GeneratorEvaluatorTest.php @@ -0,0 +1,243 @@ +not()->toBeNull() + ->and($contract1['key'])->toBeNull() + ->and((string) $contract1['value'])->toBe('positive-int') + ->and($contract1['send'])->toBeNull() + ->and($contract1['return'])->toBeNull() + ; + + $twoArgs = new GenericTypeNode(new IdentifierTypeNode('iterable'), [ + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('positive-int'), + ]); + $contract2 = GeneratorEvaluator::extractContract($twoArgs); + expect($contract2)->not()->toBeNull() + ->and((string) $contract2['key'])->toBe('non-empty-string') + ->and((string) $contract2['value'])->toBe('positive-int') + ->and($contract2['send'])->toBeNull() + ->and($contract2['return'])->toBeNull() + ; + + $fourArgs = new GenericTypeNode(new IdentifierTypeNode('\\Generator'), [ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('int'), + new IdentifierTypeNode('positive-int'), + new IdentifierTypeNode('bool'), + ]); + $contract4 = GeneratorEvaluator::extractContract($fourArgs); + expect($contract4)->not()->toBeNull() + ->and((string) $contract4['key'])->toBe('string') + ->and((string) $contract4['value'])->toBe('int') + ->and((string) $contract4['send'])->toBe('positive-int') + ->and((string) $contract4['return'])->toBe('bool') + ; + }); + + test('extracts contract from ArrayTypeNode (T[]) and bare Generator/iterable identifiers', function () { + $arrayType = new ArrayTypeNode(new IdentifierTypeNode('non-empty-string')); + $contractArr = GeneratorEvaluator::extractContract($arrayType); + expect($contractArr)->not()->toBeNull() + ->and($contractArr['key'])->toBeNull() + ->and((string) $contractArr['value'])->toBe('non-empty-string') + ; + + $bareGen = new IdentifierTypeNode('Generator'); + $contractBare = GeneratorEvaluator::extractContract($bareGen); + expect($contractBare)->not()->toBeNull() + ->and($contractBare['key'])->toBeNull() + ->and($contractBare['value'])->toBeNull() + ; + }); + + test('returns null for unknown type aliases or non-generator generic classes', function () { + expect(GeneratorEvaluator::extractContract(new IdentifierTypeNode('CustomStreamAlias')))->toBeNull(); + expect(GeneratorEvaluator::extractContract(new GenericTypeNode(new IdentifierTypeNode('Collection'), [new IdentifierTypeNode('int')])))->toBeNull(); + }); + }); + + describe('canEliminateYield()', function () { + test('eliminates yield when literal key and value satisfy contract', function () { + $yield = new Yield_(new LNumber(42), new String_('key_a')); + + expect(GeneratorEvaluator::canEliminateYield( + $yield, + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('positive-int') + ))->toBeTrue(); + }); + + test('eliminates yield when string concatenation and interpolation satisfy non-empty-string and array-key', function () { + $concatKey = new Concat(new String_('user_'), new Variable('id')); + $encapsedVal = new Encapsed([ + new EncapsedStringPart('item_'), + new Variable('name'), + ]); + $yield = new Yield_($encapsedVal, $concatKey); + + expect(GeneratorEvaluator::canEliminateYield( + $yield, + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('non-empty-string') + ))->toBeTrue(); + + expect(GeneratorEvaluator::canEliminateYield( + $yield, + new IdentifierTypeNode('array-key'), + new IdentifierTypeNode('non-empty-string') + ))->toBeTrue(); + }); + + test('handles omitted key (implicit 0..n int key) accurately against int vs positive-int', function () { + $yieldNoKey = new Yield_(new String_('hello')); + + expect(GeneratorEvaluator::canEliminateYield( + $yieldNoKey, + new IdentifierTypeNode('int'), + new IdentifierTypeNode('non-empty-string') + ))->toBeTrue(); + + expect(GeneratorEvaluator::canEliminateYield( + $yieldNoKey, + new IdentifierTypeNode('non-negative-int'), + new IdentifierTypeNode('non-empty-string') + ))->toBeTrue(); + + // Implicit key starts at 0, which violates positive-int and string + expect(GeneratorEvaluator::canEliminateYield( + $yieldNoKey, + new IdentifierTypeNode('positive-int'), + new IdentifierTypeNode('non-empty-string') + ))->toBeFalse(); + + expect(GeneratorEvaluator::canEliminateYield( + $yieldNoKey, + new IdentifierTypeNode('string'), + new IdentifierTypeNode('non-empty-string') + ))->toBeFalse(); + }); + + test('retains checkYield when value or key is unproven or violates contract', function () { + $badVal = new Yield_(new LNumber(-5), new String_('a')); + expect(GeneratorEvaluator::canEliminateYield( + $badVal, + new IdentifierTypeNode('string'), + new IdentifierTypeNode('positive-int') + ))->toBeFalse(); + + $dynamicVal = new Yield_(new Variable('unproven'), new String_('a')); + expect(GeneratorEvaluator::canEliminateYield( + $dynamicVal, + new IdentifierTypeNode('string'), + new IdentifierTypeNode('positive-int') + ))->toBeFalse(); + }); + }); + + describe('canEliminateSend()', function () { + test('eliminates checkSend when TSend is null or mixed, and retains when constrained', function () { + expect(GeneratorEvaluator::canEliminateSend(null))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateSend(new IdentifierTypeNode('mixed')))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateSend(new IdentifierTypeNode('positive-int')))->toBeFalse() + ; + }); + }); + + describe('canEliminateYieldFrom()', function () { + test('eliminates wrapIterable on yield from array literal with valid elements and concat strings', function () { + $yieldFrom = new YieldFrom(new Array_([ + new ArrayItem(new Concat(new String_('val_'), new Variable('x')), new Concat(new String_('key_'), new Variable('k'))), + ])); + + expect(GeneratorEvaluator::canEliminateYieldFrom( + $yieldFrom, + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('non-empty-string') + ))->toBeTrue(); + }); + + test('retains wrapIterable when yield from expression is dynamic or contains invalid item', function () { + $dynamicYieldFrom = new YieldFrom(new Variable('items')); + expect(GeneratorEvaluator::canEliminateYieldFrom( + $dynamicYieldFrom, + null, + new IdentifierTypeNode('positive-int') + ))->toBeFalse(); + + $badArrayYieldFrom = new YieldFrom(new Array_([ + new ArrayItem(new LNumber(10)), + new ArrayItem(new LNumber(-5)), + ])); + expect(GeneratorEvaluator::canEliminateYieldFrom( + $badArrayYieldFrom, + null, + new IdentifierTypeNode('positive-int') + ))->toBeFalse(); + }); + }); + + describe('canEliminateGeneratorReturn()', function () { + test('eliminates generator return when TReturn is null, mixed, or satisfied by expression', function () { + expect(GeneratorEvaluator::canEliminateGeneratorReturn(null, null))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateGeneratorReturn(null, new IdentifierTypeNode('mixed')))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateGeneratorReturn(null, new IdentifierTypeNode('void')))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateGeneratorReturn(new ConstFetch(new Name('true')), new IdentifierTypeNode('bool')))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateGeneratorReturn(new Concat(new String_('ok_'), new Variable('id')), new IdentifierTypeNode('non-empty-string')))->toBeTrue() + ; + + expect(GeneratorEvaluator::canEliminateGeneratorReturn(null, new IdentifierTypeNode('bool')))->toBeFalse() + ->and(GeneratorEvaluator::canEliminateGeneratorReturn(new String_('not_void'), new IdentifierTypeNode('void')))->toBeFalse() + ; + }); + }); + + describe('EliminationSafetyPolicy::isGeneratorEliminationSafe()', function () { + test('authorizes standalone functions, private methods, and non-inherited classes, and rejects inherited public methods', function () { + $genType = new GenericTypeNode(new IdentifierTypeNode('Generator'), [new IdentifierTypeNode('int')]); + + $fn = new Function_('myGen'); + expect(EliminationSafetyPolicy::isGeneratorEliminationSafe($fn, null, $genType))->toBeTrue(); + + $privateMethod = new ClassMethod('privGen', ['flags' => Class_::MODIFIER_PRIVATE]); + expect(EliminationSafetyPolicy::isGeneratorEliminationSafe($privateMethod, ['hasRealInheritance' => true], $genType))->toBeTrue(); + + $standaloneMethod = new ClassMethod('pubGen', ['flags' => Class_::MODIFIER_PUBLIC]); + expect(EliminationSafetyPolicy::isGeneratorEliminationSafe($standaloneMethod, ['hasRealInheritance' => false], $genType))->toBeTrue(); + + $inheritedMethod = new ClassMethod('pubGen', ['flags' => Class_::MODIFIER_PUBLIC]); + expect(EliminationSafetyPolicy::isGeneratorEliminationSafe($inheritedMethod, ['hasRealInheritance' => true], $genType))->toBeFalse(); + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/ObjectEvaluatorTest.php b/tests/Internal/Ast/Elimination/ObjectEvaluatorTest.php new file mode 100644 index 00000000..df0aef59 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ObjectEvaluatorTest.php @@ -0,0 +1,56 @@ +toBeFalse(); + }); + + test('evaluates return $this against @return $this and @return self', function () { + $thisExpr = new Variable('this'); + + expect(StaticTypeEvaluator::satisfies($thisExpr, new ThisTypeNode()))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($thisExpr, new IdentifierTypeNode('$this')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($thisExpr, new IdentifierTypeNode('self')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($thisExpr, new IdentifierTypeNode('string')))->toBeFalse() + ; + }); + + test('evaluates return new static() against @return static', function () { + $newStatic = new New_(new Name('static')); + + expect(StaticTypeEvaluator::satisfies($newStatic, new IdentifierTypeNode('static')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($newStatic, new IdentifierTypeNode('self')))->toBeFalse() + ; + }); + + test('evaluates return new self() against @return self', function () { + $newSelf = new New_(new Name('self')); + + expect(StaticTypeEvaluator::satisfies($newSelf, new IdentifierTypeNode('self')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($newSelf, new IdentifierTypeNode('static')))->toBeFalse() + ; + }); + + test('evaluates return new ClassName() against non-generic @return ClassName', function () { + $newUser = new New_(new Name('User')); + + expect(StaticTypeEvaluator::satisfies($newUser, new IdentifierTypeNode('User')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($newUser, new IdentifierTypeNode('Product')))->toBeFalse() + ; + }); +}); diff --git a/tests/Internal/Ast/Elimination/ScalarEvaluatorTest.php b/tests/Internal/Ast/Elimination/ScalarEvaluatorTest.php new file mode 100644 index 00000000..56ac5b93 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ScalarEvaluatorTest.php @@ -0,0 +1,167 @@ +toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(0), new IdentifierTypeNode('positive-int')))->toBeFalse() + ->and(ScalarEvaluator::satisfies(new UnaryMinus(new LNumber(5)), new IdentifierTypeNode('positive-int')))->toBeFalse() + ; + }); + + test('evaluates negative-int with UnaryMinus', function () { + expect(ScalarEvaluator::satisfies(new UnaryMinus(new LNumber(10)), new IdentifierTypeNode('negative-int')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(10), new IdentifierTypeNode('negative-int')))->toBeFalse() + ->and(ScalarEvaluator::satisfies(new LNumber(0), new IdentifierTypeNode('negative-int')))->toBeFalse() + ; + }); + + test('evaluates non-negative-int and non-positive-int', function () { + expect(ScalarEvaluator::satisfies(new LNumber(0), new IdentifierTypeNode('non-negative-int')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(10), new IdentifierTypeNode('non-negative-int')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new UnaryMinus(new LNumber(1)), new IdentifierTypeNode('non-negative-int')))->toBeFalse() + ; + + expect(ScalarEvaluator::satisfies(new LNumber(0), new IdentifierTypeNode('non-positive-int')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new UnaryMinus(new LNumber(10)), new IdentifierTypeNode('non-positive-int')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(1), new IdentifierTypeNode('non-positive-int')))->toBeFalse() + ; + }); + + test('evaluates int bounds', function () { + $range = new GenericTypeNode(new IdentifierTypeNode('int'), [ + new ConstTypeNode(new ConstExprIntegerNode('1')), + new ConstTypeNode(new ConstExprIntegerNode('100')), + ]); + + expect(ScalarEvaluator::satisfies(new LNumber(50), $range))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(1), $range))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(100), $range))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(0), $range))->toBeFalse() + ->and(ScalarEvaluator::satisfies(new LNumber(150), $range))->toBeFalse() + ; + }); + + test('evaluates int-mask literal values', function () { + $mask = new GenericTypeNode(new IdentifierTypeNode('int-mask'), [ + new ConstTypeNode(new ConstExprIntegerNode('1')), + new ConstTypeNode(new ConstExprIntegerNode('2')), + new ConstTypeNode(new ConstExprIntegerNode('4')), + ]); + + expect(ScalarEvaluator::satisfies(new LNumber(0), $mask))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(3), $mask))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(7), $mask))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(8), $mask))->toBeFalse() + ; + }); + }); + + describe('Float Literals & Integer Coercion', function () { + test('evaluates float and positive-float', function () { + expect(ScalarEvaluator::satisfies(new DNumber(3.14), new IdentifierTypeNode('float')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new DNumber(3.14), new IdentifierTypeNode('positive-float')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new UnaryMinus(new DNumber(2.5)), new IdentifierTypeNode('positive-float')))->toBeFalse() + ->and(ScalarEvaluator::satisfies(new UnaryMinus(new DNumber(2.5)), new IdentifierTypeNode('negative-float')))->toBeTrue() + ; + }); + + test('evaluates direct float literal comparison with epsilon tolerance', function () { + $constType = new ConstTypeNode(new ConstExprFloatNode('12.34')); + + expect(ScalarEvaluator::satisfies(new DNumber(12.34), $constType))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new DNumber(12.35), $constType))->toBeFalse() + ; + }); + + test('evaluates integer coercion for float and float literal contracts', function () { + $floatLiteralType = new ConstTypeNode(new ConstExprFloatNode('10.0')); + + expect(ScalarEvaluator::satisfies(new LNumber(10), $floatLiteralType))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(11), $floatLiteralType))->toBeFalse() + ; + + expect(ScalarEvaluator::satisfies(new LNumber(10), new IdentifierTypeNode('float')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new LNumber(10), new IdentifierTypeNode('positive-float')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new UnaryMinus(new LNumber(5)), new IdentifierTypeNode('negative-float')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new UnaryMinus(new LNumber(5)), new IdentifierTypeNode('positive-float')))->toBeFalse() + ; + }); + }); + + describe('String Literals & Concatenations', function () { + test('evaluates string and non-empty-string', function () { + expect(ScalarEvaluator::satisfies(new String_('hello'), new IdentifierTypeNode('string')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new String_('hello'), new IdentifierTypeNode('non-empty-string')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new String_(''), new IdentifierTypeNode('non-empty-string')))->toBeFalse() + ->and(ScalarEvaluator::satisfies(new String_(''), new IdentifierTypeNode('string')))->toBeTrue() + ; + }); + + test('evaluates lowercase-string and uppercase-string', function () { + expect(ScalarEvaluator::satisfies(new String_('abc'), new IdentifierTypeNode('lowercase-string')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new String_('Abc'), new IdentifierTypeNode('lowercase-string')))->toBeFalse() + ->and(ScalarEvaluator::satisfies(new String_('ABC'), new IdentifierTypeNode('uppercase-string')))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new String_('aBC'), new IdentifierTypeNode('uppercase-string')))->toBeFalse() + ; + }); + + test('evaluates string concatenation with non-empty prefix guarantees non-empty-string', function () { + $concat = new Concat(new String_('user_'), new LNumber(42)); + + expect(ScalarEvaluator::satisfies($concat, new IdentifierTypeNode('non-empty-string')))->toBeTrue() + ->and(ScalarEvaluator::satisfies($concat, new IdentifierTypeNode('string')))->toBeTrue() + ; + }); + + test('evaluates string literal match against ConstTypeNode', function () { + $constType = new ConstTypeNode(new ConstExprStringNode('active', ConstExprStringNode::SINGLE_QUOTED)); + + expect(ScalarEvaluator::satisfies(new String_('active'), $constType))->toBeTrue() + ->and(ScalarEvaluator::satisfies(new String_('pending'), $constType))->toBeFalse() + ; + }); + }); + + describe('Constants (true, false, null)', function () { + test('evaluates true and false', function () { + $trueNode = new ConstFetch(new Name('true')); + $falseNode = new ConstFetch(new Name('false')); + + expect(ScalarEvaluator::satisfies($trueNode, new IdentifierTypeNode('bool')))->toBeTrue() + ->and(ScalarEvaluator::satisfies($trueNode, new IdentifierTypeNode('true')))->toBeTrue() + ->and(ScalarEvaluator::satisfies($trueNode, new IdentifierTypeNode('false')))->toBeFalse() + ->and(ScalarEvaluator::satisfies($falseNode, new IdentifierTypeNode('bool')))->toBeTrue() + ->and(ScalarEvaluator::satisfies($falseNode, new IdentifierTypeNode('false')))->toBeTrue() + ; + }); + + test('evaluates null and void', function () { + $nullNode = new ConstFetch(new Name('null')); + + expect(ScalarEvaluator::satisfies($nullNode, new IdentifierTypeNode('null')))->toBeTrue() + ->and(ScalarEvaluator::satisfies($nullNode, new IdentifierTypeNode('void')))->toBeTrue() + ->and(ScalarEvaluator::satisfies($nullNode, new IdentifierTypeNode('int')))->toBeFalse() + ; + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/StaticTypeEvaluatorTest.php b/tests/Internal/Ast/Elimination/StaticTypeEvaluatorTest.php new file mode 100644 index 00000000..d148e32f --- /dev/null +++ b/tests/Internal/Ast/Elimination/StaticTypeEvaluatorTest.php @@ -0,0 +1,310 @@ +toBeFalse() + ->and(StaticTypeEvaluator::satisfies(new New_(new Name('ArrayObject')), $intersection))->toBeFalse() + ; + }); + + test('never eliminates GenericTypeNode for classes to preserve runtime WeakMap registrations', function () { + $genericObject = new GenericTypeNode(new IdentifierTypeNode('Collection'), [new IdentifierTypeNode('Dog')]); + $newCollection = new New_(new Name('Collection')); + + expect(StaticTypeEvaluator::satisfies($newCollection, $genericObject))->toBeFalse(); + }); + + test('permits scalar and array generic containers to be evaluated at AST transform time', function () { + $intRange = new GenericTypeNode(new IdentifierTypeNode('int'), [ + new ConstTypeNode(new ConstExprIntegerNode('1')), + new ConstTypeNode(new ConstExprIntegerNode('10')), + ]); + expect(StaticTypeEvaluator::satisfies(new LNumber(5), $intRange))->toBeTrue(); + + $listType = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('int')]); + expect(StaticTypeEvaluator::satisfies(new Array_([]), $listType))->toBeTrue(); + }); + }); + + describe('Nullable Types (?T)', function () { + test('evaluates literal null against NullableTypeNode', function () { + $nullable = new NullableTypeNode(new IdentifierTypeNode('positive-int')); + $nullExpr = new ConstFetch(new Name('null')); + + expect(StaticTypeEvaluator::satisfies($nullExpr, $nullable))->toBeTrue(); + }); + + test('evaluates inner satisfied and violated values against NullableTypeNode', function () { + $nullable = new NullableTypeNode(new IdentifierTypeNode('positive-int')); + + expect(StaticTypeEvaluator::satisfies(new LNumber(42), $nullable))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new LNumber(0), $nullable))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies(new UnaryMinus(new LNumber(5)), $nullable))->toBeFalse() + ; + }); + }); + + describe('Union Types (A | B)', function () { + test('satisfies union if any member branch is statically proven', function () { + $statusUnion = new UnionTypeNode([ + new ConstTypeNode(new ConstExprStringNode('active', ConstExprStringNode::SINGLE_QUOTED)), + new ConstTypeNode(new ConstExprStringNode('pending', ConstExprStringNode::SINGLE_QUOTED)), + new IdentifierTypeNode('null'), + ]); + + expect(StaticTypeEvaluator::satisfies(new String_('active'), $statusUnion))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new String_('pending'), $statusUnion))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new ConstFetch(new Name('null')), $statusUnion))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new String_('archived'), $statusUnion))->toBeFalse() + ; + }); + + test('evaluates union of scalar refinements and literals', function () { + $mixedUnion = new UnionTypeNode([ + new IdentifierTypeNode('positive-int'), + new IdentifierTypeNode('non-empty-string'), + ]); + + expect(StaticTypeEvaluator::satisfies(new LNumber(100), $mixedUnion))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new String_('user_1'), $mixedUnion))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new LNumber(-5), $mixedUnion))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies(new String_(''), $mixedUnion))->toBeFalse() + ; + }); + }); + + describe('Scalars & Expressions Integration', function () { + test('evaluates integer literals, negative numbers, and ranges', function () { + expect(StaticTypeEvaluator::satisfies(new LNumber(10), new IdentifierTypeNode('positive-int')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new UnaryMinus(new LNumber(10)), new IdentifierTypeNode('negative-int')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new LNumber(0), new IdentifierTypeNode('non-negative-int')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new LNumber(10), new IdentifierTypeNode('non-zero-int')))->toBeTrue() + ; + }); + + test('evaluates float literals and float refinements', function () { + expect(StaticTypeEvaluator::satisfies(new DNumber(3.14), new IdentifierTypeNode('float')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new DNumber(3.14), new IdentifierTypeNode('positive-float')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new UnaryMinus(new DNumber(1.5)), new IdentifierTypeNode('negative-float')))->toBeTrue() + ; + }); + + test('evaluates string literals, empty checks, and casing refinements', function () { + expect(StaticTypeEvaluator::satisfies(new String_('hello'), new IdentifierTypeNode('non-empty-string')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new String_('abc'), new IdentifierTypeNode('lowercase-string')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new String_('ABC'), new IdentifierTypeNode('uppercase-string')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new String_('123.45'), new IdentifierTypeNode('numeric-string')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies(new String_(''), new IdentifierTypeNode('non-empty-string')))->toBeFalse() + ; + }); + + test('evaluates deterministic string concatenation with non-empty prefix', function () { + $concat = new Concat(new String_('user_'), new Variable('dynamicId')); + + expect(StaticTypeEvaluator::satisfies($concat, new IdentifierTypeNode('non-empty-string')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($concat, new IdentifierTypeNode('string')))->toBeTrue() + ; + }); + + test('evaluates booleans and null constants', function () { + $trueNode = new ConstFetch(new Name('true')); + $falseNode = new ConstFetch(new Name('false')); + $nullNode = new ConstFetch(new Name('null')); + + expect(StaticTypeEvaluator::satisfies($trueNode, new IdentifierTypeNode('bool')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($trueNode, new IdentifierTypeNode('true')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($falseNode, new IdentifierTypeNode('bool')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($falseNode, new IdentifierTypeNode('false')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($nullNode, new IdentifierTypeNode('null')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($nullNode, new IdentifierTypeNode('void')))->toBeTrue() + ; + }); + }); + + describe('Arrays, Lists & Shapes Integration', function () { + test('evaluates empty arrays against permissible and non-permissible types', function () { + $empty = new Array_([]); + + expect(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('array')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('list')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($empty, new ArrayTypeNode(new IdentifierTypeNode('int'))))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('non-empty-list')))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($empty, new IdentifierTypeNode('non-empty-array')))->toBeFalse() + ; + }); + + test('evaluates sequential lists with all satisfied literal elements', function () { + $list = new Array_([ + new ArrayItem(new LNumber(1)), + new ArrayItem(new LNumber(2)), + new ArrayItem(new LNumber(3)), + ]); + $listType = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('positive-int')]); + + expect(StaticTypeEvaluator::satisfies($list, $listType))->toBeTrue(); + }); + + test('rejects sequential list when an element violates contract', function () { + $list = new Array_([ + new ArrayItem(new LNumber(1)), + new ArrayItem(new LNumber(-5)), + ]); + $listType = new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('positive-int')]); + + expect(StaticTypeEvaluator::satisfies($list, $listType))->toBeFalse(); + }); + + test('evaluates sealed and unsealed array shapes', function () { + $shapeData = new Array_([ + new ArrayItem(new LNumber(1), new String_('id')), + new ArrayItem(new String_('Alice'), new String_('name')), + ]); + + $sealedShape = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('positive-int')), + new ArrayShapeItemNode(new ConstExprStringNode('name', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('non-empty-string')), + ]); + + expect(StaticTypeEvaluator::satisfies($shapeData, $sealedShape))->toBeTrue(); + + $unsealedShape = ArrayShapeNode::createUnsealed([ + new ArrayShapeItemNode(new ConstExprStringNode('id', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('positive-int')), + ], new ArrayShapeUnsealedTypeNode(new IdentifierTypeNode('string'), new IdentifierTypeNode('string'))); + + expect(StaticTypeEvaluator::satisfies($shapeData, $unsealedShape))->toBeTrue(); + }); + }); + + describe('Constants, Enums & Bitmasks Integration', function () { + test('evaluates class constant exact matches and wildcards', function () { + $constFetch = new ClassConstFetch(new Name('self'), new Identifier('STATUS_PAID')); + $exactType = new ConstTypeNode(new ConstFetchNode('self', 'STATUS_PAID')); + $wildcard = new ConstTypeNode(new ConstFetchNode('self', 'STATUS_*')); + + expect(StaticTypeEvaluator::satisfies($constFetch, $exactType))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($constFetch, $wildcard))->toBeTrue() + ; + }); + + test('evaluates enum case fetches against enum base type and case wildcards', function () { + $enumFetch = new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')); + + expect(StaticTypeEvaluator::satisfies($enumFetch, new IdentifierTypeNode('StatusEnum')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($enumFetch, new ConstTypeNode(new ConstFetchNode('StatusEnum', '*'))))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($enumFetch, new ConstTypeNode(new ConstFetchNode('StatusEnum', 'ACT*'))))->toBeTrue() + ; + }); + + test('evaluates bitmask zero literal and bitwise OR flags', function () { + $maskType = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode('self', 'FLAG_*')), + ]); + + $flagA = new ClassConstFetch(new Name('self'), new Identifier('FLAG_READ')); + $flagB = new ClassConstFetch(new Name('self'), new Identifier('FLAG_WRITE')); + $bitwiseOr = new BitwiseOr($flagA, $flagB); + + expect(StaticTypeEvaluator::satisfies(new LNumber(0), $maskType))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($flagA, $maskType))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($bitwiseOr, $maskType))->toBeTrue() + ; + }); + + test('evaluates enum backing property access against value-of', function () { + $propFetch = new PropertyFetch( + new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')), + new Identifier('value') + ); + $valueOf = new GenericTypeNode(new IdentifierTypeNode('value-of'), [new IdentifierTypeNode('StatusEnum')]); + + expect(StaticTypeEvaluator::satisfies($propFetch, $valueOf))->toBeTrue(); + }); + }); + + describe('Objects & Identity Returns Integration', function () { + test('evaluates exact non-generic class instantiation (new User())', function () { + $newUser = new New_(new Name('User')); + + expect(StaticTypeEvaluator::satisfies($newUser, new IdentifierTypeNode('User')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($newUser, new IdentifierTypeNode('Product')))->toBeFalse() + ; + }); + + test('evaluates $this against $this and self', function () { + $thisVar = new Variable('this'); + + expect(StaticTypeEvaluator::satisfies($thisVar, new ThisTypeNode()))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($thisVar, new IdentifierTypeNode('$this')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($thisVar, new IdentifierTypeNode('self')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($thisVar, new IdentifierTypeNode('string')))->toBeFalse() + ; + }); + + test('evaluates new static() against static', function () { + $newStatic = new New_(new Name('static')); + + expect(StaticTypeEvaluator::satisfies($newStatic, new IdentifierTypeNode('static')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($newStatic, new IdentifierTypeNode('self')))->toBeFalse() + ; + }); + }); + + describe('Dynamic Expressions (Must Always Return False / Defer to Runtime)', function () { + test('defers variable expressions', function () { + expect(StaticTypeEvaluator::satisfies(new Variable('unprovenVar'), new IdentifierTypeNode('int')))->toBeFalse(); + }); + + test('defers method calls', function () { + $methodCall = new MethodCall(new Variable('this'), new Identifier('getScore')); + expect(StaticTypeEvaluator::satisfies($methodCall, new IdentifierTypeNode('positive-int')))->toBeFalse(); + }); + + test('defers function calls', function () { + $funcCall = new FuncCall(new Name('rand')); + expect(StaticTypeEvaluator::satisfies($funcCall, new IdentifierTypeNode('int')))->toBeFalse(); + }); + }); +}); diff --git a/tests/Internal/Ast/FunctionContractInjectorTest.php b/tests/Internal/Ast/FunctionContractInjectorTest.php index 5323657a..210fd341 100644 --- a/tests/Internal/Ast/FunctionContractInjectorTest.php +++ b/tests/Internal/Ast/FunctionContractInjectorTest.php @@ -130,7 +130,6 @@ public function dd(): never FunctionContractInjector::inject($fn); - // Stmts: [0] => $_typephpArgs = ['id' => $id]; [1] => if ($combinedCondition) { ... } expect(\count($fn->stmts))->toBe(2); }); }); @@ -141,7 +140,7 @@ public function dd(): never $fn = new Node\Stmt\Function_('getName', [ 'stmts' => [ - new Node\Stmt\Return_(new Node\Scalar\String_('Alice')), + new Node\Stmt\Return_(new Node\Expr\Variable('name')), ], ], [ 'comments' => [$doc], @@ -229,6 +228,10 @@ public function dd(): never }); describe('Generator Return and Yield Wrapping', function () { + beforeEach(function () { + Config::set(['eliminate_statically_proven_checks' => false]); + }); + test('wraps yield expressions with checkYield and checkSend', function () { $doc = new Doc('/** @return Generator */'); diff --git a/tests/Internal/Ast/NodeBuilderTest.php b/tests/Internal/Ast/NodeBuilderTest.php index ab81c026..7bf0db1a 100644 --- a/tests/Internal/Ast/NodeBuilderTest.php +++ b/tests/Internal/Ast/NodeBuilderTest.php @@ -63,4 +63,24 @@ expect($callWithCaller->args)->toHaveCount(8); }); + + test('createPropertyMemberAssignCheckCall creates FuncCall node for RuntimeTypeChecker::checkPropertyMemberAssign', function () { + $obj = new Node\Expr\Variable('box'); + $chain = new Node\Expr\Array_([ + new Node\Expr\ArrayItem( + new Node\Expr\Array_([ + new Node\Expr\ArrayItem(new Node\Scalar\String_('dim')), + new Node\Expr\ArrayItem(new Node\Expr\ConstFetch(new Node\Name('null'))), + ]) + ), + ]); + $val = new Node\Scalar\LNumber(42); + + $call = NodeBuilder::createPropertyMemberAssignCheckCall($obj, 'numbers', $chain, $val); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('\TypePHP\Internal\RuntimeTypeChecker::checkPropertyMemberAssign') + ->and($call->args)->toHaveCount(5) + ; + }); }); diff --git a/tests/Internal/Ast/ScopeManagerTest.php b/tests/Internal/Ast/ScopeManagerTest.php index e64cab4f..57dced3f 100644 --- a/tests/Internal/Ast/ScopeManagerTest.php +++ b/tests/Internal/Ast/ScopeManagerTest.php @@ -94,4 +94,76 @@ expect($manager->getVarTypeFromScope('test'))->toBeNull(); }); + + describe('Inferred Variable Type Stack (registerInferredVarType & getInferredVarType)', function () { + test('registers and resolves inferred variable types while keeping explicit getVarTypeFromScope null', function () { + $manager = new ScopeManager(); + $manager->pushScope(); + + $manager->registerInferredVarType('box', 'App\Models\Box'); + + expect($manager->getInferredVarType('box'))->toBe('App\Models\Box') + ->and($manager->getVarTypeFromScope('box'))->toBeNull() + ; + }); + + test('resolves inferred variable types across nested scopes and restores on popScope', function () { + $manager = new ScopeManager(); + $manager->pushScope(); + $manager->registerInferredVarType('entity', 'App\Models\Order'); + + $manager->pushScope(); + expect($manager->getInferredVarType('entity'))->toBe('App\Models\Order'); + + $manager->registerInferredVarType('entity', 'App\Models\Invoice'); + expect($manager->getInferredVarType('entity'))->toBe('App\Models\Invoice'); + + $manager->popScope(); + expect($manager->getInferredVarType('entity'))->toBe('App\Models\Order'); + + $manager->popScope(); + expect($manager->getInferredVarType('entity'))->toBeNull(); + }); + + test('unregisters inferred variable type on demand with unregisterInferredVarType', function () { + $manager = new ScopeManager(); + $manager->pushScope(); + $manager->registerInferredVarType('temp', 'App\TempClass'); + + expect($manager->getInferredVarType('temp'))->toBe('App\TempClass'); + + $manager->unregisterInferredVarType('temp'); + expect($manager->getInferredVarType('temp'))->toBeNull(); + }); + + test('unregisterVarType clears both explicit and inferred types (e.g. on unset)', function () { + $manager = new ScopeManager(); + $manager->pushScope(); + $manager->registerVarType('item', 'positive-int'); + $manager->registerInferredVarType('item', 'App\ItemClass'); + + expect($manager->getVarTypeFromScope('item'))->toBe('positive-int') + ->and($manager->getInferredVarType('item'))->toBe('App\ItemClass') + ; + + $manager->unregisterVarType('item'); + + expect($manager->getVarTypeFromScope('item'))->toBeNull() + ->and($manager->getInferredVarType('item'))->toBeNull() + ; + }); + + test('stops resolving inferred variable types at isolated scope boundaries', function () { + $manager = new ScopeManager(); + $manager->pushScope(); + $manager->registerInferredVarType('outerVar', 'App\Outer'); + + $manager->pushScope(isIsolated: true); + + expect($manager->getInferredVarType('outerVar'))->toBeNull(); + + $manager->popScope(); + expect($manager->getInferredVarType('outerVar'))->toBe('App\Outer'); + }); + }); }); diff --git a/tests/Internal/Ast/TypeDeducerTest.php b/tests/Internal/Ast/TypeDeducerTest.php new file mode 100644 index 00000000..bd858dd8 --- /dev/null +++ b/tests/Internal/Ast/TypeDeducerTest.php @@ -0,0 +1,36 @@ +'))->toBe('positive-int') + ->and(TypeDeducer::deduceElementType('int[]'))->toBe('int') + ->and(TypeDeducer::deduceElementType('array'))->toBe('float') + ->and(TypeDeducer::deduceElementType('array{id: int, name: int}'))->toBe('int') + ->and(TypeDeducer::deduceElementType('array{id: int, name: string}'))->toBe('(int|string)') + ; + }); + + test('deduces key type from lists and maps', function () { + expect(TypeDeducer::deduceKeyType('list'))->toBe('int') + ->and(TypeDeducer::deduceKeyType('int[]'))->toBe('int') + ->and(TypeDeducer::deduceKeyType('array'))->toBe('string') + ; + }); + + test('deduces specific dimension type on array shapes', function () { + $shape = 'array{id: positive-int, username: non-empty-string}'; + + expect(TypeDeducer::deduceDimType($shape, new String_('id')))->toBe('positive-int') + ->and(TypeDeducer::deduceDimType($shape, new String_('username')))->toBe('non-empty-string') + ->and(TypeDeducer::deduceDimType('list', new LNumber(0)))->toBe('int') + ; + }); +}); diff --git a/tests/Internal/Checker/MemberAssignCheckerTest.php b/tests/Internal/Checker/MemberAssignCheckerTest.php index 2e0b166c..c00e75b3 100644 --- a/tests/Internal/Checker/MemberAssignCheckerTest.php +++ b/tests/Internal/Checker/MemberAssignCheckerTest.php @@ -8,6 +8,7 @@ use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Validator\TypeValidatorRegistry; +use TypePHP\Tests\Fixtures\Types\ConfiguredProperty; describe('MemberAssignChecker Unit Tests', function () { beforeEach(function () { @@ -251,4 +252,48 @@ ->and($invalid->getMessage())->toContain('->user->id') ; }); + + test('checkProperty validates object property dimension assignments and preserves state on failure', function () { + $fixture = new ConfiguredProperty(); + $fixture->numbers = [1, 2, 3]; + + $validAppend = MemberAssignChecker::checkProperty( + $fixture, + 'numbers', + [['dim', null]], + 4, + __FILE__, + $this->registry + ); + expect($validAppend)->toBe(4) + ->and($fixture->numbers)->toBe([1, 2, 3]) + ; + + $invalidAppend = MemberAssignChecker::checkProperty( + $fixture, + 'numbers', + [['dim', null]], + 'not_an_int', + __FILE__, + $this->registry + ); + expect($invalidAppend)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidAppend->getMessage())->toContain('numbers[3] must be of type int') + ->and($fixture->numbers)->toBe([1, 2, 3]) + ; + }); + + test('checkProperty returns value untouched when target is non-object/non-string or inline properties are disabled', function () { + expect(MemberAssignChecker::checkProperty(123, 'numbers', [['dim', null]], 'val', __FILE__, $this->registry)) + ->toBe('val') + ; + + Config::set(['inline_vars' => ['properties' => false]]); + $fixture = new ConfiguredProperty(); + $fixture->numbers = [1, 2]; + + expect(MemberAssignChecker::checkProperty($fixture, 'numbers', [['dim', null]], 'invalid', __FILE__, $this->registry)) + ->toBe('invalid') + ; + }); }); diff --git a/tests/Internal/Cli/CommandRunnerTest.php b/tests/Internal/Cli/CommandRunnerTest.php index 29f6088d..3ea72470 100644 --- a/tests/Internal/Cli/CommandRunnerTest.php +++ b/tests/Internal/Cli/CommandRunnerTest.php @@ -315,24 +315,66 @@ }); test('routes cache:clear command successfully', function () { - $stream = fopen('php://memory', 'r+'); - $exitCode = CommandRunner::run(['cache:clear'], $stream, $stream); + $tempCacheDir = sys_get_temp_dir() . '/typephp_cli_cache_clear_' . uniqid(); + Config::set(['cache_dir' => $tempCacheDir]); + + try { + $stream = fopen('php://memory', 'r+'); + $exitCode = CommandRunner::run(['cache:clear'], $stream, $stream); - expect($exitCode)->toBe(0); + expect($exitCode)->toBe(0); + } finally { + Config::reset(); + if (is_dir($tempCacheDir)) { + @rmdir($tempCacheDir); + } + } }); test('routes cache:warm command successfully', function () { - $stream = fopen('php://memory', 'r+'); - $exitCode = CommandRunner::run(['cache:warm'], $stream, $stream); + $tempCacheDir = sys_get_temp_dir() . '/typephp_cli_cache_warm_' . uniqid(); + Config::set(['cache_dir' => $tempCacheDir]); + + try { + $stream = fopen('php://memory', 'r+'); + $exitCode = CommandRunner::run(['cache:warm'], $stream, $stream); - expect($exitCode)->toBe(0); + expect($exitCode)->toBe(0); + } finally { + Config::reset(); + $files = glob($tempCacheDir . '/*'); + if ($files !== false) { + foreach ($files as $f) { + @unlink($f); + } + } + if (is_dir($tempCacheDir)) { + @rmdir($tempCacheDir); + } + } }); test('routes cache:rebuild command successfully', function () { - $stream = fopen('php://memory', 'r+'); - $exitCode = CommandRunner::run(['cache:rebuild'], $stream, $stream); + $tempCacheDir = sys_get_temp_dir() . '/typephp_cli_cache_rebuild_' . uniqid(); + Config::set(['cache_dir' => $tempCacheDir]); - expect($exitCode)->toBe(0); + try { + $stream = fopen('php://memory', 'r+'); + $exitCode = CommandRunner::run(['cache:rebuild'], $stream, $stream); + + expect($exitCode)->toBe(0); + } finally { + Config::reset(); + $files = glob($tempCacheDir . '/*'); + if ($files !== false) { + foreach ($files as $f) { + @unlink($f); + } + } + if (is_dir($tempCacheDir)) { + @rmdir($tempCacheDir); + } + } }); test('returns exit code 1 and detects unknown command for typo like helps', function () { diff --git a/tests/Internal/Docblock/DocblockExtractorTest.php b/tests/Internal/Docblock/DocblockExtractorTest.php index c3374600..9d628c6b 100644 --- a/tests/Internal/Docblock/DocblockExtractorTest.php +++ b/tests/Internal/Docblock/DocblockExtractorTest.php @@ -429,6 +429,48 @@ ; }); + test('preserves exact declaration order when mixing @template-covariant, @template-contravariant, and @template', function () { + $doc = <<<'DOC' +/** + * @template-covariant K of array-key + * @template V + * @template-contravariant TIn + */ +DOC; + $node = DocblockExtractor::parseDocString($doc); + $templates = DocblockExtractor::extractTemplates($node); + $variances = DocblockExtractor::extractTemplateVariances($node); + + expect(array_keys($templates))->toBe(['K', 'V', 'TIn']) + ->and($variances)->toBe([ + 'K' => 'covariant', + 'V' => 'invariant', + 'TIn' => 'contravariant', + ]) + ; + }); + + test('preserves declaration order when @phpstan-template refines a template declared earlier', function () { + $doc = <<<'DOC' +/** + * @template-covariant K + * @template V + * @phpstan-template K of array-key + */ +DOC; + $node = DocblockExtractor::parseDocString($doc); + $templates = DocblockExtractor::extractTemplates($node); + $variances = DocblockExtractor::extractTemplateVariances($node); + + expect(array_keys($templates))->toBe(['K', 'V']) + ->and((string) $templates['K']->bound)->toBe('array-key') + ->and($variances)->toBe([ + 'K' => 'covariant', + 'V' => 'invariant', + ]) + ; + }); + test('extracts declared template variances with @phpstan-template-covariant priority', function () { $doc = <<<'DOC' /** diff --git a/tests/Internal/Io/CacheManagerTest.php b/tests/Internal/Io/CacheManagerTest.php index 404e54c6..1583a4a6 100644 --- a/tests/Internal/Io/CacheManagerTest.php +++ b/tests/Internal/Io/CacheManagerTest.php @@ -15,20 +15,30 @@ }); test('clears cached files from directory and returns count', function () { - $dir = CacheManager::getCacheDir(); + $tempCacheDir = sys_get_temp_dir() . '/typephp_unit_cache_' . uniqid(); + Config::set(['cache_dir' => $tempCacheDir]); - if (! is_dir($dir)) { - mkdir($dir, 0777, true); - } + try { + $dir = CacheManager::getCacheDir(); - $testFile = $dir . '/test_cache_unit.php'; - file_put_contents($testFile, 'toBeGreaterThanOrEqual(1) - ->and(file_exists($testFile))->toBeFalse() - ; + $count = CacheManager::clear(); + + expect($count)->toBeGreaterThanOrEqual(1) + ->and(file_exists($testFile))->toBeFalse() + ; + } finally { + Config::reset(); + if (is_dir($tempCacheDir)) { + @rmdir($tempCacheDir); + } + } }); test('bypasses filemtime when cache_check_mtime is disabled', function () { diff --git a/tests/Internal/Io/StreamWrapperTest.php b/tests/Internal/Io/StreamWrapperTest.php index f5b411f6..a4e7d274 100644 --- a/tests/Internal/Io/StreamWrapperTest.php +++ b/tests/Internal/Io/StreamWrapperTest.php @@ -48,6 +48,8 @@ function testUser(int $id): bool }); test('wraps yield expressions in generator functions', function () { + Config::set(['eliminate_statically_proven_checks' => false]); + $genSource = <<<'PHP' toBe([ + 'Animal' => 'App\Domain\Animal', + 'Dog' => 'App\Domain\Dog', + ]) + ->and($imports['Animal'])->not()->toContain('($source)') + ->and($imports)->not()->toHaveKey('source') + ; + }); + test('ignores use statements in docblock code examples and comments', function () { $source = <<<'PHP' toBe($cloned); }); + + test('checkPropertyMemberAssign validates property dimension assignments and respects disabled switch and ignore tags', function () { + $fixture = new ConfiguredProperty(); + $fixture->numbers = [10, 20]; + + $valid = RuntimeTypeChecker::checkPropertyMemberAssign( + $fixture, + 'numbers', + [['dim', null]], + 30, + __FILE__ + ); + expect($valid)->toBe(30); + + $invalid = RuntimeTypeChecker::checkPropertyMemberAssign( + $fixture, + 'numbers', + [['dim', null]], + 'wrong', + __FILE__ + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('numbers[2] must be of type int') + ->and($fixture->numbers)->toBe([10, 20]) + ; + + $ignored = RuntimeCheckerIgnoredCaller::run( + fn () => RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__) + ); + expect($ignored)->toBe('wrong'); + + Config::set(['enabled' => false]); + expect(RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__)) + ->toBe('wrong') + ; + }); }); diff --git a/tests/Internal/Wrapper/CallableWrapperTest.php b/tests/Internal/Wrapper/CallableWrapperTest.php index b6825bfb..24c6dd0e 100644 --- a/tests/Internal/Wrapper/CallableWrapperTest.php +++ b/tests/Internal/Wrapper/CallableWrapperTest.php @@ -5,9 +5,21 @@ namespace TypePHP\Tests\Internal\Wrapper; use Closure; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode; +use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; +use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use ReflectionClass; use TypeError; use TypePHP\Internal\Docblock\DocblockParser; @@ -15,6 +27,10 @@ use TypePHP\Internal\Util\Config; use TypePHP\Internal\Validator\TypeValidatorRegistry; use TypePHP\Internal\Wrapper\CallableWrapper; +use TypePHP\Tests\Fixtures\Domain\Animal; +use TypePHP\Tests\Fixtures\Domain\Car; +use TypePHP\Tests\Fixtures\Domain\Cat; +use TypePHP\Tests\Fixtures\Domain\Dog; /** * @phpstan-type FormatterAlias callable(positive-int): non-empty-string @@ -676,4 +692,461 @@ public function __invoke(): void expect(CallableWrapper::isCallable(123))->toBeFalse(); }); }); + + describe('CallableWrapper Deep Coverage & Edge Cases', function () { + test('specialized callable cache hit on repeated generic invocation', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'val', false)], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + + $wrapped = CallableWrapper::wrapTypeNode( + $typeNode, + fn ($x) => $x, + 'TestCache', + $registry, + 'App\\Service::run', + 'cb' + ); + + expect($wrapped(42))->toBe(42); + expect($wrapped(99))->toBe(99); + }); + + test('resolveEffectiveCallableTypeNode handles built-in template tag names gracefully', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new IdentifierTypeNode('int'), false, false, 'val', false)], + new IdentifierTypeNode('int'), + [new TemplateTagValueNode('int', null, '')] + ); + + $wrapped = CallableWrapper::wrapTypeNode($typeNode, fn ($x) => $x, 'TestBuiltin', $registry); + expect($wrapped(10))->toBe(10); + }); + + test('variadic parameter with local template infers and validates all items', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, true, 'items', false)], + new IdentifierTypeNode('void'), + [new TemplateTagValueNode('T', null, '')] + ); + + $wrapped = CallableWrapper::wrapTypeNode($typeNode, fn (...$items) => null, 'TestVarLocal', $registry); + $wrapped(10, 20, 30); + expect(true)->toBeTrue(); + }); + + test('infers local template from closure native return type declaration', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + + $closure = fn (): int => 42; + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $closure, 'TestClosureRet', $registry); + expect($wrapped())->toBe(42); + }); + + test('resolves bounded local template when function is empty string using closure file reflection', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'pet', false)], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', new IdentifierTypeNode(Animal::class), '')] + ); + + $closure = fn (Animal $a): Animal => $a; + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $closure, 'TestBoundedClosure', $registry, ''); + + $dog = new Dog(); + expect($wrapped($dog))->toBe($dog); + + expect(fn () => $wrapped(new Car())) + ->toThrow(TypeError::class, Animal::class) + ; + }); + + test('unifies local template types across multiple parameters into a union (unifyLocalTypes)', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'a', false), + new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'b', false), + ], + new IdentifierTypeNode('void'), + [new TemplateTagValueNode('T', new IdentifierTypeNode(Animal::class), '')] + ); + + $fn = fn ($a, $b) => null; + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $fn, 'TestUnify', $registry, 'App\\Test::fn'); + + $dog = new Dog(); + $cat = new Cat(); + + $wrapped($dog, $cat); + expect(true)->toBeTrue(); + + $wrapped($dog, $dog); + expect(true)->toBeTrue(); + }); + + test('unifies local template when existing type is already a union', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'a', false), + new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'b', false), + new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'c', false), + ], + new IdentifierTypeNode('void'), + [new TemplateTagValueNode('T', new IdentifierTypeNode('object'), '')] + ); + + $fn = fn ($a, $b, $c) => null; + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $fn, 'TestUnifyUnion', $registry, 'App\\Test::fn'); + + $wrapped(new Dog(), new Cat(), new Car()); + expect(true)->toBeTrue(); + }); + + test('infers local template from ArrayTypeNode, GenericTypeNode, and ArrayShapeNode', function () { + $registry = new TypeValidatorRegistry(); + + $arrayTypeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new ArrayTypeNode(new IdentifierTypeNode('T')), false, false, 'items', false)], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + $wrappedArr = CallableWrapper::wrapTypeNode($arrayTypeNode, fn (array $items) => $items[0], 'TestArr', $registry); + expect($wrappedArr([10, 20]))->toBe(10); + + $listTypeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new GenericTypeNode(new IdentifierTypeNode('list'), [new IdentifierTypeNode('T')]), false, false, 'items', false)], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + $wrappedList = CallableWrapper::wrapTypeNode($listTypeNode, fn (array $items) => $items[0], 'TestList', $registry); + expect($wrappedList(['alpha', 'beta']))->toBe('alpha'); + + $mapTypeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new GenericTypeNode(new IdentifierTypeNode('array'), [new IdentifierTypeNode('string'), new IdentifierTypeNode('T')]), false, false, 'map', false)], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + $wrappedMap = CallableWrapper::wrapTypeNode($mapTypeNode, fn (array $map) => reset($map), 'TestMap', $registry); + expect($wrappedMap(['key' => 123]))->toBe(123); + + $shapeTypeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode( + ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('data', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('T')), + new ArrayShapeItemNode(new ConstExprIntegerNode('0'), false, new IdentifierTypeNode('T')), + ]), + false, + false, + 'payload', + false + ), + ], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + $wrappedShape = CallableWrapper::wrapTypeNode($shapeTypeNode, fn (array $p) => $p['data'], 'TestShape', $registry); + expect($wrappedShape(['data' => 99, 0 => 99]))->toBe(99); + + $objShapeTypeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode( + new ObjectShapeNode([ + new ObjectShapeItemNode(new IdentifierTypeNode('data'), false, new IdentifierTypeNode('T')), + ]), + false, + false, + 'obj', + false + ), + ], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + $wrappedObjShape = CallableWrapper::wrapTypeNode($objShapeTypeNode, fn ($o) => $o->data, 'TestObjShape', $registry); + expect($wrappedObjShape((object)['data' => 'hello']))->toBe('hello'); + }); + + test('wraps callable return value when callable returns another callable', function () { + $registry = new TypeValidatorRegistry(); + $innerCallableType = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new IdentifierTypeNode('positive-int'), false, false, 'num', false)], + new IdentifierTypeNode('string'), + [] + ); + + $outerCallableType = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [], + $innerCallableType, + [] + ); + + $factory = fn (): callable => fn (int $x): string => "x_{$x}"; + + $wrappedOuter = CallableWrapper::wrapTypeNode($outerCallableType, $factory, 'TestOuter', $registry); + $wrappedInner = $wrappedOuter(); + + expect($wrappedInner(42))->toBe('x_42'); + expect(fn () => $wrappedInner(-1))->toThrow(TypeError::class, 'positive-int'); + }); + }); + + test('catches native TypeError in standard non-ref dispatcher', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode(new IdentifierTypeNode('callable'), [], new IdentifierTypeNode('void'), []); + $throwing = fn () => throw new TypeError('Native non-ref error'); + + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $throwing, 'TestThrowNonRef', $registry); + + expect(fn () => $wrapped())->toThrow(TypeError::class, 'Native non-ref error'); + }); + + test('executes successful non-throwing mutation in [true, false] mixed dispatcher', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode(new IdentifierTypeNode('positive-int'), true, false, 'a', false), + new CallableTypeParameterNode(new IdentifierTypeNode('string'), false, false, 'b', false), + ], + new IdentifierTypeNode('string'), + [] + ); + + $mutator = function (int &$a, string $b): string { + $a += 10; + + return "{$b}_{$a}"; + }; + + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $mutator, 'TestSuccessTrueFalse', $registry); + $val = 5; + $result = $wrapped($val, 'score'); + + expect($val)->toBe(15) + ->and($result)->toBe('score_15') + ; + }); + + test('executes successful non-throwing mutation in [false, true] mixed dispatcher', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode(new IdentifierTypeNode('string'), false, false, 'a', false), + new CallableTypeParameterNode(new IdentifierTypeNode('positive-int'), true, false, 'b', false), + ], + new IdentifierTypeNode('string'), + [] + ); + + $mutator = function (string $a, int &$b): string { + $b += 20; + + return "{$a}_{$b}"; + }; + + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $mutator, 'TestSuccessFalseTrue', $registry); + $val = 10; + $result = $wrapped('total', $val); + + expect($val)->toBe(30) + ->and($result)->toBe('total_30') + ; + }); + + test('returns early when passing null to nullable local template parameter ?T', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new NullableTypeNode(new IdentifierTypeNode('T')), false, false, 'item', false)], + new IdentifierTypeNode('void'), + [new TemplateTagValueNode('T', null, '')] + ); + + $fn = fn ($x) => null; + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $fn, 'TestNullParam', $registry); + + $wrapped(null); + expect(true)->toBeTrue(); + }); + + test('unifyLocalTypes handles identical types and UnionTypeNode for second type', function () { + $refMethod = new \ReflectionMethod(CallableWrapper::class, 'unifyLocalTypes'); + + $intNode1 = new IdentifierTypeNode('int'); + $intNode2 = new IdentifierTypeNode('int'); + $resSame = $refMethod->invoke(null, $intNode1, $intNode2); + expect((string) $resSame)->toBe('int'); + + $unionNode2 = new UnionTypeNode([new IdentifierTypeNode('string'), new IdentifierTypeNode('bool')]); + $resUnion = $refMethod->invoke(null, $intNode1, $unionNode2); + expect((string) $resUnion)->toBe('(int | string | bool)'); + }); + + test('bypasses local template bound error when callback is executed in vendor context', function () { + $registry = new TypeValidatorRegistry(); + + $tempBase = sys_get_temp_dir() . '/typephp_vendor_bound_bypass_' . uniqid(); + $vendorDir = $tempBase . '/vendor/acme/bound_runner'; + mkdir($vendorDir, 0777, true); + $vendorFile = $vendorDir . '/VendorBoundCaller.php'; + + file_put_contents( + $vendorFile, + <<<'PHP' +toBe($car); + } finally { + @unlink($vendorFile); + @rmdir($vendorDir); + @rmdir($tempBase . '/vendor/acme'); + @rmdir($tempBase . '/vendor'); + @rmdir($tempBase); + CallerBoundaryResolver::reset(); + } + }); + + test('infers local template when argument is passed by name', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'customParam', false)], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + + $wrapped = CallableWrapper::wrapTypeNode( + $typeNode, + fn ($customParam) => $customParam, + 'TestNamedLocal', + $registry + ); + + $result = $wrapped(customParam: 100); + expect($result)->toBe(100); + }); + + test('infers local template when non-null value is passed to nullable parameter ?T', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [new CallableTypeParameterNode(new NullableTypeNode(new IdentifierTypeNode('T')), false, false, 'item', false)], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + + $fn = fn ($x) => $x; + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $fn, 'TestNonNullParam', $registry); + + $result = $wrapped(42); + expect($result)->toBe(42); + }); + + test('unifies local template when function name is empty string', function () { + $registry = new TypeValidatorRegistry(); + $typeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'a', false), + new CallableTypeParameterNode(new IdentifierTypeNode('T'), false, false, 'b', false), + ], + new IdentifierTypeNode('void'), + [new TemplateTagValueNode('T', new IdentifierTypeNode(Animal::class), '')] + ); + + $fn = fn ($a, $b) => null; + + $wrapped = CallableWrapper::wrapTypeNode($typeNode, $fn, 'TestUnifyEmptyFunc', $registry, ''); + + $wrapped(new Dog(), new Cat()); + expect(true)->toBeTrue(); + }); + + test('infers local template from ArrayShapeNode with identifier, const fetch, and auto-indexed keys', function () { + $registry = new TypeValidatorRegistry(); + $shapeTypeNode = new CallableTypeNode( + new IdentifierTypeNode('callable'), + [ + new CallableTypeParameterNode( + ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new IdentifierTypeNode('alpha'), false, new IdentifierTypeNode('T')), + new ArrayShapeItemNode(new ConstFetchNode('self', 'BETA'), false, new IdentifierTypeNode('T')), + new ArrayShapeItemNode(null, false, new IdentifierTypeNode('T')), + ]), + false, + false, + 'payload', + false + ), + ], + new IdentifierTypeNode('T'), + [new TemplateTagValueNode('T', null, '')] + ); + + $fn = fn (array $p) => $p['alpha']; + $wrapped = CallableWrapper::wrapTypeNode($shapeTypeNode, $fn, 'TestShapeKeys', $registry); + + $result = $wrapped([ + 'alpha' => 10, + 'self::BETA' => 10, + 0 => 10, + ]); + + expect($result)->toBe(10); + }); }); diff --git a/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php b/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php index ee667fc2..df38317d 100644 --- a/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php +++ b/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php @@ -21,7 +21,7 @@ . " */\r\n" . "function formatUserData(int \$id, string \$name): string\r\n" . "{\r\n" - . " return \"user_{\$id}_{\$name}\";\r\n" + . " return \$name;\r\n" . "}\r\n" . "\r\n" . "formatUserData(-5, 'Alice');\r\n"; @@ -31,19 +31,15 @@ $origLines = explode("\n", str_replace("\r\n", "\n", $source)); $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); - // 1. Total line counts must be 100% identical expect(\count($transLines))->toBe(\count($origLines)); - // 2. Call site line must be on the exact same line index $origCallLine = array_search("formatUserData(-5, 'Alice');", array_map('trim', $origLines), true); $transCallLine = array_search("formatUserData(-5, 'Alice');", array_map('trim', $transLines), true); expect($transCallLine)->toBe($origCallLine) - ->and($origCallLine)->toBe(14) // Line index 14 (Line 15 in file) + ->and($origCallLine)->toBe(14) ; - - // 3. Return statement must remain on the exact same line index (Line 11) - $origReturnLine = array_search('return "user_{$id}_{$name}";', array_map('trim', $origLines), true); + $origReturnLine = array_search('return $name;', array_map('trim', $origLines), true); expect($origReturnLine)->toBe(11) ->and($transLines[11])->toContain('RuntimeTypeChecker::checkReturn') ; diff --git a/tests/TypeChecking/Boundaries/ForeachReferenceAssignmentTest.php b/tests/TypeChecking/Boundaries/ForeachReferenceAssignmentTest.php new file mode 100644 index 00000000..3ccc73aa --- /dev/null +++ b/tests/TypeChecking/Boundaries/ForeachReferenceAssignmentTest.php @@ -0,0 +1,114 @@ + $numbers */ + $numbers = [1, 2, 3]; + + expect(function () use (&$numbers) { + foreach ($numbers as &$number) { + $number = 'wrong'; + } + })->toThrow(TypeError::class, 'Variable $number must be of type int, string \'wrong\' given'); + }); + + test('allows valid assignment to by-reference foreach item and mutates array in place', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + foreach ($numbers as &$number) { + $number *= 10; + } + unset($number); + + expect($numbers)->toBe([10, 20, 30]); + }); + + test('intercepts invalid assignment on associative map value and validates key type', function () { + /** @var array $scores */ + $scores = ['alice' => 10, 'bob' => 20]; + + expect(function () use (&$scores) { + foreach ($scores as $name => &$score) { + $score = -5; + } + })->toThrow(TypeError::class, 'Variable $score must be of type positive-int, negative int (-5) given'); + }); + + test('propagates element type when iterating member dimension (e.g. $data[\'items\'] as &$item)', function () { + /** @var array{items: list} $data */ + $data = ['items' => [1, 2, 3]]; + + expect(function () use (&$data) { + foreach ($data['items'] as &$item) { + $item = -99; + } + })->toThrow(TypeError::class, 'Variable $item must be of type positive-int'); + }); + + test('preserves explicit inline @var docblock on foreach loop over deduced type', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + expect(function () use (&$numbers) { + /** @var positive-int $number */ + foreach ($numbers as &$number) { + $number = 0; + } + })->toThrow(TypeError::class, 'positive-int'); + }); +}); + +describe('Post-Loop Boundary Re-validation (The @param-out Analog)', function () { + test('catches by-ref mutation caused by an untyped opaque function call at loop exit', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + $mutator = function (mixed &$val): void { + $val = 'corrupted_by_opaque_call'; + }; + + expect(function () use (&$numbers, $mutator) { + foreach ($numbers as &$number) { + $mutator($number); + } + })->toThrow(TypeError::class, 'Variable $numbers[0] must be of type int'); + }); + + test('statically eliminates post-loop boundary check when loop body has no opaque calls and valid operations', function () { + $source = <<<'PHP' + $numbers */ +$numbers = [1, 2, 3]; +foreach ($numbers as &$number) { + $number = 42; +} +unset($number); +PHP; + + $transformed = \TypePHP\Internal\Io\StreamWrapper::transformSource($source, 'test_loop_elim.php'); + + // Neither the assignment nor the loop boundary requires runtime checks + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkVariable'); + }); + + test('unregisters reference variable after unset() statement', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + foreach ($numbers as &$number) { + $number = 10; + } + unset($number); + + // Reusing $number without docblock after unset should not enforce int + $number = 'new_string'; + expect($number)->toBe('new_string'); + }); +}); diff --git a/tests/TypeChecking/Boundaries/PhpstanAndPsalmTagPriorityTest.php b/tests/TypeChecking/Boundaries/PhpstanAndPsalmTagPriorityTest.php index 40f4798c..d6704cfe 100644 --- a/tests/TypeChecking/Boundaries/PhpstanAndPsalmTagPriorityTest.php +++ b/tests/TypeChecking/Boundaries/PhpstanAndPsalmTagPriorityTest.php @@ -169,5 +169,36 @@ function handleCovariantProducer(CovariantProducer $producer): mixed ->and(handleCovariantProducer($producer))->toBeInstanceOf(Dog::class) ; }); + + test('merges bound and variance when @phpstan-template T of Bound and @phpstan-template-covariant T are split across tags', function () { + $producerClass = new class (new Dog()) { + /** + * @template T + * + * @phpstan-template T of Animal + * + * @phpstan-template-covariant T + */ + public function __construct(public mixed $item) + { + } + }; + + $doc = <<<'DOC' +/** + * @template T + * @phpstan-template T of \TypePHP\Tests\Fixtures\Domain\Animal + * @phpstan-template-covariant T + */ +DOC; + $node = \TypePHP\Internal\Docblock\DocblockExtractor::parseDocString($doc); + $templates = \TypePHP\Internal\Docblock\DocblockExtractor::extractTemplates($node); + $variances = \TypePHP\Internal\Docblock\DocblockExtractor::extractTemplateVariances($node); + + expect($templates)->toHaveKey('T') + ->and((string) $templates['T']->bound)->toBe('\TypePHP\Tests\Fixtures\Domain\Animal') + ->and($variances['T'])->toBe('covariant') + ; + }); }); }); diff --git a/tests/TypeChecking/Boundaries/PropertyDimensionAssignmentTest.php b/tests/TypeChecking/Boundaries/PropertyDimensionAssignmentTest.php new file mode 100644 index 00000000..8ae1e496 --- /dev/null +++ b/tests/TypeChecking/Boundaries/PropertyDimensionAssignmentTest.php @@ -0,0 +1,170 @@ + + */ + public array $numbers = [1, 2, 3]; + + /** + * @var array{id: positive-int, name: non-empty-string} + */ + public array $user = [ + 'id' => 1, + 'name' => 'Alice', + ]; + + /** + * @var array{string, int} + */ + public array $tuple = ['Alice', 30]; + + /** + * @var list> + */ + public array $matrix = [ + [1, 2], + [3, 4], + ]; + + /** + * @var list + */ + public array $scores = [10, 20]; +} + +class PropertyDimStaticBox +{ + /** + * @var list + */ + public static array $numbers = [1, 2, 3]; + + public static function reset(): void + { + self::$numbers = [1, 2, 3]; + } +} + +describe('Property Dimension & Array Append Validation ($obj->prop[] = $val)', function () { + describe('1. Object Property List Appends & Index Assignments', function () { + test('throws TypeError when appending an invalid value to an object array property ($box->numbers[] = "wrong")', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->numbers[] = 'wrong'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + + test('allows appending a valid value to an object array property', function () { + $box = new PropertyDimBox(); + + $box->numbers[] = 4; + expect($box->numbers)->toBe([1, 2, 3, 4]); + }); + + test('throws TypeError when assigning an invalid value to an existing index ($box->numbers[0] = "wrong")', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->numbers[0] = 'wrong'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + }); + + describe('2. Object Property Array Shapes & Sealed Violations', function () { + test('throws TypeError when mutating an array shape key on an object property ($box->user["name"] = 123)', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->user['name'] = 123; + })->toThrow(TypeError::class, 'must be of type non-empty-string'); + }); + + test('throws TypeError when assigning an unexpected key to a sealed array shape property ($box->user["extra"] = "forbidden")', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->user['extra'] = 'forbidden'; + })->toThrow(TypeError::class, "contains unsealed unexpected key 'extra'"); + }); + }); + + describe('3. Positional Tuples on Object Properties', function () { + test('throws TypeError when assigning invalid type to tuple index ($box->tuple[0] = 123)', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->tuple[0] = 123; + })->toThrow(TypeError::class, 'must be of type string'); + }); + + test('throws TypeError when appending extra element to a tuple ($box->tuple[] = "extra")', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->tuple[] = 'extra'; + })->toThrow(TypeError::class, "contains unsealed unexpected key '2'"); + }); + }); + + describe('4. Nested Multi-Dimensional Property Arrays', function () { + test('throws TypeError on nested multi-dimensional property array mutation ($box->matrix[0][1] = "wrong")', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->matrix[0][1] = 'wrong'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + }); + + describe('5. Static Property Array Dimensions', function () { + beforeEach(function () { + PropertyDimStaticBox::reset(); + }); + + afterEach(function () { + PropertyDimStaticBox::reset(); + }); + + test('throws TypeError when appending an invalid value to a static array property (StaticBox::$numbers[] = "wrong")', function () { + expect(function () { + PropertyDimStaticBox::$numbers[] = 'wrong'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + + test('throws TypeError when assigning an invalid value to a static array index (StaticBox::$numbers[0] = "wrong")', function () { + expect(function () { + PropertyDimStaticBox::$numbers[0] = 'wrong'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + }); + + describe('6. Compound Assignments & Atomic State Preservation', function () { + test('throws TypeError on compound assignment violating property element contract ($box->scores[0] += -100)', function () { + $box = new PropertyDimBox(); + + expect(function () use ($box) { + $box->scores[0] += -100; + })->toThrow(TypeError::class, 'must be of type positive-int'); + }); + + test('preserves property array state when dimension assignment throws TypeError (atomic failure)', function () { + $box = new PropertyDimBox(); + + try { + $box->numbers[] = 'wrong'; + } catch (TypeError) { + } + + expect($box->numbers)->toBe([1, 2, 3]); + }); + }); +}); diff --git a/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php b/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php new file mode 100644 index 00000000..fd8855c4 --- /dev/null +++ b/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php @@ -0,0 +1,205 @@ + + */ + public array $localNumbers = [1, 2, 3]; + + /** + * @var array{id: positive-int, name: non-empty-string} + */ + public array $localUser = [ + 'id' => 1, + 'name' => 'Alice', + ]; + + public function mutateInternalScoreByRef(mixed $val): void + { + $ref = &$this->localScore; + $ref = $val; + } +} + +describe('By-Reference Property Aliasing ($ref = &$obj->prop)', function () { + beforeEach(function () { + PropertyRefTargetFixture::reset(); + }); + + describe('1. External Instance Property Reference Aliasing ($ref = &$box->prop)', function () { + test('throws TypeError when assigning invalid value to reference aliasing a scalar property', function () { + $box = new PropertyRefTargetFixture(); + + $ref = &$box->score; + + expect(function () use (&$ref) { + $ref = -50; + })->toThrow(TypeError::class, 'positive-int'); + }); + + test('allows valid assignment to reference aliasing a scalar property and mutates property in place', function () { + $box = new PropertyRefTargetFixture(); + + $ref = &$box->score; + $ref = 42; + + expect($box->score)->toBe(42) + ->and($ref)->toBe(42) + ; + }); + }); + + describe('2. External Property Array Dimension Reference ($ref = &$box->numbers[0])', function () { + test('throws TypeError when assigning invalid value to reference aliasing an array property element', function () { + $box = new PropertyRefTargetFixture(); + + $ref = &$box->numbers[0]; + + expect(function () use (&$ref) { + $ref = 'not_an_int'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + + test('allows valid assignment to reference aliasing an array property element and mutates array in place', function () { + $box = new PropertyRefTargetFixture(); + + $ref = &$box->numbers[0]; + $ref = 999; + + expect($box->numbers[0])->toBe(999) + ->and($ref)->toBe(999) + ; + }); + }); + + describe('3. External Property Array Shape Key Reference ($ref = &$box->user[\'name\'])', function () { + test('throws TypeError when assigning invalid value to reference aliasing a shape property key', function () { + $box = new PropertyRefTargetFixture(); + + $ref = &$box->user['name']; + + expect(function () use (&$ref) { + $ref = ''; // Violates non-empty-string + })->toThrow(TypeError::class, 'non-empty-string'); + }); + + test('throws TypeError when assigning invalid value to reference aliasing a positive-int shape key', function () { + $box = new PropertyRefTargetFixture(); + + $ref = &$box->user['id']; + + expect(function () use (&$ref) { + $ref = -1; // Violates positive-int + })->toThrow(TypeError::class, 'positive-int'); + }); + }); + + describe('4. Internal $this Property Reference Aliasing ($ref = &$this->prop)', function () { + test('throws TypeError when internal method mutates $this scalar property via reference alias', function () { + $box = new PropertyRefTargetFixture(); + + expect(function () use ($box) { + $box->mutateInternalScoreByRef(-99); + })->toThrow(TypeError::class, 'positive-int'); + + expect($box->score)->toBe(10); + }); + + test('throws TypeError when internal method mutates $this array element via reference alias', function () { + $box = new PropertyRefTargetFixture(); + + expect(function () use ($box) { + $box->mutateInternalNumberByRef('invalid_element'); + })->toThrow(TypeError::class, 'must be of type int'); + + expect($box->numbers[0])->toBe(1); + }); + + test('throws TypeError when internal method mutates $this shape key via reference alias', function () { + $box = new PropertyRefTargetFixture(); + + expect(function () use ($box) { + $box->mutateInternalUserByRef(''); + })->toThrow(TypeError::class, 'non-empty-string'); + + expect($box->user['name'])->toBe('Alice'); + }); + }); + + describe('5. Static Property Reference Aliasing ($ref = &Class::$prop)', function () { + test('throws TypeError when assigning invalid value to reference aliasing a static property', function () { + $ref = &PropertyRefTargetFixture::$staticScore; + + expect(function () use (&$ref) { + $ref = -100; + })->toThrow(TypeError::class, 'positive-int'); + + expect(PropertyRefTargetFixture::$staticScore)->toBe(100); + }); + }); + + describe('6. Same-File Declared Class Property Reference Aliasing (AST-Level Fallback)', function () { + test('throws TypeError on scalar reference mutation for class declared in the same file', function () { + $local = new SameFilePropertyRefFixture(); + + $ref = &$local->localScore; + + expect(function () use (&$ref) { + $ref = -25; + })->toThrow(TypeError::class, 'positive-int'); + + expect($local->localScore)->toBe(10); + }); + + test('throws TypeError on array dimension reference mutation for class declared in the same file', function () { + $local = new SameFilePropertyRefFixture(); + + $ref = &$local->localNumbers[0]; + + expect(function () use (&$ref) { + $ref = 'wrong_type'; + })->toThrow(TypeError::class, 'must be of type int'); + + expect($local->localNumbers[0])->toBe(1); + }); + + test('throws TypeError on shape key reference mutation for class declared in the same file', function () { + $local = new SameFilePropertyRefFixture(); + + $ref = &$local->localUser['name']; + + expect(function () use (&$ref) { + $ref = ''; + })->toThrow(TypeError::class, 'non-empty-string'); + + expect($local->localUser['name'])->toBe('Alice'); + }); + + test('throws TypeError on $this reference mutation for class declared in the same file', function () { + $local = new SameFilePropertyRefFixture(); + + expect(function () use ($local) { + $local->mutateInternalScoreByRef(-99); + })->toThrow(TypeError::class, 'positive-int'); + + expect($local->localScore)->toBe(10); + }); + }); +}); diff --git a/tests/TypeChecking/Boundaries/ReferenceAssignmentTest.php b/tests/TypeChecking/Boundaries/ReferenceAssignmentTest.php new file mode 100644 index 00000000..617f9152 --- /dev/null +++ b/tests/TypeChecking/Boundaries/ReferenceAssignmentTest.php @@ -0,0 +1,73 @@ + $numbers */ + $numbers = [1, 2, 3]; + + $ref = &$numbers[0]; + + expect(function () use (&$ref) { + $ref = 'wrong'; + })->toThrow(TypeError::class, 'Variable $ref must be of type int, string \'wrong\' given'); + }); + + test('allows valid assignment to variable referencing array element and mutates array in place', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + $ref = &$numbers[0]; + $ref = 42; + + expect($numbers)->toBe([42, 2, 3]) + ->and($ref)->toBe(42) + ; + }); + + test('intercepts invalid assignment on aliased whole collection ($ref =& $numbers)', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + $ref = &$numbers; + + expect(function () use (&$ref) { + $ref[] = 'wrong'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + + test('intercepts invalid assignment to reference on specific array shape key', function () { + /** @var array{id: positive-int, name: non-empty-string} $user */ + $user = ['id' => 1, 'name' => 'Alice']; + + $idRef = &$user['id']; + $nameRef = &$user['name']; + + expect(function () use (&$idRef) { + $idRef = -5; + })->toThrow(TypeError::class, 'Variable $idRef must be of type positive-int'); + + expect(function () use (&$nameRef) { + $nameRef = ''; + })->toThrow(TypeError::class, 'Variable $nameRef must be of type non-empty-string'); + }); + + test('unregisters alias type when reference is broken or rebound to untyped variable', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + $ref = &$numbers[0]; + + $untypedString = 'clean'; + $ref = &$untypedString; + + // $ref is now bound to $untypedString (untyped), so assigning string must not throw int mismatch! + $ref = 'allowed_string'; + expect($ref)->toBe('allowed_string'); + }); +}); diff --git a/tests/TypeChecking/Boundaries/ReferenceMutationEndToEndTest.php b/tests/TypeChecking/Boundaries/ReferenceMutationEndToEndTest.php new file mode 100644 index 00000000..ba84daf6 --- /dev/null +++ b/tests/TypeChecking/Boundaries/ReferenceMutationEndToEndTest.php @@ -0,0 +1,69 @@ + $numbers */ + $numbers = [1, 2, 3]; + + expect(function () use (&$numbers) { + $numbers[0] = 'wrong'; + })->toThrow(TypeError::class, 'Variable $numbers[0] must be of type int, string \'wrong\' given'); + }); + + test('2. Modification through a reference alias catches type violation at mutation point', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + $ref = &$numbers[0]; + + expect(function () use (&$ref) { + $ref = 'wrong'; + })->toThrow(TypeError::class, 'Variable $ref must be of type int, string \'wrong\' given'); + }); + + test('3. Modification through foreach reference catches type violation inside loop', function () { + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + expect(function () use (&$numbers) { + foreach ($numbers as &$number) { + $number = 'wrong'; + } + })->toThrow(TypeError::class, 'Variable $number must be of type int, string \'wrong\' given'); + }); + + test('4. Mutation through a by-reference parameter catches type violation upon callback exit', function () { + /** @var callable(list&): void $corrupt */ + $corrupt = function (array &$numbers): void { + $numbers[] = 'wrong'; + }; + + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + expect(function () use ($corrupt, &$numbers) { + $corrupt($numbers); + })->toThrow(TypeError::class, 'Callback argument #1[3] must be of type int, string \'wrong\' given'); + }); + + test('5. Revalidation at reference assignment intercepts before function boundary call', function () { + /** @var callable(list): void $acceptNumbers */ + $acceptNumbers = function (array $numbers): void { + }; + + /** @var list $numbers */ + $numbers = [1, 2, 3]; + + $ref = &$numbers[0]; + + expect(function () use (&$ref) { + $ref = 'wrong'; + })->toThrow(TypeError::class, 'Variable $ref must be of type int, string \'wrong\' given'); + }); +}); diff --git a/tests/TypeChecking/Configuration/BoundaryConfigTest.php b/tests/TypeChecking/Configuration/BoundaryConfigTest.php index 1231c9f8..bfde6f58 100644 --- a/tests/TypeChecking/Configuration/BoundaryConfigTest.php +++ b/tests/TypeChecking/Configuration/BoundaryConfigTest.php @@ -110,7 +110,7 @@ public function login(): void test('skips template parameter validation when params config is set to false even if pre-bound', function () { Config::set([ 'params' => false, - 'inline_vars' => ['generics' => true], + 'inline_vars' => ['generics' => true, 'properties' => false], ]); /** @var GenericCollection $dogs */ diff --git a/tests/TypeChecking/Generics/CloneGenericInstanceTest.php b/tests/TypeChecking/Generics/CloneGenericInstanceTest.php index a50c0c92..3b57d1a6 100644 --- a/tests/TypeChecking/Generics/CloneGenericInstanceTest.php +++ b/tests/TypeChecking/Generics/CloneGenericInstanceTest.php @@ -8,7 +8,40 @@ use TypePHP\Tests\Fixtures\Generics\GenericBox; use TypePHP\Tests\Fixtures\Generics\GenericBoxWithMagicClone; +/** + * @template T + */ +class SmartBoxWithInvalidCloneFixture +{ + /** + * @var T|null + */ + public mixed $item = null; + + /** + * @param T $item + */ + public function set(mixed $item): void + { + $this->item = $item; + } + + public function __clone(): void + { + $this->set(new Car()); + } +} + describe('Clone Keyword & Generic Prebinding Preservation', function () { + test('enforces generic template contract inside __clone() method execution (TDD Reproduction)', function () { + /** @var SmartBoxWithInvalidCloneFixture $box */ + $box = new SmartBoxWithInvalidCloneFixture(); + + expect(fn () => clone $box) + ->toThrow(TypeError::class, 'must be of type ' . Dog::class) + ; + }); + test('preserves generic template bindings when a standard object is cloned', function () { /** @var GenericBox $dogBox */ $dogBox = new GenericBox(); @@ -43,19 +76,15 @@ $dog1 = new Dog(); $box1->set($dog1); - // Clone $box1 into $box2 $box2 = clone $box1; - // Mutate $box2's item to a new Dog instance $dog2 = new Dog(); $box2->set($dog2); - // Verify WeakMap and property state isolation expect($box2->item)->toBe($dog2) - ->and($box1->item)->toBe($dog1) // $box1's item remains unchanged! + ->and($box1->item)->toBe($dog1) ; - // Both $box1 and $box2 independently enforce T = Dog and reject Car! expect(fn () => $box1->set(new Car())) ->toThrow(TypeError::class, 'template T = TypePHP\Tests\Fixtures\Domain\Dog') ; diff --git a/tests/TypeChecking/Generics/MixedVarianceMultiTemplateOrderTest.php b/tests/TypeChecking/Generics/MixedVarianceMultiTemplateOrderTest.php new file mode 100644 index 00000000..170708a6 --- /dev/null +++ b/tests/TypeChecking/Generics/MixedVarianceMultiTemplateOrderTest.php @@ -0,0 +1,211 @@ +k = $k; + } + + /** + * @param V $v + */ + public function setValue(mixed $v): void + { + $this->v = $v; + } +} + +/** + * 3-Template class mixing contravariant, covariant, and invariant in order + * + * @template-contravariant TIn of Animal + * + * @template-covariant TOut of Animal + * + * @template TState + */ +class MixedThreeVariancePipeline +{ + /** + * @param TIn $input + * @param TOut $output + * @param TState $state + */ + public function __construct( + public mixed $input, + public mixed $output, + public mixed $state, + ) { + } +} + +/** + * Mixed variance with @phpstan-template bound refinement on the first template + * + * @template-covariant K + * + * @template V + * + * @phpstan-template-covariant K of array-key + */ +class RefinedMixedVarianceCatalog +{ + /** + * @param K $k + * @param V $v + */ + public function __construct( + public mixed $k, + public mixed $v, + ) { + } +} + +describe('Mixed Variance Multi-Template Declaration Order', function () { + test('preserves declaration order when @template-covariant precedes @template (Bug Reproduction)', function () { + /** @var MixedVarianceKeyValueCatalog $catalog */ + $catalog = new MixedVarianceKeyValueCatalog('prod_01', new User()); + + expect(TypePHP::getGenericType($catalog, 'K'))->toBe('string') + ->and(TypePHP::getGenericType($catalog, 'V'))->toBe(User::class) + ->and(TypePHP::getGenericTypes($catalog))->toBe([ + 'K' => 'string', + 'V' => User::class, + ]) + ->and(TypePHP::getGenericVariance($catalog, 'K'))->toBe('covariant') + ->and(TypePHP::getGenericVariance($catalog, 'V'))->toBe('invariant') + ->and(TypePHP::getGenericVariances($catalog))->toBe([ + 'K' => 'covariant', + 'V' => 'invariant', + ]) + ; + }); + + test('enforces parameter contracts against the correct positional templates K and V', function () { + /** @var MixedVarianceKeyValueCatalog $catalog */ + $catalog = new MixedVarianceKeyValueCatalog('dog_01', new Dog()); + + $catalog->setKey('dog_02'); + $catalog->setValue(new Dog()); + + expect(fn () => $catalog->setKey(12345)) + ->toThrow(TypeError::class, 'Argument $k (template K = string) must be of type string') + ; + + expect(fn () => $catalog->setValue(new Car())) + ->toThrow(TypeError::class, 'Argument $v (template V = ' . Dog::class . ') must be of type ' . Dog::class) + ; + }); + + test('enforces upper bound on K when first generic type argument violates array-key', function () { + expect(function () { + /** @var MixedVarianceKeyValueCatalog $badCatalog */ + $badCatalog = new MixedVarianceKeyValueCatalog('valid_key', 'val'); + })->toThrow( + TypeError::class, + 'Generic type argument ' . User::class . ' does not satisfy upper bound array-key of template K' + ); + + expect(function () { + new MixedVarianceKeyValueCatalog(new User(), 'val'); + })->toThrow( + TypeError::class, + 'Argument $k (template K) must be of type array-key, ' . User::class . ' given' + ); + }); + + test('enforces per-template variance rules (covariant K vs invariant V) on reassignment', function () { + /** @var MixedVarianceKeyValueCatalog $narrowKeyCatalog */ + $narrowKeyCatalog = new MixedVarianceKeyValueCatalog('dog_01', new Dog()); + + /** @var MixedVarianceKeyValueCatalog $broadKeyCatalog */ + $broadKeyCatalog = $narrowKeyCatalog; + expect($broadKeyCatalog)->toBe($narrowKeyCatalog); + + expect(function () use ($narrowKeyCatalog) { + /** @var MixedVarianceKeyValueCatalog $invalidValueVariance */ + $invalidValueVariance = $narrowKeyCatalog; + })->toThrow(TypeError::class); + }); + + test('preserves declaration order across 3 templates with contravariant, covariant, and invariant tags', function () { + /** @var MixedThreeVariancePipeline $pipeline */ + $pipeline = new MixedThreeVariancePipeline(new Dog(), new Dog(), 10); + + expect(TypePHP::getGenericTypes($pipeline))->toBe([ + 'TIn' => Dog::class, + 'TOut' => Dog::class, + 'TState' => 'positive-int', + ])->and(TypePHP::getGenericVariances($pipeline))->toBe([ + 'TIn' => 'contravariant', + 'TOut' => 'covariant', + 'TState' => 'invariant', + ]); + + // TIn is contravariant (Animal >: Dog), TOut is covariant (Dog <: Animal), TState is invariant (int === int) + /** @var MixedThreeVariancePipeline $source */ + $source = new MixedThreeVariancePipeline(new Dog(), new Dog(), 42); + + /** @var MixedThreeVariancePipeline $target */ + $target = $source; + expect($target)->toBe($source); + + // Violating contravariance on TIn: $pipeline has TIn = Dog, which is NOT a supertype of Animal or Cat + expect(function () use ($pipeline) { + /** @var MixedThreeVariancePipeline $badTarget */ + $badTarget = $pipeline; + })->toThrow(TypeError::class); + }); + + test('preserves declaration order when @phpstan-template refines an earlier template', function () { + /** @var RefinedMixedVarianceCatalog $catalog */ + $catalog = new RefinedMixedVarianceCatalog('id_1', new User()); + + expect(TypePHP::getGenericTypes($catalog))->toBe([ + 'K' => 'string', + 'V' => User::class, + ])->and(TypePHP::getGenericVariances($catalog))->toBe([ + 'K' => 'covariant', + 'V' => 'invariant', + ]); + + expect(function () { + /** @var RefinedMixedVarianceCatalog $bad */ + $bad = new RefinedMixedVarianceCatalog('id_1', 'val'); + })->toThrow( + TypeError::class, + 'Generic type argument ' . User::class . ' does not satisfy upper bound array-key of template K' + ); + }); +}); diff --git a/tests/TypeChecking/Scalars/IntMaskTest.php b/tests/TypeChecking/Scalars/IntMaskTest.php index 4d128886..2597db29 100644 --- a/tests/TypeChecking/Scalars/IntMaskTest.php +++ b/tests/TypeChecking/Scalars/IntMaskTest.php @@ -2,8 +2,64 @@ declare(strict_types=1); +use TypePHP\Exception\TypeError; use TypePHP\Tests\Fixtures\Types\BitmaskFlags; +enum TestPermissionBitmaskEnum: int +{ + case Read = 1; + case Write = 2; + case Delete = 4; +} + +/** + * 1. Wildcard on int-backed enum: Permission::* + * + * @param int-mask-of $mask + */ +function testEnumWildcardBitmaskParam(int $mask): int +{ + return $mask; +} + +/** + * 2. Prefix wildcard on int-backed enum: Permission::PERM_* + */ +enum TestPrefixedBitmaskEnum: int +{ + case PERM_VIEW = 1; + case PERM_EDIT = 2; + case OTHER_FLAG = 8; +} + +/** + * @param int-mask-of $mask + */ +function testEnumPrefixWildcardBitmaskParam(int $mask): int +{ + return $mask; +} + +/** + * 3. Specific enum cases in int-mask + * + * @param int-mask $mask + */ +function testSpecificEnumCasesMaskParam(int $mask): int +{ + return $mask; +} + +/** + * 4. Shorthand bare enum in int-mask-of + * + * @param int-mask-of $mask + */ +function testBareEnumBitmaskParam(int $mask): int +{ + return $mask; +} + /** * @param int-mask<1, 2, 4> $mask */ @@ -76,3 +132,71 @@ function testLiteralIntMask(int $mask): int }); }); }); + +describe('Enum int-mask-of and int-mask Validation', function () { + describe('int-mask-of', function () { + test('accepts 0 (empty bitmask)', function () { + expect(testEnumWildcardBitmaskParam(0))->toBe(0); + }); + + test('accepts single valid enum case values', function () { + expect(testEnumWildcardBitmaskParam(1))->toBe(1); // Read + expect(testEnumWildcardBitmaskParam(2))->toBe(2); // Write + expect(testEnumWildcardBitmaskParam(4))->toBe(4); // Delete + }); + + test('accepts combined valid bitmask values', function () { + expect(testEnumWildcardBitmaskParam(3))->toBe(3); // Read | Write (1 | 2) + expect(testEnumWildcardBitmaskParam(5))->toBe(5); // Read | Delete (1 | 4) + expect(testEnumWildcardBitmaskParam(7))->toBe(7); // Read | Write | Delete (1 | 2 | 4) + }); + + test('strictly throws TypeError when given an undefined bit (e.g. 8)', function () { + // This currently fails because 8 does not throw! + expect(fn () => testEnumWildcardBitmaskParam(8)) + ->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags') + ; + }); + + test('strictly throws TypeError when given combined bits containing an undefined flag (e.g. 1 | 8 = 9)', function () { + expect(fn () => testEnumWildcardBitmaskParam(9)) + ->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags') + ; + }); + }); + + describe('int-mask-of', function () { + test('only combines cases matching the prefix wildcard', function () { + expect(testEnumPrefixWildcardBitmaskParam(1))->toBe(1); + expect(testEnumPrefixWildcardBitmaskParam(3))->toBe(3); // PERM_VIEW | PERM_EDIT (1 | 2) + + // OTHER_FLAG (8) is in the enum, but does NOT match PERM_* + expect(fn () => testEnumPrefixWildcardBitmaskParam(8)) + ->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags') + ; + }); + }); + + describe('int-mask', function () { + test('accepts allowed enum cases and combinations', function () { + expect(testSpecificEnumCasesMaskParam(1))->toBe(1); // Read + expect(testSpecificEnumCasesMaskParam(2))->toBe(2); // Write + expect(testSpecificEnumCasesMaskParam(3))->toBe(3); // Read | Write + + expect(fn () => testSpecificEnumCasesMaskParam(4)) + ->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags') + ; + }); + }); + + describe('int-mask-of (Shorthand syntax without ::*)', function () { + test('accepts valid cases using bare enum shorthand', function () { + expect(testBareEnumBitmaskParam(1))->toBe(1); + expect(testBareEnumBitmaskParam(7))->toBe(7); + + expect(fn () => testBareEnumBitmaskParam(8)) + ->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags') + ; + }); + }); +}); diff --git a/tests/Unit/LineNumberPreservationTest.php b/tests/Unit/LineNumberPreservationTest.php index 82af75e0..619caf0f 100644 --- a/tests/Unit/LineNumberPreservationTest.php +++ b/tests/Unit/LineNumberPreservationTest.php @@ -353,4 +353,594 @@ public function __construct( ->and($origIndex)->toBe(16) ; }); + + test('preserves exact line numbers across preceding multi-line methods when a trailing class has a single-line empty {} method with @param', function () { + $source = <<<'PHP' +> $scores + * @return array + */ + public function totals(array $scores): array + { + return array_map('array_sum', $scores); + } + + /** @return array */ + public function broken(): array + { + return ['a' => 1, 'b' => 'two']; + } +} + +class Cart +{ + /** @param array $items */ + public function insert(array $items): void {} +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_three_classes_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(trim($transLines[11]))->toBe('public function charge(int $amount, array $options): string') + ->and(trim($transLines[13]))->toBe("return 'ok';") + ->and(trim($transLines[17]))->toBe('class Report') + ->and(trim($transLines[23]))->toBe('public function totals(array $scores): array') + ->and($transLines[25])->toContain('RuntimeTypeChecker::checkReturn') + ->and(trim($transLines[29]))->toBe('public function broken(): array') + ->and($transLines[31])->toContain('RuntimeTypeChecker::checkReturn') + ->and(trim($transLines[35]))->toBe('class Cart') + ->and($transLines[38])->toContain('public function insert(array $items): void {') + ; + }); + + test('distinguishes multi-line empty methods from single-line empty {} methods in the same file without line drift', function () { + $source = <<<'PHP' +toBe(\count($origLines)) + ->and(trim($transLines[9]))->toBe('public function multiLineEmpty(int $id): void') + ->and($transLines[16])->toContain('public function singleLineEmpty(string $name): void {') + ->and(trim($transLines[19]))->toBe('$targetLineAfterClass = true;') + ; + }); + + test('STRESS TEST 1: Large file with 7 classes mixing Allman, K&R, 1-line, and empty method styles preserves line numbers 1-to-1', function () { + $source = <<<'PHP' + + */ + public function streamRecords(): \Generator + { + yield 'first' => 10; + yield 'second' => 20; + } +} + +class ServiceSix +{ + /** @param positive-int $counter */ + public function emptyMultiLine(int $counter): void + { + } +} + +class ServiceSeven +{ + /** @param list $items */ + public function trailingEmpty(array $items): void {} +} + +$finalLandmarkLine = 'end_of_file_check'; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_mega_stress_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)); + + // Verify landmarks across the entire 90+ line file + $landmarks = [ + 'class ServiceOne', + 'public function allmanStyle(int $code): string', + 'class ServiceTwo', + 'public function sameLineBrace(string $label): void {', + 'interface ContractThree', + 'class ServiceFour implements ContractThree', + 'public function paramOutMethod(mixed &$id): void', + 'class ServiceFive', + 'public function streamRecords(): \Generator', + 'class ServiceSix', + 'public function emptyMultiLine(int $counter): void', + 'class ServiceSeven', + 'public function trailingEmpty(array $items): void {', + '$finalLandmarkLine = \'end_of_file_check\';', + ]; + + foreach ($landmarks as $landmark) { + $origIdx = null; + $transIdx = null; + + foreach ($origLines as $idx => $line) { + if (str_contains($line, $landmark)) { + $origIdx = $idx; + + break; + } + } + + foreach ($transLines as $idx => $line) { + if (str_contains($line, $landmark)) { + $transIdx = $idx; + + break; + } + } + + expect($transIdx)->not()->toBeNull("Failed finding transformed landmark: {$landmark}") + ->and($transIdx)->toBe($origIdx, "Line drift on landmark: {$landmark}") + ; + } + }); + + test('STRESS TEST 2: Preserves line numbers when standalone functions mix with inline @var, compound operators, and destructuring', function () { + $source = <<<'PHP' + $id, 'name' => $name] = $data; +} + +/** @param int $opt */ +function thirdEmptyWorker(int $opt): void {} + +$endOfFunctionStress = 100; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_functions_stress_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)); + + $origEnd = array_search('$endOfFunctionStress = 100;', array_map('trim', $origLines), true); + $transEnd = array_search('$endOfFunctionStress = 100;', array_map('trim', $transLines), true); + + expect($transEnd)->toBe($origEnd); + }); + + test('STRESS TEST 3: Constructor and methods with DocBlocks preserve exact line numbers', function () { + $source = <<<'PHP' + $c + */ + public function __construct(public int $a, public string $b, public array $c = []) + { + } + + /** + * @param positive-int $multiplier + * @return positive-int + */ + public function compute(int $multiplier): int + { + return $this->a * $multiplier; + } +} + +$endOfConstructorTest = true; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_ctor_multiline_trailing.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)); + + $landmarks = [ + 'public function __construct(public int $a, public string $b, public array $c = [])', + 'public function compute(int $multiplier): int', + '$this->a * $multiplier', + '$endOfConstructorTest = true;', + ]; + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + foreach ($landmarks as $landmark) { + $origLine = $findLineIndex($landmark, $origLines); + $transLine = $findLineIndex($landmark, $transLines); + + expect($transLine) + ->toBeGreaterThan(-1, "Landmark not found in transformed source: '{$landmark}'") + ->toBe($origLine, "Line drift detected on landmark: '{$landmark}'") + ; + } + }); + + test('STRESS TEST 4: Preserves exact line numbers when method contains inline @var, assignment, mutation, and return', function () { + $source = <<<'PHP' + $c + */ + public function __construct(public int $a, public string $b, public array $c = []) + { + } + + /** + * @param positive-int $multiplier + * @return positive-int + */ + public function compute(int $multiplier): int + { + /** @var positive-int $intermediate */ + $intermediate = $this->a * $multiplier; + $intermediate += 10; + + return $intermediate; + } +} + +$endOfMultiStatementTest = true; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_method_with_var_and_return.php'); + + $origLines = explode("\n", str_replace("\r\n", "\n", $source)); + $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); + + expect(\count($transLines))->toBe(\count($origLines)); + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + $landmarks = [ + 'class MultiParamClassWithVar', + 'public function __construct(public int $a, public string $b, public array $c = [])', + 'public function compute(int $multiplier): int', + '/** @var positive-int $intermediate */', + '$this->a * $multiplier', + '$endOfMultiStatementTest = true;', + ]; + + foreach ($landmarks as $landmark) { + $origLine = $findLineIndex($landmark, $origLines); + $transLine = $findLineIndex($landmark, $transLines); + + expect($transLine) + ->toBeGreaterThan(-1, "Landmark not found in transformed source: '{$landmark}'") + ->toBe($origLine, "Line drift detected on landmark: '{$landmark}'") + ; + } + + $origVarAssignLine = $findLineIndex('$this->a * $multiplier', $origLines); + $transVarAssignLine = $findLineIndex('$this->a * $multiplier', $transLines); + expect($transVarAssignLine)->toBe($origVarAssignLine, 'Line drift detected on variable assignment') + ->and($transLines[$transVarAssignLine])->toContain('RuntimeTypeChecker::checkVariable') + ; + $origMutationLine = $findLineIndex('$intermediate += 10;', $origLines); + $transMutationLine = $findLineIndex('$intermediate + 10', $transLines); + expect($transMutationLine)->toBe($origMutationLine, 'Line drift detected on compound assignment mutation') + ->and($transLines[$transMutationLine])->toContain('RuntimeTypeChecker::checkVariable') + ; + + $origReturnLine = $findLineIndex('return $intermediate;', $origLines); + $transReturnLine = $findLineIndex('RuntimeTypeChecker::checkReturn', $transLines); + expect($transReturnLine)->toBe($origReturnLine, 'Line drift detected on return statement check') + ->and($transLines[$transReturnLine])->toContain('$intermediate') + ; + }); + + test('STRESS TEST 5: Multi-line parameters with compact trailing ") {}" preserves line numbers', function () { + $source = <<<'PHP' + $c + */ + public function __construct( + public int $a, + public string $b, + public array $c = [] + ) {} + + /** + * @param positive-int $multiplier + * @return positive-int + */ + public function compute(int $multiplier): int + { + return $this->a * $multiplier; + } +} + +$endOfCompactConstructorTest = true; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_compact_trailing_ctor.php'); + + $origLines = explode("\n", str_replace("\r\n", "\n", $source)); + $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); + + expect(\count($transLines))->toBe(\count($origLines)); + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + $landmarks = [ + 'class CompactTrailingConstructor', + 'public function compute(int $multiplier): int', + '$this->a * $multiplier', + '$endOfCompactConstructorTest = true;', + ]; + + foreach ($landmarks as $landmark) { + $origLine = $findLineIndex($landmark, $origLines); + $transLine = $findLineIndex($landmark, $transLines); + + expect($transLine) + ->toBeGreaterThan(-1, "Landmark not found in transformed source: '{$landmark}'") + ->toBe($origLine, "Line drift detected on landmark: '{$landmark}'") + ; + } + }); + + test('STRESS TEST 6: Multi-line parameters with compact trailing ") {}" and method containing inline @var, mutation, and return', function () { + $source = <<<'PHP' + $c + */ + public function __construct( + public int $a, + public string $b, + public array $c = [] + ) {} + + /** + * @param positive-int $multiplier + * @return positive-int + */ + public function compute(int $multiplier): int + { + /** @var positive-int $intermediate */ + $intermediate = $this->a * $multiplier; + $intermediate += 10; + + return $intermediate; + } +} + +$endOfCompactWithVarTest = true; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_compact_ctor_with_var_and_return.php'); + + $origLines = explode("\n", str_replace("\r\n", "\n", $source)); + $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); + + expect(\count($transLines))->toBe(\count($origLines)); + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + $landmarks = [ + 'class CompactTrailingConstructorWithVar', + 'public function __construct(', + 'public function compute(int $multiplier): int', + '/** @var positive-int $intermediate */', + '$this->a * $multiplier', + '$endOfCompactWithVarTest = true;', + ]; + + foreach ($landmarks as $landmark) { + $origLine = $findLineIndex($landmark, $origLines); + $transLine = $findLineIndex($landmark, $transLines); + + expect($transLine) + ->toBeGreaterThan(-1, "Landmark not found in transformed source: '{$landmark}'") + ->toBe($origLine, "Line drift detected on landmark: '{$landmark}'") + ; + } + + $origVarAssignLine = $findLineIndex('$this->a * $multiplier', $origLines); + $transVarAssignLine = $findLineIndex('$this->a * $multiplier', $transLines); + expect($transVarAssignLine)->toBe($origVarAssignLine, 'Line drift detected on variable assignment') + ->and($transLines[$transVarAssignLine])->toContain('RuntimeTypeChecker::checkVariable') + ; + + $origMutationLine = $findLineIndex('$intermediate += 10;', $origLines); + $transMutationLine = $findLineIndex('$intermediate + 10', $transLines); + expect($transMutationLine)->toBe($origMutationLine, 'Line drift detected on compound assignment mutation') + ->and($transLines[$transMutationLine])->toContain('RuntimeTypeChecker::checkVariable') + ; + + $origReturnLine = $findLineIndex('return $intermediate;', $origLines); + $transReturnLine = $findLineIndex('RuntimeTypeChecker::checkReturn', $transLines); + expect($transReturnLine)->toBe($origReturnLine, 'Line drift detected on return statement check') + ->and($transLines[$transReturnLine])->toContain('$intermediate') + ; + }); }); diff --git a/tests/Unit/UnannotatedMethodReturnInjectionTest.php b/tests/Unit/UnannotatedMethodReturnInjectionTest.php index 86f0bff4..16df2c33 100644 --- a/tests/Unit/UnannotatedMethodReturnInjectionTest.php +++ b/tests/Unit/UnannotatedMethodReturnInjectionTest.php @@ -5,6 +5,7 @@ namespace TypePHP\Tests\Internal\Ast; use TypePHP\Internal\Io\StreamWrapper; +use TypePHP\Internal\Util\Config; describe('Unannotated Method Return Check Injection (TDD)', function () { describe('1. Standalone Classes Without Inheritance (Zero Injections)', function () { @@ -31,6 +32,28 @@ public function bark() ; }); + test('does NOT inject checkReturn into non-final standalone class method with no docblock and existing return', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain("return 'Arff';") + ; + }); + test('does NOT inject checkReturn into final standalone class method with no docblock and existing return', function () { $source = <<<'PHP' false]); + }); + + afterEach(function () { + Config::reset(); + }); + test('injects checkReturn when standalone method explicitly declares @return docblock', function () { $source = <<<'PHP'