diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 90579437..bc75fb6a 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -10,7 +10,9 @@ use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Parser\TokenIterator; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Docblock\DocblockExtractor; @@ -82,6 +84,11 @@ final class ContractVisitor extends NodeVisitorAbstract */ private array $byRefStack = []; + /** + * @var array> + */ + private array $localClassTemplates = []; + public function __construct(private string $currentFile = '') { $this->scopeManager = new ScopeManager(); @@ -208,6 +215,23 @@ public function leaveNode(Node $node): Node|array|null { $this->trackDeclarationExit($node); + if ($node instanceof Node\Stmt\Class_ && $node->name !== null) { + $className = $this->resolveQualifiedName($node->name); + if ($className !== null) { + $constChecks = $this->collectUnprovenClassConstantChecks($node, $className); + if ($constChecks !== []) { + return [$node, ...$constChecks]; + } + } + } + + if ($node instanceof Node\Stmt\Const_) { + $globalConstChecks = $this->collectUnprovenGlobalConstantChecks($node); + if ($globalConstChecks !== []) { + return [$node, ...$globalConstChecks]; + } + } + if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Expr\Closure) { array_pop($this->byRefStack); } @@ -278,6 +302,251 @@ public function leaveNode(Node $node): Node|array|null return null; } + /** + * @return list + */ + private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, string $className): array + { + $injectedStmts = []; + + foreach ($node->stmts as $stmt) { + if (! ($stmt instanceof Node\Stmt\ClassConst)) { + continue; + } + + $doc = $stmt->getDocComment(); + if ($doc === null || ! str_contains($doc->getText(), '@var')) { + continue; + } + + if (Config::isRespectIgnoreTagsEnabled() && str_contains($doc->getText(), '@typephp-ignore')) { + continue; + } + + $varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText()); + if ($varTag === null) { + continue; + } + + $typeString = $varTag[0]; + + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + $typeNode = $typeParser->parse($tokens); + + foreach ($stmt->consts as $const) { + $constName = $const->name->toString(); + $fullTarget = $className . '::' . $constName; + + if ($const->value instanceof Node\Expr\Closure && $typeNode instanceof CallableTypeNode) { + $this->instrumentConstantClosure($const->value, $typeNode, $fullTarget); + + continue; + } + + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { + continue; + } + + $classConstFetch = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName); + + $checkCall = NodeBuilder::createConstantCheckCall( + $fullTarget, + $classConstFetch, + $typeString, + $const->getStartLine() + ); + + $checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine())); + $checkStmt->setAttribute('typephp_injected', true); + $injectedStmts[] = $checkStmt; + } + } catch (\Throwable) { + } + } + + return $injectedStmts; + } + + /** + * @return list + */ + private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): array + { + $doc = $node->getDocComment(); + if ($doc === null || ! str_contains($doc->getText(), '@var')) { + return []; + } + + if (Config::isRespectIgnoreTagsEnabled() && str_contains($doc->getText(), '@typephp-ignore')) { + return []; + } + + $varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText()); + if ($varTag === null) { + return []; + } + + $typeString = $varTag[0]; + $injectedStmts = []; + + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + $typeNode = $typeParser->parse($tokens); + + foreach ($node->consts as $const) { + $constName = $const->name->toString(); + $qualifiedConstName = $this->currentNamespace !== '' + ? $this->currentNamespace . '\\' . $constName + : $constName; + + if ($const->value instanceof Node\Expr\Closure && $typeNode instanceof CallableTypeNode) { + $this->instrumentConstantClosure($const->value, $typeNode, $qualifiedConstName); + + continue; + } + + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { + continue; + } + + $constFetch = new Node\Expr\ConstFetch(new Node\Name\FullyQualified($qualifiedConstName)); + + $checkCall = NodeBuilder::createConstantCheckCall( + $qualifiedConstName, + $constFetch, + $typeString, + $const->getStartLine() + ); + + $checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine())); + $checkStmt->setAttribute('typephp_injected', true); + $injectedStmts[] = $checkStmt; + } + } catch (\Throwable) { + } + + return $injectedStmts; + } + + private function instrumentConstantClosure( + Node\Expr\Closure $closure, + CallableTypeNode $callableTypeNode, + string $caller + ): void { + $paramChecks = []; + $callableParams = $callableTypeNode->parameters; + $paramsByName = []; + + foreach ($callableParams as $idx => $pNode) { + $pName = $pNode->parameterName !== null ? ltrim($pNode->parameterName, '$') : null; + if ($pName !== null) { + $paramsByName[$pName] = $pNode; + } elseif (isset($closure->params[$idx])) { + $closureParam = $closure->params[$idx]; + if ($closureParam->var instanceof Node\Expr\Variable && \is_string($closureParam->var->name)) { + $paramsByName[$closureParam->var->name] = $pNode; + } + } + } + + foreach ($closure->params as $param) { + if ($param->var instanceof Node\Expr\Variable && \is_string($param->var->name)) { + $pName = $param->var->name; + $pContract = $paramsByName[$pName] ?? null; + + if ($pContract !== null) { + $typeStr = (string) $pContract->type; + if (strtolower(trim($typeStr)) === 'mixed') { + continue; + } + + $line = $param->getStartLine(); + $checkCall = NodeBuilder::createConstantClosureParamCheckCall( + $caller, + $pName, + new Node\Expr\Variable($pName), + $typeStr, + $line + ); + $checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $line)); + $checkStmt->setAttribute('typephp_injected', true); + $paramChecks[] = $checkStmt; + } + } + } + + if ($paramChecks !== []) { + $closure->stmts = [...$paramChecks, ...$closure->stmts]; + } + + $returnTypeNode = $callableTypeNode->returnType; + $returnTypeStr = (string) $returnTypeNode; + $isReturnUnconstrained = \in_array(strtolower(trim($returnTypeStr)), ['void', 'mixed'], true); + + if (! $isReturnUnconstrained) { + $traverser = new NodeTraverser(); + $traverser->addVisitor(new class ( + $caller, + $returnTypeNode, + $returnTypeStr, + $this->currentFile + ) extends NodeVisitorAbstract { + public function __construct( + private string $caller, + private TypeNode $returnTypeNode, + private string $returnTypeStr, + private string $currentFile + ) { + } + + public function enterNode(Node $n): int|Node|null + { + if ( + $n instanceof Node\Expr\Closure + || $n instanceof Node\Expr\ArrowFunction + || $n instanceof Node\Stmt\Function_ + || $n instanceof Node\Stmt\ClassMethod + || $n instanceof Node\Stmt\Class_ + ) { + return NodeTraverser::DONT_TRAVERSE_CHILDREN; + } + + if ($n instanceof Node\Stmt\Return_) { + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + + if ( + Config::isEliminateStaticallyProvenChecksEnabled() + && StaticTypeEvaluator::satisfies($exprToWrap, $this->returnTypeNode, $this->currentFile) + ) { + return null; + } + + $line = $n->getStartLine(); + $checkCall = NodeBuilder::createConstantClosureReturnCheckCall( + $this->caller, + $exprToWrap, + $this->returnTypeStr, + $line + ); + + $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $line); + + return $n; + } + + return null; + } + }); + + /** @var array $newStmts */ + $newStmts = $traverser->traverse($closure->stmts); + $closure->stmts = $newStmts; + } + } + private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stmt\Expression { $targetVarExpr = null; @@ -616,7 +885,6 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ $hasPropertyWithDoc = false; $isReadonly = false; $isFinal = false; - $hasTemplates = false; $doc = $node->getDocComment(); if ($doc === null && $typeName !== null && StubManager::hasClassStub($typeName)) { @@ -626,6 +894,30 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } + $templates = []; + if ($doc !== null && ( + str_contains($doc->getText(), '@template') + || str_contains($doc->getText(), '@phpstan-template') + || str_contains($doc->getText(), '@psalm-template') + )) { + try { + $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); + $templates = DocblockExtractor::extractTemplates($phpDocNode); + } catch (\Throwable) { + } + } + $hasTemplates = $templates !== []; + + if ($hasTemplates) { + $templateNames = array_keys($templates); + if ($typeName !== null) { + $this->localClassTemplates[$typeName] = $templateNames; + } + if ($shortName !== null) { + $this->localClassTemplates[$shortName] = $templateNames; + } + } + if ($node instanceof Node\Stmt\Class_) { $hasExtends = $node->extends !== null; $hasImplements = $node->implements !== []; @@ -639,8 +931,10 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } elseif ($stmt instanceof Node\Stmt\Property && $stmt->getDocComment() !== null) { $hasPropertyWithDoc = true; } elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') { + $ctorDoc = $stmt->getDocComment(); + $hasParamInCtor = $ctorDoc !== null && str_contains($ctorDoc->getText(), '@param'); foreach ($stmt->params as $param) { - if ($param->isPromoted() && $param->getDocComment() !== null) { + if ($param->isPromoted() && ($param->getDocComment() !== null || $hasParamInCtor)) { $hasPropertyWithDoc = true; break; @@ -649,11 +943,6 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } - $hasTemplates = $doc !== null && ( - str_contains($doc->getText(), '@template') - || str_contains($doc->getText(), '@phpstan-template') - || str_contains($doc->getText(), '@psalm-template') - ); $hasClassDoc = $doc !== null && ( $hasTemplates || str_contains($doc->getText(), '@phpstan-') @@ -667,12 +956,6 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } elseif ($node instanceof Node\Stmt\Enum_) { $hasRealInheritance = $node->implements !== []; $hasInheritance = $hasRealInheritance; - } else { - $hasTemplates = $doc !== null && ( - str_contains($doc->getText(), '@template') - || str_contains($doc->getText(), '@phpstan-template') - || str_contains($doc->getText(), '@psalm-template') - ); } if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) { @@ -692,16 +975,31 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } } elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') { + $methodDoc = $stmt->getDocComment(); + $methodParamTags = null; + if ($methodDoc !== null && str_contains($methodDoc->getText(), '@param')) { + try { + $methodPhpDoc = DocblockExtractor::parseDocString($methodDoc->getText()); + $methodParamTags = DocblockExtractor::getParamTags($methodPhpDoc); + } catch (\Throwable) { + } + } + 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; - } + $paramName = $p->var->name; + $pType = null; + $paramDoc = $p->getDocComment(); + if ($paramDoc !== null) { + $pType = DocblockExtractor::extractTypeFromPropertyDoc($paramDoc->getText(), $paramName); + } + if ($pType === null && $methodParamTags !== null && isset($methodParamTags[$paramName])) { + $pType = $methodParamTags[$paramName]->type; + } + if ($pType !== null) { + $this->localClassPropertyTypes[$typeName][$paramName] = (string) $pType; + if ($shortName !== null) { + $this->localClassPropertyTypes[$shortName][$paramName] = (string) $pType; } } } @@ -1136,7 +1434,13 @@ private function deduceMemberChainType(string $rootType, array $chain): ?string if (isset($this->localClassPropertyTypes[$deducedType][$propName])) { $deducedType = $this->localClassPropertyTypes[$deducedType][$propName]; } else { - $deducedType = TypeDeducer::deducePropertyType($deducedType, $propName); + $deducedType = TypeDeducer::deducePropertyType( + $deducedType, + $propName, + $this->localClassPropertyTypes, + $this->localClassTemplates, + $this->currentFile + ); } if ($deducedType === null) { return null; diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index a7fdad3a..22f06ce9 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -115,7 +115,7 @@ public static function inject( $hasSelfOut = $isClassMethod && ! $node->isStatic() && ($hasSelfOutDoc || ($hasClassTemplates && $hasRealInheritance)); $hasParam = ($isMagicGet || $isMagicCall) || ($paramCount > 0 && ( - str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc) && str_contains($docText, '$')) + str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc || $hasParamOutDoc) && str_contains($docText, '$')) )) || self::hasParamContracts( $docText, $isClassMethod, @@ -552,8 +552,15 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b * * @return array */ - public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr $thisArg): array - { + public static function buildParamOutCheckStmts( + array $byRefParamNames, + Node\Expr $thisArg, + bool $needsReturnVars = false + ): array { + $varsArg = $needsReturnVars + ? new Node\Expr\Variable('_typephpArgs') + : new Node\Expr\Array_(); + $stmts = []; foreach ($byRefParamNames as $pName) { $checkCall = new Node\Expr\FuncCall( @@ -563,6 +570,7 @@ public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr new Node\Arg(new Node\Scalar\String_($pName)), new Node\Arg(new Node\Expr\Variable($pName)), new Node\Arg($thisArg), + new Node\Arg($varsArg), ] ); @@ -798,8 +806,13 @@ public static function buildParamOutGuardExpr( array $byRefParamNames, Node\Expr $innerExpr, Node\Expr $thisArg, - ?int $line = null + ?int $line = null, + bool $needsReturnVars = false ): Node\Expr { + $varsArg = $needsReturnVars + ? new Node\Expr\Variable('_typephpArgs') + : new Node\Expr\Array_(); + $expr = $innerExpr; foreach (array_reverse($byRefParamNames) as $pName) { $checkCall = new Node\Expr\FuncCall( @@ -809,6 +822,7 @@ public static function buildParamOutGuardExpr( new Node\Arg(new Node\Scalar\String_($pName)), new Node\Arg(new Node\Expr\Variable($pName)), new Node\Arg($thisArg), + new Node\Arg($varsArg), ] ); @@ -833,7 +847,8 @@ public static function buildWrappedYieldNode( Node\Expr $thisArg, bool $wrapYield = true, bool $wrapSend = true, - array $byRefParams = [] + array $byRefParams = [], + bool $needsReturnVars = false ): Node\Expr { if ($wrapYield) { $checkYieldCall = new Node\Expr\FuncCall( @@ -858,7 +873,7 @@ public static function buildWrappedYieldNode( if ($byRefParams !== []) { $valExpr = $n->value ?? new Node\Expr\ConstFetch(new Node\Name('null')); - $n->value = self::buildParamOutGuardExpr($byRefParams, $valExpr, $thisArg, $n->getStartLine()); + $n->value = self::buildParamOutGuardExpr($byRefParams, $valExpr, $thisArg, $n->getStartLine(), $needsReturnVars); } if (! $wrapSend) { @@ -991,7 +1006,14 @@ public function enterNode(Node $n): int|Node|array|null return null; } - return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend, $this->byRefParams); + return FunctionContractInjector::buildWrappedYieldNode( + $n, + $this->thisArg, + $wrapYield, + $wrapSend, + $this->byRefParams, + $this->needsReturnVars + ); } if ($n instanceof Node\Expr\YieldFrom) { @@ -1025,7 +1047,8 @@ public function enterNode(Node $n): int|Node|array|null $this->byRefParams, $n->expr, $this->thisArg, - $n->getStartLine() + $n->getStartLine(), + $this->needsReturnVars ); } @@ -1044,7 +1067,7 @@ public function enterNode(Node $n): int|Node|array|null } $paramOutStmts = $this->byRefParams !== [] - ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg) + ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg, $this->needsReturnVars) : []; if ($paramOutStmts !== []) { @@ -1095,7 +1118,7 @@ public function enterNode(Node $n): int|Node|array|null } $paramOutStmts = $byRefParams !== [] - ? self::buildParamOutCheckStmts($byRefParams, $thisArg) + ? self::buildParamOutCheckStmts($byRefParams, $thisArg, $needsReturnVars) : []; if ($paramOutStmts !== []) { @@ -1224,7 +1247,7 @@ public function enterNode(Node $n): int|array|null } $paramOutStmts = $this->byRefParams !== [] - ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg) + ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg, $this->needsReturnVars) : []; if ($paramOutStmts !== []) { @@ -1286,7 +1309,7 @@ public function enterNode(Node $n): int|array|null } $paramOutStmts = $byRefParams !== [] - ? self::buildParamOutCheckStmts($byRefParams, $thisArg) + ? self::buildParamOutCheckStmts($byRefParams, $thisArg, $needsReturnVars) : []; if ($paramOutStmts !== []) { diff --git a/src/Internal/Ast/NodeBuilder.php b/src/Internal/Ast/NodeBuilder.php index 07a97974..10a4ba00 100644 --- a/src/Internal/Ast/NodeBuilder.php +++ b/src/Internal/Ast/NodeBuilder.php @@ -140,4 +140,60 @@ public static function createPropertyMemberAssignCheckCall( ] ); } + + public static function createConstantCheckCall( + string $constantName, + Node\Expr $valueExpr, + string $typeString, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstant'), + [ + new Node\Arg(new Node\Scalar\String_($constantName)), + new Node\Arg($valueExpr), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } + + public static function createConstantClosureParamCheckCall( + string $caller, + string $paramName, + Node\Expr $paramVar, + string $typeString, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureParam'), + [ + new Node\Arg(new Node\Scalar\String_($caller)), + new Node\Arg(new Node\Scalar\String_($paramName)), + new Node\Arg($paramVar), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } + + public static function createConstantClosureReturnCheckCall( + string $caller, + Node\Expr $valueExpr, + string $typeString, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureReturn'), + [ + new Node\Arg(new Node\Scalar\String_($caller)), + new Node\Arg($valueExpr), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } } diff --git a/src/Internal/Ast/TypeDeducer.php b/src/Internal/Ast/TypeDeducer.php index 6e5f61ce..ff41ed8d 100644 --- a/src/Internal/Ast/TypeDeducer.php +++ b/src/Internal/Ast/TypeDeducer.php @@ -20,6 +20,8 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Generics\TemplateSubstitutor; +use TypePHP\Internal\Resolver\SpecialTypeResolver; /** * Deduces element, key, and indexed member types from container type strings. @@ -173,9 +175,17 @@ public static function deduceDimType(string $containerTypeString, ?Expr $dimExpr /** * Deduces the property type of an object shape or class property access ($obj->prop). + * + * @param array> $localPropertyTypes + * @param array> $localClassTemplates */ - public static function deducePropertyType(string $containerTypeString, string $propName): ?string - { + public static function deducePropertyType( + string $containerTypeString, + string $propName, + array $localPropertyTypes = [], + array $localClassTemplates = [], + string $currentFile = '' + ): ?string { $typeNode = self::parseTypeString($containerTypeString); if ($typeNode === null) { return null; @@ -185,6 +195,10 @@ public static function deducePropertyType(string $containerTypeString, string $p $typeNode = $typeNode->type; } + if ($currentFile !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile); + } + if ($typeNode instanceof ObjectShapeNode) { foreach ($typeNode->items as $item) { $name = $item->keyName instanceof IdentifierTypeNode @@ -199,6 +213,15 @@ public static function deducePropertyType(string $containerTypeString, string $p if ($typeNode instanceof IdentifierTypeNode) { $className = $typeNode->name; + $shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className; + + if (isset($localPropertyTypes[$className][$propName])) { + return $localPropertyTypes[$className][$propName]; + } + if (isset($localPropertyTypes[$shortName][$propName])) { + return $localPropertyTypes[$shortName][$propName]; + } + if ( class_exists($className, false) || class_exists($className) || interface_exists($className, false) || interface_exists($className) @@ -211,6 +234,70 @@ class_exists($className, false) || class_exists($className) } } + if ($typeNode instanceof GenericTypeNode) { + $baseType = $typeNode->type; + $className = $baseType instanceof IdentifierTypeNode ? $baseType->name : (string) $baseType; + $shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className; + + $rawPropType = null; + $templateNames = null; + + if (isset($localPropertyTypes[$className][$propName])) { + $rawPropType = $localPropertyTypes[$className][$propName]; + $templateNames = $localClassTemplates[$className] ?? ($localClassTemplates[$shortName] ?? null); + } elseif (isset($localPropertyTypes[$shortName][$propName])) { + $rawPropType = $localPropertyTypes[$shortName][$propName]; + $templateNames = $localClassTemplates[$shortName] ?? ($localClassTemplates[$className] ?? null); + } + + if ($rawPropType === null) { + if ( + class_exists($className, false) || class_exists($className) + || interface_exists($className, false) || interface_exists($className) + || trait_exists($className, false) || trait_exists($className) + ) { + $parsedProp = DocblockParser::parseProperty($className, $propName); + if ($parsedProp !== null) { + $rawPropType = $parsedProp; + } + $templates = DocblockParser::parseClassTemplates($className); + if ($templates !== []) { + $templateNames = array_keys($templates); + } + } + } + + if ($rawPropType !== null) { + $propTypeNode = \is_string($rawPropType) ? self::parseTypeString($rawPropType) : $rawPropType; + if ($propTypeNode === null) { + return \is_string($rawPropType) ? $rawPropType : (string) $rawPropType; + } + + if ($templateNames !== null && $templateNames !== []) { + $bindings = []; + if (\count($templateNames) === 2 && \count($typeNode->genericTypes) === 1) { + $firstLower = strtolower($templateNames[0]); + if ($firstLower === 'k' || $firstLower === 'tkey' || $firstLower === 'key') { + $bindings[$templateNames[0]] = new IdentifierTypeNode('array-key'); + $bindings[$templateNames[1]] = $typeNode->genericTypes[0]; + } + } else { + foreach ($templateNames as $idx => $tName) { + if (isset($typeNode->genericTypes[$idx])) { + $bindings[$tName] = $typeNode->genericTypes[$idx]; + } + } + } + + if ($bindings !== []) { + $propTypeNode = TemplateSubstitutor::substitute($propTypeNode, $bindings); + } + } + + return (string) $propTypeNode; + } + } + return null; } diff --git a/src/Internal/Checker/ConditionalChecker.php b/src/Internal/Checker/ConditionalChecker.php index e09f5b0b..ebc776e3 100644 --- a/src/Internal/Checker/ConditionalChecker.php +++ b/src/Internal/Checker/ConditionalChecker.php @@ -293,8 +293,17 @@ public static function resolveTemplateConditional( string $function = '' ): TypeNode { $subjectTypeNode = $node->subjectType; - if ($subjectTypeNode instanceof IdentifierTypeNode && isset($boundTemplates[$subjectTypeNode->name])) { - $subjectTypeNode = $boundTemplates[$subjectTypeNode->name]; + if ($subjectTypeNode instanceof IdentifierTypeNode) { + if (isset($boundTemplates[$subjectTypeNode->name])) { + $subjectTypeNode = $boundTemplates[$subjectTypeNode->name]; + } elseif ($function !== '') { + $contract = DocblockParser::parse($function); + $allTemplates = $contract['allTemplates'] ?? [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + if (isset($allTemplates[$subjectTypeNode->name])) { + $templateTag = $allTemplates[$subjectTypeNode->name]; + $subjectTypeNode = $templateTag->default ?? $templateTag->bound ?? $subjectTypeNode; + } + } } $isTargetMatch = TemplateManager::checkVariance($subjectTypeNode, $node->targetType, GenericTypeNode::VARIANCE_COVARIANT); diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 33e1b6c2..9f7dc6f0 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -57,7 +57,7 @@ public static function checkSend( return null; } - $types = self::resolveYieldAndSendTypes($function, $thisOrClass); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); if ($types === null) { return $sendValue; } @@ -82,7 +82,7 @@ public static function checkYield( TypeValidatorRegistry $registry, object|string|null $thisOrClass = null ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); if ($types === null) { return $value; } @@ -115,7 +115,7 @@ public static function checkReturn( TypeValidatorRegistry $registry, object|string|null $thisOrClass = null ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); if ($types === null) { return $value; } @@ -143,8 +143,11 @@ public static function checkReturn( * * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode}|null */ - private static function resolveYieldAndSendTypes(string $function, object|string|null $thisOrClass): ?array - { + private static function resolveYieldAndSendTypes( + string $function, + object|string|null $thisOrClass, + ?TypeValidatorRegistry $registry = null + ): ?array { if (isset(self::$noContractCache[$function])) { return null; } @@ -166,10 +169,11 @@ private static function resolveYieldAndSendTypes(string $function, object|string $aliases = $contract['aliases'] ?? []; $hasGenerics = \count($allTemplates) > 0; $hasAliases = \count($aliases) > 0; + $hasConditionals = ConditionalChecker::containsConditional($returnTypeNode); $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; // Static / non-generic generator: cache permanently for this function - if (! $hasGenerics && ! $hasAliases && $thisObj === null) { + if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && $thisObj === null) { $resolvedNode = SpecialTypeResolver::resolve($returnTypeNode, $function, null); return self::$staticYieldTypeCache[$function] = self::extractYieldTypes($resolvedNode); @@ -180,7 +184,7 @@ private static function resolveYieldAndSendTypes(string $function, object|string $sig = null; $boundCount = \count($boundTemplates); - if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && $thisObj === null) { + if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && ! $hasConditionals && $thisObj === null) { if ($boundCount === 1) { $first = reset($boundTemplates); $sig = $first instanceof IdentifierTypeNode ? $first->name : (string) $first; @@ -200,11 +204,19 @@ private static function resolveYieldAndSendTypes(string $function, object|string $returnTypeNode = $aliases[$returnTypeNode->name]; } + if ($hasConditionals && $registry !== null) { + $returnTypeNode = ConditionalChecker::resolve($returnTypeNode, [], $boundTemplates, $registry, $function); + } + if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) { $returnTypeNode = TemplateSubstitutor::substitute($returnTypeNode, $boundTemplates, $allTemplates); $returnTypeNode = SpecialTypeResolver::resolve($returnTypeNode, $function, $thisObj); } + if (ConditionalChecker::containsConditional($returnTypeNode) && $registry !== null) { + $returnTypeNode = ConditionalChecker::resolve($returnTypeNode, [], $boundTemplates, $registry, $function); + } + $types = self::extractYieldTypes($returnTypeNode); if ($sig !== null) { diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 5b719f9c..62437a39 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -238,7 +238,9 @@ public static function validateCollectionElementMutation( string $typeString, string $varName, string $file, - TypeValidatorRegistry $registry + TypeValidatorRegistry $registry, + ?string $caller = null, + mixed $thisOrClass = null ): ?ErrorMessage { if (\count($path) !== 1 || $path[0][0] !== 'dim') { return null; @@ -246,12 +248,16 @@ public static function validateCollectionElementMutation( try { $normalized = DocblockNormalizer::normalize($typeString); - [$typeNode] = self::parseTypeString($normalized); + [$typeNode, $needsContext] = self::parseTypeString($normalized); if ($file !== '') { $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); } + if ($needsContext && $caller !== null) { + $typeNode = self::resolveCallerContext($typeNode, $caller, $thisOrClass); + } + $key = $path[0][1]; $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 85b416d9..2374a28f 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -54,7 +54,9 @@ public static function check( $typeString, $varName, $file, - $registry + $registry, + $caller, + $thisOrClass ); if ($directErr instanceof ErrorMessage) { diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index c0e8d764..63362fdd 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -312,6 +312,10 @@ private static function prepareGenericBindings( $targetClass = \is_string($thisOrClass) && $thisOrClass !== '' ? $thisOrClass : $declaringClass; TemplateManager::getClassInheritedBindings($targetClass); } + + if ($thisObj !== null && ! str_ends_with(strtolower($effectiveFunction), '::__construct')) { + TemplateManager::applyClassTemplateDefaults($thisObj, $classTemplates); + } } } @@ -417,7 +421,7 @@ private static function validateAllParameters( } } - if (\count($allTemplates) > 1) { + if (\count($allTemplates) > 0) { return self::validateCrossReferencedTemplateBounds( $contractTypes, $baseTypes, @@ -651,7 +655,7 @@ private static function extractCallableNodes(array $types): array } /** - * Re-validates template upper bounds that reference other sibling templates once all parameters have been bound. + * Re-validates template upper bounds that reference templates (F-bounds and cross-template bounds) once all parameters have been bound. * * @param array $contractTypes * @param array $baseTypes @@ -680,17 +684,13 @@ private static function validateCrossReferencedTemplateBounds( continue; } - $otherTemplates = $allTemplates; - unset($otherTemplates[$tName]); - - if (! DocblockParser::typeReferencesTemplate($templateNode->bound, $otherTemplates)) { + if (! DocblockParser::typeReferencesTemplate($templateNode->bound, $allTemplates)) { continue; } $substitutedBound = TemplateSubstitutor::substitute($templateNode->bound, $finalBoundTemplates); $resolvedBound = SpecialTypeResolver::resolve($substitutedBound, $effectiveFunction, $thisObj); - $matchedParam = false; foreach ($contractTypes as $paramName => $_) { if (! isset($vars[$paramName]) && ! \array_key_exists($paramName, $vars)) { continue; @@ -701,7 +701,6 @@ private static function validateCrossReferencedTemplateBounds( $isSensitive = $sensitiveParams[$paramName] ?? false; if ($baseType instanceof GenericTypeNode && self::isClassStringTemplate($baseType, [$tName => $templateNode])) { - $matchedParam = true; if (\is_string($val) && ! self::checkClassStringSatisfiesBound($val, $resolvedBound)) { $redact = $isSensitive || Config::isRedactValuesEnabled(); $boundDisplay = (string) $resolvedBound; @@ -710,7 +709,6 @@ private static function validateCrossReferencedTemplateBounds( return ErrorFactory::createError($effectiveFunction . '(): Argument $' . $paramName . ' (class-string<' . $tName . '>) must be a class-string of ' . $boundDisplay . ', ' . $displayVal); } } elseif (self::getTemplateName($baseType, [$tName => $templateNode]) === $tName) { - $matchedParam = true; $sampleVal = ($baseType instanceof ArrayTypeNode && \is_array($val)) ? ($val[0] ?? null) : $val; if ($sampleVal !== null) { $err = $registry->validate($sampleVal, $resolvedBound, $effectiveFunction . '(): Argument $' . $paramName . ' (template ' . $tName . ')', $isSensitive); @@ -721,7 +719,7 @@ private static function validateCrossReferencedTemplateBounds( } } - if (! $matchedParam && ! TemplateManager::checkVariance($finalBoundTemplates[$tName], $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT)) { + if (! TemplateManager::checkVariance($finalBoundTemplates[$tName], $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT)) { return ErrorFactory::createError( $effectiveFunction . "(): Generic type argument {$finalBoundTemplates[$tName]} does not satisfy upper bound {$resolvedBound} of template {$tName}" ); diff --git a/src/Internal/Checker/ParamOutChecker.php b/src/Internal/Checker/ParamOutChecker.php index 4dd10ff1..45db2f4d 100644 --- a/src/Internal/Checker/ParamOutChecker.php +++ b/src/Internal/Checker/ParamOutChecker.php @@ -29,13 +29,17 @@ public static function reset(): void self::$noParamOutContractCache = []; } + /** + * @param array $vars + */ public static function checkParamOut( string $function, string $paramName, mixed $value, object|string|null $thisOrClass, TypeValidatorRegistry $registry, - string $effectiveFunction = '' + string $effectiveFunction = '', + array $vars = [] ): ?ErrorMessage { if (! Config::isParamsEnabled()) { return null; @@ -66,7 +70,7 @@ public static function checkParamOut( return null; } - $paramOuts = $contract['paramOuts'] ?? []; + $paramOuts = $paramOuts = $contract['paramOuts'] ?? []; if (! isset($paramOuts[$paramName])) { return null; @@ -78,11 +82,19 @@ public static function checkParamOut( ? TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates) : []; + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); + } + if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) { $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $allTemplates); } $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); + } + $context = $effectiveFunction . '(): Argument &$' . $paramName . ' (param-out)'; $err = $registry->validate($value, $typeNode, $context); diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index f98ebf09..4d63a368 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -627,6 +627,33 @@ public static function isFBounded(TemplateTagValueNode $templateNode, string $co ); } + /** + * Retrieves static class-level bindings including declared template defaults. + * + * @param class-string $className + * + * @return array + */ + public static function getClassStaticBindings(string $className): array + { + $bindings = self::getClassInheritedBindings($className); + + try { + $ref = new \ReflectionClass($className); + [$hierarchyTemplates] = self::collectHierarchyTemplatesAndVariances($ref); + + foreach ($hierarchyTemplates as $tName => $templateTag) { + if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { + $bindings[$tName] = $templateTag->default; + } + } + } catch (\Throwable $e) { + // Silently ignore reflection errors + } + + return $bindings; + } + /** * Retrieves currently bound template types for a function call or object instance / static class. * @@ -642,9 +669,10 @@ public static function getBoundTemplates(string $function, object|string|null $t if ($thisObj !== null) { self::ensureInstanceInherited($thisObj); - if (isset(self::$instanceTemplateBindings[$thisObj])) { - $bindings = self::$instanceTemplateBindings[$thisObj]; - } + $isCtor = str_ends_with(strtolower($function), '::__construct'); + $bindings = $isCtor + ? (self::$instanceTemplateBindings[$thisObj] ?? []) + : self::getBoundTemplatesForInstance($thisObj); $methodTemplates = self::getMethodTemplates($function); if ($methodTemplates !== []) { @@ -658,7 +686,7 @@ public static function getBoundTemplates(string $function, object|string|null $t : (str_contains($function, '::') ? explode('::', $function, 2)[0] : ''); if ($className !== '' && (class_exists($className, false) || class_exists($className) || interface_exists($className) || trait_exists($className))) { - $classBindings = self::getClassInheritedBindings($className); + $classBindings = self::getClassStaticBindings($className); $bindings = $classBindings; $methodTemplates = self::getMethodTemplates($function); @@ -696,11 +724,24 @@ public static function getBoundTemplatesForInstance(object $instance): array { self::ensureInstanceInherited($instance); - if (self::$instanceTemplateBindings !== null && isset(self::$instanceTemplateBindings[$instance])) { - return self::$instanceTemplateBindings[$instance]; + $bindings = (self::$instanceTemplateBindings !== null && isset(self::$instanceTemplateBindings[$instance])) + ? self::$instanceTemplateBindings[$instance] + : []; + + try { + $ref = new \ReflectionClass($instance); + [$hierarchyTemplates] = self::collectHierarchyTemplatesAndVariances($ref); + + foreach ($hierarchyTemplates as $tName => $templateTag) { + if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { + $bindings[$tName] = $templateTag->default; + } + } + } catch (\Throwable $e) { + // Silently ignore reflection errors } - return []; + return $bindings; } /** @@ -784,7 +825,12 @@ public static function isBound(string $function, object|string|null $thisOrClass return false; } - return isset(self::$instanceTemplateBindings[$thisObj][$templateName]); + $isCtor = str_ends_with(strtolower($function), '::__construct'); + $instanceBindings = $isCtor + ? (self::$instanceTemplateBindings[$thisObj] ?? []) + : self::getBoundTemplatesForInstance($thisObj); + + return isset($instanceBindings[$templateName]); } $className = \is_string($thisOrClass) && $thisOrClass !== '' @@ -796,7 +842,7 @@ public static function isBound(string $function, object|string|null $thisOrClass return false; } - $classBindings = self::getClassInheritedBindings($className); + $classBindings = self::getClassStaticBindings($className); return isset($classBindings[$templateName]); } @@ -823,7 +869,12 @@ public static function getBoundType(string $function, object|string|null $thisOr return null; } - return self::$instanceTemplateBindings[$thisObj][$templateName] ?? null; + $isCtor = str_ends_with(strtolower($function), '::__construct'); + $instanceBindings = $isCtor + ? (self::$instanceTemplateBindings[$thisObj] ?? []) + : self::getBoundTemplatesForInstance($thisObj); + + return $instanceBindings[$templateName] ?? null; } $className = \is_string($thisOrClass) && $thisOrClass !== '' @@ -835,7 +886,7 @@ public static function getBoundType(string $function, object|string|null $thisOr return null; } - $classBindings = self::getClassInheritedBindings($className); + $classBindings = self::getClassStaticBindings($className); return $classBindings[$templateName] ?? null; } @@ -925,6 +976,56 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t return null; } + /** + * Checks whether a template's default type is an unspecialized placeholder (e.g. mixed or repeating its own bound). + */ + public static function isUnspecializedDefault(TemplateTagValueNode $templateTag): bool + { + if ($templateTag->default === null) { + return true; + } + + if ($templateTag->default instanceof IdentifierTypeNode) { + if (strtolower($templateTag->default->name) === 'mixed') { + return true; + } + } + + if ($templateTag->bound !== null && (string) $templateTag->default === (string) $templateTag->bound) { + return true; + } + + return false; + } + + /** + * Binds declared default template types onto an instance for any template not yet bound. + * + * @param array $classTemplates + */ + public static function applyClassTemplateDefaults(object $instance, array $classTemplates): void + { + if ($classTemplates === []) { + return; + } + + self::ensureInstanceInherited($instance); + self::$instanceTemplateBindings ??= new WeakMap(); + $bindings = self::$instanceTemplateBindings[$instance] ?? []; + $changed = false; + + foreach ($classTemplates as $tName => $templateTag) { + if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { + $bindings[$tName] = $templateTag->default; + $changed = true; + } + } + + if ($changed) { + self::$instanceTemplateBindings[$instance] = $bindings; + } + } + /** * @param \ReflectionClass $ref * diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index 5a699127..2ba0f72e 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.12.1_'; + public const VERSION_PREFIX = 'v0.12.3_'; /** * Cached absolute cache directory path. diff --git a/src/Internal/Reporting/ViolationCollector.php b/src/Internal/Reporting/ViolationCollector.php index 007f9084..8dd6558e 100644 --- a/src/Internal/Reporting/ViolationCollector.php +++ b/src/Internal/Reporting/ViolationCollector.php @@ -55,7 +55,7 @@ public static function reset(): void /** * Handles a validation failure according to the configured on_violation mode ('throw', 'warn', 'report'). * - * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send' $kind + * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send'|'constant' $kind */ public static function handle( ErrorMessage $error, diff --git a/src/Internal/Reporting/ViolationRecord.php b/src/Internal/Reporting/ViolationRecord.php index 4ceb3a84..4993f24a 100644 --- a/src/Internal/Reporting/ViolationRecord.php +++ b/src/Internal/Reporting/ViolationRecord.php @@ -12,7 +12,7 @@ final class ViolationRecord implements JsonSerializable { /** - * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send' $kind + * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send'|'constant' $kind */ public function __construct( public readonly string $file, diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 1792d925..558aa52e 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -6,6 +6,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Parser\TokenIterator; use TypePHP\Internal\Ast\ScopeCleaner; use TypePHP\Internal\Checker\GeneratorChecker; use TypePHP\Internal\Checker\InlineChecker; @@ -16,10 +17,13 @@ use TypePHP\Internal\Checker\SelfOutChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\Docblock\DocblockExtractor; +use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Reporting\ViolationCollector; use TypePHP\Internal\Resolver\CallerBoundaryResolver; +use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\IgnoreManager; use TypePHP\Internal\Validator\TypeValidatorRegistry; @@ -67,6 +71,128 @@ public static function isEnabled(): bool return Config::isEnabled(); } + /** + * Validates class-level and global constants against declared @var contracts upon declaration/load. + */ + public static function checkConstant( + string $constantName, + mixed $value, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! Config::isEnabled()) { + return $value; + } + + try { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + $typeNode = $typeParser->parse($tokens); + + if ($file !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + } + + $context = "Constant {$constantName}"; + + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + return ViolationCollector::handle($err, 'constant', $value, $file, $line, $constantName); + } + } catch (\Throwable $e) { + // Silently ignore unexpected parsing errors + } + + return $value; + } + + /** + * Validates an argument passed into a constant closure against its parameter contract. + */ + public static function checkConstantClosureParam( + string $caller, + string $paramName, + mixed $value, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! Config::isEnabled() || ! Config::isParamsEnabled()) { + return $value; + } + + try { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + $typeNode = $typeParser->parse($tokens); + + if ($file !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + } + + $context = "{$caller}(): Argument \${$paramName}"; + + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + return ViolationCollector::handle($err, 'parameter', $value, $file, $line, $caller, '$' . $paramName); + } + } catch (\Throwable $e) { + } + + return $value; + } + + /** + * Validates a return value from a constant closure against its return type contract. + */ + public static function checkConstantClosureReturn( + string $caller, + mixed $value, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! Config::isEnabled() || ! Config::isReturnsEnabled()) { + return $value; + } + + try { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + $typeNode = $typeParser->parse($tokens); + + if ($file !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + } + + $context = "{$caller}(): Return value"; + + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + return ViolationCollector::handle($err, 'return', $value, $file, $line, $caller, 'return'); + } + } catch (\Throwable $e) { + } + + return $value; + } + /** * Evaluates member/dimension mutation assignments on an object or static property * ($obj->prop[$key] = $val or Class::$prop[$key] = $val) atomically before writing. @@ -410,9 +536,16 @@ public static function checkParams(string $function, array $vars, object|string| /** * Validates a by-reference parameter's post-condition (@param-out) upon exit. + * + * @param array|null $vars */ - public static function checkParamOut(string $function, string $paramName, mixed $value, object|string|null $thisOrClass = null): ?ErrorMessage - { + public static function checkParamOut( + string $function, + string $paramName, + mixed $value, + object|string|null $thisOrClass = null, + ?array $vars = [] + ): ?ErrorMessage { if (! Config::isEnabled() || ! Config::isParamsOutEnabled()) { return null; } @@ -424,7 +557,9 @@ public static function checkParamOut(string $function, string $paramName, mixed return null; } - $res = ParamOutChecker::checkParamOut($function, $paramName, $value, $thisOrClass, self::getRegistry(), $effectiveFunction); + $vars = $vars !== null ? $vars : []; + + $res = ParamOutChecker::checkParamOut($function, $paramName, $value, $thisOrClass, self::getRegistry(), $effectiveFunction, $vars); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index bd8fedc4..caa71742 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -10,6 +10,7 @@ use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use TypePHP\Exception\TypeError as TypePHPTypeError; +use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Docblock\DocblockParser; @@ -53,6 +54,19 @@ public static function wrap(string $function, string $paramName, mixed $iterable $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + } + + if (\count($boundTemplates) > 0 || \count($templates) > 0) { + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); + $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); + } + + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + } + if (\count($boundTemplates) > 0 || \count($templates) > 0) { $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); diff --git a/tests/Fixtures/Generics/MultiTemplateBag.php b/tests/Fixtures/Generics/MultiTemplateBag.php index 0b73fded..6994aada 100644 --- a/tests/Fixtures/Generics/MultiTemplateBag.php +++ b/tests/Fixtures/Generics/MultiTemplateBag.php @@ -5,8 +5,8 @@ namespace TypePHP\Tests\Fixtures\Generics; /** - * @template K of array-key = string - * @template V = int + * @template K of array-key + * @template V */ class MultiTemplateBag { diff --git a/tests/Internal/Ast/NodeBuilderTest.php b/tests/Internal/Ast/NodeBuilderTest.php index 7bf0db1a..1331515a 100644 --- a/tests/Internal/Ast/NodeBuilderTest.php +++ b/tests/Internal/Ast/NodeBuilderTest.php @@ -83,4 +83,64 @@ ->and($call->args)->toHaveCount(5) ; }); + + test('createConstantCheckCall creates FuncCall node for RuntimeTypeChecker::checkConstant', function () { + $valExpr = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified('App\Config'), 'Data'); + + $call = NodeBuilder::createConstantCheckCall('App\Config::Data', $valExpr, 'list', 12); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkConstant') + ->and($call->args)->toHaveCount(5) + ->and($call->args[0]->value->value)->toBe('App\Config::Data') + ->and($call->args[1]->value)->toBe($valExpr) + ->and($call->args[2]->value->value)->toBe('list') + ->and($call->args[3]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class) + ->and($call->args[4]->value->value)->toBe(12) + ; + }); + + test('createConstantClosureParamCheckCall creates FuncCall node for RuntimeTypeChecker::checkConstantClosureParam', function () { + $paramVar = new Node\Expr\Variable('id'); + + $call = NodeBuilder::createConstantClosureParamCheckCall( + 'App\Config::Formatter', + 'id', + $paramVar, + 'positive-int', + 15 + ); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureParam') + ->and($call->args)->toHaveCount(6) + ->and($call->args[0]->value->value)->toBe('App\Config::Formatter') + ->and($call->args[1]->value->value)->toBe('id') + ->and($call->args[2]->value)->toBe($paramVar) + ->and($call->args[3]->value->value)->toBe('positive-int') + ->and($call->args[4]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class) + ->and($call->args[5]->value->value)->toBe(15) + ; + }); + + test('createConstantClosureReturnCheckCall creates FuncCall node for RuntimeTypeChecker::checkConstantClosureReturn', function () { + $valueExpr = new Node\Scalar\String_('test'); + + $call = NodeBuilder::createConstantClosureReturnCheckCall( + 'App\Config::Callback', + $valueExpr, + 'int', + 20 + ); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureReturn') + ->and($call->args)->toHaveCount(5) + ->and($call->args[0]->value->value)->toBe('App\Config::Callback') + ->and($call->args[1]->value)->toBe($valueExpr) + ->and($call->args[2]->value->value)->toBe('int') + ->and($call->args[3]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class) + ->and($call->args[4]->value->value)->toBe(20) + ; + }); }); diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index 96517bcd..7e6eef3f 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -762,4 +762,102 @@ function vendorAction(): void ->toThrow(TypeError::class, 'positive-int') ; }); + + test('checkConstant validates class and global constants and respects disabled switch', function () { + $valid = RuntimeTypeChecker::checkConstant('App\Config::Data', ['User', 'Product'], 'list', __FILE__, 10); + expect($valid)->toBe(['User', 'Product']); + + $invalidClass = RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10); + expect($invalidClass)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidClass->getMessage())->toContain('must be a list') + ; + + $invalidGlobal = RuntimeTypeChecker::checkConstant('GLOBAL_TIMEOUT', -5, 'positive-int', __FILE__, 20); + expect($invalidGlobal)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidGlobal->getMessage())->toContain('must be of type positive-int') + ; + + Config::set(['enabled' => false]); + expect(RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10)) + ->toBe(['user' => 'User']) + ; + }); + + test('checkConstant respects @typephp-ignore on caller', function () { + $res = RuntimeCheckerIgnoredCaller::run( + fn () => RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10) + ); + + expect($res)->toBe(['user' => 'User']); + }); + + test('checkConstantClosureParam validates arguments and respects config toggles and ignore tags', function () { + $valid = RuntimeTypeChecker::checkConstantClosureParam( + 'App\Config::Formatter', + 'id', + 10, + 'positive-int', + __FILE__, + 15 + ); + expect($valid)->toBe(10); + + $invalid = RuntimeTypeChecker::checkConstantClosureParam( + 'App\Config::Formatter', + 'id', + -5, + 'positive-int', + __FILE__, + 15 + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('App\Config::Formatter(): Argument $id must be of type positive-int') + ; + + Config::set(['params' => false]); + expect(RuntimeTypeChecker::checkConstantClosureParam('App\Config::Formatter', 'id', -5, 'positive-int'))->toBe(-5); + + Config::set(['enabled' => false, 'params' => true]); + expect(RuntimeTypeChecker::checkConstantClosureParam('App\Config::Formatter', 'id', -5, 'positive-int'))->toBe(-5); + + Config::set(['enabled' => true, 'params' => true]); + $ignored = RuntimeCheckerIgnoredCaller::run( + fn () => RuntimeTypeChecker::checkConstantClosureParam('App\Config::Formatter', 'id', -5, 'positive-int') + ); + expect($ignored)->toBe(-5); + }); + + test('checkConstantClosureReturn validates return values and respects config toggles and ignore tags', function () { + $valid = RuntimeTypeChecker::checkConstantClosureReturn( + 'App\Config::Callback', + 42, + 'int', + __FILE__, + 25 + ); + expect($valid)->toBe(42); + + $invalid = RuntimeTypeChecker::checkConstantClosureReturn( + 'App\Config::Callback', + 'not_an_int', + 'int', + __FILE__, + 25 + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('App\Config::Callback(): Return value must be of type int, string \'not_an_int\' returned') + ; + + Config::set(['returns' => false]); + expect(RuntimeTypeChecker::checkConstantClosureReturn('App\Config::Callback', 'not_an_int', 'int'))->toBe('not_an_int'); + + Config::set(['enabled' => false, 'returns' => true]); + expect(RuntimeTypeChecker::checkConstantClosureReturn('App\Config::Callback', 'not_an_int', 'int'))->toBe('not_an_int'); + + Config::set(['enabled' => true, 'returns' => true]); + $ignored = RuntimeCheckerIgnoredCaller::run( + fn () => RuntimeTypeChecker::checkConstantClosureReturn('App\Config::Callback', 'not_an_int', 'int') + ); + expect($ignored)->toBe('not_an_int'); + }); }); diff --git a/tests/TypeChecking/Boundaries/ConstantContractsTest.php b/tests/TypeChecking/Boundaries/ConstantContractsTest.php new file mode 100644 index 00000000..4ec526d7 --- /dev/null +++ b/tests/TypeChecking/Boundaries/ConstantContractsTest.php @@ -0,0 +1,564 @@ + contract (User Reproduction)', function () { + $source = <<<'PHP' + + */ + public const Data = [ + 'user' => 'User', + 'product' => 'Product', + ]; +} +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/FixtureBadListConst.php'; + file_put_contents($filePath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $filePath) + ->toThrow(TypeError::class, 'Constant TypePHP\Tests\TypeChecking\Boundaries\FixtureBadListConst::Data must be a list, associative array (key \'user\') given') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('accepts class constant satisfying list contract', function () { + $source = <<<'PHP' + + */ + public const Data = [ + 'User', + 'Product', + ]; +} + +return FixtureValidListConst::Data; +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/FixtureValidListConst.php'; + file_put_contents($filePath, $source); + + try { + StreamWrapper::register(); + + $result = require $filePath; + expect($result)->toBe(['User', 'Product']); + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when class constant violates scalar refinement (positive-int)', function () { + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'Constant TypePHP\Tests\TypeChecking\Boundaries\FixtureBadScalarConst::RETRIES must be of type positive-int, negative int (-5) given') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when class constant violates array shape', function () { + $source = <<<'PHP' + -1, + 'role' => 'admin', + ]; +} +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/FixtureBadShapeConst.php'; + file_put_contents($filePath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $filePath) + ->toThrow(TypeError::class, "['id'] must be of type positive-int") + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); + + describe('2. Global Constant Validation', function () { + test('throws TypeError when global const violates non-empty-string contract', function () { + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'Constant GLOBAL_BAD_EMPTY_NAME must be of type non-empty-string') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); + + describe('3. Compile-Time Static Elimination & Zero Line-Drift', function () { + test('eliminates check on statically proven valid constant (zero injections)', function () { + $source = <<<'PHP' + + */ + public const Data = ['User', 'Product']; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'ValidConfig.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkConstant') + ->and($transformed)->not()->toContain('checkClassConstant') + ; + }); + + test('guarantees zero line-drift when constant check is injected', function () { + $source = <<<'PHP' + + */ + public const Data = [ + 'user' => 'User', + ]; +} + +$landmark = 'line_16_exact'; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'ConfigWithDriftCheck.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)); + + $origIndex = array_search('$landmark = \'line_16_exact\';', array_map('trim', $origLines), true); + $transIndex = array_search('$landmark = \'line_16_exact\';', array_map('trim', $transLines), true); + + expect($transIndex)->toBe($origIndex) + ->and($origIndex)->toBe(16) + ; + }); + + test('points to exact line number of the constant definition in thrown TypeError', function () { + $source = <<<'PHP' +getLine())->toBe(12); + } + + expect($caught)->toBeTrue(); + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); + + describe('4. Closures in Constants (PHP 8.5+)', function () { + test('throws TypeError when constant closure violates return contract', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'ConfigConstClosureReturnViolation::Callback(): Return value must be of type int, string \'not_an_int\' returned') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError on direct execution of constant closure (Config::Callback)()', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'ConfigConstClosureDirectCall::Callback(): Return value must be of type int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when constant closure parameter violates contract', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'ConfigConstClosureParamViolation::Formatter(): Argument $id must be of type positive-int, negative int (-5) given') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when global constant closure violates return contract', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'GLOBAL_CONST_CLOSURE(): Return value must be of type int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('accepts valid constant closure and executes cleanly', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' +toBe('user_42'); + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('guarantees zero line-drift when instrumenting closures inside constants', function () { + $source = <<<'PHP' +toBe(\count($origLines)); + + $origIndex = array_search('$landmark = \'line_18_exact\';', array_map('trim', $origLines), true); + $transIndex = array_search('$landmark = \'line_18_exact\';', array_map('trim', $transLines), true); + + expect($transIndex)->toBe($origIndex) + ->and($origIndex)->toBe(17) + ; + }); + + test('eliminates return check when closure return is statically proven valid', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkReturn'); + }); + }); +}); diff --git a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php index 2dcc478b..3b5d8ec8 100644 --- a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php +++ b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php @@ -357,6 +357,47 @@ public function runValid(mixed &$x): Generator } } +/** + * 13. Parameter-based conditional @param-out on standalone function + * + * @param bool $asInt + * @param mixed &$out + * + * @param-out ($asInt is true ? positive-int : non-empty-string) $out + */ +function tddParamOutConditionalByFlag(bool $asInt, mixed &$out, mixed $newVal): void +{ + $out = $newVal; +} + +class IssueParamOutConditionalService +{ + /** + * @param 'int'|'string' $format + * @param mixed &$out + * + * @param-out ($format is 'int' ? positive-int : non-empty-string) $out + */ + public function formatOutput(string $format, mixed &$out, mixed $newVal): void + { + $out = $newVal; + } + + /** + * Mutates $asInt inside the body before exit (must evaluate against initial entry argument!) + * + * @param bool $asInt + * @param mixed &$out + * + * @param-out ($asInt is true ? positive-int : non-empty-string) $out + */ + public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): void + { + $asInt = false; + $out = $newVal; + } +} + describe('@param-out & @phpstan-param-out Contracts', function () { describe('1. Basic Scalar @param-out', function () { test('accepts valid post-condition mutation on by-ref parameter', function () { @@ -679,4 +720,52 @@ public function runValid(mixed &$x): Generator ; }); }); + + describe('13. Parameter-Based Conditional @param-out ($param is Target ? A : B)', function () { + test('evaluates true branch (positive-int) on standalone function when $asInt is true', function () { + $out = null; + tddParamOutConditionalByFlag(true, $out, 42); + expect($out)->toBe(42); + + expect(fn () => tddParamOutConditionalByFlag(true, $out, -10)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; + }); + + test('evaluates else branch (non-empty-string) on standalone function when $asInt is false', function () { + $out = null; + tddParamOutConditionalByFlag(false, $out, 'valid_text'); + expect($out)->toBe('valid_text'); + + expect(fn () => tddParamOutConditionalByFlag(false, $out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; + }); + + test('evaluates parameter-based conditional @param-out on class methods and preserves entry argument on in-body mutation', function () { + $service = new IssueParamOutConditionalService(); + $out = null; + + $service->formatOutput('int', $out, 100); + expect($out)->toBe(100); + + expect(fn () => $service->formatOutput('int', $out, -5)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; + + $service->formatOutput('string', $out, 'hello'); + expect($out)->toBe('hello'); + + expect(fn () => $service->formatOutput('string', $out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; + + $service->mutateFlagBeforeExit(true, $out, 50); + expect($out)->toBe(50); + + expect(fn () => $service->mutateFlagBeforeExit(true, $out, 'wrong_branch')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; + }); + }); }); diff --git a/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php b/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php index fd8855c4..eba6db1b 100644 --- a/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php +++ b/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php @@ -5,6 +5,9 @@ namespace TypePHP\Tests\TypeChecking\Boundaries; use TypePHP\Exception\TypeError; +use TypePHP\Tests\Fixtures\Domain\Car; +use TypePHP\Tests\Fixtures\Domain\Dog; +use TypePHP\Tests\Fixtures\Generics\GenericBox; use TypePHP\Tests\Fixtures\Properties\PropertyRefTargetFixture; /** @@ -38,6 +41,133 @@ public function mutateInternalScoreByRef(mixed $val): void } } +class GenericRefUser +{ + public function __construct(public string $name = 'Alice') + { + } +} + +class GenericRefProduct +{ + public function __construct(public string $sku = 'PROD-1') + { + } +} + +/** + * @template T + */ +class SameFileGenericBox +{ + /** + * @param T $value + */ + public function __construct( + public mixed $value + ) { + } + + public function mutateInternalValueByRef(mixed $val): void + { + $ref = &$this->value; + $ref = $val; + } +} + +/** + * @template K of array-key + * @template V + */ +class SameFileGenericMap +{ + /** + * @param K $key + * @param V $val + */ + public function __construct( + public mixed $key, + public mixed $val + ) { + } +} + +/** + * Generic fixture with list property + * + * @template T + */ +class GenericListBoxFixture +{ + /** + * @var list + */ + public array $items = []; + + /** + * @param list $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } + + public function mutateItemByRef(int $index, mixed $val): void + { + $ref = &$this->items[$index]; + $ref = $val; + } + + public function appendItemViaRef(mixed $val): void + { + $ref = &$this->items; + $ref[] = $val; + } +} + +/** + * Generic fixture with typed array T[] property + * + * @template T + */ +class GenericTypedArrayBoxFixture +{ + /** + * @var T[] + */ + public array $items = []; + + /** + * @param T[] $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } +} + +/** + * Generic fixture with array map property + * + * @template K of array-key + * @template V + */ +class GenericMapBoxFixture +{ + /** + * @var array + */ + public array $items = []; + + /** + * @param array $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } +} + describe('By-Reference Property Aliasing ($ref = &$obj->prop)', function () { beforeEach(function () { PropertyRefTargetFixture::reset(); @@ -202,4 +332,202 @@ public function mutateInternalScoreByRef(mixed $val): void expect($local->localScore)->toBe(10); }); }); + + describe('7. Generic Property Reference Aliasing ($ref = &$genericBox->item)', function () { + test('throws TypeError when assigning invalid value to reference aliasing a generic property (GenericBox)', function () { + /** @var GenericBox $dogBox */ + $dogBox = new GenericBox(); + $dogBox->item = new Dog(); + + $ref = &$dogBox->item; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + }); + + test('allows valid assignment to reference aliasing a generic property and mutates property in place', function () { + /** @var GenericBox $dogBox */ + $dogBox = new GenericBox(); + $dogBox->item = new Dog(); + + $ref = &$dogBox->item; + $newDog = new Dog(); + $ref = $newDog; + + expect($dogBox->item)->toBe($newDog) + ->and($ref)->toBe($newDog) + ; + }); + + test('throws TypeError when assigning invalid value to reference aliasing a promoted generic property (User Bug Reproduction)', function () { + /** @var SameFileGenericBox $userBox */ + $userBox = new SameFileGenericBox(new GenericRefUser()); + + $reference = &$userBox->value; + + expect(function () use (&$reference) { + $reference = new GenericRefProduct(); + })->toThrow(TypeError::class, GenericRefUser::class); + }); + + test('throws TypeError when assigning invalid value to reference aliasing multi-template generic property', function () { + /** @var SameFileGenericMap $map */ + $map = new SameFileGenericMap('timeout', 10); + + $keyRef = &$map->key; + $valRef = &$map->val; + + expect(function () use (&$valRef) { + $valRef = -50; + })->toThrow(TypeError::class, 'positive-int'); + + expect(function () use (&$keyRef) { + $keyRef = 12345; + })->toThrow(TypeError::class, 'must be of type string'); + }); + + test('throws TypeError when internal method mutates generic $this property via reference alias', function () { + /** @var SameFileGenericBox $userBox */ + $userBox = new SameFileGenericBox(new GenericRefUser()); + + expect(function () use ($userBox) { + $userBox->mutateInternalValueByRef(new GenericRefProduct()); + })->toThrow(TypeError::class, GenericRefUser::class); + + expect($userBox->value)->toBeInstanceOf(GenericRefUser::class); + }); + }); + + describe('8. Generic Array Properties: By-Reference Aliasing & Element Mutations', function () { + test('throws TypeError when assigning invalid value to reference aliasing an element of generic list', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items[0]; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when assigning invalid value to reference aliasing an element of generic T[]', function () { + /** @var GenericTypedArrayBoxFixture $box */ + $box = new GenericTypedArrayBoxFixture([new Dog()]); + + $ref = &$box->items[0]; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when assigning invalid value to reference aliasing an element of generic array', function () { + /** @var GenericMapBoxFixture $box */ + $box = new GenericMapBoxFixture(['pet' => new Dog()]); + + $ref = &$box->items['pet']; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items['pet'])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when appending invalid value to reference aliasing the entire generic array property', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items; + + expect(function () use (&$ref) { + $ref[] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items)->toHaveCount(1); + }); + + test('throws TypeError when assigning by index to reference aliasing the entire generic array property', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items; + + expect(function () use (&$ref) { + $ref[0] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError on direct array append to generic property ($box->items[] = new Car())', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture(); + + expect(function () use ($box) { + $box->items[] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items)->toBeEmpty(); + }); + + test('throws TypeError on direct index assignment to generic property ($box->items[0] = new Car())', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + expect(function () use ($box) { + $box->items[0] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when internal method mutates generic $this array element via reference alias', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + expect(function () use ($box) { + $box->mutateItemByRef(0, new Car()); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when internal method appends to generic $this array via reference alias', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + expect(function () use ($box) { + $box->appendItemViaRef(new Car()); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items)->toHaveCount(1); + }); + + test('allows valid assignment to generic array element reference and mutates in place', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items[0]; + $newDog = new Dog(); + $ref = $newDog; + + expect($box->items[0])->toBe($newDog) + ->and($ref)->toBe($newDog) + ; + + $arrayRef = &$box->items; + $buddy = new Dog(); + $arrayRef[] = $buddy; + + expect($box->items)->toHaveCount(2) + ->and($box->items[1])->toBe($buddy) + ; + }); + }); }); diff --git a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php index d3cdc053..f9637230 100644 --- a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php +++ b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php @@ -63,6 +63,56 @@ public function run(): Generator } } +/** + * Top-level conditional generator return with default template T = int + * + * @template T = int + * + * @param T|null $sample + * @param mixed $yieldValue + * + * @return (T is int ? Generator : Generator) + */ +function testConditionalGeneratorReturn(mixed $sample = null, mixed $yieldValue = null): Generator +{ + yield 0 => $yieldValue; +} + +/** + * Nested conditional element inside Generator return + * + * @template T = int + * + * @param T|null $sample + * @param mixed $yieldValue + * + * @return Generator + */ +function testNestedConditionalGeneratorReturn(mixed $sample = null, mixed $yieldValue = null): Generator +{ + yield 0 => $yieldValue; +} + +/** + * Conditional iterable parameter with Traversable lazy wrapping + * + * @template T = int + * + * @param iterable $stream + * @param T|null $sample + * + * @return list + */ +function testConditionalIterableParam(iterable $stream, mixed $sample = null): array +{ + $collected = []; + foreach ($stream as $item) { + $collected[] = $item; + } + + return $collected; +} + describe('Generic Iterables & Generators (@template T with iterable and Generator)', function () { describe('Generic Iterable Parameters (iterable)', function () { test('collects items from iterable matching inferred template T = int', function () { @@ -211,4 +261,54 @@ public function run(): Generator })->toThrow(TypeError::class, 'must be of type void'); }); }); + + describe('Conditional Generator & Iterable Contracts', function () { + test('validates top-level conditional generator return with default T = int and overridden T = string', function () { + $validIntGen = testConditionalGeneratorReturn(null, 42); + expect(iterator_to_array($validIntGen))->toBe([0 => 42]); + + $badIntGen = testConditionalGeneratorReturn(null, -10); + expect(fn () => iterator_to_array($badIntGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + $validStrGen = testConditionalGeneratorReturn('override', 'hello'); + expect(iterator_to_array($validStrGen))->toBe([0 => 'hello']); + + $badStrGen = testConditionalGeneratorReturn('override', ''); + expect(fn () => iterator_to_array($badStrGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string') + ; + }); + + test('validates nested conditional element inside Generator', function () { + $validGen = testNestedConditionalGeneratorReturn(null, 100); + expect(iterator_to_array($validGen))->toBe([0 => 100]); + + $badGen = testNestedConditionalGeneratorReturn(null, -5); + expect(fn () => iterator_to_array($badGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + $badStrGen = testNestedConditionalGeneratorReturn('override', ''); + expect(fn () => iterator_to_array($badStrGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string') + ; + }); + + test('lazily validates conditional iterable parameter on Traversable iteration', function () { + $validIter = new ArrayIterator([10, 20, 30]); + expect(testConditionalIterableParam($validIter))->toBe([10, 20, 30]); + + $badIntIter = new ArrayIterator([10, -5, 30]); + expect(fn () => testConditionalIterableParam($badIntIter)) + ->toThrow(TypeError::class, 'Iterator $stream value must be of type positive-int') + ; + + $badStrIter = new ArrayIterator(['valid', '']); + expect(fn () => testConditionalIterableParam($badStrIter, 'override')) + ->toThrow(TypeError::class, 'Iterator $stream value must be of type non-empty-string') + ; + }); + }); }); diff --git a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php index da842745..fed90015 100644 --- a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php +++ b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php @@ -2,7 +2,9 @@ declare(strict_types=1); +use TypePHP\Exception\TypeError; use TypePHP\Tests\Fixtures\Domain\Dog; +use TypePHP\TypePHP; /** * 1. Default template without explicit bound (@template T = string) @@ -32,22 +34,518 @@ function testDefaultTemplateObject(mixed $value): mixed return $value; } +/** + * 3. Standalone function with default template in conditional return + * + * @template T = int + * + * @param T|null $sample + * @param mixed $returnValue + * + * @return (T is int ? positive-int : non-empty-string) + */ +function testDefaultTemplateConditionalReturn(mixed $sample = null, mixed $returnValue = null): mixed +{ + return $returnValue; +} + +/** + * 4. Standalone function with default template in conditional parameter + * + * @template T = int + * + * @param (T is int ? positive-int : non-empty-string) $payload + * @param T|null $sample + */ +function testDefaultTemplateConditionalParam(mixed $payload, mixed $sample = null): mixed +{ + return $payload; +} + +/** + * 5. Standalone function with default template in conditional @param-out + * + * @template T = int + * + * @param mixed &$out + * @param mixed $newValue + * @param T|null $sample + * + * @param-out (T is int ? positive-int : non-empty-string) $out + */ +function testDefaultTemplateConditionalParamOut(mixed &$out, mixed $newValue, mixed $sample = null): void +{ + $out = $newValue; +} + +/** + * 6. Class with default template type (@template T = int) and no constructor + * + * @template T = int + */ +class DefaultIntBox +{ + /** + * @var list + */ + public array $items = []; + + /** + * @param T $item + */ + public function add(mixed $item): void + { + $this->items[] = $item; + } + + /** + * Zero-parameter method with conditional return based on class template T + * + * @return (T is int ? positive-int : non-empty-string) + */ + public function getDefaultConditionalValue(mixed $val): mixed + { + return $this->computeConditional($val); + } + + /** + * @return (T is int ? positive-int : non-empty-string) + */ + public function computeOne(): mixed + { + return 42; + } + + /** + * @return (T is int ? positive-int : non-empty-string) + */ + public function computeInvalidNegative(): mixed + { + return -10; + } + + /** + * @param mixed &$out + * + * @param-out T $out + */ + public function exportTo(mixed &$out, mixed $val): void + { + $out = $val; + } + + /** + * @param mixed &$out + * + * @param-out (T is int ? positive-int : non-empty-string) $out + */ + public function exportConditionalTo(mixed &$out, mixed $val): void + { + $out = $val; + } + + /** + * @return (T is int ? positive-int : non-empty-string) + */ + private function computeConditional(mixed $val): mixed + { + return $val; + } +} + +/** + * 7. Class with default template type (@template T = int) and optional constructor parameter + * + * @template T = int + */ +class DefaultBoxWithCtor +{ + /** + * @var T|null + */ + public mixed $value = null; + + /** + * @param T|null $initial + */ + public function __construct(mixed $initial = null) + { + $this->value = $initial; + } + + /** + * @param T $val + */ + public function set(mixed $val): void + { + $this->value = $val; + } +} + +/** + * 8. Multi-template class with partial default (@template K of array-key = string, @template V) + * + * @template K of array-key = string + * @template V + */ +class PartialDefaultMap +{ + /** + * @var array + */ + public array $entries = []; + + /** + * @param K $key + * @param V $val + */ + public function put(mixed $key, mixed $val): void + { + $this->entries[$key] = $val; + } +} + +/** + * Class with static methods and class-level template default + * + * @template T = int + */ +class DefaultStaticClassHolder +{ + /** + * @return T + */ + public static function getDefault(): mixed + { + return 'not_an_int'; + } + + /** + * @param T $val + */ + public static function checkDefaultParam(mixed $val): mixed + { + return $val; + } +} + +/** + * Class with 0-arg method and typestate self-out + * + * @template T = int + */ +class DefaultTypestateZeroArgHolder +{ + /** + * @var T|null + */ + public mixed $val = null; + + /** + * 0-argument method with @self-out + * + * @self-out self + */ + public function enableString(): void + { + } + + /** + * @param T $v + */ + public function set(mixed $v): void + { + $this->val = $v; + } +} + describe('Default Template Annotations (@template T = DefaultType)', function () { - test('uses default template type string when template T is unbound', function () { - expect(testDefaultTemplateString('hello'))->toBe('hello'); + describe('1. Standalone Function Default Templates', function () { + test('uses default template type string when template T is unbound', function () { + expect(testDefaultTemplateString('hello'))->toBe('hello'); - expect(fn () => testDefaultTemplateString(12345)) - ->toThrow(TypeError::class, 'Return value') - ; + expect(fn () => testDefaultTemplateString(12345)) + ->toThrow(TypeError::class, 'Return value') + ; + }); + + test('uses default template type stdClass when template has both bound and default', function () { + $std = new stdClass(); + expect(testDefaultTemplateObject($std))->toBe($std); + + // Dog is an object (satisfies bound 'object'), but NOT stdClass (violates default 'stdClass') + expect(fn () => testDefaultTemplateObject(new Dog())) + ->toThrow(TypeError::class, 'Return value') + ; + }); }); - test('uses default template type stdClass when template has both bound and default', function () { - $std = new stdClass(); - expect(testDefaultTemplateObject($std))->toBe($std); + describe('2. Unannotated Class Instantiation with Default Template (@template T = int)', function () { + test('records default template type on unannotated instance in getGenericTypes and getGenericType', function () { + $box = new DefaultIntBox(); + + expect(TypePHP::getGenericTypes($box))->toBe(['T' => 'int']) + ->and(TypePHP::getGenericType($box))->toBe('int') + ; + }); + + test('enforces default template type on method calls and property mutations for unannotated instance', function () { + $freshBox = new DefaultIntBox(); + + // Must reject string even on the very first method call before any valid int is added! + expect(fn () => $freshBox->add('not_an_int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + + $box = new DefaultIntBox(); + $box->add(42); + expect($box->items)->toBe([42]); + + expect(fn () => $box->add('not_an_int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + + expect(function () use ($box) { + $box->items[] = 'not_an_int'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + + test('allows @var annotation to override the default template type', function () { + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + + expect(TypePHP::getGenericTypes($stringBox))->toBe(['T' => 'string']) + ->and(TypePHP::getGenericType($stringBox))->toBe('string') + ; + + $stringBox->add('hello'); + expect($stringBox->items)->toBe(['hello']); + + expect(fn () => $stringBox->add(42)) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + }); + + describe('3. Constructor Inference vs Default Template Fallback', function () { + test('falls back to default T = int when constructor is called with no arguments', function () { + $box = new DefaultBoxWithCtor(); + + expect(TypePHP::getGenericTypes($box))->toBe(['T' => 'int']); + + $box->set(100); + expect($box->value)->toBe(100); + + expect(fn () => $box->set('wrong')) + ->toThrow(TypeError::class, 'must be of type int') + ; + }); + + test('overrides default T = int when constructor argument infers T = string', function () { + $box = new DefaultBoxWithCtor('initial_string'); + + expect(TypePHP::getGenericTypes($box))->toBe(['T' => 'string']); + + $box->set('updated_string'); + expect($box->value)->toBe('updated_string'); + + expect(fn () => $box->set(100)) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + }); + + describe('4. Partial Defaults on Multi-Template Classes', function () { + test('records K = string default on instantiation and infers V on first method call', function () { + $map = new PartialDefaultMap(); + + expect(TypePHP::getGenericTypes($map))->toBe(['K' => 'string']); + + // Key must already be enforced as string even on the first call! + expect(fn () => $map->put(123, 'value')) + ->toThrow(TypeError::class, 'must be of type string') + ; + + $map->put('first_key', 42); + + expect(TypePHP::getGenericTypes($map))->toBe([ + 'K' => 'string', + 'V' => 'int', + ]); + + expect(fn () => $map->put('second_key', 'not_an_int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + }); + }); + + describe('5. Conditional Types with Default Templates (T is Target ? A : B)', function () { + test('evaluates true branch (positive-int) on standalone function when T falls back to default int', function () { + expect(testDefaultTemplateConditionalReturn(null, 42))->toBe(42); + + expect(fn () => testDefaultTemplateConditionalReturn(null, -10)) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => testDefaultTemplateConditionalReturn(null, 'string_val')) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('evaluates else branch (non-empty-string) on standalone function when T is overridden to string', function () { + expect(testDefaultTemplateConditionalReturn('override', 'valid_string'))->toBe('valid_string'); + + expect(fn () => testDefaultTemplateConditionalReturn('override', '')) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + + test('evaluates conditional parameter using default T = int when sample is omitted', function () { + expect(testDefaultTemplateConditionalParam(42))->toBe(42); + + expect(fn () => testDefaultTemplateConditionalParam(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => testDefaultTemplateConditionalParam('not_int')) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('evaluates conditional return on zero-parameter class methods using class default T = int', function () { + $box = new DefaultIntBox(); + + expect($box->computeOne())->toBe(42); + + expect(fn () => $box->computeInvalidNegative()) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect($box->getDefaultConditionalValue(100))->toBe(100); + + expect(fn () => $box->getDefaultConditionalValue(-50)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('evaluates else branch on class conditional return when default is overridden via @var DefaultIntBox', function () { + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + + expect($stringBox->getDefaultConditionalValue('hello'))->toBe('hello'); + + expect(fn () => $stringBox->getDefaultConditionalValue('')) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + }); + + describe('6. @param-out with Default Templates & Conditional @param-out', function () { + test('enforces default T = int on @param-out T $out for unannotated class instance', function () { + $box = new DefaultIntBox(); + $out = null; + + $box->exportTo($out, 99); + expect($out)->toBe(99); + + expect(fn () => $box->exportTo($out, 'not_an_int')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type int') + ; + }); + + test('enforces overridden T = string on @param-out T $out when pre-bound via @var', function () { + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + $out = null; + + $stringBox->exportTo($out, 'valid_str'); + expect($out)->toBe('valid_str'); + + expect(fn () => $stringBox->exportTo($out, 12345)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type string') + ; + }); + + test('enforces conditional @param-out (T is int ? positive-int : non-empty-string) on class method', function () { + $box = new DefaultIntBox(); + $out = null; + + $box->exportConditionalTo($out, 50); + expect($out)->toBe(50); + + expect(fn () => $box->exportConditionalTo($out, -20)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; + + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + $stringBox->exportConditionalTo($out, 'active'); + expect($out)->toBe('active'); + + expect(fn () => $stringBox->exportConditionalTo($out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; + }); + + test('enforces conditional @param-out on standalone function with default T = int', function () { + $out = null; + + testDefaultTemplateConditionalParamOut($out, 100); + expect($out)->toBe(100); + + expect(fn () => testDefaultTemplateConditionalParamOut($out, -5)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; + + testDefaultTemplateConditionalParamOut($out, 'hello', 'sample_str'); + expect($out)->toBe('hello'); + + expect(fn () => testDefaultTemplateConditionalParamOut($out, '', 'sample_str')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; + }); + }); + + describe('7. TemplateManager Consistency on Unannotated Instances & Static Classes', function () { + test('getBoundTemplates, isBound, and getBoundType return default T = int on unannotated instance with 0-arg method', function () { + $box = new DefaultIntBox(); + $templates = ['T' => new PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode('T', null, '', new PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('int'))]; + + $bound = \TypePHP\Internal\Generics\TemplateManager::getBoundTemplates(DefaultIntBox::class . '::computeOne', $box, $templates); + expect($bound)->toHaveKey('T') + ->and((string) $bound['T'])->toBe('int') + ; + + expect(\TypePHP\Internal\Generics\TemplateManager::isBound(DefaultIntBox::class . '::computeOne', $box, 'T'))->toBeTrue() + ->and((string) \TypePHP\Internal\Generics\TemplateManager::getBoundType(DefaultIntBox::class . '::computeOne', $box, 'T'))->toBe('int') + ; + }); + + test('enforces default template T = int on static method parameters and return types', function () { + expect(fn () => DefaultStaticClassHolder::checkDefaultParam('wrong_type')) + ->toThrow(TypeError::class, 'must be of type int') + ; + + expect(DefaultStaticClassHolder::checkDefaultParam(42))->toBe(42); + + expect(fn () => DefaultStaticClassHolder::getDefault()) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; + }); + + test('preserves default T = int across 0-argument @self-out method call', function () { + $holder = new DefaultTypestateZeroArgHolder(); + + $holder->enableString(); + + expect(TypePHP::getGenericType($holder))->toBe('(int | string)'); + + $holder->set(42); + $holder->set('now_allowed_string'); - // Dog is an object (satisfies bound 'object'), but NOT stdClass (violates default 'stdClass') - expect(fn () => testDefaultTemplateObject(new Dog())) - ->toThrow(TypeError::class, 'Return value') - ; + expect(fn () => $holder->set(new stdClass())) + ->toThrow(TypeError::class, 'must be of type (int | string)') + ; + }); }); }); diff --git a/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php b/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php index 2d879346..7c0dcf7f 100644 --- a/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php +++ b/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php @@ -4,6 +4,7 @@ namespace TypePHP\Tests\TypeChecking\Generics; +use Closure; use TypePHP\Exception\TypeError; /** @@ -57,6 +58,21 @@ public function __construct(public int $v) } } +/** + * Unbounded generic holder to test F-bound inference from generic objects + * + * @template T + */ +final class FBoundHolder +{ + /** + * @param T $item + */ + public function __construct(public mixed $item) + { + } +} + /** * Raw min without docblock contract */ @@ -81,6 +97,54 @@ function fBoundMin(FBoundComparable $a, FBoundComparable $b): FBoundComparable return $a->compareTo($b) <= 0 ? $a : $b; } +/** + * F-Bounded template inside a generic list parameter + * + * @template T of FBoundComparable + * + * @param list $items + */ +function fBoundAcceptList(array $items): bool +{ + return true; +} + +/** + * F-Bounded template inside an array shape parameter + * + * @template T of FBoundComparable + * + * @param array{item: T} $payload + */ +function fBoundAcceptShape(array $payload): bool +{ + return true; +} + +/** + * F-Bounded template inferred from a Closure parameter typehint + * + * @template T of FBoundComparable + * + * @param Closure(T): int $callback + */ +function fBoundAcceptClosure(Closure $callback): bool +{ + return true; +} + +/** + * F-Bounded template inferred from a Generic Object parameter + * + * @template T of FBoundComparable + * + * @param FBoundHolder $holder + */ +function fBoundAcceptHolder(FBoundHolder $holder): bool +{ + return true; +} + /** * C#: class AGenericClass where T : IComparable * @@ -268,4 +332,38 @@ public function compareTo(mixed $other): int ); }); }); + + describe('4. F-Bounds in Compound Parameter Types (Lists, Shapes, Closures & Generic Objects)', function () { + test('accepts valid FBoundNum and rejects FBoundRogue inside list parameter', function () { + expect(fBoundAcceptList([new FBoundNum(1), new FBoundNum(2)]))->toBeTrue(); + + expect(fn () => fBoundAcceptList([new FBoundRogue()])) + ->toThrow(TypeError::class) + ; + }); + + test('accepts valid FBoundNum and rejects FBoundRogue inside array shape parameter', function () { + expect(fBoundAcceptShape(['item' => new FBoundNum(10)]))->toBeTrue(); + + expect(fn () => fBoundAcceptShape(['item' => new FBoundRogue()])) + ->toThrow(TypeError::class) + ; + }); + + test('accepts valid FBoundNum and rejects FBoundRogue in Closure(T) parameter typehint', function () { + expect(fBoundAcceptClosure(fn (FBoundNum $n): int => $n->value))->toBeTrue(); + + expect(fn () => fBoundAcceptClosure(fn (FBoundRogue $r): int => $r->id)) + ->toThrow(TypeError::class) + ; + }); + + test('accepts valid FBoundNum and rejects FBoundRogue inside Generic Object FBoundHolder parameter', function () { + expect(fBoundAcceptHolder(new FBoundHolder(new FBoundNum(5))))->toBeTrue(); + + expect(fn () => fBoundAcceptHolder(new FBoundHolder(new FBoundRogue()))) + ->toThrow(TypeError::class) + ; + }); + }); });