diff --git a/README.md b/README.md index be2ec2d2..69c8ce54 100644 --- a/README.md +++ b/README.md @@ -284,7 +284,7 @@ All the documentation lives on the **[typephp.dev](https://typephp.dev/)** websi TypePHP stands on the shoulders of giants. It simply would not exist without two foundational cornerstones of the PHP ecosystem: * **[PHPStan](https://phpstan.org/) & [`phpstan/phpdoc-parser`](https://github.com/phpstan/phpdoc-parser)** (created by [Ondřej Mirtes](https://github.com/ondrejmirtes) and contributors): - A massive and sincere debt of gratitude is owed to the PHPStan team. Beyond establishing the modern type standard in PHP, `phpstan/phpdoc-parser` is the parsing powerhouse behind TypePHP. It enables TypePHP to tokenize, parse, and evaluate complex type theory—including reified generics (`@template`), conditional types, intersection/union types, DNF, array shapes, and variance—directly at runtime. + A massive and sincere debt of gratitude is owed to the PHPStan team. Beyond establishing the modern type standard in PHP, `phpstan/phpdoc-parser` is the parsing powerhouse behind TypePHP. It enables TypePHP to tokenize, parse, and evaluate complex type theory and including reified generics (`@template`), conditional types, intersection/union types, DNF, array shapes, and variance—directly at runtime. * **[`nikic/php-parser`](https://github.com/nikic/PHP-Parser)** (created by [Nikita Popov](https://github.com/nikic)): The gold standard for PHP abstract syntax tree (AST) parsing and code manipulation. It powers TypePHP's transparent stream wrapper interception, format-preserving AST transformations, and zero line-drift instrumentation. diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php index d0e20799..b23413e5 100644 --- a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -77,7 +77,7 @@ public static function isReturnEliminationSafe( } if ($returnTypeNode instanceof GenericTypeNode) { - $baseName = strtolower($returnTypeNode->type->name); + $baseName = strtolower((string) $returnTypeNode->type); if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) { return false; } @@ -114,7 +114,7 @@ public static function isGeneratorEliminationSafe( } if ($returnTypeNode instanceof GenericTypeNode) { - $baseName = strtolower(ltrim($returnTypeNode->type->name, '\\')); + $baseName = strtolower(ltrim((string) $returnTypeNode->type, '\\')); if (! isset(self::PERMISSIBLE_GENERATOR_GENERICS[$baseName])) { return false; } diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index f4aed5b7..0062d0ce 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -102,7 +102,7 @@ public static function satisfiesEmptyArray(TypeNode $typeNode): bool } if ($typeNode instanceof GenericTypeNode) { - return isset(self::EMPTY_ARRAY_ALLOWED_GENERICS[strtolower($typeNode->type->name)]); + return isset(self::EMPTY_ARRAY_ALLOWED_GENERICS[strtolower((string) $typeNode->type)]); } if ($typeNode instanceof ArrayShapeNode) { @@ -141,7 +141,7 @@ private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTy */ private static function satisfiesGenericArray(Array_ $arrayExpr, GenericTypeNode $node, string $currentFile): bool { - $base = strtolower($node->type->name); + $base = strtolower((string) $node->type); $genericCount = \count($node->genericTypes); if ($base === 'list' && $genericCount >= 1) { diff --git a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php index 72cd8972..76079cf7 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php @@ -83,7 +83,7 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty return $targetClassName === $typeNode->name; } - if ($typeNode instanceof GenericTypeNode && strtolower($typeNode->type->name) === 'int-mask-of') { + if ($typeNode instanceof GenericTypeNode && strtolower((string) $typeNode->type) === 'int-mask-of') { $inner = $typeNode->genericTypes[0] ?? null; if ($inner instanceof ConstTypeNode && $inner->constExpr instanceof ConstFetchNode) { return self::matchesWildcard($constName, $inner->constExpr->name); @@ -98,7 +98,7 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty */ private static function satisfiesBitwiseOr(BitwiseOr $expr, TypeNode $typeNode, string $currentFile): bool { - if (! ($typeNode instanceof GenericTypeNode) || strtolower($typeNode->type->name) !== 'int-mask-of') { + if (! ($typeNode instanceof GenericTypeNode) || strtolower((string) $typeNode->type) !== 'int-mask-of') { return false; } @@ -119,7 +119,7 @@ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode return false; } - if (! ($typeNode instanceof GenericTypeNode) || strtolower($typeNode->type->name) !== 'value-of') { + if (! ($typeNode instanceof GenericTypeNode) || strtolower((string) $typeNode->type) !== 'value-of') { return false; } diff --git a/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php index 205abb9b..82edffa8 100644 --- a/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php @@ -70,7 +70,7 @@ public static function extractContract(TypeNode $returnTypeNode): ?array } if ($returnTypeNode instanceof GenericTypeNode) { - $base = strtolower(ltrim($returnTypeNode->type->name, '\\')); + $base = strtolower(ltrim((string) $returnTypeNode->type, '\\')); if (! isset(self::GENERATOR_ROOT_TYPES[$base])) { return null; } diff --git a/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php index 11c91d97..e1c3227e 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php @@ -171,7 +171,7 @@ private static function satisfiesInteger(int $value, TypeNode $typeNode): bool } if ($typeNode instanceof GenericTypeNode) { - $base = strtolower($typeNode->type->name); + $base = strtolower((string) $typeNode->type); if ($base === 'int' || $base === 'integer') { return self::satisfiesIntRange($value, $typeNode); diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index dfab34b9..ddd22382 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -66,7 +66,7 @@ public static function satisfies(Expr $expr, TypeNode $typeNode, string $current } if ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower($typeNode->type->name); + $baseName = strtolower((string) $typeNode->type); if (! isset(self::PERMISSIBLE_GENERIC_CONTAINERS[$baseName])) { return false; } diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index e5019f13..a7fdad3a 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -165,7 +165,10 @@ public static function inject( $classContext, $returnTypeNode, $currentFile, - $hasMethodTemplates + $hasMethodTemplates, + $needsReturnVars, + $hasParamOut ? $byRefParams : [], + $hasSelfOut ) : self::wrapNonGeneratorReturns( $node->stmts, @@ -485,7 +488,7 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b ] ); - $throwStmt = self::buildTypeErrorThrowStmt(new Node\Expr\Variable('__typephpErr')); + $throwStmt = self::buildTypeErrorThrowStmt(new Node\Expr\Variable('__typephpScope')); $cacheKeyExpr = new Node\Scalar\MagicConst\Method(); $noParamFetch = new Node\Expr\StaticPropertyFetch( @@ -525,7 +528,7 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b 'stmts' => [ new Node\Stmt\If_( new Node\Expr\Instanceof_( - new Node\Expr\Assign(new Node\Expr\Variable('__typephpErr'), $checkCall), + new Node\Expr\Assign(new Node\Expr\Variable('__typephpScope'), $checkCall), new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage') ), ['stmts' => [$throwStmt]] @@ -788,11 +791,49 @@ public static function buildTernaryReturnExpr(Node\Expr\FuncCall $checkCall, ?in ); } + /** + * @param array $byRefParamNames + */ + public static function buildParamOutGuardExpr( + array $byRefParamNames, + Node\Expr $innerExpr, + Node\Expr $thisArg, + ?int $line = null + ): Node\Expr { + $expr = $innerExpr; + foreach (array_reverse($byRefParamNames) as $pName) { + $checkCall = new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkParamOut'), + [ + new Node\Arg(new Node\Scalar\MagicConst\Method()), + new Node\Arg(new Node\Scalar\String_($pName)), + new Node\Arg(new Node\Expr\Variable($pName)), + new Node\Arg($thisArg), + ] + ); + + $expr = new Node\Expr\Ternary( + new Node\Expr\Instanceof_( + new Node\Expr\Assign(new Node\Expr\Variable('__typephpErr'), $checkCall), + new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage') + ), + self::buildTypeErrorThrowExpr(new Node\Expr\Variable('__typephpErr'), $line), + $expr + ); + } + + return $expr; + } + + /** + * @param array $byRefParams + */ public static function buildWrappedYieldNode( Node\Expr\Yield_ $n, Node\Expr $thisArg, bool $wrapYield = true, - bool $wrapSend = true + bool $wrapSend = true, + array $byRefParams = [] ): Node\Expr { if ($wrapYield) { $checkYieldCall = new Node\Expr\FuncCall( @@ -815,6 +856,11 @@ 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()); + } + if (! $wrapSend) { return $n; } @@ -841,6 +887,7 @@ public static function buildWrappedYieldNode( /** * @param array $stmts * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext + * @param array $byRefParams * * @return array */ @@ -851,7 +898,10 @@ private static function wrapGeneratorReturns( ?array $classContext = null, ?TypeNode $returnTypeNode = null, string $currentFile = '', - bool $hasMethodTemplates = false + bool $hasMethodTemplates = false, + bool $needsReturnVars = false, + array $byRefParams = [], + bool $hasSelfOut = false ): array { $canEliminate = $functionNode !== null && ! $hasMethodTemplates @@ -867,18 +917,29 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ($thisArg, $genContract, $currentFile) extends NodeVisitorAbstract { + $traverser->addVisitor(new class ( + $thisArg, + $genContract, + $currentFile, + $needsReturnVars, + $byRefParams, + $hasSelfOut + ) extends NodeVisitorAbstract { /** * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract + * @param array $byRefParams */ public function __construct( private Node\Expr $thisArg, private ?array $genContract, - private string $currentFile + private string $currentFile, + private bool $needsReturnVars, + private array $byRefParams, + private bool $hasSelfOut ) { } - public function enterNode(Node $n): int|Node|null + public function enterNode(Node $n): int|Node|array|null { if ($n instanceof Node\Expr\Closure || $n instanceof Node\Expr\ArrowFunction || $n instanceof Node\Stmt\Function_ || $n instanceof Node\Stmt\ClassMethod) { return NodeTraverser::DONT_TRAVERSE_CHILDREN; @@ -926,11 +987,11 @@ public function enterNode(Node $n): int|Node|null $wrapSend = $this->genContract === null || ! GeneratorEvaluator::canEliminateSend($this->genContract['send']); - if (! $wrapYield && ! $wrapSend) { + if (! $wrapYield && ! $wrapSend && $this->byRefParams === []) { return null; } - return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend); + return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend, $this->byRefParams); } if ($n instanceof Node\Expr\YieldFrom) { @@ -939,27 +1000,36 @@ public function enterNode(Node $n): int|Node|null } $n->setAttribute('typephp_wrapped', true); - if ( - $this->genContract !== null + $canEliminateYieldFrom = $this->genContract !== null && GeneratorEvaluator::canEliminateYieldFrom( $n, $this->genContract['key'], $this->genContract['value'], $this->currentFile - ) - ) { - return null; + ); + + if (! $canEliminateYieldFrom) { + $n->expr = new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::wrapIterable'), + [ + new Node\Arg(new Node\Scalar\MagicConst\Method()), + new Node\Arg(new Node\Scalar\String_('return')), + new Node\Arg($n->expr), + new Node\Arg($this->thisArg), + ] + ); } - $n->expr = new Node\Expr\FuncCall( - new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::wrapIterable'), - [ - new Node\Arg(new Node\Scalar\MagicConst\Method()), - new Node\Arg(new Node\Scalar\String_('return')), - new Node\Arg($n->expr), - new Node\Arg($this->thisArg), - ] - ); + if ($this->byRefParams !== []) { + $n->expr = FunctionContractInjector::buildParamOutGuardExpr( + $this->byRefParams, + $n->expr, + $this->thisArg, + $n->getStartLine() + ); + } + + return null; } if ($n instanceof Node\Stmt\Return_) { @@ -968,6 +1038,19 @@ public function enterNode(Node $n): int|Node|null } $n->setAttribute('typephp_generator_return_wrapped', true); + $exitStmts = []; + if ($this->hasSelfOut) { + $exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars); + } + + $paramOutStmts = $this->byRefParams !== [] + ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg) + : []; + + if ($paramOutStmts !== []) { + $exitStmts = [...$exitStmts, ...$paramOutStmts]; + } + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; @@ -980,7 +1063,7 @@ public function enterNode(Node $n): int|Node|null $this->currentFile ) ) { - return $n; + return $exitStmts !== [] ? [...$exitStmts, $n] : $n; } $checkCall = new Node\Expr\FuncCall( @@ -994,7 +1077,7 @@ public function enterNode(Node $n): int|Node|null $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $n->getStartLine()); - return $n; + return $exitStmts !== [] ? [...$exitStmts, $n] : $n; } return null; @@ -1006,6 +1089,23 @@ public function enterNode(Node $n): int|Node|null $lastStmt = end($newStmts); if (! $lastStmt instanceof Node\Stmt\Return_ && ! ($lastStmt instanceof Node\Stmt\Expression && $lastStmt->expr instanceof Node\Expr\Throw_)) { + $exitStmts = []; + if ($hasSelfOut) { + $exitStmts[] = self::buildSelfOutCheckStmt($thisArg, $needsReturnVars); + } + + $paramOutStmts = $byRefParams !== [] + ? self::buildParamOutCheckStmts($byRefParams, $thisArg) + : []; + + if ($paramOutStmts !== []) { + $exitStmts = [...$exitStmts, ...$paramOutStmts]; + } + + if ($exitStmts !== []) { + $newStmts = [...$newStmts, ...$exitStmts]; + } + if ( $genContract === null || ! GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile) diff --git a/src/Internal/Ast/TypeDeducer.php b/src/Internal/Ast/TypeDeducer.php index 9c8c2fb8..6e5f61ce 100644 --- a/src/Internal/Ast/TypeDeducer.php +++ b/src/Internal/Ast/TypeDeducer.php @@ -54,7 +54,7 @@ public static function deduceElementType(string $typeString): ?string } if ($typeNode instanceof GenericTypeNode) { - $base = strtolower($typeNode->type->name); + $base = strtolower((string) $typeNode->type); $count = \count($typeNode->genericTypes); if (\in_array($base, ['list', 'non-empty-list'], true) && $count >= 1) { @@ -101,7 +101,7 @@ public static function deduceKeyType(string $typeString): string } if ($typeNode instanceof GenericTypeNode) { - $base = strtolower($typeNode->type->name); + $base = strtolower((string) $typeNode->type); $count = \count($typeNode->genericTypes); if (\in_array($base, ['list', 'non-empty-list'], true)) { diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 4794a4c9..5b719f9c 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -185,7 +185,7 @@ public static function checkVariable( $context = ($varName === 'return') ? 'Return value' : "Variable \$$varName"; if ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower($typeNode->type->name); + $baseName = strtolower((string) $typeNode->type); $isCollection = isset(self::ARRAY_TYPES[$baseName]); if (! $isCollection) { @@ -256,7 +256,7 @@ public static function validateCollectionElementMutation( $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); if ($typeNode instanceof GenericTypeNode) { - $base = strtolower($typeNode->type->name); + $base = strtolower((string) $typeNode->type); if ($base === 'list' || $base === 'non-empty-list') { if ($key !== null && ! \is_int($key)) { @@ -346,7 +346,7 @@ private static function wrapShapeCallables(ArrayShapeNode $shapeNode, array $val private static function wrapCollectionCallables(TypeNode $typeNode, array $value, string $context, TypeValidatorRegistry $registry): array { $innerCallable = null; - if ($typeNode instanceof GenericTypeNode && \in_array(strtolower($typeNode->type->name), ['list', 'array', 'iterable'], true)) { + if ($typeNode instanceof GenericTypeNode && \in_array(strtolower((string) $typeNode->type), ['list', 'array', 'iterable'], true)) { $innerCallable = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null; } elseif ($typeNode instanceof ArrayTypeNode) { $innerCallable = $typeNode->type; @@ -971,7 +971,7 @@ private static function shouldValidateType(TypeNode $node): bool } if ($node instanceof GenericTypeNode) { - $lower = strtolower($node->type->name); + $lower = strtolower((string) $node->type); if (isset(self::ARRAY_TYPES[$lower])) { return $checkArrays; } diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index e75f1e79..39e21f51 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -583,8 +583,8 @@ private static function inferTemplatesFromClosures( $closureParams = $refClosure->getParameters(); foreach ($cTypeNode->parameters as $idx => $pNode) { - if ($pNode->type instanceof IdentifierTypeNode && isset($templates[$pNode->type->name]) && isset($closureParams[$idx])) { - $tName = $pNode->type->name; + if ($pNode->type instanceof IdentifierTypeNode && isset($templates[(string) $pNode->type]) && isset($closureParams[$idx])) { + $tName = (string) $pNode->type; $isClassLevel = ! TemplateManager::isMethodTemplate($effectiveFunction, $tName) && isset($classTemplates[$tName]); $targetObj = $isClassLevel ? $thisObj : null; @@ -822,7 +822,7 @@ private static function inferTemplateFromTypeAndValue( } if ($typeNode instanceof GenericTypeNode) { - $baseType = strtolower($typeNode->type->name); + $baseType = strtolower((string) $typeNode->type); if (isset(self::ITERABLE_TYPES[$baseType]) && \is_array($value)) { self::inferArrayTemplatesFromAllElements($typeNode, $value, $effectiveFunction, $thisObj, $templates); } elseif (\is_object($value)) { @@ -856,7 +856,7 @@ private static function inferArrayTemplatesFromAllElements( } if ($typeNode instanceof GenericTypeNode) { - $baseType = strtolower($typeNode->type->name); + $baseType = strtolower((string) $typeNode->type); if (! isset(self::ITERABLE_TYPES[$baseType])) { return; } @@ -1021,7 +1021,7 @@ private static function inferGenericObjectNode( } if ($typeNode instanceof GenericTypeNode && \is_object($value)) { - $baseName = strtolower($typeNode->type->name); + $baseName = strtolower((string) $typeNode->type); if (isset(self::COLLECTION_TYPES[$baseName])) { return; } @@ -1031,7 +1031,7 @@ private static function inferGenericObjectNode( return; } - $targetClassFqcn = SpecialTypeResolver::resolveFqcn($typeNode->type->name, new \ReflectionClass($value)); + $targetClassFqcn = SpecialTypeResolver::resolveFqcn((string) $typeNode->type, new \ReflectionClass($value)); $targetTemplateNames = self::$classDeclaredTemplateNamesCache[$targetClassFqcn] ?? null; if ($targetTemplateNames === null) { @@ -1089,7 +1089,7 @@ private static function inferGenericObjectNode( if ($typeNode instanceof ArrayTypeNode) { $innerType = $typeNode->type; } elseif ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower($typeNode->type->name); + $baseName = strtolower((string) $typeNode->type); if (isset(self::COLLECTION_TYPES[$baseName])) { $innerType = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null; } @@ -1276,7 +1276,7 @@ private static function isClassStringTemplate(GenericTypeNode $typeNode, array $ { return isset($typeNode->genericTypes[0]) && $typeNode->genericTypes[0] instanceof IdentifierTypeNode - && strtolower($typeNode->type->name) === 'class-string' + && strtolower((string) $typeNode->type) === 'class-string' && isset($templates[$typeNode->genericTypes[0]->name]); } @@ -1386,12 +1386,12 @@ private static function getTemplateName(TypeNode $typeNode, array $templates): ? return $typeNode->name; } - if ($typeNode instanceof NullableTypeNode && $typeNode->type instanceof IdentifierTypeNode && isset($templates[$typeNode->type->name])) { - return $typeNode->type->name; + if ($typeNode instanceof NullableTypeNode && $typeNode->type instanceof IdentifierTypeNode && isset($templates[(string) $typeNode->type])) { + return (string) $typeNode->type; } - if ($typeNode instanceof ArrayTypeNode && $typeNode->type instanceof IdentifierTypeNode && isset($templates[$typeNode->type->name])) { - return $typeNode->type->name; + if ($typeNode instanceof ArrayTypeNode && $typeNode->type instanceof IdentifierTypeNode && isset($templates[(string) $typeNode->type])) { + return (string) $typeNode->type; } if ($typeNode instanceof UnionTypeNode && \count($typeNode->types) === 2) { diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index b6eb0002..e20b6266 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -256,7 +256,7 @@ private static function handleMagicPropertyRead( if ($typeNode instanceof IdentifierTypeNode) { $baseName = strtolower(ltrim($typeNode->name, '\\')); } elseif ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower(ltrim($typeNode->type->name, '\\')); + $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); } if (isset(self::GENERIC_ITERABLES[$baseName])) { @@ -375,7 +375,7 @@ private static function evaluateReturn( if ($resolvedType instanceof IdentifierTypeNode) { $baseName = strtolower(ltrim($resolvedType->name, '\\')); } elseif ($resolvedType instanceof GenericTypeNode) { - $baseName = strtolower(ltrim($resolvedType->type->name, '\\')); + $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); } if (isset(self::GENERIC_ITERABLES[$baseName])) { @@ -458,7 +458,7 @@ private static function evaluateReturn( if ($resolvedType instanceof IdentifierTypeNode) { $baseName = strtolower(ltrim($resolvedType->name, '\\')); } elseif ($resolvedType instanceof GenericTypeNode) { - $baseName = strtolower(ltrim($resolvedType->type->name, '\\')); + $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); } if (isset(self::GENERIC_ITERABLES[$baseName])) { diff --git a/src/Internal/Docblock/DocblockExtractor.php b/src/Internal/Docblock/DocblockExtractor.php index 6560fadd..9c42229c 100644 --- a/src/Internal/Docblock/DocblockExtractor.php +++ b/src/Internal/Docblock/DocblockExtractor.php @@ -588,7 +588,7 @@ public static function extractAliases( $localName = $importTag->importedAs ?? $importTag->importedAlias; if (! isset($aliases[$localName])) { - $fqcnSource = SpecialTypeResolver::resolveFqcn($importTag->importedFrom->name, $ref); + $fqcnSource = SpecialTypeResolver::resolveFqcn((string) $importTag->importedFrom, $ref); $resolvedType = self::resolveImportedTypeAlias($fqcnSource, $importTag->importedAlias); if ($resolvedType !== null) { $aliases[$localName] = $resolvedType; @@ -651,7 +651,7 @@ public static function resolveImportedTypeAlias(string $fqcn, string $importedAl $importTag = $tag->value; $localName = $importTag->importedAs ?? $importTag->importedAlias; if ($localName === $importedAlias) { - $fqcn = SpecialTypeResolver::resolveFqcn($importTag->importedFrom->name, $ref); + $fqcn = SpecialTypeResolver::resolveFqcn((string) $importTag->importedFrom, $ref); $importedAlias = $importTag->importedAlias; $nextFound = true; diff --git a/src/Internal/Docblock/DocblockNormalizer.php b/src/Internal/Docblock/DocblockNormalizer.php index 9ad579b8..76a30f3e 100644 --- a/src/Internal/Docblock/DocblockNormalizer.php +++ b/src/Internal/Docblock/DocblockNormalizer.php @@ -36,6 +36,28 @@ public static function normalize(string $doc): string return $doc; } + if (substr_count($doc, '@') > 1) { + $doc = preg_replace_callback( + '/(?:\/\*\*|^\s*\*)\s*@[a-zA-Z0-9_-]+[^\r\n]*/m', + static function (array $matches): string { + return preg_replace( + '/([^\r\n*\/ \t])[ \t]+(@(?:phpstan-|psalm-|template-)?(?:param-out|param|return|var|template(?:-covariant|-contravariant)?|self-out|this-out|type|import-type|extends|implements|use|property(?:-read|-write)?|method)\b)/', + "$1\n * $2", + $matches[0] + ) ?? $matches[0]; + }, + $doc + ) ?? $doc; + } + + if (str_contains($doc, 'param-out') && str_contains($doc, '&')) { + $doc = preg_replace( + '/(@(?:phpstan-|psalm-)?param-out\s+[^\r\n]+?)\s*&\s*(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)(?=\s|$|\*\/)/', + '$1 $2', + $doc + ) ?? $doc; + } + if (str_contains($doc, '-type') && str_contains($doc, '=')) { $doc = preg_replace('/(@(?:phpstan|psalm)-type\s+[a-zA-Z0-9_\x80-\xff]+)\s*=\s*/', '$1 ', $doc) ?? $doc; } diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index a7eb5506..e42800b9 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -200,7 +200,7 @@ public static function typeReferencesTemplate(?TypeNode $node, array $templateNa } if ($node instanceof GenericTypeNode) { - if (isset($templateNames[$node->type->name])) { + if (isset($templateNames[(string) $node->type])) { return true; } foreach ($node->genericTypes as $gt) { @@ -1674,7 +1674,7 @@ private static function wrapVariadicParameterType( if ( ! ($type instanceof ArrayTypeNode) - && ! ($type instanceof GenericTypeNode && \in_array(strtolower($type->type->name), ['array', 'list', 'iterable', 'traversable', 'non-empty-array', 'non-empty-list'], true)) + && ! ($type instanceof GenericTypeNode && \in_array(strtolower((string) $type->type), ['array', 'list', 'iterable', 'traversable', 'non-empty-array', 'non-empty-list'], true)) ) { return new ArrayTypeNode($type); } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 2ec53725..8115e527 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -867,7 +867,7 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ */ public static function bindInstanceFromNode(object $instance, GenericTypeNode $typeNode, string $context = '', bool $forceBind = false): ?ErrorMessage { - $className = $typeNode->type->name; + $className = (string) $typeNode->type; if (isset(self::CONTEXT_SELF_REFERENCES[strtolower($className)])) { $className = $instance::class; } @@ -1172,7 +1172,7 @@ private static function collectInheritedGenericTagBindings( string $actualClassName, array &$bindings ): void { - $parentName = SpecialTypeResolver::resolveFqcn($genericTypeNode->type->name, $hierClass); + $parentName = SpecialTypeResolver::resolveFqcn((string) $genericTypeNode->type, $hierClass); $isHierarchyMember = is_a($actualClassName, $parentName, true) || trait_exists($parentName); if (! ClassNameValidator::isValid($parentName) || ! $isHierarchyMember) { @@ -1340,7 +1340,7 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return $lowerExpected === 'array' || $lowerExpected === 'iterable'; } - if ($existing instanceof GenericTypeNode && isset($allowedSubtypes[strtolower($existing->type->name)])) { + if ($existing instanceof GenericTypeNode && isset($allowedSubtypes[strtolower((string) $existing->type)])) { return true; } } @@ -1388,7 +1388,7 @@ private static function checkIdentifierAgainstGenericVariance( GenericTypeNode $expected, string $variance, ): bool { - if (! self::isSubclass($existing->name, $expected->type->name)) { + if (! self::isSubclass($existing->name, (string) $expected->type)) { return false; } @@ -1405,13 +1405,13 @@ private static function checkIdentifierAgainstGenericVariance( try { $classBindings = self::getClassInheritedBindings($existing->name); if ($classBindings !== []) { - $parentTemplates = DocblockParser::parseClassTemplates($expected->type->name); + $parentTemplates = DocblockParser::parseClassTemplates((string) $expected->type); $parentTemplateNames = array_keys($parentTemplates); $declaredVariances = []; - if (class_exists($expected->type->name, false) || class_exists($expected->type->name) || interface_exists($expected->type->name)) { + if (class_exists((string) $expected->type, false) || class_exists((string) $expected->type) || interface_exists((string) $expected->type)) { try { - $ref = new \ReflectionClass($expected->type->name); + $ref = new \ReflectionClass((string) $expected->type); [, $classVariances] = self::collectHierarchyTemplatesAndVariances($ref); $declaredVariances = array_values($classVariances); } catch (\Throwable $e) { @@ -1565,15 +1565,15 @@ private static function checkExistingIntersectionVariance(IntersectionTypeNode $ private static function checkNestedGenericVariance(GenericTypeNode $existing, GenericTypeNode $expected): bool { - $expectedClassName = $expected->type->name; + $expectedClassName = (string) $expected->type; $lowerExpected = strtolower($expectedClassName); if (isset(self::COLLECTION_SUBTYPES[$lowerExpected])) { - $lowerExisting = strtolower($existing->type->name); + $lowerExisting = strtolower((string) $existing->type); if (! isset(self::COLLECTION_SUBTYPES[$lowerExpected][$lowerExisting])) { return false; } - } elseif (! is_a($existing->type->name, $expectedClassName, true)) { + } elseif (! is_a((string) $existing->type, $expectedClassName, true)) { return false; } @@ -1821,11 +1821,11 @@ private static function resolveTypeNodeAst(TypeNode $n, \ReflectionClass $ref): } if ($n instanceof GenericTypeNode) { - $lower = strtolower($n->type->name); + $lower = strtolower((string) $n->type); $baseName = match ($lower) { 'self', 'static', '$this' => $ref->getName(), 'parent' => ($parent = $ref->getParentClass()) !== false ? $parent->getName() : 'parent', - default => SpecialTypeResolver::resolveFqcn($n->type->name, $ref), + default => SpecialTypeResolver::resolveFqcn((string) $n->type, $ref), }; $base = new IdentifierTypeNode($baseName); diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index 54b4bfd1..5a699127 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.0_'; + public const VERSION_PREFIX = 'v0.12.1_'; /** * Cached absolute cache directory path. diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index ba0212a5..80172316 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -739,7 +739,7 @@ private static function resolveCallable(CallableTypeNode $node, \ReflectionClass $resolvedParameters = []; foreach ($node->parameters as $param) { - $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[$param->type->name])) + $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[(string) $param->type])) ? $param->type : self::resolve($param->type, $context, $thisObj); @@ -893,7 +893,7 @@ private static function resolveCallableForFile(CallableTypeNode $node, string $f $resolvedParameters = []; foreach ($node->parameters as $param) { - $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[$param->type->name])) + $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[(string) $param->type])) ? clone $param->type : self::resolveForFile($param->type, $file); diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 28e4c2ad..1792d925 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -192,10 +192,6 @@ public static function checkStaticProperty( return $value; } - if ($className !== '') { - self::$checkedStaticProperties[$className][$propName] = true; - } - $res = self::checkProperty($value, $objectOrClass, $propName, $file); if ($res instanceof ErrorMessage) { $typeError = new \TypePHP\Exception\TypeError($res->getMessage()); @@ -203,6 +199,10 @@ public static function checkStaticProperty( throw ErrorFactory::prepareException($typeError, $line, $file !== '' ? $file : null); } + if ($className !== '') { + self::$checkedStaticProperties[$className][$propName] = true; + } + return $value; } diff --git a/src/Internal/Validator/CallableValidator.php b/src/Internal/Validator/CallableValidator.php index c277bc29..309af4a1 100644 --- a/src/Internal/Validator/CallableValidator.php +++ b/src/Internal/Validator/CallableValidator.php @@ -21,7 +21,7 @@ final class CallableValidator implements TypeValidatorInterface public function validate(mixed $value, TypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { /** @var CallableTypeNode $node */ - $identifierName = strtolower(ltrim($node->identifier->name, '\\')); + $identifierName = strtolower(ltrim((string) $node->identifier, '\\')); if (str_contains($identifierName, 'closure')) { if (! ($value instanceof Closure)) { diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 756c4342..82e714a0 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -82,7 +82,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali { /** @var GenericTypeNode $genericNode */ $genericNode = $node; - $baseType = strtolower($genericNode->type->name); + $baseType = strtolower((string) $genericNode->type); return match ($baseType) { 'int', 'integer' => $this->validateIntRange($value, $genericNode, $context, $isSensitive), @@ -120,7 +120,7 @@ private function validateKeyOf(mixed $value, GenericTypeNode $node, string $cont return null; } - if ($targetType instanceof GenericTypeNode && strtolower($targetType->type->name) === 'value-of') { + if ($targetType instanceof GenericTypeNode && strtolower((string) $targetType->type) === 'value-of') { return $this->validateKeyOfNestedValueOf($value, $targetType, $context, $isSensitive); } @@ -498,7 +498,7 @@ private function resolveMaskOfPattern(string $className, string $pattern): array private function validateList(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { - $baseType = strtolower($node->type->name); + $baseType = strtolower((string) $node->type); if (! \is_array($value) || (\count($value) > 0 && ! array_is_list($value))) { return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); @@ -528,10 +528,10 @@ private function validateList(mixed $value, GenericTypeNode $node, string $conte private function validateArray(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { - $baseType = strtolower($node->type->name); + $baseType = strtolower((string) $node->type); if (! \is_array($value) && ! ($value instanceof \Traversable)) { - return ErrorFactory::createError($context . ' must be of type ' . $node->type->name . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + return ErrorFactory::createError($context . ' must be of type ' . (string) $node->type . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } if (! \is_array($value)) { @@ -602,7 +602,7 @@ private function validateKeyValueTypeArray( return null; } - $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower($valTypeNode->type->name)])); + $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valTypeNode->type)])); if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { $keys = array_keys($value); @@ -805,16 +805,16 @@ private function validateClassStringBound(string $value, TypeNode $targetNode, s private function validateObjectGeneric(mixed $value, GenericTypeNode $node, string $context, bool $isSensitive = false): ?ErrorMessage { - if (! ClassNameValidator::isValid($node->type->name)) { + if (! ClassNameValidator::isValid((string) $node->type)) { return null; } if (! \is_object($value)) { - return ErrorFactory::createError($context . ' must be an object of type ' . $node->type->name . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + return ErrorFactory::createError($context . ' must be an object of type ' . (string) $node->type . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } - if (! is_a($value, $node->type->name)) { - return ErrorFactory::createError($context . ' must be an instance of ' . $node->type->name . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + if (! is_a($value, (string) $node->type)) { + return ErrorFactory::createError($context . ' must be an instance of ' . (string) $node->type . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } return RuntimeTypeChecker::bindInstanceFromNode($value, $node, $context); diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index 9d9176d2..d461624f 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -120,7 +120,7 @@ public static function wrap(string $function, string $paramName, mixed $callable if (\is_array($callable) && $typeNode !== null) { $innerCallableTypeNode = null; - if ($typeNode instanceof GenericTypeNode && \in_array(strtolower($typeNode->type->name), ['list', 'array', 'iterable'], strict: true)) { + if ($typeNode instanceof GenericTypeNode && \in_array(strtolower((string) $typeNode->type), ['list', 'array', 'iterable'], strict: true)) { $innerCallableTypeNode = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null; } elseif ($typeNode instanceof ArrayTypeNode) { $innerCallableTypeNode = $typeNode->type; @@ -159,7 +159,7 @@ public static function wrapTypeNode( return $callable; } - $identifierName = strtolower(ltrim($typeNode->identifier->name, '\\')); + $identifierName = strtolower(ltrim((string) $typeNode->identifier, '\\')); self::enforceClosureConstraints($identifierName, $callable, $prefix); /** @var callable $callable */ @@ -522,7 +522,7 @@ private static function inferLocalTemplateFromParam( } if ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower($typeNode->type->name); + $baseName = strtolower((string) $typeNode->type); if (\in_array($baseName, ['list', 'array', 'iterable'], true) && \is_array($value)) { $innerType = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null; if ($innerType !== null) { diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index c42c209e..bd8fedc4 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -62,7 +62,7 @@ public static function wrap(string $function, string $paramName, mixed $iterable if ($typeNode instanceof IdentifierTypeNode) { $baseName = strtolower(ltrim($typeNode->name, '\\')); } elseif ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower(ltrim($typeNode->type->name, '\\')); + $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); } $standardIterables = ['iterable', 'traversable', 'iterator', 'generator']; diff --git a/src/Internal/Wrapper/IteratorProxy.php b/src/Internal/Wrapper/IteratorProxy.php index c613d498..4e5c4bf2 100644 --- a/src/Internal/Wrapper/IteratorProxy.php +++ b/src/Internal/Wrapper/IteratorProxy.php @@ -24,7 +24,7 @@ final class IteratorProxy implements OuterIterator, Countable * @param \Closure(mixed, mixed): void $typeCheckCallback */ public function __construct( - Traversable $iterable, + private Traversable $iterable, private \Closure $typeCheckCallback ) { $this->inner = self::resolveIterator($iterable); @@ -47,6 +47,10 @@ private static function resolveIterator(Traversable $iterable): Iterator public function rewind(): void { + if ($this->iterable instanceof IteratorAggregate && $this->inner instanceof \Generator) { + $this->inner = self::resolveIterator($this->iterable); + } + $this->inner->rewind(); } @@ -81,6 +85,10 @@ public function getInnerIterator(): Iterator public function count(): int { + if ($this->iterable instanceof Countable) { + return $this->iterable->count(); + } + if ($this->inner instanceof Countable) { return $this->inner->count(); } @@ -93,7 +101,17 @@ public function count(): int */ public function __call(string $method, array $args): mixed { + if (method_exists($this->iterable, $method)) { + // @phpstan-ignore method.dynamicName + return $this->iterable->$method(...$args); + } + + if ($this->inner !== $this->iterable && method_exists($this->inner, $method)) { + // @phpstan-ignore method.dynamicName + return $this->inner->$method(...$args); + } + // @phpstan-ignore method.dynamicName - return $this->inner->$method(...$args); + return $this->iterable->$method(...$args); } } diff --git a/tests/Internal/Ast/Elimination/AstCheckEliminationIntegrationTest.php b/tests/Internal/Ast/Elimination/AstCheckEliminationIntegrationTest.php index 42e3cd4e..0538923c 100644 --- a/tests/Internal/Ast/Elimination/AstCheckEliminationIntegrationTest.php +++ b/tests/Internal/Ast/Elimination/AstCheckEliminationIntegrationTest.php @@ -418,4 +418,47 @@ function genInvalidReturn(): Generator $transformedInvalid = StreamWrapper::transformSource($invalidReturn, 'test_gen_ret_invalid.php'); expect($transformedInvalid)->toContain('RuntimeTypeChecker::checkGeneratorReturn'); }); + + test('completely eliminates checkYield, checkSend, and checkGeneratorReturn on proven 4-arg Generator with mixed TSend', function () { + $source = <<<'PHP' + */ +function counterStreamMixed(): Generator +{ + yield 0 => 10; + yield 1 => 20; + + return 'done'; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_gen_mixed_send.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkYield') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkSend') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn') + ->and($transformed)->toContain('yield 0 => 10;') + ->and($transformed)->toContain('yield 1 => 20;') + ->and($transformed)->toContain("return 'done';") + ; + }); + + test('retains checkSend on 4-arg Generator when TSend is void to strictly police sent values', function () { + $source = <<<'PHP' + */ +function counterStreamVoid(): Generator +{ + yield 0 => 10; + return 'done'; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_gen_void_send.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkYield') + ->and($transformed)->toContain('RuntimeTypeChecker::checkSend') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn') + ; + }); }); diff --git a/tests/Internal/Ast/Elimination/GeneratorEvaluatorTest.php b/tests/Internal/Ast/Elimination/GeneratorEvaluatorTest.php index b31bf95c..d33c324b 100644 --- a/tests/Internal/Ast/Elimination/GeneratorEvaluatorTest.php +++ b/tests/Internal/Ast/Elimination/GeneratorEvaluatorTest.php @@ -240,4 +240,15 @@ expect(EliminationSafetyPolicy::isGeneratorEliminationSafe($inheritedMethod, ['hasRealInheritance' => true], $genType))->toBeFalse(); }); }); + + describe('canEliminateSend()', function () { + test('eliminates checkSend only when TSend is null or mixed, and retains when constrained', function () { + expect(GeneratorEvaluator::canEliminateSend(null))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateSend(new IdentifierTypeNode('mixed')))->toBeTrue() + ->and(GeneratorEvaluator::canEliminateSend(new IdentifierTypeNode('void')))->toBeFalse() + ->and(GeneratorEvaluator::canEliminateSend(new IdentifierTypeNode('null')))->toBeFalse() + ->and(GeneratorEvaluator::canEliminateSend(new IdentifierTypeNode('positive-int')))->toBeFalse() + ; + }); + }); }); diff --git a/tests/Internal/Ast/FunctionContractInjectorTest.php b/tests/Internal/Ast/FunctionContractInjectorTest.php index 210fd341..dd79d974 100644 --- a/tests/Internal/Ast/FunctionContractInjectorTest.php +++ b/tests/Internal/Ast/FunctionContractInjectorTest.php @@ -271,6 +271,38 @@ public function dd(): never ->and($yieldFrom->expr)->toBeInstanceOf(Node\Expr\FuncCall::class) ; }); + + test('injects checkParamOut into generator methods with by-ref @param-out parameters', function () { + $doc = new Doc("/**\n * @param int &\$x\n * @param-out int &\$x\n * @return \\Generator\n */"); + + $method = new Node\Stmt\ClassMethod('run', [ + 'params' => [ + new Node\Param( + var: new Node\Expr\Variable('x'), + byRef: true + ), + ], + 'stmts' => [ + new Node\Stmt\Expression( + new Node\Expr\Assign( + new Node\Expr\Variable('x'), + new Node\Scalar\String_('not an int') + ) + ), + new Node\Stmt\Expression( + new Node\Expr\Yield_(new Node\Scalar\LNumber(1)) + ), + new Node\Stmt\Return_(null), + ], + ], [ + 'comments' => [$doc], + ]); + + FunctionContractInjector::inject($method); + + $printed = (new TypePHP\Internal\Ast\TypePHPPrinter())->prettyPrint($method->stmts ?? []); + expect($printed)->toContain('RuntimeTypeChecker::checkParamOut'); + }); }); describe('Static vs Instance Methods & Lifecycles', function () { diff --git a/tests/Internal/Docblock/DocblockExtractorTest.php b/tests/Internal/Docblock/DocblockExtractorTest.php index 9d628c6b..df4ee397 100644 --- a/tests/Internal/Docblock/DocblockExtractorTest.php +++ b/tests/Internal/Docblock/DocblockExtractorTest.php @@ -615,4 +615,60 @@ class HelperService ; }); }); + + test('extracts @param-out tag when variable includes by-reference ampersand (&$x)', function () { + $doc = <<<'DOC' +/** + * @param int &$x + * @param-out positive-int &$x + */ +DOC; + $node = DocblockExtractor::parseDocString($doc); + $tags = DocblockExtractor::getParamOutTags($node); + + expect($tags)->toHaveKey('x') + ->and((string) $tags['x']->type)->toBe('positive-int') + ; + }); + + test('extracts @phpstan-param-out and @psalm-param-out tags with by-reference ampersand (&$x)', function () { + $doc = <<<'DOC' +/** + * @psalm-param-out int &$a + * @phpstan-param-out non-empty-string &$b + */ +DOC; + $node = DocblockExtractor::parseDocString($doc); + $tags = DocblockExtractor::getParamOutTags($node); + + expect($tags)->toHaveKey('a') + ->and((string) $tags['a']->type)->toBe('int') + ->and($tags)->toHaveKey('b') + ->and((string) $tags['b']->type)->toBe('non-empty-string') + ; + }); + + test('extracts @param-out when multiple tags are written on a single-line docblock', function () { + $doc1 = '/** @param int $x @param-out positive-int $x */'; + $tags1 = DocblockExtractor::getParamOutTags(DocblockExtractor::parseDocString($doc1)); + expect($tags1)->toHaveKey('x') + ->and((string) $tags1['x']->type)->toBe('positive-int') + ; + + $doc2 = '/** @param int &$x @param-out positive-int &$x */'; + $tags2 = DocblockExtractor::getParamOutTags(DocblockExtractor::parseDocString($doc2)); + expect($tags2)->toHaveKey('x') + ->and((string) $tags2['x']->type)->toBe('positive-int') + ; + + $doc3 = '/** @param int $x @param-out positive-int $x @return int */'; + $parsed3 = DocblockExtractor::parseDocString($doc3); + $tags3 = DocblockExtractor::getParamOutTags($parsed3); + $return3 = DocblockExtractor::getReturnTag($parsed3); + expect($tags3)->toHaveKey('x') + ->and((string) $tags3['x']->type)->toBe('positive-int') + ->and($return3)->not()->toBeNull() + ->and((string) $return3->type)->toBe('int') + ; + }); }); diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index 5128c0cf..96517bcd 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -752,4 +752,14 @@ function vendorAction(): void ->toBe('wrong') ; }); + + test('checkStaticProperty does not mark property as checked when validation fails and throws', function () { + expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); }); diff --git a/tests/Internal/Wrapper/IteratorProxyTest.php b/tests/Internal/Wrapper/IteratorProxyTest.php index 3a6cf266..01ec4764 100644 --- a/tests/Internal/Wrapper/IteratorProxyTest.php +++ b/tests/Internal/Wrapper/IteratorProxyTest.php @@ -79,4 +79,13 @@ ->and($proxy->offsetExists('z'))->toBeFalse() ; }); + + test('forwards custom method calls and count() to outer IteratorAggregate before inner Iterator', function () { + $aggregate = new \TypePHP\Tests\Fixtures\Services\NestedAggregateService(['alpha' => 10, 'beta' => 20]); + $proxy = new IteratorProxy($aggregate, fn () => null); + + expect($proxy->getCustomMetadata())->toBe('custom_metadata_string') + ->and($proxy->count())->toBe(2) + ; + }); }); diff --git a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php index 98a05292..2dcc478b 100644 --- a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php +++ b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php @@ -202,6 +202,161 @@ function tddPsalmOverridesStandardParamOut(mixed &$code): void $code = ''; // Fails @psalm-param-out (non-empty-string) } +class Issue1SingleLineParamOutA +{ + /** + * @param int $x @param-out int $x + */ + public function run(&$x): void + { + $x = 'not an int'; + } +} + +class Issue1SingleLineAmpersandB +{ + /** + * @param int &$x @param-out int &$x + */ + public function run(&$x): void + { + $x = 'bad'; + } +} + +class Issue1SingleLineWithReturnC +{ + /** + * @param int $x @param-out int $x @return int + */ + public function run(&$x): int + { + $x = 'bad'; + + return 1; + } +} + +class Issue1SingleLinePhpstanD +{ + /** + * @param int $x @phpstan-param-out int $x + */ + public function run(&$x): void + { + $x = 'bad'; + } +} + +class Issue1MultiLineAmpersandE +{ + /** + * @param int &$x + * + * @param-out int &$x + */ + public function run(&$x): void + { + $x = 'not an int'; + } +} + +class Issue2GenericMethodWithParamOut +{ + /** + * @template T + * + * @param T &$slot + * + * @param-out T &$slot + * + * @return T + */ + public function run(mixed &$slot): mixed + { + return 'string returned for T=int'; + } + + /** + * @template T + * + * @param T &$first + * @param mixed &$second + * + * @param-out T &$first + * @param-out T &$second + */ + public function syncBoth(mixed &$first, mixed &$second): void + { + $second = 'wrong type for T=int'; + } +} + +/** + * @template T + * + * @param T &$slot + * + * @param-out T &$slot + * + * @return T + */ +function issue2StandaloneGenericWithParamOut(mixed &$slot): mixed +{ + return 'string returned for T=int'; +} + +class Issue4GeneratorParamOutService +{ + /** + * Mutates &$x to invalid type before yield (Bug3B reproduction) + * + * @param int &$x + * + * @param-out int &$x + * + * @return Generator + */ + public function runInvalidBeforeYield(mixed &$x): Generator + { + $x = 'not an int'; + yield 1; + + return; + } + + /** + * Mutates &$x to invalid type after yield, before return/fallthrough + * + * @param int &$x + * + * @param-out positive-int &$x + * + * @return Generator + */ + public function runInvalidAfterYield(mixed &$x): Generator + { + yield 1; + $x = -50; + } + + /** + * Valid mutation across generator execution + * + * @param int &$x + * + * @param-out positive-int &$x + * + * @return Generator + */ + public function runValid(mixed &$x): Generator + { + $x = 10; + yield 1; + $x = 42; + } +} + 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 () { @@ -404,4 +559,124 @@ function tddPsalmOverridesStandardParamOut(mixed &$code): void ; }); }); + + describe('10. Reproductions: Single-Line Multi-Tag & Ampersand (&$x) Syntax Variants', function () { + test('Class A: single-line @param and @param-out without ampersand throws TypeError', function () { + $a = new Issue1SingleLineParamOutA(); + $v = 1; + + expect(fn () => $a->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; + }); + + test('Class B: single-line @param and @param-out with &$x ampersand throws TypeError', function () { + $b = new Issue1SingleLineAmpersandB(); + $v = 1; + + expect(fn () => $b->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; + }); + + test('Class C: single-line @param, @param-out, and @return throws TypeError', function () { + $c = new Issue1SingleLineWithReturnC(); + $v = 1; + + expect(fn () => $c->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; + }); + + test('Class D: single-line @param and @phpstan-param-out throws TypeError', function () { + $d = new Issue1SingleLinePhpstanD(); + $v = 1; + + expect(fn () => $d->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; + }); + + test('Class E: multi-line @param-out with &$x ampersand throws TypeError', function () { + $e = new Issue1MultiLineAmpersandE(); + $v = 1; + + expect(fn () => $e->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; + }); + }); + + describe('11. ScopeCleaner Preservation Across @param-out and @return', function () { + test('enforces generic @return T after @param-out check passes on class method', function () { + $service = new Issue2GenericMethodWithParamOut(); + $v = 42; + + expect(fn () => $service->run($v)) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; + }); + + test('enforces generic @return T after @param-out check passes on standalone function', function () { + $v = 42; + + expect(fn () => issue2StandaloneGenericWithParamOut($v)) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; + }); + + test('preserves generic template T across multiple sequential @param-out checks in the same method', function () { + $service = new Issue2GenericMethodWithParamOut(); + $first = 42; + $second = 100; + + expect(fn () => $service->syncBoth($first, $second)) + ->toThrow(TypeError::class, 'Argument &$second (param-out) must be of type int') + ; + }); + }); + + describe('12. Reproductions: Generators with @param-out', function () { + test('throws TypeError when generator mutates by-ref param to invalid type before yield during foreach', function () { + $service = new Issue4GeneratorParamOutService(); + $x = 1; + + expect(function () use ($service, &$x) { + foreach ($service->runInvalidBeforeYield($x) as $_) { + } + })->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); + }); + + test('throws TypeError at yield suspension boundary even if caller only calls current()', function () { + $service = new Issue4GeneratorParamOutService(); + $x = 1; + + $gen = $service->runInvalidBeforeYield($x); + + expect(fn () => $gen->current()) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; + }); + + test('throws TypeError when generator mutates by-ref param to invalid type after yield before finishing', function () { + $service = new Issue4GeneratorParamOutService(); + $x = 1; + + expect(function () use ($service, &$x) { + foreach ($service->runInvalidAfterYield($x) as $_) { + } + })->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type positive-int'); + }); + + test('accepts valid @param-out mutations in generator across yields and completion', function () { + $service = new Issue4GeneratorParamOutService(); + $x = 1; + + $items = iterator_to_array($service->runValid($x)); + + expect($items)->toBe([1]) + ->and($x)->toBe(42) + ; + }); + }); }); diff --git a/tests/TypeChecking/Boundaries/PropertyDefaultValidationTest.php b/tests/TypeChecking/Boundaries/PropertyDefaultValidationTest.php index a15aa94a..41349ac7 100644 --- a/tests/TypeChecking/Boundaries/PropertyDefaultValidationTest.php +++ b/tests/TypeChecking/Boundaries/PropertyDefaultValidationTest.php @@ -40,7 +40,35 @@ class InstancePropertyDefaultValid public int $score = 100; } +class StaticPropertyReflectionCorrupted +{ + /** + * @var int + */ + public static $port = 8080; +} + describe('Property Default Value Validation at Declaration & Instantiation', function () { + test('re-validates and throws on subsequent reads after a caught static property TypeError (Issue 3)', function () { + expect(fn () => StaticPropertyDefaultInvalid::$score) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => StaticPropertyDefaultInvalid::$score) + ->toThrow(TypeError::class, 'positive-int') + ; + + (new ReflectionProperty(StaticPropertyReflectionCorrupted::class, 'port'))->setValue(null, 'corrupted'); + + expect(fn () => StaticPropertyReflectionCorrupted::$port) + ->toThrow(TypeError::class, 'must be of type int') + ; + + expect(fn () => StaticPropertyReflectionCorrupted::$port) + ->toThrow(TypeError::class, 'must be of type int') + ; + }); + test('rejects invalid static property default integer upon access or loading', function () { expect(fn () => StaticPropertyDefaultInvalid::$score) ->toThrow(TypeError::class, 'positive-int') diff --git a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php index 659b1f04..d3cdc053 100644 --- a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php +++ b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php @@ -50,6 +50,19 @@ function testGeneratorWithInvalidVoidReturn(): Generator return 'not_void'; } +class D2GeneratorFixture +{ + /** + * @return Generator + */ + public function run(): Generator + { + yield 1; + + return; + } +} + 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 () { @@ -149,6 +162,22 @@ function testGeneratorWithInvalidVoidReturn(): Generator ->toThrow(TypeError::class, 'must be of type int') ; }); + + test('strictly enforces TSend = void and throws TypeError when non-null value is sent into generator', function () { + $g = (new D2GeneratorFixture())->run(); + $g->current(); + + expect(fn () => $g->send('not null')) + ->toThrow(TypeError::class, 'Generator sent value (TSend) must be of type void, string \'not null\' given') + ; + }); + + test('allows standard foreach iteration on generator with TSend = void', function () { + $g = (new D2GeneratorFixture())->run(); + $items = iterator_to_array($g); + + expect($items)->toBe([1]); + }); }); describe('Generator Return Value Validation (TReturn)', function () { diff --git a/tests/TypeChecking/CallablesAndIterators/LazyIteratorsAndGeneratorsTest.php b/tests/TypeChecking/CallablesAndIterators/LazyIteratorsAndGeneratorsTest.php index d9fd9f9b..56b9a30c 100644 --- a/tests/TypeChecking/CallablesAndIterators/LazyIteratorsAndGeneratorsTest.php +++ b/tests/TypeChecking/CallablesAndIterators/LazyIteratorsAndGeneratorsTest.php @@ -133,6 +133,14 @@ function testTraversableReturnContract(array $data): Traversable return new ArrayIterator($data); } +/** + * @param Traversable $items + */ +function testCustomMethodOnTraversableParam(Traversable $items): string +{ + return $items->getCustomMetadata(); +} + describe('Lazy Generator Parameter Contracts (@param Generator)', function () { test('iterates valid generator yielding string keys and positive-int values', function () { $validGen = function (): Generator { @@ -220,6 +228,7 @@ function testTraversableReturnContract(array $data): Traversable expect(testTraversableParamContract($nestedService))->toBe(['item1' => 10, 'item2' => 20]); expect(testCountableTraversableParam($nestedService))->toBe(2); + expect(testCustomMethodOnTraversableParam($nestedService))->toBe('custom_metadata_string'); }); });