diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index bc75fb6a..2a75f216 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -1181,6 +1181,14 @@ private function handleAssign(Node\Expr\Assign $node): void if ($resolvedClass !== null) { $this->scopeManager->registerInferredVarType($varName, $resolvedClass); } + } elseif ($node->expr instanceof Node\Expr\Clone_ && $node->expr->expr instanceof Node\Expr\Variable && \is_string($node->expr->expr->name)) { + $sourceVarName = $node->expr->expr->name; + $sourceType = $this->scopeManager->getVarTypeFromScope($sourceVarName) + ?? $this->scopeManager->getInferredVarType($sourceVarName); + + if ($sourceType !== null) { + $this->scopeManager->registerInferredVarType($varName, $sourceType); + } } elseif (! ($node->expr instanceof Node\Expr\AssignRef)) { $this->scopeManager->unregisterInferredVarType($varName); } diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 2374a28f..25a9b5c9 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -4,8 +4,14 @@ namespace TypePHP\Internal\Checker; +use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; +use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use ReflectionProperty; +use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Generics\TemplateManager; +use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StructureMutator; use TypePHP\Internal\Validator\TypeValidatorRegistry; @@ -109,6 +115,31 @@ public static function checkProperty( } $currentVal = self::readPropertyValue($objectOrClass, $className, $propName); + + if ( + Config::isArrayValidationHybrid() + && \is_array($currentVal) + && \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD + && \count($chain) === 1 + && $chain[0][0] === 'dim' + ) { + $directErr = self::validatePropertyElementMutation( + $objectOrClass, + $className, + $propName, + $chain, + $value, + $file, + $registry + ); + + if ($directErr instanceof ErrorMessage) { + return $directErr; + } + + return $value; + } + $copy = StructureMutator::mutateCopy($currentVal, $chain, $value); $res = InlineChecker::checkProperty($copy, $objectOrClass, $propName, $file, $registry); @@ -120,6 +151,86 @@ public static function checkProperty( return $value; } + /** + * Directly validates a single element appended/assigned to a large property array in O(1). + * + * @param list $chain + */ + private static function validatePropertyElementMutation( + mixed $objectOrClass, + string $className, + string $propName, + array $chain, + mixed $value, + string $file, + TypeValidatorRegistry $registry + ): ?ErrorMessage { + try { + $rawTypeNode = DocblockParser::parseProperty($className, $propName); + if ($rawTypeNode === null) { + return null; + } + + $typeNode = $rawTypeNode; + if (\is_object($objectOrClass)) { + $allTemplates = DocblockParser::parseClassTemplates($className); + if ($allTemplates !== []) { + $boundTemplates = TemplateManager::getBoundTemplates('none', $objectOrClass, $allTemplates); + if ($boundTemplates !== []) { + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $allTemplates); + } + } + } + + $key = $chain[0][1]; + $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); + + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower((string) $typeNode->type); + + if ($base === 'list' || $base === 'non-empty-list') { + if ($key !== null && ! \is_int($key)) { + return ErrorFactory::createError("Property {$className}::\${$propName} must be a list, non-integer key '{$keyStr}' given"); + } + + $valueType = $typeNode->genericTypes[0] ?? null; + if ($valueType !== null) { + $context = "Property {$className}::\${$propName}" . ($key !== null ? "[{$key}]" : '[]'); + + return $registry->validate($value, $valueType, $context); + } + } elseif (\in_array($base, ['array', 'non-empty-array', 'iterable'], true)) { + $genericCount = \count($typeNode->genericTypes); + + if ($genericCount >= 2 && $key !== null) { + $keyType = $typeNode->genericTypes[0]; + $keyErr = $registry->validate($key, $keyType, "Property {$className}::\${$propName} key"); + if ($keyErr !== null) { + return $keyErr; + } + } + + $valueType = $genericCount >= 2 + ? $typeNode->genericTypes[1] + : ($typeNode->genericTypes[0] ?? null); + + if ($valueType !== null) { + $context = "Property {$className}::\${$propName}" . ($key !== null ? "['{$keyStr}']" : '[]'); + + return $registry->validate($value, $valueType, $context); + } + } + } elseif ($typeNode instanceof ArrayTypeNode) { + $context = "Property {$className}::\${$propName}" . ($key !== null ? "[{$keyStr}]" : '[]'); + + return $registry->validate($value, $typeNode->type, $context); + } + } catch (\Throwable) { + } + + return null; + } + /** * Safely reads the current value of an instance or static property across all visibilities. */ diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 63362fdd..50b1cb7d 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -944,10 +944,18 @@ private static function inferArrayTemplatesFromAllElements( ?object $thisObj, array $templates ): void { - if ($typeNode instanceof NullableTypeNode) { + while ($typeNode instanceof NullableTypeNode) { $typeNode = $typeNode->type; } + if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { + foreach ($typeNode->types as $subType) { + self::inferArrayTemplatesFromAllElements($subType, $arrVal, $effectiveFunction, $thisObj, $templates); + } + + return; + } + if ($typeNode instanceof GenericTypeNode) { $baseType = strtolower((string) $typeNode->type); if (! isset(self::ITERABLE_TYPES[$baseType])) { @@ -1109,22 +1117,45 @@ private static function inferGenericObjectNode( array $templates, array $classTemplates = [] ): void { - if ($typeNode instanceof NullableTypeNode) { + while ($typeNode instanceof NullableTypeNode) { $typeNode = $typeNode->type; } + if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { + foreach ($typeNode->types as $subType) { + self::inferGenericObjectNode($subType, $value, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + + return; + } + if ($typeNode instanceof GenericTypeNode && \is_object($value)) { $baseName = strtolower((string) $typeNode->type); if (isset(self::COLLECTION_TYPES[$baseName])) { return; } + $contextRef = null; + if (str_contains($effectiveFunction, '::')) { + $declaringClass = explode('::', $effectiveFunction, 2)[0]; + if (class_exists($declaringClass, false) || class_exists($declaringClass) || interface_exists($declaringClass) || trait_exists($declaringClass)) { + $contextRef = new \ReflectionClass($declaringClass); + } + } elseif (\function_exists($effectiveFunction)) { + $contextRef = new \ReflectionFunction($effectiveFunction); + } + + $targetClassFqcn = SpecialTypeResolver::resolveFqcn((string) $typeNode->type, $contextRef ?? new \ReflectionClass($value)); + + if (! is_a($value, $targetClassFqcn)) { + return; + } + $boundOnInstance = TemplateManager::getBoundTemplatesForInstance($value); if ($boundOnInstance === []) { return; } - $targetClassFqcn = SpecialTypeResolver::resolveFqcn((string) $typeNode->type, new \ReflectionClass($value)); $targetTemplateNames = self::$classDeclaredTemplateNamesCache[$targetClassFqcn] ?? null; if ($targetTemplateNames === null) { diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 4d63a368..80507ec4 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1324,6 +1324,24 @@ private static function collectInheritedGenericTagBindings( $normalizedGenericTypes = self::normalizeGenericArguments($genericTypeNode->genericTypes, $parentTemplateNodes); $hierAliases = DocblockParser::parseClassAliases($hierClass->getName()); + $hierTemplates = DocblockParser::parseClassTemplates($hierClass->getName()); + if ($hierTemplates === []) { + $hierDoc = StubManager::getClassDoc($hierClass->getName()) ?? $hierClass->getDocComment(); + if ($hierDoc !== false) { + $hierPhpDocNode = DocblockExtractor::parseDocString($hierDoc); + $hierTemplates = DocblockExtractor::extractTemplates($hierPhpDocNode); + } + } + + $hierFallbackBindings = []; + foreach ($hierTemplates as $tName => $tTag) { + $boundOrDef = $tTag->default ?? $tTag->bound; + if ($boundOrDef !== null) { + $boundOrDef = SpecialTypeResolver::resolve($boundOrDef, $hierClass); + } + $hierFallbackBindings[$tName] = $boundOrDef ?? new IdentifierTypeNode('mixed'); + } + foreach ($parentTemplateNames as $idx => $templateName) { if (isset($normalizedGenericTypes[$idx])) { $typeArg = $normalizedGenericTypes[$idx]; @@ -1345,11 +1363,11 @@ private static function collectInheritedGenericTagBindings( $isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($resolved->name); $isRealType = self::isRealTypeSymbol($resolved->name); - if (! $isBuiltIn && ! $isRealType) { + if (! $isBuiltIn && ! $isRealType && ! isset($declaredTemplateNames[$resolved->name])) { continue; } - if (isset($declaredTemplateNames[$resolved->name])) { + if (isset($declaredTemplateNames[$resolved->name]) && $resolved->name === $templateName) { continue; } } @@ -1359,6 +1377,10 @@ private static function collectInheritedGenericTagBindings( } } + if (DocblockParser::typeReferencesTemplate($resolved, $declaredTemplateNames) && $hierFallbackBindings !== []) { + $resolved = TemplateSubstitutor::substitute($resolved, $hierFallbackBindings); + } + $bindings[$templateName] ??= $resolved; } } diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index caa71742..5d0c7e5f 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -9,6 +9,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Exception\TypeError as TypePHPTypeError; use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; @@ -86,7 +87,7 @@ public static function wrap(string $function, string $paramName, mixed $iterable [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($typeNode, $aliases); - if ($keyTypeNode === null && $itemTypeNode === null) { + if (self::isUnconstrainedKey($keyTypeNode) && self::isUnconstrained($itemTypeNode)) { return $iterable; } @@ -106,6 +107,53 @@ public static function wrap(string $function, string $paramName, mixed $iterable return self::wrapGenerator($iterable, $typeCheckCallback); } + /** + * Checks if a key type node is absent or covers all possible collection keys (mixed, array-key, or any scalar/object). + */ + private static function isUnconstrainedKey(?TypeNode $node): bool + { + if ($node === null) { + return true; + } + + if ($node instanceof IdentifierTypeNode) { + $lower = strtolower($node->name); + + return \in_array($lower, ['mixed', 'array-key'], true); + } + + if ($node instanceof UnionTypeNode) { + $types = []; + foreach ($node->types as $t) { + if ($t instanceof IdentifierTypeNode) { + $types[strtolower($t->name)] = true; + } + } + + if (isset($types['mixed']) || isset($types['array-key'])) { + return true; + } + + if (isset($types['string'], $types['int'], $types['bool'], $types['float'], $types['object'])) { + return true; + } + } + + return false; + } + + /** + * Checks if a type node is absent or unconstrained mixed. + */ + private static function isUnconstrained(?TypeNode $node): bool + { + if ($node === null) { + return true; + } + + return $node instanceof IdentifierTypeNode && strtolower($node->name) === 'mixed'; + } + /** * Extracts key and value TypeNodes from an iterable type node AST or type alias. * @@ -190,6 +238,7 @@ private static function createValidationCallback( /** * Wraps an iterable generator in an interceptor generator to evaluate type checks on each yield. + * Advances generators using valid()/current()/next() without calling rewind() on already-started generators. * * @param iterable $iterable * @param \Closure(mixed, mixed): void $typeCheckCallback @@ -198,6 +247,18 @@ private static function createValidationCallback( */ private static function wrapGenerator(iterable $iterable, \Closure $typeCheckCallback): Generator { + if ($iterable instanceof Generator) { + while ($iterable->valid()) { + $key = $iterable->key(); + $value = $iterable->current(); + $typeCheckCallback($key, $value); + yield $key => $value; + $iterable->next(); + } + + return; + } + foreach ($iterable as $key => $value) { $typeCheckCallback($key, $value); yield $key => $value; diff --git a/src/Internal/Wrapper/IteratorProxy.php b/src/Internal/Wrapper/IteratorProxy.php index 4e5c4bf2..14bcc9f7 100644 --- a/src/Internal/Wrapper/IteratorProxy.php +++ b/src/Internal/Wrapper/IteratorProxy.php @@ -17,7 +17,7 @@ */ final class IteratorProxy implements OuterIterator, Countable { - private Iterator $inner; + private ?Iterator $inner = null; /** * @param Traversable $iterable @@ -27,7 +27,6 @@ public function __construct( private Traversable $iterable, private \Closure $typeCheckCallback ) { - $this->inner = self::resolveIterator($iterable); } /** @@ -45,24 +44,37 @@ private static function resolveIterator(Traversable $iterable): Iterator return $iterable; } + private function getInner(): Iterator + { + if ($this->inner === null) { + $this->inner = self::resolveIterator($this->iterable); + } + + return $this->inner; + } + public function rewind(): void { - if ($this->iterable instanceof IteratorAggregate && $this->inner instanceof \Generator) { + if ($this->iterable instanceof IteratorAggregate) { $this->inner = self::resolveIterator($this->iterable); + } else { + $this->inner ??= self::resolveIterator($this->iterable); } - $this->inner->rewind(); + if (! ($this->inner instanceof \Generator)) { + $this->inner->rewind(); + } } public function valid(): bool { - return $this->inner->valid(); + return $this->getInner()->valid(); } public function current(): mixed { - $key = $this->inner->key(); - $val = $this->inner->current(); + $key = $this->getInner()->key(); + $val = $this->getInner()->current(); ($this->typeCheckCallback)($key, $val); return $val; @@ -70,17 +82,17 @@ public function current(): mixed public function key(): mixed { - return $this->inner->key(); + return $this->getInner()->key(); } public function next(): void { - $this->inner->next(); + $this->getInner()->next(); } public function getInnerIterator(): Iterator { - return $this->inner; + return $this->getInner(); } public function count(): int @@ -89,11 +101,12 @@ public function count(): int return $this->iterable->count(); } - if ($this->inner instanceof Countable) { - return $this->inner->count(); + $inner = $this->getInner(); + if ($inner instanceof Countable) { + return $inner->count(); } - return iterator_count($this->inner); + return iterator_count($inner); } /** @@ -106,9 +119,10 @@ public function __call(string $method, array $args): mixed return $this->iterable->$method(...$args); } - if ($this->inner !== $this->iterable && method_exists($this->inner, $method)) { + $inner = $this->getInner(); + if ($inner !== $this->iterable && method_exists($inner, $method)) { // @phpstan-ignore method.dynamicName - return $this->inner->$method(...$args); + return $inner->$method(...$args); } // @phpstan-ignore method.dynamicName diff --git a/tests/Internal/Checker/MemberAssignCheckerTest.php b/tests/Internal/Checker/MemberAssignCheckerTest.php index c00e75b3..10a76338 100644 --- a/tests/Internal/Checker/MemberAssignCheckerTest.php +++ b/tests/Internal/Checker/MemberAssignCheckerTest.php @@ -4,18 +4,56 @@ namespace TypePHP\Tests\Internal\Checker; +use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use TypePHP\Internal\Checker\MemberAssignChecker; use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Validator\TypeValidatorRegistry; use TypePHP\Tests\Fixtures\Types\ConfiguredProperty; +class HybridPropertyFixture +{ + /** + * @var list + */ + public array $listProp = []; + + /** + * @var array + */ + public array $mapProp = []; + + /** + * @var array + */ + public array $singleGenericProp = []; + + public array $unannotatedProp = []; +} + +/** + * @template T + */ +class HybridGenericPropertyHolder +{ + /** + * @var list + */ + public array $items = []; +} + describe('MemberAssignChecker Unit Tests', function () { beforeEach(function () { $this->registry = new TypeValidatorRegistry(); }); + afterEach(function () { + Config::reset(); + }); + test('accepts valid array shape key assignment and returns value', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = ['count' => 5, 'name' => 'Alice']; $chain = [['dim', 'count']]; @@ -26,7 +64,7 @@ 'array{count: int, name: string}', 'stats', __FILE__, - $this->registry + $registry ); expect($result)->toBe(10) @@ -35,6 +73,7 @@ }); test('returns ErrorMessage on invalid array shape key assignment', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = ['count' => 5]; $chain = [['dim', 'count']]; @@ -45,7 +84,7 @@ 'array{count: int}', 'stats', __FILE__, - $this->registry + $registry ); expect($result)->toBeInstanceOf(ErrorMessage::class) @@ -54,6 +93,7 @@ }); test('returns ErrorMessage when assigning unexpected key to sealed array shape', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = ['count' => 5]; $chain = [['dim', 'extra']]; @@ -64,7 +104,7 @@ 'array{count: int}', 'stats', __FILE__, - $this->registry + $registry ); expect($result)->toBeInstanceOf(ErrorMessage::class) @@ -74,6 +114,7 @@ test('fast-path O(1) in hybrid mode validates leaf directly on large list', function () { Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = range(1, 200); $chain = [['dim', 50]]; @@ -85,7 +126,7 @@ 'list', 'list', __FILE__, - $this->registry + $registry ); expect($valid)->toBe(100); @@ -96,7 +137,7 @@ 'list', 'list', __FILE__, - $this->registry + $registry ); expect($invalid)->toBeInstanceOf(ErrorMessage::class) ->and($invalid->getMessage())->toContain('positive-int') @@ -105,6 +146,7 @@ test('fast-path in hybrid mode rejects non-integer keys on list types', function () { Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = [1, 2, 3]; $chain = [['dim', 'string_key']]; @@ -116,7 +158,7 @@ 'list', 'items', __FILE__, - $this->registry + $registry ); expect($result)->toBeInstanceOf(ErrorMessage::class) @@ -126,6 +168,7 @@ test('fast-path in hybrid mode validates key on generic maps (array)', function () { Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = ['a' => 1]; $chain = [['dim', 123]]; @@ -137,7 +180,7 @@ 'array', 'map', __FILE__, - $this->registry + $registry ); expect($result)->toBeInstanceOf(ErrorMessage::class) @@ -146,6 +189,7 @@ }); test('validates multi-level nested array shape assignment', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = ['user' => ['id' => 1, 'role' => 'admin']]; $chain = [['dim', 'user'], ['dim', 'id']]; @@ -156,7 +200,7 @@ 'array{user: array{id: positive-int, role: non-empty-string}}', 'config', __FILE__, - $this->registry + $registry ); expect($valid)->toBe(42); @@ -167,7 +211,7 @@ 'array{user: array{id: positive-int, role: non-empty-string}}', 'config', __FILE__, - $this->registry + $registry ); expect($invalid)->toBeInstanceOf(ErrorMessage::class) ->and($invalid->getMessage())->toContain("['user']['id']") @@ -175,6 +219,7 @@ }); test('validates object shape property assignment on stdClass', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = (object) ['count' => 5]; $chain = [['prop', 'count']]; @@ -185,7 +230,7 @@ 'object{count: int}', 'stats', __FILE__, - $this->registry + $registry ); expect($valid)->toBe(10) ->and($root->count)->toBe(5) @@ -198,7 +243,7 @@ 'object{count: int}', 'stats', __FILE__, - $this->registry + $registry ); expect($invalid)->toBeInstanceOf(ErrorMessage::class) ->and($invalid->getMessage())->toContain('->count must be of type int') @@ -206,6 +251,7 @@ }); test('returns ErrorMessage when assigning unexpected property to sealed object shape', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = (object) ['count' => 5]; $chain = [['prop', 'unexpected_field']]; @@ -216,7 +262,7 @@ 'object{count: int}', 'stats', __FILE__, - $this->registry + $registry ); expect($result)->toBeInstanceOf(ErrorMessage::class) @@ -225,6 +271,7 @@ }); test('validates multi-level nested object shape property assignment', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $root = (object) ['user' => (object) ['id' => 1]]; $chain = [['prop', 'user'], ['prop', 'id']]; @@ -235,7 +282,7 @@ 'object{user: object{id: positive-int}}', 'data', __FILE__, - $this->registry + $registry ); expect($valid)->toBe(100); @@ -246,7 +293,7 @@ 'object{user: object{id: positive-int}}', 'data', __FILE__, - $this->registry + $registry ); expect($invalid)->toBeInstanceOf(ErrorMessage::class) ->and($invalid->getMessage())->toContain('->user->id') @@ -254,6 +301,7 @@ }); test('checkProperty validates object property dimension assignments and preserves state on failure', function () { + $registry = $this->registry ?? new TypeValidatorRegistry(); $fixture = new ConfiguredProperty(); $fixture->numbers = [1, 2, 3]; @@ -263,7 +311,7 @@ [['dim', null]], 4, __FILE__, - $this->registry + $registry ); expect($validAppend)->toBe(4) ->and($fixture->numbers)->toBe([1, 2, 3]) @@ -275,7 +323,7 @@ [['dim', null]], 'not_an_int', __FILE__, - $this->registry + $registry ); expect($invalidAppend)->toBeInstanceOf(ErrorMessage::class) ->and($invalidAppend->getMessage())->toContain('numbers[3] must be of type int') @@ -284,7 +332,9 @@ }); test('checkProperty returns value untouched when target is non-object/non-string or inline properties are disabled', function () { - expect(MemberAssignChecker::checkProperty(123, 'numbers', [['dim', null]], 'val', __FILE__, $this->registry)) + $registry = $this->registry ?? new TypeValidatorRegistry(); + + expect(MemberAssignChecker::checkProperty(123, 'numbers', [['dim', null]], 'val', __FILE__, $registry)) ->toBe('val') ; @@ -292,8 +342,243 @@ $fixture = new ConfiguredProperty(); $fixture->numbers = [1, 2]; - expect(MemberAssignChecker::checkProperty($fixture, 'numbers', [['dim', null]], 'invalid', __FILE__, $this->registry)) + expect(MemberAssignChecker::checkProperty($fixture, 'numbers', [['dim', null]], 'invalid', __FILE__, $registry)) ->toBe('invalid') ; }); + + test('checkProperty validates and accepts element mutation on ArrayTypeNode property with > 128 items in hybrid mode', function () { + Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); + + $fixture = new ConfiguredProperty(); + $fixture->numbers = range(1, 150); + + $valid = MemberAssignChecker::checkProperty( + $fixture, + 'numbers', + [['dim', 50]], + 42, + __FILE__, + $registry + ); + expect($valid)->toBe(42); + + $validAppend = MemberAssignChecker::checkProperty( + $fixture, + 'numbers', + [['dim', null]], + 100, + __FILE__, + $registry + ); + expect($validAppend)->toBe(100); + }); + + test('checkProperty rejects element mutation on ArrayTypeNode property with > 128 items when value is invalid', function () { + Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); + + $fixture = new ConfiguredProperty(); + $fixture->numbers = range(1, 150); + + $invalid = MemberAssignChecker::checkProperty( + $fixture, + 'numbers', + [['dim', 50]], + 'not_an_int', + __FILE__, + $registry + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('numbers[50] must be of type int') + ; + }); + + test('checkProperty validates list property on > 128 items: valid index, valid append, invalid value, and non-integer key', function () { + Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); + + $fixture = new HybridPropertyFixture(); + $fixture->listProp = range(1, 150); + + $validIndex = MemberAssignChecker::checkProperty( + $fixture, + 'listProp', + [['dim', 20]], + 500, + __FILE__, + $registry + ); + expect($validIndex)->toBe(500); + + $validAppend = MemberAssignChecker::checkProperty( + $fixture, + 'listProp', + [['dim', null]], + 600, + __FILE__, + $registry + ); + expect($validAppend)->toBe(600); + + $invalidVal = MemberAssignChecker::checkProperty( + $fixture, + 'listProp', + [['dim', 20]], + -10, + __FILE__, + $registry + ); + expect($invalidVal)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidVal->getMessage())->toContain('listProp[20] must be of type positive-int') + ; + + $invalidKey = MemberAssignChecker::checkProperty( + $fixture, + 'listProp', + [['dim', 'non_int_key']], + 500, + __FILE__, + $registry + ); + expect($invalidKey)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidKey->getMessage())->toContain("must be a list, non-integer key 'non_int_key' given") + ; + }); + + test('checkProperty validates generic key-value map property on > 128 items: valid key/value, invalid value, and invalid key', function () { + Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); + + $fixture = new HybridPropertyFixture(); + $map = []; + for ($i = 0; $i < 150; $i++) { + $map["key_{$i}"] = $i + 1; + } + $fixture->mapProp = $map; + + $valid = MemberAssignChecker::checkProperty( + $fixture, + 'mapProp', + [['dim', 'key_10']], + 999, + __FILE__, + $registry + ); + expect($valid)->toBe(999); + + $validAppend = MemberAssignChecker::checkProperty( + $fixture, + 'mapProp', + [['dim', null]], + 888, + __FILE__, + $registry + ); + expect($validAppend)->toBe(888); + + $invalidVal = MemberAssignChecker::checkProperty( + $fixture, + 'mapProp', + [['dim', 'key_10']], + -5, + __FILE__, + $registry + ); + expect($invalidVal)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidVal->getMessage())->toContain("mapProp['key_10'] must be of type positive-int") + ; + + $invalidKey = MemberAssignChecker::checkProperty( + $fixture, + 'mapProp', + [['dim', 12345]], + 100, + __FILE__, + $registry + ); + expect($invalidKey)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidKey->getMessage())->toContain('mapProp key must be of type string') + ; + }); + + test('checkProperty validates single generic array property on > 128 items (array)', function () { + Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); + + $fixture = new HybridPropertyFixture(); + $fixture->singleGenericProp = range(1, 150); + + $valid = MemberAssignChecker::checkProperty( + $fixture, + 'singleGenericProp', + [['dim', 10]], + 50, + __FILE__, + $registry + ); + expect($valid)->toBe(50); + + $invalid = MemberAssignChecker::checkProperty( + $fixture, + 'singleGenericProp', + [['dim', 10]], + -5, + __FILE__, + $registry + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain("singleGenericProp['10'] must be of type positive-int") + ; + }); + + test('checkProperty substitutes generic templates on class when validating element mutation in hybrid mode', function () { + Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); + + $holder = new HybridGenericPropertyHolder(); + $holder->items = range(1, 150); + TemplateManager::bindTemplate('none', $holder, 'T', new IdentifierTypeNode('positive-int')); + + $valid = MemberAssignChecker::checkProperty( + $holder, + 'items', + [['dim', 10]], + 42, + __FILE__, + $registry + ); + expect($valid)->toBe(42); + + $invalid = MemberAssignChecker::checkProperty( + $holder, + 'items', + [['dim', 10]], + -5, + __FILE__, + $registry + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('items[10] must be of type positive-int') + ; + }); + + test('checkProperty returns null from validatePropertyElementMutation when property has no docblock and falls back cleanly', function () { + Config::set(['array_validation' => 'hybrid']); + $registry = $this->registry ?? new TypeValidatorRegistry(); + + $fixture = new HybridPropertyFixture(); + $fixture->unannotatedProp = range(1, 150); + + $result = MemberAssignChecker::checkProperty( + $fixture, + 'unannotatedProp', + [['dim', 10]], + 'any_value', + __FILE__, + $registry + ); + expect($result)->toBe('any_value'); + }); }); diff --git a/tests/Internal/Wrapper/IterableWrapperTest.php b/tests/Internal/Wrapper/IterableWrapperTest.php index df31be9f..99701b2a 100644 --- a/tests/Internal/Wrapper/IterableWrapperTest.php +++ b/tests/Internal/Wrapper/IterableWrapperTest.php @@ -9,6 +9,7 @@ use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use ReflectionClass; use TypeError; use TypePHP\Internal\Docblock\DocblockParser; @@ -39,6 +40,34 @@ function fixtureReturnIterableFunction(): iterable return ['item1' => 10, 'item2' => 20]; } +/** + * @param iterable $items + */ +function fixtureUnionWithMixedKey(iterable $items): void +{ +} + +/** + * @param iterable $items + */ +function fixtureUnionWithArrayKey(iterable $items): void +{ +} + +/** + * @param iterable $items + */ +function fixtureUnionAllTypesKey(iterable $items): void +{ +} + +/** + * @param iterable $items + */ +function fixtureConstrainedUnionKey(iterable $items): void +{ +} + describe('IterableWrapper Unit Tests', function () { afterEach(function () { CallerBoundaryResolver::reset(); @@ -324,4 +353,157 @@ public static function execute(callable $action): mixed } }); }); + + describe('Generator Resumption & Lazy Sequence Support (TDD Bug Verification)', function () { + test('wraps and consumes an already started generator without throwing Cannot rewind exception', function () { + $registry = new TypeValidatorRegistry(); + + $generator = (function (): Generator { + yield 'first' => 10; + yield 'second' => 20; + yield 'third' => 30; + })(); + + $generator->current(); + $generator->next(); + + $wrapped = IterableWrapper::wrap( + __NAMESPACE__ . '\fixtureValidIterableFunction', + 'items', + $generator, + $registry + ); + + $results = []; + foreach ($wrapped as $k => $v) { + $results[$k] = $v; + } + + expect($results)->toBe([ + 'second' => 20, + 'third' => 30, + ]); + }); + + test('wrapping an IteratorAggregate parameter preserves lazy evaluation until iteration', function () { + $registry = new TypeValidatorRegistry(); + $generatorEvaluated = false; + + $lazyAggregate = new class ($generatorEvaluated) implements \IteratorAggregate { + public function __construct(private bool &$generatorEvaluated) + { + } + + public function getIterator(): \Traversable + { + $this->generatorEvaluated = true; + yield 'item1' => 10; + } + }; + + $wrapped = IterableWrapper::wrap( + __NAMESPACE__ . '\fixtureValidIterableFunction', + 'items', + $lazyAggregate, + $registry + ); + + expect($generatorEvaluated)->toBeFalse('Lazy aggregate was prematurely materialized during IterableWrapper::wrap()'); + + $out = []; + foreach ($wrapped as $k => $v) { + $out[$k] = $v; + } + + expect($generatorEvaluated)->toBeTrue() + ->and($out)->toBe(['item1' => 10]) + ; + }); + }); + + describe('isUnconstrainedKey() Union Type Coverage', function () { + test('returns unconstrained true for unions containing mixed or array-key', function () { + $registry = new TypeValidatorRegistry(); + $iterator = new ArrayIterator(['a' => 1]); + + $resultMixed = IterableWrapper::wrap( + __NAMESPACE__ . '\fixtureUnionWithMixedKey', + 'items', + $iterator, + $registry + ); + expect($resultMixed)->toBe($iterator); + + $resultArrayKey = IterableWrapper::wrap( + __NAMESPACE__ . '\fixtureUnionWithArrayKey', + 'items', + $iterator, + $registry + ); + expect($resultArrayKey)->toBe($iterator); + }); + + test('returns unconstrained true for union covering all scalar and object key types', function () { + $registry = new TypeValidatorRegistry(); + $iterator = new ArrayIterator(['a' => 1]); + + $result = IterableWrapper::wrap( + __NAMESPACE__ . '\fixtureUnionAllTypesKey', + 'items', + $iterator, + $registry + ); + expect($result)->toBe($iterator); + }); + + test('returns false for constrained union keys and proceeds to wrap iterator', function () { + $registry = new TypeValidatorRegistry(); + $iterator = new ArrayIterator(['a' => 1]); + + $wrapped = IterableWrapper::wrap( + __NAMESPACE__ . '\fixtureConstrainedUnionKey', + 'items', + $iterator, + $registry + ); + + expect($wrapped)->toBeInstanceOf(\TypePHP\Internal\Wrapper\IteratorProxy::class); + }); + + test('directly validates isUnconstrainedKey via reflection across all union branches', function () { + $refMethod = new \ReflectionMethod(IterableWrapper::class, 'isUnconstrainedKey'); + + $unionMixed = new UnionTypeNode([ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('mixed'), + ]); + expect($refMethod->invoke(null, $unionMixed))->toBeTrue(); + + $unionArrayKey = new UnionTypeNode([ + new IdentifierTypeNode('int'), + new IdentifierTypeNode('array-key'), + ]); + expect($refMethod->invoke(null, $unionArrayKey))->toBeTrue(); + + $unionAllTypes = new UnionTypeNode([ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('int'), + new IdentifierTypeNode('bool'), + new IdentifierTypeNode('float'), + new IdentifierTypeNode('object'), + ]); + expect($refMethod->invoke(null, $unionAllTypes))->toBeTrue(); + + $unionIncomplete = new UnionTypeNode([ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('int'), + ]); + expect($refMethod->invoke(null, $unionIncomplete))->toBeFalse(); + + $unionNonIdentifier = new UnionTypeNode([ + new ArrayTypeNode(new IdentifierTypeNode('int')), + ]); + expect($refMethod->invoke(null, $unionNonIdentifier))->toBeFalse(); + }); + }); }); diff --git a/tests/Internal/Wrapper/IteratorProxyTest.php b/tests/Internal/Wrapper/IteratorProxyTest.php index 01ec4764..04169964 100644 --- a/tests/Internal/Wrapper/IteratorProxyTest.php +++ b/tests/Internal/Wrapper/IteratorProxyTest.php @@ -89,3 +89,67 @@ ; }); }); + +describe('Laziness & Generator Lifecycle (TDD Bug Verification)', function () { + test('does not call getIterator() on IteratorAggregate during construction', function () { + $invoked = false; + $lazyAggregate = new class ($invoked) implements \IteratorAggregate { + public function __construct(private bool &$invoked) + { + } + + public function getIterator(): \Traversable + { + $this->invoked = true; + + return (function () { + yield 'x' => 100; + })(); + } + }; + + $proxy = new IteratorProxy($lazyAggregate, fn () => null); + + expect($invoked)->toBeFalse('IteratorAggregate::getIterator() was called eagerly in IteratorProxy::__construct()'); + + $values = []; + foreach ($proxy as $k => $v) { + $values[$k] = $v; + } + + expect($invoked)->toBeTrue() + ->and($values)->toBe(['x' => 100]) + ; + }); + + test('does not prematurely consume one-shot IteratorAggregate before foreach begins', function () { + $consumedPasses = 0; + $oneShotAggregate = new class ($consumedPasses) implements \IteratorAggregate { + public function __construct(private int &$consumedPasses) + { + } + + public function getIterator(): \Traversable + { + if ($this->consumedPasses > 0) { + throw new \RuntimeException('Already iterated!'); + } + $this->consumedPasses++; + + return (function () { + yield 1; + yield 2; + })(); + } + }; + + $proxy = new IteratorProxy($oneShotAggregate, fn () => null); + + $items = []; + foreach ($proxy as $v) { + $items[] = $v; + } + + expect($items)->toBe([1, 2]); + }); +}); diff --git a/tests/TypeChecking/Generics/TypestateSelfOutPropertyTest.php b/tests/TypeChecking/Generics/TypestateSelfOutPropertyTest.php index 0a4951ad..f1459a01 100644 --- a/tests/TypeChecking/Generics/TypestateSelfOutPropertyTest.php +++ b/tests/TypeChecking/Generics/TypestateSelfOutPropertyTest.php @@ -111,3 +111,98 @@ public function getDashboard(): string ; }); }); + +describe('Typestate Transitions with Cloning & Reference Aliasing', function () { + test('cloned instance inherits transitioned typestate from original object', function () { + $session = new FixtureTypestateAuthSession(); + $session->login('alice', 'hunter2'); + + expect(TypePHP::getGenericType($session))->toBe("'authenticated'"); + + $cloned = clone $session; + + expect(TypePHP::getGenericType($cloned))->toBe("'authenticated'") + ->and($cloned->state)->toBe('authenticated') + ->and($cloned->username)->toBe('alice') + ; + }); + + test('preserves WeakMap state isolation when clone transitions to a different typestate', function () { + $session = new FixtureTypestateAuthSession(); + $session->login('alice', 'hunter2'); + + $cloned = clone $session; + expect(TypePHP::getGenericType($cloned))->toBe("'authenticated'"); + + $cloned->logout(); + + expect(TypePHP::getGenericType($cloned))->toBe("'unauthenticated'") + ->and(TypePHP::getGenericType($session))->toBe("'authenticated'") + ->and($cloned->state)->toBe('unauthenticated') + ->and($session->state)->toBe('authenticated') + ; + }); + + test('enforces inline @var typestate contract when assigning from clone expression', function () { + $session = new FixtureTypestateAuthSession(); + $session->login('alice', 'hunter2'); + + /** @var FixtureTypestateAuthSession<'authenticated'> $authCopy */ + $authCopy = clone $session; + expect($authCopy->state)->toBe('authenticated'); + + $unauthSession = new FixtureTypestateAuthSession(); + $unauthSession->login('bob', 'secret'); + $unauthSession->logout(); + + expect(function () use ($unauthSession) { + /** @var FixtureTypestateAuthSession<'authenticated'> $badCopy */ + $badCopy = clone $unauthSession; + })->toThrow(TypeError::class, "FixtureTypestateAuthSession"); + }); + + test('throws TypeError when assigning invalid value to reference aliasing cloned typestate property', function () { + $session = new FixtureTypestateAuthSession(); + $session->login('alice', 'hunter2'); + + /** @var FixtureTypestateAuthSession<'authenticated'> $cloned */ + $cloned = clone $session; + + $ref = &$cloned->state; + + expect(function () use (&$ref) { + $ref = 'hacked_state'; + })->toThrow(TypeError::class, "must be literal 'authenticated'"); + + expect($cloned->state)->toBe('authenticated'); + }); + + test('allows valid assignment to reference aliasing cloned typestate property', function () { + $session = new FixtureTypestateAuthSession(); + $session->login('alice', 'hunter2'); + + /** @var FixtureTypestateAuthSession<'authenticated'> $cloned */ + $cloned = clone $session; + + $ref = &$cloned->state; + $ref = 'authenticated'; + + expect($cloned->state)->toBe('authenticated') + ->and($ref)->toBe('authenticated') + ; + }); + + test('propagates typestate to reference alias when cloning without explicit @var annotation', function () { + /** @var FixtureTypestateAuthSession<'authenticated'> $session */ + $session = new FixtureTypestateAuthSession(); + $session->login('alice', 'hunter2'); + + $cloned = clone $session; + + $ref = &$cloned->state; + + expect(function () use (&$ref) { + $ref = 'invalid_state'; + })->toThrow(TypeError::class, "must be literal 'authenticated'"); + }); +}); diff --git a/tests/TypeChecking/Generics/UnionInferenceAndBoundsTest.php b/tests/TypeChecking/Generics/UnionInferenceAndBoundsTest.php new file mode 100644 index 00000000..b22d2d3b --- /dev/null +++ b/tests/TypeChecking/Generics/UnionInferenceAndBoundsTest.php @@ -0,0 +1,119 @@ + + */ +class ConcreteUnionStore implements UnionStore +{ +} + +/** + * @template K of array-key + * @template V + */ +class UnionView +{ + /** + * @param UnionStore|ConcreteUnionStore $store + */ + public function __construct(public mixed $store) + { + } + + /** + * @param K $key + */ + public function putKey(mixed $key): void + { + } +} + +/** + * @template K + * @template V + */ +class MyMapEntry +{ +} + +/** + * @template T + */ +interface MyElementStore +{ +} + +/** + * @template K of array-key + * @template V + * + * @implements MyElementStore> + */ +class MyMapEntryStore implements MyElementStore +{ + public function __construct() + { + } +} + +describe('Generics: Union Type Inference & Unbound Template Fallbacks', function () { + + test('infers generic types correctly when constructor parameter uses a union of generic types', function () { + $store = new ConcreteUnionStore(); + + RuntimeTypeChecker::bindInstanceFromNode( + $store, + new GenericTypeNode(new IdentifierTypeNode(ConcreteUnionStore::class), [ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('int'), + ]), + '', + true + ); + + $view = new UnionView($store); + + expect(function () use ($view) { + $view->putKey(123); + })->toThrow(TypeError::class, 'must be of type string'); + }); + + test('unbound templates in implemented interfaces fall back to their declared bounds instead of literal strings', function () { + $set = new class () { + /** + * @var MyElementStore> + */ + public mixed $store; + + public function assign(): void + { + $this->store = new MyMapEntryStore(); + } + }; + + $set->assign(); + + expect(true)->toBeTrue(); + }); + +});